text
stringlengths
54
60.6k
<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "MDSMap.h" #include <sstream> using std::stringstream; void MDSMap::print(ostream& out) { out << "epoch " << epoch << std::endl; out << "\nclient_epoch " << client_epoch << std::endl; out << "created " << created << std::endl; out << "tableserver " << tableserver << std::endl; out << "root " << root << std::endl; out << "session_timeout " << session_timeout << "\n" << "session_autoclose " << session_autoclose << "\n"; out << "\nmax_mds " << max_mds << std::endl; set<int> upset; get_up_mds_set(upset); out << "in " << in << "\n" << "up " << upset << "\n"; multimap< pair<unsigned,unsigned>, entity_addr_t > foo; for (map<entity_addr_t,mds_info_t>::iterator p = mds_info.begin(); p != mds_info.end(); p++) foo.insert(pair<pair<unsigned,unsigned>,entity_addr_t>(pair<unsigned,unsigned>(p->second.mds, p->second.inc-1), p->first)); for (multimap< pair<unsigned,unsigned>, entity_addr_t >::iterator p = foo.begin(); p != foo.end(); p++) { mds_info_t& info = mds_info[p->second]; out << info.addr << " mds" << info.mds << "." << info.inc << " " << get_state_name(info.state) << " seq " << info.state_seq; if (info.laggy()) out << " laggy since " << info.laggy_since; out << "\n"; } if (failed.size()) out << "failed " << failed << "\n"; if (stopped.size()) out << "stopped " << failed << "\n"; } void MDSMap::print_summary(ostream& out) { map<int,int> by_state; for (map<entity_addr_t,mds_info_t>::iterator p = mds_info.begin(); p != mds_info.end(); p++) by_state[p->second.state]++; out << "e" << get_epoch() << ": " << up.size() << "/" << in.size() << " up"; for (map<int,int>::reverse_iterator p = by_state.rbegin(); p != by_state.rend(); p++) out << ", " << p->second << " " << get_state_name(p->first); if (failed.size()) out << ", " << failed.size() << " failed"; } <commit_msg>mds: include max mds in mdsmap summary<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "MDSMap.h" #include <sstream> using std::stringstream; void MDSMap::print(ostream& out) { out << "epoch " << epoch << std::endl; out << "\nclient_epoch " << client_epoch << std::endl; out << "created " << created << std::endl; out << "tableserver " << tableserver << std::endl; out << "root " << root << std::endl; out << "session_timeout " << session_timeout << "\n" << "session_autoclose " << session_autoclose << "\n"; out << "\nmax_mds " << max_mds << std::endl; set<int> upset; get_up_mds_set(upset); out << "in " << in << "\n" << "up " << upset << "\n"; multimap< pair<unsigned,unsigned>, entity_addr_t > foo; for (map<entity_addr_t,mds_info_t>::iterator p = mds_info.begin(); p != mds_info.end(); p++) foo.insert(pair<pair<unsigned,unsigned>,entity_addr_t>(pair<unsigned,unsigned>(p->second.mds, p->second.inc-1), p->first)); for (multimap< pair<unsigned,unsigned>, entity_addr_t >::iterator p = foo.begin(); p != foo.end(); p++) { mds_info_t& info = mds_info[p->second]; out << info.addr << " mds" << info.mds << "." << info.inc << " " << get_state_name(info.state) << " seq " << info.state_seq; if (info.laggy()) out << " laggy since " << info.laggy_since; out << "\n"; } if (failed.size()) out << "failed " << failed << "\n"; if (stopped.size()) out << "stopped " << failed << "\n"; } void MDSMap::print_summary(ostream& out) { map<int,int> by_state; for (map<entity_addr_t,mds_info_t>::iterator p = mds_info.begin(); p != mds_info.end(); p++) by_state[p->second.state]++; out << "e" << get_epoch() << ": " << up.size() << "/" << in.size() << "/" << max_mds << " up"; for (map<int,int>::reverse_iterator p = by_state.rbegin(); p != by_state.rend(); p++) out << ", " << p->second << " " << get_state_name(p->first); if (failed.size()) out << ", " << failed.size() << " failed"; } <|endoftext|>
<commit_before>/* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. 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 "paddle/fluid/operators/temporal_shift_op.h" #include <memory> #include <string> #include <vector> #include "paddle/fluid/framework/op_registry.h" namespace paddle { namespace operators { using framework::Tensor; class TemporalShiftOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; protected: void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) of TemporalShiftOp should not be null."); PADDLE_ENFORCE(ctx->HasOutput("Out"), "Output(Out) of TemporalShiftOp should not be null."); auto dim_x = ctx->GetInputDim("X"); PADDLE_ENFORCE_EQ(dim_x.size(), 4, "Input(X) rank should be 4 in shape of [N*T, C, H, W]."); int seg_num = ctx->Attrs().Get<int>("seg_num"); float shift_ratio = ctx->Attrs().Get<float>("shift_ratio"); PADDLE_ENFORCE_GT(seg_num, 0, "Attr(seg_num) should be greater than 0."); PADDLE_ENFORCE(shift_ratio > 0 || shift_ratio < .5, "Attr(shift_ratio) should be greater than 0 and less " "than 0.5."); if (ctx->IsRuntime()) { PADDLE_ENFORCE_EQ( dim_x[0] % seg_num, 0, "Input(X) dims[0] should be divided exactly by Attr(seg_num)."); } ctx->SetOutputDim("Out", dim_x); ctx->ShareLoD("X", "Out"); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType(ctx.Input<Tensor>("X")->type(), ctx.GetPlace()); } }; class TemporalShiftOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("X", "The input tensor of temporal shift operator. " "This is a 4-D tensor with shape of [N*T, C, H, W]. " "While N is the batch size, T is the temporal segment " "number, C is the channel number, H is the height of " "features and W is the width of features."); AddOutput("Out", "The output tensor of temporal shift operator. " "This is a 4-D tensor in the same shape with Input(X)."); AddAttr<int>("seg_num", "The temporal segment number, this should be a positive " "integer."); AddAttr<float>( "shift_ratio", "The shift ratio of the channels, the first :attr:`shift_ratio` part " "of channels will be shifted by -1 along the temporal dimension, " "and the second :attr:`shift_ratio` part of channels will be shifted " "by 1 along the temporal dimension. Default 0.25.") .SetDefault(0.25); AddComment(R"DOC( This operator calculates the temporal shifting features for Input(X). Input(X) should be in shape of [N*T, C, H, W], while N is the batch size, T is the temporal segment number specified by :attr:`seg_num`, C is the channel number, H and W is the height and width of features. Temporal Shifting is calculated as follows: Step 1: Reshape Input(X) to [N, T, C, H, W]. Step 2: Pad 0 to reshaping result in the 2nd(T) dimension with padding width as 1 on each side, padding result will be in shape of [N, T+2, C, H, W]. Step 3: Assume :attr:`shift_ratio` is :math:`1/4`, slice padding result as follows: $$ slice1 = x[:, :T, :C/4, :, :] $$ $$ slice2 = x[:, 2:T+2, C/4:C/2, :, :] $$ $$ slice3 = x[:, 1:T+1, C/2:, :, :] $$ Step 4: Concatenate three slices along the 3rd(C) dimension and reshape result to [N*T, C, H, W]. For details of temporal shifting, please refer to paper: `Temporal Shift Module <http://arxiv.org/abs/1811.08383>`_ . )DOC"); } }; class TemporalShiftOpGrad : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; protected: void InferShape(framework::InferShapeContext* ctx) const override { if (ctx->HasOutput(framework::GradVarName("X"))) { ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim(framework::GradVarName("Out"))); } } framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType( ctx.Input<Tensor>(framework::GradVarName("Out"))->type(), ctx.GetPlace()); } }; class TemporalShiftGradOpDescMaker : public framework::SingleGradOpDescMaker { public: using framework::SingleGradOpDescMaker::SingleGradOpDescMaker; protected: std::unique_ptr<framework::OpDesc> Apply() const override { std::unique_ptr<framework::OpDesc> op(new framework::OpDesc()); op->SetType("temporal_shift_grad"); op->SetInput(framework::GradVarName("Out"), OutputGrad("Out")); op->SetOutput(framework::GradVarName("X"), InputGrad("X")); op->SetAttrMap(Attrs()); return op; } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(temporal_shift, ops::TemporalShiftOp, ops::TemporalShiftOpMaker, ops::TemporalShiftGradOpDescMaker); REGISTER_OPERATOR(temporal_shift_grad, ops::TemporalShiftOpGrad); REGISTER_OP_CPU_KERNEL(temporal_shift, ops::TemporalShiftKernel<float>, ops::TemporalShiftKernel<double>); REGISTER_OP_CPU_KERNEL(temporal_shift_grad, ops::TemporalShiftGradKernel<float>, ops::TemporalShiftGradKernel<double>); <commit_msg>fix temporal_shift OP PADDLE_ENFORCE. test=develop (#19161)<commit_after>/* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. 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 "paddle/fluid/operators/temporal_shift_op.h" #include <memory> #include <string> #include <vector> #include "paddle/fluid/framework/op_registry.h" namespace paddle { namespace operators { using framework::Tensor; class TemporalShiftOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; protected: void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE_EQ(ctx->HasInput("X"), true, "Input(X) of TemporalShiftOp should not be null."); PADDLE_ENFORCE_EQ(ctx->HasOutput("Out"), true, "Output(Out) of TemporalShiftOp should not be null."); auto dim_x = ctx->GetInputDim("X"); PADDLE_ENFORCE_EQ(dim_x.size(), 4, "Input(X) rank should be 4 in shape of [N*T, C, H, W]."); int seg_num = ctx->Attrs().Get<int>("seg_num"); float shift_ratio = ctx->Attrs().Get<float>("shift_ratio"); PADDLE_ENFORCE_GT(seg_num, 0, "Attr(seg_num) should be greater than 0."); PADDLE_ENFORCE_GT(shift_ratio, 0., "Attr(shift_ratio) should be greater than 0"); PADDLE_ENFORCE_LT(shift_ratio, 0.5, "Attr(shift_ratio) should be less than 0.5"); if (ctx->IsRuntime()) { PADDLE_ENFORCE_EQ( dim_x[0] % seg_num, 0, "Input(X) dims[0] should be divided exactly by Attr(seg_num)."); } ctx->SetOutputDim("Out", dim_x); ctx->ShareLoD("X", "Out"); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType(ctx.Input<Tensor>("X")->type(), ctx.GetPlace()); } }; class TemporalShiftOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("X", "The input tensor of temporal shift operator. " "This is a 4-D tensor with shape of [N*T, C, H, W]. " "While N is the batch size, T is the temporal segment " "number, C is the channel number, H is the height of " "features and W is the width of features."); AddOutput("Out", "The output tensor of temporal shift operator. " "This is a 4-D tensor in the same shape with Input(X)."); AddAttr<int>("seg_num", "The temporal segment number, this should be a positive " "integer."); AddAttr<float>( "shift_ratio", "The shift ratio of the channels, the first :attr:`shift_ratio` part " "of channels will be shifted by -1 along the temporal dimension, " "and the second :attr:`shift_ratio` part of channels will be shifted " "by 1 along the temporal dimension. Default 0.25.") .SetDefault(0.25); AddComment(R"DOC( This operator calculates the temporal shifting features for Input(X). Input(X) should be in shape of [N*T, C, H, W], while N is the batch size, T is the temporal segment number specified by :attr:`seg_num`, C is the channel number, H and W is the height and width of features. Temporal Shifting is calculated as follows: Step 1: Reshape Input(X) to [N, T, C, H, W]. Step 2: Pad 0 to reshaping result in the 2nd(T) dimension with padding width as 1 on each side, padding result will be in shape of [N, T+2, C, H, W]. Step 3: Assume :attr:`shift_ratio` is :math:`1/4`, slice padding result as follows: $$ slice1 = x[:, :T, :C/4, :, :] $$ $$ slice2 = x[:, 2:T+2, C/4:C/2, :, :] $$ $$ slice3 = x[:, 1:T+1, C/2:, :, :] $$ Step 4: Concatenate three slices along the 3rd(C) dimension and reshape result to [N*T, C, H, W]. For details of temporal shifting, please refer to paper: `Temporal Shift Module <http://arxiv.org/abs/1811.08383>`_ . )DOC"); } }; class TemporalShiftOpGrad : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; protected: void InferShape(framework::InferShapeContext* ctx) const override { if (ctx->HasOutput(framework::GradVarName("X"))) { ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim(framework::GradVarName("Out"))); } } framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType( ctx.Input<Tensor>(framework::GradVarName("Out"))->type(), ctx.GetPlace()); } }; class TemporalShiftGradOpDescMaker : public framework::SingleGradOpDescMaker { public: using framework::SingleGradOpDescMaker::SingleGradOpDescMaker; protected: std::unique_ptr<framework::OpDesc> Apply() const override { std::unique_ptr<framework::OpDesc> op(new framework::OpDesc()); op->SetType("temporal_shift_grad"); op->SetInput(framework::GradVarName("Out"), OutputGrad("Out")); op->SetOutput(framework::GradVarName("X"), InputGrad("X")); op->SetAttrMap(Attrs()); return op; } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(temporal_shift, ops::TemporalShiftOp, ops::TemporalShiftOpMaker, ops::TemporalShiftGradOpDescMaker); REGISTER_OPERATOR(temporal_shift_grad, ops::TemporalShiftOpGrad); REGISTER_OP_CPU_KERNEL(temporal_shift, ops::TemporalShiftKernel<float>, ops::TemporalShiftKernel<double>); REGISTER_OP_CPU_KERNEL(temporal_shift_grad, ops::TemporalShiftGradKernel<float>, ops::TemporalShiftGradKernel<double>); <|endoftext|>
<commit_before>#include <iostream> class Number { private: int number; std::vector<int> function getFactors(); int function getLargestPrimeFactor(); } <commit_msg>adding some changes<commit_after>#include <iostream> class Number { private: int number; std::vector<int> function getFactors(); int function getLargestPrimeFactor(); } #include <iostream> #include <vector> #include <cmath> // Initializing Number::Number(int n) : mNumber(n) { } // Get the factors of a number std::vector<int> problem3::getFactors() { double squareRootValue = floor(sqrt(mNumber)); // Cheching if if(squareRootValue >= 2) { for(int i = 2; i <= squareRootValue; i++) { if(mNumber % i == 0) mFactors = push(i); else getFactors(); } } } int problem3::getLargestPrimeFactor() { } int main() { return 0; } <|endoftext|>
<commit_before>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION 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 "was/Client.hxx" #include "was/Launch.hxx" #include "was/Lease.hxx" #include "stopwatch.hxx" #include "lease.hxx" #include "HttpResponseHandler.hxx" #include "direct.hxx" #include "strmap.hxx" #include "istream/Handler.hxx" #include "istream/Pointer.hxx" #include "istream/UnusedPtr.hxx" #include "istream/FileIstream.hxx" #include "fb_pool.hxx" #include "PInstance.hxx" #include "spawn/Config.hxx" #include "spawn/ChildOptions.hxx" #include "spawn/Registry.hxx" #include "spawn/Local.hxx" #include "io/Logger.hxx" #include "util/ConstBuffer.hxx" #include "util/Cancellable.hxx" #include "util/PrintException.hxx" #include "util/StaticArray.hxx" #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> struct Context final : PInstance, WasLease, IstreamHandler, HttpResponseHandler { WasProcess process; IstreamPointer body; bool error; CancellablePointer cancel_ptr; Context():body(nullptr) {} /* virtual methods from class IstreamHandler */ size_t OnData(const void *data, size_t length) noexcept override; void OnEof() noexcept override { body.Clear(); } void OnError(std::exception_ptr ep) noexcept override { PrintException(ep); body.Clear(); error = true; } /* virtual methods from class Lease */ void ReleaseWas(gcc_unused bool reuse) override { kill(process.pid, SIGTERM); process.Close(); } void ReleaseWasStop(gcc_unused uint64_t input_received) override { ReleaseWas(false); } /* virtual methods from class HttpResponseHandler */ void OnHttpResponse(http_status_t status, StringMap &&headers, UnusedIstreamPtr body) noexcept override; void OnHttpError(std::exception_ptr ep) noexcept override; }; /* * istream handler * */ size_t Context::OnData(const void *data, size_t length) noexcept { ssize_t nbytes = write(1, data, length); if (nbytes <= 0) { error = true; body.ClearAndClose(); return 0; } return (size_t)nbytes; } /* * http_response_handler * */ void Context::OnHttpResponse(gcc_unused http_status_t status, gcc_unused StringMap &&headers, UnusedIstreamPtr _body) noexcept { if (_body) body.Set(std::move(_body), *this); } void Context::OnHttpError(std::exception_ptr ep) noexcept { PrintException(ep); error = true; } static Istream * request_body(EventLoop &event_loop, struct pool &pool) { struct stat st; return fstat(0, &st) == 0 && S_ISREG(st.st_mode) ? istream_file_fd_new(event_loop, pool, "/dev/stdin", UniqueFileDescriptor(STDIN_FILENO), FdType::FD_FILE, -1) : nullptr; } int main(int argc, char **argv) try { SetLogLevel(5); StaticArray<const char *, 64> params; if (argc < 3) { fprintf(stderr, "Usage: run_was PATH URI [--parameter a=b ...]\n"); return EXIT_FAILURE; } const char *uri = argv[2]; for (int i = 3; i < argc;) { if (strcmp(argv[i], "--parameter") == 0 || strcmp(argv[i], "-p") == 0) { ++i; if (i >= argc) throw std::runtime_error("Parameter value missing"); if (params.full()) throw std::runtime_error("Too many parameters"); params.push_back(argv[i++]); } else throw std::runtime_error("Unrecognized parameter"); } direct_global_init(); SpawnConfig spawn_config; const ScopeFbPoolInit fb_pool_init; ChildOptions child_options; Context context; ChildProcessRegistry child_process_registry(context.event_loop); child_process_registry.SetVolatile(); LocalSpawnService spawn_service(spawn_config, child_process_registry); context.process = was_launch(spawn_service, "was", argv[1], nullptr, child_options, {}, nullptr); was_client_request(context.root_pool, context.event_loop, nullptr, context.process.control, context.process.input, context.process.output, context, HTTP_METHOD_GET, uri, nullptr, nullptr, nullptr, *strmap_new(context.root_pool), UnusedIstreamPtr(request_body(context.event_loop, context.root_pool)), { (const char *const*)params.raw(), params.size() }, context, context.cancel_ptr); context.event_loop.Dispatch(); return context.error; } catch (const std::exception &e) { PrintException(e); return EXIT_FAILURE; } <commit_msg>test/run_was: print the status to stderr<commit_after>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION 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 "was/Client.hxx" #include "was/Launch.hxx" #include "was/Lease.hxx" #include "stopwatch.hxx" #include "lease.hxx" #include "HttpResponseHandler.hxx" #include "direct.hxx" #include "strmap.hxx" #include "istream/Handler.hxx" #include "istream/Pointer.hxx" #include "istream/UnusedPtr.hxx" #include "istream/FileIstream.hxx" #include "fb_pool.hxx" #include "PInstance.hxx" #include "spawn/Config.hxx" #include "spawn/ChildOptions.hxx" #include "spawn/Registry.hxx" #include "spawn/Local.hxx" #include "io/Logger.hxx" #include "util/ConstBuffer.hxx" #include "util/Cancellable.hxx" #include "util/PrintException.hxx" #include "util/StaticArray.hxx" #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> struct Context final : PInstance, WasLease, IstreamHandler, HttpResponseHandler { WasProcess process; IstreamPointer body; bool error; CancellablePointer cancel_ptr; Context():body(nullptr) {} /* virtual methods from class IstreamHandler */ size_t OnData(const void *data, size_t length) noexcept override; void OnEof() noexcept override { body.Clear(); } void OnError(std::exception_ptr ep) noexcept override { PrintException(ep); body.Clear(); error = true; } /* virtual methods from class Lease */ void ReleaseWas(gcc_unused bool reuse) override { kill(process.pid, SIGTERM); process.Close(); } void ReleaseWasStop(gcc_unused uint64_t input_received) override { ReleaseWas(false); } /* virtual methods from class HttpResponseHandler */ void OnHttpResponse(http_status_t status, StringMap &&headers, UnusedIstreamPtr body) noexcept override; void OnHttpError(std::exception_ptr ep) noexcept override; }; /* * istream handler * */ size_t Context::OnData(const void *data, size_t length) noexcept { ssize_t nbytes = write(1, data, length); if (nbytes <= 0) { error = true; body.ClearAndClose(); return 0; } return (size_t)nbytes; } /* * http_response_handler * */ void Context::OnHttpResponse(http_status_t status, gcc_unused StringMap &&headers, UnusedIstreamPtr _body) noexcept { fprintf(stderr, "status: %s\n", http_status_to_string(status)); if (_body) body.Set(std::move(_body), *this); } void Context::OnHttpError(std::exception_ptr ep) noexcept { PrintException(ep); error = true; } static Istream * request_body(EventLoop &event_loop, struct pool &pool) { struct stat st; return fstat(0, &st) == 0 && S_ISREG(st.st_mode) ? istream_file_fd_new(event_loop, pool, "/dev/stdin", UniqueFileDescriptor(STDIN_FILENO), FdType::FD_FILE, -1) : nullptr; } int main(int argc, char **argv) try { SetLogLevel(5); StaticArray<const char *, 64> params; if (argc < 3) { fprintf(stderr, "Usage: run_was PATH URI [--parameter a=b ...]\n"); return EXIT_FAILURE; } const char *uri = argv[2]; for (int i = 3; i < argc;) { if (strcmp(argv[i], "--parameter") == 0 || strcmp(argv[i], "-p") == 0) { ++i; if (i >= argc) throw std::runtime_error("Parameter value missing"); if (params.full()) throw std::runtime_error("Too many parameters"); params.push_back(argv[i++]); } else throw std::runtime_error("Unrecognized parameter"); } direct_global_init(); SpawnConfig spawn_config; const ScopeFbPoolInit fb_pool_init; ChildOptions child_options; Context context; ChildProcessRegistry child_process_registry(context.event_loop); child_process_registry.SetVolatile(); LocalSpawnService spawn_service(spawn_config, child_process_registry); context.process = was_launch(spawn_service, "was", argv[1], nullptr, child_options, {}, nullptr); was_client_request(context.root_pool, context.event_loop, nullptr, context.process.control, context.process.input, context.process.output, context, HTTP_METHOD_GET, uri, nullptr, nullptr, nullptr, *strmap_new(context.root_pool), UnusedIstreamPtr(request_body(context.event_loop, context.root_pool)), { (const char *const*)params.raw(), params.size() }, context, context.cancel_ptr); context.event_loop.Dispatch(); return context.error; } catch (const std::exception &e) { PrintException(e); return EXIT_FAILURE; } <|endoftext|>
<commit_before>#include "chainerx/routines/normalization.h" #include <cstdint> #include <memory> #include <utility> #include "chainerx/array.h" #include "chainerx/axes.h" #include "chainerx/backprop_mode.h" #include "chainerx/backward_builder.h" #include "chainerx/backward_context.h" #include "chainerx/device.h" #include "chainerx/dtype.h" #include "chainerx/error.h" #include "chainerx/graph.h" #include "chainerx/macro.h" #include "chainerx/routines/math.h" #include "chainerx/routines/routines_util.h" #include "chainerx/routines/statistics.h" #include "chainerx/scalar.h" #include "chainerx/shape.h" namespace chainerx { namespace { struct PreprocessBatchNormResult { // Arrays are reshaped if necessary Array gamma; Array beta; Array mean; Array var; Axes sorted_axis; }; // Reshapes the array. If the shape is unchanged, an array with identical array body is returned. Note that chainerx::Reshape() returns // a view with different array body if the shape is unchanged. Array ReshapeOrIdentity(const Array& a, const Shape& shape) { if (a.shape() == shape) { return a; } return a.Reshape(shape); } // Reshapes the input arrays (except x) as needed. // Sorted axes is also returned. PreprocessBatchNormResult PreprocessBatchNorm( const Array& x, const Array& gamma, const Array& beta, const Array& mean, const Array& var, const OptionalAxes& axis) { Dtype dtype = x.dtype(); CheckEqual(dtype, gamma.dtype()); CheckEqual(dtype, beta.dtype()); CheckEqual(dtype, mean.dtype()); CheckEqual(dtype, var.dtype()); Axes sorted_axis = axis.has_value() ? internal::GetSortedAxes(*axis, x.ndim()) : Axes{0}; Shape reduced_shape = internal::ReduceShape(x.shape(), sorted_axis, true); int64_t reduced_size = reduced_shape.GetTotalSize(); if (gamma.GetTotalSize() != reduced_size) { throw DimensionError{ "Gamma must have the same size as the reduced input. Actual: ", gamma.GetTotalSize(), ". Expected: ", reduced_size, "."}; } if (beta.GetTotalSize() != reduced_size) { throw DimensionError{ "Beta must have the same size as the reduced input. Actual: ", beta.GetTotalSize(), ". Expected: ", reduced_size, "."}; } if (mean.GetTotalSize() != reduced_size) { throw DimensionError{ "Mean must have the same size as the reduced input. Actual: ", mean.GetTotalSize(), ". Expected: ", reduced_size, "."}; } if (var.GetTotalSize() != reduced_size) { throw DimensionError{ "Variance must have the same size as the reduced input. Actual: ", var.GetTotalSize(), ". Expected: ", reduced_size, "."}; } Array gamma_reshaped = ReshapeOrIdentity(gamma, reduced_shape); Array beta_reshaped = ReshapeOrIdentity(beta, reduced_shape); Array mean_reshaped = ReshapeOrIdentity(mean, reduced_shape); Array var_reshaped = ReshapeOrIdentity(var, reduced_shape); CHAINERX_ASSERT(gamma_reshaped.data() == gamma.data()); // No data copy should occur CHAINERX_ASSERT(beta_reshaped.data() == beta.data()); CHAINERX_ASSERT(mean_reshaped.data() == mean.data()); CHAINERX_ASSERT(var_reshaped.data() == var.data()); return {std::move(gamma_reshaped), std::move(beta_reshaped), std::move(mean_reshaped), std::move(var_reshaped), sorted_axis}; } } // namespace Array BatchNorm( const Array& x, const Array& gamma, const Array& beta, const Array& running_mean, const Array& running_var, Scalar eps, Scalar decay, const OptionalAxes& axis) { PreprocessBatchNormResult result = PreprocessBatchNorm(x, gamma, beta, running_mean, running_var, axis); std::shared_ptr<BatchNormForwardBackward> fb = x.device().GetBatchNormForwardBackward(result.mean, result.var, eps, decay, result.sorted_axis); const Array& gamma_reshaped = result.gamma; const Array& beta_reshaped = result.beta; Array out = fb->Forward(x.AsGradStopped(), gamma_reshaped.AsGradStopped(), beta_reshaped.AsGradStopped()); internal::MakeViewForForwardBackwardOutput(out); BackwardBuilder bb{"batch_norm", {x, gamma_reshaped, beta_reshaped}, {out}}; if (BackwardBuilder::Target bt = bb.CreateTarget({0, 1, 2})) { bt.Define([fb = std::move(fb), x_tok = bb.RetainInput(0), gamma_tok = bb.RetainInput(1), eps, sorted_axis = result.sorted_axis]( BackwardContext& bctx) { const Array& gout = *bctx.output_grad(); Array gx{}; Array ggamma{}; Array gbeta{}; { std::array<Array, 3> ginputs = fb->Backward(gout.AsGradStopped()); internal::MakeViewForForwardBackwardOutput(ginputs); gx = std::move(ginputs[0]); ggamma = std::move(ginputs[1]); gbeta = std::move(ginputs[2]); } CHAINERX_ASSERT(internal::GetArrayBody(gx)->nodes().empty()); CHAINERX_ASSERT(internal::GetArrayBody(ggamma)->nodes().empty()); CHAINERX_ASSERT(internal::GetArrayBody(gbeta)->nodes().empty()); if (bctx.next_required()) { const Array& x = bctx.GetRetainedInput(x_tok); const Array& gamma_reshaped = bctx.GetRetainedInput(gamma_tok); BackwardBuilder bb2{"batch_norm_backward", {x, gamma_reshaped, gout}, {gx, ggamma, gbeta}}; if (BackwardBuilder::Target bt2 = bb2.CreateTarget({0, 1, 2})) { bt2.Define([x_tok = bb2.RetainInput(0), gamma2_tok = bb2.RetainInput(1), gout_tok = bb2.RetainInput(2), eps, sorted_axis, gx_tok = bb2.RetainOutput(0), ggamma_tok = bb2.RetainOutput(1)](BackwardContext& bctx2) { const Array& x = bctx2.GetRetainedInput(x_tok); const Array& gamma_reshaped = bctx2.GetRetainedInput(gamma2_tok); const Array& gout = bctx2.GetRetainedInput(gout_tok); const Array& ggx = *bctx2.output_grad(0); const Array& gggamma = *bctx2.output_grad(1); const Array& ggbeta = *bctx2.output_grad(2); const Array& x_mean = Mean(x, sorted_axis, true); const Array& x_var = Var(x, sorted_axis, true); const Array& x_inv_std = Reciprocal(Sqrt(x_var + eps)); const Array& gx = bctx2.GetRetainedOutput(gx_tok); const Array& ggamma = bctx2.GetRetainedOutput(ggamma_tok); // Auxiliary values int64_t n = x.GetTotalSize() / gamma_reshaped.GetTotalSize(); double inv_n = 1.0 / n; Array r = (gx * ggx).Sum(sorted_axis); Array coeff = gamma_reshaped * x_inv_std; Array coeff_m = coeff * inv_n; Array x_hat = (x - x_mean) * x_inv_std; Array gggamma2 = gggamma - coeff_m * (x_hat * ggx).Sum(sorted_axis); Array ggbeta2 = ggbeta - coeff_m * ggx.Sum(sorted_axis); Array gx_hat2 = gggamma2 * gout - coeff_m * ggamma * ggx; Array gstd2 = -x_inv_std * (r + (x_hat * gx_hat2).Sum(sorted_axis)); Array gmean2 = -x_inv_std * gx_hat2.Sum(sorted_axis); Array gx2 = x_inv_std * gx_hat2 + inv_n * (gmean2 + x_hat * gstd2); Array ggout2 = gggamma2 * x_hat + ggbeta2 + coeff * ggx; Array ggamma2 = r / gamma_reshaped; bctx2.input_grad(0) = std::move(gx2); bctx2.input_grad(1) = std::move(ggamma2); bctx2.input_grad(2) = std::move(ggout2); }); } bb2.Finalize(); } // TODO(niboshi): Assign at once bctx.input_grad(0) = std::move(gx); bctx.input_grad(1) = std::move(ggamma); bctx.input_grad(2) = std::move(gbeta); }); } bb.Finalize(); return out; } Array FixedBatchNorm( const Array& x, const Array& gamma, const Array& beta, const Array& mean, const Array& var, Scalar eps, const OptionalAxes& axis) { PreprocessBatchNormResult result = PreprocessBatchNorm(x, gamma.AsGradStopped(), beta.AsGradStopped(), mean.AsGradStopped(), var.AsGradStopped(), axis); { NoBackpropModeScope scope{}; return x.device().FixedBatchNorm(x.AsGradStopped(), result.gamma, result.beta, result.mean, result.var, eps, result.sorted_axis); } } } // namespace chainerx <commit_msg>Fix BatchNorm for nullptr upstream gradients<commit_after>#include "chainerx/routines/normalization.h" #include <cstdint> #include <memory> #include <utility> #include <nonstd/optional.hpp> #include "chainerx/array.h" #include "chainerx/axes.h" #include "chainerx/backprop_mode.h" #include "chainerx/backward_builder.h" #include "chainerx/backward_context.h" #include "chainerx/device.h" #include "chainerx/dtype.h" #include "chainerx/error.h" #include "chainerx/graph.h" #include "chainerx/macro.h" #include "chainerx/routines/creation.h" #include "chainerx/routines/math.h" #include "chainerx/routines/routines_util.h" #include "chainerx/routines/statistics.h" #include "chainerx/scalar.h" #include "chainerx/shape.h" namespace chainerx { namespace { struct PreprocessBatchNormResult { // Arrays are reshaped if necessary Array gamma; Array beta; Array mean; Array var; Axes sorted_axis; }; // Reshapes the array. If the shape is unchanged, an array with identical array body is returned. Note that chainerx::Reshape() returns // a view with different array body if the shape is unchanged. Array ReshapeOrIdentity(const Array& a, const Shape& shape) { if (a.shape() == shape) { return a; } return a.Reshape(shape); } // Reshapes the input arrays (except x) as needed. // Sorted axes is also returned. PreprocessBatchNormResult PreprocessBatchNorm( const Array& x, const Array& gamma, const Array& beta, const Array& mean, const Array& var, const OptionalAxes& axis) { Dtype dtype = x.dtype(); CheckEqual(dtype, gamma.dtype()); CheckEqual(dtype, beta.dtype()); CheckEqual(dtype, mean.dtype()); CheckEqual(dtype, var.dtype()); Axes sorted_axis = axis.has_value() ? internal::GetSortedAxes(*axis, x.ndim()) : Axes{0}; Shape reduced_shape = internal::ReduceShape(x.shape(), sorted_axis, true); int64_t reduced_size = reduced_shape.GetTotalSize(); if (gamma.GetTotalSize() != reduced_size) { throw DimensionError{ "Gamma must have the same size as the reduced input. Actual: ", gamma.GetTotalSize(), ". Expected: ", reduced_size, "."}; } if (beta.GetTotalSize() != reduced_size) { throw DimensionError{ "Beta must have the same size as the reduced input. Actual: ", beta.GetTotalSize(), ". Expected: ", reduced_size, "."}; } if (mean.GetTotalSize() != reduced_size) { throw DimensionError{ "Mean must have the same size as the reduced input. Actual: ", mean.GetTotalSize(), ". Expected: ", reduced_size, "."}; } if (var.GetTotalSize() != reduced_size) { throw DimensionError{ "Variance must have the same size as the reduced input. Actual: ", var.GetTotalSize(), ". Expected: ", reduced_size, "."}; } Array gamma_reshaped = ReshapeOrIdentity(gamma, reduced_shape); Array beta_reshaped = ReshapeOrIdentity(beta, reduced_shape); Array mean_reshaped = ReshapeOrIdentity(mean, reduced_shape); Array var_reshaped = ReshapeOrIdentity(var, reduced_shape); CHAINERX_ASSERT(gamma_reshaped.data() == gamma.data()); // No data copy should occur CHAINERX_ASSERT(beta_reshaped.data() == beta.data()); CHAINERX_ASSERT(mean_reshaped.data() == mean.data()); CHAINERX_ASSERT(var_reshaped.data() == var.data()); return {std::move(gamma_reshaped), std::move(beta_reshaped), std::move(mean_reshaped), std::move(var_reshaped), sorted_axis}; } Array ArrayOrZeros(const nonstd::optional<Array>& array, const Array& zeros_template) { if (array.has_value()) { return *array; } return ZerosLike(zeros_template, zeros_template.device()); } } // namespace Array BatchNorm( const Array& x, const Array& gamma, const Array& beta, const Array& running_mean, const Array& running_var, Scalar eps, Scalar decay, const OptionalAxes& axis) { PreprocessBatchNormResult result = PreprocessBatchNorm(x, gamma, beta, running_mean, running_var, axis); std::shared_ptr<BatchNormForwardBackward> fb = x.device().GetBatchNormForwardBackward(result.mean, result.var, eps, decay, result.sorted_axis); const Array& gamma_reshaped = result.gamma; const Array& beta_reshaped = result.beta; Array out = fb->Forward(x.AsGradStopped(), gamma_reshaped.AsGradStopped(), beta_reshaped.AsGradStopped()); internal::MakeViewForForwardBackwardOutput(out); BackwardBuilder bb{"batch_norm", {x, gamma_reshaped, beta_reshaped}, {out}}; if (BackwardBuilder::Target bt = bb.CreateTarget({0, 1, 2})) { bt.Define([fb = std::move(fb), x_tok = bb.RetainInput(0), gamma_tok = bb.RetainInput(1), eps, sorted_axis = result.sorted_axis]( BackwardContext& bctx) { const Array& gout = *bctx.output_grad(); Array gx{}; Array ggamma{}; Array gbeta{}; { std::array<Array, 3> ginputs = fb->Backward(gout.AsGradStopped()); internal::MakeViewForForwardBackwardOutput(ginputs); gx = std::move(ginputs[0]); ggamma = std::move(ginputs[1]); gbeta = std::move(ginputs[2]); } CHAINERX_ASSERT(internal::GetArrayBody(gx)->nodes().empty()); CHAINERX_ASSERT(internal::GetArrayBody(ggamma)->nodes().empty()); CHAINERX_ASSERT(internal::GetArrayBody(gbeta)->nodes().empty()); if (bctx.next_required()) { const Array& x = bctx.GetRetainedInput(x_tok); const Array& gamma_reshaped = bctx.GetRetainedInput(gamma_tok); BackwardBuilder bb2{"batch_norm_backward", {x, gamma_reshaped, gout}, {gx, ggamma, gbeta}}; if (BackwardBuilder::Target bt2 = bb2.CreateTarget({0, 1, 2})) { bt2.Define([x_tok = bb2.RetainInput(0), gamma2_tok = bb2.RetainInput(1), gout_tok = bb2.RetainInput(2), eps, sorted_axis, gx_tok = bb2.RetainOutput(0), ggamma_tok = bb2.RetainOutput(1)](BackwardContext& bctx2) { const Array& x = bctx2.GetRetainedInput(x_tok); const Array& gamma_reshaped = bctx2.GetRetainedInput(gamma2_tok); const Array& gout = bctx2.GetRetainedInput(gout_tok); Array ggx = ArrayOrZeros(bctx2.output_grad(0), x); Array gggamma = ArrayOrZeros(bctx2.output_grad(1), gamma_reshaped); Array ggbeta = ArrayOrZeros(bctx2.output_grad(2), gamma_reshaped); const Array& x_mean = Mean(x, sorted_axis, true); const Array& x_var = Var(x, sorted_axis, true); const Array& x_inv_std = Reciprocal(Sqrt(x_var + eps)); const Array& gx = bctx2.GetRetainedOutput(gx_tok); const Array& ggamma = bctx2.GetRetainedOutput(ggamma_tok); // Auxiliary values int64_t n = x.GetTotalSize() / gamma_reshaped.GetTotalSize(); double inv_n = 1.0 / n; Array r = (gx * ggx).Sum(sorted_axis, true); Array coeff = gamma_reshaped * x_inv_std; Array coeff_m = coeff * inv_n; Array x_hat = (x - x_mean) * x_inv_std; Array gggamma2 = gggamma - coeff_m * (x_hat * ggx).Sum(sorted_axis, true); Array ggbeta2 = ggbeta - coeff_m * ggx.Sum(sorted_axis, true); Array gx_hat2 = gggamma2 * gout - coeff_m * ggamma * ggx; Array gstd2 = -x_inv_std * (r + (x_hat * gx_hat2).Sum(sorted_axis, true)); Array gmean2 = -x_inv_std * gx_hat2.Sum(sorted_axis, true); Array gx2 = x_inv_std * gx_hat2 + inv_n * (gmean2 + x_hat * gstd2); Array ggout2 = gggamma2 * x_hat + ggbeta2 + coeff * ggx; Array ggamma2 = r / gamma_reshaped; bctx2.input_grad(0) = std::move(gx2); bctx2.input_grad(1) = std::move(ggamma2); bctx2.input_grad(2) = std::move(ggout2); }); } bb2.Finalize(); } // TODO(niboshi): Assign at once bctx.input_grad(0) = std::move(gx); bctx.input_grad(1) = std::move(ggamma); bctx.input_grad(2) = std::move(gbeta); }); } bb.Finalize(); return out; } Array FixedBatchNorm( const Array& x, const Array& gamma, const Array& beta, const Array& mean, const Array& var, Scalar eps, const OptionalAxes& axis) { PreprocessBatchNormResult result = PreprocessBatchNorm(x, gamma.AsGradStopped(), beta.AsGradStopped(), mean.AsGradStopped(), var.AsGradStopped(), axis); { NoBackpropModeScope scope{}; return x.device().FixedBatchNorm(x.AsGradStopped(), result.gamma, result.beta, result.mean, result.var, eps, result.sorted_axis); } } } // namespace chainerx <|endoftext|>
<commit_before>/* Copyright (C) 2001-2020 by Serge Lamikhov-Center Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef ELFIO_SYMBOLS_HPP #define ELFIO_SYMBOLS_HPP namespace ELFIO { //------------------------------------------------------------------------------ template <class S> class symbol_section_accessor_template { public: //------------------------------------------------------------------------------ symbol_section_accessor_template( const elfio& elf_file_, S* symbol_section_ ) : elf_file( elf_file_ ), symbol_section( symbol_section_ ) { find_hash_section(); } //------------------------------------------------------------------------------ Elf_Xword get_symbols_num() const { Elf_Xword nRet = 0; if ( 0 != symbol_section->get_entry_size() ) { nRet = symbol_section->get_size() / symbol_section->get_entry_size(); } return nRet; } //------------------------------------------------------------------------------ bool get_symbol( Elf_Xword index, std::string& name, Elf64_Addr& value, Elf_Xword& size, unsigned char& bind, unsigned char& type, Elf_Half& section_index, unsigned char& other ) const { bool ret = false; if ( elf_file.get_class() == ELFCLASS32 ) { ret = generic_get_symbol<Elf32_Sym>( index, name, value, size, bind, type, section_index, other ); } else { ret = generic_get_symbol<Elf64_Sym>( index, name, value, size, bind, type, section_index, other ); } return ret; } //------------------------------------------------------------------------------ bool get_symbol( const std::string& name, Elf64_Addr& value, Elf_Xword& size, unsigned char& bind, unsigned char& type, Elf_Half& section_index, unsigned char& other ) const { bool ret = false; if ( 0 != get_hash_table_index() ) { Elf_Word nbucket = *(const Elf_Word*)hash_section->get_data(); Elf_Word nchain = *(const Elf_Word*)( hash_section->get_data() + sizeof( Elf_Word ) ); Elf_Word val = elf_hash( (const unsigned char*)name.c_str() ); Elf_Word y = *(const Elf_Word*)( hash_section->get_data() + ( 2 + val % nbucket ) * sizeof( Elf_Word ) ); std::string str; get_symbol( y, str, value, size, bind, type, section_index, other ); while ( str != name && STN_UNDEF != y && y < nchain ) { y = *(const Elf_Word*)( hash_section->get_data() + ( 2 + nbucket + y ) * sizeof( Elf_Word ) ); get_symbol( y, str, value, size, bind, type, section_index, other ); } if ( str == name ) { ret = true; } } else { for ( Elf_Xword i = 0; i < get_symbols_num() && !ret; i++ ) { std::string symbol_name; if ( get_symbol( i, symbol_name, value, size, bind, type, section_index, other ) ) { if ( symbol_name == name ) { ret = true; } } } } return ret; } //------------------------------------------------------------------------------ bool get_symbol( const Elf64_Addr& value, std::string& name, Elf_Xword& size, unsigned char& bind, unsigned char& type, Elf_Half& section_index, unsigned char& other ) const { const endianess_convertor& convertor = elf_file.get_convertor(); Elf_Xword idx = 0; bool match = false; Elf64_Addr v = 0; if ( elf_file.get_class() == ELFCLASS32 ) { match = generic_search_symbols<Elf32_Sym>( [&]( const Elf32_Sym* sym ) { return convertor( sym->st_value ) == value; }, idx ); } else { match = generic_search_symbols<Elf64_Sym>( [&]( const Elf64_Sym* sym ) { return convertor( sym->st_value ) == value; }, idx ); } if ( match ) { return get_symbol( idx, name, v, size, bind, type, section_index, other ); } return false; } //------------------------------------------------------------------------------ Elf_Word add_symbol( Elf_Word name, Elf64_Addr value, Elf_Xword size, unsigned char info, unsigned char other, Elf_Half shndx ) { Elf_Word nRet; if ( symbol_section->get_size() == 0 ) { if ( elf_file.get_class() == ELFCLASS32 ) { nRet = generic_add_symbol<Elf32_Sym>( 0, 0, 0, 0, 0, 0 ); } else { nRet = generic_add_symbol<Elf64_Sym>( 0, 0, 0, 0, 0, 0 ); } } if ( elf_file.get_class() == ELFCLASS32 ) { nRet = generic_add_symbol<Elf32_Sym>( name, value, size, info, other, shndx ); } else { nRet = generic_add_symbol<Elf64_Sym>( name, value, size, info, other, shndx ); } return nRet; } //------------------------------------------------------------------------------ Elf_Word add_symbol( Elf_Word name, Elf64_Addr value, Elf_Xword size, unsigned char bind, unsigned char type, unsigned char other, Elf_Half shndx ) { return add_symbol( name, value, size, ELF_ST_INFO( bind, type ), other, shndx ); } //------------------------------------------------------------------------------ Elf_Word add_symbol( string_section_accessor& pStrWriter, const char* str, Elf64_Addr value, Elf_Xword size, unsigned char info, unsigned char other, Elf_Half shndx ) { Elf_Word index = pStrWriter.add_string( str ); return add_symbol( index, value, size, info, other, shndx ); } //------------------------------------------------------------------------------ Elf_Word add_symbol( string_section_accessor& pStrWriter, const char* str, Elf64_Addr value, Elf_Xword size, unsigned char bind, unsigned char type, unsigned char other, Elf_Half shndx ) { return add_symbol( pStrWriter, str, value, size, ELF_ST_INFO( bind, type ), other, shndx ); } //------------------------------------------------------------------------------ Elf_Xword arrange_local_symbols( std::function<void( Elf_Xword first, Elf_Xword second )> func = nullptr ) { int nRet = 0; if ( elf_file.get_class() == ELFCLASS32 ) { nRet = generic_arrange_local_symbols<Elf32_Sym>( func ); } else { nRet = generic_arrange_local_symbols<Elf64_Sym>( func ); } return nRet; } //------------------------------------------------------------------------------ private: //------------------------------------------------------------------------------ void find_hash_section() { hash_section = 0; hash_section_index = 0; Elf_Half nSecNo = elf_file.sections.size(); for ( Elf_Half i = 0; i < nSecNo && 0 == hash_section_index; ++i ) { const section* sec = elf_file.sections[i]; if ( sec->get_link() == symbol_section->get_index() ) { hash_section = sec; hash_section_index = i; } } } //------------------------------------------------------------------------------ Elf_Half get_string_table_index() const { return (Elf_Half)symbol_section->get_link(); } //------------------------------------------------------------------------------ Elf_Half get_hash_table_index() const { return hash_section_index; } //------------------------------------------------------------------------------ template <class T> const T* generic_get_symbol_ptr( Elf_Xword index ) const { if ( 0 != symbol_section->get_data() && index < get_symbols_num() ) { const T* pSym = reinterpret_cast<const T*>( symbol_section->get_data() + index * symbol_section->get_entry_size() ); return pSym; } return nullptr; } //------------------------------------------------------------------------------ template <class T> bool generic_search_symbols( std::function<bool( const T* )> match, Elf_Xword& idx ) const { for ( Elf_Xword i = 0; i < get_symbols_num(); i++ ) { const T* symPtr = generic_get_symbol_ptr<T>( i ); if ( symPtr == nullptr ) return false; if ( match( symPtr ) ) { idx = i; return true; } } return false; } //------------------------------------------------------------------------------ template <class T> bool generic_get_symbol( Elf_Xword index, std::string& name, Elf64_Addr& value, Elf_Xword& size, unsigned char& bind, unsigned char& type, Elf_Half& section_index, unsigned char& other ) const { bool ret = false; if ( 0 != symbol_section->get_data() && index < get_symbols_num() ) { const T* pSym = reinterpret_cast<const T*>( symbol_section->get_data() + index * symbol_section->get_entry_size() ); const endianess_convertor& convertor = elf_file.get_convertor(); section* string_section = elf_file.sections[get_string_table_index()]; string_section_accessor str_reader( string_section ); const char* pStr = str_reader.get_string( convertor( pSym->st_name ) ); if ( 0 != pStr ) { name = pStr; } value = convertor( pSym->st_value ); size = convertor( pSym->st_size ); bind = ELF_ST_BIND( pSym->st_info ); type = ELF_ST_TYPE( pSym->st_info ); section_index = convertor( pSym->st_shndx ); other = pSym->st_other; ret = true; } return ret; } //------------------------------------------------------------------------------ template <class T> Elf_Word generic_add_symbol( Elf_Word name, Elf64_Addr value, Elf_Xword size, unsigned char info, unsigned char other, Elf_Half shndx ) { const endianess_convertor& convertor = elf_file.get_convertor(); T entry; entry.st_name = convertor( name ); entry.st_value = value; entry.st_value = convertor( entry.st_value ); entry.st_size = size; entry.st_size = convertor( entry.st_size ); entry.st_info = convertor( info ); entry.st_other = convertor( other ); entry.st_shndx = convertor( shndx ); symbol_section->append_data( reinterpret_cast<char*>( &entry ), sizeof( entry ) ); Elf_Word nRet = symbol_section->get_size() / sizeof( entry ) - 1; return nRet; } //------------------------------------------------------------------------------ template <class T> Elf_Xword generic_arrange_local_symbols( std::function<void( Elf_Xword first, Elf_Xword second )> func ) { const endianess_convertor& convertor = elf_file.get_convertor(); const Elf_Xword size = symbol_section->get_entry_size(); Elf_Xword first_not_local = 1; // Skip the first entry. It is always NOTYPE Elf_Xword current = 0; Elf_Xword count = get_symbols_num(); while ( true ) { T* p1 = nullptr; T* p2 = nullptr; while ( first_not_local < count ) { p1 = const_cast<T*>( generic_get_symbol_ptr<T>( first_not_local ) ); if ( ELF_ST_BIND( convertor( p1->st_info ) ) != STB_LOCAL ) break; ++first_not_local; } current = first_not_local + 1; while ( current < count ) { p2 = const_cast<T*>( generic_get_symbol_ptr<T>( current ) ); if ( ELF_ST_BIND( convertor( p2->st_info ) ) == STB_LOCAL ) break; ++current; } if ( first_not_local < count && current < count ) { if ( func ) func( first_not_local, current ); // Swap the symbols T tmp; std::copy( p1, p1 + 1, &tmp ); std::copy( p2, p2 + 1, p1 ); std::copy( &tmp, &tmp + 1, p2 ); } else { // Update 'info' field of the section symbol_section->set_info( first_not_local ); break; } } // Elf_Word nRet = symbol_section->get_size() / sizeof(entry) - 1; return first_not_local; } //------------------------------------------------------------------------------ private: const elfio& elf_file; S* symbol_section; Elf_Half hash_section_index; const section* hash_section; }; using symbol_section_accessor = symbol_section_accessor_template<section>; using const_symbol_section_accessor = symbol_section_accessor_template<const section>; } // namespace ELFIO #endif // ELFIO_SYMBOLS_HPP <commit_msg>Remove unused var; Use std::swap()<commit_after>/* Copyright (C) 2001-2020 by Serge Lamikhov-Center Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef ELFIO_SYMBOLS_HPP #define ELFIO_SYMBOLS_HPP namespace ELFIO { //------------------------------------------------------------------------------ template <class S> class symbol_section_accessor_template { public: //------------------------------------------------------------------------------ symbol_section_accessor_template( const elfio& elf_file_, S* symbol_section_ ) : elf_file( elf_file_ ), symbol_section( symbol_section_ ) { find_hash_section(); } //------------------------------------------------------------------------------ Elf_Xword get_symbols_num() const { Elf_Xword nRet = 0; if ( 0 != symbol_section->get_entry_size() ) { nRet = symbol_section->get_size() / symbol_section->get_entry_size(); } return nRet; } //------------------------------------------------------------------------------ bool get_symbol( Elf_Xword index, std::string& name, Elf64_Addr& value, Elf_Xword& size, unsigned char& bind, unsigned char& type, Elf_Half& section_index, unsigned char& other ) const { bool ret = false; if ( elf_file.get_class() == ELFCLASS32 ) { ret = generic_get_symbol<Elf32_Sym>( index, name, value, size, bind, type, section_index, other ); } else { ret = generic_get_symbol<Elf64_Sym>( index, name, value, size, bind, type, section_index, other ); } return ret; } //------------------------------------------------------------------------------ bool get_symbol( const std::string& name, Elf64_Addr& value, Elf_Xword& size, unsigned char& bind, unsigned char& type, Elf_Half& section_index, unsigned char& other ) const { bool ret = false; if ( 0 != get_hash_table_index() ) { Elf_Word nbucket = *(const Elf_Word*)hash_section->get_data(); Elf_Word nchain = *(const Elf_Word*)( hash_section->get_data() + sizeof( Elf_Word ) ); Elf_Word val = elf_hash( (const unsigned char*)name.c_str() ); Elf_Word y = *(const Elf_Word*)( hash_section->get_data() + ( 2 + val % nbucket ) * sizeof( Elf_Word ) ); std::string str; get_symbol( y, str, value, size, bind, type, section_index, other ); while ( str != name && STN_UNDEF != y && y < nchain ) { y = *(const Elf_Word*)( hash_section->get_data() + ( 2 + nbucket + y ) * sizeof( Elf_Word ) ); get_symbol( y, str, value, size, bind, type, section_index, other ); } if ( str == name ) { ret = true; } } else { for ( Elf_Xword i = 0; i < get_symbols_num() && !ret; i++ ) { std::string symbol_name; if ( get_symbol( i, symbol_name, value, size, bind, type, section_index, other ) ) { if ( symbol_name == name ) { ret = true; } } } } return ret; } //------------------------------------------------------------------------------ bool get_symbol( const Elf64_Addr& value, std::string& name, Elf_Xword& size, unsigned char& bind, unsigned char& type, Elf_Half& section_index, unsigned char& other ) const { const endianess_convertor& convertor = elf_file.get_convertor(); Elf_Xword idx = 0; bool match = false; Elf64_Addr v = 0; if ( elf_file.get_class() == ELFCLASS32 ) { match = generic_search_symbols<Elf32_Sym>( [&]( const Elf32_Sym* sym ) { return convertor( sym->st_value ) == value; }, idx ); } else { match = generic_search_symbols<Elf64_Sym>( [&]( const Elf64_Sym* sym ) { return convertor( sym->st_value ) == value; }, idx ); } if ( match ) { return get_symbol( idx, name, v, size, bind, type, section_index, other ); } return false; } //------------------------------------------------------------------------------ Elf_Word add_symbol( Elf_Word name, Elf64_Addr value, Elf_Xword size, unsigned char info, unsigned char other, Elf_Half shndx ) { Elf_Word nRet; if ( symbol_section->get_size() == 0 ) { if ( elf_file.get_class() == ELFCLASS32 ) { nRet = generic_add_symbol<Elf32_Sym>( 0, 0, 0, 0, 0, 0 ); } else { nRet = generic_add_symbol<Elf64_Sym>( 0, 0, 0, 0, 0, 0 ); } } if ( elf_file.get_class() == ELFCLASS32 ) { nRet = generic_add_symbol<Elf32_Sym>( name, value, size, info, other, shndx ); } else { nRet = generic_add_symbol<Elf64_Sym>( name, value, size, info, other, shndx ); } return nRet; } //------------------------------------------------------------------------------ Elf_Word add_symbol( Elf_Word name, Elf64_Addr value, Elf_Xword size, unsigned char bind, unsigned char type, unsigned char other, Elf_Half shndx ) { return add_symbol( name, value, size, ELF_ST_INFO( bind, type ), other, shndx ); } //------------------------------------------------------------------------------ Elf_Word add_symbol( string_section_accessor& pStrWriter, const char* str, Elf64_Addr value, Elf_Xword size, unsigned char info, unsigned char other, Elf_Half shndx ) { Elf_Word index = pStrWriter.add_string( str ); return add_symbol( index, value, size, info, other, shndx ); } //------------------------------------------------------------------------------ Elf_Word add_symbol( string_section_accessor& pStrWriter, const char* str, Elf64_Addr value, Elf_Xword size, unsigned char bind, unsigned char type, unsigned char other, Elf_Half shndx ) { return add_symbol( pStrWriter, str, value, size, ELF_ST_INFO( bind, type ), other, shndx ); } //------------------------------------------------------------------------------ Elf_Xword arrange_local_symbols( std::function<void( Elf_Xword first, Elf_Xword second )> func = nullptr ) { int nRet = 0; if ( elf_file.get_class() == ELFCLASS32 ) { nRet = generic_arrange_local_symbols<Elf32_Sym>( func ); } else { nRet = generic_arrange_local_symbols<Elf64_Sym>( func ); } return nRet; } //------------------------------------------------------------------------------ private: //------------------------------------------------------------------------------ void find_hash_section() { hash_section = 0; hash_section_index = 0; Elf_Half nSecNo = elf_file.sections.size(); for ( Elf_Half i = 0; i < nSecNo && 0 == hash_section_index; ++i ) { const section* sec = elf_file.sections[i]; if ( sec->get_link() == symbol_section->get_index() ) { hash_section = sec; hash_section_index = i; } } } //------------------------------------------------------------------------------ Elf_Half get_string_table_index() const { return (Elf_Half)symbol_section->get_link(); } //------------------------------------------------------------------------------ Elf_Half get_hash_table_index() const { return hash_section_index; } //------------------------------------------------------------------------------ template <class T> const T* generic_get_symbol_ptr( Elf_Xword index ) const { if ( 0 != symbol_section->get_data() && index < get_symbols_num() ) { const T* pSym = reinterpret_cast<const T*>( symbol_section->get_data() + index * symbol_section->get_entry_size() ); return pSym; } return nullptr; } //------------------------------------------------------------------------------ template <class T> bool generic_search_symbols( std::function<bool( const T* )> match, Elf_Xword& idx ) const { for ( Elf_Xword i = 0; i < get_symbols_num(); i++ ) { const T* symPtr = generic_get_symbol_ptr<T>( i ); if ( symPtr == nullptr ) return false; if ( match( symPtr ) ) { idx = i; return true; } } return false; } //------------------------------------------------------------------------------ template <class T> bool generic_get_symbol( Elf_Xword index, std::string& name, Elf64_Addr& value, Elf_Xword& size, unsigned char& bind, unsigned char& type, Elf_Half& section_index, unsigned char& other ) const { bool ret = false; if ( 0 != symbol_section->get_data() && index < get_symbols_num() ) { const T* pSym = reinterpret_cast<const T*>( symbol_section->get_data() + index * symbol_section->get_entry_size() ); const endianess_convertor& convertor = elf_file.get_convertor(); section* string_section = elf_file.sections[get_string_table_index()]; string_section_accessor str_reader( string_section ); const char* pStr = str_reader.get_string( convertor( pSym->st_name ) ); if ( 0 != pStr ) { name = pStr; } value = convertor( pSym->st_value ); size = convertor( pSym->st_size ); bind = ELF_ST_BIND( pSym->st_info ); type = ELF_ST_TYPE( pSym->st_info ); section_index = convertor( pSym->st_shndx ); other = pSym->st_other; ret = true; } return ret; } //------------------------------------------------------------------------------ template <class T> Elf_Word generic_add_symbol( Elf_Word name, Elf64_Addr value, Elf_Xword size, unsigned char info, unsigned char other, Elf_Half shndx ) { const endianess_convertor& convertor = elf_file.get_convertor(); T entry; entry.st_name = convertor( name ); entry.st_value = value; entry.st_value = convertor( entry.st_value ); entry.st_size = size; entry.st_size = convertor( entry.st_size ); entry.st_info = convertor( info ); entry.st_other = convertor( other ); entry.st_shndx = convertor( shndx ); symbol_section->append_data( reinterpret_cast<char*>( &entry ), sizeof( entry ) ); Elf_Word nRet = symbol_section->get_size() / sizeof( entry ) - 1; return nRet; } //------------------------------------------------------------------------------ template <class T> Elf_Xword generic_arrange_local_symbols( std::function<void( Elf_Xword first, Elf_Xword second )> func ) { const endianess_convertor& convertor = elf_file.get_convertor(); Elf_Xword first_not_local = 1; // Skip the first entry. It is always NOTYPE Elf_Xword current = 0; Elf_Xword count = get_symbols_num(); while ( true ) { T* p1 = nullptr; T* p2 = nullptr; while ( first_not_local < count ) { p1 = const_cast<T*>( generic_get_symbol_ptr<T>( first_not_local ) ); if ( ELF_ST_BIND( convertor( p1->st_info ) ) != STB_LOCAL ) break; ++first_not_local; } current = first_not_local + 1; while ( current < count ) { p2 = const_cast<T*>( generic_get_symbol_ptr<T>( current ) ); if ( ELF_ST_BIND( convertor( p2->st_info ) ) == STB_LOCAL ) break; ++current; } if ( first_not_local < count && current < count ) { if ( func ) func( first_not_local, current ); std::swap( *p1, *p2 ); } else { // Update 'info' field of the section symbol_section->set_info( first_not_local ); break; } } // Elf_Word nRet = symbol_section->get_size() / sizeof(entry) - 1; return first_not_local; } //------------------------------------------------------------------------------ private: const elfio& elf_file; S* symbol_section; Elf_Half hash_section_index; const section* hash_section; }; using symbol_section_accessor = symbol_section_accessor_template<section>; using const_symbol_section_accessor = symbol_section_accessor_template<const section>; } // namespace ELFIO #endif // ELFIO_SYMBOLS_HPP <|endoftext|>
<commit_before>#include <cassert> #include <iostream> #include <list> #include <pqxx/pqxx> #include <pqxx/compiler-internal.hxx> using namespace PGSTD; using namespace pqxx; namespace { #ifndef PQXX_HAVE_DISTANCE template<typename ITERATOR> size_t distance(ITERATOR begin, ITERATOR end) { size_t d = 0; while (begin != end) { ++begin; ++d; } return d; } #endif // PQXX_HAVE_DISTANCE void compare_results(string name, result lhs, result rhs) { if (lhs != rhs) throw logic_error("Executing " + name + " as prepared statement " "yields different results from direct execution"); if (lhs.empty()) throw logic_error("Results being compared are empty. Not much point!"); } string stringize(transaction_base &t, const string &arg) { return "'" + t.esc(arg) + "'"; } string stringize(transaction_base &t, const char arg[]) { return arg ? stringize(t,string(arg)) : "null"; } string stringize(transaction_base &t, char arg[]) { return arg ? stringize(t, string(arg)) : "null"; } template<typename T> string stringize(transaction_base &t, T i) { return stringize(t, to_string(i)); } // Substitute variables in raw query. This is not likely to be very robust, // but it should do for just this test. The main shortcomings are escaping, // and not knowing when to quote the variables. // Note we do the replacement backwards (meaning forward_only iterators won't // do!) to avoid substituting e.g. "$12" as "$1" first. template<typename ITER> string subst(transaction_base &t, string q, ITER patbegin, ITER patend) { int i = distance(patbegin, patend); for (ITER arg = patend; i > 0; --i) { --arg; const string marker = "$" + to_string(i), var = stringize(t, *arg); const string::size_type msz = marker.size(); while (q.find(marker) != string::npos) q.replace(q.find(marker),msz,var); } return q; } template<typename CNTNR> string subst(transaction_base &t, string q, const CNTNR &patterns) { return subst(t, q, patterns.begin(), patterns.end()); } } // namespace // Test program for libpqxx. Define and use prepared statements. // // Usage: test085 int main() { try { /* A bit of nastiness in prepared statements: on 7.3.x backends we can't * compare pg_tables.tablename to a string. We work around this by using * the LIKE operator. * * Later backend versions do not suffer from this problem. */ const string QN_readpgtables = "ReadPGTables", Q_readpgtables = "SELECT * FROM pg_tables", QN_seetable = "SeeTable", Q_seetable = Q_readpgtables + " WHERE tablename LIKE $1", QN_seetables = "SeeTables", Q_seetables = Q_seetable + " OR tablename LIKE $2"; lazyconnection C; cout << "Preparing a simple statement..." << endl; C.prepare(QN_readpgtables, Q_readpgtables); nontransaction T(C, "test85"); try { // See if a basic prepared statement works just like a regular query cout << "Basic correctness check on prepared statement..." << endl; compare_results(QN_readpgtables, T.prepared(QN_readpgtables).exec(), T.exec(Q_readpgtables)); } catch (const exception &) { if (!C.supports(connection_base::cap_prepared_statements)) { cout << "Backend version does not support prepared statements. " "Skipping." << endl; return 0; } throw; } // Try prepare_now() on an already prepared statement C.prepare_now(QN_readpgtables); // Pro forma check: same thing but with name passed as C-style string compare_results(QN_readpgtables+"_char", T.prepared(QN_readpgtables.c_str()).exec(), T.exec(Q_readpgtables)); cout << "Dropping prepared statement..." << endl; C.unprepare(QN_readpgtables); bool failed = true; try { disable_noticer d(C); C.prepare_now(QN_readpgtables); failed = false; } catch (const exception &e) { cout << "(Expected) " << e.what() << endl; } if (!failed) throw runtime_error("prepare_now() succeeded on dropped statement"); // Just to try and confuse things, "unprepare" twice cout << "Testing error detection and handling..." << endl; try { C.unprepare(QN_readpgtables); } catch (const exception &e) { cout << "(Expected) " << e.what() << endl; } // Verify that attempt to execute unprepared statement fails bool failsOK = true; try { T.prepared(QN_readpgtables).exec(); failsOK = false; } catch (const exception &e) { cout << "(Expected) " << e.what() << endl; } if (!failsOK) throw logic_error("Execute unprepared statement didn't fail"); // Re-prepare the same statement and test again C.prepare(QN_readpgtables, Q_readpgtables); C.prepare_now(QN_readpgtables); compare_results(QN_readpgtables+"_2", T.prepared(QN_readpgtables).exec(), T.exec(Q_readpgtables)); // Double preparation of identical statement should be ignored... C.prepare(QN_readpgtables, Q_readpgtables); compare_results(QN_readpgtables+"_double", T.prepared(QN_readpgtables).exec(), T.exec(Q_readpgtables)); // ...But a modified definition shouldn't try { failsOK = true; C.prepare(QN_readpgtables, Q_readpgtables + " ORDER BY tablename"); failsOK = false; } catch (const exception &e) { cout << "(Expected) " << e.what() << endl; } if (!failsOK) throw logic_error("Bad redefinition of statement went unnoticed"); cout << "Testing prepared statement with parameter..." << endl; C.prepare(QN_seetable, Q_seetable)("varchar", pqxx::prepare::treat_string); vector<string> args; args.push_back("pg_type"); compare_results(QN_seetable+"_seq", T.prepared(QN_seetable)(args[0]).exec(), T.exec(subst(T,Q_seetable,args))); cout << "Testing prepared statement with 2 parameters..." << endl; C.prepare(QN_seetables, Q_seetables) ("varchar",pqxx::prepare::treat_string) ("varchar",pqxx::prepare::treat_string); args.push_back("pg_index"); compare_results(QN_seetables+"_seq", T.prepared(QN_seetables)(args[0])(args[1]).exec(), T.exec(subst(T,Q_seetables,args))); cout << "Testing prepared statement with a null parameter..." << endl; vector<const char *> ptrs; ptrs.push_back(0); ptrs.push_back("pg_index"); compare_results(QN_seetables+"_null1", T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(), T.exec(subst(T,Q_seetables,ptrs))); compare_results(QN_seetables+"_null2", T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(), T.prepared(QN_seetables)()(ptrs[1]).exec()); compare_results(QN_seetables+"_null3", T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(), T.prepared(QN_seetables)("somestring",false)(ptrs[1]).exec()); compare_results(QN_seetables+"_null4", T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(), T.prepared(QN_seetables)(42,false)(ptrs[1]).exec()); compare_results(QN_seetables+"_null5", T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(), T.prepared(QN_seetables)(0,false)(ptrs[1]).exec()); cout << "Testing wrong numbers of parameters..." << endl; try { failsOK = true; T.prepared(QN_seetables)()()("hi mom!").exec(); failsOK = false; } catch (const exception &e) { cout << "(Expected) " << e.what() << endl; } if (!failsOK) throw logic_error("No error for too many parameters"); try { failsOK = true; T.prepared(QN_seetables)("who, me?").exec(); failsOK = false; } catch (const exception &e) { cout << "(Expected) " << e.what() << endl; } if (!failsOK) throw logic_error("No error for too few parameters"); cout << "Done." << endl; } catch (const feature_not_supported &e) { cout << "Backend version does not support prepared statements. Skipping." << endl; return 0; } catch (const sql_error &e) { cerr << "SQL error: " << e.what() << endl << "Query was: " << e.query() << endl; return 1; } catch (const exception &e) { // All exceptions thrown by libpqxx are derived from std::exception cerr << "Exception: " << e.what() << endl; return 2; } catch (...) { // This is really unexpected (see above) cerr << "Unhandled exception" << endl; return 100; } return 0; } <commit_msg>Put compiler-internal include in a better place.<commit_after>#include <cassert> #include <iostream> #include <list> #include <pqxx/compiler-internal.hxx> #include <pqxx/pqxx> using namespace PGSTD; using namespace pqxx; namespace { #ifndef PQXX_HAVE_DISTANCE template<typename ITERATOR> size_t distance(ITERATOR begin, ITERATOR end) { size_t d = 0; while (begin != end) { ++begin; ++d; } return d; } #endif // PQXX_HAVE_DISTANCE void compare_results(string name, result lhs, result rhs) { if (lhs != rhs) throw logic_error("Executing " + name + " as prepared statement " "yields different results from direct execution"); if (lhs.empty()) throw logic_error("Results being compared are empty. Not much point!"); } string stringize(transaction_base &t, const string &arg) { return "'" + t.esc(arg) + "'"; } string stringize(transaction_base &t, const char arg[]) { return arg ? stringize(t,string(arg)) : "null"; } string stringize(transaction_base &t, char arg[]) { return arg ? stringize(t, string(arg)) : "null"; } template<typename T> string stringize(transaction_base &t, T i) { return stringize(t, to_string(i)); } // Substitute variables in raw query. This is not likely to be very robust, // but it should do for just this test. The main shortcomings are escaping, // and not knowing when to quote the variables. // Note we do the replacement backwards (meaning forward_only iterators won't // do!) to avoid substituting e.g. "$12" as "$1" first. template<typename ITER> string subst(transaction_base &t, string q, ITER patbegin, ITER patend) { int i = distance(patbegin, patend); for (ITER arg = patend; i > 0; --i) { --arg; const string marker = "$" + to_string(i), var = stringize(t, *arg); const string::size_type msz = marker.size(); while (q.find(marker) != string::npos) q.replace(q.find(marker),msz,var); } return q; } template<typename CNTNR> string subst(transaction_base &t, string q, const CNTNR &patterns) { return subst(t, q, patterns.begin(), patterns.end()); } } // namespace // Test program for libpqxx. Define and use prepared statements. // // Usage: test085 int main() { try { /* A bit of nastiness in prepared statements: on 7.3.x backends we can't * compare pg_tables.tablename to a string. We work around this by using * the LIKE operator. * * Later backend versions do not suffer from this problem. */ const string QN_readpgtables = "ReadPGTables", Q_readpgtables = "SELECT * FROM pg_tables", QN_seetable = "SeeTable", Q_seetable = Q_readpgtables + " WHERE tablename LIKE $1", QN_seetables = "SeeTables", Q_seetables = Q_seetable + " OR tablename LIKE $2"; lazyconnection C; cout << "Preparing a simple statement..." << endl; C.prepare(QN_readpgtables, Q_readpgtables); nontransaction T(C, "test85"); try { // See if a basic prepared statement works just like a regular query cout << "Basic correctness check on prepared statement..." << endl; compare_results(QN_readpgtables, T.prepared(QN_readpgtables).exec(), T.exec(Q_readpgtables)); } catch (const exception &) { if (!C.supports(connection_base::cap_prepared_statements)) { cout << "Backend version does not support prepared statements. " "Skipping." << endl; return 0; } throw; } // Try prepare_now() on an already prepared statement C.prepare_now(QN_readpgtables); // Pro forma check: same thing but with name passed as C-style string compare_results(QN_readpgtables+"_char", T.prepared(QN_readpgtables.c_str()).exec(), T.exec(Q_readpgtables)); cout << "Dropping prepared statement..." << endl; C.unprepare(QN_readpgtables); bool failed = true; try { disable_noticer d(C); C.prepare_now(QN_readpgtables); failed = false; } catch (const exception &e) { cout << "(Expected) " << e.what() << endl; } if (!failed) throw runtime_error("prepare_now() succeeded on dropped statement"); // Just to try and confuse things, "unprepare" twice cout << "Testing error detection and handling..." << endl; try { C.unprepare(QN_readpgtables); } catch (const exception &e) { cout << "(Expected) " << e.what() << endl; } // Verify that attempt to execute unprepared statement fails bool failsOK = true; try { T.prepared(QN_readpgtables).exec(); failsOK = false; } catch (const exception &e) { cout << "(Expected) " << e.what() << endl; } if (!failsOK) throw logic_error("Execute unprepared statement didn't fail"); // Re-prepare the same statement and test again C.prepare(QN_readpgtables, Q_readpgtables); C.prepare_now(QN_readpgtables); compare_results(QN_readpgtables+"_2", T.prepared(QN_readpgtables).exec(), T.exec(Q_readpgtables)); // Double preparation of identical statement should be ignored... C.prepare(QN_readpgtables, Q_readpgtables); compare_results(QN_readpgtables+"_double", T.prepared(QN_readpgtables).exec(), T.exec(Q_readpgtables)); // ...But a modified definition shouldn't try { failsOK = true; C.prepare(QN_readpgtables, Q_readpgtables + " ORDER BY tablename"); failsOK = false; } catch (const exception &e) { cout << "(Expected) " << e.what() << endl; } if (!failsOK) throw logic_error("Bad redefinition of statement went unnoticed"); cout << "Testing prepared statement with parameter..." << endl; C.prepare(QN_seetable, Q_seetable)("varchar", pqxx::prepare::treat_string); vector<string> args; args.push_back("pg_type"); compare_results(QN_seetable+"_seq", T.prepared(QN_seetable)(args[0]).exec(), T.exec(subst(T,Q_seetable,args))); cout << "Testing prepared statement with 2 parameters..." << endl; C.prepare(QN_seetables, Q_seetables) ("varchar",pqxx::prepare::treat_string) ("varchar",pqxx::prepare::treat_string); args.push_back("pg_index"); compare_results(QN_seetables+"_seq", T.prepared(QN_seetables)(args[0])(args[1]).exec(), T.exec(subst(T,Q_seetables,args))); cout << "Testing prepared statement with a null parameter..." << endl; vector<const char *> ptrs; ptrs.push_back(0); ptrs.push_back("pg_index"); compare_results(QN_seetables+"_null1", T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(), T.exec(subst(T,Q_seetables,ptrs))); compare_results(QN_seetables+"_null2", T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(), T.prepared(QN_seetables)()(ptrs[1]).exec()); compare_results(QN_seetables+"_null3", T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(), T.prepared(QN_seetables)("somestring",false)(ptrs[1]).exec()); compare_results(QN_seetables+"_null4", T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(), T.prepared(QN_seetables)(42,false)(ptrs[1]).exec()); compare_results(QN_seetables+"_null5", T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(), T.prepared(QN_seetables)(0,false)(ptrs[1]).exec()); cout << "Testing wrong numbers of parameters..." << endl; try { failsOK = true; T.prepared(QN_seetables)()()("hi mom!").exec(); failsOK = false; } catch (const exception &e) { cout << "(Expected) " << e.what() << endl; } if (!failsOK) throw logic_error("No error for too many parameters"); try { failsOK = true; T.prepared(QN_seetables)("who, me?").exec(); failsOK = false; } catch (const exception &e) { cout << "(Expected) " << e.what() << endl; } if (!failsOK) throw logic_error("No error for too few parameters"); cout << "Done." << endl; } catch (const feature_not_supported &e) { cout << "Backend version does not support prepared statements. Skipping." << endl; return 0; } catch (const sql_error &e) { cerr << "SQL error: " << e.what() << endl << "Query was: " << e.query() << endl; return 1; } catch (const exception &e) { // All exceptions thrown by libpqxx are derived from std::exception cerr << "Exception: " << e.what() << endl; return 2; } catch (...) { // This is really unexpected (see above) cerr << "Unhandled exception" << endl; return 100; } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: LineChartType.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: vg $ $Date: 2007-05-22 18:49:07 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "LineChartType.hxx" #include "PropertyHelper.hxx" #include "macros.hxx" #include "servicenames_charttypes.hxx" #include "ContainerHelper.hxx" #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_CURVESTYLE_HPP_ #include <com/sun/star/chart2/CurveStyle.hpp> #endif using namespace ::com::sun::star; using ::rtl::OUString; using ::com::sun::star::beans::Property; using ::com::sun::star::uno::Sequence; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Any; using ::osl::MutexGuard; namespace { enum { PROP_LINECHARTTYPE_CURVE_STYLE, PROP_LINECHARTTYPE_CURVE_RESOLUTION, PROP_LINECHARTTYPE_SPLINE_ORDER }; void lcl_AddPropertiesToVector( ::std::vector< Property > & rOutProperties ) { rOutProperties.push_back( Property( C2U( "CurveStyle" ), PROP_LINECHARTTYPE_CURVE_STYLE, ::getCppuType( reinterpret_cast< const chart2::CurveStyle * >(0)), beans::PropertyAttribute::BOUND | beans::PropertyAttribute::MAYBEDEFAULT )); rOutProperties.push_back( Property( C2U( "CurveResolution" ), PROP_LINECHARTTYPE_CURVE_RESOLUTION, ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)), beans::PropertyAttribute::BOUND | beans::PropertyAttribute::MAYBEDEFAULT )); rOutProperties.push_back( Property( C2U( "SplineOrder" ), PROP_LINECHARTTYPE_SPLINE_ORDER, ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)), beans::PropertyAttribute::BOUND | beans::PropertyAttribute::MAYBEDEFAULT )); } void lcl_AddDefaultsToMap( ::chart::tPropertyValueMap & rOutMap ) { OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LINECHARTTYPE_CURVE_STYLE )); rOutMap[ PROP_LINECHARTTYPE_CURVE_STYLE ] = uno::makeAny( chart2::CurveStyle_LINES ); OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LINECHARTTYPE_CURVE_RESOLUTION )); rOutMap[ PROP_LINECHARTTYPE_CURVE_RESOLUTION ] = uno::makeAny( sal_Int32( 20 ) ); // todo: check whether order 3 means polygons of order 3 or 2. (see // http://www.people.nnov.ru/fractal/Splines/Basis.htm ) OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LINECHARTTYPE_SPLINE_ORDER )); rOutMap[ PROP_LINECHARTTYPE_SPLINE_ORDER ] = uno::makeAny( sal_Int32( 3 ) ); } const Sequence< Property > & lcl_GetPropertySequence() { static Sequence< Property > aPropSeq; // /-- ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if( 0 == aPropSeq.getLength() ) { // get properties ::std::vector< ::com::sun::star::beans::Property > aProperties; lcl_AddPropertiesToVector( aProperties ); // and sort them for access via bsearch ::std::sort( aProperties.begin(), aProperties.end(), ::chart::PropertyNameLess() ); // transfer result to static Sequence aPropSeq = ::chart::ContainerHelper::ContainerToSequence( aProperties ); } return aPropSeq; } } // anonymous namespace namespace chart { LineChartType::LineChartType( const uno::Reference< uno::XComponentContext > & xContext ) : ChartType( xContext ) { } LineChartType::LineChartType( const LineChartType & rOther ) : ChartType( rOther ) { } LineChartType::~LineChartType() {} // ____ XCloneable ____ uno::Reference< util::XCloneable > SAL_CALL LineChartType::createClone() throw (uno::RuntimeException) { return uno::Reference< util::XCloneable >( new LineChartType( *this )); } // ____ XChartType ____ ::rtl::OUString SAL_CALL LineChartType::getChartType() throw (uno::RuntimeException) { return CHART2_SERVICE_NAME_CHARTTYPE_LINE; } // ____ OPropertySet ____ uno::Any LineChartType::GetDefaultValue( sal_Int32 nHandle ) const throw(beans::UnknownPropertyException) { static tPropertyValueMap aStaticDefaults; // /-- ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if( 0 == aStaticDefaults.size() ) { // initialize defaults lcl_AddDefaultsToMap( aStaticDefaults ); } tPropertyValueMap::const_iterator aFound( aStaticDefaults.find( nHandle )); if( aFound == aStaticDefaults.end()) return uno::Any(); return (*aFound).second; // \-- } ::cppu::IPropertyArrayHelper & SAL_CALL LineChartType::getInfoHelper() { static ::cppu::OPropertyArrayHelper aArrayHelper( lcl_GetPropertySequence(), /* bSorted = */ sal_True ); return aArrayHelper; } // ____ XPropertySet ____ uno::Reference< beans::XPropertySetInfo > SAL_CALL LineChartType::getPropertySetInfo() throw (uno::RuntimeException) { static uno::Reference< beans::XPropertySetInfo > xInfo; // /-- ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if( !xInfo.is()) { xInfo = ::cppu::OPropertySetHelper::createPropertySetInfo( getInfoHelper()); } return xInfo; // \-- } uno::Sequence< ::rtl::OUString > LineChartType::getSupportedServiceNames_Static() { uno::Sequence< ::rtl::OUString > aServices( 3 ); aServices[ 0 ] = CHART2_SERVICE_NAME_CHARTTYPE_LINE; aServices[ 1 ] = C2U( "com.sun.star.chart2.ChartType" ); aServices[ 2 ] = C2U( "com.sun.star.beans.PropertySet" ); return aServices; } // implement XServiceInfo methods basing upon getSupportedServiceNames_Static APPHELPER_XSERVICEINFO_IMPL( LineChartType, C2U( "com.sun.star.comp.chart.LineChartType" )); } // namespace chart <commit_msg>INTEGRATION: CWS chart11 (1.9.38); FILE MERGED 2007/07/31 12:56:45 bm 1.9.38.1: #i80084# avoid usage of map operator[] with enums as keys, simplify initialization of default property values<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: LineChartType.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: vg $ $Date: 2007-09-18 15:05:46 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "LineChartType.hxx" #include "PropertyHelper.hxx" #include "macros.hxx" #include "servicenames_charttypes.hxx" #include "ContainerHelper.hxx" #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_CURVESTYLE_HPP_ #include <com/sun/star/chart2/CurveStyle.hpp> #endif using namespace ::com::sun::star; using ::rtl::OUString; using ::com::sun::star::beans::Property; using ::com::sun::star::uno::Sequence; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Any; using ::osl::MutexGuard; namespace { enum { PROP_LINECHARTTYPE_CURVE_STYLE, PROP_LINECHARTTYPE_CURVE_RESOLUTION, PROP_LINECHARTTYPE_SPLINE_ORDER }; void lcl_AddPropertiesToVector( ::std::vector< Property > & rOutProperties ) { rOutProperties.push_back( Property( C2U( "CurveStyle" ), PROP_LINECHARTTYPE_CURVE_STYLE, ::getCppuType( reinterpret_cast< const chart2::CurveStyle * >(0)), beans::PropertyAttribute::BOUND | beans::PropertyAttribute::MAYBEDEFAULT )); rOutProperties.push_back( Property( C2U( "CurveResolution" ), PROP_LINECHARTTYPE_CURVE_RESOLUTION, ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)), beans::PropertyAttribute::BOUND | beans::PropertyAttribute::MAYBEDEFAULT )); rOutProperties.push_back( Property( C2U( "SplineOrder" ), PROP_LINECHARTTYPE_SPLINE_ORDER, ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)), beans::PropertyAttribute::BOUND | beans::PropertyAttribute::MAYBEDEFAULT )); } void lcl_AddDefaultsToMap( ::chart::tPropertyValueMap & rOutMap ) { ::chart::PropertyHelper::setPropertyValueDefault( rOutMap, PROP_LINECHARTTYPE_CURVE_STYLE, ::chart2::CurveStyle_LINES ); ::chart::PropertyHelper::setPropertyValueDefault< sal_Int32 >( rOutMap, PROP_LINECHARTTYPE_CURVE_RESOLUTION, 20 ); // todo: check whether order 3 means polygons of order 3 or 2. (see // http://www.people.nnov.ru/fractal/Splines/Basis.htm ) ::chart::PropertyHelper::setPropertyValueDefault< sal_Int32 >( rOutMap, PROP_LINECHARTTYPE_SPLINE_ORDER, 3 ); } const Sequence< Property > & lcl_GetPropertySequence() { static Sequence< Property > aPropSeq; // /-- ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if( 0 == aPropSeq.getLength() ) { // get properties ::std::vector< ::com::sun::star::beans::Property > aProperties; lcl_AddPropertiesToVector( aProperties ); // and sort them for access via bsearch ::std::sort( aProperties.begin(), aProperties.end(), ::chart::PropertyNameLess() ); // transfer result to static Sequence aPropSeq = ::chart::ContainerHelper::ContainerToSequence( aProperties ); } return aPropSeq; } } // anonymous namespace namespace chart { LineChartType::LineChartType( const uno::Reference< uno::XComponentContext > & xContext ) : ChartType( xContext ) { } LineChartType::LineChartType( const LineChartType & rOther ) : ChartType( rOther ) { } LineChartType::~LineChartType() {} // ____ XCloneable ____ uno::Reference< util::XCloneable > SAL_CALL LineChartType::createClone() throw (uno::RuntimeException) { return uno::Reference< util::XCloneable >( new LineChartType( *this )); } // ____ XChartType ____ ::rtl::OUString SAL_CALL LineChartType::getChartType() throw (uno::RuntimeException) { return CHART2_SERVICE_NAME_CHARTTYPE_LINE; } // ____ OPropertySet ____ uno::Any LineChartType::GetDefaultValue( sal_Int32 nHandle ) const throw(beans::UnknownPropertyException) { static tPropertyValueMap aStaticDefaults; // /-- ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if( 0 == aStaticDefaults.size() ) { // initialize defaults lcl_AddDefaultsToMap( aStaticDefaults ); } tPropertyValueMap::const_iterator aFound( aStaticDefaults.find( nHandle )); if( aFound == aStaticDefaults.end()) return uno::Any(); return (*aFound).second; // \-- } ::cppu::IPropertyArrayHelper & SAL_CALL LineChartType::getInfoHelper() { static ::cppu::OPropertyArrayHelper aArrayHelper( lcl_GetPropertySequence(), /* bSorted = */ sal_True ); return aArrayHelper; } // ____ XPropertySet ____ uno::Reference< beans::XPropertySetInfo > SAL_CALL LineChartType::getPropertySetInfo() throw (uno::RuntimeException) { static uno::Reference< beans::XPropertySetInfo > xInfo; // /-- ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if( !xInfo.is()) { xInfo = ::cppu::OPropertySetHelper::createPropertySetInfo( getInfoHelper()); } return xInfo; // \-- } uno::Sequence< ::rtl::OUString > LineChartType::getSupportedServiceNames_Static() { uno::Sequence< ::rtl::OUString > aServices( 3 ); aServices[ 0 ] = CHART2_SERVICE_NAME_CHARTTYPE_LINE; aServices[ 1 ] = C2U( "com.sun.star.chart2.ChartType" ); aServices[ 2 ] = C2U( "com.sun.star.beans.PropertySet" ); return aServices; } // implement XServiceInfo methods basing upon getSupportedServiceNames_Static APPHELPER_XSERVICEINFO_IMPL( LineChartType, C2U( "com.sun.star.comp.chart.LineChartType" )); } // namespace chart <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/web_page_view.h" #include "base/callback.h" #include "base/logging.h" #include "base/string_util.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "chrome/browser/chromeos/login/helper.h" #include "chrome/browser/chromeos/login/rounded_rect_painter.h" #include "content/browser/child_process_security_policy.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/browser/webui/web_ui.h" #include "content/common/bindings_policy.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "ipc/ipc_message.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/canvas.h" #include "views/background.h" #include "views/border.h" #include "views/controls/label.h" #include "views/controls/throbber.h" using base::TimeDelta; using views::Label; using views::View; using webkit_glue::FormData; namespace chromeos { namespace { // Spacing (vertical/horizontal) between controls. const int kSpacing = 10; // Time in ms after that waiting controls are shown on Start. const int kStartDelayMs = 500; // Time in ms after that waiting controls are hidden on Stop. const int kStopDelayMs = 500; } // namespace /////////////////////////////////////////////////////////////////////////////// // WizardWebPageViewTabContents, public: WizardWebPageViewTabContents::WizardWebPageViewTabContents( Profile* profile, SiteInstance* site_instance, WebPageDelegate* page_delegate) : TabContents(profile, site_instance, MSG_ROUTING_NONE, NULL, NULL), page_delegate_(page_delegate) { } void WizardWebPageViewTabContents::DidFailProvisionalLoadWithError( RenderViewHost* render_view_host, bool is_main_frame, int error_code, const GURL& url, bool showing_repost_interstitial) { LOG(ERROR) << "Page load failed. URL = " << url << ", error: " << error_code; page_delegate_->OnPageLoadFailed(url.spec()); } void WizardWebPageViewTabContents::DidDisplayInsecureContent() { LOG(ERROR) << "Page load failed: did display insecure content"; page_delegate_->OnPageLoadFailed("Displayed insecure content"); } void WizardWebPageViewTabContents::DidRunInsecureContent( const std::string& security_origin) { LOG(ERROR) << "Page load failed: did run insecure content"; page_delegate_->OnPageLoadFailed(security_origin); } void WizardWebPageViewTabContents::DocumentLoadedInFrame( long long /*frame_id*/) { page_delegate_->OnPageLoaded(); } void WizardWebPageViewTabContents::DidFinishLoad( long long /*frame_id*/) { } /////////////////////////////////////////////////////////////////////////////// // WebPageDomView, public: void WebPageDomView::SetTabContentsDelegate( TabContentsDelegate* delegate) { tab_contents_->set_delegate(delegate); } /////////////////////////////////////////////////////////////////////////////// // WebPageView, public: WebPageView::WebPageView() : throbber_(NULL), connecting_label_(NULL) {} WebPageView::~WebPageView() {} void WebPageView::Init() { views::Painter* painter = CreateWizardPainter( &BorderDefinition::kScreenBorder); set_background( views::Background::CreateBackgroundPainter(true, painter)); set_border(CreateWizardBorder(&BorderDefinition::kScreenBorder)); dom_view()->SetVisible(false); AddChildView(dom_view()); throbber_ = CreateDefaultThrobber(); AddChildView(throbber_); connecting_label_ = new views::Label(); connecting_label_->SetText( UTF16ToWide(l10n_util::GetStringUTF16(IDS_LOAD_STATE_CONNECTING))); ResourceBundle& rb = ResourceBundle::GetSharedInstance(); connecting_label_->SetFont(rb.GetFont(ResourceBundle::MediumFont)); connecting_label_->SetVisible(false); AddChildView(connecting_label_ ); start_timer_.Start(TimeDelta::FromMilliseconds(kStartDelayMs), this, &WebPageView::ShowWaitingControls); } void WebPageView::InitDOM(Profile* profile, SiteInstance* site_instance) { dom_view()->Init(profile, site_instance); } void WebPageView::LoadURL(const GURL& url) { dom_view()->LoadURL(url); } void WebPageView::SetTabContentsDelegate( TabContentsDelegate* delegate) { dom_view()->SetTabContentsDelegate(delegate); } void WebPageView::SetWebPageDelegate(WebPageDelegate* delegate) { dom_view()->set_web_page_delegate(delegate); } void WebPageView::ShowPageContent() { // TODO(nkostylev): Show throbber as an overlay until page has been rendered. start_timer_.Stop(); if (!stop_timer_.IsRunning()) { stop_timer_.Start(TimeDelta::FromMilliseconds(kStopDelayMs), this, &WebPageView::ShowRenderedPage); } } /////////////////////////////////////////////////////////////////////////////// // WebPageView, private: void WebPageView::ShowRenderedPage() { throbber_->Stop(); connecting_label_->SetVisible(false); dom_view()->SetVisible(true); } void WebPageView::ShowWaitingControls() { throbber_->Start(); connecting_label_->SetVisible(true); } /////////////////////////////////////////////////////////////////////////////// // WebPageView, views::View implementation: void WebPageView::Layout() { dom_view()->SetBoundsRect(GetContentsBounds()); int y = height() / 2 - throbber_->GetPreferredSize().height() / 2; throbber_->SetBounds( width() / 2 - throbber_->GetPreferredSize().width() / 2, y, throbber_->GetPreferredSize().width(), throbber_->GetPreferredSize().height()); connecting_label_->SetBounds( width() / 2 - connecting_label_->GetPreferredSize().width() / 2, y + throbber_->GetPreferredSize().height() + kSpacing, connecting_label_->GetPreferredSize().width(), connecting_label_->GetPreferredSize().height()); } } // namespace chromeos <commit_msg>fix compile error that just started happening on linux views builders, not sure why<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/web_page_view.h" #include "base/callback.h" #include "base/logging.h" #include "base/string_util.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "chrome/browser/chromeos/login/helper.h" #include "chrome/browser/chromeos/login/rounded_rect_painter.h" #include "content/browser/child_process_security_policy.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/browser/webui/web_ui.h" #include "content/common/bindings_policy.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "ipc/ipc_message.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/canvas.h" #include "views/background.h" #include "views/border.h" #include "views/controls/label.h" #include "views/controls/throbber.h" using base::TimeDelta; using views::Label; using views::View; namespace chromeos { namespace { // Spacing (vertical/horizontal) between controls. const int kSpacing = 10; // Time in ms after that waiting controls are shown on Start. const int kStartDelayMs = 500; // Time in ms after that waiting controls are hidden on Stop. const int kStopDelayMs = 500; } // namespace /////////////////////////////////////////////////////////////////////////////// // WizardWebPageViewTabContents, public: WizardWebPageViewTabContents::WizardWebPageViewTabContents( Profile* profile, SiteInstance* site_instance, WebPageDelegate* page_delegate) : TabContents(profile, site_instance, MSG_ROUTING_NONE, NULL, NULL), page_delegate_(page_delegate) { } void WizardWebPageViewTabContents::DidFailProvisionalLoadWithError( RenderViewHost* render_view_host, bool is_main_frame, int error_code, const GURL& url, bool showing_repost_interstitial) { LOG(ERROR) << "Page load failed. URL = " << url << ", error: " << error_code; page_delegate_->OnPageLoadFailed(url.spec()); } void WizardWebPageViewTabContents::DidDisplayInsecureContent() { LOG(ERROR) << "Page load failed: did display insecure content"; page_delegate_->OnPageLoadFailed("Displayed insecure content"); } void WizardWebPageViewTabContents::DidRunInsecureContent( const std::string& security_origin) { LOG(ERROR) << "Page load failed: did run insecure content"; page_delegate_->OnPageLoadFailed(security_origin); } void WizardWebPageViewTabContents::DocumentLoadedInFrame( long long /*frame_id*/) { page_delegate_->OnPageLoaded(); } void WizardWebPageViewTabContents::DidFinishLoad( long long /*frame_id*/) { } /////////////////////////////////////////////////////////////////////////////// // WebPageDomView, public: void WebPageDomView::SetTabContentsDelegate( TabContentsDelegate* delegate) { tab_contents_->set_delegate(delegate); } /////////////////////////////////////////////////////////////////////////////// // WebPageView, public: WebPageView::WebPageView() : throbber_(NULL), connecting_label_(NULL) {} WebPageView::~WebPageView() {} void WebPageView::Init() { views::Painter* painter = CreateWizardPainter( &BorderDefinition::kScreenBorder); set_background( views::Background::CreateBackgroundPainter(true, painter)); set_border(CreateWizardBorder(&BorderDefinition::kScreenBorder)); dom_view()->SetVisible(false); AddChildView(dom_view()); throbber_ = CreateDefaultThrobber(); AddChildView(throbber_); connecting_label_ = new views::Label(); connecting_label_->SetText( UTF16ToWide(l10n_util::GetStringUTF16(IDS_LOAD_STATE_CONNECTING))); ResourceBundle& rb = ResourceBundle::GetSharedInstance(); connecting_label_->SetFont(rb.GetFont(ResourceBundle::MediumFont)); connecting_label_->SetVisible(false); AddChildView(connecting_label_ ); start_timer_.Start(TimeDelta::FromMilliseconds(kStartDelayMs), this, &WebPageView::ShowWaitingControls); } void WebPageView::InitDOM(Profile* profile, SiteInstance* site_instance) { dom_view()->Init(profile, site_instance); } void WebPageView::LoadURL(const GURL& url) { dom_view()->LoadURL(url); } void WebPageView::SetTabContentsDelegate( TabContentsDelegate* delegate) { dom_view()->SetTabContentsDelegate(delegate); } void WebPageView::SetWebPageDelegate(WebPageDelegate* delegate) { dom_view()->set_web_page_delegate(delegate); } void WebPageView::ShowPageContent() { // TODO(nkostylev): Show throbber as an overlay until page has been rendered. start_timer_.Stop(); if (!stop_timer_.IsRunning()) { stop_timer_.Start(TimeDelta::FromMilliseconds(kStopDelayMs), this, &WebPageView::ShowRenderedPage); } } /////////////////////////////////////////////////////////////////////////////// // WebPageView, private: void WebPageView::ShowRenderedPage() { throbber_->Stop(); connecting_label_->SetVisible(false); dom_view()->SetVisible(true); } void WebPageView::ShowWaitingControls() { throbber_->Start(); connecting_label_->SetVisible(true); } /////////////////////////////////////////////////////////////////////////////// // WebPageView, views::View implementation: void WebPageView::Layout() { dom_view()->SetBoundsRect(GetContentsBounds()); int y = height() / 2 - throbber_->GetPreferredSize().height() / 2; throbber_->SetBounds( width() / 2 - throbber_->GetPreferredSize().width() / 2, y, throbber_->GetPreferredSize().width(), throbber_->GetPreferredSize().height()); connecting_label_->SetBounds( width() / 2 - connecting_label_->GetPreferredSize().width() / 2, y + throbber_->GetPreferredSize().height() + kSpacing, connecting_label_->GetPreferredSize().width(), connecting_label_->GetPreferredSize().height()); } } // namespace chromeos <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://www.qtsoftware.com/contact. ** $QT_END_LICENSE$ ** ***************************************************************************/ #include <QtGui> #include "mainwindow.h" //![0] MainWindow::MainWindow() { audioOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this); mediaObject = new Phonon::MediaObject(this); metaInformationResolver = new Phonon::MediaObject(this); mediaObject->setTickInterval(1000); //![0] //![2] connect(mediaObject, SIGNAL(tick(qint64)), this, SLOT(tick(qint64))); connect(mediaObject, SIGNAL(stateChanged(Phonon::State, Phonon::State)), this, SLOT(stateChanged(Phonon::State, Phonon::State))); connect(metaInformationResolver, SIGNAL(stateChanged(Phonon::State,Phonon::State)), this, SLOT(metaStateChanged(Phonon::State, Phonon::State))); connect(mediaObject, SIGNAL(currentSourceChanged(const Phonon::MediaSource &)), this, SLOT(sourceChanged(const Phonon::MediaSource &))); connect(mediaObject, SIGNAL(aboutToFinish()), this, SLOT(aboutToFinish())); //![2] //![1] Phonon::createPath(mediaObject, audioOutput); //![1] setupActions(); setupMenus(); setupUi(); timeLcd->display("00:00"); } //![6] void MainWindow::addFiles() { QStringList files = QFileDialog::getOpenFileNames(this, tr("Select Music Files"), QDesktopServices::storageLocation(QDesktopServices::MusicLocation)); if (files.isEmpty()) return; int index = sources.size(); foreach (QString string, files) { Phonon::MediaSource source(string); sources.append(source); } if (!sources.isEmpty()) metaInformationResolver->setCurrentSource(sources.at(index)); } //![6] void MainWindow::about() { QMessageBox::information(this, tr("About Music Player"), tr("The Music Player example shows how to use Phonon - the multimedia" " framework that comes with Qt - to create a simple music player.")); } //![9] void MainWindow::stateChanged(Phonon::State newState, Phonon::State /* oldState */) { switch (newState) { case Phonon::ErrorState: if (mediaObject->errorType() == Phonon::FatalError) { QMessageBox::warning(this, tr("Fatal Error"), mediaObject->errorString()); } else { QMessageBox::warning(this, tr("Error"), mediaObject->errorString()); } break; //![9] //![10] case Phonon::PlayingState: playAction->setEnabled(false); pauseAction->setEnabled(true); stopAction->setEnabled(true); break; case Phonon::StoppedState: stopAction->setEnabled(false); playAction->setEnabled(true); pauseAction->setEnabled(false); timeLcd->display("00:00"); break; case Phonon::PausedState: pauseAction->setEnabled(false); stopAction->setEnabled(true); playAction->setEnabled(true); break; //![10] case Phonon::BufferingState: break; default: ; } } //![11] void MainWindow::tick(qint64 time) { QTime displayTime(0, (time / 60000) % 60, (time / 1000) % 60); timeLcd->display(displayTime.toString("mm:ss")); } //![11] //![12] void MainWindow::tableClicked(int row, int /* column */) { bool wasPlaying = mediaObject->state() == Phonon::PlayingState; mediaObject->stop(); mediaObject->clearQueue(); mediaObject->setCurrentSource(sources[row]); if (wasPlaying) mediaObject->play(); else mediaObject->stop(); } //![12] //![13] void MainWindow::sourceChanged(const Phonon::MediaSource &source) { musicTable->selectRow(sources.indexOf(source)); timeLcd->display("00:00"); } //![13] //![14] void MainWindow::metaStateChanged(Phonon::State newState, Phonon::State /* oldState */) { if (newState == Phonon::ErrorState) { QMessageBox::warning(this, tr("Error opening files"), metaInformationResolver->errorString()); while (!sources.isEmpty() && !(sources.takeLast() == metaInformationResolver->currentSource())); return; } if (newState != Phonon::StoppedState && newState != Phonon::PausedState) return; if (metaInformationResolver->currentSource().type() == Phonon::MediaSource::Invalid) return; QMap<QString, QString> metaData = metaInformationResolver->metaData(); QString title = metaData.value("TITLE"); if (title == "") title = metaInformationResolver->currentSource().fileName(); QTableWidgetItem *titleItem = new QTableWidgetItem(title); titleItem->setFlags(titleItem->flags() ^ Qt::ItemIsEditable); QTableWidgetItem *artistItem = new QTableWidgetItem(metaData.value("ARTIST")); artistItem->setFlags(artistItem->flags() ^ Qt::ItemIsEditable); QTableWidgetItem *albumItem = new QTableWidgetItem(metaData.value("ALBUM")); albumItem->setFlags(albumItem->flags() ^ Qt::ItemIsEditable); QTableWidgetItem *yearItem = new QTableWidgetItem(metaData.value("DATE")); yearItem->setFlags(yearItem->flags() ^ Qt::ItemIsEditable); //![14] int currentRow = musicTable->rowCount(); musicTable->insertRow(currentRow); musicTable->setItem(currentRow, 0, titleItem); musicTable->setItem(currentRow, 1, artistItem); musicTable->setItem(currentRow, 2, albumItem); musicTable->setItem(currentRow, 3, yearItem); //![15] if (musicTable->selectedItems().isEmpty()) { musicTable->selectRow(0); mediaObject->setCurrentSource(metaInformationResolver->currentSource()); } Phonon::MediaSource source = metaInformationResolver->currentSource(); int index = sources.indexOf(metaInformationResolver->currentSource()) + 1; if (sources.size() > index) { metaInformationResolver->setCurrentSource(sources.at(index)); } else { musicTable->resizeColumnsToContents(); if (musicTable->columnWidth(0) > 300) musicTable->setColumnWidth(0, 300); } } //![15] //![16] void MainWindow::aboutToFinish() { int index = sources.indexOf(mediaObject->currentSource()) + 1; if (sources.size() > index) { mediaObject->enqueue(sources.at(index)); } } //![16] void MainWindow::setupActions() { playAction = new QAction(style()->standardIcon(QStyle::SP_MediaPlay), tr("Play"), this); playAction->setShortcut(tr("Crl+P")); playAction->setDisabled(true); pauseAction = new QAction(style()->standardIcon(QStyle::SP_MediaPause), tr("Pause"), this); pauseAction->setShortcut(tr("Ctrl+A")); pauseAction->setDisabled(true); stopAction = new QAction(style()->standardIcon(QStyle::SP_MediaStop), tr("Stop"), this); stopAction->setShortcut(tr("Ctrl+S")); stopAction->setDisabled(true); nextAction = new QAction(style()->standardIcon(QStyle::SP_MediaSkipForward), tr("Next"), this); nextAction->setShortcut(tr("Ctrl+N")); previousAction = new QAction(style()->standardIcon(QStyle::SP_MediaSkipBackward), tr("Previous"), this); previousAction->setShortcut(tr("Ctrl+R")); addFilesAction = new QAction(tr("Add &Files"), this); addFilesAction->setShortcut(tr("Ctrl+F")); exitAction = new QAction(tr("E&xit"), this); exitAction->setShortcuts(QKeySequence::Quit); aboutAction = new QAction(tr("A&bout"), this); aboutAction->setShortcut(tr("Ctrl+B")); aboutQtAction = new QAction(tr("About &Qt"), this); aboutQtAction->setShortcut(tr("Ctrl+Q")); //![5] connect(playAction, SIGNAL(triggered()), mediaObject, SLOT(play())); connect(pauseAction, SIGNAL(triggered()), mediaObject, SLOT(pause()) ); connect(stopAction, SIGNAL(triggered()), mediaObject, SLOT(stop())); //![5] connect(addFilesAction, SIGNAL(triggered()), this, SLOT(addFiles())); connect(exitAction, SIGNAL(triggered()), this, SLOT(close())); connect(aboutAction, SIGNAL(triggered()), this, SLOT(about())); connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt())); } void MainWindow::setupMenus() { QMenu *fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(addFilesAction); fileMenu->addSeparator(); fileMenu->addAction(exitAction); QMenu *aboutMenu = menuBar()->addMenu(tr("&Help")); aboutMenu->addAction(aboutAction); aboutMenu->addAction(aboutQtAction); } //![3] void MainWindow::setupUi() { //![3] QToolBar *bar = new QToolBar; bar->addAction(playAction); bar->addAction(pauseAction); bar->addAction(stopAction); //![4] seekSlider = new Phonon::SeekSlider(this); seekSlider->setMediaObject(mediaObject); volumeSlider = new Phonon::VolumeSlider(this); volumeSlider->setAudioOutput(audioOutput); //![4] volumeSlider->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); QLabel *volumeLabel = new QLabel; volumeLabel->setPixmap(QPixmap("images/volume.png")); QPalette palette; palette.setBrush(QPalette::Light, Qt::darkGray); timeLcd = new QLCDNumber; timeLcd->setPalette(palette); QStringList headers; headers << tr("Title") << tr("Artist") << tr("Album") << tr("Year"); musicTable = new QTableWidget(0, 4); musicTable->setHorizontalHeaderLabels(headers); musicTable->setSelectionMode(QAbstractItemView::SingleSelection); musicTable->setSelectionBehavior(QAbstractItemView::SelectRows); connect(musicTable, SIGNAL(cellPressed(int, int)), this, SLOT(tableClicked(int, int))); QHBoxLayout *seekerLayout = new QHBoxLayout; seekerLayout->addWidget(seekSlider); seekerLayout->addWidget(timeLcd); QHBoxLayout *playbackLayout = new QHBoxLayout; playbackLayout->addWidget(bar); playbackLayout->addStretch(); playbackLayout->addWidget(volumeLabel); playbackLayout->addWidget(volumeSlider); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addWidget(musicTable); mainLayout->addLayout(seekerLayout); mainLayout->addLayout(playbackLayout); QWidget *widget = new QWidget; widget->setLayout(mainLayout); setCentralWidget(widget); setWindowTitle("Phonon Music Player"); } <commit_msg>unwarn<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://www.qtsoftware.com/contact. ** $QT_END_LICENSE$ ** ***************************************************************************/ #include <QtGui> #include "mainwindow.h" //![0] MainWindow::MainWindow() { audioOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this); mediaObject = new Phonon::MediaObject(this); metaInformationResolver = new Phonon::MediaObject(this); mediaObject->setTickInterval(1000); //![0] //![2] connect(mediaObject, SIGNAL(tick(qint64)), this, SLOT(tick(qint64))); connect(mediaObject, SIGNAL(stateChanged(Phonon::State, Phonon::State)), this, SLOT(stateChanged(Phonon::State, Phonon::State))); connect(metaInformationResolver, SIGNAL(stateChanged(Phonon::State,Phonon::State)), this, SLOT(metaStateChanged(Phonon::State, Phonon::State))); connect(mediaObject, SIGNAL(currentSourceChanged(const Phonon::MediaSource &)), this, SLOT(sourceChanged(const Phonon::MediaSource &))); connect(mediaObject, SIGNAL(aboutToFinish()), this, SLOT(aboutToFinish())); //![2] //![1] Phonon::createPath(mediaObject, audioOutput); //![1] setupActions(); setupMenus(); setupUi(); timeLcd->display("00:00"); } //![6] void MainWindow::addFiles() { QStringList files = QFileDialog::getOpenFileNames(this, tr("Select Music Files"), QDesktopServices::storageLocation(QDesktopServices::MusicLocation)); if (files.isEmpty()) return; int index = sources.size(); foreach (QString string, files) { Phonon::MediaSource source(string); sources.append(source); } if (!sources.isEmpty()) metaInformationResolver->setCurrentSource(sources.at(index)); } //![6] void MainWindow::about() { QMessageBox::information(this, tr("About Music Player"), tr("The Music Player example shows how to use Phonon - the multimedia" " framework that comes with Qt - to create a simple music player.")); } //![9] void MainWindow::stateChanged(Phonon::State newState, Phonon::State /* oldState */) { switch (newState) { case Phonon::ErrorState: if (mediaObject->errorType() == Phonon::FatalError) { QMessageBox::warning(this, tr("Fatal Error"), mediaObject->errorString()); } else { QMessageBox::warning(this, tr("Error"), mediaObject->errorString()); } break; //![9] //![10] case Phonon::PlayingState: playAction->setEnabled(false); pauseAction->setEnabled(true); stopAction->setEnabled(true); break; case Phonon::StoppedState: stopAction->setEnabled(false); playAction->setEnabled(true); pauseAction->setEnabled(false); timeLcd->display("00:00"); break; case Phonon::PausedState: pauseAction->setEnabled(false); stopAction->setEnabled(true); playAction->setEnabled(true); break; //![10] case Phonon::BufferingState: break; default: ; } } //![11] void MainWindow::tick(qint64 time) { QTime displayTime(0, (time / 60000) % 60, (time / 1000) % 60); timeLcd->display(displayTime.toString("mm:ss")); } //![11] //![12] void MainWindow::tableClicked(int row, int /* column */) { bool wasPlaying = mediaObject->state() == Phonon::PlayingState; mediaObject->stop(); mediaObject->clearQueue(); mediaObject->setCurrentSource(sources[row]); if (wasPlaying) mediaObject->play(); else mediaObject->stop(); } //![12] //![13] void MainWindow::sourceChanged(const Phonon::MediaSource &source) { musicTable->selectRow(sources.indexOf(source)); timeLcd->display("00:00"); } //![13] //![14] void MainWindow::metaStateChanged(Phonon::State newState, Phonon::State /* oldState */) { if (newState == Phonon::ErrorState) { QMessageBox::warning(this, tr("Error opening files"), metaInformationResolver->errorString()); while (!sources.isEmpty() && !(sources.takeLast() == metaInformationResolver->currentSource())) /* loop */; return; } if (newState != Phonon::StoppedState && newState != Phonon::PausedState) return; if (metaInformationResolver->currentSource().type() == Phonon::MediaSource::Invalid) return; QMap<QString, QString> metaData = metaInformationResolver->metaData(); QString title = metaData.value("TITLE"); if (title == "") title = metaInformationResolver->currentSource().fileName(); QTableWidgetItem *titleItem = new QTableWidgetItem(title); titleItem->setFlags(titleItem->flags() ^ Qt::ItemIsEditable); QTableWidgetItem *artistItem = new QTableWidgetItem(metaData.value("ARTIST")); artistItem->setFlags(artistItem->flags() ^ Qt::ItemIsEditable); QTableWidgetItem *albumItem = new QTableWidgetItem(metaData.value("ALBUM")); albumItem->setFlags(albumItem->flags() ^ Qt::ItemIsEditable); QTableWidgetItem *yearItem = new QTableWidgetItem(metaData.value("DATE")); yearItem->setFlags(yearItem->flags() ^ Qt::ItemIsEditable); //![14] int currentRow = musicTable->rowCount(); musicTable->insertRow(currentRow); musicTable->setItem(currentRow, 0, titleItem); musicTable->setItem(currentRow, 1, artistItem); musicTable->setItem(currentRow, 2, albumItem); musicTable->setItem(currentRow, 3, yearItem); //![15] if (musicTable->selectedItems().isEmpty()) { musicTable->selectRow(0); mediaObject->setCurrentSource(metaInformationResolver->currentSource()); } Phonon::MediaSource source = metaInformationResolver->currentSource(); int index = sources.indexOf(metaInformationResolver->currentSource()) + 1; if (sources.size() > index) { metaInformationResolver->setCurrentSource(sources.at(index)); } else { musicTable->resizeColumnsToContents(); if (musicTable->columnWidth(0) > 300) musicTable->setColumnWidth(0, 300); } } //![15] //![16] void MainWindow::aboutToFinish() { int index = sources.indexOf(mediaObject->currentSource()) + 1; if (sources.size() > index) { mediaObject->enqueue(sources.at(index)); } } //![16] void MainWindow::setupActions() { playAction = new QAction(style()->standardIcon(QStyle::SP_MediaPlay), tr("Play"), this); playAction->setShortcut(tr("Crl+P")); playAction->setDisabled(true); pauseAction = new QAction(style()->standardIcon(QStyle::SP_MediaPause), tr("Pause"), this); pauseAction->setShortcut(tr("Ctrl+A")); pauseAction->setDisabled(true); stopAction = new QAction(style()->standardIcon(QStyle::SP_MediaStop), tr("Stop"), this); stopAction->setShortcut(tr("Ctrl+S")); stopAction->setDisabled(true); nextAction = new QAction(style()->standardIcon(QStyle::SP_MediaSkipForward), tr("Next"), this); nextAction->setShortcut(tr("Ctrl+N")); previousAction = new QAction(style()->standardIcon(QStyle::SP_MediaSkipBackward), tr("Previous"), this); previousAction->setShortcut(tr("Ctrl+R")); addFilesAction = new QAction(tr("Add &Files"), this); addFilesAction->setShortcut(tr("Ctrl+F")); exitAction = new QAction(tr("E&xit"), this); exitAction->setShortcuts(QKeySequence::Quit); aboutAction = new QAction(tr("A&bout"), this); aboutAction->setShortcut(tr("Ctrl+B")); aboutQtAction = new QAction(tr("About &Qt"), this); aboutQtAction->setShortcut(tr("Ctrl+Q")); //![5] connect(playAction, SIGNAL(triggered()), mediaObject, SLOT(play())); connect(pauseAction, SIGNAL(triggered()), mediaObject, SLOT(pause()) ); connect(stopAction, SIGNAL(triggered()), mediaObject, SLOT(stop())); //![5] connect(addFilesAction, SIGNAL(triggered()), this, SLOT(addFiles())); connect(exitAction, SIGNAL(triggered()), this, SLOT(close())); connect(aboutAction, SIGNAL(triggered()), this, SLOT(about())); connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt())); } void MainWindow::setupMenus() { QMenu *fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(addFilesAction); fileMenu->addSeparator(); fileMenu->addAction(exitAction); QMenu *aboutMenu = menuBar()->addMenu(tr("&Help")); aboutMenu->addAction(aboutAction); aboutMenu->addAction(aboutQtAction); } //![3] void MainWindow::setupUi() { //![3] QToolBar *bar = new QToolBar; bar->addAction(playAction); bar->addAction(pauseAction); bar->addAction(stopAction); //![4] seekSlider = new Phonon::SeekSlider(this); seekSlider->setMediaObject(mediaObject); volumeSlider = new Phonon::VolumeSlider(this); volumeSlider->setAudioOutput(audioOutput); //![4] volumeSlider->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); QLabel *volumeLabel = new QLabel; volumeLabel->setPixmap(QPixmap("images/volume.png")); QPalette palette; palette.setBrush(QPalette::Light, Qt::darkGray); timeLcd = new QLCDNumber; timeLcd->setPalette(palette); QStringList headers; headers << tr("Title") << tr("Artist") << tr("Album") << tr("Year"); musicTable = new QTableWidget(0, 4); musicTable->setHorizontalHeaderLabels(headers); musicTable->setSelectionMode(QAbstractItemView::SingleSelection); musicTable->setSelectionBehavior(QAbstractItemView::SelectRows); connect(musicTable, SIGNAL(cellPressed(int, int)), this, SLOT(tableClicked(int, int))); QHBoxLayout *seekerLayout = new QHBoxLayout; seekerLayout->addWidget(seekSlider); seekerLayout->addWidget(timeLcd); QHBoxLayout *playbackLayout = new QHBoxLayout; playbackLayout->addWidget(bar); playbackLayout->addStretch(); playbackLayout->addWidget(volumeLabel); playbackLayout->addWidget(volumeSlider); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addWidget(musicTable); mainLayout->addLayout(seekerLayout); mainLayout->addLayout(playbackLayout); QWidget *widget = new QWidget; widget->setLayout(mainLayout); setCentralWidget(widget); setWindowTitle("Phonon Music Player"); } <|endoftext|>
<commit_before>// Copyright (c) 2010 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/dom_ui/dom_ui_favicon_source.h" #include "app/resource_bundle.h" #include "base/callback.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/profile.h" #include "chrome/common/url_constants.h" #include "grit/app_resources.h" DOMUIFavIconSource::DOMUIFavIconSource(Profile* profile) : DataSource(chrome::kChromeUIFavIconHost, MessageLoop::current()), profile_(profile) { } DOMUIFavIconSource::~DOMUIFavIconSource() { } void DOMUIFavIconSource::StartDataRequest(const std::string& path, bool is_off_the_record, int request_id) { FaviconService* favicon_service = profile_->GetFaviconService(Profile::EXPLICIT_ACCESS); if (favicon_service) { FaviconService::Handle handle; if (path.empty()) { SendDefaultResponse(request_id); return; } if (path.size() > 8 && path.substr(0, 8) == "iconurl/") { handle = favicon_service->GetFavicon( GURL(path.substr(8)), &cancelable_consumer_, NewCallback(this, &DOMUIFavIconSource::OnFavIconDataAvailable)); } else { handle = favicon_service->GetFaviconForURL( GURL(path), &cancelable_consumer_, NewCallback(this, &DOMUIFavIconSource::OnFavIconDataAvailable)); } // Attach the ChromeURLDataManager request ID to the history request. cancelable_consumer_.SetClientData(favicon_service, handle, request_id); } else { SendResponse(request_id, NULL); } } std::string DOMUIFavIconSource::GetMimeType(const std::string&) const { // We need to explicitly return a mime type, otherwise if the user tries to // drag the image they get no extension. return "image/png"; } void DOMUIFavIconSource::OnFavIconDataAvailable( FaviconService::Handle request_handle, bool know_favicon, scoped_refptr<RefCountedMemory> data, bool expired, GURL icon_url) { FaviconService* favicon_service = profile_->GetFaviconService(Profile::EXPLICIT_ACCESS); int request_id = cancelable_consumer_.GetClientData(favicon_service, request_handle); if (know_favicon && data.get() && data->size()) { // Forward the data along to the networking system. SendResponse(request_id, data); } else { SendDefaultResponse(request_id); } } void DOMUIFavIconSource::SendDefaultResponse(int request_id) { if (!default_favicon_.get()) { default_favicon_ = ResourceBundle::GetSharedInstance().LoadDataResourceBytes( IDR_DEFAULT_FAVICON); } SendResponse(request_id, default_favicon_); } <commit_msg>DOMUIFavIconSource should use original profile since the incognito profile might go away.<commit_after>// Copyright (c) 2010 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/dom_ui/dom_ui_favicon_source.h" #include "app/resource_bundle.h" #include "base/callback.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/profile.h" #include "chrome/common/url_constants.h" #include "grit/app_resources.h" DOMUIFavIconSource::DOMUIFavIconSource(Profile* profile) : DataSource(chrome::kChromeUIFavIconHost, MessageLoop::current()), profile_(profile->GetOriginalProfile()) { } DOMUIFavIconSource::~DOMUIFavIconSource() { } void DOMUIFavIconSource::StartDataRequest(const std::string& path, bool is_off_the_record, int request_id) { FaviconService* favicon_service = profile_->GetFaviconService(Profile::EXPLICIT_ACCESS); if (favicon_service) { FaviconService::Handle handle; if (path.empty()) { SendDefaultResponse(request_id); return; } if (path.size() > 8 && path.substr(0, 8) == "iconurl/") { handle = favicon_service->GetFavicon( GURL(path.substr(8)), &cancelable_consumer_, NewCallback(this, &DOMUIFavIconSource::OnFavIconDataAvailable)); } else { handle = favicon_service->GetFaviconForURL( GURL(path), &cancelable_consumer_, NewCallback(this, &DOMUIFavIconSource::OnFavIconDataAvailable)); } // Attach the ChromeURLDataManager request ID to the history request. cancelable_consumer_.SetClientData(favicon_service, handle, request_id); } else { SendResponse(request_id, NULL); } } std::string DOMUIFavIconSource::GetMimeType(const std::string&) const { // We need to explicitly return a mime type, otherwise if the user tries to // drag the image they get no extension. return "image/png"; } void DOMUIFavIconSource::OnFavIconDataAvailable( FaviconService::Handle request_handle, bool know_favicon, scoped_refptr<RefCountedMemory> data, bool expired, GURL icon_url) { FaviconService* favicon_service = profile_->GetFaviconService(Profile::EXPLICIT_ACCESS); int request_id = cancelable_consumer_.GetClientData(favicon_service, request_handle); if (know_favicon && data.get() && data->size()) { // Forward the data along to the networking system. SendResponse(request_id, data); } else { SendDefaultResponse(request_id); } } void DOMUIFavIconSource::SendDefaultResponse(int request_id) { if (!default_favicon_.get()) { default_favicon_ = ResourceBundle::GetSharedInstance().LoadDataResourceBytes( IDR_DEFAULT_FAVICON); } SendResponse(request_id, default_favicon_); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/constrained_html_ui.h" #include "base/lazy_instance.h" #include "base/values.h" #include "chrome/browser/ui/webui/html_dialog_ui.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/common/bindings_policy.h" static base::LazyInstance<PropertyAccessor<ConstrainedHtmlUIDelegate*> > g_constrained_html_ui_property_accessor(base::LINKER_INITIALIZED); ConstrainedHtmlUI::ConstrainedHtmlUI(TabContents* contents) : ChromeWebUI(contents) { } ConstrainedHtmlUI::~ConstrainedHtmlUI() { } void ConstrainedHtmlUI::RenderViewCreated( RenderViewHost* render_view_host) { ConstrainedHtmlUIDelegate* delegate = GetConstrainedDelegate(); if (!delegate) return; HtmlDialogUIDelegate* dialog_delegate = delegate->GetHtmlDialogUIDelegate(); std::vector<WebUIMessageHandler*> handlers; dialog_delegate->GetWebUIMessageHandlers(&handlers); render_view_host->SetWebUIProperty("dialogArguments", dialog_delegate->GetDialogArgs()); for (std::vector<WebUIMessageHandler*>::iterator it = handlers.begin(); it != handlers.end(); ++it) { (*it)->Attach(this); AddMessageHandler(*it); } // Add a "DialogClose" callback which matches HTMLDialogUI behavior. RegisterMessageCallback("DialogClose", NewCallback(this, &ConstrainedHtmlUI::OnDialogCloseMessage)); } void ConstrainedHtmlUI::OnDialogCloseMessage(const ListValue* args) { ConstrainedHtmlUIDelegate* delegate = GetConstrainedDelegate(); if (!delegate) return; std::string json_retval; if (!args->GetString(0, &json_retval)) NOTREACHED() << "Could not read JSON argument"; delegate->GetHtmlDialogUIDelegate()->OnDialogClosed(json_retval); delegate->OnDialogCloseFromWebUI(); } ConstrainedHtmlUIDelegate* ConstrainedHtmlUI::GetConstrainedDelegate() { ConstrainedHtmlUIDelegate** property = GetPropertyAccessor().GetProperty(tab_contents()->property_bag()); return property ? *property : NULL; } // static PropertyAccessor<ConstrainedHtmlUIDelegate*>& ConstrainedHtmlUI::GetPropertyAccessor() { return g_constrained_html_ui_property_accessor.Get(); } <commit_msg>Allow no arguments in ConstrainedHtmlUI::OnDialogClose().<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/constrained_html_ui.h" #include "base/lazy_instance.h" #include "base/values.h" #include "chrome/browser/ui/webui/html_dialog_ui.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/common/bindings_policy.h" static base::LazyInstance<PropertyAccessor<ConstrainedHtmlUIDelegate*> > g_constrained_html_ui_property_accessor(base::LINKER_INITIALIZED); ConstrainedHtmlUI::ConstrainedHtmlUI(TabContents* contents) : ChromeWebUI(contents) { } ConstrainedHtmlUI::~ConstrainedHtmlUI() { } void ConstrainedHtmlUI::RenderViewCreated( RenderViewHost* render_view_host) { ConstrainedHtmlUIDelegate* delegate = GetConstrainedDelegate(); if (!delegate) return; HtmlDialogUIDelegate* dialog_delegate = delegate->GetHtmlDialogUIDelegate(); std::vector<WebUIMessageHandler*> handlers; dialog_delegate->GetWebUIMessageHandlers(&handlers); render_view_host->SetWebUIProperty("dialogArguments", dialog_delegate->GetDialogArgs()); for (std::vector<WebUIMessageHandler*>::iterator it = handlers.begin(); it != handlers.end(); ++it) { (*it)->Attach(this); AddMessageHandler(*it); } // Add a "DialogClose" callback which matches HTMLDialogUI behavior. RegisterMessageCallback("DialogClose", NewCallback(this, &ConstrainedHtmlUI::OnDialogCloseMessage)); } void ConstrainedHtmlUI::OnDialogCloseMessage(const ListValue* args) { ConstrainedHtmlUIDelegate* delegate = GetConstrainedDelegate(); if (!delegate) return; std::string json_retval; if (!args->empty() && !args->GetString(0, &json_retval)) NOTREACHED() << "Could not read JSON argument"; delegate->GetHtmlDialogUIDelegate()->OnDialogClosed(json_retval); delegate->OnDialogCloseFromWebUI(); } ConstrainedHtmlUIDelegate* ConstrainedHtmlUI::GetConstrainedDelegate() { ConstrainedHtmlUIDelegate** property = GetPropertyAccessor().GetProperty(tab_contents()->property_bag()); return property ? *property : NULL; } // static PropertyAccessor<ConstrainedHtmlUIDelegate*>& ConstrainedHtmlUI::GetPropertyAccessor() { return g_constrained_html_ui_property_accessor.Get(); } <|endoftext|>
<commit_before>#include "calc.h" #include "sevensegment.h" #include "pocketcalculator.h" #include "cute.h" #include "ide_listener.h" #include "xml_listener.h" #include "cute_runner.h" #include <string> #include <sstream> #include <limits> #include <algorithm> namespace calc_tests { constexpr int max { std::numeric_limits<int>::max() }, min { std::numeric_limits<int>::min() }; void multiplies_positive_numbers() { ASSERT_EQUAL(20, calc(4, 5, '*')); } void multiplies_negative_with_positive_number() { ASSERT_EQUAL(-30, calc(-6, 5, '*')); } void multiplies_negative_numbers() { ASSERT_EQUAL(20, calc(-4, -5, '*')); } void recognizes_overflows_when_multiplying() { calc(1, max, '*'); calc(1, min, '*'); calc(-1, max, '*'); calc(-1, min+1, '*'); calc(2, max/2, '*'); calc(2, min/2, '*'); calc(-2, max/2, '*'); calc(-2, min/2+1, '*'); ASSERT_THROWS(calc(4, max/3, '*'), std::overflow_error); ASSERT_THROWS(calc(4, min/3, '*'), std::overflow_error); ASSERT_THROWS(calc(-4, max/3, '*'), std::overflow_error); ASSERT_THROWS(calc(-4, min/3, '*'), std::overflow_error); } void divides() { ASSERT_EQUAL(5, calc(60, 12, '/')); ASSERT_EQUAL(-3, calc(9, -3, '/')); } void throws_when_dividing_by_zero() { ASSERT_THROWS(calc(1, 0, '/'), std::domain_error); } void adds() { ASSERT_EQUAL(5, calc(2, 3, '+')); ASSERT_EQUAL(-10, calc(-6, -4, '+')); } void recognizes_overflows_when_adding() { calc(max, 0, '+'); // must not throw ASSERT_THROWS(calc(max, 1, '+'), std::overflow_error); calc(min, 0, '+'); // must not throw ASSERT_THROWS(calc(min, -1, '+'), std::overflow_error); } void subtracts() { ASSERT_EQUAL(17, calc(20, 3, '-')); ASSERT_EQUAL(-5, calc(-2, 3, '-')); } void recognizes_overflows_when_subtracting() { calc(max, 0, '-'); // must not throw ASSERT_THROWS(calc(max, -1, '-'), std::overflow_error); calc(min, 0, '-'); // must not throw ASSERT_THROWS(calc(min, 1, '-'), std::overflow_error); } void knows_modulo() { ASSERT_EQUAL(5, calc(15, 10, '%')); ASSERT_EQUAL(-5, calc(-15, 10, '%')); } void throws_when_modulo_zero() { ASSERT_THROWS(calc(10, 0, '%'), std::domain_error); } void throws_when_given_invalid_operator() { ASSERT_THROWS(calc(1, 1, '^'), std::runtime_error); } void takes_term_from_istream() { std::istringstream term_stream { "1+1" }; int result = calc(term_stream); ASSERT_EQUAL(2, result); } const std::vector<std::string> invalid_terms { "foobar", "3+2-", "1", "8--", "*", "4%%6", "3//7", }; void throws_when_given_invalid_term() { for(auto const term : invalid_terms) { std::istringstream term_stream { term }; ASSERT_THROWS(calc(term_stream), std::exception); // TODO: more specific? } } void add_tests_to_suite(cute::suite& s) { s.push_back(CUTE(multiplies_positive_numbers)); s.push_back(CUTE(multiplies_negative_with_positive_number)); s.push_back(CUTE(multiplies_negative_numbers)); s.push_back(CUTE(recognizes_overflows_when_multiplying)); s.push_back(CUTE(divides)); s.push_back(CUTE(throws_when_dividing_by_zero)); s.push_back(CUTE(adds)); s.push_back(CUTE(recognizes_overflows_when_adding)); s.push_back(CUTE(subtracts)); s.push_back(CUTE(recognizes_overflows_when_subtracting)); s.push_back(CUTE(throws_when_given_invalid_operator)); s.push_back(CUTE(knows_modulo)); s.push_back(CUTE(throws_when_modulo_zero)); s.push_back(CUTE(takes_term_from_istream)); s.push_back(CUTE(throws_when_given_invalid_term)); } } namespace sevensegment_tests { const std::string large_8 { " - \n" "| |\n" " - \n" "| |\n" " - \n" }; const std::string large_1 { " \n" " |\n" " \n" " |\n" " \n" }; const std::string large_3_scale2 { " -- \n" " |\n" " |\n" " -- \n" " |\n" " |\n" " -- \n" }; void prints_digit() { std::ostringstream output {}; sevensegment::printLargeDigit(8, output); ASSERT_EQUAL(large_8, output.str()); output.str(""); sevensegment::printLargeDigit(1, output); ASSERT_EQUAL(large_1, output.str()); } void prints_scaled_digit() { std::ostringstream output {}; sevensegment::printLargeDigit(3, output, 2); ASSERT_EQUAL(large_3_scale2, output.str()); } void throws_when_digit_out_of_range() { std::ostringstream output {}; ASSERT_THROWS(sevensegment::printLargeDigit(10,output), std::out_of_range); } void throws_when_scale_out_of_range() { std::ostringstream output {}; ASSERT_THROWS(sevensegment::printLargeDigit(5,output, 0), std::range_error); } const std::string large_number { " - - - \n" "| | | | | |\n" " - - - - \n" " | | || |\n" " - - - \n" }; const std::string large_negative_number { " - - \n" " | |\n" " - - - \n" " | |\n" " - - \n" }; void prints_number() { std::ostringstream output {}; sevensegment::printLargeNumber(54321, output); ASSERT_EQUAL(large_number, output.str()); } void prints_negative_number() { std::ostringstream output {}; sevensegment::printLargeNumber(-33, output); ASSERT_EQUAL(large_negative_number, output.str()); } const std::string large_error { " - \n" "| \n" " - - - - - \n" "| | | | || \n" " - - \n" }; void prints_error() { std::ostringstream output {}; sevensegment::printLargeError(output); ASSERT_EQUAL(large_error, output.str()); } void throws_when_too_many_digits_for_display() { std::ostringstream output {}; ASSERT_THROWS(sevensegment::printLargeNumber(100000000, output, 1), std::overflow_error); } void add_tests_to_suite(cute::suite& s) { s.push_back(CUTE(prints_digit)); s.push_back(CUTE(prints_scaled_digit)); s.push_back(CUTE(throws_when_digit_out_of_range)); s.push_back(CUTE(throws_when_scale_out_of_range)); s.push_back(CUTE(prints_number)); s.push_back(CUTE(prints_negative_number)); s.push_back(CUTE(prints_error)); s.push_back(CUTE(throws_when_too_many_digits_for_display)); } } namespace pocketcalculator_tests { const std::string large_output { " -- -- \n" " | |\n" " | |\n" " -- -- \n" "| | \n" "| | \n" " -- -- \n" }; bool includes(const std::string str, const std::string substr) { return (str.find(substr) != std::string::npos); } void gets_term_and_prints_result() { std::ostringstream output {}; std::istringstream input { "2+20" }; pocketcalculator::start(input, output); ASSERT(includes(output.str(), large_output)); } const std::string error_scale2 { " -- \n" "| \n" "| \n" " -- -- -- -- -- \n" "| | | | | | \n" "| | | | | | \n" " -- -- \n" }; void prints_error_on_invalid_input() { for(auto const term : calc_tests::invalid_terms) { std::ostringstream output {}; std::istringstream input { term }; pocketcalculator::start(input, output); ASSERT(includes(output.str(), error_scale2)); } } const std::string large_2_scale4 { " ---- \n" " |\n" " |\n" " |\n" " |\n" " ---- \n" "| \n" "| \n" "| \n" "| \n" " ---- \n" }; void scales() { std::ostringstream output {}; std::istringstream input {"1+1"}; pocketcalculator::start(input, output, 4); ASSERT(includes(output.str(), large_2_scale4)); } const std::string large_2_scale2 { " -- \n" " |\n" " |\n" " -- \n" "| \n" "| \n" " -- \n" }; void uses_default_scale_when_scale_omitted() { std::ostringstream output {}; std::istringstream input {"1+1"}; pocketcalculator::start(input, output); ASSERT(includes(output.str(), large_2_scale2)); } void add_tests_to_suite(cute::suite& s) { s.push_back(CUTE(gets_term_and_prints_result)); s.push_back(CUTE(prints_error_on_invalid_input)); s.push_back(CUTE(scales)); s.push_back(CUTE(uses_default_scale_when_scale_omitted)); } // TODO: add env scale test } void runAllTests(int argc, char const *argv[]){ cute::suite s {}; calc_tests::add_tests_to_suite(s); sevensegment_tests::add_tests_to_suite(s); pocketcalculator_tests::add_tests_to_suite(s); cute::xml_file_opener xmlfile(argc,argv); cute::xml_listener<cute::ide_listener<> > lis(xmlfile.out); cute::makeRunner(lis,argc,argv)(s, "AllTests"); } int main(int argc, char const *argv[]){ runAllTests(argc,argv); return 0; } <commit_msg>add TODO<commit_after>#include "calc.h" #include "sevensegment.h" #include "pocketcalculator.h" #include "cute.h" #include "ide_listener.h" #include "xml_listener.h" #include "cute_runner.h" #include <string> #include <sstream> #include <limits> #include <algorithm> namespace calc_tests { constexpr int max { std::numeric_limits<int>::max() }, min { std::numeric_limits<int>::min() }; void multiplies_positive_numbers() { ASSERT_EQUAL(20, calc(4, 5, '*')); } void multiplies_negative_with_positive_number() { ASSERT_EQUAL(-30, calc(-6, 5, '*')); } void multiplies_negative_numbers() { ASSERT_EQUAL(20, calc(-4, -5, '*')); } void recognizes_overflows_when_multiplying() { calc(1, max, '*'); calc(1, min, '*'); calc(-1, max, '*'); calc(-1, min+1, '*'); calc(2, max/2, '*'); calc(2, min/2, '*'); calc(-2, max/2, '*'); calc(-2, min/2+1, '*'); ASSERT_THROWS(calc(4, max/3, '*'), std::overflow_error); ASSERT_THROWS(calc(4, min/3, '*'), std::overflow_error); ASSERT_THROWS(calc(-4, max/3, '*'), std::overflow_error); ASSERT_THROWS(calc(-4, min/3, '*'), std::overflow_error); } void divides() { ASSERT_EQUAL(5, calc(60, 12, '/')); ASSERT_EQUAL(-3, calc(9, -3, '/')); } void throws_when_dividing_by_zero() { ASSERT_THROWS(calc(1, 0, '/'), std::domain_error); } void adds() { ASSERT_EQUAL(5, calc(2, 3, '+')); ASSERT_EQUAL(-10, calc(-6, -4, '+')); } void recognizes_overflows_when_adding() { calc(max, 0, '+'); // must not throw ASSERT_THROWS(calc(max, 1, '+'), std::overflow_error); calc(min, 0, '+'); // must not throw ASSERT_THROWS(calc(min, -1, '+'), std::overflow_error); } void subtracts() { ASSERT_EQUAL(17, calc(20, 3, '-')); ASSERT_EQUAL(-5, calc(-2, 3, '-')); } void recognizes_overflows_when_subtracting() { calc(max, 0, '-'); // must not throw ASSERT_THROWS(calc(max, -1, '-'), std::overflow_error); calc(min, 0, '-'); // must not throw ASSERT_THROWS(calc(min, 1, '-'), std::overflow_error); } void knows_modulo() { ASSERT_EQUAL(5, calc(15, 10, '%')); ASSERT_EQUAL(-5, calc(-15, 10, '%')); } void throws_when_modulo_zero() { ASSERT_THROWS(calc(10, 0, '%'), std::domain_error); } void throws_when_given_invalid_operator() { ASSERT_THROWS(calc(1, 1, '^'), std::runtime_error); } void takes_term_from_istream() { std::istringstream term_stream { "1+1" }; int result = calc(term_stream); ASSERT_EQUAL(2, result); } const std::vector<std::string> invalid_terms { "foobar", "3+2-", "1", "8--", "*", "4%%6", "3//7", }; void throws_when_given_invalid_term() { for(auto const term : invalid_terms) { std::istringstream term_stream { term }; ASSERT_THROWS(calc(term_stream), std::exception); // TODO: more specific? } } void add_tests_to_suite(cute::suite& s) { s.push_back(CUTE(multiplies_positive_numbers)); s.push_back(CUTE(multiplies_negative_with_positive_number)); s.push_back(CUTE(multiplies_negative_numbers)); s.push_back(CUTE(recognizes_overflows_when_multiplying)); s.push_back(CUTE(divides)); s.push_back(CUTE(throws_when_dividing_by_zero)); s.push_back(CUTE(adds)); s.push_back(CUTE(recognizes_overflows_when_adding)); s.push_back(CUTE(subtracts)); s.push_back(CUTE(recognizes_overflows_when_subtracting)); s.push_back(CUTE(throws_when_given_invalid_operator)); s.push_back(CUTE(knows_modulo)); s.push_back(CUTE(throws_when_modulo_zero)); s.push_back(CUTE(takes_term_from_istream)); s.push_back(CUTE(throws_when_given_invalid_term)); } } namespace sevensegment_tests { const std::string large_8 { " - \n" "| |\n" " - \n" "| |\n" " - \n" }; const std::string large_1 { " \n" " |\n" " \n" " |\n" " \n" }; const std::string large_3_scale2 { " -- \n" " |\n" " |\n" " -- \n" " |\n" " |\n" " -- \n" }; void prints_digit() { std::ostringstream output {}; sevensegment::printLargeDigit(8, output); ASSERT_EQUAL(large_8, output.str()); output.str(""); sevensegment::printLargeDigit(1, output); ASSERT_EQUAL(large_1, output.str()); } void prints_scaled_digit() { std::ostringstream output {}; sevensegment::printLargeDigit(3, output, 2); ASSERT_EQUAL(large_3_scale2, output.str()); } void throws_when_digit_out_of_range() { std::ostringstream output {}; ASSERT_THROWS(sevensegment::printLargeDigit(10,output), std::out_of_range); } void throws_when_scale_out_of_range() { std::ostringstream output {}; ASSERT_THROWS(sevensegment::printLargeDigit(5,output, 0), std::range_error); } const std::string large_number { " - - - \n" "| | | | | |\n" " - - - - \n" " | | || |\n" " - - - \n" }; const std::string large_negative_number { " - - \n" " | |\n" " - - - \n" " | |\n" " - - \n" }; void prints_number() { std::ostringstream output {}; sevensegment::printLargeNumber(54321, output); ASSERT_EQUAL(large_number, output.str()); } void prints_negative_number() { std::ostringstream output {}; sevensegment::printLargeNumber(-33, output); ASSERT_EQUAL(large_negative_number, output.str()); } const std::string large_error { " - \n" "| \n" " - - - - - \n" "| | | | || \n" " - - \n" }; void prints_error() { std::ostringstream output {}; sevensegment::printLargeError(output); ASSERT_EQUAL(large_error, output.str()); } void throws_when_too_many_digits_for_display() { std::ostringstream output {}; ASSERT_THROWS(sevensegment::printLargeNumber(100000000, output, 1), std::overflow_error); } void add_tests_to_suite(cute::suite& s) { s.push_back(CUTE(prints_digit)); s.push_back(CUTE(prints_scaled_digit)); s.push_back(CUTE(throws_when_digit_out_of_range)); s.push_back(CUTE(throws_when_scale_out_of_range)); s.push_back(CUTE(prints_number)); s.push_back(CUTE(prints_negative_number)); s.push_back(CUTE(prints_error)); s.push_back(CUTE(throws_when_too_many_digits_for_display)); } } namespace pocketcalculator_tests { const std::string large_output { " -- -- \n" " | |\n" " | |\n" " -- -- \n" "| | \n" "| | \n" " -- -- \n" }; // TODO: we don't have a prompt anymore. so maybe this functionality is obsolete anyway bool includes(const std::string str, const std::string substr) { return (str.find(substr) != std::string::npos); } void gets_term_and_prints_result() { std::ostringstream output {}; std::istringstream input { "2+20" }; pocketcalculator::start(input, output); ASSERT(includes(output.str(), large_output)); } const std::string error_scale2 { " -- \n" "| \n" "| \n" " -- -- -- -- -- \n" "| | | | | | \n" "| | | | | | \n" " -- -- \n" }; void prints_error_on_invalid_input() { for(auto const term : calc_tests::invalid_terms) { std::ostringstream output {}; std::istringstream input { term }; pocketcalculator::start(input, output); ASSERT(includes(output.str(), error_scale2)); } } const std::string large_2_scale4 { " ---- \n" " |\n" " |\n" " |\n" " |\n" " ---- \n" "| \n" "| \n" "| \n" "| \n" " ---- \n" }; void scales() { std::ostringstream output {}; std::istringstream input {"1+1"}; pocketcalculator::start(input, output, 4); ASSERT(includes(output.str(), large_2_scale4)); } const std::string large_2_scale2 { " -- \n" " |\n" " |\n" " -- \n" "| \n" "| \n" " -- \n" }; void uses_default_scale_when_scale_omitted() { std::ostringstream output {}; std::istringstream input {"1+1"}; pocketcalculator::start(input, output); ASSERT(includes(output.str(), large_2_scale2)); } void add_tests_to_suite(cute::suite& s) { s.push_back(CUTE(gets_term_and_prints_result)); s.push_back(CUTE(prints_error_on_invalid_input)); s.push_back(CUTE(scales)); s.push_back(CUTE(uses_default_scale_when_scale_omitted)); } // TODO: add env scale test } void runAllTests(int argc, char const *argv[]){ cute::suite s {}; calc_tests::add_tests_to_suite(s); sevensegment_tests::add_tests_to_suite(s); pocketcalculator_tests::add_tests_to_suite(s); cute::xml_file_opener xmlfile(argc,argv); cute::xml_listener<cute::ide_listener<> > lis(xmlfile.out); cute::makeRunner(lis,argc,argv)(s, "AllTests"); } int main(int argc, char const *argv[]){ runAllTests(argc,argv); return 0; } <|endoftext|>
<commit_before>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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/>. */ #include "module.hh" #include "agent.hh" #include "log/logmanager.hh" #include <sofia-sip/tport.h> #include <sofia-sip/msg_addr.h> #include <unordered_map> using namespace ::std; typedef struct DosContext { uint64_t recv_msg_count_since_last_check; double last_check_recv_msg_check_time; double packet_count_rate; } DosContext; class DoSProtection : public Module, ModuleToolbox { private: static ModuleInfo<DoSProtection> sInfo; int mTimePeriod; int mPacketRateLimit; int mBanTime; unordered_map<string, DosContext> mDosContexts; unordered_map<string, DosContext>::iterator mDOSHashtableIterator; void onDeclare(GenericStruct *module_config) { ConfigItemDescriptor configs[] = { {Integer, "time-period", "Number of milliseconds to consider to compute the packet rate", "3000"}, {Integer, "packet-rate-limit", "Maximum packet rate in packets/seconds, averaged over [time-period] " "millisecond(s) to consider it as a DoS attack.", "20"}, {Integer, "ban-time", "Number of minutes to ban the ip/port using iptables (might be less because it justs " "uses the minutes of the clock, not the seconds. So if the unban command is queued " "at 13:11:56 and scheduled and the ban time is 1 minute, it will be executed at " "13:12:00)", "2"}, config_item_end}; module_config->get<ConfigBoolean>("enabled")->setDefault("true"); module_config->addChildrenValues(configs); } void onLoad(const GenericStruct *mc) { mTimePeriod = mc->get<ConfigInt>("time-period")->read(); mPacketRateLimit = mc->get<ConfigInt>("packet-rate-limit")->read(); mBanTime = mc->get<ConfigInt>("ban-time")->read(); mDOSHashtableIterator = mDosContexts.begin(); tport_t *primaries = tport_primaries(nta_agent_tports(mAgent->getSofiaAgent())); if (primaries == NULL) LOGF("No sip transport defined."); for (tport_t *tport = primaries; tport != NULL; tport = tport_next(tport)) { tport_set_params(tport, TPTAG_DOS(mTimePeriod), TAG_END()); } if (getuid() != 0) { LOGE("Flexisip not started with root privileges! iptables commands for DoS protection won't work."); return; } } void onUnload() { } void onIdle() { struct timeval now; double started_time_in_millis, time_elapsed; gettimeofday(&now, NULL); started_time_in_millis = now.tv_sec * 1000 + (now.tv_usec / 1000); if (mDOSHashtableIterator == mDosContexts.end()) { mDOSHashtableIterator = mDosContexts.begin(); } for (; mDOSHashtableIterator != mDosContexts.end();) { double now_in_millis; DosContext dos = mDOSHashtableIterator->second; gettimeofday(&now, NULL); now_in_millis = now.tv_sec * 1000 + (now.tv_usec / 1000); time_elapsed = now_in_millis - dos.last_check_recv_msg_check_time; if (time_elapsed >= 3600 * 1000) { // If no message received in the past hour mDOSHashtableIterator = mDosContexts.erase(mDOSHashtableIterator); } else { ++mDOSHashtableIterator; } if (now_in_millis - started_time_in_millis >= 100) { // Do not use more than 100ms to clean the hashtable LOGW("Started to clean dos hashtable %fms ago, let's stop for now a continue later", now_in_millis - started_time_in_millis); break; } } } static void ban_ip_with_iptables(const char *ip, const char *port, const char *protocol, int ban_time) { char iptables_cmd[512]; snprintf(iptables_cmd, sizeof(iptables_cmd), "iptables -A INPUT -p %s -s %s -m multiport --sports %s -j DROP " "&& echo \"iptables -D INPUT -p %s -s %s -m multiport --sports %s " "-j DROP\" | at now +%i minutes", protocol, ip, port, protocol, ip, port, ban_time); if (system(iptables_cmd) != 0) { LOGW("iptables command failed: %s", strerror(errno)); } } void onRequest(shared_ptr<RequestSipEvent> &ev) { shared_ptr<tport_t> inTport = ev->getIncomingTport(); tport_t *tport = inTport.get(); if (tport == NULL) { LOGE("Tport is null, can't check the packet count rate"); return; } if (tport_is_udp(tport)) { // Sofia doesn't create a secondary tport for udp, so it will ban the primary and we // don't want that shared_ptr<MsgSip> msg = ev->getMsgSip(); MsgSip *msgSip = msg.get(); su_sockaddr_t su[1]; socklen_t len = sizeof su; sockaddr *addr = NULL; char ip[NI_MAXHOST], port[NI_MAXSERV]; int err; msg_get_address(msgSip->getMsg(), su, &len); addr = &(su[0].su_sa); if ((err = getnameinfo(addr, len, ip, sizeof(ip), port, sizeof(port), NI_NUMERICHOST | NI_NUMERICSERV)) == 0) { string id = string(ip) + ":" + string(port); struct timeval now; DosContext &dosContext = mDosContexts[id]; double now_in_millis, time_elapsed; dosContext.recv_msg_count_since_last_check++; gettimeofday(&now, NULL); now_in_millis = now.tv_sec * 1000 + (now.tv_usec / 1000); if (dosContext.last_check_recv_msg_check_time == 0) { dosContext.last_check_recv_msg_check_time = now_in_millis; } time_elapsed = now_in_millis - dosContext.last_check_recv_msg_check_time; if (time_elapsed < 0) { dosContext.packet_count_rate = 0; dosContext.recv_msg_count_since_last_check = 0; dosContext.last_check_recv_msg_check_time = now_in_millis; } else if (time_elapsed >= mTimePeriod) { dosContext.packet_count_rate = dosContext.recv_msg_count_since_last_check / time_elapsed * 1000; dosContext.recv_msg_count_since_last_check = 0; dosContext.last_check_recv_msg_check_time = now_in_millis; } if (dosContext.packet_count_rate >= mPacketRateLimit) { LOGW("Packet count rate (%f) >= limit (%i), blocking ip/port %s/%s on protocol udp for %i minutes", dosContext.packet_count_rate, mPacketRateLimit, ip, port, mBanTime); ban_ip_with_iptables(ip, port, "udp", mBanTime); dosContext.packet_count_rate = 0; // Reset it to not add the iptables rule twice by mistake ev->terminateProcessing(); // the event is discarded } } else { LOGW("getnameinfo() failed: %s", gai_strerror(err)); } } else { float packet_count_rate = tport_get_packet_count_rate(tport); if (packet_count_rate >= mPacketRateLimit) { sockaddr *addr = tport_get_address(tport)->ai_addr; socklen_t len = tport_get_address(tport)->ai_addrlen; char ip[NI_MAXHOST], port[NI_MAXSERV]; int err; if ((err = getnameinfo(addr, len, ip, sizeof(ip), port, sizeof(port), NI_NUMERICHOST | NI_NUMERICSERV)) == 0) { LOGW("Packet count rate (%f) >= limit (%i), blocking ip/port %s/%s on protocol tcp for %i minutes", packet_count_rate, mPacketRateLimit, ip, port, mBanTime); ban_ip_with_iptables(ip, port, "tcp", mBanTime); tport_reset_packet_count_rate(tport); // Reset it to not add the iptables rule twice by mistake ev->terminateProcessing(); // the event is discarded } else { LOGW("getnameinfo() failed: %s", gai_strerror(err)); } } } } void onResponse(std::shared_ptr<ResponseSipEvent> &ev){ }; public: DoSProtection(Agent *ag) : Module(ag) { } ~DoSProtection() { } }; ModuleInfo<DoSProtection> DoSProtection::sInfo("DoSProtection", "This module bans user when they are sending too much packets on a given timelapse" "To see the list of currently banned ips/ports, use iptables -L" "You can also check the queue of unban commands using atq", ModuleInfoBase::ModuleOid::DoSProtection); <commit_msg>Fix PR 2837<commit_after>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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/>. */ #include "module.hh" #include "agent.hh" #include "log/logmanager.hh" #include <sofia-sip/tport.h> #include <sofia-sip/msg_addr.h> #include <unordered_map> using namespace ::std; typedef struct DosContext { uint64_t recv_msg_count_since_last_check; double last_check_recv_msg_check_time; double packet_count_rate; } DosContext; class DoSProtection : public Module, ModuleToolbox { private: static ModuleInfo<DoSProtection> sInfo; int mTimePeriod; int mPacketRateLimit; int mBanTime; unordered_map<string, DosContext> mDosContexts; unordered_map<string, DosContext>::iterator mDOSHashtableIterator; void onDeclare(GenericStruct *module_config) { ConfigItemDescriptor configs[] = { {Integer, "time-period", "Number of milliseconds to consider to compute the packet rate", "3000"}, {Integer, "packet-rate-limit", "Maximum packet rate in packets/seconds, averaged over [time-period] " "millisecond(s) to consider it as a DoS attack.", "20"}, {Integer, "ban-time", "Number of minutes to ban the ip/port using iptables (might be less because it justs " "uses the minutes of the clock, not the seconds. So if the unban command is queued " "at 13:11:56 and scheduled and the ban time is 1 minute, it will be executed at " "13:12:00)", "2"}, config_item_end}; module_config->get<ConfigBoolean>("enabled")->setDefault("true"); module_config->addChildrenValues(configs); } void onLoad(const GenericStruct *mc) { mTimePeriod = mc->get<ConfigInt>("time-period")->read(); mPacketRateLimit = mc->get<ConfigInt>("packet-rate-limit")->read(); mBanTime = mc->get<ConfigInt>("ban-time")->read(); mDOSHashtableIterator = mDosContexts.begin(); tport_t *primaries = tport_primaries(nta_agent_tports(mAgent->getSofiaAgent())); if (primaries == NULL) LOGF("No sip transport defined."); for (tport_t *tport = primaries; tport != NULL; tport = tport_next(tport)) { tport_set_params(tport, TPTAG_DOS(mTimePeriod), TAG_END()); } if (getuid() != 0) { LOGE("Flexisip not started with root privileges! iptables commands for DoS protection won't work."); return; } } void onUnload() { } virtual bool isValidNextConfig( const ConfigValue &value ) { GenericStruct *module_config = dynamic_cast<GenericStruct *>(value.getParent()); if (!module_config->get<ConfigBoolean>("enabled")->readNext()) return true; else { #if __APPLE__ LOGEN("DosProtection only works on linux hosts. Please disable this module."); return false; #else int at_command = system("which at"); if( WIFEXITED(at_command) && WEXITSTATUS(at_command) == 0 ) { // at command was found, we can be sure that iptables rules will be cleaned up after the required time return true; } else { LOGEN("Couldn't find the commant 'at' in your PATH. DosProtection needs it to be used correctly. Please fix this or disable DosProtection."); return false; } #endif } } void onIdle() { struct timeval now; double started_time_in_millis, time_elapsed; gettimeofday(&now, NULL); started_time_in_millis = now.tv_sec * 1000 + (now.tv_usec / 1000); if (mDOSHashtableIterator == mDosContexts.end()) { mDOSHashtableIterator = mDosContexts.begin(); } for (; mDOSHashtableIterator != mDosContexts.end();) { double now_in_millis; DosContext dos = mDOSHashtableIterator->second; gettimeofday(&now, NULL); now_in_millis = now.tv_sec * 1000 + (now.tv_usec / 1000); time_elapsed = now_in_millis - dos.last_check_recv_msg_check_time; if (time_elapsed >= 3600 * 1000) { // If no message received in the past hour mDOSHashtableIterator = mDosContexts.erase(mDOSHashtableIterator); } else { ++mDOSHashtableIterator; } if (now_in_millis - started_time_in_millis >= 100) { // Do not use more than 100ms to clean the hashtable LOGW("Started to clean dos hashtable %fms ago, let's stop for now a continue later", now_in_millis - started_time_in_millis); break; } } } static void ban_ip_with_iptables(const char *ip, const char *port, const char *protocol, int ban_time) { char iptables_cmd[512]; snprintf(iptables_cmd, sizeof(iptables_cmd), "iptables -A INPUT -p %s -s %s -m multiport --sports %s -j DROP " "&& echo \"iptables -D INPUT -p %s -s %s -m multiport --sports %s " "-j DROP\" | at now +%i minutes", protocol, ip, port, protocol, ip, port, ban_time); if (system(iptables_cmd) != 0) { LOGW("iptables command failed: %s", strerror(errno)); } } void onRequest(shared_ptr<RequestSipEvent> &ev) { shared_ptr<tport_t> inTport = ev->getIncomingTport(); tport_t *tport = inTport.get(); if (tport == NULL) { LOGE("Tport is null, can't check the packet count rate"); return; } if (tport_is_udp(tport)) { // Sofia doesn't create a secondary tport for udp, so it will ban the primary and we // don't want that shared_ptr<MsgSip> msg = ev->getMsgSip(); MsgSip *msgSip = msg.get(); su_sockaddr_t su[1]; socklen_t len = sizeof su; sockaddr *addr = NULL; char ip[NI_MAXHOST], port[NI_MAXSERV]; int err; msg_get_address(msgSip->getMsg(), su, &len); addr = &(su[0].su_sa); if ((err = getnameinfo(addr, len, ip, sizeof(ip), port, sizeof(port), NI_NUMERICHOST | NI_NUMERICSERV)) == 0) { string id = string(ip) + ":" + string(port); struct timeval now; DosContext &dosContext = mDosContexts[id]; double now_in_millis, time_elapsed; dosContext.recv_msg_count_since_last_check++; gettimeofday(&now, NULL); now_in_millis = now.tv_sec * 1000 + (now.tv_usec / 1000); if (dosContext.last_check_recv_msg_check_time == 0) { dosContext.last_check_recv_msg_check_time = now_in_millis; } time_elapsed = now_in_millis - dosContext.last_check_recv_msg_check_time; if (time_elapsed < 0) { dosContext.packet_count_rate = 0; dosContext.recv_msg_count_since_last_check = 0; dosContext.last_check_recv_msg_check_time = now_in_millis; } else if (time_elapsed >= mTimePeriod) { dosContext.packet_count_rate = dosContext.recv_msg_count_since_last_check / time_elapsed * 1000; dosContext.recv_msg_count_since_last_check = 0; dosContext.last_check_recv_msg_check_time = now_in_millis; } if (dosContext.packet_count_rate >= mPacketRateLimit) { LOGW("Packet count rate (%f) >= limit (%i), blocking ip/port %s/%s on protocol udp for %i minutes", dosContext.packet_count_rate, mPacketRateLimit, ip, port, mBanTime); ban_ip_with_iptables(ip, port, "udp", mBanTime); dosContext.packet_count_rate = 0; // Reset it to not add the iptables rule twice by mistake ev->terminateProcessing(); // the event is discarded } } else { LOGW("getnameinfo() failed: %s", gai_strerror(err)); } } else { float packet_count_rate = tport_get_packet_count_rate(tport); if (packet_count_rate >= mPacketRateLimit) { sockaddr *addr = tport_get_address(tport)->ai_addr; socklen_t len = tport_get_address(tport)->ai_addrlen; char ip[NI_MAXHOST], port[NI_MAXSERV]; int err; if ((err = getnameinfo(addr, len, ip, sizeof(ip), port, sizeof(port), NI_NUMERICHOST | NI_NUMERICSERV)) == 0) { LOGW("Packet count rate (%f) >= limit (%i), blocking ip/port %s/%s on protocol tcp for %i minutes", packet_count_rate, mPacketRateLimit, ip, port, mBanTime); ban_ip_with_iptables(ip, port, "tcp", mBanTime); tport_reset_packet_count_rate(tport); // Reset it to not add the iptables rule twice by mistake ev->terminateProcessing(); // the event is discarded } else { LOGW("getnameinfo() failed: %s", gai_strerror(err)); } } } } void onResponse(std::shared_ptr<ResponseSipEvent> &ev){ }; public: DoSProtection(Agent *ag) : Module(ag) { } ~DoSProtection() { } }; ModuleInfo<DoSProtection> DoSProtection::sInfo("DoSProtection", "This module bans user when they are sending too much packets on a given timelapse" "To see the list of currently banned ips/ports, use iptables -L" "You can also check the queue of unban commands using atq", ModuleInfoBase::ModuleOid::DoSProtection); <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: bibcont.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:13:23 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef ADDRCONT_HXX #define ADDRCONT_HXX #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _SV_SPLITWIN_HXX #include <vcl/splitwin.hxx> #endif #ifndef _SV_TIMER_HXX //autogen wg. Timer #include <vcl/timer.hxx> #endif #ifndef _BIBSHORTCUTHANDLER_HXX #include "bibshortcuthandler.hxx" #endif #include "bibmod.hxx" #define TOP_WINDOW 1 #define BOTTOM_WINDOW 2 class BibDataManager; class BibWindowContainer : public BibWindow //Window { private: // !BibShortCutHandler is also always a Window! BibShortCutHandler* pChild; protected: virtual void Resize(); public: BibWindowContainer( Window* pParent, WinBits nStyle = WB_3DLOOK ); BibWindowContainer( Window* pParent, BibShortCutHandler* pChild, WinBits nStyle = WB_3DLOOK); ~BibWindowContainer(); inline Window* GetChild(); virtual void GetFocus(); virtual BOOL HandleShortCutKey( const KeyEvent& rKeyEvent ); // returns true, if key was handled }; inline Window* BibWindowContainer::GetChild() { return pChild? pChild->GetWindow() : NULL; } class BibBookContainer: public BibSplitWindow { private: ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xTopFrameRef; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xBottomFrameRef; ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > xTopPeerRef; ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > xBottomPeerRef; sal_Bool bFirstTime; BibWindowContainer* pTopWin; BibWindowContainer* pBottomWin; BibDataManager* pDatMan; HdlBibModul pBibMod; Timer aTimer; DECL_LINK( SplitHdl, Timer*); protected: virtual void Split(); virtual long PreNotify( NotifyEvent& rNEvt ); ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > GetTopComponentInterface( sal_Bool bCreate = sal_True ); void SetTopComponentInterface( ::com::sun::star::awt::XWindowPeer* pIFace ); ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > GetBottomComponentInterface( sal_Bool bCreate = sal_True ); void SetBottomComponentInterface( ::com::sun::star::awt::XWindowPeer* pIFace ); public: BibBookContainer(Window* pParent,BibDataManager*, WinBits nStyle = WB_3DLOOK ); ~BibBookContainer(); inline BibWindow* GetTopWin() {return pTopWin;} inline BibWindow* GetBottomWin() {return pBottomWin;} // !BibShortCutHandler is also always a Window! void createTopFrame( BibShortCutHandler* pWin ); void createBottomFrame( BibShortCutHandler* pWin ); virtual void GetFocus(); virtual sal_Bool HandleShortCutKey( const KeyEvent& rKeyEvent ); // returns true, if key was handled }; #endif <commit_msg>INTEGRATION: CWS wae4extensions (1.7.388); FILE MERGED 2007/09/27 07:18:22 fs 1.7.388.1: #i81612# warning-free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: bibcont.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: ihi $ $Date: 2008-01-14 14:38:07 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef ADDRCONT_HXX #define ADDRCONT_HXX #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _SV_SPLITWIN_HXX #include <vcl/splitwin.hxx> #endif #ifndef _SV_TIMER_HXX //autogen wg. Timer #include <vcl/timer.hxx> #endif #ifndef _BIBSHORTCUTHANDLER_HXX #include "bibshortcuthandler.hxx" #endif #include "bibmod.hxx" #define TOP_WINDOW 1 #define BOTTOM_WINDOW 2 class BibDataManager; class BibWindowContainer : public BibWindow //Window { private: // !BibShortCutHandler is also always a Window! BibShortCutHandler* pChild; protected: virtual void Resize(); public: BibWindowContainer( Window* pParent, WinBits nStyle = WB_3DLOOK ); BibWindowContainer( Window* pParent, BibShortCutHandler* pChild, WinBits nStyle = WB_3DLOOK); ~BibWindowContainer(); inline Window* GetChild(); virtual void GetFocus(); virtual BOOL HandleShortCutKey( const KeyEvent& rKeyEvent ); // returns true, if key was handled using Window::GetChild; }; inline Window* BibWindowContainer::GetChild() { return pChild? pChild->GetWindow() : NULL; } class BibBookContainer: public BibSplitWindow { private: ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xTopFrameRef; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xBottomFrameRef; ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > xTopPeerRef; ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > xBottomPeerRef; BibDataManager* pDatMan; BibWindowContainer* pTopWin; BibWindowContainer* pBottomWin; sal_Bool bFirstTime; HdlBibModul pBibMod; Timer aTimer; DECL_LINK( SplitHdl, Timer*); protected: virtual void Split(); virtual long PreNotify( NotifyEvent& rNEvt ); ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > GetTopComponentInterface( sal_Bool bCreate = sal_True ); void SetTopComponentInterface( ::com::sun::star::awt::XWindowPeer* pIFace ); ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > GetBottomComponentInterface( sal_Bool bCreate = sal_True ); void SetBottomComponentInterface( ::com::sun::star::awt::XWindowPeer* pIFace ); public: BibBookContainer(Window* pParent,BibDataManager*, WinBits nStyle = WB_3DLOOK ); ~BibBookContainer(); inline BibWindow* GetTopWin() {return pTopWin;} inline BibWindow* GetBottomWin() {return pBottomWin;} // !BibShortCutHandler is also always a Window! void createTopFrame( BibShortCutHandler* pWin ); void createBottomFrame( BibShortCutHandler* pWin ); virtual void GetFocus(); virtual sal_Bool HandleShortCutKey( const KeyEvent& rKeyEvent ); // returns true, if key was handled }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: groupboxwiz.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:30:50 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _EXTENSIONS_DBP_GROUPBOXWIZ_HXX_ #define _EXTENSIONS_DBP_GROUPBOXWIZ_HXX_ #ifndef _EXTENSIONS_DBP_CONTROLWIZARD_HXX #include "controlwizard.hxx" #endif #ifndef _EXTENSIONS_DBP_COMMONPAGESDBP_HXX_ #include "commonpagesdbp.hxx" #endif //......................................................................... namespace dbp { //......................................................................... //===================================================================== //= OOptionGroupSettings //===================================================================== struct OOptionGroupSettings : public OControlWizardSettings { StringArray aLabels; StringArray aValues; String sDefaultField; String sDBField; String sName; }; //===================================================================== //= OGroupBoxWizard //===================================================================== class OGroupBoxWizard : public OControlWizard { protected: OOptionGroupSettings m_aSettings; sal_Bool m_bVisitedDefault : 1; sal_Bool m_bVisitedDB : 1; public: OGroupBoxWizard( Window* _pParent, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxObjectModel, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB ); OOptionGroupSettings& getSettings() { return m_aSettings; } protected: // OWizardMachine overridables virtual ::svt::OWizardPage* createPage( WizardState _nState ); virtual WizardState determineNextState( WizardState _nCurrentState ); virtual void enterState( WizardState _nState ); virtual sal_Bool onFinish(sal_Int32 _nResult); virtual sal_Bool approveControl(sal_Int16 _nClassId); protected: void createRadios(); }; //===================================================================== //= OGBWPage //===================================================================== class OGBWPage : public OControlWizardPage { public: OGBWPage( OControlWizard* _pParent, const ResId& _rId ) : OControlWizardPage(_pParent, _rId) { } protected: OOptionGroupSettings& getSettings() { return static_cast<OGroupBoxWizard*>(getDialog())->getSettings(); } }; //===================================================================== //= ORadioSelectionPage //===================================================================== class ORadioSelectionPage : public OGBWPage { protected: FixedLine m_aFrame; FixedText m_aRadioNameLabel; Edit m_aRadioName; PushButton m_aMoveRight; PushButton m_aMoveLeft; FixedText m_aExistingRadiosLabel; ListBox m_aExistingRadios; public: ORadioSelectionPage( OControlWizard* _pParent ); protected: // TabPage overridables void ActivatePage(); // OWizardPage overridables virtual void initializePage(); virtual sal_Bool commitPage(COMMIT_REASON _eReason); virtual sal_Bool determineNextButtonState(); DECL_LINK( OnMoveEntry, PushButton* ); DECL_LINK( OnEntrySelected, ListBox* ); DECL_LINK( OnNameModified, Edit* ); void implCheckMoveButtons(); }; //===================================================================== //= ODefaultFieldSelectionPage //===================================================================== class ODefaultFieldSelectionPage : public OMaybeListSelectionPage { protected: FixedLine m_aFrame; FixedText m_aDefaultSelectionLabel; RadioButton m_aDefSelYes; RadioButton m_aDefSelNo; ListBox m_aDefSelection; public: ODefaultFieldSelectionPage( OControlWizard* _pParent ); protected: // OWizardPage overridables virtual void initializePage(); virtual sal_Bool commitPage(COMMIT_REASON _eReason); OOptionGroupSettings& getSettings() { return static_cast<OGroupBoxWizard*>(getDialog())->getSettings(); } }; //===================================================================== //= OOptionValuesPage //===================================================================== class OOptionValuesPage : public OGBWPage { protected: FixedLine m_aFrame; FixedText m_aDescription; FixedText m_aValueLabel; Edit m_aValue; FixedText m_aOptionsLabel; ListBox m_aOptions; StringArray m_aUncommittedValues; WizardState m_nLastSelection; public: OOptionValuesPage( OControlWizard* _pParent ); protected: // TabPage overridables void ActivatePage(); // OWizardPage overridables virtual void initializePage(); virtual sal_Bool commitPage(COMMIT_REASON _eReason); void implTraveledOptions(); DECL_LINK( OnOptionSelected, ListBox* ); }; //===================================================================== //= OOptionDBFieldPage //===================================================================== class OOptionDBFieldPage : public ODBFieldPage { public: OOptionDBFieldPage( OControlWizard* _pParent ); protected: OOptionGroupSettings& getSettings() { return static_cast<OGroupBoxWizard*>(getDialog())->getSettings(); } // ODBFieldPage overridables virtual String& getDBFieldSetting(); }; //===================================================================== //= OFinalizeGBWPage //===================================================================== class OFinalizeGBWPage : public OGBWPage { protected: FixedLine m_aFrame; FixedText m_aNameLabel; Edit m_aName; FixedText m_aThatsAll; public: OFinalizeGBWPage( OControlWizard* _pParent ); protected: // TabPage overridables void ActivatePage(); // OWizardPage overridables virtual void initializePage(); virtual sal_Bool commitPage(COMMIT_REASON _eReason); virtual sal_Bool determineNextButtonState(); }; //......................................................................... } // namespace dbp //......................................................................... #endif // _EXTENSIONS_DBP_GROUPBOXWIZ_HXX_ <commit_msg>INTEGRATION: CWS odbmacros2 (1.8.424); FILE MERGED 2008/02/11 11:14:56 fs 1.8.424.3: IWizardPage is COMMIT_REASON is deprecated - replace usages with CommitPageReason, while I have an svtools-incompatible CWS 2008/01/30 13:19:50 fs 1.8.424.2: canAdvance made const 2008/01/15 09:52:42 fs 1.8.424.1: some re-factoring of OWizardMachine, RoadmapWizard and derived classes, to prepare the migration UI for #i49133#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: groupboxwiz.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: kz $ $Date: 2008-03-06 18:41:35 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _EXTENSIONS_DBP_GROUPBOXWIZ_HXX_ #define _EXTENSIONS_DBP_GROUPBOXWIZ_HXX_ #ifndef _EXTENSIONS_DBP_CONTROLWIZARD_HXX #include "controlwizard.hxx" #endif #ifndef _EXTENSIONS_DBP_COMMONPAGESDBP_HXX_ #include "commonpagesdbp.hxx" #endif //......................................................................... namespace dbp { //......................................................................... //===================================================================== //= OOptionGroupSettings //===================================================================== struct OOptionGroupSettings : public OControlWizardSettings { StringArray aLabels; StringArray aValues; String sDefaultField; String sDBField; String sName; }; //===================================================================== //= OGroupBoxWizard //===================================================================== class OGroupBoxWizard : public OControlWizard { protected: OOptionGroupSettings m_aSettings; sal_Bool m_bVisitedDefault : 1; sal_Bool m_bVisitedDB : 1; public: OGroupBoxWizard( Window* _pParent, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxObjectModel, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB ); OOptionGroupSettings& getSettings() { return m_aSettings; } protected: // OWizardMachine overridables virtual ::svt::OWizardPage* createPage( WizardState _nState ); virtual WizardState determineNextState( WizardState _nCurrentState ) const; virtual void enterState( WizardState _nState ); virtual sal_Bool onFinish(sal_Int32 _nResult); virtual sal_Bool approveControl(sal_Int16 _nClassId); protected: void createRadios(); }; //===================================================================== //= OGBWPage //===================================================================== class OGBWPage : public OControlWizardPage { public: OGBWPage( OControlWizard* _pParent, const ResId& _rId ) : OControlWizardPage(_pParent, _rId) { } protected: OOptionGroupSettings& getSettings() { return static_cast<OGroupBoxWizard*>(getDialog())->getSettings(); } }; //===================================================================== //= ORadioSelectionPage //===================================================================== class ORadioSelectionPage : public OGBWPage { protected: FixedLine m_aFrame; FixedText m_aRadioNameLabel; Edit m_aRadioName; PushButton m_aMoveRight; PushButton m_aMoveLeft; FixedText m_aExistingRadiosLabel; ListBox m_aExistingRadios; public: ORadioSelectionPage( OControlWizard* _pParent ); protected: // TabPage overridables void ActivatePage(); // OWizardPage overridables virtual void initializePage(); virtual sal_Bool commitPage( CommitPageReason _eReason ); virtual bool canAdvance() const; DECL_LINK( OnMoveEntry, PushButton* ); DECL_LINK( OnEntrySelected, ListBox* ); DECL_LINK( OnNameModified, Edit* ); void implCheckMoveButtons(); }; //===================================================================== //= ODefaultFieldSelectionPage //===================================================================== class ODefaultFieldSelectionPage : public OMaybeListSelectionPage { protected: FixedLine m_aFrame; FixedText m_aDefaultSelectionLabel; RadioButton m_aDefSelYes; RadioButton m_aDefSelNo; ListBox m_aDefSelection; public: ODefaultFieldSelectionPage( OControlWizard* _pParent ); protected: // OWizardPage overridables virtual void initializePage(); virtual sal_Bool commitPage( CommitPageReason _eReason ); OOptionGroupSettings& getSettings() { return static_cast<OGroupBoxWizard*>(getDialog())->getSettings(); } }; //===================================================================== //= OOptionValuesPage //===================================================================== class OOptionValuesPage : public OGBWPage { protected: FixedLine m_aFrame; FixedText m_aDescription; FixedText m_aValueLabel; Edit m_aValue; FixedText m_aOptionsLabel; ListBox m_aOptions; StringArray m_aUncommittedValues; WizardState m_nLastSelection; public: OOptionValuesPage( OControlWizard* _pParent ); protected: // TabPage overridables void ActivatePage(); // OWizardPage overridables virtual void initializePage(); virtual sal_Bool commitPage( CommitPageReason _eReason ); void implTraveledOptions(); DECL_LINK( OnOptionSelected, ListBox* ); }; //===================================================================== //= OOptionDBFieldPage //===================================================================== class OOptionDBFieldPage : public ODBFieldPage { public: OOptionDBFieldPage( OControlWizard* _pParent ); protected: OOptionGroupSettings& getSettings() { return static_cast<OGroupBoxWizard*>(getDialog())->getSettings(); } // ODBFieldPage overridables virtual String& getDBFieldSetting(); }; //===================================================================== //= OFinalizeGBWPage //===================================================================== class OFinalizeGBWPage : public OGBWPage { protected: FixedLine m_aFrame; FixedText m_aNameLabel; Edit m_aName; FixedText m_aThatsAll; public: OFinalizeGBWPage( OControlWizard* _pParent ); protected: // TabPage overridables void ActivatePage(); // OWizardPage overridables virtual void initializePage(); virtual sal_Bool commitPage( CommitPageReason _eReason ); virtual bool canAdvance() const; }; //......................................................................... } // namespace dbp //......................................................................... #endif // _EXTENSIONS_DBP_GROUPBOXWIZ_HXX_ <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <[email protected]> //------------------------------------------------------------------------------ #include <cling/UserInterface/UserInterface.h> #include <cling/MetaProcessor/MetaProcessor.h> #include "textinput/TextInput.h" #include "textinput/StreamReader.h" #include "textinput/TerminalDisplay.h" #include "llvm/Support/raw_ostream.h" //--------------------------------------------------------------------------- // Construct an interface for an interpreter //--------------------------------------------------------------------------- cling::UserInterface::UserInterface(Interpreter& interp, const char* prompt /*= "[cling] $"*/): m_MetaProcessor(new MetaProcessor(interp)) { } //--------------------------------------------------------------------------- // Destruct the interface //--------------------------------------------------------------------------- cling::UserInterface::~UserInterface() { delete m_MetaProcessor; } //--------------------------------------------------------------------------- // Interact with the user using a prompt //--------------------------------------------------------------------------- void cling::UserInterface::runInteractively(bool nologo /* = false */) { if (!nologo) { PrintLogo(); } static const char* histfile = ".cling_history"; std::string Prompt("[cling]$ "); using namespace textinput; StreamReader* R = StreamReader::Create(); TerminalDisplay* D = TerminalDisplay::Create(); TextInput TI(*R, *D, histfile); TI.SetPrompt(Prompt.c_str()); std::string line; MetaProcessorOpts& MPOpts = m_MetaProcessor->getMetaProcessorOpts(); while (!MPOpts.Quitting) { TextInput::EReadResult RR = TI.ReadInput(); TI.TakeInput(line); if (RR == TextInput::kRREOF) { MPOpts.Quitting = true; continue; } int indent = m_MetaProcessor->process(line.c_str()); Prompt = "[cling]"; if (MPOpts.RawInput) Prompt.append("! "); else Prompt.append("$ "); if (indent > 0) // Continuation requested. Prompt.append('?' + std::string(indent * 3, ' ')); TI.SetPrompt(Prompt.c_str()); } } void cling::UserInterface::PrintLogo() { llvm::outs() << "\n"; llvm::outs() << "****************** CLING ******************" << "\n"; llvm::outs() << "* Type C++ code and press enter to run it *" << "\n"; llvm::outs() << "* Type .q to exit *" << "\n"; llvm::outs() << "*******************************************" << "\n"; } <commit_msg>Fix Savannah #95065: flush llvm::outs() before TextInput interaction.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <[email protected]> //------------------------------------------------------------------------------ #include <cling/UserInterface/UserInterface.h> #include <cling/MetaProcessor/MetaProcessor.h> #include "textinput/TextInput.h" #include "textinput/StreamReader.h" #include "textinput/TerminalDisplay.h" #include "llvm/Support/raw_ostream.h" //--------------------------------------------------------------------------- // Construct an interface for an interpreter //--------------------------------------------------------------------------- cling::UserInterface::UserInterface(Interpreter& interp, const char* prompt /*= "[cling] $"*/): m_MetaProcessor(new MetaProcessor(interp)) { } //--------------------------------------------------------------------------- // Destruct the interface //--------------------------------------------------------------------------- cling::UserInterface::~UserInterface() { delete m_MetaProcessor; } //--------------------------------------------------------------------------- // Interact with the user using a prompt //--------------------------------------------------------------------------- void cling::UserInterface::runInteractively(bool nologo /* = false */) { if (!nologo) { PrintLogo(); } static const char* histfile = ".cling_history"; std::string Prompt("[cling]$ "); using namespace textinput; StreamReader* R = StreamReader::Create(); TerminalDisplay* D = TerminalDisplay::Create(); TextInput TI(*R, *D, histfile); TI.SetPrompt(Prompt.c_str()); std::string line; MetaProcessorOpts& MPOpts = m_MetaProcessor->getMetaProcessorOpts(); while (!MPOpts.Quitting) { llvm::outs().flush(); TextInput::EReadResult RR = TI.ReadInput(); TI.TakeInput(line); if (RR == TextInput::kRREOF) { MPOpts.Quitting = true; continue; } int indent = m_MetaProcessor->process(line.c_str()); Prompt = "[cling]"; if (MPOpts.RawInput) Prompt.append("! "); else Prompt.append("$ "); if (indent > 0) // Continuation requested. Prompt.append('?' + std::string(indent * 3, ' ')); TI.SetPrompt(Prompt.c_str()); } } void cling::UserInterface::PrintLogo() { llvm::outs() << "\n"; llvm::outs() << "****************** CLING ******************" << "\n"; llvm::outs() << "* Type C++ code and press enter to run it *" << "\n"; llvm::outs() << "* Type .q to exit *" << "\n"; llvm::outs() << "*******************************************" << "\n"; } <|endoftext|>
<commit_before>//mandala #include "resource_mgr.hpp" namespace mandala { resource_mgr_t resources; size_t resource_mgr_t::count() const { size_t count = 0; for (const auto& resources : type_resources) { count += resources.second.size(); } return count; } void resource_mgr_t::prune() { for (auto& type_resource : type_resources) { auto& resources = type_resource.second; auto resources_itr = resources.begin(); while (resources_itr != resources.end()) { if (resources_itr->second.unique()) { resources_itr = resources.erase(resources_itr); } else { ++resources_itr; } } } } void resource_mgr_t::purge() { type_resources.clear(); } } <commit_msg>added leak checking for resource_mgr.purge()<commit_after>#if defined(DEBUG) //std #include <vector> //boost #include <boost\weak_ptr.hpp> #endif //mandala #include "resource_mgr.hpp" namespace mandala { resource_mgr_t resources; size_t resource_mgr_t::count() const { size_t count = 0; for (const auto& resources : type_resources) { count += resources.second.size(); } return count; } void resource_mgr_t::prune() { for (auto& type_resource : type_resources) { auto& resources = type_resource.second; auto resources_itr = resources.begin(); while (resources_itr != resources.end()) { if (resources_itr->second.unique()) { resources_itr = resources.erase(resources_itr); } else { ++resources_itr; } } } } void resource_mgr_t::purge() { #if defined(DEBUG) std::vector<boost::weak_ptr<resource_t>> resources; for (auto& type_resource : type_resources) { for (auto& resource : type_resource.second) { resources.push_back(resource.second); } } #endif type_resources.clear(); #if defined(DEBUG) for (auto& resource : resources) { assert(resource.expired()); } #endif } } <|endoftext|>
<commit_before>#ifndef SPOTIFY_BACKSTAGE_SPOTIFYBACKSTAGE_HPP #define SPOTIFY_BACKSTAGE_SPOTIFYBACKSTAGE_HPP #include <memory> #include <string> #include <utility> #include <vector> namespace spotify_backstage { struct EqState; struct Track; class SpotifyBackstage { public: SpotifyBackstage(const std::string& username, const std::string& password); ~SpotifyBackstage(); EqState getEqState(); std::vector<Track> getPlayQueue(); void enqueue(const std::string& uri); void play(); void stop(); void next(); std::vector<Track> search(const std::string& query, int num_results, int offset); void setEqOn(bool on); void setGain(double gain); void setBass(double bass); void setMid(double mid); void setTreble(double treble); int getCurrentOutputDevice(); std::vector<std::pair<int, std::string>> getOutputDevices(); void setOutputDevice(int dev); private: class Impl; std::unique_ptr<Impl> impl_; }; struct EqState { EqState(bool on, double g, double b, double m, double t) : is_on(on), gain(g), bass(b), mid(m), treble(t) { } bool is_on; double gain; double bass; double mid; double treble; }; struct Track { Track(const std::string& artist_p, const std::string& album_p, const std::string& track_p, int duration_sec_p, const std::string& uri_p) : artist(artist_p), album(album_p), track(track_p), duration_sec(duration_sec_p), uri(uri_p) { } std::string artist; std::string album; std::string track; int duration_sec; std::string uri; }; } #endif <commit_msg>Add documentation to SpotifyBackstage.hpp<commit_after>#ifndef SPOTIFY_BACKSTAGE_SPOTIFYBACKSTAGE_HPP #define SPOTIFY_BACKSTAGE_SPOTIFYBACKSTAGE_HPP #include <memory> #include <string> #include <utility> #include <vector> namespace spotify_backstage { struct EqState; struct Track; /** * SpotifyBackstage implements the API to spotify-backstage library. * It offers a Spotify-powered music backend including playback, queuing tracks, Spotify search, etc. * The API is used by creating a SpotifyBackstage instance. * * Features: * - Play queue: Enqueue tracks to the play queue. spotify-backstage will play them in the order they were added. * - Search: Search tracks from Spotify catalog. * - Equalizer: Simple three channel equalizer. * - Output device selection: Ability to select the output device for the audio. */ class SpotifyBackstage { public: /** * Ctor. * * @param username Spotify username * @param password Password for username */ SpotifyBackstage(const std::string& username, const std::string& password); ~SpotifyBackstage(); /** Get the current state of the equalizer */ EqState getEqState(); /** Get the current play queue */ std::vector<Track> getPlayQueue(); /** * Enqueue a track to the play queue. * * @param uri Spotify URI of the track to enqueue. */ void enqueue(const std::string& uri); /** * Start playback. The track currently at the head of the play queue will start playing. * Once the track is finished, it's removed from the play queue and the next track in the queue is played. * The playback will continue for as long as there are tracks in the play queue, or stop() is called. */ void play(); /** Stop playback. */ void stop(); /** * Stop the playback, remove the track currently at the head of the play queue from the queue, * and start playing the next track in the queue (if the queue is not empty). */ void next(); /** * Search tracks from the Spotify catalog. * * @param query Search query string. * @param num_results Max number of tracks to return. * @param offset Offset in the full result list from which to start taking the returned tracks. * This parameter is useful if you want to do more than one search with the same * query string. For example, * * Get the first 10 results for "Neil Young": * search("Neil Young", 10, 0); * * Get the next 10 results: * search("Neil Young", 10, 10); */ std::vector<Track> search(const std::string& query, int num_results, int offset); /** * Set equalizer on/off. * * @param on true = on, false = off. */ void setEqOn(bool on); /** * Set equalizer gain. * * @gain The gain. 1.0 = 100%. */ void setGain(double gain); /** * Set equalizer bass channel level. * * @param bass The level. 1.0 = 100%. */ void setBass(double bass); /** * Set equalizer mid channel level. * * @param mid The level. 1.0 = 100%. */ void setMid(double mid); /** * Set equalizer treble channel level. * * @param treble The level. 1.0 = 100%. */ void setTreble(double treble); /** Get the index of the currently selected audio output device. */ int getCurrentOutputDevice(); /** * Get a list of audio output devices available in the system. * The items in the list contain the device's index and name. */ std::vector<std::pair<int, std::string>> getOutputDevices(); /** * Set the audio output device. * * @param dev Index of the device to set. */ void setOutputDevice(int dev); private: class Impl; std::unique_ptr<Impl> impl_; }; /** * EqState encapsulates the state of the equalizer. * With the gain and the channel levels, value 1.0 = 100%. */ struct EqState { EqState(bool on, double g, double b, double m, double t) : is_on(on), gain(g), bass(b), mid(m), treble(t) { } /** Is the equalizer on? */ bool is_on; /** Equalizer gain */ double gain; /** Bass channel level */ double bass; /** Mid channel level */ double mid; /** Treble channel level */ double treble; }; /** * Track contains information of a single Spotify track. */ struct Track { Track(const std::string& artist_p, const std::string& album_p, const std::string& track_p, int duration_sec_p, const std::string& uri_p) : artist(artist_p), album(album_p), track(track_p), duration_sec(duration_sec_p), uri(uri_p) { } /** Artist(s) */ std::string artist; /** Album */ std::string album; /** Track name */ std::string track; /** Track duration in seconds */ int duration_sec; /** Track's Spotify URI */ std::string uri; }; } #endif <|endoftext|>
<commit_before> #include "stdafx.h" Storage::Variant::Variant() : type(Null), data(0) {} Storage::Variant::~Variant() { free(); } void Storage::Variant::free() { switch(type) { case Str: if(str) delete str; break; case Data: if(data) delete data; break; } } Storage::Data::Data(const char* data, uint length) : data((char*)malloc(length)), length(length) { memcpy(this->data, data, length); } Storage::Data::~Data() { if(data) ::free(data); } Storage::Str::Str(const wchar* data, uint length) : length(length) { uint size = (length + 1) * sizeof(wchar); this->data = (wchar*)malloc(size); memcpy(this->data, data, size); this->data[length] = L'\0'; } Storage::Str::~Str() { if(data) ::free(data); } Storage::Storage() : parent(0) { current = this; } Storage::Storage(Storage* parent) : parent(parent) { current = this; } Storage::~Storage() { free(); } void Storage::free() { for(std::unordered_map<std::string, Storage*>::iterator i = storages.begin(), end = storages.end(); i != end; ++i) delete i->second; for(std::vector<Storage*>::iterator i = array.begin(), end = array.end(); i != end; ++i) delete *i; entries.clear(); storages.clear(); array.resize(0); } Storage* Storage::getCurrentStorage() { current->current = current; return current; } void Storage::setCurrentStorage(Storage* storage) { current = storage ? storage : this; } bool Storage::enterSection(const char* name) { std::string key(name); std::unordered_map<std::string, Storage*>::iterator i = current->storages.find(key); if(i == current->storages.end()) { Storage* storage = new Storage(current); current->storages[key] = storage; current = storage; return true; } else { current = i->second; return true; } } Storage* Storage::getSection(const char* name) { if(!enterSection(name)) return 0; Storage* storage = getCurrentStorage(); leave(); return storage; } bool Storage::leave() { if(!current->parent) return false; current = current->parent; return true; } bool Storage::enterNumSection(uint pos) { if(pos >= current->array.size()) setNumSectionCount(pos + 1); current = current->array[pos]; return true; } Storage* Storage::getNumSection(uint pos) { if(!enterNumSection(pos)) return 0; Storage* storage = getCurrentStorage(); leave(); return storage; } bool Storage::deleteSection(const char* name) { std::string key(name); std::unordered_map<std::string, Storage*>::iterator i = current->storages.find(key); if(i == current->storages.end()) return false; else { delete i->second; current->storages.erase(i); return true; } } bool Storage::deleteNumSection(uint pos) { if(pos >= current->array.size()) return false; delete current->array[pos]; current->array.erase(current->array.begin() + pos); return true; } bool Storage::swapNumSections(uint pos1, uint pos2) { uint size = (uint) current->array.size(); if(pos1 >= size || pos2 >= size) return false; Storage* tmp = current->array[pos1]; current->array[pos1] = current->array[pos2]; current->array[pos2] = tmp; return true; } uint Storage::getNumSectionCount() const { return (uint)current->array.size(); } bool Storage::setNumSectionCount(uint size) { if(size < current->array.size()) { for(uint i = size, count = (uint)current->array.size(); i < count; ++i) delete current->array[i]; current->array.resize(size); } else if(size > current->array.size()) { uint i = (uint)current->array.size(); current->array.resize(size); for(; i < size; ++i) current->array[i] = new Storage(current); } return true; } const wchar* Storage::getStr(const char* name, uint* length, const wchar* default, uint defaultLength) const { std::unordered_map<std::string, Variant>::const_iterator i = current->entries.find(std::string(name)); if(i == current->entries.end()) { if(length) *length = defaultLength; return default; } const Variant& val(i->second); if(val.type != Variant::Str) { if(length) *length = defaultLength; return default; } if(length) *length = val.str->length; return val.str->data; } int Storage::getInt(const char* name, int default) const { std::unordered_map<std::string, Variant>::const_iterator i = current->entries.find(std::string(name)); if(i == current->entries.end()) return default; const Variant& val(i->second); if(val.type != Variant::Int) return default; return val._int; } uint Storage::getUInt(const char* name, uint default) const { std::unordered_map<std::string, Variant>::const_iterator i = current->entries.find(std::string(name)); if(i == current->entries.end()) return default; const Variant& val(i->second); if(val.type != Variant::UInt) return default; return val._uint; } bool Storage::getData(const char* name, char** data, uint* length, const char* defaultData, uint defaultLength) const { std::unordered_map<std::string, Variant>::iterator i = current->entries.find(std::string(name)); if(i == current->entries.end()) { *data = (char*)defaultData; if(length) *length = defaultLength; return false; } const Variant& val(i->second); if(val.type != Variant::Data) { *data = (char*)defaultData; if(length) *length = defaultLength; return false; } *data = (char*)val.data->data; if(length) *length = val.data->length; return true; } bool Storage::setStr(const char* name, const wchar* value, uint length) { Variant& val(current->entries[std::string(name)]); val.free(); val.type = Variant::Str; val.str = new Str(value, length ? length : (uint)wcslen(value)); return true; } bool Storage::setInt(const char* name, int value) { Variant& val(current->entries[std::string(name)]); val.free(); val.type = Variant::Int; val._int = value; return true; } bool Storage::setUInt(const char* name, uint value) { Variant& val(current->entries[std::string(name)]); val.free(); val.type = Variant::UInt; val._uint = value; return true; } bool Storage::setData(const char* name, char* data, uint length) { Variant& val(current->entries[std::string(name)]); val.free(); val.type = Variant::Data; val.data = new Data(data, length); return true; } bool Storage::deleteEntry(const char* name) { std::unordered_map<std::string, Variant>::iterator i = current->entries.find(std::string(name)); if(i == current->entries.end()) return false; current->entries.erase(i); return true; } bool Storage::save() { if(filename.empty()) return false; HANDLE hFile = CreateFile(filename.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) return false; uint header = 1; // minimal header bool ret = write(hFile, &header, sizeof(header)) && save(hFile); CloseHandle(hFile); return ret; } bool Storage::load(const wchar* file) { HANDLE hFile = CreateFile(file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) return false; uint header; bool ret = read(hFile, &header, sizeof(header)) && header == 1 && load(hFile); CloseHandle(hFile); if(ret) filename = file; return ret; } bool Storage::read(HANDLE hFile, void* buffer, unsigned size) const { DWORD bi; return ReadFile(hFile, buffer, size, &bi, NULL) && bi == size; } bool Storage::write(HANDLE hFile, const void* buffer, unsigned size) const { DWORD bi; return WriteFile(hFile, buffer, size, &bi, NULL) ? true : false; } bool Storage::load(HANDLE hFile) { free(); // read all entries uint size; if(!read(hFile, &size, sizeof(size))) return false; std::vector<char> keybuffer; uint keysize; for(uint i = 0; i < size; ++i) { if(!read(hFile, &keysize, sizeof(keysize))) return false; keybuffer.resize(keysize + 1); if(!read(hFile, &keybuffer[0], keysize)) return false; keybuffer[keysize] = '\0'; Variant& var(entries[std::string(&keybuffer[0])]); if(!read(hFile, &var.type, sizeof(var.type))) return false; switch(var.type) { case Variant::Int: case Variant::UInt: if(!read(hFile, &var._int, sizeof(int))) return false; break; case Variant::Str: { var.str = new Str; if(!read(hFile, &var.str->length, sizeof(var.str->length))) return false; uint size = var.str->length * sizeof(wchar); var.str->data = (wchar*)malloc(size + sizeof(wchar)); if(!read(hFile, var.str->data, size) ) return false; var.str->data[var.str->length] = L'\0'; } break; case Variant::Data: var.data = new Data; if(!read(hFile, &var.data->length, sizeof(var.data->length))) return false; var.data->data = (char*)malloc(var.data->length); if(!read(hFile, var.data->data, var.data->length) ) return false; break; } } // read substorages if(!read(hFile, &size, sizeof(size))) return false; for(uint i = 0; i < size; ++i) { if(!read(hFile, &keysize, sizeof(keysize))) return false; keybuffer.resize(keysize + 1); if(!read(hFile, &keybuffer[0], keysize)) return false; keybuffer[keysize] = '\0'; Storage*& storage = storages[std::string(&keybuffer[0])]; storage = new Storage(this); if(!storage->load(hFile)) return false; } // read array if(!read(hFile, &size, sizeof(size))) return false; array.resize(size); for(uint i = 0; i < size; ++i) { Storage*& storage = array[i]; storage = new Storage(this); if(!storage->load(hFile)) return false; } return true; } bool Storage::save(HANDLE hFile) const { // save all entries uint size = (uint)entries.size(); if(!write(hFile, &size, sizeof(size))) return false; for(std::unordered_map<std::string, Variant>::const_iterator i = entries.begin(), end = entries.end(); i != end; ++i) { const std::string& key(i->first); const Variant& var(i->second); uint keysize = (uint)key.size(); if(!write(hFile, &keysize, sizeof(keysize)) || !write(hFile, key.c_str(), keysize) || !write(hFile, &var.type, sizeof(var.type)) ) return false; switch(var.type) { case Variant::Int: case Variant::UInt: if(!write(hFile, &var._int, sizeof(int))) return false; break; case Variant::Str: if(!write(hFile, &var.str->length, sizeof(var.str->length)) || !write(hFile, var.str->data, var.str->length * sizeof(wchar)) ) return false; break; case Variant::Data: if(!write(hFile, &var.data->length, sizeof(var.data->length)) || !write(hFile, var.data->data, var.data->length) ) return false; break; } } // save substorages size = (uint)storages.size(); if(!write(hFile, &size, sizeof(size))) return false; for(std::unordered_map<std::string, Storage*>::const_iterator i = storages.begin(), end = storages.end(); i != end; ++i) { const std::string& key(i->first); Storage* storage(i->second); uint keysize = (uint)key.size(); if(!write(hFile, &keysize, sizeof(keysize)) || !write(hFile, key.c_str(), keysize) || !storage->save(hFile)) return false; } // save array size = (uint)array.size(); if(!write(hFile, &size, sizeof(size))) return false; for(std::vector<Storage*>::const_iterator i = array.begin(), end = array.end(); i != end; ++i) if(!(*i)->save(hFile)) return false; return true; } <commit_msg>Dock: Fix issue with not working settings saving<commit_after> #include "stdafx.h" Storage::Variant::Variant() : type(Null), data(0) {} Storage::Variant::~Variant() { free(); } void Storage::Variant::free() { switch(type) { case Str: if(str) delete str; break; case Data: if(data) delete data; break; } } Storage::Data::Data(const char* data, uint length) : data((char*)malloc(length)), length(length) { memcpy(this->data, data, length); } Storage::Data::~Data() { if(data) ::free(data); } Storage::Str::Str(const wchar* data, uint length) : length(length) { uint size = (length + 1) * sizeof(wchar); this->data = (wchar*)malloc(size); memcpy(this->data, data, size); this->data[length] = L'\0'; } Storage::Str::~Str() { if(data) ::free(data); } Storage::Storage() : parent(0) { current = this; } Storage::Storage(Storage* parent) : parent(parent) { current = this; } Storage::~Storage() { free(); } void Storage::free() { for(std::unordered_map<std::string, Storage*>::iterator i = storages.begin(), end = storages.end(); i != end; ++i) delete i->second; for(std::vector<Storage*>::iterator i = array.begin(), end = array.end(); i != end; ++i) delete *i; entries.clear(); storages.clear(); array.resize(0); } Storage* Storage::getCurrentStorage() { current->current = current; return current; } void Storage::setCurrentStorage(Storage* storage) { current = storage ? storage : this; } bool Storage::enterSection(const char* name) { std::string key(name); std::unordered_map<std::string, Storage*>::iterator i = current->storages.find(key); if(i == current->storages.end()) { Storage* storage = new Storage(current); current->storages[key] = storage; current = storage; return true; } else { current = i->second; return true; } } Storage* Storage::getSection(const char* name) { if(!enterSection(name)) return 0; Storage* storage = getCurrentStorage(); leave(); return storage; } bool Storage::leave() { if(!current->parent) return false; current = current->parent; return true; } bool Storage::enterNumSection(uint pos) { if(pos >= current->array.size()) setNumSectionCount(pos + 1); current = current->array[pos]; return true; } Storage* Storage::getNumSection(uint pos) { if(!enterNumSection(pos)) return 0; Storage* storage = getCurrentStorage(); leave(); return storage; } bool Storage::deleteSection(const char* name) { std::string key(name); std::unordered_map<std::string, Storage*>::iterator i = current->storages.find(key); if(i == current->storages.end()) return false; else { delete i->second; current->storages.erase(i); return true; } } bool Storage::deleteNumSection(uint pos) { if(pos >= current->array.size()) return false; delete current->array[pos]; current->array.erase(current->array.begin() + pos); return true; } bool Storage::swapNumSections(uint pos1, uint pos2) { uint size = (uint) current->array.size(); if(pos1 >= size || pos2 >= size) return false; Storage* tmp = current->array[pos1]; current->array[pos1] = current->array[pos2]; current->array[pos2] = tmp; return true; } uint Storage::getNumSectionCount() const { return (uint)current->array.size(); } bool Storage::setNumSectionCount(uint size) { if(size < current->array.size()) { for(uint i = size, count = (uint)current->array.size(); i < count; ++i) delete current->array[i]; current->array.resize(size); } else if(size > current->array.size()) { uint i = (uint)current->array.size(); current->array.resize(size); for(; i < size; ++i) current->array[i] = new Storage(current); } return true; } const wchar* Storage::getStr(const char* name, uint* length, const wchar* default, uint defaultLength) const { std::unordered_map<std::string, Variant>::const_iterator i = current->entries.find(std::string(name)); if(i == current->entries.end()) { if(length) *length = defaultLength; return default; } const Variant& val(i->second); if(val.type != Variant::Str) { if(length) *length = defaultLength; return default; } if(length) *length = val.str->length; return val.str->data; } int Storage::getInt(const char* name, int default) const { std::unordered_map<std::string, Variant>::const_iterator i = current->entries.find(std::string(name)); if(i == current->entries.end()) return default; const Variant& val(i->second); if(val.type != Variant::Int) return default; return val._int; } uint Storage::getUInt(const char* name, uint default) const { std::unordered_map<std::string, Variant>::const_iterator i = current->entries.find(std::string(name)); if(i == current->entries.end()) return default; const Variant& val(i->second); if(val.type != Variant::UInt) return default; return val._uint; } bool Storage::getData(const char* name, char** data, uint* length, const char* defaultData, uint defaultLength) const { std::unordered_map<std::string, Variant>::iterator i = current->entries.find(std::string(name)); if(i == current->entries.end()) { *data = (char*)defaultData; if(length) *length = defaultLength; return false; } const Variant& val(i->second); if(val.type != Variant::Data) { *data = (char*)defaultData; if(length) *length = defaultLength; return false; } *data = (char*)val.data->data; if(length) *length = val.data->length; return true; } bool Storage::setStr(const char* name, const wchar* value, uint length) { Variant& val(current->entries[std::string(name)]); val.free(); val.type = Variant::Str; val.str = new Str(value, length ? length : (uint)wcslen(value)); return true; } bool Storage::setInt(const char* name, int value) { Variant& val(current->entries[std::string(name)]); val.free(); val.type = Variant::Int; val._int = value; return true; } bool Storage::setUInt(const char* name, uint value) { Variant& val(current->entries[std::string(name)]); val.free(); val.type = Variant::UInt; val._uint = value; return true; } bool Storage::setData(const char* name, char* data, uint length) { Variant& val(current->entries[std::string(name)]); val.free(); val.type = Variant::Data; val.data = new Data(data, length); return true; } bool Storage::deleteEntry(const char* name) { std::unordered_map<std::string, Variant>::iterator i = current->entries.find(std::string(name)); if(i == current->entries.end()) return false; current->entries.erase(i); return true; } bool Storage::save() { if(filename.empty()) return false; HANDLE hFile = CreateFile(filename.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) return false; uint header = 1; // minimal header bool ret = write(hFile, &header, sizeof(header)) && save(hFile); CloseHandle(hFile); return ret; } bool Storage::load(const wchar* file) { filename = file; HANDLE hFile = CreateFile(file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) return false; uint header; bool ret = read(hFile, &header, sizeof(header)) && header == 1 && load(hFile); CloseHandle(hFile); return ret; } bool Storage::read(HANDLE hFile, void* buffer, unsigned size) const { DWORD bi; return ReadFile(hFile, buffer, size, &bi, NULL) && bi == size; } bool Storage::write(HANDLE hFile, const void* buffer, unsigned size) const { DWORD bi; return WriteFile(hFile, buffer, size, &bi, NULL) ? true : false; } bool Storage::load(HANDLE hFile) { free(); // read all entries uint size; if(!read(hFile, &size, sizeof(size))) return false; std::vector<char> keybuffer; uint keysize; for(uint i = 0; i < size; ++i) { if(!read(hFile, &keysize, sizeof(keysize))) return false; keybuffer.resize(keysize + 1); if(!read(hFile, &keybuffer[0], keysize)) return false; keybuffer[keysize] = '\0'; Variant& var(entries[std::string(&keybuffer[0])]); if(!read(hFile, &var.type, sizeof(var.type))) return false; switch(var.type) { case Variant::Int: case Variant::UInt: if(!read(hFile, &var._int, sizeof(int))) return false; break; case Variant::Str: { var.str = new Str; if(!read(hFile, &var.str->length, sizeof(var.str->length))) return false; uint size = var.str->length * sizeof(wchar); var.str->data = (wchar*)malloc(size + sizeof(wchar)); if(!read(hFile, var.str->data, size) ) return false; var.str->data[var.str->length] = L'\0'; } break; case Variant::Data: var.data = new Data; if(!read(hFile, &var.data->length, sizeof(var.data->length))) return false; var.data->data = (char*)malloc(var.data->length); if(!read(hFile, var.data->data, var.data->length) ) return false; break; } } // read substorages if(!read(hFile, &size, sizeof(size))) return false; for(uint i = 0; i < size; ++i) { if(!read(hFile, &keysize, sizeof(keysize))) return false; keybuffer.resize(keysize + 1); if(!read(hFile, &keybuffer[0], keysize)) return false; keybuffer[keysize] = '\0'; Storage*& storage = storages[std::string(&keybuffer[0])]; storage = new Storage(this); if(!storage->load(hFile)) return false; } // read array if(!read(hFile, &size, sizeof(size))) return false; array.resize(size); for(uint i = 0; i < size; ++i) { Storage*& storage = array[i]; storage = new Storage(this); if(!storage->load(hFile)) return false; } return true; } bool Storage::save(HANDLE hFile) const { // save all entries uint size = (uint)entries.size(); if(!write(hFile, &size, sizeof(size))) return false; for(std::unordered_map<std::string, Variant>::const_iterator i = entries.begin(), end = entries.end(); i != end; ++i) { const std::string& key(i->first); const Variant& var(i->second); uint keysize = (uint)key.size(); if(!write(hFile, &keysize, sizeof(keysize)) || !write(hFile, key.c_str(), keysize) || !write(hFile, &var.type, sizeof(var.type)) ) return false; switch(var.type) { case Variant::Int: case Variant::UInt: if(!write(hFile, &var._int, sizeof(int))) return false; break; case Variant::Str: if(!write(hFile, &var.str->length, sizeof(var.str->length)) || !write(hFile, var.str->data, var.str->length * sizeof(wchar)) ) return false; break; case Variant::Data: if(!write(hFile, &var.data->length, sizeof(var.data->length)) || !write(hFile, var.data->data, var.data->length) ) return false; break; } } // save substorages size = (uint)storages.size(); if(!write(hFile, &size, sizeof(size))) return false; for(std::unordered_map<std::string, Storage*>::const_iterator i = storages.begin(), end = storages.end(); i != end; ++i) { const std::string& key(i->first); Storage* storage(i->second); uint keysize = (uint)key.size(); if(!write(hFile, &keysize, sizeof(keysize)) || !write(hFile, key.c_str(), keysize) || !storage->save(hFile)) return false; } // save array size = (uint)array.size(); if(!write(hFile, &size, sizeof(size))) return false; for(std::vector<Storage*>::const_iterator i = array.begin(), end = array.end(); i != end; ++i) if(!(*i)->save(hFile)) return false; return true; } <|endoftext|>
<commit_before>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2016 */ /* * OTRadValve TempControl tests. */ #include <gtest/gtest.h> #include <stdio.h> #include <stdlib.h> #include "OTSIM900Link.h" // Test for general sanity of OTSIM900Link. // Make sure that an instance can be created and does not die horribly. // Underlying simulated serial/SIM900 never accepts data or responds, eg like a dead card. TEST(OTSIM900Link,basicsDeadCard) { const bool verbose = false; class NULLSerialStream final : public Stream { public: void begin(unsigned long) { } void begin(unsigned long, uint8_t); void end(); virtual size_t write(uint8_t c) override { if(verbose) { fprintf(stderr, "%c\n", (char) c); } return(0); } virtual int available() override { return(-1); } virtual int read() override { return(-1); } virtual int peek() override { return(-1); } virtual void flush() override { } }; OTSIM900Link::OTSIM900Link<0, 0, 0, NULLSerialStream> l0; EXPECT_TRUE(l0.begin()); EXPECT_EQ(OTSIM900Link::GET_STATE, l0._getState()); // Try to hang just by calling poll() repeatedly. for(int i = 0; i < 100; ++i) { l0.poll(); } EXPECT_GE(OTSIM900Link::START_UP, l0._getState()) << "should keep trying to start with GET_STATE, RETRY_GET_STATE and START_UP"; // ... l0.end(); } // Test for general sanity of OTSIM900Link. // Make sure that an instance can be created and does not die horribly. // Underlying simulated serial/SIM900 accepts output, does not respond. namespace B1 { const bool verbose = true; // Does a trivial simulation of SIM900, responding to start of 'A' of AT command. // Exercises every major non-PANIC state of the OTSIM900Link implementation. class TrivialSimulator final : public Stream { public: // Events exposed. static bool haveSeenCommandStart; private: // Command being collected from OTSIM900Link. bool waitingForCommand = true; bool collectingCommand = false; // Entire request starting "AT"; no trailing CR or LF stored. std::string command; // Reply (postfix) being returned to OTSIM900Link: empty if none. std::string reply; public: void begin(unsigned long) { } void begin(unsigned long, uint8_t); void end(); virtual size_t write(uint8_t uc) override { const char c = (char)uc; if(waitingForCommand) { // Look for leading 'A' of 'AT' to start a command. if('A' == c) { waitingForCommand = false; collectingCommand = true; command = 'A'; haveSeenCommandStart = true; // Note at least one command start. } } else { // Look for CR (or LF) to terminate a command. if(('\r' == c) || ('\n' == c)) { waitingForCommand = true; collectingCommand = false; if(verbose) { fprintf(stderr, "command received: %s\n", command.c_str()); } // Respond to particular commands... if("AT" == command) { reply = "AT\r"; } // DHD20161101: "No PIN" response (deliberately not typical SIM900 response) resulted in SIGSEGV from not checking getResponse() result for NULL. // Should futz/vary the response to check sensitivity. // TODO: have at least one response be expected SIM900 answer for no-PIN SIM. else if("AT+CPIN?" == command) { reply = (random() & 1) ? "No PIN" : "OK READY"; } } else if(collectingCommand) { command += c; } } if(verbose) { if(isprint(c)) { fprintf(stderr, "<%c\n", c); } else { fprintf(stderr, "< %d\n", (int)c); } } return(1); } virtual int read() override { if(0 == reply.size()) { return(-1); } const char c = reply[0]; if(verbose) { if(isprint(c)) { fprintf(stderr, ">%c\n", c); } else { fprintf(stderr, "> %d\n", (int)c); } } reply.erase(0, 1); return(c); } virtual int available() override { return(-1); } virtual int peek() override { return(-1); } virtual void flush() override { } }; // Events exposed. bool TrivialSimulator::haveSeenCommandStart; } TEST(OTSIM900Link,basicsSimpleSimulator) { // const bool verbose = true; //srandomdev(); // Seed random() for use in simulator. ASSERT_FALSE(B1::TrivialSimulator::haveSeenCommandStart); OTSIM900Link::OTSIM900Link<0, 0, 0, B1::TrivialSimulator> l0; EXPECT_TRUE(l0.begin()); EXPECT_EQ(OTSIM900Link::GET_STATE, l0._getState()); // Try to hang just by calling poll() repeatedly. for(int i = 0; i < 100; ++i) { l0.poll(); } EXPECT_TRUE(B1::TrivialSimulator::haveSeenCommandStart) << "should see some attempt to communicate with SIM900"; EXPECT_LE(OTSIM900Link::WAIT_FOR_REGISTRATION, l0._getState()) << "should make it to at least WAIT_FOR_REGISTRATION"; // ... l0.end(); } <commit_msg>Added to test harness<commit_after>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2016 */ /* * OTRadValve TempControl tests. */ #include <gtest/gtest.h> #include <stdio.h> #include <stdlib.h> #include "OTSIM900Link.h" // Test for general sanity of OTSIM900Link. // Make sure that an instance can be created and does not die horribly. // Underlying simulated serial/SIM900 never accepts data or responds, eg like a dead card. TEST(OTSIM900Link,basicsDeadCard) { const bool verbose = false; class NULLSerialStream final : public Stream { public: void begin(unsigned long) { } void begin(unsigned long, uint8_t); void end(); virtual size_t write(uint8_t c) override { if(verbose) { fprintf(stderr, "%c\n", (char) c); } return(0); } virtual int available() override { return(-1); } virtual int read() override { return(-1); } virtual int peek() override { return(-1); } virtual void flush() override { } }; OTSIM900Link::OTSIM900Link<0, 0, 0, NULLSerialStream> l0; EXPECT_TRUE(l0.begin()); EXPECT_EQ(OTSIM900Link::GET_STATE, l0._getState()); // Try to hang just by calling poll() repeatedly. for(int i = 0; i < 100; ++i) { l0.poll(); } EXPECT_GE(OTSIM900Link::START_UP, l0._getState()) << "should keep trying to start with GET_STATE, RETRY_GET_STATE and START_UP"; // ... l0.end(); } // Test for general sanity of OTSIM900Link. // Make sure that an instance can be created and does not die horribly. // Underlying simulated serial/SIM900 accepts output, does not respond. namespace B1 { const bool verbose = true; // Does a trivial simulation of SIM900, responding to start of 'A' of AT command. // Exercises every major non-PANIC state of the OTSIM900Link implementation. class TrivialSimulator final : public Stream { public: // Events exposed. static bool haveSeenCommandStart; private: // Command being collected from OTSIM900Link. bool waitingForCommand = true; bool collectingCommand = false; // Entire request starting "AT"; no trailing CR or LF stored. std::string command; // Reply (postfix) being returned to OTSIM900Link: empty if none. std::string reply; public: void begin(unsigned long) { } void begin(unsigned long, uint8_t); void end(); virtual size_t write(uint8_t uc) override { const char c = (char)uc; if(waitingForCommand) { // Look for leading 'A' of 'AT' to start a command. if('A' == c) { waitingForCommand = false; collectingCommand = true; command = 'A'; haveSeenCommandStart = true; // Note at least one command start. } } else { // Look for CR (or LF) to terminate a command. if(('\r' == c) || ('\n' == c)) { waitingForCommand = true; collectingCommand = false; if(verbose) { fprintf(stderr, "command received: %s\n", command.c_str()); } // Respond to particular commands... if("AT" == command) { reply = "AT\r"; } // Relevant states: GET_STATE, RETRY_GET_STATE, START_UP // DHD20161101: "No PIN" response (deliberately not typical SIM900 response) resulted in SIGSEGV from not checking getResponse() result for NULL. // Should futz/vary the response to check sensitivity. // TODO: have at least one response be expected SIM900 answer for no-PIN SIM. else if("AT+CPIN?" == command) { reply = (random() & 1) ? "No PIN\r" : "OK READY\r"; } // Relevant states: CHECK_PIN else if("AT+CREG?" == command) { reply = (random() & 1) ? "+CREG: 0,0\r" : "+CREG: 0,5\r"; } // Relevant states: WAIT_FOR_REGISTRATION // else if("AT+CSTT=" == command) { reply = (random() & 1) ? "gbfhs\r" : "\n OK\r"; } // Relevant states: SET_APN FIXME need to pass OTSIM900Link a config! } else if(collectingCommand) { command += c; } } if(verbose) { if(isprint(c)) { fprintf(stderr, "<%c\n", c); } else { fprintf(stderr, "< %d\n", (int)c); } } return(1); } virtual int read() override { if(0 == reply.size()) { return(-1); } const char c = reply[0]; if(verbose) { if(isprint(c)) { fprintf(stderr, ">%c\n", c); } else { fprintf(stderr, "> %d\n", (int)c); } } reply.erase(0, 1); return(c); } virtual int available() override { return(-1); } virtual int peek() override { return(-1); } virtual void flush() override { } }; // Events exposed. bool TrivialSimulator::haveSeenCommandStart; } TEST(OTSIM900Link,basicsSimpleSimulator) { // const bool verbose = true; //srandomdev(); // Seed random() for use in simulator. ASSERT_FALSE(B1::TrivialSimulator::haveSeenCommandStart); OTSIM900Link::OTSIM900Link<0, 0, 0, B1::TrivialSimulator> l0; EXPECT_TRUE(l0.begin()); EXPECT_EQ(OTSIM900Link::GET_STATE, l0._getState()); // Try to hang just by calling poll() repeatedly. for(int i = 0; i < 100; ++i) { l0.poll(); } EXPECT_TRUE(B1::TrivialSimulator::haveSeenCommandStart) << "should see some attempt to communicate with SIM900"; EXPECT_LE(OTSIM900Link::WAIT_FOR_REGISTRATION, l0._getState()) << "should make it to at least WAIT_FOR_REGISTRATION"; // ... l0.end(); } <|endoftext|>
<commit_before>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2016 */ /* * OTRadValve SIM900 tests. */ #include <gtest/gtest.h> #include <stdio.h> #include <stdlib.h> #include "OTSIM900Link.h" // Test the getter function definitely does what it should. TEST(OTSIM900Link, getterFunction) { const char SIM900_PIN[] = "1111"; const OTSIM900Link::OTSIM900LinkConfig_t SIM900Config(false, SIM900_PIN, NULL, NULL, NULL); EXPECT_EQ(SIM900_PIN[0], SIM900Config.get((const uint8_t *)SIM900Config.PIN)); } // Test for general sanity of OTSIM900Link. // Make sure that an instance can be created and does not die horribly. // Underlying simulated serial/SIM900 never accepts data or responds, eg like a dead card. TEST(OTSIM900Link,basicsDeadCard) { const bool verbose = false; class NULLSerialStream final : public Stream { public: void begin(unsigned long) { } void begin(unsigned long, uint8_t); void end(); virtual size_t write(uint8_t c) override { if(verbose) { fprintf(stderr, "%c\n", (char) c); } return(0); } virtual int available() override { return(-1); } virtual int read() override { return(-1); } virtual int peek() override { return(-1); } virtual void flush() override { } }; const char SIM900_PIN[] = "1111"; const char SIM900_APN[] = "apn"; const char SIM900_UDP_ADDR[] = "0.0.0.0"; // ORS server const char SIM900_UDP_PORT[] = "9999"; const OTSIM900Link::OTSIM900LinkConfig_t SIM900Config(false, SIM900_PIN, SIM900_APN, SIM900_UDP_ADDR, SIM900_UDP_PORT); const OTRadioLink::OTRadioChannelConfig l0Config(&SIM900Config, true); OTSIM900Link::OTSIM900Link<0, 0, 0, NULLSerialStream> l0; EXPECT_TRUE(l0.configure(1, &l0Config)); EXPECT_TRUE(l0.begin()); EXPECT_EQ(OTSIM900Link::GET_STATE, l0._getState()); // Try to hang just by calling poll() repeatedly. for(int i = 0; i < 100; ++i) { l0.poll(); } EXPECT_GE(OTSIM900Link::GET_STATE, l0._getState()) << "should keep trying to start with GET_STATE, RETRY_GET_STATE"; // ... l0.end(); } // Walk through state space of OTSIM900Link. // Make sure that an instance can be created and does not die horribly. // Is meant to mainly walk through all the normal expected SIM900 behaviour when all is well. // Other tests can look at error handling including unexpected/garbage responses. namespace B1 { const bool verbose = true; // Does a simple simulation of SIM900, responding sensibly to all commands needed by the OTSIM900Link impl. // Allows for exercise of every major non-PANIC state of the OTSIM900Link implementation. class GoodSimulator final : public Stream { public: // Events exposed. static bool haveSeenCommandStart; private: // Command being collected from OTSIM900Link. bool waitingForCommand = true; bool collectingCommand = false; // Entire request starting "AT"; no trailing CR or LF stored. std::string command; // Reply (postfix) being returned to OTSIM900Link: empty if none. std::string reply; public: void begin(unsigned long) { } void begin(unsigned long, uint8_t); void end(); virtual size_t write(uint8_t uc) override { const char c = (char)uc; if(waitingForCommand) { // Look for leading 'A' of 'AT' to start a command. if('A' == c) { waitingForCommand = false; collectingCommand = true; command = 'A'; haveSeenCommandStart = true; // Note at least one command start. } } else { // Look for CR (or LF) to terminate a command. if(('\r' == c) || ('\n' == c)) { waitingForCommand = true; collectingCommand = false; if(verbose) { fprintf(stderr, "command received: %s\n", command.c_str()); } // Respond to particular commands... if("AT" == command) { reply = "AT\r"; } // Relevant states: GET_STATE, RETRY_GET_STATE, START_UP else if("AT+CPIN?" == command) { reply = /* (random() & 1) ? "No PIN\r" : */ "READY\r"; } // Relevant states: CHECK_PIN else if("AT+CREG?" == command) { reply = /* (random() & 1) ? "+CREG: 0,0\r" : */ "+CREG: 0,5\r"; } // Relevant states: WAIT_FOR_REGISTRATION else if("AT+CSTT=apn" == command) { reply = /* (random() & 1) ? "gbfhs\r" : */ "AT+CSTT\r\n\r\nOK\r"; } // Relevant states: SET_APN } else if(collectingCommand) { command += c; } } if(verbose) { if(isprint(c)) { fprintf(stderr, "<%c\n", c); } else { fprintf(stderr, "< %d\n", (int)c); } } return(1); } virtual int read() override { if(0 == reply.size()) { return(-1); } const char c = reply[0]; if(verbose) { if(isprint(c)) { fprintf(stderr, ">%c\n", c); } else { fprintf(stderr, "> %d\n", (int)c); } } reply.erase(0, 1); return(c); } virtual int available() override { return(-1); } virtual int peek() override { return(-1); } virtual void flush() override { } }; // Events exposed. bool GoodSimulator::haveSeenCommandStart; } TEST(OTSIM900Link,basicsSimpleSimulator) { // const bool verbose = B1::verbose; srandom(::testing::UnitTest::GetInstance()->random_seed()); // Seed random() for use in simulator; --gtest_shuffle will force it to change. const char SIM900_PIN[] = "1111"; const char SIM900_APN[] = "apn"; const char SIM900_UDP_ADDR[] = "0.0.0.0"; // ORS server const char SIM900_UDP_PORT[] = "9999"; const OTSIM900Link::OTSIM900LinkConfig_t SIM900Config(false, SIM900_PIN, SIM900_APN, SIM900_UDP_ADDR, SIM900_UDP_PORT); const OTRadioLink::OTRadioChannelConfig l0Config(&SIM900Config, true); ASSERT_FALSE(B1::GoodSimulator::haveSeenCommandStart); OTSIM900Link::OTSIM900Link<0, 0, 0, B1::GoodSimulator> l0; EXPECT_TRUE(l0.configure(1, &l0Config)); EXPECT_TRUE(l0.begin()); EXPECT_EQ(OTSIM900Link::GET_STATE, l0._getState()); // Try to hang just by calling poll() repeatedly. for(int i = 0; i < 100; ++i) { l0.poll(); } EXPECT_TRUE(B1::GoodSimulator::haveSeenCommandStart) << "should see some attempt to communicate with SIM900"; EXPECT_LE(OTSIM900Link::WAIT_FOR_REGISTRATION, l0._getState()) << "should make it to at least WAIT_FOR_REGISTRATION"; // ... l0.end(); } <commit_msg>Expanded test rig<commit_after>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2016 */ /* * OTRadValve SIM900 tests. */ #include <gtest/gtest.h> #include <stdio.h> #include <stdlib.h> #include "OTSIM900Link.h" // Test the getter function definitely does what it should. TEST(OTSIM900Link, getterFunction) { const char SIM900_PIN[] = "1111"; const OTSIM900Link::OTSIM900LinkConfig_t SIM900Config(false, SIM900_PIN, NULL, NULL, NULL); EXPECT_EQ(SIM900_PIN[0], SIM900Config.get((const uint8_t *)SIM900Config.PIN)); } // Test for general sanity of OTSIM900Link. // Make sure that an instance can be created and does not die horribly. // Underlying simulated serial/SIM900 never accepts data or responds, eg like a dead card. TEST(OTSIM900Link,basicsDeadCard) { const bool verbose = false; class NULLSerialStream final : public Stream { public: void begin(unsigned long) { } void begin(unsigned long, uint8_t); void end(); virtual size_t write(uint8_t c) override { if(verbose) { fprintf(stderr, "%c\n", (char) c); } return(0); } virtual int available() override { return(-1); } virtual int read() override { return(-1); } virtual int peek() override { return(-1); } virtual void flush() override { } }; const char SIM900_PIN[] = "1111"; const char SIM900_APN[] = "apn"; const char SIM900_UDP_ADDR[] = "0.0.0.0"; // ORS server const char SIM900_UDP_PORT[] = "9999"; const OTSIM900Link::OTSIM900LinkConfig_t SIM900Config(false, SIM900_PIN, SIM900_APN, SIM900_UDP_ADDR, SIM900_UDP_PORT); const OTRadioLink::OTRadioChannelConfig l0Config(&SIM900Config, true); OTSIM900Link::OTSIM900Link<0, 0, 0, NULLSerialStream> l0; EXPECT_TRUE(l0.configure(1, &l0Config)); EXPECT_TRUE(l0.begin()); EXPECT_EQ(OTSIM900Link::GET_STATE, l0._getState()); // Try to hang just by calling poll() repeatedly. for(int i = 0; i < 100; ++i) { l0.poll(); } EXPECT_GE(OTSIM900Link::GET_STATE, l0._getState()) << "should keep trying to start with GET_STATE, RETRY_GET_STATE"; // ... l0.end(); } // Walk through state space of OTSIM900Link. // Make sure that an instance can be created and does not die horribly. // Is meant to mainly walk through all the normal expected SIM900 behaviour when all is well. // Other tests can look at error handling including unexpected/garbage responses. namespace B1 { const bool verbose = true; // Does a simple simulation of SIM900, responding sensibly to all commands needed by the OTSIM900Link impl. // Allows for exercise of every major non-PANIC state of the OTSIM900Link implementation. class GoodSimulator final : public Stream { public: // Events exposed. static bool haveSeenCommandStart; private: // Command being collected from OTSIM900Link. bool waitingForCommand = true; bool collectingCommand = false; // Entire request starting "AT"; no trailing CR or LF stored. std::string command; // Reply (postfix) being returned to OTSIM900Link: empty if none. std::string reply; public: void begin(unsigned long) { } void begin(unsigned long, uint8_t); void end(); virtual size_t write(uint8_t uc) override { const char c = (char)uc; if(waitingForCommand) { // Look for leading 'A' of 'AT' to start a command. if('A' == c) { waitingForCommand = false; collectingCommand = true; command = 'A'; haveSeenCommandStart = true; // Note at least one command start. } } else { // Look for CR (or LF) to terminate a command. if(('\r' == c) || ('\n' == c)) { waitingForCommand = true; collectingCommand = false; if(verbose) { fprintf(stderr, "command received: %s\n", command.c_str()); } // Respond to particular commands... if("AT" == command) { reply = "AT\r"; } // Relevant states: GET_STATE, RETRY_GET_STATE, START_UP else if("AT+CPIN?" == command) { reply = /* (random() & 1) ? "No PIN\r" : */ "READY\r"; } // Relevant states: CHECK_PIN else if("AT+CREG?" == command) { reply = /* (random() & 1) ? "+CREG: 0,0\r" : */ "+CREG: 0,5\r"; } // Relevant states: WAIT_FOR_REGISTRATION else if("AT+CSTT=apn" == command) { reply = "AT+CSTT\r\n\r\nOK\r"; } // Relevant states: SET_APN else if("AT+CIPSTATUS" == command) { reply = ""; } // Relevant states: START_GPRS, WAIT_FOR_UDP else if("AT+CIICR" == command) { reply = "AT+CIICR\r\n\r\nOK\r\n"; } // Relevant states: START_GPRS else if("AT+CIFSR" == command) { reply = "AT+CIFSR\r\n\r\n172.16.101.199\r\n"; } // Relevant States: GET_IP else if("AT+CIPSTART" == command) { reply = "AT+CIPSTART=\"UDP\",\"0.0.0.0\",\"9999\"\r\n\r\nOK\r\n\r\nCONNECT OK\r\n"; } // Relevant states: OPEN_UDP fixme command probably wrong else if("AT+CIPSEND=3" == command) { reply = "AT+CIPSEND=3\r\n\r\n>"; } // Relevant states: SENDING else if("123" == command) { reply = "123\r\nSEND OK\r\n"; } // Relevant states: SENDING else if("" == command) { reply = ""; } // Relevant states: else if("" == command) { reply = ""; } // Relevant states: } else if(collectingCommand) { command += c; } } if(verbose) { if(isprint(c)) { fprintf(stderr, "<%c\n", c); } else { fprintf(stderr, "< %d\n", (int)c); } } return(1); } virtual int read() override { if(0 == reply.size()) { return(-1); } const char c = reply[0]; if(verbose) { if(isprint(c)) { fprintf(stderr, ">%c\n", c); } else { fprintf(stderr, "> %d\n", (int)c); } } reply.erase(0, 1); return(c); } virtual int available() override { return(-1); } virtual int peek() override { return(-1); } virtual void flush() override { } }; // Events exposed. bool GoodSimulator::haveSeenCommandStart; } TEST(OTSIM900Link,basicsSimpleSimulator) { // const bool verbose = B1::verbose; srandom(::testing::UnitTest::GetInstance()->random_seed()); // Seed random() for use in simulator; --gtest_shuffle will force it to change. const char SIM900_PIN[] = "1111"; const char SIM900_APN[] = "apn"; const char SIM900_UDP_ADDR[] = "0.0.0.0"; // ORS server const char SIM900_UDP_PORT[] = "9999"; const OTSIM900Link::OTSIM900LinkConfig_t SIM900Config(false, SIM900_PIN, SIM900_APN, SIM900_UDP_ADDR, SIM900_UDP_PORT); const OTRadioLink::OTRadioChannelConfig l0Config(&SIM900Config, true); ASSERT_FALSE(B1::GoodSimulator::haveSeenCommandStart); OTSIM900Link::OTSIM900Link<0, 0, 0, B1::GoodSimulator> l0; EXPECT_TRUE(l0.configure(1, &l0Config)); EXPECT_TRUE(l0.begin()); EXPECT_EQ(OTSIM900Link::GET_STATE, l0._getState()); // Try to hang just by calling poll() repeatedly. for(int i = 0; i < 100; ++i) { l0.poll(); } EXPECT_TRUE(B1::GoodSimulator::haveSeenCommandStart) << "should see some attempt to communicate with SIM900"; EXPECT_LE(OTSIM900Link::WAIT_FOR_REGISTRATION, l0._getState()) << "should make it to at least WAIT_FOR_REGISTRATION"; // ... l0.end(); } <|endoftext|>
<commit_before>#include "recordattendancedlg.h" #include "ui_recordattendancedlg.h" #include <models/trainingmodel.h> RecordAttendanceDlg::RecordAttendanceDlg(QSqlRecord record, QWidget *parent) : QDialog(parent), ui(new Ui::RecordAttendanceDlg) { ui->setupUi(this); attendanceModel = new AttendanceModel(record); ui->treeView->setModel(attendanceModel); connect(ui->btnSave, SIGNAL(clicked()), attendanceModel, SLOT(saveData())); connect(ui->btnSave, SIGNAL(clicked()), this, SLOT(close())); //QString trainingDatetime = new TrainingModel().filter() } RecordAttendanceDlg::~RecordAttendanceDlg() { delete ui; } <commit_msg>Show datetime<commit_after>#include "recordattendancedlg.h" #include "ui_recordattendancedlg.h" #include <QDateTime> #include <QSqlField> #include <models/trainingmodel.h> RecordAttendanceDlg::RecordAttendanceDlg(QSqlRecord record, QWidget *parent) : QDialog(parent), ui(new Ui::RecordAttendanceDlg) { ui->setupUi(this); attendanceModel = new AttendanceModel(record); ui->treeView->setModel(attendanceModel); connect(ui->btnSave, SIGNAL(clicked()), attendanceModel, SLOT(saveData())); connect(ui->btnSave, SIGNAL(clicked()), this, SLOT(close())); QDateTime datetime = record.field("datetime").value().toDateTime(); ui->txtTrainingDatetime->setText(datetime.toString(tr("dd.MM.yyyy h:mm"))); } RecordAttendanceDlg::~RecordAttendanceDlg() { delete ui; } <|endoftext|>
<commit_before>#include "Soldier.h" #include "j1Render.h" #include "j1Textures.h" #include "j1App.h" #include "p2Defs.h" #include "j1Scene.h" #include "j1Input.h" #include "j1Item.h" #include "j1Collision.h" #include "j1EntityElementsScene.h" #include "j1Audio.h" #include "j1Player.h" #include "j1Weapon.h" #include "j1DynamicObjects.h" Soldier::Soldier():NPC() { name = "Soldier"; type = CREATURE; srand(time(NULL)); } Soldier::~Soldier() {} bool Soldier::Awake(pugi::xml_node &conf, uint id) { bool stop_search = false; for (int s_id = conf.attribute("id").as_int(0); stop_search == false; s_id = conf.next_sibling().attribute("id").as_int(0)) { if (id == s_id) { hp = conf.attribute("hp").as_int(0); position.x = conf.attribute("pos_x").as_int(0); position.y = conf.attribute("pos_y").as_int(0); std::string temp = conf.attribute("file").as_string(""); item_id = conf.attribute("item_id").as_int(0); temp = conf.attribute("dir").as_string(""); if (temp == "up") direction = UP; else if (temp == "down") direction = DOWN; else if (temp == "left") direction = LEFT; else direction = RIGHT; movable = conf.attribute("canMove").as_bool(false); destructible = conf.attribute("destructible").as_bool(false); if (destructible == false) { soldier_type = PASSIVE; } else { soldier_type = AGGRESSIVE; } npc_id = id; stop_search = true; } } return true; } bool Soldier::CleanUp() { return true; } void Soldier::OnCollision(Collider* c1, Collider* c2) { if (c1 != nullptr && c2 != nullptr) { //SWORD COLLISION if (c1 == collision_feet && c2->type == COLLIDER_SWORD && c1->callback != nullptr) { if (destructible == true && state != S_HIT) { App->audio->PlayFx(12); knockback_time.Start(); hp--; state = S_HIT; anim_state = S_IDLE; dir_hit = c2->callback->direction; prev_position = position; } } //ARROW COLLISION if (c1 == collision_feet && c2->type == COLLIDER_ARROW && c2->arrow_callback != nullptr) { if (c2->arrow_callback->step == AIR && destructible == true && state != S_HIT) { App->audio->PlayFx(12); knockback_time.Start(); hp--; state = S_HIT; anim_state = S_IDLE; dir_hit = c2->arrow_callback->direction; prev_position = position; c2->arrow_callback->step = IMPACT; // TODO MED -> set step to impact: this will reproduce the impact animation and, when finished, set step to DIE. } } //DYNOBJECT COLLISION if (c1 == collision_feet && c2->type == COLLIDER_DYNOBJECT && c2->callback != nullptr) { if (((DynamicObjects*)c2->callback)->GetState() == D_AIR) { App->audio->PlayFx(12); knockback_time.Start(); hp -= 2; // TODO LOW -> set attack dmg to each type of dynobject. state = S_HIT; anim_state = S_IDLE; dir_hit = c2->callback->direction; prev_position = position; ((DynamicObjects*)c2->callback)->SetState(D_DYING); } } } } bool Soldier::Start() { if (soldier_type == AGGRESSIVE) { offset_x = 8; offset_y = 15; state = S_IDLE; anim_state = S_IDLE; speed = 40; timetoplay = SDL_GetTicks(); reset_distance = false; reset_run = true; radar = 75; chase_speed = 50; } else if (soldier_type == PASSIVE) { offset_x = 8; offset_y = 15; anim_state = S_GUARD; } //Set collider collision_feet = App->collision->AddCollider({ position.x - offset_x, position.y - offset_y, 16, 15 }, COLLIDER_ENEMY, this); //Get the animations animation = *App->anim_manager->GetAnimStruct(SOLDIER); return true; } bool Soldier::Update(float dt) { BROFILER_CATEGORY("DoUpdate_Soldier", Profiler::Color::Pink); // STATE MACHINE ------------------ if (App->scene->gamestate == INGAME) { if (soldier_type == AGGRESSIVE) { switch (state) { case S_IDLE: { CheckPlayerPos(); Idle(); break; } case S_WALKING: { CheckPlayerPos(); Walking(dt); break; } case S_DYING: { Die(); break; } case S_HIT: { Movebyhit(dt); break; } case S_CHASING: { CheckPlayerPos(); Chase(dt); break; } case S_ATTACKING: { Attack(); break; } default: { break; } } } collision_feet->SetPos(position.x - offset_x, position.y - offset_y); } else if (App->scene->gamestate == INMENU) { } /*else if (App->scene->gamestate == TIMETOPLAY) { if (SDL_GetTicks() - timetoplay > 1000) { App->scene->gamestate = INGAME; } }*/ return true; } void Soldier::Draw() { BROFILER_CATEGORY("Draw_SOLDIER", Profiler::Color::Yellow); //App->anim_manager->Drawing_Manager(state, direction, position, 6); if (direction == UP) { anim_rect = animation.anim[anim_state].North_action.GetCurrentFrame(); pivot = animation.anim[anim_state].North_action.GetCurrentOffset(); } else if (direction == DOWN) { anim_rect = animation.anim[anim_state].South_action.GetCurrentFrame(); pivot = animation.anim[anim_state].South_action.GetCurrentOffset(); } else if (direction == LEFT) { anim_rect = animation.anim[anim_state].West_action.GetCurrentFrame(); pivot = animation.anim[anim_state].West_action.GetCurrentOffset(); } else if (direction == RIGHT) { anim_rect = animation.anim[anim_state].East_action.GetCurrentFrame(); pivot = animation.anim[anim_state].East_action.GetCurrentOffset(); } App->render->Blit(animation.graphics, position.x - pivot.x, position.y - pivot.y, &anim_rect); } bool Soldier::CheckPlayerPos() { int distance_player = App->scene->player->position.DistanceTo(position); if (distance_player <= radar && App->scene->player->invincible_timer.ReadSec() >= 1) { state = S_CHASING; anim_state = S_WALKING; } else { state = S_IDLE; anim_state = S_IDLE; } return true; } bool Soldier::Idle() { if (movable) { if (reset_run) { timetorun = SDL_GetTicks(); reset_run = false; } else { if (SDL_GetTicks() - timetorun > 2000) { int direc_select = rand() % 4 + 1; if (direc_select == 1) { direction = UP; } else if (direc_select == 2) { direction = DOWN; } else if (direc_select == 3) { direction = LEFT; } else if (direc_select == 4) { direction = RIGHT; } state = S_WALKING; anim_state = S_WALKING; reset_distance = true; } } } return true; } bool Soldier::Walking(float dt) { walking = false; if (reset_distance) { distance = rand() % 100 + 20; dis_moved = 0; reset_distance = false; } Move(dt); if(dis_moved >= distance) { walking = false; reset_run = true; } if (walking == false) { state = S_IDLE; anim_state = S_IDLE; } else { state = S_WALKING; anim_state = S_WALKING; } return true; } bool Soldier::Move(float dt) { if (direction == LEFT) { if (App->map->MovementCost(collision_feet->rect.x - ceil(speed*dt), collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, LEFT) == 0) { position.x -= ceil(speed*dt); dis_moved++; } else { dis_moved++; } walking = true; } if (direction == RIGHT) { if (App->map->MovementCost(collision_feet->rect.x + collision_feet->rect.w + ceil(speed*dt), collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, RIGHT) == 0) { position.x += ceil(speed*dt); dis_moved++; } else { dis_moved++; } walking = true; } if (direction == UP) { if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y - ceil(speed*dt), collision_feet->rect.w, collision_feet->rect.h, UP) == 0) { position.y -= ceil(speed*dt); dis_moved++; } else { dis_moved++; } walking = true; } if (direction == DOWN) { if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y + collision_feet->rect.h + ceil(speed*dt), collision_feet->rect.w, collision_feet->rect.h, DOWN) == 0) { position.y += ceil(speed*dt); dis_moved++; } else { dis_moved++; } walking = true; } return true; } bool Soldier::Chase(float dt) { //path.clear(); //attack_time.Start(); if (App->scene->player->GetState() != L_HIT) { iPoint player_pos = App->map->WorldToMap(App->scene->player->position.x, App->scene->player->position.y); GoTo(player_pos, ceil(dt*chase_speed)); Orientate(); } return true; } bool Soldier::Attack() { return true; } bool Soldier::Die() { App->audio->PlayFx(11); if (item_id != 0) { App->entity_elements->CreateItem(item_id, position); } App->entity_elements->DeleteEnemy(this); return true; } bool Soldier::Movebyhit(float dt) { if (hp <= 0) { state = S_DYING; anim_state = S_IDLE; return true; } if (knockback_time.ReadSec() >= 0.2) { state = S_CHASING; anim_state = S_WALKING; return true; } if (dir_hit == UP) { if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y - ceil(240*dt), collision_feet->rect.w, collision_feet->rect.h, UP) == 0) { position.y -= ceil(240 * dt); } } else if (dir_hit == DOWN) { if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y + collision_feet->rect.h + ceil(240 * dt), collision_feet->rect.w, collision_feet->rect.h, DOWN) == 0) { position.y += ceil(240 * dt); } } else if (dir_hit == LEFT) { if (App->map->MovementCost(collision_feet->rect.x - ceil(240 * dt), collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, LEFT) == 0) { position.x -= ceil(240 * dt); } } else if (dir_hit == RIGHT) { if (App->map->MovementCost(collision_feet->rect.x + collision_feet->rect.w + ceil(240 * dt), collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, RIGHT) == 0) { position.x += ceil(240 * dt); } } /*if (position.x > (prev_position.x + 65) || position.x < (prev_position.x + 65) || position.y >(prev_position.y + 65) || position.y < (prev_position.y + 65)) { state = L_IDLE; }*/ return true; } SoldierState Soldier::GetState() const { return state; } void Soldier::SetState(SoldierState s_state) { state = s_state; } void Soldier::SetAnimState(SoldierState a_state) { anim_state = a_state; } SoldierType Soldier::GetType() const { return soldier_type; } <commit_msg>Soldier collision bug fixed<commit_after>#include "Soldier.h" #include "j1Render.h" #include "j1Textures.h" #include "j1App.h" #include "p2Defs.h" #include "j1Scene.h" #include "j1Input.h" #include "j1Item.h" #include "j1Collision.h" #include "j1EntityElementsScene.h" #include "j1Audio.h" #include "j1Player.h" #include "j1Weapon.h" #include "j1DynamicObjects.h" Soldier::Soldier():NPC() { name = "Soldier"; type = CREATURE; srand(time(NULL)); } Soldier::~Soldier() {} bool Soldier::Awake(pugi::xml_node &conf, uint id) { bool stop_search = false; for (int s_id = conf.attribute("id").as_int(0); stop_search == false; s_id = conf.next_sibling().attribute("id").as_int(0)) { if (id == s_id) { hp = conf.attribute("hp").as_int(0); position.x = conf.attribute("pos_x").as_int(0); position.y = conf.attribute("pos_y").as_int(0); std::string temp = conf.attribute("file").as_string(""); item_id = conf.attribute("item_id").as_int(0); temp = conf.attribute("dir").as_string(""); if (temp == "up") direction = UP; else if (temp == "down") direction = DOWN; else if (temp == "left") direction = LEFT; else direction = RIGHT; movable = conf.attribute("canMove").as_bool(false); destructible = conf.attribute("destructible").as_bool(false); if (destructible == false) { soldier_type = PASSIVE; } else { soldier_type = AGGRESSIVE; } npc_id = id; stop_search = true; } } return true; } bool Soldier::CleanUp() { return true; } void Soldier::OnCollision(Collider* c1, Collider* c2) { if (c1 != nullptr && c2 != nullptr) { //SWORD COLLISION if (c1 == collision_feet && c2->type == COLLIDER_SWORD && c1->callback != nullptr) { if (destructible == true && state != S_HIT) { App->audio->PlayFx(12); knockback_time.Start(); hp--; state = S_HIT; anim_state = S_IDLE; dir_hit = c2->callback->direction; prev_position = position; } } //ARROW COLLISION if (c1 == collision_feet && c2->type == COLLIDER_ARROW && c2->arrow_callback != nullptr) { if (c2->arrow_callback->step == AIR && destructible == true && state != S_HIT) { App->audio->PlayFx(12); knockback_time.Start(); hp--; state = S_HIT; anim_state = S_IDLE; dir_hit = c2->arrow_callback->direction; prev_position = position; c2->arrow_callback->step = IMPACT; // TODO MED -> set step to impact: this will reproduce the impact animation and, when finished, set step to DIE. } } //DYNOBJECT COLLISION if (c1 == collision_feet && c2->type == COLLIDER_DYNOBJECT && c2->callback != nullptr) { if (((DynamicObjects*)c2->callback)->GetState() == D_AIR) { App->audio->PlayFx(12); knockback_time.Start(); hp -= 2; // TODO LOW -> set attack dmg to each type of dynobject. state = S_HIT; anim_state = S_IDLE; dir_hit = c2->callback->direction; prev_position = position; ((DynamicObjects*)c2->callback)->SetState(D_DYING); } } } } bool Soldier::Start() { if (soldier_type == AGGRESSIVE) { offset_x = 8; offset_y = 15; state = S_IDLE; anim_state = S_IDLE; speed = 40; timetoplay = SDL_GetTicks(); reset_distance = false; reset_run = true; radar = 75; chase_speed = 50; } else if (soldier_type == PASSIVE) { offset_x = 8; offset_y = 15; anim_state = S_GUARD; } //Set collider collision_feet = App->collision->AddCollider({ position.x - offset_x, position.y - offset_y, 16, 15 }, COLLIDER_ENEMY, this); //Get the animations animation = *App->anim_manager->GetAnimStruct(SOLDIER); return true; } bool Soldier::Update(float dt) { BROFILER_CATEGORY("DoUpdate_Soldier", Profiler::Color::Pink); // STATE MACHINE ------------------ if (App->scene->gamestate == INGAME) { if (soldier_type == AGGRESSIVE) { switch (state) { case S_IDLE: { CheckPlayerPos(); Idle(); break; } case S_WALKING: { CheckPlayerPos(); Walking(dt); break; } case S_DYING: { Die(); break; } case S_HIT: { Movebyhit(dt); break; } case S_CHASING: { CheckPlayerPos(); Chase(dt); break; } case S_ATTACKING: { Attack(); break; } default: { break; } } } if (collision_feet != nullptr) { collision_feet->SetPos(position.x - offset_x, position.y - offset_y); } } else if (App->scene->gamestate == INMENU) { } /*else if (App->scene->gamestate == TIMETOPLAY) { if (SDL_GetTicks() - timetoplay > 1000) { App->scene->gamestate = INGAME; } }*/ return true; } void Soldier::Draw() { BROFILER_CATEGORY("Draw_SOLDIER", Profiler::Color::Yellow); //App->anim_manager->Drawing_Manager(state, direction, position, 6); if (direction == UP) { anim_rect = animation.anim[anim_state].North_action.GetCurrentFrame(); pivot = animation.anim[anim_state].North_action.GetCurrentOffset(); } else if (direction == DOWN) { anim_rect = animation.anim[anim_state].South_action.GetCurrentFrame(); pivot = animation.anim[anim_state].South_action.GetCurrentOffset(); } else if (direction == LEFT) { anim_rect = animation.anim[anim_state].West_action.GetCurrentFrame(); pivot = animation.anim[anim_state].West_action.GetCurrentOffset(); } else if (direction == RIGHT) { anim_rect = animation.anim[anim_state].East_action.GetCurrentFrame(); pivot = animation.anim[anim_state].East_action.GetCurrentOffset(); } App->render->Blit(animation.graphics, position.x - pivot.x, position.y - pivot.y, &anim_rect); } bool Soldier::CheckPlayerPos() { int distance_player = App->scene->player->position.DistanceTo(position); if (distance_player <= radar && App->scene->player->invincible_timer.ReadSec() >= 1) { state = S_CHASING; anim_state = S_WALKING; } else { state = S_IDLE; anim_state = S_IDLE; } return true; } bool Soldier::Idle() { if (movable) { if (reset_run) { timetorun = SDL_GetTicks(); reset_run = false; } else { if (SDL_GetTicks() - timetorun > 2000) { int direc_select = rand() % 4 + 1; if (direc_select == 1) { direction = UP; } else if (direc_select == 2) { direction = DOWN; } else if (direc_select == 3) { direction = LEFT; } else if (direc_select == 4) { direction = RIGHT; } state = S_WALKING; anim_state = S_WALKING; reset_distance = true; } } } return true; } bool Soldier::Walking(float dt) { walking = false; if (reset_distance) { distance = rand() % 100 + 20; dis_moved = 0; reset_distance = false; } Move(dt); if(dis_moved >= distance) { walking = false; reset_run = true; } if (walking == false) { state = S_IDLE; anim_state = S_IDLE; } else { state = S_WALKING; anim_state = S_WALKING; } return true; } bool Soldier::Move(float dt) { if (direction == LEFT) { if (App->map->MovementCost(collision_feet->rect.x - ceil(speed*dt), collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, LEFT) == 0) { position.x -= ceil(speed*dt); dis_moved++; } else { dis_moved++; } walking = true; } if (direction == RIGHT) { if (App->map->MovementCost(collision_feet->rect.x + collision_feet->rect.w + ceil(speed*dt), collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, RIGHT) == 0) { position.x += ceil(speed*dt); dis_moved++; } else { dis_moved++; } walking = true; } if (direction == UP) { if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y - ceil(speed*dt), collision_feet->rect.w, collision_feet->rect.h, UP) == 0) { position.y -= ceil(speed*dt); dis_moved++; } else { dis_moved++; } walking = true; } if (direction == DOWN) { if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y + collision_feet->rect.h + ceil(speed*dt), collision_feet->rect.w, collision_feet->rect.h, DOWN) == 0) { position.y += ceil(speed*dt); dis_moved++; } else { dis_moved++; } walking = true; } return true; } bool Soldier::Chase(float dt) { //path.clear(); //attack_time.Start(); if (App->scene->player->GetState() != L_HIT) { iPoint player_pos = App->map->WorldToMap(App->scene->player->position.x, App->scene->player->position.y); GoTo(player_pos, ceil(dt*chase_speed)); Orientate(); } return true; } bool Soldier::Attack() { return true; } bool Soldier::Die() { App->audio->PlayFx(11); if (item_id != 0) { App->entity_elements->CreateItem(item_id, position); } App->entity_elements->DeleteEnemy(this); return true; } bool Soldier::Movebyhit(float dt) { if (hp <= 0) { state = S_DYING; anim_state = S_IDLE; return true; } if (knockback_time.ReadSec() >= 0.2) { state = S_CHASING; anim_state = S_WALKING; return true; } if (dir_hit == UP) { if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y - ceil(240*dt), collision_feet->rect.w, collision_feet->rect.h, UP) == 0) { position.y -= ceil(240 * dt); } } else if (dir_hit == DOWN) { if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y + collision_feet->rect.h + ceil(240 * dt), collision_feet->rect.w, collision_feet->rect.h, DOWN) == 0) { position.y += ceil(240 * dt); } } else if (dir_hit == LEFT) { if (App->map->MovementCost(collision_feet->rect.x - ceil(240 * dt), collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, LEFT) == 0) { position.x -= ceil(240 * dt); } } else if (dir_hit == RIGHT) { if (App->map->MovementCost(collision_feet->rect.x + collision_feet->rect.w + ceil(240 * dt), collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, RIGHT) == 0) { position.x += ceil(240 * dt); } } /*if (position.x > (prev_position.x + 65) || position.x < (prev_position.x + 65) || position.y >(prev_position.y + 65) || position.y < (prev_position.y + 65)) { state = L_IDLE; }*/ return true; } SoldierState Soldier::GetState() const { return state; } void Soldier::SetState(SoldierState s_state) { state = s_state; } void Soldier::SetAnimState(SoldierState a_state) { anim_state = a_state; } SoldierType Soldier::GetType() const { return soldier_type; } <|endoftext|>
<commit_before>#include<bits/stdc++.h> #include<random> #include<chrono> #define ui unsigned int using namespace std; int main() { ui n=1000,d=5,epsi,m,l,s; cout<<"Enter the number of Nodes (n) where n > 49 : "<<endl; cin>>n; assert(n>49); cout<<"Enter the degree of each node (d) where d > 3 : "<<endl; cin>>d; assert(d > 3); cout<<"Enter the value of epsilon (epsi) where 0 < epsi < 1 : "<<endl; cin>>epsi; assert(epsi>0 && epsi<1); cout<<"Enter the value to repeat the loop (s) where s>=48/epsi : "<<endl; cin>>s; assert(s>=48/epsi); cout<<"Enter the no of random walks (m) where m>=s*12*sqrt(n)/(epsi^2) : "<<endl; cin>>m; assert(m>=(s*12*sqrt(n)/pow(epsi,2))); cout<<"Enter the length of random walk (l) where l>=16*(d^2)*ln(n/epsi) : "<<endl; cin>>l; assert(l>=(16*(d^2)*ln(n/epsi))); /**************************************************************/ /* Generating Random Graph */ /* */ /**************************************************************/ unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine generator (seed); std::uniform_int_distribution<ui> distribution(1,n); vector<set <ui> > G(n+1); for(unsigned int i=1;i<=n;++i) { while(G[i].size()!=5) { ui neighbour; neighbour = distribution(generator); if(G[neighbour].size()!=5) auto newno = G[i].insert(neighbour); if(newno.second==true) G[neighbour].insert(i); } } for(ui i=1;i<=n;++i) { cout<<"Node "<<i<<": " ; for(auto it = G[i].begin(); it != G[i].end();++it) { cout<<" "<<*it; } cout<<endl; } /**************************************************************/ /* Random Walks & Expansion Tester */ /* */ /**************************************************************/ ui s=50; distribution.reset(); while(s--) { ui v; v = distribution(generator); vector< ui> pairs1; for(ui m=1; m<=(sqrt(n)); ++m) { ui w=v; std::uniform_int_distribution<ui> dVertex (1,5); for(ui l=1; l<= log2(n);++l) { auto it=G[w].begin(); w = dVertex(generator); while(w--) { it++; } w=*it; } pairs1.push_back(w); } sort(pairs1.begin(),pairs1.end()); ui collision= pairs1.size(); vector<ui>::iterator it; it = unique (pairs1.begin(), pairs1.end()); pairs1.resize(distance(pairs1.begin(),it) ); collision = collision- pairs1.size(); if(collision < (((sqrt(n))*((sqrt(n))-1))/(2*n))) {cout<<"Reject"<<endl;return 0;} } cout<<"Accept"<<endl; return 0; } <commit_msg>Update TestingExpansion.cpp<commit_after>#include<bits/stdc++.h> #include<random> #include<chrono> #define ui unsigned int using namespace std; int main() { ui n=1000,d=5,m,l,s; double epsi; cout<<"Enter the number of Nodes (n) where n > 49 : "<<endl; cin>>n; assert(n>49); cout<<"Enter the degree of each node (d) where d > 3 : "<<endl; cin>>d; assert(d > 3); cout<<"Enter the value of epsilon (epsi) where 0 < epsi < 1 : "<<endl; cin>>epsi; assert(epsi>0 && epsi<1); cout<<"Enter the value to repeat the loop (s) where s>=48/epsi : "<<endl; cin>>s; assert(s>=48/epsi); cout<<"Enter the no of random walks (m) where m>=s*12*sqrt(n)/(epsi^2) : "<<endl; cin>>m; assert(m>=(s*12*sqrt(n)/pow(epsi,2))); cout<<"Enter the length of random walk (l) where l>=16*(d^2)*ln(n/epsi) : "<<endl; cin>>l; assert(l>=(16*(d^2)*ln(n/epsi))); /**************************************************************/ /* Generating Random Graph */ /* */ /**************************************************************/ unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine generator (seed); std::uniform_int_distribution<ui> distribution(1,n); vector<set <ui> > G(n+1); for(unsigned int i=1;i<=n;++i) { while(G[i].size()!=5) { ui neighbour; neighbour = distribution(generator); if(G[neighbour].size()!=5) auto newno = G[i].insert(neighbour); if(newno.second==true) G[neighbour].insert(i); } } for(ui i=1;i<=n;++i) { cout<<"Node "<<i<<": " ; for(auto it = G[i].begin(); it != G[i].end();++it) { cout<<" "<<*it; } cout<<endl; } /**************************************************************/ /* Random Walks & Expansion Tester */ /* */ /**************************************************************/ ui s=50; distribution.reset(); while(s--) { ui v; v = distribution(generator); vector< ui> pairs1; for(ui m=1; m<=(sqrt(n)); ++m) { ui w=v; std::uniform_int_distribution<ui> dVertex (1,5); for(ui l=1; l<= log2(n);++l) { auto it=G[w].begin(); w = dVertex(generator); while(w--) { it++; } w=*it; } pairs1.push_back(w); } sort(pairs1.begin(),pairs1.end()); ui collision= pairs1.size(); vector<ui>::iterator it; it = unique (pairs1.begin(), pairs1.end()); pairs1.resize(distance(pairs1.begin(),it) ); collision = collision- pairs1.size(); if(collision < (((sqrt(n))*((sqrt(n))-1))/(2*n))) {cout<<"Reject"<<endl;return 0;} } cout<<"Accept"<<endl; return 0; } <|endoftext|>
<commit_before>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include "SceneManager.h" #include "Scene.h" namespace ouzel { namespace scene { SceneManager::SceneManager() { } SceneManager::~SceneManager() { } void SceneManager::setScene(const ScenePtr& newScene) { if (scene != newScene) { if (locked) { nextScene = scene; } else { scene = newScene; if (scene) { scene->recalculateProjection(); } } } } void SceneManager::draw() { if (scene) { lock(); scene->draw(); unlock(); } } void SceneManager::recalculateProjection() { if (scene) { scene->recalculateProjection(); } } void SceneManager::lock() { ++locked; } void SceneManager::unlock() { if (--locked == 0 && nextScene) { setScene(nextScene); nextScene.reset(); } } } // namespace scene } // namespace ouzel <commit_msg>Fix scene replace<commit_after>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include "SceneManager.h" #include "Scene.h" namespace ouzel { namespace scene { SceneManager::SceneManager() { } SceneManager::~SceneManager() { } void SceneManager::setScene(const ScenePtr& newScene) { if (scene != newScene) { if (locked) { nextScene = newScene; } else { scene = newScene; if (scene) { scene->recalculateProjection(); } } } } void SceneManager::draw() { if (scene) { lock(); scene->draw(); unlock(); } } void SceneManager::recalculateProjection() { if (scene) { scene->recalculateProjection(); } } void SceneManager::lock() { ++locked; } void SceneManager::unlock() { if (--locked == 0 && nextScene) { setScene(nextScene); nextScene.reset(); } } } // namespace scene } // namespace ouzel <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2009 Hauke Heibel <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "main.h" #include <Eigen/Core> #include <Eigen/Geometry> #include <Eigen/LU> // required for MatrixBase::determinant #include <Eigen/SVD> // required for SVD using namespace Eigen; // Constructs a random matrix from the unitary group U(size). template <typename T> Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> randMatrixUnitary(int size) { typedef T Scalar; typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> MatrixType; MatrixType Q; int max_tries = 40; double is_unitary = false; while (!is_unitary && max_tries > 0) { // initialize random matrix Q = MatrixType::Random(size, size); // orthogonalize columns using the Gram-Schmidt algorithm for (int col = 0; col < size; ++col) { typename MatrixType::ColXpr colVec = Q.col(col); for (int prevCol = 0; prevCol < col; ++prevCol) { typename MatrixType::ColXpr prevColVec = Q.col(prevCol); colVec -= colVec.dot(prevColVec)*prevColVec; } Q.col(col) = colVec.normalized(); } // this additional orthogonalization is not necessary in theory but should enhance // the numerical orthogonality of the matrix for (int row = 0; row < size; ++row) { typename MatrixType::RowXpr rowVec = Q.row(row); for (int prevRow = 0; prevRow < row; ++prevRow) { typename MatrixType::RowXpr prevRowVec = Q.row(prevRow); rowVec -= rowVec.dot(prevRowVec)*prevRowVec; } Q.row(row) = rowVec.normalized(); } // final check is_unitary = Q.isUnitary(); --max_tries; } if (max_tries == 0) eigen_assert(false && "randMatrixUnitary: Could not construct unitary matrix!"); return Q; } // Constructs a random matrix from the special unitary group SU(size). template <typename T> Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> randMatrixSpecialUnitary(int size) { typedef T Scalar; typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> MatrixType; // initialize unitary matrix MatrixType Q = randMatrixUnitary<Scalar>(size); // tweak the first column to make the determinant be 1 Q.col(0) *= numext::conj(Q.determinant()); return Q; } template <typename MatrixType> void run_test(int dim, int num_elements) { using std::abs; typedef typename internal::traits<MatrixType>::Scalar Scalar; typedef Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> MatrixX; typedef Matrix<Scalar, Eigen::Dynamic, 1> VectorX; // MUST be positive because in any other case det(cR_t) may become negative for // odd dimensions! const Scalar c = abs(internal::random<Scalar>()); MatrixX R = randMatrixSpecialUnitary<Scalar>(dim); VectorX t = Scalar(50)*VectorX::Random(dim,1); MatrixX cR_t = MatrixX::Identity(dim+1,dim+1); cR_t.block(0,0,dim,dim) = c*R; cR_t.block(0,dim,dim,1) = t; MatrixX src = MatrixX::Random(dim+1, num_elements); src.row(dim) = Matrix<Scalar, 1, Dynamic>::Constant(num_elements, Scalar(1)); MatrixX dst = cR_t*src; MatrixX cR_t_umeyama = umeyama(src.block(0,0,dim,num_elements), dst.block(0,0,dim,num_elements)); const Scalar error = ( cR_t_umeyama*src - dst ).norm() / dst.norm(); VERIFY(error < Scalar(40)*std::numeric_limits<Scalar>::epsilon()); } template<typename Scalar, int Dimension> void run_fixed_size_test(int num_elements) { using std::abs; typedef Matrix<Scalar, Dimension+1, Dynamic> MatrixX; typedef Matrix<Scalar, Dimension+1, Dimension+1> HomMatrix; typedef Matrix<Scalar, Dimension, Dimension> FixedMatrix; typedef Matrix<Scalar, Dimension, 1> FixedVector; const int dim = Dimension; // MUST be positive because in any other case det(cR_t) may become negative for // odd dimensions! const Scalar c = abs(internal::random<Scalar>()); FixedMatrix R = randMatrixSpecialUnitary<Scalar>(dim); FixedVector t = Scalar(50)*FixedVector::Random(dim,1); HomMatrix cR_t = HomMatrix::Identity(dim+1,dim+1); cR_t.block(0,0,dim,dim) = c*R; cR_t.block(0,dim,dim,1) = t; MatrixX src = MatrixX::Random(dim+1, num_elements); src.row(dim) = Matrix<Scalar, 1, Dynamic>::Constant(num_elements, Scalar(1)); MatrixX dst = cR_t*src; Block<MatrixX, Dimension, Dynamic> src_block(src,0,0,dim,num_elements); Block<MatrixX, Dimension, Dynamic> dst_block(dst,0,0,dim,num_elements); HomMatrix cR_t_umeyama = umeyama(src_block, dst_block); const Scalar error = ( cR_t_umeyama*src - dst ).array().square().sum(); VERIFY(error < Scalar(10)*std::numeric_limits<Scalar>::epsilon()); } void test_umeyama() { for (int i=0; i<g_repeat; ++i) { const int num_elements = internal::random<int>(40,500); // works also for dimensions bigger than 3... for (int dim=2; dim<8; ++dim) { CALL_SUBTEST_1(run_test<MatrixXd>(dim, num_elements)); CALL_SUBTEST_2(run_test<MatrixXf>(dim, num_elements)); } CALL_SUBTEST_3((run_fixed_size_test<float, 2>(num_elements))); CALL_SUBTEST_4((run_fixed_size_test<float, 3>(num_elements))); CALL_SUBTEST_5((run_fixed_size_test<float, 4>(num_elements))); CALL_SUBTEST_6((run_fixed_size_test<double, 2>(num_elements))); CALL_SUBTEST_7((run_fixed_size_test<double, 3>(num_elements))); CALL_SUBTEST_8((run_fixed_size_test<double, 4>(num_elements))); } // Those two calls don't compile and result in meaningful error messages! // umeyama(MatrixXcf(),MatrixXcf()); // umeyama(MatrixXcd(),MatrixXcd()); } <commit_msg>Relaxed umeyama test. Problem was ill-posed if linear part was scaled with very small number. This should fix bug 744.<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2009 Hauke Heibel <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "main.h" #include <Eigen/Core> #include <Eigen/Geometry> #include <Eigen/LU> // required for MatrixBase::determinant #include <Eigen/SVD> // required for SVD using namespace Eigen; // Constructs a random matrix from the unitary group U(size). template <typename T> Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> randMatrixUnitary(int size) { typedef T Scalar; typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> MatrixType; MatrixType Q; int max_tries = 40; double is_unitary = false; while (!is_unitary && max_tries > 0) { // initialize random matrix Q = MatrixType::Random(size, size); // orthogonalize columns using the Gram-Schmidt algorithm for (int col = 0; col < size; ++col) { typename MatrixType::ColXpr colVec = Q.col(col); for (int prevCol = 0; prevCol < col; ++prevCol) { typename MatrixType::ColXpr prevColVec = Q.col(prevCol); colVec -= colVec.dot(prevColVec)*prevColVec; } Q.col(col) = colVec.normalized(); } // this additional orthogonalization is not necessary in theory but should enhance // the numerical orthogonality of the matrix for (int row = 0; row < size; ++row) { typename MatrixType::RowXpr rowVec = Q.row(row); for (int prevRow = 0; prevRow < row; ++prevRow) { typename MatrixType::RowXpr prevRowVec = Q.row(prevRow); rowVec -= rowVec.dot(prevRowVec)*prevRowVec; } Q.row(row) = rowVec.normalized(); } // final check is_unitary = Q.isUnitary(); --max_tries; } if (max_tries == 0) eigen_assert(false && "randMatrixUnitary: Could not construct unitary matrix!"); return Q; } // Constructs a random matrix from the special unitary group SU(size). template <typename T> Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> randMatrixSpecialUnitary(int size) { typedef T Scalar; typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> MatrixType; // initialize unitary matrix MatrixType Q = randMatrixUnitary<Scalar>(size); // tweak the first column to make the determinant be 1 Q.col(0) *= numext::conj(Q.determinant()); return Q; } template <typename MatrixType> void run_test(int dim, int num_elements) { using std::abs; typedef typename internal::traits<MatrixType>::Scalar Scalar; typedef Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> MatrixX; typedef Matrix<Scalar, Eigen::Dynamic, 1> VectorX; // MUST be positive because in any other case det(cR_t) may become negative for // odd dimensions! const Scalar c = abs(internal::random<Scalar>()); MatrixX R = randMatrixSpecialUnitary<Scalar>(dim); VectorX t = Scalar(50)*VectorX::Random(dim,1); MatrixX cR_t = MatrixX::Identity(dim+1,dim+1); cR_t.block(0,0,dim,dim) = c*R; cR_t.block(0,dim,dim,1) = t; MatrixX src = MatrixX::Random(dim+1, num_elements); src.row(dim) = Matrix<Scalar, 1, Dynamic>::Constant(num_elements, Scalar(1)); MatrixX dst = cR_t*src; MatrixX cR_t_umeyama = umeyama(src.block(0,0,dim,num_elements), dst.block(0,0,dim,num_elements)); const Scalar error = ( cR_t_umeyama*src - dst ).norm() / dst.norm(); VERIFY(error < Scalar(40)*std::numeric_limits<Scalar>::epsilon()); } template<typename Scalar, int Dimension> void run_fixed_size_test(int num_elements) { using std::abs; typedef Matrix<Scalar, Dimension+1, Dynamic> MatrixX; typedef Matrix<Scalar, Dimension+1, Dimension+1> HomMatrix; typedef Matrix<Scalar, Dimension, Dimension> FixedMatrix; typedef Matrix<Scalar, Dimension, 1> FixedVector; const int dim = Dimension; // MUST be positive because in any other case det(cR_t) may become negative for // odd dimensions! // Also if c is to small compared to t.norm(), problem is ill-posed (cf. Bug 744) const Scalar c = internal::random<Scalar>(0.5, 2.0); FixedMatrix R = randMatrixSpecialUnitary<Scalar>(dim); FixedVector t = Scalar(32)*FixedVector::Random(dim,1); HomMatrix cR_t = HomMatrix::Identity(dim+1,dim+1); cR_t.block(0,0,dim,dim) = c*R; cR_t.block(0,dim,dim,1) = t; MatrixX src = MatrixX::Random(dim+1, num_elements); src.row(dim) = Matrix<Scalar, 1, Dynamic>::Constant(num_elements, Scalar(1)); MatrixX dst = cR_t*src; Block<MatrixX, Dimension, Dynamic> src_block(src,0,0,dim,num_elements); Block<MatrixX, Dimension, Dynamic> dst_block(dst,0,0,dim,num_elements); HomMatrix cR_t_umeyama = umeyama(src_block, dst_block); const Scalar error = ( cR_t_umeyama*src - dst ).squaredNorm(); VERIFY(error < Scalar(16)*std::numeric_limits<Scalar>::epsilon()); } void test_umeyama() { for (int i=0; i<g_repeat; ++i) { const int num_elements = internal::random<int>(40,500); // works also for dimensions bigger than 3... for (int dim=2; dim<8; ++dim) { CALL_SUBTEST_1(run_test<MatrixXd>(dim, num_elements)); CALL_SUBTEST_2(run_test<MatrixXf>(dim, num_elements)); } CALL_SUBTEST_3((run_fixed_size_test<float, 2>(num_elements))); CALL_SUBTEST_4((run_fixed_size_test<float, 3>(num_elements))); CALL_SUBTEST_5((run_fixed_size_test<float, 4>(num_elements))); CALL_SUBTEST_6((run_fixed_size_test<double, 2>(num_elements))); CALL_SUBTEST_7((run_fixed_size_test<double, 3>(num_elements))); CALL_SUBTEST_8((run_fixed_size_test<double, 4>(num_elements))); } // Those two calls don't compile and result in meaningful error messages! // umeyama(MatrixXcf(),MatrixXcf()); // umeyama(MatrixXcd(),MatrixXcd()); } <|endoftext|>
<commit_before>// @(#)root/proof:$Name: $:$Id: TCondor.cxx,v 1.4 2003/09/04 23:19:31 rdm Exp $ // Author: Maarten Ballintijn 06/12/03 /************************************************************************* * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TCondor // // // // Interface to the Condor system. TCondor provides a (partial) API for // // querying and controlling the Condor system, including experimental // // extensions like COD (computing on demand) // // // ////////////////////////////////////////////////////////////////////////// #include "TCondor.h" #include "TList.h" #include "TSystem.h" #include "TObjString.h" #include "TRegexp.h" #include "TProofDebug.h" #include "Riostream.h" ClassImp(TCondorSlave) ClassImp(TCondor) //______________________________________________________________________________ TCondor::TCondor(const char *pool) : fPool(pool), fState(kFree) { // Create Condor interface object. Uses Condor apps since there is no // API yet. fClaims = new TList; // hack our path :-/ TString path = gSystem->Getenv("PATH"); path = "/opt/condor/bin:" + path; gSystem->Setenv("PATH",path); gSystem->Setenv("CONDOR_CONFIG","/opt/condor/etc/condor_config"); } //______________________________________________________________________________ TCondor::~TCondor() { // Cleanup Condor interface. PDB(kCondor,1) Info("~TCondor","fState %d", fState ); if (fState != kFree) { Release(); } delete fClaims; } //______________________________________________________________________________ void TCondor::Print(Option_t * opt) const { cout << "OBJ: " << IsA()->GetName() << "\tPool: \"" << fPool << "\"" << "\tState: " << fState << endl; fClaims->Print(opt); } //______________________________________________________________________________ TCondorSlave *TCondor::ClaimVM(const char *vm, const char * /*cmd*/, Int_t &port) { // Claim a VirtualMachine for PROOF usage. TString claimCmd = Form("condor_cod request -name %s -timeout 10 2>/dev/null", vm ); PDB(kCondor,2) Info("ClaimVM","command: %s", claimCmd.Data()); FILE *pipe = gSystem->OpenPipe(claimCmd, "r"); if (!pipe) { SysError("ClaimVM","cannot run command: %s", claimCmd.Data()); return 0; } TString claimId; TString line; while (line.Gets(pipe)) { PDB(kCondor,3) Info("ClaimVM","line = %s", line.Data()); if (line.BeginsWith("ClaimId = \"")) { line.Remove(0, line.Index("\"")+1); line.Chop(); // remove trailing " claimId = line; PDB(kCondor,1) Info("ClaimVM","claim = '%s'", claimId.Data()); TRegexp r("[0-9]*$"); TString num = line(r); port = 37000 + atoi(num.Data()); PDB(kCondor,1) Info("ClaimVM","port = %d", port); } } Int_t r = gSystem->ClosePipe(pipe); PDB(kCondor,1) Info("ClaimVM","command: %s returned %d", claimCmd.Data(), r); TString jobad("jobad"); FILE *jf = gSystem->TempFilename(jobad); if (jf == 0) return 0; fputs("JobUniverse = 5\n", jf); // vanilla fputs("Cmd = \"/usr/local/root/bin/proofd\"\n", jf); fputs("Iwd = \"/tmp\"\n", jf); fputs("In = \"/dev/null\"\n", jf); fprintf(jf, "Out = \"/tmp/proofd.out.%d\"\n", port); fprintf(jf, "Err = \"/tmp/proofd.err.%d\"\n", port); fprintf(jf, "Args = \"-f -p %d -d 3 /usr/local/root\"\n", port); fclose(jf); TString activateCmd = Form("condor_cod activate -id '%s' -jobad %s", claimId.Data(), jobad.Data() ); PDB(kCondor,2) Info("ClaimVM","command: %s", activateCmd.Data()); pipe = gSystem->OpenPipe(activateCmd, "r"); if (!pipe) { SysError("ClaimVM","cannot run command: %s", activateCmd.Data()); return 0; } while (line.Gets(pipe)) { PDB(kCondor,3) Info("ClaimVM","Activate: line = %s", line.Data()); } r = gSystem->ClosePipe(pipe); PDB(kCondor,1) Info("ClaimVM","command: %s returned %d", activateCmd.Data(), r); gSystem->Unlink(jobad.Data()); // TODO: get info at the start for all nodes ... TCondorSlave *claim = new TCondorSlave; claim->fClaimID = claimId; TString node(vm); node = node.Remove(0, node.Index("@")+1); claim->fHostname = node; claim->fPort = port; if ( !GetVmInfo(vm, claim->fImage, claim->fPerfIdx) ) { // assume vm is gone delete claim; return 0; } return claim; } //______________________________________________________________________________ TList *TCondor::GetVirtualMachines() const { // Get the names of the virtual machines in the pool. // Return a TList of TObjString or 0 in case of failure TString poolopt = fPool ? "" : Form("-pool %s", fPool.Data()); TString cmd = Form("condor_status %s -format \"%%s\\n\" Name", poolopt.Data()); PDB(kCondor,2) Info("GetVirtualMachines","command: %s", cmd.Data()); FILE *pipe = gSystem->OpenPipe(cmd, "r"); if (!pipe) { SysError("GetVirtualMachines","cannot run command: %s", cmd.Data()); return 0; } TString line; TList *l = new TList; while (line.Gets(pipe)) { PDB(kCondor,3) Info("GetVirtualMachines","line = %s", line.Data()); if (line != "") l->Add(new TObjString(line)); } Int_t r = gSystem->ClosePipe(pipe); PDB(kCondor,1) Info("GetVirtualMachines","command: %s returned %d", cmd.Data(), r); return l; } //______________________________________________________________________________ TList *TCondor::Claim(Int_t n, const char *cmd) { if (fState != kFree) { Error("Claim","not in state Free"); return 0; } TList *vms = GetVirtualMachines(); TIter next(vms); TObjString *vm; for(Int_t i=0; i < n && (vm = (TObjString*) next()) != 0; i++ ) { Int_t port = 17000+i; // hard code port for the moment TCondorSlave *claim = ClaimVM(vm->GetName(), cmd, port); if (claim != 0) { fClaims->Add(claim); } } fState = kActive; return fClaims; } //______________________________________________________________________________ Bool_t TCondor::SetState(EState state) { TIter next(fClaims); TCondorSlave *claim; while((claim = (TCondorSlave*) next()) != 0) { TString cmd = Form("condor_cod %s -id '%s'", state == kSuspended ? "suspend" : "resume", claim->fClaimID.Data()); PDB(kCondor,2) Info("SetState","command: %s", cmd.Data()); FILE *pipe = gSystem->OpenPipe(cmd, "r"); if (!pipe) { SysError("SetState","cannot run command: %s", cmd.Data()); return kFALSE; } TString line; while (line.Gets(pipe)) { PDB(kCondor,3) Info("SetState","line = %s", line.Data()); } Int_t r = gSystem->ClosePipe(pipe); PDB(kCondor,1) Info("SetState","command: %s returned %d", cmd.Data(), r); } fState = state; return kTRUE; } //______________________________________________________________________________ Bool_t TCondor::Suspend() { if (fState != kActive) { Error("Suspend","not in state Active"); return kFALSE; } return SetState(kSuspended); } //______________________________________________________________________________ Bool_t TCondor::Resume() { if (fState != kSuspended) { Error("Suspend","not in state Suspended"); return kFALSE; } return SetState(kActive); } //______________________________________________________________________________ Bool_t TCondor::Release() { if (fState == kFree) { Error("Suspend","not in state Active or Suspended"); return kFALSE; } TCondorSlave *claim; while((claim = (TCondorSlave*) fClaims->First()) != 0) { TString cmd = Form("condor_cod release -id '%s'", claim->fClaimID.Data()); PDB(kCondor,2) Info("SetState","command: %s", cmd.Data()); FILE *pipe = gSystem->OpenPipe(cmd, "r"); if (!pipe) { SysError("Release","cannot run command: %s", cmd.Data()); return kFALSE; } TString line; while (line.Gets(pipe)) { PDB(kCondor,3) Info("Release","line = %s", line.Data()); } Int_t r = gSystem->ClosePipe(pipe); PDB(kCondor,1) Info("Release","command: %s returned %d", cmd.Data(), r); fClaims->Remove(claim); delete claim; } fState = kFree; return kTRUE; } //______________________________________________________________________________ Bool_t TCondor::GetVmInfo(const char *vm, TString &image, Int_t &perfidx) const { TString cmd = Form("condor_status -format \"%%d:\" Mips -format \"%%s\\n\" FileSystemDomain " "-const 'Name==\"%s\"'", vm); PDB(kCondor,2) Info("GetVmInfo","command: %s", cmd.Data()); FILE *pipe = gSystem->OpenPipe(cmd, "r"); if (!pipe) { SysError("GetVmInfo","cannot run command: %s", cmd.Data()); return 0; } TString line; while (line.Gets(pipe)) { PDB(kCondor,3) Info("GetVmInfo","line = %s", line.Data()); if (line != "") { TString amips = line(TRegexp("^[0-9]*")); perfidx = atoi(amips); image = line(TRegexp("[^:]+$")); break; } } Int_t r = gSystem->ClosePipe(pipe); PDB(kCondor,1) Info("GetVmInfo","command: %s returned %d", cmd.Data(), r); return kTRUE; } //______________________________________________________________________________ TString TCondor::GetImage(const char *host) const { TString cmd = Form("condor_status -direct %s -format \"Image:%%s\\n\" " "FileSystemDomain", host); PDB(kCondor,2) Info("GetImage","command: %s", cmd.Data()); FILE *pipe = gSystem->OpenPipe(cmd, "r"); if (!pipe) { SysError("GetImage","cannot run command: %s", cmd.Data()); return 0; } TString image; TString line; while (line.Gets(pipe)) { PDB(kCondor,3) Info("GetImage","line = %s", line.Data()); if (line != "") { image = line(TRegexp("[^:]+$")); break; } } Int_t r = gSystem->ClosePipe(pipe); PDB(kCondor,1) Info("GetImage","command: %s returned %d", cmd.Data(), r); return image; } //______________________________________________________________________________ void TCondorSlave::Print(Option_t * /*opt*/ ) const { cout << "OBJ: " << IsA()->GetName() << " " << fHostname << ":" << fPort << " Perf: " << fPerfIdx << " Image: " << fImage << endl; } <commit_msg>change TempFilename() to TempFileName().<commit_after>// @(#)root/proof:$Name: $:$Id: TCondor.cxx,v 1.5 2003/09/23 08:54:50 rdm Exp $ // Author: Maarten Ballintijn 06/12/03 /************************************************************************* * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TCondor // // // // Interface to the Condor system. TCondor provides a (partial) API for // // querying and controlling the Condor system, including experimental // // extensions like COD (computing on demand) // // // ////////////////////////////////////////////////////////////////////////// #include "TCondor.h" #include "TList.h" #include "TSystem.h" #include "TObjString.h" #include "TRegexp.h" #include "TProofDebug.h" #include "Riostream.h" ClassImp(TCondorSlave) ClassImp(TCondor) //______________________________________________________________________________ TCondor::TCondor(const char *pool) : fPool(pool), fState(kFree) { // Create Condor interface object. Uses Condor apps since there is no // API yet. fClaims = new TList; // hack our path :-/ TString path = gSystem->Getenv("PATH"); path = "/opt/condor/bin:" + path; gSystem->Setenv("PATH",path); gSystem->Setenv("CONDOR_CONFIG","/opt/condor/etc/condor_config"); } //______________________________________________________________________________ TCondor::~TCondor() { // Cleanup Condor interface. PDB(kCondor,1) Info("~TCondor","fState %d", fState ); if (fState != kFree) { Release(); } delete fClaims; } //______________________________________________________________________________ void TCondor::Print(Option_t * opt) const { cout << "OBJ: " << IsA()->GetName() << "\tPool: \"" << fPool << "\"" << "\tState: " << fState << endl; fClaims->Print(opt); } //______________________________________________________________________________ TCondorSlave *TCondor::ClaimVM(const char *vm, const char * /*cmd*/, Int_t &port) { // Claim a VirtualMachine for PROOF usage. TString claimCmd = Form("condor_cod request -name %s -timeout 10 2>/dev/null", vm ); PDB(kCondor,2) Info("ClaimVM","command: %s", claimCmd.Data()); FILE *pipe = gSystem->OpenPipe(claimCmd, "r"); if (!pipe) { SysError("ClaimVM","cannot run command: %s", claimCmd.Data()); return 0; } TString claimId; TString line; while (line.Gets(pipe)) { PDB(kCondor,3) Info("ClaimVM","line = %s", line.Data()); if (line.BeginsWith("ClaimId = \"")) { line.Remove(0, line.Index("\"")+1); line.Chop(); // remove trailing " claimId = line; PDB(kCondor,1) Info("ClaimVM","claim = '%s'", claimId.Data()); TRegexp r("[0-9]*$"); TString num = line(r); port = 37000 + atoi(num.Data()); PDB(kCondor,1) Info("ClaimVM","port = %d", port); } } Int_t r = gSystem->ClosePipe(pipe); PDB(kCondor,1) Info("ClaimVM","command: %s returned %d", claimCmd.Data(), r); TString jobad("jobad"); FILE *jf = gSystem->TempFileName(jobad); if (jf == 0) return 0; fputs("JobUniverse = 5\n", jf); // vanilla fputs("Cmd = \"/usr/local/root/bin/proofd\"\n", jf); fputs("Iwd = \"/tmp\"\n", jf); fputs("In = \"/dev/null\"\n", jf); fprintf(jf, "Out = \"/tmp/proofd.out.%d\"\n", port); fprintf(jf, "Err = \"/tmp/proofd.err.%d\"\n", port); fprintf(jf, "Args = \"-f -p %d -d 3 /usr/local/root\"\n", port); fclose(jf); TString activateCmd = Form("condor_cod activate -id '%s' -jobad %s", claimId.Data(), jobad.Data() ); PDB(kCondor,2) Info("ClaimVM","command: %s", activateCmd.Data()); pipe = gSystem->OpenPipe(activateCmd, "r"); if (!pipe) { SysError("ClaimVM","cannot run command: %s", activateCmd.Data()); return 0; } while (line.Gets(pipe)) { PDB(kCondor,3) Info("ClaimVM","Activate: line = %s", line.Data()); } r = gSystem->ClosePipe(pipe); PDB(kCondor,1) Info("ClaimVM","command: %s returned %d", activateCmd.Data(), r); gSystem->Unlink(jobad.Data()); // TODO: get info at the start for all nodes ... TCondorSlave *claim = new TCondorSlave; claim->fClaimID = claimId; TString node(vm); node = node.Remove(0, node.Index("@")+1); claim->fHostname = node; claim->fPort = port; if ( !GetVmInfo(vm, claim->fImage, claim->fPerfIdx) ) { // assume vm is gone delete claim; return 0; } return claim; } //______________________________________________________________________________ TList *TCondor::GetVirtualMachines() const { // Get the names of the virtual machines in the pool. // Return a TList of TObjString or 0 in case of failure TString poolopt = fPool ? "" : Form("-pool %s", fPool.Data()); TString cmd = Form("condor_status %s -format \"%%s\\n\" Name", poolopt.Data()); PDB(kCondor,2) Info("GetVirtualMachines","command: %s", cmd.Data()); FILE *pipe = gSystem->OpenPipe(cmd, "r"); if (!pipe) { SysError("GetVirtualMachines","cannot run command: %s", cmd.Data()); return 0; } TString line; TList *l = new TList; while (line.Gets(pipe)) { PDB(kCondor,3) Info("GetVirtualMachines","line = %s", line.Data()); if (line != "") l->Add(new TObjString(line)); } Int_t r = gSystem->ClosePipe(pipe); PDB(kCondor,1) Info("GetVirtualMachines","command: %s returned %d", cmd.Data(), r); return l; } //______________________________________________________________________________ TList *TCondor::Claim(Int_t n, const char *cmd) { if (fState != kFree) { Error("Claim","not in state Free"); return 0; } TList *vms = GetVirtualMachines(); TIter next(vms); TObjString *vm; for(Int_t i=0; i < n && (vm = (TObjString*) next()) != 0; i++ ) { Int_t port = 17000+i; // hard code port for the moment TCondorSlave *claim = ClaimVM(vm->GetName(), cmd, port); if (claim != 0) { fClaims->Add(claim); } } fState = kActive; return fClaims; } //______________________________________________________________________________ Bool_t TCondor::SetState(EState state) { TIter next(fClaims); TCondorSlave *claim; while((claim = (TCondorSlave*) next()) != 0) { TString cmd = Form("condor_cod %s -id '%s'", state == kSuspended ? "suspend" : "resume", claim->fClaimID.Data()); PDB(kCondor,2) Info("SetState","command: %s", cmd.Data()); FILE *pipe = gSystem->OpenPipe(cmd, "r"); if (!pipe) { SysError("SetState","cannot run command: %s", cmd.Data()); return kFALSE; } TString line; while (line.Gets(pipe)) { PDB(kCondor,3) Info("SetState","line = %s", line.Data()); } Int_t r = gSystem->ClosePipe(pipe); PDB(kCondor,1) Info("SetState","command: %s returned %d", cmd.Data(), r); } fState = state; return kTRUE; } //______________________________________________________________________________ Bool_t TCondor::Suspend() { if (fState != kActive) { Error("Suspend","not in state Active"); return kFALSE; } return SetState(kSuspended); } //______________________________________________________________________________ Bool_t TCondor::Resume() { if (fState != kSuspended) { Error("Suspend","not in state Suspended"); return kFALSE; } return SetState(kActive); } //______________________________________________________________________________ Bool_t TCondor::Release() { if (fState == kFree) { Error("Suspend","not in state Active or Suspended"); return kFALSE; } TCondorSlave *claim; while((claim = (TCondorSlave*) fClaims->First()) != 0) { TString cmd = Form("condor_cod release -id '%s'", claim->fClaimID.Data()); PDB(kCondor,2) Info("SetState","command: %s", cmd.Data()); FILE *pipe = gSystem->OpenPipe(cmd, "r"); if (!pipe) { SysError("Release","cannot run command: %s", cmd.Data()); return kFALSE; } TString line; while (line.Gets(pipe)) { PDB(kCondor,3) Info("Release","line = %s", line.Data()); } Int_t r = gSystem->ClosePipe(pipe); PDB(kCondor,1) Info("Release","command: %s returned %d", cmd.Data(), r); fClaims->Remove(claim); delete claim; } fState = kFree; return kTRUE; } //______________________________________________________________________________ Bool_t TCondor::GetVmInfo(const char *vm, TString &image, Int_t &perfidx) const { TString cmd = Form("condor_status -format \"%%d:\" Mips -format \"%%s\\n\" FileSystemDomain " "-const 'Name==\"%s\"'", vm); PDB(kCondor,2) Info("GetVmInfo","command: %s", cmd.Data()); FILE *pipe = gSystem->OpenPipe(cmd, "r"); if (!pipe) { SysError("GetVmInfo","cannot run command: %s", cmd.Data()); return 0; } TString line; while (line.Gets(pipe)) { PDB(kCondor,3) Info("GetVmInfo","line = %s", line.Data()); if (line != "") { TString amips = line(TRegexp("^[0-9]*")); perfidx = atoi(amips); image = line(TRegexp("[^:]+$")); break; } } Int_t r = gSystem->ClosePipe(pipe); PDB(kCondor,1) Info("GetVmInfo","command: %s returned %d", cmd.Data(), r); return kTRUE; } //______________________________________________________________________________ TString TCondor::GetImage(const char *host) const { TString cmd = Form("condor_status -direct %s -format \"Image:%%s\\n\" " "FileSystemDomain", host); PDB(kCondor,2) Info("GetImage","command: %s", cmd.Data()); FILE *pipe = gSystem->OpenPipe(cmd, "r"); if (!pipe) { SysError("GetImage","cannot run command: %s", cmd.Data()); return 0; } TString image; TString line; while (line.Gets(pipe)) { PDB(kCondor,3) Info("GetImage","line = %s", line.Data()); if (line != "") { image = line(TRegexp("[^:]+$")); break; } } Int_t r = gSystem->ClosePipe(pipe); PDB(kCondor,1) Info("GetImage","command: %s returned %d", cmd.Data(), r); return image; } //______________________________________________________________________________ void TCondorSlave::Print(Option_t * /*opt*/ ) const { cout << "OBJ: " << IsA()->GetName() << " " << fHostname << ":" << fPort << " Perf: " << fPerfIdx << " Image: " << fImage << endl; } <|endoftext|>
<commit_before>/* Resembla: Word-based Japanese similar sentence search library https://github.com/tuem/resembla Copyright 2017 Takashi Uemura 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 __RESEMBLA_REGRESSION_HPP__ #define __RESEMBLA_REGRESSION_HPP__ #include <string> #include <vector> #include <memory> #include <unordered_map> #include <fstream> #include "resembla_interface.hpp" #include "reranker.hpp" #include "regression/feature.hpp" #include "regression/extractor/feature_extractor.hpp" namespace resembla { template<typename ScoreFunction> class ResemblaRegression: public ResemblaInterface { public: ResemblaRegression(size_t max_candidate, std::shared_ptr<FeatureExtractor> feature_extractor, std::shared_ptr<ScoreFunction> score_func, std::string corpus_path = "", size_t feature_col = 2): max_candidate(max_candidate), preprocess(feature_extractor), score_func(score_func), reranker(), preprocess_corpus(!corpus_path.empty()) { if(preprocess_corpus){ loadCorpusFeatures(corpus_path, feature_col); } } void append(const std::string name, const std::shared_ptr<ResemblaInterface> resembla, bool is_primary = true) { resemblas[name] = resembla; if(is_primary && primary_resembla_name.empty()){ primary_resembla_name = name; } } std::vector<output_type> find(const string_type& query, double threshold = 0.0, size_t max_response = 0) { std::vector<string_type> candidate_texts; std::unordered_map<string_type, StringFeatureMap> candidate_features; // primary resembla for(const auto& r: resemblas[primary_resembla_name]->find(query, threshold / 2.0, max_candidate * 2)){ candidate_texts.push_back(r.text); candidate_features[r.text] = preprocess_corpus ? corpus_features[r.text] : (*preprocess)(r.text); candidate_features[r.text][primary_resembla_name] = Feature::toText(r.score); } // other resemblas for(const auto& p: resemblas){ if(p.first == primary_resembla_name){ continue; } for(auto r: p.second->eval(query, candidate_texts, threshold / 2.0, max_candidate * 2)){ candidate_features[r.text][p.first] = Feature::toText(r.score); } } return eval(query, candidate_features, threshold, max_response); } std::vector<output_type> eval(const string_type& query, const std::vector<string_type>& targets, double threshold = 0.0, size_t max_response = 0) const { std::unordered_map<string_type, StringFeatureMap> candidate_features; for(const auto& t: targets){ if(preprocess_corpus){ auto i = corpus_features.find(t); if(i != std::end(corpus_features)){ candidate_features[t] = i->second; continue; } } candidate_features[t] = (*preprocess)(t); } for(const auto& p: resemblas){ for(const auto& r: p.second->eval(query, targets, threshold / 2.0, max_response * 2)){ candidate_features[r.text][p.first] = Feature::toText(r.score); } } return eval(query, candidate_features, threshold, max_response); } protected: std::vector<output_type> eval(const string_type& query, const std::unordered_map<string_type, StringFeatureMap>& candidate_features, double threshold, size_t max_response) const { // prepare data for reranking std::vector<WorkData> candidates; for(const auto& c: candidate_features){ candidates.push_back(std::make_pair(c.first, c.second)); } WorkData input_data = std::make_pair(query, (*preprocess)(query)); // rerank by its own metric std::vector<ResemblaInterface::output_type> results; for(const auto& r: reranker.rerank(input_data, std::begin(candidates), std::end(candidates), *score_func, threshold, max_response)){ results.push_back({r.first, score_func->name, r.second}); } return results; } using WorkData = std::pair<string_type, typename FeatureExtractor::output_type>; std::unordered_map<std::string, std::shared_ptr<ResemblaInterface>> resemblas; std::string primary_resembla_name; const size_t max_candidate; const std::shared_ptr<FeatureExtractor> preprocess; const std::shared_ptr<ScoreFunction> score_func; const Reranker<string_type> reranker; const bool preprocess_corpus; std::unordered_map<string_type, typename FeatureExtractor::output_type> corpus_features; void loadCorpusFeatures(const std::string& corpus_path, size_t features_col) { std::ifstream ifs(corpus_path); if(ifs.fail()){ throw std::runtime_error("input file is not available: " + corpus_path); } while(ifs.good()){ std::string line; std::getline(ifs, line); if(ifs.eof() || line.length() == 0){ break; } auto columns = split(line, '\t'); if(features_col - 1 < columns.size()){ corpus_features[cast_string<string_type>(columns[0])] = (*preprocess)(columns[0], columns[features_col - 1]); } } } }; } #endif <commit_msg>improve corpus format support<commit_after>/* Resembla: Word-based Japanese similar sentence search library https://github.com/tuem/resembla Copyright 2017 Takashi Uemura 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 __RESEMBLA_REGRESSION_HPP__ #define __RESEMBLA_REGRESSION_HPP__ #include <string> #include <vector> #include <memory> #include <unordered_map> #include <fstream> #include "resembla_interface.hpp" #include "reranker.hpp" #include "regression/feature.hpp" #include "regression/extractor/feature_extractor.hpp" namespace resembla { template<typename ScoreFunction> class ResemblaRegression: public ResemblaInterface { public: ResemblaRegression(size_t max_candidate, std::shared_ptr<FeatureExtractor> feature_extractor, std::shared_ptr<ScoreFunction> score_func, std::string corpus_path = "", size_t text_col = 1, size_t features_col = 2): max_candidate(max_candidate), preprocess(feature_extractor), score_func(score_func), reranker(), preprocess_corpus(!corpus_path.empty()) { if(preprocess_corpus){ loadCorpusFeatures(corpus_path, text_col, features_col); } } void append(const std::string name, const std::shared_ptr<ResemblaInterface> resembla, bool is_primary = true) { resemblas[name] = resembla; if(is_primary && primary_resembla_name.empty()){ primary_resembla_name = name; } } std::vector<output_type> find(const string_type& query, double threshold = 0.0, size_t max_response = 0) { std::vector<string_type> candidate_texts; std::unordered_map<string_type, StringFeatureMap> candidate_features; // primary resembla for(const auto& r: resemblas[primary_resembla_name]->find(query, threshold / 2.0, max_candidate * 2)){ candidate_texts.push_back(r.text); candidate_features[r.text] = preprocess_corpus ? corpus_features[r.text] : (*preprocess)(r.text); candidate_features[r.text][primary_resembla_name] = Feature::toText(r.score); } // other resemblas for(const auto& p: resemblas){ if(p.first == primary_resembla_name){ continue; } for(auto r: p.second->eval(query, candidate_texts, 0.0, 0)){ candidate_features[r.text][p.first] = Feature::toText(r.score); candidate_features[r.text][p.first] = Feature::toText(r.score); } } return eval(query, candidate_features, threshold, max_response); } std::vector<output_type> eval(const string_type& query, const std::vector<string_type>& targets, double threshold = 0.0, size_t max_response = 0) const { std::unordered_map<string_type, StringFeatureMap> candidate_features; for(const auto& t: targets){ if(preprocess_corpus){ auto i = corpus_features.find(t); if(i != std::end(corpus_features)){ candidate_features[t] = i->second; continue; } } candidate_features[t] = (*preprocess)(t); } for(const auto& p: resemblas){ for(const auto& r: p.second->eval(query, targets, 0.0, 0)){ candidate_features[r.text][p.first] = Feature::toText(r.score); } } return eval(query, candidate_features, threshold, max_response); } protected: using WorkData = std::pair<string_type, typename FeatureExtractor::output_type>; std::unordered_map<std::string, std::shared_ptr<ResemblaInterface>> resemblas; std::string primary_resembla_name; const size_t max_candidate; const std::shared_ptr<FeatureExtractor> preprocess; const std::shared_ptr<ScoreFunction> score_func; const Reranker<string_type> reranker; const bool preprocess_corpus; std::unordered_map<string_type, typename FeatureExtractor::output_type> corpus_features; void loadCorpusFeatures(const std::string& corpus_path, size_t text_col, size_t features_col) { std::ifstream ifs(corpus_path); if(ifs.fail()){ throw std::runtime_error("input file is not available: " + corpus_path); } while(ifs.good()){ std::string line; std::getline(ifs, line); if(ifs.eof() || line.length() == 0){ break; } auto columns = split(line, '\t'); if(text_col - 1 < columns.size()){ std::string raw_features = features_col - 1 < columns.size() ? columns[features_col - 1] : ""; corpus_features[cast_string<string_type>(columns[text_col - 1])] = (*preprocess)(columns[text_col - 1], raw_features); } } } std::vector<output_type> eval(const string_type& query, const std::unordered_map<string_type, StringFeatureMap>& candidate_features, double threshold, size_t max_response) const { // prepare data for reranking std::vector<WorkData> candidates; for(const auto& c: candidate_features){ candidates.push_back(std::make_pair(c.first, c.second)); } WorkData input_data = std::make_pair(query, (*preprocess)(query)); // rerank by its own metric std::vector<ResemblaInterface::output_type> results; for(const auto& r: reranker.rerank(input_data, std::begin(candidates), std::end(candidates), *score_func, threshold, max_response)){ results.push_back({r.first, score_func->name, r.second}); } return results; } }; } #endif <|endoftext|>
<commit_before>#include <QSettings> #include <QDir> #include <QFile> #include <QApplication> #include "TranslatorHelper.h" #include "Settings.h" TranslatorHelper::TranslatorHelper () : translatorsDir_ ("translators"), currentIndex_ (0), triesLeft_ (0) { translatorsDir_ = QApplication::applicationDirPath () + QDir::separator () + translatorsDir_; } void TranslatorHelper::setEnabledTranslators (const QStringList &enabled) const { QSettings settings; settings.beginGroup (settings_names::translationGroup); settings.setValue (settings_names::translators, enabled.join ("|")); } QStringList TranslatorHelper::possibleTranslators (QStringList &enabled) const { #define GET(FIELD) settings.value (settings_names::FIELD, settings_values::FIELD) QSettings settings; settings.beginGroup (settings_names::translationGroup); QStringList exist = QDir (translatorsDir_).entryList (QStringList () << "*.js", QDir::Files); QStringList saved = GET (translators).toString ().split ("|", QString::SkipEmptyParts); QStringList on, off; std::copy_if (saved.begin (), saved.end (), std::back_inserter (on), [&](const QString &i) { return exist.contains (i); }); on = on.isEmpty () ? exist : on; std::copy_if (exist.begin (), exist.end (), std::back_inserter (off), [&](const QString &i) { return !on.contains (i); }); enabled = on; return (on + off); #undef GET } QStringList TranslatorHelper::enabledTranslatorScripts () const { QStringList enabled; possibleTranslators (enabled); QStringList scripts; foreach (const QString &name, enabled) { QFile f (translatorsDir_ + QDir::separator () + name); if (f.open (QFile::ReadOnly)) { QString script = QString::fromUtf8 (f.readAll ()); if (!script.isEmpty ()) { scripts << script; } } } return scripts; } void TranslatorHelper::loadScripts () { scripts_ = enabledTranslatorScripts (); } void TranslatorHelper::newItem (bool forceRotate) { triesLeft_ = scripts_.size (); currentIndex_ = forceRotate ? currentIndex_ + 1 : 0; } QString TranslatorHelper::nextScript () { --triesLeft_; if (++currentIndex_ >= scripts_.size ()) { currentIndex_ = 0; } return currentScript (); } QString TranslatorHelper::currentScript () const { return (triesLeft_ > 0 ? scripts_.at (currentIndex_) : QString ()); } bool TranslatorHelper::gotScripts () const { return !scripts_.isEmpty (); } <commit_msg>Fixed possible wrong index usage<commit_after>#include <QSettings> #include <QDir> #include <QFile> #include <QApplication> #include "TranslatorHelper.h" #include "Settings.h" TranslatorHelper::TranslatorHelper () : translatorsDir_ ("translators"), currentIndex_ (0), triesLeft_ (0) { translatorsDir_ = QApplication::applicationDirPath () + QDir::separator () + translatorsDir_; } void TranslatorHelper::setEnabledTranslators (const QStringList &enabled) const { QSettings settings; settings.beginGroup (settings_names::translationGroup); settings.setValue (settings_names::translators, enabled.join ("|")); } QStringList TranslatorHelper::possibleTranslators (QStringList &enabled) const { #define GET(FIELD) settings.value (settings_names::FIELD, settings_values::FIELD) QSettings settings; settings.beginGroup (settings_names::translationGroup); QStringList exist = QDir (translatorsDir_).entryList (QStringList () << "*.js", QDir::Files); QStringList saved = GET (translators).toString ().split ("|", QString::SkipEmptyParts); QStringList on, off; std::copy_if (saved.begin (), saved.end (), std::back_inserter (on), [&](const QString &i) { return exist.contains (i); }); on = on.isEmpty () ? exist : on; std::copy_if (exist.begin (), exist.end (), std::back_inserter (off), [&](const QString &i) { return !on.contains (i); }); enabled = on; return (on + off); #undef GET } QStringList TranslatorHelper::enabledTranslatorScripts () const { QStringList enabled; possibleTranslators (enabled); QStringList scripts; foreach (const QString &name, enabled) { QFile f (translatorsDir_ + QDir::separator () + name); if (f.open (QFile::ReadOnly)) { QString script = QString::fromUtf8 (f.readAll ()); if (!script.isEmpty ()) { scripts << script; } } } return scripts; } void TranslatorHelper::loadScripts () { scripts_ = enabledTranslatorScripts (); } void TranslatorHelper::newItem (bool forceRotate) { triesLeft_ = scripts_.size (); currentIndex_ = forceRotate ? currentIndex_ + 1 : 0; if (currentIndex_ >= scripts_.size ()) { currentIndex_ = 0; } } QString TranslatorHelper::nextScript () { --triesLeft_; if (++currentIndex_ >= scripts_.size ()) { currentIndex_ = 0; } return currentScript (); } QString TranslatorHelper::currentScript () const { if (triesLeft_ > 0 && currentIndex_ < scripts_.size ()) { return scripts_.at (currentIndex_); } return QString (); } bool TranslatorHelper::gotScripts () const { return !scripts_.isEmpty (); } <|endoftext|>
<commit_before>/* $Id$ */ /* generate_extra_defs.cc * * Copyright (C) 2001 The Free Software Foundation * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "generate_extra_defs.h" #include <algorithm> std::string get_properties(GType gtype) { std::string strResult; std::string strObjectName = g_type_name(gtype); //Get the list of properties: GParamSpec** ppParamSpec = 0; guint iCount = 0; if(G_TYPE_IS_OBJECT(gtype)) { GObjectClass* pGClass = G_OBJECT_CLASS(g_type_class_ref(gtype)); ppParamSpec = g_object_class_list_properties (pGClass, &iCount); g_type_class_unref(pGClass); if(!ppParamSpec) { strResult += ";; Warning: g_object_class_list_properties() returned NULL for " + std::string(g_type_name(gtype)) + "\n"; } } else if (G_TYPE_IS_INTERFACE(gtype)) { gpointer pGInterface = g_type_default_interface_ref(gtype); if(pGInterface) //We check because this fails for G_TYPE_VOLUME, for some reason. { ppParamSpec = g_object_interface_list_properties(pGInterface, &iCount); g_type_default_interface_unref(pGInterface); if(!ppParamSpec) { strResult += ";; Warning: g_object_interface_list_properties() returned NULL for " + std::string(g_type_name(gtype)) + "\n"; } } } //This extra check avoids an occasional crash, for instance for GVolume if(!ppParamSpec) iCount = 0; for(guint i = 0; i < iCount; i++) { GParamSpec* pParamSpec = ppParamSpec[i]; // Generate the property if the specified gtype actually owns the property. // (Generally all properties, including any base classes' properties are // retrieved by g_object_interface_list_properties() for a given gtype. // The base classes' properties should not be generated). if(pParamSpec && pParamSpec->owner_type == gtype) { //Name and type: const std::string strName = g_param_spec_get_name(pParamSpec); const std::string strTypeName = G_PARAM_SPEC_TYPE_NAME(pParamSpec); const gchar* pchBlurb = g_param_spec_get_blurb(pParamSpec); std::string strDocs = (pchBlurb) ? pchBlurb : ""; // Quick hack to get rid of nested double quotes: std::replace(strDocs.begin(), strDocs.end(), '"', '\''); strResult += "(define-property " + strName + "\n"; strResult += " (of-object \"" + strObjectName + "\")\n"; strResult += " (prop-type \"" + strTypeName + "\")\n"; strResult += " (docs \"" + strDocs + "\")\n"; //Flags: GParamFlags flags = pParamSpec->flags; bool bReadable = (flags & G_PARAM_READABLE) == G_PARAM_READABLE; bool bWritable = (flags & G_PARAM_WRITABLE) == G_PARAM_WRITABLE; bool bConstructOnly = (flags & G_PARAM_CONSTRUCT_ONLY) == G_PARAM_CONSTRUCT_ONLY; //#t and #f aren't documented, but I guess that it's correct based on the example in the .defs spec. const std::string strTrue = "#t"; const std::string strFalse = "#f"; strResult += " (readable " + (bReadable ? strTrue : strFalse) + ")\n"; strResult += " (writable " + (bWritable ? strTrue : strFalse) + ")\n"; strResult += " (construct-only " + (bConstructOnly ? strTrue : strFalse) + ")\n"; strResult += ")\n\n"; //close (define-property } } g_free(ppParamSpec); return strResult; } bool gtype_is_a_pointer(GType gtype) { return (g_type_is_a(gtype, G_TYPE_OBJECT) || g_type_is_a(gtype, G_TYPE_BOXED)); } std::string get_type_name(GType gtype, GTypeIsAPointerFunc is_a_pointer_func) //Adds a * if necessary. { std::string strTypeName = g_type_name(gtype); if (is_a_pointer_func && is_a_pointer_func(gtype)) strTypeName += "*"; //Add * to show that it's a pointer. else if( g_type_is_a(gtype, G_TYPE_STRING) ) strTypeName = "gchar*"; //g_type_name() returns "gchararray". return strTypeName; } std::string get_type_name_parameter(GType gtype, GTypeIsAPointerFunc is_a_pointer_func) { std::string strTypeName = get_type_name(gtype, is_a_pointer_func); //All signal parameters that are registered as GTK_TYPE_STRING are actually const gchar*. if(strTypeName == "gchar*") strTypeName = "const-gchar*"; return strTypeName; } std::string get_type_name_signal(GType gtype, GTypeIsAPointerFunc is_a_pointer_func) { return get_type_name_parameter(gtype, is_a_pointer_func); //At the moment, it needs the same stuff. } std::string get_signals(GType gtype, GTypeIsAPointerFunc is_a_pointer_func) { std::string strResult; std::string strObjectName = g_type_name(gtype); gpointer gclass_ref = 0; gpointer ginterface_ref = 0; if(G_TYPE_IS_OBJECT(gtype)) gclass_ref = g_type_class_ref(gtype); //Ensures that class_init() is called. else if(G_TYPE_IS_INTERFACE(gtype)) ginterface_ref = g_type_default_interface_ref(gtype); //install signals. //Get the list of signals: guint iCount = 0; guint* pIDs = g_signal_list_ids (gtype, &iCount); //Loop through the list of signals: if(pIDs) { for(guint i = 0; i < iCount; i++) { guint signal_id = pIDs[i]; //Name: std::string strName = g_signal_name(signal_id); strResult += "(define-signal " + strName + "\n"; strResult += " (of-object \"" + strObjectName + "\")\n"; //Other information about the signal: GSignalQuery signalQuery = { 0, 0, 0, GSignalFlags(0), 0, 0, 0, }; g_signal_query(signal_id, &signalQuery); //Return type: std::string strReturnTypeName = get_type_name_signal( signalQuery.return_type & ~G_SIGNAL_TYPE_STATIC_SCOPE, is_a_pointer_func ); //The type is mangled with a flag. Hacky. //bool bReturnTypeHasStaticScope = (signalQuery.return_type & G_SIGNAL_TYPE_STATIC_SCOPE) == G_SIGNAL_TYPE_STATIC_SCOPE; strResult += " (return-type \"" + strReturnTypeName + "\")\n"; //When: { bool bWhenFirst = (signalQuery.signal_flags & G_SIGNAL_RUN_FIRST) == G_SIGNAL_RUN_FIRST; bool bWhenLast = (signalQuery.signal_flags & G_SIGNAL_RUN_LAST) == G_SIGNAL_RUN_LAST; std::string strWhen = "unknown"; if(bWhenFirst && bWhenLast) strWhen = "both"; else if(bWhenFirst) strWhen = "first"; else if(bWhenLast) strWhen = "last"; strResult += " (when \"" + strWhen + "\")\n"; } //Loop through the list of parameters: const GType* pParameters = signalQuery.param_types; if(pParameters) { strResult += " (parameters\n"; for(unsigned i = 0; i < signalQuery.n_params; i++) { GType typeParamMangled = pParameters[i]; //Parameter name: //TODO: How can we get the real parameter name? gchar* pchNum = g_strdup_printf("%d", i); std::string strParamName = "p" + std::string(pchNum); g_free(pchNum); pchNum = 0; //Just like above, for the return type: std::string strTypeName = get_type_name_signal( typeParamMangled & ~G_SIGNAL_TYPE_STATIC_SCOPE, is_a_pointer_func ); //The type is mangled with a flag. Hacky. //bool bReturnTypeHasStaticScope = (typeParamMangled & G_SIGNAL_TYPE_STATIC_SCOPE) == G_SIGNAL_TYPE_STATIC_SCOPE; strResult += " '(\"" + strTypeName + "\" \"" + strParamName + "\")\n"; } strResult += " )\n"; //close (properties } strResult += ")\n\n"; //close (define=signal } } g_free(pIDs); if(gclass_ref) g_type_class_unref(gclass_ref); //to match the g_type_class_ref() above. else if(ginterface_ref) g_type_default_interface_unref(ginterface_ref); // for interface ref above. return strResult; } std::string get_defs(GType gtype, GTypeIsAPointerFunc is_a_pointer_func) { std::string strObjectName = g_type_name(gtype); std::string strDefs = ";; From " + strObjectName + "\n\n"; if(G_TYPE_IS_OBJECT(gtype) || G_TYPE_IS_INTERFACE(gtype)) { strDefs += get_signals(gtype, is_a_pointer_func); strDefs += get_properties(gtype); } return strDefs; } <commit_msg>tools/extra_defs_gen/generate_extra_defs.cc: Update some comments<commit_after>/* $Id$ */ /* generate_extra_defs.cc * * Copyright (C) 2001 The Free Software Foundation * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "generate_extra_defs.h" #include <algorithm> // Until the glib bug https://bugzilla.gnome.org/show_bug.cgi?id=465631 // is fixed, get_properties() must be called for a GObject before it's // called for a GInterface. std::string get_properties(GType gtype) { std::string strResult; std::string strObjectName = g_type_name(gtype); //Get the list of properties: GParamSpec** ppParamSpec = 0; guint iCount = 0; if(G_TYPE_IS_OBJECT(gtype)) { GObjectClass* pGClass = G_OBJECT_CLASS(g_type_class_ref(gtype)); ppParamSpec = g_object_class_list_properties (pGClass, &iCount); g_type_class_unref(pGClass); if(!ppParamSpec) { strResult += ";; Warning: g_object_class_list_properties() returned NULL for " + std::string(g_type_name(gtype)) + "\n"; } } else if (G_TYPE_IS_INTERFACE(gtype)) { gpointer pGInterface = g_type_default_interface_ref(gtype); if(pGInterface) { ppParamSpec = g_object_interface_list_properties(pGInterface, &iCount); g_type_default_interface_unref(pGInterface); if(!ppParamSpec) { strResult += ";; Warning: g_object_interface_list_properties() returned NULL for " + std::string(g_type_name(gtype)) + "\n"; } } else strResult += ";; Warning: g_type_default_interface_ref() returned NULL for " + std::string(g_type_name(gtype)) + "\n"; } //This extra check avoids an occasional crash if(!ppParamSpec) iCount = 0; for(guint i = 0; i < iCount; i++) { GParamSpec* pParamSpec = ppParamSpec[i]; // Generate the property if the specified gtype actually owns the property. // (Generally all properties, including any base classes' properties are // retrieved by g_object_interface_list_properties() for a given gtype. // The base classes' properties should not be generated). if(pParamSpec && pParamSpec->owner_type == gtype) { //Name and type: const std::string strName = g_param_spec_get_name(pParamSpec); const std::string strTypeName = G_PARAM_SPEC_TYPE_NAME(pParamSpec); const gchar* pchBlurb = g_param_spec_get_blurb(pParamSpec); std::string strDocs = (pchBlurb) ? pchBlurb : ""; // Quick hack to get rid of nested double quotes: std::replace(strDocs.begin(), strDocs.end(), '"', '\''); strResult += "(define-property " + strName + "\n"; strResult += " (of-object \"" + strObjectName + "\")\n"; strResult += " (prop-type \"" + strTypeName + "\")\n"; strResult += " (docs \"" + strDocs + "\")\n"; //Flags: GParamFlags flags = pParamSpec->flags; bool bReadable = (flags & G_PARAM_READABLE) == G_PARAM_READABLE; bool bWritable = (flags & G_PARAM_WRITABLE) == G_PARAM_WRITABLE; bool bConstructOnly = (flags & G_PARAM_CONSTRUCT_ONLY) == G_PARAM_CONSTRUCT_ONLY; //#t and #f aren't documented, but I guess that it's correct based on the example in the .defs spec. const std::string strTrue = "#t"; const std::string strFalse = "#f"; strResult += " (readable " + (bReadable ? strTrue : strFalse) + ")\n"; strResult += " (writable " + (bWritable ? strTrue : strFalse) + ")\n"; strResult += " (construct-only " + (bConstructOnly ? strTrue : strFalse) + ")\n"; strResult += ")\n\n"; //close (define-property } } g_free(ppParamSpec); return strResult; } bool gtype_is_a_pointer(GType gtype) { return (g_type_is_a(gtype, G_TYPE_OBJECT) || g_type_is_a(gtype, G_TYPE_BOXED)); } std::string get_type_name(GType gtype, GTypeIsAPointerFunc is_a_pointer_func) //Adds a * if necessary. { std::string strTypeName = g_type_name(gtype); if (is_a_pointer_func && is_a_pointer_func(gtype)) strTypeName += "*"; //Add * to show that it's a pointer. else if( g_type_is_a(gtype, G_TYPE_STRING) ) strTypeName = "gchar*"; //g_type_name() returns "gchararray". return strTypeName; } std::string get_type_name_parameter(GType gtype, GTypeIsAPointerFunc is_a_pointer_func) { std::string strTypeName = get_type_name(gtype, is_a_pointer_func); //All signal parameters that are registered as GTK_TYPE_STRING are actually const gchar*. if(strTypeName == "gchar*") strTypeName = "const-gchar*"; return strTypeName; } std::string get_type_name_signal(GType gtype, GTypeIsAPointerFunc is_a_pointer_func) { return get_type_name_parameter(gtype, is_a_pointer_func); //At the moment, it needs the same stuff. } std::string get_signals(GType gtype, GTypeIsAPointerFunc is_a_pointer_func) { std::string strResult; std::string strObjectName = g_type_name(gtype); gpointer gclass_ref = 0; gpointer ginterface_ref = 0; if(G_TYPE_IS_OBJECT(gtype)) gclass_ref = g_type_class_ref(gtype); //Ensures that class_init() is called. else if(G_TYPE_IS_INTERFACE(gtype)) ginterface_ref = g_type_default_interface_ref(gtype); //install signals. //Get the list of signals: guint iCount = 0; guint* pIDs = g_signal_list_ids (gtype, &iCount); //Loop through the list of signals: if(pIDs) { for(guint i = 0; i < iCount; i++) { guint signal_id = pIDs[i]; //Name: std::string strName = g_signal_name(signal_id); strResult += "(define-signal " + strName + "\n"; strResult += " (of-object \"" + strObjectName + "\")\n"; //Other information about the signal: GSignalQuery signalQuery = { 0, 0, 0, GSignalFlags(0), 0, 0, 0, }; g_signal_query(signal_id, &signalQuery); //Return type: std::string strReturnTypeName = get_type_name_signal( signalQuery.return_type & ~G_SIGNAL_TYPE_STATIC_SCOPE, is_a_pointer_func ); //The type is mangled with a flag. Hacky. //bool bReturnTypeHasStaticScope = (signalQuery.return_type & G_SIGNAL_TYPE_STATIC_SCOPE) == G_SIGNAL_TYPE_STATIC_SCOPE; strResult += " (return-type \"" + strReturnTypeName + "\")\n"; //When: { bool bWhenFirst = (signalQuery.signal_flags & G_SIGNAL_RUN_FIRST) == G_SIGNAL_RUN_FIRST; bool bWhenLast = (signalQuery.signal_flags & G_SIGNAL_RUN_LAST) == G_SIGNAL_RUN_LAST; std::string strWhen = "unknown"; if(bWhenFirst && bWhenLast) strWhen = "both"; else if(bWhenFirst) strWhen = "first"; else if(bWhenLast) strWhen = "last"; strResult += " (when \"" + strWhen + "\")\n"; } //Loop through the list of parameters: const GType* pParameters = signalQuery.param_types; if(pParameters) { strResult += " (parameters\n"; for(unsigned i = 0; i < signalQuery.n_params; i++) { GType typeParamMangled = pParameters[i]; //Parameter name: //We can't get the real parameter name from the GObject system. It's not registered with g_signal_new(). gchar* pchNum = g_strdup_printf("%d", i); std::string strParamName = "p" + std::string(pchNum); g_free(pchNum); pchNum = 0; //Just like above, for the return type: std::string strTypeName = get_type_name_signal( typeParamMangled & ~G_SIGNAL_TYPE_STATIC_SCOPE, is_a_pointer_func ); //The type is mangled with a flag. Hacky. //bool bTypeHasStaticScope = (typeParamMangled & G_SIGNAL_TYPE_STATIC_SCOPE) == G_SIGNAL_TYPE_STATIC_SCOPE; strResult += " '(\"" + strTypeName + "\" \"" + strParamName + "\")\n"; } strResult += " )\n"; //close (parameters } strResult += ")\n\n"; //close (define-signal } } g_free(pIDs); if(gclass_ref) g_type_class_unref(gclass_ref); //to match the g_type_class_ref() above. else if(ginterface_ref) g_type_default_interface_unref(ginterface_ref); // for interface ref above. return strResult; } std::string get_defs(GType gtype, GTypeIsAPointerFunc is_a_pointer_func) { std::string strObjectName = g_type_name(gtype); std::string strDefs; if(G_TYPE_IS_OBJECT(gtype) || G_TYPE_IS_INTERFACE(gtype)) { strDefs = ";; From " + strObjectName + "\n\n"; strDefs += get_signals(gtype, is_a_pointer_func); strDefs += get_properties(gtype); } else strDefs = ";; " + strObjectName + " is neither a GObject nor a GInterface. Not checked for signals and properties.\n\n"; return strDefs; } <|endoftext|>
<commit_before>#include <termox/system/system.hpp> #include <algorithm> #include <cstdlib> #include <functional> #include <iterator> #include <map> #include <memory> #include <shared_mutex> #include <stdexcept> #include <thread> #include <utility> #include <vector> #include <signals_light/signal.hpp> #include <termox/system/animation_engine.hpp> #include <termox/system/detail/filter_send.hpp> #include <termox/system/detail/focus.hpp> #include <termox/system/detail/is_sendable.hpp> #include <termox/system/detail/send.hpp> #include <termox/system/detail/send_shortcut.hpp> #include <termox/system/detail/user_input_event_loop.hpp> #include <termox/system/event.hpp> #include <termox/system/event_loop.hpp> #include <termox/system/event_queue.hpp> #include <termox/system/system.hpp> #include <termox/terminal/terminal.hpp> #include <termox/widget/area.hpp> #include <termox/widget/widget.hpp> namespace ox { auto System::focus_widget() -> Widget* { return detail::Focus::focus_widget(); } void System::set_focus(Widget& w) { detail::Focus::set(w); } void System::clear_focus() { detail::Focus::clear(); } void System::enable_tab_focus() { detail::Focus::enable_tab_focus(); } void System::disable_tab_focus() { detail::Focus::disable_tab_focus(); } void System::post_event(Event e) { current_queue_.get().append(std::move(e)); } void System::exit() { user_input_loop_.exit(0); Terminal::uninitialize(); std::quick_exit(0); } void System::set_head(Widget* new_head) { if (auto* const head = head_.load(); head != nullptr) head->disable(); if (new_head != nullptr) { new_head->enable(); System::post_event(Resize_event{*new_head, Terminal::area()}); detail::Focus::set(*new_head); } head_ = new_head; } auto System::run() -> int { auto* const head = head_.load(); if (head == nullptr) return -1; auto const result = user_input_loop_.run(); // user_input_loop_ is already stopped if you are here. animation_engine_.stop(); Terminal::stop_dynamic_color_engine(); return result; } auto System::send_event(Event e) -> bool { auto handled = std::visit([](auto const& e) { return detail::send_shortcut(e); }, e); if (!std::visit([](auto const& e) { return detail::is_sendable(e); }, e)) return false; if (!handled) { handled = std::visit([](auto const& e) { return detail::filter_send(e); }, e); } if (!handled) std::visit([](auto e) { detail::send(std::move(e)); }, std::move(e)); return true; } auto System::send_event(Paint_event e) -> bool { if (!detail::is_sendable(e)) return false; auto const handled = detail::filter_send(e); if (!handled) detail::send(std::move(e)); return true; } auto System::send_event(Delete_event e) -> bool { auto const handled = detail::filter_send(e); if (!handled) detail::send(std::move(e)); return true; } sl::Slot<void()> System::quit = [] { System::exit(); }; detail::User_input_event_loop System::user_input_loop_; Animation_engine System::animation_engine_; std::reference_wrapper<Event_queue> System::current_queue_ = user_input_loop_.event_queue(); } // namespace ox <commit_msg>change std::quick_exit to std::_Exit to see if works on MacOS<commit_after>#include <termox/system/system.hpp> #include <algorithm> #include <cstdlib> #include <functional> #include <iterator> #include <map> #include <memory> #include <shared_mutex> #include <stdexcept> #include <thread> #include <utility> #include <vector> #include <signals_light/signal.hpp> #include <termox/system/animation_engine.hpp> #include <termox/system/detail/filter_send.hpp> #include <termox/system/detail/focus.hpp> #include <termox/system/detail/is_sendable.hpp> #include <termox/system/detail/send.hpp> #include <termox/system/detail/send_shortcut.hpp> #include <termox/system/detail/user_input_event_loop.hpp> #include <termox/system/event.hpp> #include <termox/system/event_loop.hpp> #include <termox/system/event_queue.hpp> #include <termox/system/system.hpp> #include <termox/terminal/terminal.hpp> #include <termox/widget/area.hpp> #include <termox/widget/widget.hpp> namespace ox { auto System::focus_widget() -> Widget* { return detail::Focus::focus_widget(); } void System::set_focus(Widget& w) { detail::Focus::set(w); } void System::clear_focus() { detail::Focus::clear(); } void System::enable_tab_focus() { detail::Focus::enable_tab_focus(); } void System::disable_tab_focus() { detail::Focus::disable_tab_focus(); } void System::post_event(Event e) { current_queue_.get().append(std::move(e)); } void System::exit() { user_input_loop_.exit(0); Terminal::uninitialize(); std::_Exit(0); } void System::set_head(Widget* new_head) { if (auto* const head = head_.load(); head != nullptr) head->disable(); if (new_head != nullptr) { new_head->enable(); System::post_event(Resize_event{*new_head, Terminal::area()}); detail::Focus::set(*new_head); } head_ = new_head; } auto System::run() -> int { auto* const head = head_.load(); if (head == nullptr) return -1; auto const result = user_input_loop_.run(); // user_input_loop_ is already stopped if you are here. animation_engine_.stop(); Terminal::stop_dynamic_color_engine(); return result; } auto System::send_event(Event e) -> bool { auto handled = std::visit([](auto const& e) { return detail::send_shortcut(e); }, e); if (!std::visit([](auto const& e) { return detail::is_sendable(e); }, e)) return false; if (!handled) { handled = std::visit([](auto const& e) { return detail::filter_send(e); }, e); } if (!handled) std::visit([](auto e) { detail::send(std::move(e)); }, std::move(e)); return true; } auto System::send_event(Paint_event e) -> bool { if (!detail::is_sendable(e)) return false; auto const handled = detail::filter_send(e); if (!handled) detail::send(std::move(e)); return true; } auto System::send_event(Delete_event e) -> bool { auto const handled = detail::filter_send(e); if (!handled) detail::send(std::move(e)); return true; } sl::Slot<void()> System::quit = [] { System::exit(); }; detail::User_input_event_loop System::user_input_loop_; Animation_engine System::animation_engine_; std::reference_wrapper<Event_queue> System::current_queue_ = user_input_loop_.event_queue(); } // namespace ox <|endoftext|>
<commit_before>#ifndef _SPATIAL_MATH_RECT_INL_ #define _SPATIAL_MATH_RECT_INL_ #include <limits> #include <algorithm> namespace sm { template <typename T> Rect<T>::Rect() { MakeEmpty(); } template <typename T> Rect<T>::Rect(T width, T height) { Build(width, height); } template <typename T> Rect<T>::Rect(const Vector2<T>& center, T width, T height) { Build(width, height); Translate(center); } template <typename T> Rect<T>::Rect(const Vector2<T>& v0, const Vector2<T>& v1) { xmin = (std::min)(v0.x, v1.x); ymin = (std::min)(v0.y, v1.y); xmax = (std::max)(v0.x, v1.x); ymax = (std::max)(v0.y, v1.y); } template <typename T> bool Rect<T>::operator == (const Rect<T>& r) const { return xmin == r.xmin && xmax == r.xmax && ymin == r.ymin && ymax == r.ymax; } template <typename T> void Rect<T>::Build(T width, T height) { T hw = width * 0.5f, hh = height * 0.5f; xmin = -hw; xmax = hw; ymin = -hh; ymax = hh; } template <typename T> void Rect<T>::MakeEmpty() { xmin = ymin = std::numeric_limits<T>::max(); xmax = ymax = -std::numeric_limits<T>::max(); } template <typename T> bool Rect<T>::IsValid() const { return xmin != std::numeric_limits<T>::max() && ymin != std::numeric_limits<T>::max() && xmax != -std::numeric_limits<T>::max() && ymax != -std::numeric_limits<T>::max() && xmin <= xmax && ymin <= ymax; } template <typename T> void Rect<T>::Combine(const Vector2<T>& v) { if (v.x < xmin) xmin = v.x; if (v.x > xmax) xmax = v.x; if (v.y < ymin) ymin = v.y; if (v.y > ymax) ymax = v.y; } template <typename T> void Rect<T>::Combine(const Rect<T>& r) { if (r.xmin < xmin) xmin = r.xmin; if (r.xmax > xmax) xmax = r.xmax; if (r.ymin < ymin) ymin = r.ymin; if (r.ymax > ymax) ymax = r.ymax; } template <typename T> Vector2<T> Rect<T>::Size() const { return Vector2<T>(xmax - xmin, ymax - ymin); } template <typename T> Vector2<T> Rect<T>::Center() const { return Vector2<T>((xmin + xmax) * 0.5f, (ymin + ymax) * 0.5f); } template <typename T> void Rect<T>::Translate(const Vector2<T>& offset) { xmin += offset.x; xmax += offset.x; ymin += offset.y; ymax += offset.y; } template <typename T> void Rect<T>::Scale(T sx, T sy) { xmin *= sx; xmax *= sx; ymin *= sy; ymax *= sy; } template <typename T> void Rect<T>::Shear(T kx, T ky) { MakeEmpty(); // x' = x + y*kx // y' = x*ky + y sm ::vec2 v[4]; v[0].x = xmin + ymin * kx; v[0].y = xmin * ky + ymin; v[1].x = xmax + ymin * kx; v[1].y = xmax * ky + ymin; v[2].x = xmax + ymax * kx; v[2].y = xmax * ky + ymax; v[3].x = xmin + ymax * kx; v[3].y = xmin * ky + ymax; for (int i = 0; i < 4; ++i) { Combine(v[i]); } } } #endif // _SPATIAL_MATH_RECT_INL_<commit_msg>[FIXED] rect shear<commit_after>#ifndef _SPATIAL_MATH_RECT_INL_ #define _SPATIAL_MATH_RECT_INL_ #include <limits> #include <algorithm> namespace sm { template <typename T> Rect<T>::Rect() { MakeEmpty(); } template <typename T> Rect<T>::Rect(T width, T height) { Build(width, height); } template <typename T> Rect<T>::Rect(const Vector2<T>& center, T width, T height) { Build(width, height); Translate(center); } template <typename T> Rect<T>::Rect(const Vector2<T>& v0, const Vector2<T>& v1) { xmin = (std::min)(v0.x, v1.x); ymin = (std::min)(v0.y, v1.y); xmax = (std::max)(v0.x, v1.x); ymax = (std::max)(v0.y, v1.y); } template <typename T> bool Rect<T>::operator == (const Rect<T>& r) const { return xmin == r.xmin && xmax == r.xmax && ymin == r.ymin && ymax == r.ymax; } template <typename T> void Rect<T>::Build(T width, T height) { T hw = width * 0.5f, hh = height * 0.5f; xmin = -hw; xmax = hw; ymin = -hh; ymax = hh; } template <typename T> void Rect<T>::MakeEmpty() { xmin = ymin = std::numeric_limits<T>::max(); xmax = ymax = -std::numeric_limits<T>::max(); } template <typename T> bool Rect<T>::IsValid() const { return xmin != std::numeric_limits<T>::max() && ymin != std::numeric_limits<T>::max() && xmax != -std::numeric_limits<T>::max() && ymax != -std::numeric_limits<T>::max() && xmin <= xmax && ymin <= ymax; } template <typename T> void Rect<T>::Combine(const Vector2<T>& v) { if (v.x < xmin) xmin = v.x; if (v.x > xmax) xmax = v.x; if (v.y < ymin) ymin = v.y; if (v.y > ymax) ymax = v.y; } template <typename T> void Rect<T>::Combine(const Rect<T>& r) { if (r.xmin < xmin) xmin = r.xmin; if (r.xmax > xmax) xmax = r.xmax; if (r.ymin < ymin) ymin = r.ymin; if (r.ymax > ymax) ymax = r.ymax; } template <typename T> Vector2<T> Rect<T>::Size() const { return Vector2<T>(xmax - xmin, ymax - ymin); } template <typename T> Vector2<T> Rect<T>::Center() const { return Vector2<T>((xmin + xmax) * 0.5f, (ymin + ymax) * 0.5f); } template <typename T> void Rect<T>::Translate(const Vector2<T>& offset) { xmin += offset.x; xmax += offset.x; ymin += offset.y; ymax += offset.y; } template <typename T> void Rect<T>::Scale(T sx, T sy) { xmin *= sx; xmax *= sx; ymin *= sy; ymax *= sy; } template <typename T> void Rect<T>::Shear(T kx, T ky) { // x' = x + y*kx // y' = x*ky + y sm ::vec2 v[4]; v[0].x = xmin + ymin * kx; v[0].y = xmin * ky + ymin; v[1].x = xmax + ymin * kx; v[1].y = xmax * ky + ymin; v[2].x = xmax + ymax * kx; v[2].y = xmax * ky + ymax; v[3].x = xmin + ymax * kx; v[3].y = xmin * ky + ymax; MakeEmpty(); for (int i = 0; i < 4; ++i) { Combine(v[i]); } } } #endif // _SPATIAL_MATH_RECT_INL_<|endoftext|>
<commit_before>/* * Copyright (C) 2013 Daniel Nicoletti <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "dispatcher_p.h" #include "common.h" #include "context.h" #include "controller.h" #include "action.h" #include "request_p.h" #include "dispatchtypepath.h" #include <QUrl> #include <QMetaMethod> #include <QStringBuilder> #include <QDebug> using namespace Cutelyst; Dispatcher::Dispatcher(QObject *parent) : QObject(parent), d_ptr(new DispatcherPrivate) { } Dispatcher::~Dispatcher() { delete d_ptr; } void Dispatcher::setupActions(const QList<Controller*> &controllers) { Q_D(Dispatcher); if (d->dispatchers.isEmpty()) { registerDispatchType(new DispatchTypePath(this)); } Q_FOREACH (Controller *controller, controllers) { // App controller // qDebug() << "Found a controller:" << controller << meta->className(); const QMetaObject *meta = controller->metaObject(); controller->setObjectName(meta->className()); bool instanceUsed = false; for (int i = 0; i < meta->methodCount(); ++i) { QMetaMethod method = meta->method(i); if (method.methodType() == QMetaMethod::Method || method.methodType() == QMetaMethod::Slot) { bool registered = false; Action *action = new Action(method, controller, this); if (action->isValid() && !d->actionHash.contains(action->privateName())) { if (!action->attributes().contains("Private")) { // Register the action with each dispatcher Q_FOREACH (DispatchType *dispatch, d->dispatchers) { if (dispatch->registerAction(action)) { registered = true; } } } else { // We register private actions registered = true; } } // The Begin, Auto, End actions are not // registered by Dispatchers but we need them // as private actions anyway if (registered || action->isValid()) { d->actionHash.insert(action->privateName(), action); d->containerHash[action->ns()] << action; instanceUsed = true; } else { delete action; } } } if (instanceUsed) { d->constrollerHash.insert(meta->className(), controller); } } printActions(); } bool Dispatcher::dispatch(Context *ctx) { if (ctx->action()) { QByteArray action = ctx->ns(); action.reserve(action.size() + 12); action.prepend('/'); action.append("/_DISPATCH", 10); return forward(ctx, action); } else { QString error; const QString &path = ctx->req()->path(); if (path.isEmpty()) { error = QLatin1String("No default action defined"); } else { error = QLatin1String("Unknown resource \"") % path % QLatin1Char('"'); } qCDebug(CUTELYST_DISPATCHER) << error; ctx->error(error); } return false; } bool Dispatcher::forward(Context *ctx, const QByteArray &opname, const QStringList &arguments) { Action *action = command2Action(ctx, opname); if (action) { return action->dispatch(ctx); } qCCritical(CUTELYST_DISPATCHER) << "Action not found" << action; return false; } void Dispatcher::prepareAction(Context *ctx) { Q_D(Dispatcher); QByteArray path = ctx->req()->path().toLatin1(); QList<QByteArray> pathParts = path.split('/'); QList<QByteArray> args; // Root action pathParts.prepend(QByteArrayLiteral("")); int pos = path.size(); while (pos != -1) { Q_FOREACH (DispatchType *type, d->dispatchers) { QByteArray actionPath = path.mid(1, pos); if (type->match(ctx, actionPath, args)) { ctx->req()->d_ptr->args = unexcapedArgs(args); if (!path.isEmpty()) { qCDebug(CUTELYST_DISPATCHER) << "Path is" << actionPath; } if (!ctx->args().isEmpty()) { qCDebug(CUTELYST_DISPATCHER) << "Arguments are" << ctx->args().join(QLatin1Char('/')); } return; } } pos = path.lastIndexOf('/', pos - 1); args.prepend(pathParts.takeLast()); } } Action *Dispatcher::getAction(const QByteArray &name, const QByteArray &ns) const { Q_D(const Dispatcher); if (name.isEmpty()) { return 0; } QByteArray action = cleanNamespace(ns); action.reserve(action.size() + name.size() + 1); action.append('/'); action.append(name); return d->actionHash.value(action); } ActionList Dispatcher::getActions(const QByteArray &name, const QByteArray &ns) const { Q_D(const Dispatcher); ActionList ret; if (name.isEmpty()) { return ret; } QByteArray _ns = cleanNamespace(ns); ActionList containers = d->getContainers(_ns); Q_FOREACH (Action *action, containers) { if (action->name() == name) { ret.prepend(action); } } return ret; } QHash<QByteArray, Controller *> Dispatcher::controllers() const { Q_D(const Dispatcher); return d->constrollerHash; } QByteArray Dispatcher::uriForAction(Action *action, const QStringList &captures) { Q_D(const Dispatcher); Q_FOREACH (DispatchType *dispatch, d->dispatchers) { QByteArray uri = dispatch->uriForAction(action, captures); if (!uri.isNull()) { return uri.isEmpty() ? QByteArray("/", 1) : uri; } } return QByteArray(); } void Dispatcher::registerDispatchType(DispatchType *dispatchType) { Q_D(Dispatcher); d->dispatchers.append(dispatchType); } void Dispatcher::printActions() { Q_D(Dispatcher); QString buffer; QTextStream out(&buffer, QIODevice::WriteOnly); bool showInternalActions = false; out << "Loaded Private actions:" << endl; QString privateTitle("Private"); QString classTitle("Class"); QString methodTitle("Method"); int privateLength = privateTitle.length(); int classLength = classTitle.length(); int actionLength = methodTitle.length(); QHash<QByteArray, Action*>::ConstIterator it = d->actionHash.constBegin(); while (it != d->actionHash.constEnd()) { Action *action = it.value(); QByteArray path = it.key(); if (!path.startsWith('/')) { path.prepend('/'); } privateLength = qMax(privateLength, path.length()); classLength = qMax(classLength, action->className().length()); actionLength = qMax(actionLength, action->name().length()); ++it; } out << "." << QString().fill(QLatin1Char('-'), privateLength).toUtf8().data() << "+" << QString().fill(QLatin1Char('-'), classLength).toUtf8().data() << "+" << QString().fill(QLatin1Char('-'), actionLength).toUtf8().data() << "." << endl; out << "|" << privateTitle.leftJustified(privateLength).toUtf8().data() << "|" << classTitle.leftJustified(classLength).toUtf8().data() << "|" << methodTitle.leftJustified(actionLength).toUtf8().data() << "|" << endl; out << "." << QString().fill(QLatin1Char('-'), privateLength).toUtf8().data() << "+" << QString().fill(QLatin1Char('-'), classLength).toUtf8().data() << "+" << QString().fill(QLatin1Char('-'), actionLength).toUtf8().data() << "." << endl; QList<QByteArray> keys = d->actionHash.keys(); qSort(keys.begin(), keys.end()); Q_FOREACH (const QByteArray &key, keys) { Action *action = d->actionHash.value(key); if (showInternalActions || !action->name().startsWith('_')) { QString path = key; if (!path.startsWith(QLatin1String("/"))) { path.prepend(QLatin1String("/")); } out << "|" << path.leftJustified(privateLength).toUtf8().data() << "|" << QString(action->className()).leftJustified(classLength).toUtf8().data() << "|" << QString(action->name()).leftJustified(actionLength).toUtf8().data() << "|" << endl; } } out << "." << QString().fill(QLatin1Char('-'), privateLength).toUtf8().data() << "+" << QString().fill(QLatin1Char('-'), classLength).toUtf8().data() << "+" << QString().fill(QLatin1Char('-'), actionLength).toUtf8().data() << "."; qCDebug(CUTELYST_DISPATCHER) << buffer.toUtf8().data(); // List all public actions Q_FOREACH (DispatchType *dispatch, d->dispatchers) { dispatch->list(); } } Action *Dispatcher::command2Action(Context *ctx, const QByteArray &command, const QStringList &extraParams) { Q_D(Dispatcher); // qDebug() << Q_FUNC_INFO << "Command" << command; Action *ret = d->actionHash.value(command); if (!ret) { ret = invokeAsPath(ctx, command, ctx->args()); } return ret; } QStringList Dispatcher::unexcapedArgs(const QList<QByteArray> &args) { QStringList ret; Q_FOREACH (const QByteArray &arg, args) { ret.append(QUrl::fromPercentEncoding(arg)); } return ret; } QByteArray Dispatcher::actionRel2Abs(Context *ctx, const QByteArray &path) { QByteArray ret = path; if (!ret.startsWith('/')) { // TODO at Catalyst it uses // c->stack->last()->namespace ret.prepend('/'); ret.prepend(ctx->action()->ns()); } if (ret.startsWith('/')) { ret.remove(0, 1); } return ret; } Action *Dispatcher::invokeAsPath(Context *ctx, const QByteArray &relativePath, const QStringList &args) { Q_D(Dispatcher); Action *ret; QByteArray path = actionRel2Abs(ctx, relativePath); int pos = path.lastIndexOf('/'); int lastPos = path.size(); do { if (pos == -1) { ret = getAction(path, QByteArray()); if (ret) { return ret; } } else { QByteArray name = path.mid(pos + 1, lastPos); path = path.mid(0, pos); ret = getAction(name, path); if (ret) { return ret; } } lastPos = pos; pos = path.indexOf('/', pos - 1); } while (pos != -1); return 0; } QByteArray Dispatcher::cleanNamespace(const QByteArray &ns) const { QByteArray ret = ns; bool lastWasSlash = true; // remove initial slash int nsSize = ns.size(); const char * data = ret.constData(); for (int i = 0; i < nsSize; ++i) { if (data[i] == '/') { if (lastWasSlash) { ret.remove(i, 1); data = ret.constData(); --nsSize; } else { lastWasSlash = true; } } else { lastWasSlash = false; } } return ret; } ActionList DispatcherPrivate::getContainers(const QByteArray &ns) const { ActionList ret; if (ns != "/") { int pos = ns.size(); // qDebug() << pos << _ns.mid(0, pos); while (pos > 0) { // qDebug() << pos << _ns.mid(0, pos); ret.append(containerHash.value(ns.mid(0, pos))); pos = ns.lastIndexOf('/', pos - 1); } } ret.append(containerHash.value("")); return ret; } <commit_msg>Fix compilation<commit_after>/* * Copyright (C) 2013 Daniel Nicoletti <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "dispatcher_p.h" #include "common.h" #include "context.h" #include "controller.h" #include "action.h" #include "request_p.h" #include "dispatchtypepath.h" #include <QUrl> #include <QMetaMethod> #include <QStringBuilder> #include <QDebug> using namespace Cutelyst; Dispatcher::Dispatcher(QObject *parent) : QObject(parent), d_ptr(new DispatcherPrivate) { } Dispatcher::~Dispatcher() { delete d_ptr; } void Dispatcher::setupActions(const QList<Controller*> &controllers) { Q_D(Dispatcher); if (d->dispatchers.isEmpty()) { registerDispatchType(new DispatchTypePath(this)); } Q_FOREACH (Controller *controller, controllers) { // App controller // qDebug() << "Found a controller:" << controller << meta->className(); const QMetaObject *meta = controller->metaObject(); controller->setObjectName(meta->className()); bool instanceUsed = false; for (int i = 0; i < meta->methodCount(); ++i) { QMetaMethod method = meta->method(i); if (method.methodType() == QMetaMethod::Method || method.methodType() == QMetaMethod::Slot) { bool registered = false; Action *action = new Action(method, controller); if (action->isValid() && !d->actionHash.contains(action->privateName())) { if (!action->attributes().contains("Private")) { // Register the action with each dispatcher Q_FOREACH (DispatchType *dispatch, d->dispatchers) { if (dispatch->registerAction(action)) { registered = true; } } } else { // We register private actions registered = true; } } // The Begin, Auto, End actions are not // registered by Dispatchers but we need them // as private actions anyway if (registered || action->isValid()) { d->actionHash.insert(action->privateName(), action); d->containerHash[action->ns()] << action; instanceUsed = true; } else { delete action; } } } if (instanceUsed) { d->constrollerHash.insert(meta->className(), controller); } } printActions(); } bool Dispatcher::dispatch(Context *ctx) { if (ctx->action()) { QByteArray action = ctx->ns(); action.reserve(action.size() + 12); action.prepend('/'); action.append("/_DISPATCH", 10); return forward(ctx, action); } else { QString error; const QString &path = ctx->req()->path(); if (path.isEmpty()) { error = QLatin1String("No default action defined"); } else { error = QLatin1String("Unknown resource \"") % path % QLatin1Char('"'); } qCDebug(CUTELYST_DISPATCHER) << error; ctx->error(error); } return false; } bool Dispatcher::forward(Context *ctx, const QByteArray &opname, const QStringList &arguments) { Action *action = command2Action(ctx, opname); if (action) { return action->dispatch(ctx); } qCCritical(CUTELYST_DISPATCHER) << "Action not found" << action; return false; } void Dispatcher::prepareAction(Context *ctx) { Q_D(Dispatcher); QByteArray path = ctx->req()->path().toLatin1(); QList<QByteArray> pathParts = path.split('/'); QList<QByteArray> args; // Root action pathParts.prepend(QByteArrayLiteral("")); int pos = path.size(); while (pos != -1) { Q_FOREACH (DispatchType *type, d->dispatchers) { QByteArray actionPath = path.mid(1, pos); if (type->match(ctx, actionPath, args)) { ctx->req()->d_ptr->args = unexcapedArgs(args); if (!path.isEmpty()) { qCDebug(CUTELYST_DISPATCHER) << "Path is" << actionPath; } if (!ctx->args().isEmpty()) { qCDebug(CUTELYST_DISPATCHER) << "Arguments are" << ctx->args().join(QLatin1Char('/')); } return; } } pos = path.lastIndexOf('/', pos - 1); args.prepend(pathParts.takeLast()); } } Action *Dispatcher::getAction(const QByteArray &name, const QByteArray &ns) const { Q_D(const Dispatcher); if (name.isEmpty()) { return 0; } QByteArray action = cleanNamespace(ns); action.reserve(action.size() + name.size() + 1); action.append('/'); action.append(name); return d->actionHash.value(action); } ActionList Dispatcher::getActions(const QByteArray &name, const QByteArray &ns) const { Q_D(const Dispatcher); ActionList ret; if (name.isEmpty()) { return ret; } QByteArray _ns = cleanNamespace(ns); ActionList containers = d->getContainers(_ns); Q_FOREACH (Action *action, containers) { if (action->name() == name) { ret.prepend(action); } } return ret; } QHash<QByteArray, Controller *> Dispatcher::controllers() const { Q_D(const Dispatcher); return d->constrollerHash; } QByteArray Dispatcher::uriForAction(Action *action, const QStringList &captures) { Q_D(const Dispatcher); Q_FOREACH (DispatchType *dispatch, d->dispatchers) { QByteArray uri = dispatch->uriForAction(action, captures); if (!uri.isNull()) { return uri.isEmpty() ? QByteArray("/", 1) : uri; } } return QByteArray(); } void Dispatcher::registerDispatchType(DispatchType *dispatchType) { Q_D(Dispatcher); d->dispatchers.append(dispatchType); } void Dispatcher::printActions() { Q_D(Dispatcher); QString buffer; QTextStream out(&buffer, QIODevice::WriteOnly); bool showInternalActions = false; out << "Loaded Private actions:" << endl; QString privateTitle("Private"); QString classTitle("Class"); QString methodTitle("Method"); int privateLength = privateTitle.length(); int classLength = classTitle.length(); int actionLength = methodTitle.length(); QHash<QByteArray, Action*>::ConstIterator it = d->actionHash.constBegin(); while (it != d->actionHash.constEnd()) { Action *action = it.value(); QByteArray path = it.key(); if (!path.startsWith('/')) { path.prepend('/'); } privateLength = qMax(privateLength, path.length()); classLength = qMax(classLength, action->className().length()); actionLength = qMax(actionLength, action->name().length()); ++it; } out << "." << QString().fill(QLatin1Char('-'), privateLength).toUtf8().data() << "+" << QString().fill(QLatin1Char('-'), classLength).toUtf8().data() << "+" << QString().fill(QLatin1Char('-'), actionLength).toUtf8().data() << "." << endl; out << "|" << privateTitle.leftJustified(privateLength).toUtf8().data() << "|" << classTitle.leftJustified(classLength).toUtf8().data() << "|" << methodTitle.leftJustified(actionLength).toUtf8().data() << "|" << endl; out << "." << QString().fill(QLatin1Char('-'), privateLength).toUtf8().data() << "+" << QString().fill(QLatin1Char('-'), classLength).toUtf8().data() << "+" << QString().fill(QLatin1Char('-'), actionLength).toUtf8().data() << "." << endl; QList<QByteArray> keys = d->actionHash.keys(); qSort(keys.begin(), keys.end()); Q_FOREACH (const QByteArray &key, keys) { Action *action = d->actionHash.value(key); if (showInternalActions || !action->name().startsWith('_')) { QString path = key; if (!path.startsWith(QLatin1String("/"))) { path.prepend(QLatin1String("/")); } out << "|" << path.leftJustified(privateLength).toUtf8().data() << "|" << QString(action->className()).leftJustified(classLength).toUtf8().data() << "|" << QString(action->name()).leftJustified(actionLength).toUtf8().data() << "|" << endl; } } out << "." << QString().fill(QLatin1Char('-'), privateLength).toUtf8().data() << "+" << QString().fill(QLatin1Char('-'), classLength).toUtf8().data() << "+" << QString().fill(QLatin1Char('-'), actionLength).toUtf8().data() << "."; qCDebug(CUTELYST_DISPATCHER) << buffer.toUtf8().data(); // List all public actions Q_FOREACH (DispatchType *dispatch, d->dispatchers) { dispatch->list(); } } Action *Dispatcher::command2Action(Context *ctx, const QByteArray &command, const QStringList &extraParams) { Q_D(Dispatcher); // qDebug() << Q_FUNC_INFO << "Command" << command; Action *ret = d->actionHash.value(command); if (!ret) { ret = invokeAsPath(ctx, command, ctx->args()); } return ret; } QStringList Dispatcher::unexcapedArgs(const QList<QByteArray> &args) { QStringList ret; Q_FOREACH (const QByteArray &arg, args) { ret.append(QUrl::fromPercentEncoding(arg)); } return ret; } QByteArray Dispatcher::actionRel2Abs(Context *ctx, const QByteArray &path) { QByteArray ret = path; if (!ret.startsWith('/')) { // TODO at Catalyst it uses // c->stack->last()->namespace ret.prepend('/'); ret.prepend(ctx->action()->ns()); } if (ret.startsWith('/')) { ret.remove(0, 1); } return ret; } Action *Dispatcher::invokeAsPath(Context *ctx, const QByteArray &relativePath, const QStringList &args) { Q_D(Dispatcher); Action *ret; QByteArray path = actionRel2Abs(ctx, relativePath); int pos = path.lastIndexOf('/'); int lastPos = path.size(); do { if (pos == -1) { ret = getAction(path, QByteArray()); if (ret) { return ret; } } else { QByteArray name = path.mid(pos + 1, lastPos); path = path.mid(0, pos); ret = getAction(name, path); if (ret) { return ret; } } lastPos = pos; pos = path.indexOf('/', pos - 1); } while (pos != -1); return 0; } QByteArray Dispatcher::cleanNamespace(const QByteArray &ns) const { QByteArray ret = ns; bool lastWasSlash = true; // remove initial slash int nsSize = ns.size(); const char * data = ret.constData(); for (int i = 0; i < nsSize; ++i) { if (data[i] == '/') { if (lastWasSlash) { ret.remove(i, 1); data = ret.constData(); --nsSize; } else { lastWasSlash = true; } } else { lastWasSlash = false; } } return ret; } ActionList DispatcherPrivate::getContainers(const QByteArray &ns) const { ActionList ret; if (ns != "/") { int pos = ns.size(); // qDebug() << pos << _ns.mid(0, pos); while (pos > 0) { // qDebug() << pos << _ns.mid(0, pos); ret.append(containerHash.value(ns.mid(0, pos))); pos = ns.lastIndexOf('/', pos - 1); } } ret.append(containerHash.value("")); return ret; } <|endoftext|>
<commit_before>/* * * RippleLikeWallet * * Created by El Khalil Bellakrid on 06/01/2019. * * The MIT License (MIT) * * Copyright (c) 2019 Ledger * * 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 "RippleLikeWallet.h" #include "RippleLikeAccount.h" #include <algorithm> #include <async/wait.h> #include <api/ErrorCode.hpp> #include <api/AccountCallback.hpp> #include <api/ConfigurationDefaults.hpp> #include <api/KeychainEngines.hpp> #include <ripple/RippleLikeExtendedPublicKey.h> #include <wallet/common/database/AccountDatabaseHelper.h> #include <wallet/ripple/database/RippleLikeAccountDatabaseHelper.h> namespace ledger { namespace core { const api::WalletType RippleLikeWallet::type = api::WalletType::ETHEREUM; RippleLikeWallet::RippleLikeWallet(const std::string &name, const std::shared_ptr<RippleLikeBlockchainExplorer> &explorer, const std::shared_ptr<RippleLikeBlockchainObserver> &observer, const std::shared_ptr<RippleLikeKeychainFactory> &keychainFactory, const RippleLikeAccountSynchronizerFactory &synchronizer, const std::shared_ptr<WalletPool> &pool, const api::Currency &network, const std::shared_ptr<DynamicObject> &configuration, const DerivationScheme &scheme ) : AbstractWallet(name, network, pool, configuration, scheme) { _explorer = explorer; _observer = observer; _keychainFactory = keychainFactory; _synchronizerFactory = synchronizer; } bool RippleLikeWallet::isSynchronizing() { return false; } std::shared_ptr<api::EventBus> RippleLikeWallet::synchronize() { return nullptr; } FuturePtr<ledger::core::api::Account> RippleLikeWallet::newAccountWithInfo(const api::AccountCreationInfo &info) { if (info.chainCodes.size() != 1 || info.publicKeys.size() != 1 || info.owners.size() != 1) throw make_exception(api::ErrorCode::INVALID_ARGUMENT, "Account creation info are inconsistent (only one public key is needed)"); auto self = getSelf(); return async<api::ExtendedKeyAccountCreationInfo>([self, info]() -> api::ExtendedKeyAccountCreationInfo { if (info.owners.size() != info.derivations.size() || info.owners.size() != info.chainCodes.size() || info.publicKeys.size() != info.owners.size()) throw make_exception(api::ErrorCode::INVALID_ARGUMENT, "Account creation info are inconsistent (size of arrays differs)"); api::ExtendedKeyAccountCreationInfo result; if (info.chainCodes[0].size() != 32 || info.publicKeys[0].size() != 33) throw make_exception(api::ErrorCode::INVALID_ARGUMENT, "Account creation info are inconsistent (contains invalid public key(s))"); DerivationPath occurencePath(info.derivations[0]); auto xpub = RippleLikeExtendedPublicKey::fromRaw( self->getCurrency(), Option<std::vector<uint8_t>>(), info.publicKeys[0], info.chainCodes[0], info.derivations[0] ); result.owners.push_back(info.owners[0]); result.derivations.push_back(info.derivations[0]); result.extendedKeys.push_back(xpub->toBase58()); result.index = info.index; return result; }).flatMap<std::shared_ptr<ledger::core::api::Account>>(getContext(), [self](const api::ExtendedKeyAccountCreationInfo &info) -> Future<std::shared_ptr<ledger::core::api::Account>> { return self->newAccountWithExtendedKeyInfo( info); }); } static int32_t getAccountIndex(const DerivationScheme &dPath, int32_t index) { // Set account index only if account level not hardened, // otherwise keep the one defined in derivation scheme return dPath.getSchemeTo(DerivationSchemeLevel::ACCOUNT_INDEX).getPath().isLastChildHardened() ? dPath.getAccountIndex() : index; } FuturePtr<ledger::core::api::Account> RippleLikeWallet::newAccountWithExtendedKeyInfo(const api::ExtendedKeyAccountCreationInfo &info) { if (info.extendedKeys.empty()) { throw make_exception(api::ErrorCode::INVALID_ARGUMENT, "Empty extended keys passed to newAccountWithExtendedKeyInfo"); } auto self = getSelf(); auto scheme = getDerivationScheme(); auto accountIndex = getAccountIndex(scheme, info.index); scheme.setCoinType(getCurrency().bip44CoinType).setAccountIndex(accountIndex); auto xpubPath = scheme.getSchemeTo(DerivationSchemeLevel::ACCOUNT_INDEX).getPath(); return async<std::shared_ptr<api::Account> >([=]() -> std::shared_ptr<api::Account> { auto keychain = self->_keychainFactory->build( accountIndex, xpubPath, getConfig(), info, getAccountInternalPreferences(accountIndex), getCurrency() ); soci::session sql(self->getDatabase()->getPool()); soci::transaction tr(sql); auto accountUid = AccountDatabaseHelper::createAccountUid(self->getWalletUid(), accountIndex); if (AccountDatabaseHelper::accountExists(sql, self->getWalletUid(), accountIndex)) throw make_exception(api::ErrorCode::ACCOUNT_ALREADY_EXISTS, "Account {}, for wallet '{}', already exists", accountIndex, self->getWalletUid()); AccountDatabaseHelper::createAccount(sql, self->getWalletUid(), accountIndex); RippleLikeAccountDatabaseHelper::createAccount(sql, self->getWalletUid(), accountIndex, info.extendedKeys[info.extendedKeys.size() - 1]); tr.commit(); auto account = std::static_pointer_cast<api::Account>(std::make_shared<RippleLikeAccount>( self->shared_from_this(), accountIndex, self->_explorer, self->_observer, self->_synchronizerFactory(), keychain )); self->addAccountInstanceToInstanceCache(std::dynamic_pointer_cast<AbstractAccount>(account)); return account; }); } static DerivationScheme getAccountScheme(DerivationScheme &scheme) { auto accountScheme = scheme.getSchemeTo(DerivationSchemeLevel::ACCOUNT_INDEX); // To handle all exotic paths we should avoid private derivations // So if node or/and address level are hardened, then they are included in account's derivation path auto path = scheme.getPath(); auto hardenedDepth = path.getDepth(); while (hardenedDepth) { if (path.isHardened(hardenedDepth - 1)) { break; } hardenedDepth--; } auto lastHardenedScheme = scheme.getSchemeToDepth(hardenedDepth); return accountScheme.getPath().getDepth() > lastHardenedScheme.getPath().getDepth() ? accountScheme : lastHardenedScheme; } Future<api::ExtendedKeyAccountCreationInfo> RippleLikeWallet::getExtendedKeyAccountCreationInfo(int32_t accountIndex) { auto self = std::dynamic_pointer_cast<RippleLikeWallet>(shared_from_this()); return async<api::ExtendedKeyAccountCreationInfo>( [self, accountIndex]() -> api::ExtendedKeyAccountCreationInfo { api::ExtendedKeyAccountCreationInfo info; auto scheme = self->getDerivationScheme(); info.index = getAccountIndex(scheme, accountIndex); scheme.setCoinType(self->getCurrency().bip44CoinType).setAccountIndex(info.index); auto keychainEngine = self->getConfiguration()->getString( api::Configuration::KEYCHAIN_ENGINE).value_or( api::ConfigurationDefaults::DEFAULT_KEYCHAIN); if (keychainEngine == api::KeychainEngines::BIP32_P2PKH || keychainEngine == api::KeychainEngines::BIP49_P2SH) { info.derivations.push_back(getAccountScheme(scheme).getPath().toString()); info.owners.push_back(std::string("main")); } else { throw make_exception(api::ErrorCode::IMPLEMENTATION_IS_MISSING, "No implementation found found for keychain {}", keychainEngine); } return info; }); } Future<api::AccountCreationInfo> RippleLikeWallet::getAccountCreationInfo(int32_t accountIndex) { auto self = std::dynamic_pointer_cast<RippleLikeWallet>(shared_from_this()); return getExtendedKeyAccountCreationInfo(accountIndex).map<api::AccountCreationInfo>(getContext(), [self, accountIndex](const api::ExtendedKeyAccountCreationInfo info) { api::AccountCreationInfo result; result.index = getAccountIndex(self->getDerivationScheme(), accountIndex); auto length = info.derivations.size(); for (auto i = 0; i < length; i++) { DerivationPath path(info.derivations[i]); auto owner = info.owners[i]; result.derivations.push_back(path.toString()); result.owners.push_back(owner); } return result; }); } std::shared_ptr<RippleLikeWallet> RippleLikeWallet::getSelf() { return std::dynamic_pointer_cast<RippleLikeWallet>(shared_from_this()); } std::shared_ptr<AbstractAccount> RippleLikeWallet::createAccountInstance(soci::session &sql, const std::string &accountUid) { RippleLikeAccountDatabaseEntry entry; RippleLikeAccountDatabaseHelper::queryAccount(sql, accountUid, entry); auto scheme = getDerivationScheme(); scheme.setCoinType(getCurrency().bip44CoinType).setAccountIndex(entry.index); auto xpubPath = getAccountScheme(scheme).getPath(); auto keychain = _keychainFactory->restore(entry.index, xpubPath, getConfig(), entry.address, getAccountInternalPreferences(entry.index), getCurrency()); return std::make_shared<RippleLikeAccount>(shared_from_this(), entry.index, _explorer, _observer, _synchronizerFactory(), keychain); } std::shared_ptr<RippleLikeBlockchainExplorer> RippleLikeWallet::getBlockchainExplorer() { return _explorer; } } } <commit_msg>Fix XRP accounts from being created with account index = 0.<commit_after>/* * * RippleLikeWallet * * Created by El Khalil Bellakrid on 06/01/2019. * * The MIT License (MIT) * * Copyright (c) 2019 Ledger * * 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 "RippleLikeWallet.h" #include "RippleLikeAccount.h" #include <algorithm> #include <async/wait.h> #include <api/ErrorCode.hpp> #include <api/AccountCallback.hpp> #include <api/ConfigurationDefaults.hpp> #include <api/KeychainEngines.hpp> #include <ripple/RippleLikeExtendedPublicKey.h> #include <wallet/common/database/AccountDatabaseHelper.h> #include <wallet/ripple/database/RippleLikeAccountDatabaseHelper.h> namespace ledger { namespace core { const api::WalletType RippleLikeWallet::type = api::WalletType::ETHEREUM; RippleLikeWallet::RippleLikeWallet(const std::string &name, const std::shared_ptr<RippleLikeBlockchainExplorer> &explorer, const std::shared_ptr<RippleLikeBlockchainObserver> &observer, const std::shared_ptr<RippleLikeKeychainFactory> &keychainFactory, const RippleLikeAccountSynchronizerFactory &synchronizer, const std::shared_ptr<WalletPool> &pool, const api::Currency &network, const std::shared_ptr<DynamicObject> &configuration, const DerivationScheme &scheme ) : AbstractWallet(name, network, pool, configuration, scheme) { _explorer = explorer; _observer = observer; _keychainFactory = keychainFactory; _synchronizerFactory = synchronizer; } bool RippleLikeWallet::isSynchronizing() { return false; } std::shared_ptr<api::EventBus> RippleLikeWallet::synchronize() { return nullptr; } FuturePtr<ledger::core::api::Account> RippleLikeWallet::newAccountWithInfo(const api::AccountCreationInfo &info) { if (info.chainCodes.size() != 1 || info.publicKeys.size() != 1 || info.owners.size() != 1) throw make_exception(api::ErrorCode::INVALID_ARGUMENT, "Account creation info are inconsistent (only one public key is needed)"); auto self = getSelf(); return async<api::ExtendedKeyAccountCreationInfo>([self, info]() -> api::ExtendedKeyAccountCreationInfo { if (info.owners.size() != info.derivations.size() || info.owners.size() != info.chainCodes.size() || info.publicKeys.size() != info.owners.size()) throw make_exception(api::ErrorCode::INVALID_ARGUMENT, "Account creation info are inconsistent (size of arrays differs)"); api::ExtendedKeyAccountCreationInfo result; if (info.chainCodes[0].size() != 32 || info.publicKeys[0].size() != 33) throw make_exception(api::ErrorCode::INVALID_ARGUMENT, "Account creation info are inconsistent (contains invalid public key(s))"); DerivationPath occurencePath(info.derivations[0]); auto xpub = RippleLikeExtendedPublicKey::fromRaw( self->getCurrency(), Option<std::vector<uint8_t>>(), info.publicKeys[0], info.chainCodes[0], info.derivations[0] ); result.owners.push_back(info.owners[0]); result.derivations.push_back(info.derivations[0]); result.extendedKeys.push_back(xpub->toBase58()); result.index = info.index; return result; }).flatMap<std::shared_ptr<ledger::core::api::Account>>(getContext(), [self](const api::ExtendedKeyAccountCreationInfo &info) -> Future<std::shared_ptr<ledger::core::api::Account>> { return self->newAccountWithExtendedKeyInfo( info); }); } static int32_t getAccountIndex(const DerivationScheme &dPath, int32_t index) { // Set account index only if account level not hardened, // otherwise keep the one defined in derivation scheme return dPath.getSchemeTo(DerivationSchemeLevel::ACCOUNT_INDEX).getPath().isLastChildHardened() ? dPath.getAccountIndex() : index; } FuturePtr<ledger::core::api::Account> RippleLikeWallet::newAccountWithExtendedKeyInfo(const api::ExtendedKeyAccountCreationInfo &info) { logger()->debug("Creating new XRP account (index = {}) with extended key info", info.index); if (info.extendedKeys.empty()) { throw make_exception(api::ErrorCode::INVALID_ARGUMENT, "Empty extended keys passed to newAccountWithExtendedKeyInfo"); } auto self = getSelf(); auto scheme = getDerivationScheme(); auto accountIndex = info.index; scheme.setCoinType(getCurrency().bip44CoinType).setAccountIndex(accountIndex); auto xpubPath = scheme.getSchemeTo(DerivationSchemeLevel::ACCOUNT_INDEX).getPath(); return async<std::shared_ptr<api::Account> >([=]() -> std::shared_ptr<api::Account> { auto keychain = self->_keychainFactory->build( accountIndex, xpubPath, getConfig(), info, getAccountInternalPreferences(accountIndex), getCurrency() ); soci::session sql(self->getDatabase()->getPool()); soci::transaction tr(sql); auto accountUid = AccountDatabaseHelper::createAccountUid(self->getWalletUid(), accountIndex); if (AccountDatabaseHelper::accountExists(sql, self->getWalletUid(), accountIndex)) throw make_exception(api::ErrorCode::ACCOUNT_ALREADY_EXISTS, "Account {}, for wallet '{}', already exists", accountIndex, self->getWalletUid()); AccountDatabaseHelper::createAccount(sql, self->getWalletUid(), accountIndex); RippleLikeAccountDatabaseHelper::createAccount(sql, self->getWalletUid(), accountIndex, info.extendedKeys[info.extendedKeys.size() - 1]); tr.commit(); auto account = std::static_pointer_cast<api::Account>(std::make_shared<RippleLikeAccount>( self->shared_from_this(), accountIndex, self->_explorer, self->_observer, self->_synchronizerFactory(), keychain )); self->addAccountInstanceToInstanceCache(std::dynamic_pointer_cast<AbstractAccount>(account)); return account; }); } static DerivationScheme getAccountScheme(DerivationScheme &scheme) { auto accountScheme = scheme.getSchemeTo(DerivationSchemeLevel::ACCOUNT_INDEX); // To handle all exotic paths we should avoid private derivations // So if node or/and address level are hardened, then they are included in account's derivation path auto path = scheme.getPath(); auto hardenedDepth = path.getDepth(); while (hardenedDepth) { if (path.isHardened(hardenedDepth - 1)) { break; } hardenedDepth--; } auto lastHardenedScheme = scheme.getSchemeToDepth(hardenedDepth); return accountScheme.getPath().getDepth() > lastHardenedScheme.getPath().getDepth() ? accountScheme : lastHardenedScheme; } Future<api::ExtendedKeyAccountCreationInfo> RippleLikeWallet::getExtendedKeyAccountCreationInfo(int32_t accountIndex) { auto self = std::dynamic_pointer_cast<RippleLikeWallet>(shared_from_this()); return async<api::ExtendedKeyAccountCreationInfo>( [self, accountIndex]() -> api::ExtendedKeyAccountCreationInfo { api::ExtendedKeyAccountCreationInfo info; auto scheme = self->getDerivationScheme(); info.index = getAccountIndex(scheme, accountIndex); scheme.setCoinType(self->getCurrency().bip44CoinType).setAccountIndex(info.index); auto keychainEngine = self->getConfiguration()->getString( api::Configuration::KEYCHAIN_ENGINE).value_or( api::ConfigurationDefaults::DEFAULT_KEYCHAIN); if (keychainEngine == api::KeychainEngines::BIP32_P2PKH || keychainEngine == api::KeychainEngines::BIP49_P2SH) { info.derivations.push_back(getAccountScheme(scheme).getPath().toString()); info.owners.push_back(std::string("main")); } else { throw make_exception(api::ErrorCode::IMPLEMENTATION_IS_MISSING, "No implementation found found for keychain {}", keychainEngine); } return info; }); } Future<api::AccountCreationInfo> RippleLikeWallet::getAccountCreationInfo(int32_t accountIndex) { auto self = std::dynamic_pointer_cast<RippleLikeWallet>(shared_from_this()); return getExtendedKeyAccountCreationInfo(accountIndex).map<api::AccountCreationInfo>(getContext(), [self, accountIndex](const api::ExtendedKeyAccountCreationInfo info) { api::AccountCreationInfo result; result.index = getAccountIndex(self->getDerivationScheme(), accountIndex); auto length = info.derivations.size(); for (auto i = 0; i < length; i++) { DerivationPath path(info.derivations[i]); auto owner = info.owners[i]; result.derivations.push_back(path.toString()); result.owners.push_back(owner); } return result; }); } std::shared_ptr<RippleLikeWallet> RippleLikeWallet::getSelf() { return std::dynamic_pointer_cast<RippleLikeWallet>(shared_from_this()); } std::shared_ptr<AbstractAccount> RippleLikeWallet::createAccountInstance(soci::session &sql, const std::string &accountUid) { RippleLikeAccountDatabaseEntry entry; RippleLikeAccountDatabaseHelper::queryAccount(sql, accountUid, entry); auto scheme = getDerivationScheme(); scheme.setCoinType(getCurrency().bip44CoinType).setAccountIndex(entry.index); auto xpubPath = getAccountScheme(scheme).getPath(); auto keychain = _keychainFactory->restore(entry.index, xpubPath, getConfig(), entry.address, getAccountInternalPreferences(entry.index), getCurrency()); return std::make_shared<RippleLikeAccount>(shared_from_this(), entry.index, _explorer, _observer, _synchronizerFactory(), keychain); } std::shared_ptr<RippleLikeBlockchainExplorer> RippleLikeWallet::getBlockchainExplorer() { return _explorer; } } } <|endoftext|>
<commit_before>#include "csparser.h" #include "cutscenes_defaults.h" #include <fstream> #include <cstring> //strtok #include <iterator> //istreambuf_iterator #include <cstdlib> #include <algorithm> //ererase #include <sstream> CsParser::CsParser(const std::vector<std::string> &imagePaths) : _image_paths(imagePaths), _version(0), _defaults_file_path(""), _error_message("") { } bool CsParser::parse(const std::string &csPath) { std::ifstream file; file.open(csPath.c_str(), std::ios_base::in); std::istreambuf_iterator<char> i(file.rdbuf()); if (!parseHeader(i)){ _error_message = "error parsing header"; return false; } if (_defaults_file_path != ""){ if (!parseDefaults()){ _error_message = "error parsing "+_defaults_file_path; return false; } } if (!parseDeclarations(i)){ _error_message = "error parsing declarations"; return false; } if (!parseAnimations(i)){ _error_message = "error parsing animations"; return false; } return true; } std::string CsParser::getErrorMessage() const { return _error_message; } std::vector<CsObject> CsParser::objects() const { return _objects; } std::map<std::string, CsStep> CsParser::steps() const { return _steps; } std::vector<std::string> CsParser::startingSteps() const { return _starting_steps; } bool CsParser::parseInt(const std::string &in, int *out) { std::string found; if (!regexMatchSingle("[+-]?[0-9]+", in, &found)) return false; *out = atoi(found.c_str()); return true; } bool CsParser::parseFloat(const std::string &in, float *out) { std::string found; if (!regexMatchSingle("[-+]?[0-9]*\\.?[0-9]*", in, &found)) return false; char *endptr; *out = strtof(found.c_str(), &endptr); if (endptr != (found.c_str() + found.length())) return false; return true; } bool CsParser::parseString(const std::string &in, std::string *out) { *out = ""; std::string::const_iterator i; for (i = in.begin(); i != in.end(); ++i){ if ((*i) == ' '){ if ((i+1) != in.end() && *(i+1) != ' ' && *out != "") return false; continue; } *out += (*i); } if (*out == "") return false; return true; } bool CsParser::parseQuotedString(const std::string &in, std::string *out) { if (!regexMatchSingle("\"[^\"]*\"", in, out)) return false; strip(*out, '"'); return true; } bool CsParser::parseState(std::string *in, CsState *s) { strip(*in, ' '); while (in->length() > 0) { std::string token = removeFirstSlice(in, ","); std::string var; if (token == ""){ token = *in; in->clear(); } var = removeFirstSlice(&token, ":"); if (var == "") break; if (var != "x" && var != "y" && var != "width" && var != "height" && var != "alpha"){ return false; } std::string stateName = var; float stateValue; if (!parseFloat(token, &stateValue)) return false; (*s)[stateName] = stateValue; } return true; } std::string CsParser::readline(std::istreambuf_iterator<char> &i) { std::istreambuf_iterator<char> eof; std::string line = ""; while (i != eof && (*i) != '\n'){ line += (*i); ++i; } ++i; return line; } void CsParser::strip(std::string &string, const char expr) { string.erase(std::remove(string.begin(), string.end(), expr), string.end()); } std::string CsParser::removeFirstSlice(std::string *in, const std::string &separator) { std::string result; size_t c_pos = findUnquoted(*in, separator); if (c_pos == std::string::npos) return ""; result = in->substr(0, c_pos); *in = in->substr(c_pos + separator.length()); return result; } bool CsParser::regexMatchSingle(const std::string &expression, const std::string &input, std::string *output) { TRexpp regex; const char *found = ""; const char *last = ""; regex.Compile(expression.c_str()); regex.Search(input.c_str(), &found, &last); std::string last_str(last); if (last_str.length() > 0){ strip(last_str, ' '); if (last_str.length() > 0){ return false; } } output->assign(found); if (output->length() > 0) return true; return false; } bool CsParser::parseHeader(std::istreambuf_iterator<char> &i) { std::istreambuf_iterator<char> eof; std::string line = ""; while (true){ if (i == eof) return false; line = readline(i); if (line.substr(0,3) == "###") break; } //getting version number and definitions file line = line.substr(3); strip(line, ' '); std::string version = removeFirstSlice(&line, ","); if(version == ""){ return parseInt(line, &_version); } if (!parseInt(version, &_version)) return false; if (!parseQuotedString(line, &_defaults_file_path)) return false; return true; } bool CsParser::parseDeclaration(std::string d_string) { CsObject obj; if (!parseString(removeFirstSlice(&d_string, ":"), &(obj.name))){ strip(d_string, ' '); if (d_string.length() > 0) return false; return true; } if (!parseQuotedString(removeFirstSlice(&d_string, ","), &(obj.content))) return false; obj.isText = false; std::vector<std::string>::const_iterator i = find(_image_paths.begin(), _image_paths.end(), obj.content); if (i == _image_paths.end()) obj.isText = true; strip(d_string, ' '); replaceWDefaults(d_string); if (!parseState(&d_string, &(obj.state))) return false; if(d_string.length() > 0) return false; _objects.push_back(obj); return true; } bool CsParser::parseDeclarations(std::istreambuf_iterator<char> &i) { std::string line = ""; std::istreambuf_iterator<char> eof; while(i != eof){ line = readline(i); if (line.find("---") != std::string::npos) break; if (!parseDeclaration(line)) return false; } return true; } bool CsParser::parseStepContent(std::string &line, CsStep &step) { std::string objectName; if (!parseString(removeFirstSlice(&line, ":"), &objectName)){ strip(line, ' '); if (line != "") return false; return true; } strip(line, ' '); replaceWDefaults(line); CsState s; if (!isObject(objectName)) return false; if (!parseState(&line, &s)) return false; step.objStates[objectName] = s; return true; } bool CsParser::parseSubSteps(std::istreambuf_iterator<char> &i, std::string &line, const std::string &name, int *n) { std::istreambuf_iterator<char> eof; line = readline(i); while(i != eof){ CsStep step; step.duration = -1; if (line.find("->") != std::string::npos) break; if (line.find(":") != std::string::npos) return false; strip(line, ' '); if (line == ""){ line = readline(i); continue; } if (!parseInt(line, &(step.duration))) return false; line = readline(i); while(i != eof && line.find(":") != std::string::npos && line.find("->") == std::string::npos){ if (!parseStepContent(line, step)) return false; line = readline(i); } if (*n > 0){ _steps[name+intToString((*n)-1)].next.push_back(name+intToString(*n)); } _steps[name+intToString(*n)] = step; (*n)++; } (*n)--; return true; } bool CsParser::parseAnimations(std::istreambuf_iterator<char> &i) { std::istreambuf_iterator<char> eof; std::map<std::string, int> steps_length; std::string line = readline(i); while (i != eof){ if (line.substr(0, 2) != "->"){ strip(line, ' '); if (line != "") return false; line = readline(i); continue; } line = line.substr(2); //parsing step header std::string name_str = removeFirstSlice(&line, ","); std::string prev = ""; if (name_str != ""){ if(!parseString(line, &prev)) return false; } else { name_str = line; } std::string name; if (!parseString(name_str, &name)) return false; int stepNumber = 0; if (!parseSubSteps(i, line, name, &stepNumber)) return false; steps_length[name] = stepNumber; if (prev != ""){ std::map<std::string, CsStep>::iterator i =_steps.find(prev+intToString(steps_length[prev])); if (i == _steps.end()) return false; (*i).second.next.push_back(name+"0"); } else { _starting_steps.push_back(name+"0"); } } return true; } void CsParser::mapReplace(std::map<std::string, std::string> m, std::string &string) { std::map<std::string, std::string>::iterator i; for (i = m.begin(); i != m.end(); ++i){ size_t start_pos = 0; while((start_pos = string.find((*i).first, start_pos)) != std::string::npos) string.replace(start_pos, (*i).first.length(), (*i).second); } } void CsParser::replaceWDefaults(std::string &string) { mapReplace(_defaults, string); mapReplace(Defaults::declarations, string); } bool CsParser::parseDefaults() { std::ifstream file; file.open(_defaults_file_path.c_str(), std::ios_base::in); std::istreambuf_iterator<char> i(file.rdbuf()); std::istreambuf_iterator<char> eof; std::string line = ""; while (i != eof){ line = readline(i); strip(line, ' '); size_t arrow_pos = line.find("=>"); if (arrow_pos == std::string::npos){ if (line.length() > 0) return false; continue; } std::string var = ""; if (!parseString(line.substr(0, arrow_pos), &var)) return false; _defaults[var] = line.substr(arrow_pos + 2); } return true; } bool CsParser::isObject(const std::string &name) { std::vector<CsObject>::iterator i; for (i = _objects.begin(); i != _objects.end(); ++i){ if ((*i).name == name) return true; } return false; } size_t findUnquoted(const std::string &input, const std::string &toFind) { int n = input.length(); int m = toFind.length(); size_t i = 0; while (int(i) < n-m){ if (input.at(i) == '"'){ ++i; while (input.at(i) != '"' && int(i) < n-m) ++i; } int j = 0; while (j < m && input.at(i+j) == toFind.at(j)) ++j; if (j == m) return i; i++; } return std::string::npos; } std::string intToString(int i) { std::stringstream ss; std::string s; ss << i; s = ss.str(); return s; } <commit_msg>parser sops after the last line<commit_after>#include "csparser.h" #include "cutscenes_defaults.h" #include <fstream> #include <cstring> //strtok #include <iterator> //istreambuf_iterator #include <cstdlib> #include <algorithm> //ererase #include <sstream> CsParser::CsParser(const std::vector<std::string> &imagePaths) : _image_paths(imagePaths), _version(0), _defaults_file_path(""), _error_message("") { } bool CsParser::parse(const std::string &csPath) { std::ifstream file; file.open(csPath.c_str(), std::ios_base::in); std::istreambuf_iterator<char> i(file.rdbuf()); if (!parseHeader(i)){ _error_message = "error parsing header"; return false; } if (_defaults_file_path != ""){ if (!parseDefaults()){ _error_message = "error parsing "+_defaults_file_path; return false; } } if (!parseDeclarations(i)){ _error_message = "error parsing declarations"; return false; } if (!parseAnimations(i)){ _error_message = "error parsing animations"; return false; } return true; } std::string CsParser::getErrorMessage() const { return _error_message; } std::vector<CsObject> CsParser::objects() const { return _objects; } std::map<std::string, CsStep> CsParser::steps() const { return _steps; } std::vector<std::string> CsParser::startingSteps() const { return _starting_steps; } bool CsParser::parseInt(const std::string &in, int *out) { std::string found; if (!regexMatchSingle("[+-]?[0-9]+", in, &found)) return false; *out = atoi(found.c_str()); return true; } bool CsParser::parseFloat(const std::string &in, float *out) { std::string found; if (!regexMatchSingle("[-+]?[0-9]*\\.?[0-9]*", in, &found)) return false; char *endptr; *out = strtof(found.c_str(), &endptr); if (endptr != (found.c_str() + found.length())) return false; return true; } bool CsParser::parseString(const std::string &in, std::string *out) { *out = ""; std::string::const_iterator i; for (i = in.begin(); i != in.end(); ++i){ if ((*i) == ' '){ if ((i+1) != in.end() && *(i+1) != ' ' && *out != "") return false; continue; } *out += (*i); } if (*out == "") return false; return true; } bool CsParser::parseQuotedString(const std::string &in, std::string *out) { if (!regexMatchSingle("\"[^\"]*\"", in, out)) return false; strip(*out, '"'); return true; } bool CsParser::parseState(std::string *in, CsState *s) { strip(*in, ' '); while (in->length() > 0) { std::string token = removeFirstSlice(in, ","); std::string var; if (token == ""){ token = *in; in->clear(); } var = removeFirstSlice(&token, ":"); if (var == "") break; if (var != "x" && var != "y" && var != "width" && var != "height" && var != "alpha"){ return false; } std::string stateName = var; float stateValue; if (!parseFloat(token, &stateValue)) return false; (*s)[stateName] = stateValue; } return true; } std::string CsParser::readline(std::istreambuf_iterator<char> &i) { std::istreambuf_iterator<char> eof; std::string line = ""; while (i != eof && (*i) != '\n'){ line += (*i); ++i; } ++i; return line; } void CsParser::strip(std::string &string, const char expr) { string.erase(std::remove(string.begin(), string.end(), expr), string.end()); } std::string CsParser::removeFirstSlice(std::string *in, const std::string &separator) { std::string result; size_t c_pos = findUnquoted(*in, separator); if (c_pos == std::string::npos) return ""; result = in->substr(0, c_pos); *in = in->substr(c_pos + separator.length()); return result; } bool CsParser::regexMatchSingle(const std::string &expression, const std::string &input, std::string *output) { TRexpp regex; const char *found = ""; const char *last = ""; regex.Compile(expression.c_str()); regex.Search(input.c_str(), &found, &last); std::string last_str(last); if (last_str.length() > 0){ strip(last_str, ' '); if (last_str.length() > 0){ return false; } } output->assign(found); if (output->length() > 0) return true; return false; } bool CsParser::parseHeader(std::istreambuf_iterator<char> &i) { std::istreambuf_iterator<char> eof; std::string line = ""; while (true){ if (i == eof) return false; line = readline(i); if (line.substr(0,3) == "###") break; } //getting version number and definitions file line = line.substr(3); strip(line, ' '); std::string version = removeFirstSlice(&line, ","); if(version == ""){ return parseInt(line, &_version); } if (!parseInt(version, &_version)) return false; if (!parseQuotedString(line, &_defaults_file_path)) return false; return true; } bool CsParser::parseDeclaration(std::string d_string) { CsObject obj; if (!parseString(removeFirstSlice(&d_string, ":"), &(obj.name))){ strip(d_string, ' '); if (d_string.length() > 0) return false; return true; } if (!parseQuotedString(removeFirstSlice(&d_string, ","), &(obj.content))) return false; obj.isText = false; std::vector<std::string>::const_iterator i = find(_image_paths.begin(), _image_paths.end(), obj.content); if (i == _image_paths.end()) obj.isText = true; strip(d_string, ' '); replaceWDefaults(d_string); if (!parseState(&d_string, &(obj.state))) return false; if(d_string.length() > 0) return false; _objects.push_back(obj); return true; } bool CsParser::parseDeclarations(std::istreambuf_iterator<char> &i) { std::string line = ""; std::istreambuf_iterator<char> eof; while(i != eof){ line = readline(i); if (line.find("---") != std::string::npos) break; if (!parseDeclaration(line)) return false; } return true; } bool CsParser::parseStepContent(std::string &line, CsStep &step) { std::string objectName; if (!parseString(removeFirstSlice(&line, ":"), &objectName)){ strip(line, ' '); if (line != "") return false; return true; } strip(line, ' '); replaceWDefaults(line); CsState s; if (!isObject(objectName)) return false; if (!parseState(&line, &s)) return false; step.objStates[objectName] = s; return true; } bool CsParser::parseSubSteps(std::istreambuf_iterator<char> &i, std::string &line, const std::string &name, int *n) { std::istreambuf_iterator<char> eof; line = readline(i); while(i != eof){ CsStep step; step.duration = -1; if (line.find("->") != std::string::npos) break; if (line.find(":") != std::string::npos) return false; strip(line, ' '); if (line == ""){ line = readline(i); continue; } if (!parseInt(line, &(step.duration))) return false; line = readline(i); while(line.find(":") != std::string::npos && line.find("->") == std::string::npos){ if (!parseStepContent(line, step)) return false; if (i == eof) break; line = readline(i); } if (*n > 0){ _steps[name+intToString((*n)-1)].next.push_back(name+intToString(*n)); } _steps[name+intToString(*n)] = step; (*n)++; } (*n)--; return true; } bool CsParser::parseAnimations(std::istreambuf_iterator<char> &i) { std::istreambuf_iterator<char> eof; std::map<std::string, int> steps_length; std::string line = readline(i); while (i != eof){ if (line.substr(0, 2) != "->"){ strip(line, ' '); if (line != "") return false; line = readline(i); continue; } line = line.substr(2); //parsing step header std::string name_str = removeFirstSlice(&line, ","); std::string prev = ""; if (name_str != ""){ if(!parseString(line, &prev)) return false; } else { name_str = line; } std::string name; if (!parseString(name_str, &name)) return false; int stepNumber = 0; if (!parseSubSteps(i, line, name, &stepNumber)) return false; steps_length[name] = stepNumber; if (prev != ""){ std::map<std::string, CsStep>::iterator i =_steps.find(prev+intToString(steps_length[prev])); if (i == _steps.end()) return false; (*i).second.next.push_back(name+"0"); } else { _starting_steps.push_back(name+"0"); } } return true; } void CsParser::mapReplace(std::map<std::string, std::string> m, std::string &string) { std::map<std::string, std::string>::iterator i; for (i = m.begin(); i != m.end(); ++i){ size_t start_pos = 0; while((start_pos = string.find((*i).first, start_pos)) != std::string::npos) string.replace(start_pos, (*i).first.length(), (*i).second); } } void CsParser::replaceWDefaults(std::string &string) { mapReplace(_defaults, string); mapReplace(Defaults::declarations, string); } bool CsParser::parseDefaults() { std::ifstream file; file.open(_defaults_file_path.c_str(), std::ios_base::in); std::istreambuf_iterator<char> i(file.rdbuf()); std::istreambuf_iterator<char> eof; std::string line = ""; while (i != eof){ line = readline(i); strip(line, ' '); size_t arrow_pos = line.find("=>"); if (arrow_pos == std::string::npos){ if (line.length() > 0) return false; continue; } std::string var = ""; if (!parseString(line.substr(0, arrow_pos), &var)) return false; _defaults[var] = line.substr(arrow_pos + 2); } return true; } bool CsParser::isObject(const std::string &name) { std::vector<CsObject>::iterator i; for (i = _objects.begin(); i != _objects.end(); ++i){ if ((*i).name == name) return true; } return false; } size_t findUnquoted(const std::string &input, const std::string &toFind) { int n = input.length(); int m = toFind.length(); size_t i = 0; while (int(i) < n-m){ if (input.at(i) == '"'){ ++i; while (input.at(i) != '"' && int(i) < n-m) ++i; } int j = 0; while (j < m && input.at(i+j) == toFind.at(j)) ++j; if (j == m) return i; i++; } return std::string::npos; } std::string intToString(int i) { std::stringstream ss; std::string s; ss << i; s = ss.str(); return s; } <|endoftext|>
<commit_before>#include <sstream> #include <iostream> #include <stdio.h> #include <unistd.h> #include "errno.h" #include <string> #include <list> #include <string.h> #include <vector> #include <cstdlib> #include <sys/wait.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> //#include "redir.h" using namespace std; void fixing_spacing_command(char *org_prompt, int check_redir) { char *fin_prompt = (char*)malloc(50000); char connect[4]; connect[0] = ';'; connect[1] = '&'; connect[2] = '|'; connect[3] = '#'; connect[4] = '>'; //x is passed in prompt //i is finished prompt after changing spaces for(int x = 0,i = 0; org_prompt[x] != '\0'; x++, i++) { if(org_prompt[x] == connect[3]) { org_prompt[x] = '\0'; fin_prompt[i] = '\0'; } else if(org_prompt[x] == connect[0]) { fin_prompt[i] = ' '; fin_prompt[++i] = ';'; fin_prompt[++i] = ' '; } else if(org_prompt[x] == connect[1] && org_prompt[x + 1] == connect[1]) { fin_prompt[i] = ' '; fin_prompt[++i] = '&'; fin_prompt[++i] = '&'; fin_prompt[++i] = ' '; ++x; } else if(org_prompt[x] == connect[3] && org_prompt[x + 1] == connect[3]) { fin_prompt[i] = ' '; fin_prompt[++i] = '|'; fin_prompt[++i] = '|'; fin_prompt[++i] = ' '; ++x; } else if(org_prompt[x] == connect[4]) { check_redir = 1; //redir 1 means one output bracket fin_prompt[i] = ';'; fin_prompt[++i] = ' '; fin_prompt[++i] = ' '; fin_prompt[++i] = ' '; ++x; } else { fin_prompt[i] = org_prompt[x]; } if(org_prompt[x + 1] == '\0') fin_prompt[i + 1] = '\0'; } strcpy(org_prompt, fin_prompt); //copies altered version } int exec_status; bool str_continue = true; bool execute(char* command, char* command_list[], int conect_type, bool redir) { cout << "conect:type: " << conect_type << endl; int status; int process_ID = fork(); if(process_ID <= -1) { perror("Error occured during forking()"); exit(1); } else if(process_ID == 0) //child process { if(redir) { cout << "did this output" << endl; int fd; if((fd = open("outfile", O_RDWR | O_CREAT | O_TRUNC, 0744)) == -1) { perror("open"); } if(close(1) == -1) { perror("close"); } if(dup(fd) == -1) { perror("dup"); } exec_status = (execvp(command, command_list)); //cout << "output exec status: " << exec_status << endl; if(exec_status == -1) { perror("error with passed in argument list"); return exec_status; exit(1); } } else { cout << "this is wrong" << endl; exec_status = (execvp(command, command_list)); //cout << "output exec status: " << exec_status << endl; if(exec_status == -1) { perror("error with passed in argument list"); return exec_status; exit(1); } } } else if(process_ID > 0) //parent process { if(waitpid(process_ID, &status,0) == -1) { perror("error with waitpid()"); } } return(!(status == 0 && conect_type == -1) ||( status > 0 && conect_type == 2)); } int check_connections(char* check) { if(!strcmp(check, ";")) return 0; else if(!strcmp(check, "||")) return 1; else if(!strcmp(check, "&&")) return 2; else if(!strcmp(check, ">")) return 3; else return -1; } void check_exit(char *str) { if(!strcmp(str, "exit")) { exit(0); } } bool chk_redir(string s) { for(int x = 0; x < s.size(); x++) { if(s.at(x) == '>') { return true; } } return false; } int main(int argc, char **argv) { int check_redir = 0; /////////////////////////////////////////////// int sequence = 0; //sequence of which is executable and flags char* host = (char*)malloc(500); string userinfo; bool prompter = true; char* token; //will be bit of code strtok cuts off bool exec_result = true; //error checks the user if(getlogin() != NULL) { userinfo = getlogin(); } else { perror("error getting user info"); } if(gethostname(host, 500) == -1) { perror("Error getting host name"); } //outputs the userinfo with login and host while(prompter) { cout << userinfo << "@" << host << " $ "; //////////////////////////////////////////////login part done, next is all shell commands char prompt_holder[50000];//orginal array to hold prompt char *comd_arr[50000]; for(int x = 0; x < 50001; x++) { prompt_holder[x] = 0; comd_arr[x] = 0; } unsigned int comd_arr_cnt = 0; str_continue = true; //string converter; //converts all bits of string into one piece string to_be_tokenized; getline(cin, to_be_tokenized); bool to_redir; to_redir = chk_redir(to_be_tokenized);//checks if there is redirection sign in command for(unsigned int x = 0; x < to_be_tokenized.size(); x++) { prompt_holder[x] = to_be_tokenized.at(x); } fixing_spacing_command(prompt_holder, check_redir); int connect_check; //indicates which connection is in token token = strtok(prompt_holder, "\t "); //cout << "output token: " << token << endl; exec_result = true; while(token != NULL && exec_result && str_continue) { connect_check = check_connections(token); check_exit(token); if(connect_check == -1 && sequence < 1 && str_continue) { //cout << "does this come out on top" << endl; check_exit(token); comd_arr[comd_arr_cnt] = token; comd_arr_cnt++; sequence++; //increment only once to see which is executable } else if(sequence > 0 && connect_check == -1 && str_continue) { comd_arr[comd_arr_cnt] = token; comd_arr_cnt++; } else if(connect_check != -1) { check_exit(token); comd_arr[comd_arr_cnt] = '\0' ; sequence = 0; comd_arr_cnt = 0; //cout << "does it output second iteration " << endl; exec_result = execute(comd_arr[0], comd_arr, connect_check, to_redir); //cout << "output exec_status: " << exec_status << endl; //cout << "output exec_result tho: " << exec_result << endl; //cout << "connect_check: " << connect_check << endl; //cout << "str_continue: " << str_continue << endl; if(exec_status == 0) { if(connect_check == 2) { str_continue = false; //cout << "str_continue: " << str_continue << endl; } if(connect_check == 1) { str_continue = false; } } if(exec_result == 1) { if(connect_check == 2) { str_continue = true; } } } token = strtok(NULL, "\t "); if(connect_check == -1 && token == NULL && exec_result && str_continue) { cout << "guess this executeisw ith this " << endl; comd_arr[comd_arr_cnt] = '\0'; execute(comd_arr[0], comd_arr, connect_check, to_redir); } } } } /* || && ; succeeds || notsucceed && ls -a [ls] [-a] exekcvp([ls],[[ls],[-a]]) char* argumentList[50000]; char executable[50000]; argumentList[0] = executable; unsigned int size = 0; ls -a \0 execvp(argumentList[0], argumentList); */ <commit_msg>got second redirection symbol working<commit_after>#include <sstream> #include <iostream> #include <stdio.h> #include <unistd.h> #include "errno.h" #include <string> #include <list> #include <string.h> #include <vector> #include <cstdlib> #include <sys/wait.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> //#include "redir.h" using namespace std; void fixing_spacing_command(char *org_prompt, int check_redir) { char *fin_prompt = (char*)malloc(50000); char connect[4]; connect[0] = ';'; connect[1] = '&'; connect[2] = '|'; connect[3] = '#'; connect[4] = '>'; //x is passed in prompt //i is finished prompt after changing spaces for(int x = 0,i = 0; org_prompt[x] != '\0'; x++, i++) { if(org_prompt[x] == connect[3]) { org_prompt[x] = '\0'; fin_prompt[i] = '\0'; } else if(org_prompt[x] == connect[0]) { fin_prompt[i] = ' '; fin_prompt[++i] = ';'; fin_prompt[++i] = ' '; } else if(org_prompt[x] == connect[1] && org_prompt[x + 1] == connect[1]) { fin_prompt[i] = ' '; fin_prompt[++i] = '&'; fin_prompt[++i] = '&'; fin_prompt[++i] = ' '; ++x; } else if(org_prompt[x] == connect[3] && org_prompt[x + 1] == connect[3]) { fin_prompt[i] = ' '; fin_prompt[++i] = '|'; fin_prompt[++i] = '|'; fin_prompt[++i] = ' '; ++x; } else if(org_prompt[x] == connect[4]) { check_redir = 1; //redir 1 means one output bracket fin_prompt[i] = ';'; fin_prompt[++i] = ' '; fin_prompt[++i] = ' '; fin_prompt[++i] = ' '; ++x; } else { fin_prompt[i] = org_prompt[x]; } if(org_prompt[x + 1] == '\0') fin_prompt[i + 1] = '\0'; } strcpy(org_prompt, fin_prompt); //copies altered version } int exec_status; bool str_continue = true; bool execute(char* command, char* command_list[], int conect_type, int redir) { cout << "conect:type: " << conect_type << endl; int status; int process_ID = fork(); if(process_ID <= -1) { perror("Error occured during forking()"); exit(1); } else if(process_ID == 0) //child process { if(redir == 1) { cout << "did this output" << endl; int fd; if((fd = open("outfile", O_RDWR | O_CREAT | O_TRUNC, 0744)) == -1) { perror("open"); } if(close(1) == -1) { perror("close"); } if(dup(fd) == -1) { perror("dup"); } exec_status = (execvp(command, command_list)); //cout << "output exec status: " << exec_status << endl; if(exec_status == -1) { perror("error with passed in argument list"); return exec_status; exit(1); } } if(redir == 2) { cout << "yay this should output now" << endl; int fd; if((fd = open("outfile", O_RDWR | O_CREAT | O_APPEND, 0744)) == -1) { perror("open"); } if(close(1) == -1) { perror("close"); } if(dup(fd) == -1) { perror("dup"); } exec_status = (execvp(command, command_list)); //cout << "output exec status: " << exec_status << endl; if(exec_status == -1) { perror("error with passed in argument list"); return exec_status; exit(1); } } else { cout << "this is wrong" << endl; exec_status = (execvp(command, command_list)); //cout << "output exec status: " << exec_status << endl; if(exec_status == -1) { perror("error with passed in argument list"); return exec_status; exit(1); } } } else if(process_ID > 0) //parent process { if(waitpid(process_ID, &status,0) == -1) { perror("error with waitpid()"); } } return(!(status == 0 && conect_type == -1) ||( status > 0 && conect_type == 2)); } int check_connections(char* check) { if(!strcmp(check, ";")) return 0; else if(!strcmp(check, "||")) return 1; else if(!strcmp(check, "&&")) return 2; else if(!strcmp(check, ">")) return 3; else return -1; } void check_exit(char *str) { if(!strcmp(str, "exit")) { exit(0); } } int chk_redir(string s) { for(int x = 0; x < s.size(); x++) { //cout << "output x: " << x << endl; if(s.at(x) == '>') { //cout << "output x: " << endl; int y = x; if(y++ < s.size() && s.at(x) == '>') { return 2; } else {return 1;} } } return 0; } int main(int argc, char **argv) { int check_redir = 0; /////////////////////////////////////////////// int sequence = 0; //sequence of which is executable and flags char* host = (char*)malloc(500); string userinfo; bool prompter = true; char* token; //will be bit of code strtok cuts off bool exec_result = true; //error checks the user if(getlogin() != NULL) { userinfo = getlogin(); } else { perror("error getting user info"); } if(gethostname(host, 500) == -1) { perror("Error getting host name"); } //outputs the userinfo with login and host while(prompter) { cout << userinfo << "@" << host << " $ "; //////////////////////////////////////////////login part done, next is all shell commands char prompt_holder[50000];//orginal array to hold prompt char *comd_arr[50000]; for(int x = 0; x < 50001; x++) { prompt_holder[x] = 0; comd_arr[x] = 0; } unsigned int comd_arr_cnt = 0; str_continue = true; //string converter; //converts all bits of string into one piece string to_be_tokenized; getline(cin, to_be_tokenized); int to_redir; //certain number corresponds to what redirection it is to_redir = chk_redir(to_be_tokenized);//checks if there is redirection sign in command for(unsigned int x = 0; x < to_be_tokenized.size(); x++) { prompt_holder[x] = to_be_tokenized.at(x); } fixing_spacing_command(prompt_holder, check_redir); int connect_check; //indicates which connection is in token token = strtok(prompt_holder, "\t "); //cout << "output token: " << token << endl; exec_result = true; while(token != NULL && exec_result && str_continue) { connect_check = check_connections(token); check_exit(token); if(connect_check == -1 && sequence < 1 && str_continue) { //cout << "does this come out on top" << endl; check_exit(token); comd_arr[comd_arr_cnt] = token; comd_arr_cnt++; sequence++; //increment only once to see which is executable } else if(sequence > 0 && connect_check == -1 && str_continue) { comd_arr[comd_arr_cnt] = token; comd_arr_cnt++; } else if(connect_check != -1) { check_exit(token); comd_arr[comd_arr_cnt] = '\0' ; sequence = 0; comd_arr_cnt = 0; //cout << "does it output second iteration " << endl; exec_result = execute(comd_arr[0], comd_arr, connect_check, to_redir); //cout << "output exec_status: " << exec_status << endl; //cout << "output exec_result tho: " << exec_result << endl; //cout << "connect_check: " << connect_check << endl; //cout << "str_continue: " << str_continue << endl; if(exec_status == 0) { if(connect_check == 2) { str_continue = false; //cout << "str_continue: " << str_continue << endl; } if(connect_check == 1) { str_continue = false; } } if(exec_result == 1) { if(connect_check == 2) { str_continue = true; } } } token = strtok(NULL, "\t "); if(connect_check == -1 && token == NULL && exec_result && str_continue) { cout << "guess this executeisw ith this " << endl; comd_arr[comd_arr_cnt] = '\0'; execute(comd_arr[0], comd_arr, connect_check, to_redir); } } } } /* || && ; succeeds || notsucceed && ls -a [ls] [-a] exekcvp([ls],[[ls],[-a]]) char* argumentList[50000]; char executable[50000]; argumentList[0] = executable; unsigned int size = 0; ls -a \0 execvp(argumentList[0], argumentList); */ <|endoftext|>
<commit_before>// Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "sdk/tera_replication.h" #include "common/mutex.h" #include "types.h" #include "utils/config_utils.h" DEFINE_bool(tera_replication_read_try_all, false, "try to read all replicas instread of randomly choose one"); DEFINE_bool(tera_replication_write_need_all_success, false, "return OK only if all replicas write success"); DEFINE_string(tera_replication_conf_paths, "../conf/tera.flag", "paths for flag files. use \';\' to split"); namespace tera { class RowMutationReplicateImpl : public RowMutationReplicate { public: RowMutationReplicateImpl(const std::vector<RowMutation*>& row_mutations, const std::vector<Table*>& tables) : _row_mutations(row_mutations), _tables(tables), _user_callback(NULL), _user_context(NULL), _finish_cond(&_mutex), _finish_count(0), _success_row_mutation(NULL), _fail_row_mutation(NULL) { CHECK_GT(_row_mutations.size(), 0u); for (size_t i = 0; i < _row_mutations.size(); i++) { _row_mutations[i]->SetCallBack(RowMutationCallback); _row_mutations[i]->SetContext(this); } } virtual ~RowMutationReplicateImpl() { for (size_t i = 0; i < _row_mutations.size(); i++) { delete _row_mutations[i]; } } virtual const std::string& RowKey() { return _row_mutations[0]->RowKey(); } virtual void Put(const std::string& value) { for (size_t i = 0; i < _row_mutations.size(); i++) { _row_mutations[i]->Put(value); } } virtual void Put(const std::string& value, int32_t ttl) { for (size_t i = 0; i < _row_mutations.size(); i++) { _row_mutations[i]->Put(value, ttl); } } virtual void DeleteRow() { for (size_t i = 0; i < _row_mutations.size(); i++) { _row_mutations[i]->DeleteRow(); } } virtual void SetCallBack(Callback callback) { _user_callback = callback; } virtual Callback GetCallBack() { return _user_callback; } virtual void SetContext(void* context) { _user_context = context; } virtual void* GetContext() { return _user_context; } virtual const ErrorCode& GetError() { if (_fail_row_mutation == NULL) { CHECK_NOTNULL(_success_row_mutation); return _success_row_mutation->GetError(); } if (_success_row_mutation == NULL) { CHECK_NOTNULL(_fail_row_mutation); return _fail_row_mutation->GetError(); } if (FLAGS_tera_replication_write_need_all_success) { return _fail_row_mutation->GetError(); } else { return _success_row_mutation->GetError(); } } public: const std::vector<RowMutation*>& GetRowMutationList() { return _row_mutations; } const std::vector<Table*>& GetTableList() { return _tables; } bool IsAsync() { return (_user_callback != NULL); } void Wait() { CHECK(_user_callback == NULL); MutexLock l(&_mutex); while (_finish_count < _row_mutations.size()) { _finish_cond.Wait(); } } private: RowMutationReplicateImpl(const RowMutationReplicateImpl&); void operator=(const RowMutationReplicateImpl&); static void RowMutationCallback(RowMutation* mutation) { RowMutationReplicateImpl* mutation_rep = (RowMutationReplicateImpl*)mutation->GetContext(); mutation_rep->ProcessCallback(mutation); } void ProcessCallback(RowMutation* mutation) { _mutex.Lock(); if (mutation->GetError().GetType() == tera::ErrorCode::kOK) { if (_success_row_mutation == NULL) { _success_row_mutation = mutation; } } else { if (_fail_row_mutation == NULL) { _fail_row_mutation = mutation; } } if (++_finish_count == _row_mutations.size()) { if (_user_callback != NULL) { _mutex.Unlock(); // remember to unlock _user_callback(this); return; // remember to return } else { _finish_cond.Signal(); } } _mutex.Unlock(); } std::vector<RowMutation*> _row_mutations; std::vector<Table*> _tables; RowMutationReplicate::Callback _user_callback; void* _user_context; Mutex _mutex; CondVar _finish_cond; uint32_t _finish_count; RowMutation* _success_row_mutation; RowMutation* _fail_row_mutation; }; class RowReaderReplicateImpl : public RowReaderReplicate { public: RowReaderReplicateImpl(const std::vector<RowReader*>& row_readers, const std::vector<Table*>& tables) : _row_readers(row_readers), _tables(tables), _user_callback(NULL), _user_context(NULL), _finish_cond(&_mutex), _finish_count(0), _valid_row_reader(NULL) { CHECK_GT(_row_readers.size(), 0u); for (size_t i = 0; i < _row_readers.size(); i++) { _row_readers[i]->SetCallBack(RowReaderCallback); _row_readers[i]->SetContext(this); } } virtual ~RowReaderReplicateImpl() { for (size_t i = 0; i < _row_readers.size(); i++) { delete _row_readers[i]; } } virtual const std::string& RowName() { return _row_readers[0]->RowName(); } virtual void SetCallBack(Callback callback) { _user_callback = callback; for (size_t i = 0; i < _row_readers.size(); i++) { _row_readers[i]->SetCallBack(RowReaderCallback); _row_readers[i]->SetContext(this); } } virtual void SetContext(void* context) { _user_context = context; } virtual void* GetContext() { return _user_context; } virtual ErrorCode GetError() { CHECK_NOTNULL(_valid_row_reader); return _valid_row_reader->GetError(); } virtual std::string Value() { CHECK_NOTNULL(_valid_row_reader); return _valid_row_reader->Value(); } public: const std::vector<RowReader*>& GetRowReaderList() { return _row_readers; } const std::vector<Table*>& GetTableList() { return _tables; } bool IsAsync() { return (_user_callback != NULL); } void Wait() { CHECK(_user_callback == NULL); MutexLock l(&_mutex); while (_finish_count < _row_readers.size()) { _finish_cond.Wait(); } } private: RowReaderReplicateImpl(const RowReaderReplicateImpl&); void operator=(const RowReaderReplicateImpl&); static void RowReaderCallback(RowReader* reader) { RowReaderReplicateImpl* reader_rep = (RowReaderReplicateImpl*)reader->GetContext(); reader_rep->ProcessCallback(reader); } void ProcessCallback(RowReader* reader) { _mutex.Lock(); if (_valid_row_reader == NULL && reader->GetError().GetType() == tera::ErrorCode::kOK) { _valid_row_reader = reader; } if (++_finish_count == _row_readers.size()) { // if all readers fail, use readers[0] if (_valid_row_reader == NULL) { _valid_row_reader = _row_readers[0]; } if (_user_callback != NULL) { _mutex.Unlock(); // remember to unlock _user_callback(this); return; // remember to return } else { _finish_cond.Signal(); } } _mutex.Unlock(); } std::vector<RowReader*> _row_readers; std::vector<Table*> _tables; RowReaderReplicate::Callback _user_callback; void* _user_context; Mutex _mutex; CondVar _finish_cond; uint32_t _finish_count; RowReader* _valid_row_reader; }; /// 表接口 class TableReplicateImpl : public TableReplicate { public: TableReplicateImpl(std::vector<Table*> tables) : _tables(tables) {} virtual ~TableReplicateImpl() { for (size_t i = 0; i < _tables.size(); i++) { delete _tables[i]; } } virtual RowMutationReplicate* NewRowMutation(const std::string& row_key) { std::vector<RowMutation*> row_mutations; for (size_t i = 0; i < _tables.size(); i++) { row_mutations.push_back(_tables[i]->NewRowMutation(row_key)); } return new RowMutationReplicateImpl(row_mutations, _tables); } virtual void ApplyMutation(RowMutationReplicate* mutation_rep) { RowMutationReplicateImpl* mutation_rep_impl = (RowMutationReplicateImpl*)mutation_rep; bool is_async = mutation_rep_impl->IsAsync(); const std::vector<RowMutation*>& mutation_list = mutation_rep_impl->GetRowMutationList(); const std::vector<Table*>& table_list = mutation_rep_impl->GetTableList(); for (size_t i = 0; i < mutation_list.size(); i++) { table_list[i]->ApplyMutation(mutation_list[i]); } if (!is_async) { mutation_rep_impl->Wait(); } } virtual RowReaderReplicate* NewRowReader(const std::string& row_key) { std::vector<RowReader*> row_readers; std::vector<Table*> tables; if (FLAGS_tera_replication_read_try_all) { for (size_t i = 0; i < _tables.size(); i++) { row_readers.push_back(_tables[i]->NewRowReader(row_key)); tables.push_back(_tables[i]); } } else { size_t i = random() % _tables.size(); row_readers.push_back(_tables[i]->NewRowReader(row_key)); tables.push_back(_tables[i]); } return new RowReaderReplicateImpl(row_readers, tables); } virtual void Get(RowReaderReplicate* reader_rep) { RowReaderReplicateImpl* reader_rep_impl = (RowReaderReplicateImpl*)reader_rep; bool is_async = reader_rep_impl->IsAsync(); const std::vector<RowReader*>& reader_list = reader_rep_impl->GetRowReaderList(); const std::vector<Table*>& table_list = reader_rep_impl->GetTableList(); for (size_t i = 0; i < reader_list.size(); i++) { table_list[i]->Get(reader_list[i]); } if (!is_async) { reader_rep_impl->Wait(); } } private: TableReplicateImpl(const TableReplicateImpl&); void operator=(const TableReplicateImpl&); std::vector<Table*> _tables; }; class ClientReplicateImpl : public ClientReplicate { public: /// 打开表格, 失败返回NULL virtual TableReplicate* OpenTable(const std::string& table_name, ErrorCode* err) { std::vector<Table*> tables; for (size_t i = 0; i < _clients.size(); i++) { Table* table = _clients[i]->OpenTable(table_name, err); if (table == NULL) { for (size_t j = 0; j < tables.size(); j++) { delete tables[j]; } return NULL; } tables.push_back(table); } return new TableReplicateImpl(tables); } ClientReplicateImpl(const std::vector<Client*>& clients) : _clients(clients) {} virtual ~ClientReplicateImpl() { for (size_t i = 0; i < _clients.size(); i++) { delete _clients[i]; } } private: ClientReplicateImpl(const ClientReplicateImpl&); void operator=(const ClientReplicateImpl&); std::vector<Client*> _clients; }; void ClientReplicate::SetGlogIsInitialized() { Client::SetGlogIsInitialized(); } ClientReplicate* ClientReplicate::NewClient(const std::string& confpath, const std::string& log_prefix, ErrorCode* err) { utils::LoadFlagFile(confpath); std::string conf_paths = FLAGS_tera_replication_conf_paths; std::vector<std::string> confs; size_t token_pos = 0; while (token_pos < conf_paths.size()) { size_t delim_pos = conf_paths.find(';', token_pos); std::string token(conf_paths, token_pos, delim_pos - token_pos); if (!token.empty()) { confs.push_back(token); } if (delim_pos == std::string::npos) { break; } token_pos = delim_pos + 1; } std::vector<Client*> clients; for (size_t i = 0; i < confs.size(); i++) { Client* client = Client::NewClient(confs[i], log_prefix, err); if (client == NULL) { for (size_t j = 0; j < clients.size(); j++) { delete clients[j]; } return NULL; } clients.push_back(client); } return new ClientReplicateImpl(clients); } ClientReplicate* ClientReplicate::NewClient(const std::string& confpath, ErrorCode* err) { return NewClient(confpath, "tera", err); } ClientReplicate* ClientReplicate::NewClient() { return NewClient("", NULL); } } // namespace tera <commit_msg>issue=#907 bugfix of replication sdk<commit_after>// Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "sdk/tera_replication.h" #include "common/mutex.h" #include "types.h" #include "utils/config_utils.h" DEFINE_bool(tera_replication_read_try_all, false, "try to read all replicas instread of randomly choose one"); DEFINE_bool(tera_replication_write_need_all_success, false, "return OK only if all replicas write success"); DEFINE_string(tera_replication_conf_paths, "../conf/tera.flag", "paths for flag files. use \';\' to split"); namespace tera { class RowMutationReplicateImpl : public RowMutationReplicate { public: RowMutationReplicateImpl(const std::vector<RowMutation*>& row_mutations, const std::vector<Table*>& tables) : _row_mutations(row_mutations), _tables(tables), _user_callback(NULL), _user_context(NULL), _finish_cond(&_mutex), _finish_count(0), _success_row_mutation(NULL), _fail_row_mutation(NULL) { CHECK_GT(_row_mutations.size(), 0u); for (size_t i = 0; i < _row_mutations.size(); i++) { _row_mutations[i]->SetCallBack(RowMutationCallback); _row_mutations[i]->SetContext(this); } } virtual ~RowMutationReplicateImpl() { for (size_t i = 0; i < _row_mutations.size(); i++) { delete _row_mutations[i]; } } virtual const std::string& RowKey() { return _row_mutations[0]->RowKey(); } virtual void Put(const std::string& value) { for (size_t i = 0; i < _row_mutations.size(); i++) { _row_mutations[i]->Put(value); } } virtual void Put(const std::string& value, int32_t ttl) { for (size_t i = 0; i < _row_mutations.size(); i++) { _row_mutations[i]->Put(value, ttl); } } virtual void DeleteRow() { for (size_t i = 0; i < _row_mutations.size(); i++) { _row_mutations[i]->DeleteRow(); } } virtual void SetCallBack(Callback callback) { _user_callback = callback; } virtual Callback GetCallBack() { return _user_callback; } virtual void SetContext(void* context) { _user_context = context; } virtual void* GetContext() { return _user_context; } virtual const ErrorCode& GetError() { if (_fail_row_mutation == NULL) { CHECK_NOTNULL(_success_row_mutation); return _success_row_mutation->GetError(); } if (_success_row_mutation == NULL) { CHECK_NOTNULL(_fail_row_mutation); return _fail_row_mutation->GetError(); } if (FLAGS_tera_replication_write_need_all_success) { return _fail_row_mutation->GetError(); } else { return _success_row_mutation->GetError(); } } public: const std::vector<RowMutation*>& GetRowMutationList() { return _row_mutations; } const std::vector<Table*>& GetTableList() { return _tables; } bool IsAsync() { return (_user_callback != NULL); } void Wait() { CHECK(_user_callback == NULL); MutexLock l(&_mutex); while (_finish_count < _row_mutations.size()) { _finish_cond.Wait(); } } private: RowMutationReplicateImpl(const RowMutationReplicateImpl&); void operator=(const RowMutationReplicateImpl&); static void RowMutationCallback(RowMutation* mutation) { RowMutationReplicateImpl* mutation_rep = (RowMutationReplicateImpl*)mutation->GetContext(); mutation_rep->ProcessCallback(mutation); } void ProcessCallback(RowMutation* mutation) { _mutex.Lock(); if (mutation->GetError().GetType() == tera::ErrorCode::kOK) { if (_success_row_mutation == NULL) { _success_row_mutation = mutation; } } else { if (_fail_row_mutation == NULL) { _fail_row_mutation = mutation; } } if (++_finish_count == _row_mutations.size()) { if (_user_callback != NULL) { _mutex.Unlock(); // remember to unlock _user_callback(this); return; // remember to return } else { _finish_cond.Signal(); } } _mutex.Unlock(); } std::vector<RowMutation*> _row_mutations; std::vector<Table*> _tables; RowMutationReplicate::Callback _user_callback; void* _user_context; Mutex _mutex; CondVar _finish_cond; uint32_t _finish_count; RowMutation* _success_row_mutation; RowMutation* _fail_row_mutation; }; class RowReaderReplicateImpl : public RowReaderReplicate { public: RowReaderReplicateImpl(const std::vector<RowReader*>& row_readers, const std::vector<Table*>& tables) : _row_readers(row_readers), _tables(tables), _user_callback(NULL), _user_context(NULL), _finish_cond(&_mutex), _finish_count(0), _valid_row_reader(NULL) { CHECK_GT(_row_readers.size(), 0u); for (size_t i = 0; i < _row_readers.size(); i++) { _row_readers[i]->SetCallBack(RowReaderCallback); _row_readers[i]->SetContext(this); } } virtual ~RowReaderReplicateImpl() { for (size_t i = 0; i < _row_readers.size(); i++) { delete _row_readers[i]; } } virtual const std::string& RowName() { return _row_readers[0]->RowName(); } virtual void SetCallBack(Callback callback) { _user_callback = callback; } virtual void SetContext(void* context) { _user_context = context; } virtual void* GetContext() { return _user_context; } virtual ErrorCode GetError() { CHECK_NOTNULL(_valid_row_reader); return _valid_row_reader->GetError(); } virtual std::string Value() { CHECK_NOTNULL(_valid_row_reader); return _valid_row_reader->Value(); } public: const std::vector<RowReader*>& GetRowReaderList() { return _row_readers; } const std::vector<Table*>& GetTableList() { return _tables; } bool IsAsync() { return (_user_callback != NULL); } void Wait() { CHECK(_user_callback == NULL); MutexLock l(&_mutex); while (_finish_count < _row_readers.size()) { _finish_cond.Wait(); } } private: RowReaderReplicateImpl(const RowReaderReplicateImpl&); void operator=(const RowReaderReplicateImpl&); static void RowReaderCallback(RowReader* reader) { RowReaderReplicateImpl* reader_rep = (RowReaderReplicateImpl*)reader->GetContext(); reader_rep->ProcessCallback(reader); } void ProcessCallback(RowReader* reader) { _mutex.Lock(); if (_valid_row_reader == NULL && reader->GetError().GetType() == tera::ErrorCode::kOK) { _valid_row_reader = reader; } if (++_finish_count == _row_readers.size()) { // if all readers fail, use readers[0] if (_valid_row_reader == NULL) { _valid_row_reader = _row_readers[0]; } if (_user_callback != NULL) { _mutex.Unlock(); // remember to unlock _user_callback(this); return; // remember to return } else { _finish_cond.Signal(); } } _mutex.Unlock(); } std::vector<RowReader*> _row_readers; std::vector<Table*> _tables; RowReaderReplicate::Callback _user_callback; void* _user_context; Mutex _mutex; CondVar _finish_cond; uint32_t _finish_count; RowReader* _valid_row_reader; }; /// 表接口 class TableReplicateImpl : public TableReplicate { public: TableReplicateImpl(std::vector<Table*> tables) : _tables(tables) {} virtual ~TableReplicateImpl() { for (size_t i = 0; i < _tables.size(); i++) { delete _tables[i]; } } virtual RowMutationReplicate* NewRowMutation(const std::string& row_key) { std::vector<RowMutation*> row_mutations; for (size_t i = 0; i < _tables.size(); i++) { row_mutations.push_back(_tables[i]->NewRowMutation(row_key)); } return new RowMutationReplicateImpl(row_mutations, _tables); } virtual void ApplyMutation(RowMutationReplicate* mutation_rep) { RowMutationReplicateImpl* mutation_rep_impl = (RowMutationReplicateImpl*)mutation_rep; bool is_async = mutation_rep_impl->IsAsync(); const std::vector<RowMutation*>& mutation_list = mutation_rep_impl->GetRowMutationList(); const std::vector<Table*>& table_list = mutation_rep_impl->GetTableList(); // in async mode, after the last call of ApplyMutation, we should not access // 'mutation_rep_impl' anymore, that's why we assign the value of 'mutation_list.size()' // to a local variable 'mutation_num' size_t mutation_num = mutation_list.size(); for (size_t i = 0; i < mutation_num; i++) { table_list[i]->ApplyMutation(mutation_list[i]); } if (!is_async) { mutation_rep_impl->Wait(); } } virtual RowReaderReplicate* NewRowReader(const std::string& row_key) { std::vector<RowReader*> row_readers; std::vector<Table*> tables; if (FLAGS_tera_replication_read_try_all) { for (size_t i = 0; i < _tables.size(); i++) { row_readers.push_back(_tables[i]->NewRowReader(row_key)); tables.push_back(_tables[i]); } } else { size_t i = random() % _tables.size(); row_readers.push_back(_tables[i]->NewRowReader(row_key)); tables.push_back(_tables[i]); } return new RowReaderReplicateImpl(row_readers, tables); } virtual void Get(RowReaderReplicate* reader_rep) { RowReaderReplicateImpl* reader_rep_impl = (RowReaderReplicateImpl*)reader_rep; bool is_async = reader_rep_impl->IsAsync(); const std::vector<RowReader*>& reader_list = reader_rep_impl->GetRowReaderList(); const std::vector<Table*>& table_list = reader_rep_impl->GetTableList(); size_t reader_num = reader_list.size(); for (size_t i = 0; i < reader_num; i++) { table_list[i]->Get(reader_list[i]); } if (!is_async) { reader_rep_impl->Wait(); } } private: TableReplicateImpl(const TableReplicateImpl&); void operator=(const TableReplicateImpl&); std::vector<Table*> _tables; }; class ClientReplicateImpl : public ClientReplicate { public: /// 打开表格, 失败返回NULL virtual TableReplicate* OpenTable(const std::string& table_name, ErrorCode* err) { std::vector<Table*> tables; for (size_t i = 0; i < _clients.size(); i++) { Table* table = _clients[i]->OpenTable(table_name, err); if (table == NULL) { for (size_t j = 0; j < tables.size(); j++) { delete tables[j]; } return NULL; } tables.push_back(table); } return new TableReplicateImpl(tables); } ClientReplicateImpl(const std::vector<Client*>& clients) : _clients(clients) {} virtual ~ClientReplicateImpl() { for (size_t i = 0; i < _clients.size(); i++) { delete _clients[i]; } } private: ClientReplicateImpl(const ClientReplicateImpl&); void operator=(const ClientReplicateImpl&); std::vector<Client*> _clients; }; void ClientReplicate::SetGlogIsInitialized() { Client::SetGlogIsInitialized(); } ClientReplicate* ClientReplicate::NewClient(const std::string& confpath, const std::string& log_prefix, ErrorCode* err) { utils::LoadFlagFile(confpath); std::string conf_paths = FLAGS_tera_replication_conf_paths; std::vector<std::string> confs; size_t token_pos = 0; while (token_pos < conf_paths.size()) { size_t delim_pos = conf_paths.find(';', token_pos); std::string token(conf_paths, token_pos, delim_pos - token_pos); if (!token.empty()) { confs.push_back(token); } if (delim_pos == std::string::npos) { break; } token_pos = delim_pos + 1; } std::vector<Client*> clients; for (size_t i = 0; i < confs.size(); i++) { Client* client = Client::NewClient(confs[i], log_prefix, err); if (client == NULL) { for (size_t j = 0; j < clients.size(); j++) { delete clients[j]; } return NULL; } clients.push_back(client); } return new ClientReplicateImpl(clients); } ClientReplicate* ClientReplicate::NewClient(const std::string& confpath, ErrorCode* err) { return NewClient(confpath, "tera", err); } ClientReplicate* ClientReplicate::NewClient() { return NewClient("", NULL); } } // namespace tera <|endoftext|>
<commit_before>/** * Concept 4 : compile time constants. */ #include <iostream> int main() { constexpr uint32_t MEMORY_SIZE{ 512 }; } <commit_msg>Update constexpr_variable.cpp<commit_after>/** * Concept 4 : compile time constants. */ #include <iostream> int main() { constexpr uint32_t MEMORY_SIZE{ 512 }; std::cout << MEMORY_SIZE << std::endl; } <|endoftext|>
<commit_before>#include "rhodes/JNIRhodes.h" #include <common/rhoparams.h> #undef DEFAULT_LOGCATEGORY #define DEFAULT_LOGCATEGORY "MapView" RHO_GLOBAL void mapview_create(rho_param *p) { #ifdef RHO_GOOGLE_API_KEY JNIEnv *env = jnienv(); jclass clsMapView = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); if (!clsMapView) return; jmethodID midCreate = getJNIClassStaticMethod(env, clsMapView, "create", "(Ljava/lang/String;Ljava/util/Map;)V"); if (!midCreate) return; if (p->type != RHO_PARAM_HASH) { RAWLOG_ERROR("create: wrong input parameter (expect Hash)"); return; } jobject paramsObj = RhoValueConverter(env).createObject(p); jstring keyObj = rho_cast<jstring>(RHO_GOOGLE_API_KEY); env->CallStaticVoidMethod(clsMapView, midCreate, keyObj, paramsObj); env->DeleteLocalRef(keyObj); env->DeleteLocalRef(paramsObj); #else RAWLOG_ERROR("MapView disabled at build time"); #endif } RHO_GLOBAL void mapview_close() { #ifdef RHO_GOOGLE_API_KEY JNIEnv *env = jnienv(); jclass clsMapView = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); if (!clsMapView) return; jmethodID midClose = getJNIClassStaticMethod(env, clsMapView, "close", "()V"); if (!midClose) return; env->CallStaticVoidMethod(clsMapView, midClose); #endif } RHO_GLOBAL VALUE mapview_state_started() { #ifdef RHO_GOOGLE_API_KEY VALUE nil = rho_ruby_get_NIL(); JNIEnv *env = jnienv(); jclass cls = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); if (!cls) return nil; jmethodID mid = getJNIClassStaticMethod(env, cls, "isStarted", "()Z"); if (!mid) return nil; return rho_ruby_create_boolean(env->CallStaticBooleanMethod(cls, mid)); #else return rho_ruby_create_boolean(0); #endif } RHO_GLOBAL double mapview_state_center_lat() { #ifdef RHO_GOOGLE_API_KEY JNIEnv *env = jnienv(); jclass cls = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); if (!cls) return 0; jmethod mid = getJNIClassStaticMethod(env, cls, "getCenterLatitude", "()D"); if (!mid) return 0; return env->CallStaticDoubleMethod(cls, mid); #else return 0; #endif } RHO_GLOBAL double mapview_state_center_lon() { #ifdef RHO_GOOGLE_API_KEY JNIEnv *env = jnienv(); jclass cls = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); if (!cls) return 0; jmethod mid = getJNIClassStaticMethod(env, cls, "getCenterLongitude", "()D"); if (!mid) return 0; return env->CallStaticDoubleMethod(cls, mid); #else return 0; #endif } <commit_msg>fix compilation error when api key is included.<commit_after>#include "rhodes/JNIRhodes.h" #include <common/rhoparams.h> #undef DEFAULT_LOGCATEGORY #define DEFAULT_LOGCATEGORY "MapView" RHO_GLOBAL void mapview_create(rho_param *p) { #ifdef RHO_GOOGLE_API_KEY JNIEnv *env = jnienv(); jclass clsMapView = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); if (!clsMapView) return; jmethodID midCreate = getJNIClassStaticMethod(env, clsMapView, "create", "(Ljava/lang/String;Ljava/util/Map;)V"); if (!midCreate) return; if (p->type != RHO_PARAM_HASH) { RAWLOG_ERROR("create: wrong input parameter (expect Hash)"); return; } jobject paramsObj = RhoValueConverter(env).createObject(p); jstring keyObj = rho_cast<jstring>(RHO_GOOGLE_API_KEY); env->CallStaticVoidMethod(clsMapView, midCreate, keyObj, paramsObj); env->DeleteLocalRef(keyObj); env->DeleteLocalRef(paramsObj); #else RAWLOG_ERROR("MapView disabled at build time"); #endif } RHO_GLOBAL void mapview_close() { #ifdef RHO_GOOGLE_API_KEY JNIEnv *env = jnienv(); jclass clsMapView = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); if (!clsMapView) return; jmethodID midClose = getJNIClassStaticMethod(env, clsMapView, "close", "()V"); if (!midClose) return; env->CallStaticVoidMethod(clsMapView, midClose); #endif } RHO_GLOBAL VALUE mapview_state_started() { #ifdef RHO_GOOGLE_API_KEY VALUE nil = rho_ruby_get_NIL(); JNIEnv *env = jnienv(); jclass cls = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); if (!cls) return nil; jmethodID mid = getJNIClassStaticMethod(env, cls, "isStarted", "()Z"); if (!mid) return nil; return rho_ruby_create_boolean(env->CallStaticBooleanMethod(cls, mid)); #else return rho_ruby_create_boolean(0); #endif } RHO_GLOBAL double mapview_state_center_lat() { #ifdef RHO_GOOGLE_API_KEY JNIEnv *env = jnienv(); jclass cls = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); if (!cls) return 0; jmethodID mid = getJNIClassStaticMethod(env, cls, "getCenterLatitude", "()D"); if (!mid) return 0; return env->CallStaticDoubleMethod(cls, mid); #else return 0; #endif } RHO_GLOBAL double mapview_state_center_lon() { #ifdef RHO_GOOGLE_API_KEY JNIEnv *env = jnienv(); jclass cls = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); if (!cls) return 0; jmethodID mid = getJNIClassStaticMethod(env, cls, "getCenterLongitude", "()D"); if (!mid) return 0; return env->CallStaticDoubleMethod(cls, mid); #else return 0; #endif } <|endoftext|>
<commit_before>/** * particles.cpp * \author Joshua Vasquez * \date May 1, 2014 to June 8, 2014 */ #include "particles.hpp" #include <limits> ///< for representation of inifinity as a float Particles::Particles(size_t numParticles) :numParticles_{numParticles} { // dynamically allocate an array of pointers to particles. theParticles_ = new Particle*[numParticles_]; for (size_t eachPart = 0; eachPart < numParticles_; ++eachPart) theParticles_[eachPart] = new Particle{0,0,0}; } Particles::~Particles() { // Free our dynamically allocated memory. for (size_t eachPart = 0; eachPart< numParticles_; ++eachPart) delete theParticles_[eachPart]; delete [] theParticles_; // FIXME: is this a double-delete? } void Particles::scatterParticles(float xmax, float ymax) { std::default_random_engine generator; //FIXME: change to real distributions, not int distributions. std::uniform_int_distribution<int> distributionX(0,xmax); std::uniform_int_distribution<int> distributionY(0,ymax); std::uniform_int_distribution<int> distributionTheta(0,360); for(size_t eachPart = 0; eachPart < numParticles_; ++eachPart) { theParticles_[eachPart]->xVal_ = distributionX(generator); theParticles_[eachPart]->yVal_ = distributionY(generator); theParticles_[eachPart]->theta_ = distributionTheta(generator); } } void Particles::propagateParticles() { } void Particles::updateParticles() { } // Particle Member functions Particles::Particle::Particle(double xVal, double yVal, double weight) :xVal_{xVal}, yVal_{yVal}, weight_{weight} { // Nothing else to do! } Particles::Particle::~Particle() { // Nothing to do! } void Particles::Particle::updateParticle(double lWheelDelta, double rWheelDelta, bool noise) { double noiseLeftW = 0; double noiseRightW = 0; if (noise) { // TODO: create the generator once, not each time fn is called! std::default_random_engine generator; std::normal_distribution<double> distribution(-1.0, 1.0); // TODO: tweak noise function later! noiseLeftW = (lWheelDelta)*distribution(generator); noiseRightW = (rWheelDelta)*distribution(generator); } else { // Calc new x,y,theta through motion model. Check THETA usage. xVal_ += (robotParams::wheelRadius_ / 2) * (lWheelDelta + noiseLeftW + rWheelDelta + noiseRightW) * cos(theta_*(M_PI/180)); yVal_ += (robotParams::wheelRadius_ / 2) * (lWheelDelta + noiseLeftW + rWheelDelta + noiseRightW) * sin(theta_*(M_PI/180)); theta_ += (robotParams::wheelRadius_ / robotParams::wheelSpacing_) * ((rWheelDelta + noiseRightW)- (lWheelDelta + noiseLeftW)); } } float Particles::getWallDist( float scannerX, float scannerY, float scannerTheta, float segX1, float segY1, float segX2, float segY2) { // Compare Slopes: float laserM = round(tan(tuneAngle(scannerTheta))); float segmentM = (segY2 - segY1)/(segX2 - segX1); float intersectionX, intersectionY; // Handle the case where angles point in opposite vertical directions. if((laserM == std::numeric_limits<float>::infinity() || (laserM == -std::numeric_limits<float>::infinity())) && (segmentM == std::numeric_limits<float>::infinity() || (segmentM == -std::numeric_limits<float>::infinity()))) return std::numeric_limits<float>::infinity(); // Handle the case where both lines are basically parallel. if (approxEqual(laserM, segmentM, 1)) return std::numeric_limits<float>::infinity(); // Use geometry when a vertical line is involved. // Old triangle formula: R = x/cos(theta). if(segmentM == std::numeric_limits<float>::infinity()) { // FIXME: double-check if off-segment check works // FIXME: intersectionDist should be positive!! float intersectionDist = std::abs((std::max(segX1,scannerX) - std::min(segX1, scannerX))/ cos(tuneAngle(scannerTheta))); /* std::cout <<"intersectionDist:" << intersectionDist << std::endl; */ intersectionX = round(scannerX + intersectionDist * std::abs(cos(tuneAngle(scannerTheta)))); intersectionY = round(scannerY + intersectionDist * std::abs(sin(tuneAngle(scannerTheta)))); /* std::cout << "intersection: (" << intersectionX << ", " << intersectionY << ")" << std::endl; */ // Calculate if intersection is on wall segment. if (scanOffSegment(intersectionX, intersectionY, segX1, segY1, segX2, segY2)) { /* std::cout << "scan off segment" << std::endl; */ return std::numeric_limits<float>::infinity(); } if (scanBackwards(scannerX, scannerY, scannerTheta, intersectionX, intersectionY)) { /* std::cout << "scan backwards!" << std::endl; */ return std::numeric_limits<float>::infinity(); } return intersectionDist; } if(laserM == std::numeric_limits<float>::infinity()) { // FIXME: double-check if off-segment check works float wallAngle = atan2((segY2 - segY1), (segX2 - segX1)); float intersectionDist = std::abs((std::max(segX1,scannerX) - std::min(segX1, scannerX))/ cos(wallAngle)); intersectionX = round(scannerX + intersectionDist * std::abs(cos(tuneAngle(scannerTheta)))); intersectionY = round(scannerY + intersectionDist * std::abs(sin(tuneAngle(scannerTheta)))); if (scanOffSegment(intersectionX, intersectionY, segX1, segY1, segX2, segY2)) return std::numeric_limits<float>::infinity(); if (scanBackwards(scannerX, scannerY, scannerTheta, intersectionX, intersectionY)) return std::numeric_limits<float>::infinity(); else return intersectionDist; } // Use algebra for all other cases. float laserYInt = laserM*(-scannerX) + scannerY; float segmentYInt = segmentM * (-segX1) + segY1; intersectionX = (segmentYInt - laserYInt)/(laserM - segmentM); intersectionY = laserM*intersectionX + laserYInt; if (scanBackwards(scannerX, scannerY, scannerTheta, intersectionX, intersectionY)) return std::numeric_limits<float>::infinity(); if (scanOffSegment(intersectionX, intersectionY, segX1, segY1, segX2, segY2)) return std::numeric_limits<float>::infinity(); // translate to origin, and compute distance. return sqrt(pow((scannerX - intersectionX), 2) + pow((scannerY - intersectionY), 2)); } float Particles::tuneAngle(float angleInDeg) { float newAngle = angleInDeg; // Map to circle range: while (newAngle > 360) newAngle -= 360; while (newAngle < -360) newAngle += 360; // Convert to -Pi/2 to Pi/2 range. if (newAngle > 180.) newAngle -= 360.; if (newAngle < -180.) newAngle += 360.; // Convert to radian. newAngle *= (M_PI/180.); return newAngle; } float Particles::round(float input) { if (input > largeVal_) return std::numeric_limits<float>::infinity(); if (input < -largeVal_) return -std::numeric_limits<float>::infinity(); if (std::abs(input) < smallVal_) return 0.; return input; } bool Particles::approxEqual(float approxVal, float actualVal, float percentError) { if( round(actualVal) == 0.0) { return (round(approxVal) == 0.0); } return (((std::abs(approxVal - actualVal) / std::abs(actualVal)) * 100.0) < percentError); } bool Particles::scanBackwards(float scannerX, float scannerY, float scannerTheta, float intersectionX, float intersectionY) { // Find angle of intersection point, relative to scanner point. // Translate laser scan line to intersect origin. // Take that angle with atan2 float intersectionAngle = atan2( (intersectionY - scannerY), (intersectionX - scannerX)); /* std::cout << "intersectionAngle: " << intersectionAngle << std::endl; std::cout << "laser angle: " << tuneAngle(scannerTheta) << std::endl; */ if (!approxEqual(intersectionAngle, tuneAngle(scannerTheta), 3)) { return true; } return false; } bool Particles::scanOffSegment(float intersectionX, float intersectionY, float segX1, float segY1, float segX2, float segY2) { if ((intersectionX < std::min(segX1,segX2)) || (intersectionX > std::max(segX1, segX2))) { // handle rounding error cases for narrow ranges of segX1 and segX2 if (!(approxEqual(segX1, segX2, 3) && approxEqual(segX1, intersectionX, 3))) { return true; } } if ((intersectionY < std::min(segY1,segY2)) || (intersectionY > std::max(segY1,segY2))) { // handle rounding error cases for narrow ranges of segY1 and segY2 if (!(approxEqual(segY1, segY2, 3) && approxEqual(segY1, intersectionY, 3))) { return true; } } return false; } <commit_msg>getWallDist working for all tested cases thus far.<commit_after>/** * particles.cpp * \author Joshua Vasquez * \date May 1, 2014 to June 8, 2014 */ #include "particles.hpp" #include <limits> ///< for representation of inifinity as a float Particles::Particles(size_t numParticles) :numParticles_{numParticles} { // dynamically allocate an array of pointers to particles. theParticles_ = new Particle*[numParticles_]; for (size_t eachPart = 0; eachPart < numParticles_; ++eachPart) theParticles_[eachPart] = new Particle{0,0,0}; } Particles::~Particles() { // Free our dynamically allocated memory. for (size_t eachPart = 0; eachPart< numParticles_; ++eachPart) delete theParticles_[eachPart]; delete [] theParticles_; // FIXME: is this a double-delete? } void Particles::scatterParticles(float xmax, float ymax) { std::default_random_engine generator; //FIXME: change to real distributions, not int distributions. std::uniform_int_distribution<int> distributionX(0,xmax); std::uniform_int_distribution<int> distributionY(0,ymax); std::uniform_int_distribution<int> distributionTheta(0,360); for(size_t eachPart = 0; eachPart < numParticles_; ++eachPart) { theParticles_[eachPart]->xVal_ = distributionX(generator); theParticles_[eachPart]->yVal_ = distributionY(generator); theParticles_[eachPart]->theta_ = distributionTheta(generator); } } void Particles::propagateParticles() { } void Particles::updateParticles() { } // Particle Member functions Particles::Particle::Particle(double xVal, double yVal, double weight) :xVal_{xVal}, yVal_{yVal}, weight_{weight} { // Nothing else to do! } Particles::Particle::~Particle() { // Nothing to do! } void Particles::Particle::updateParticle(double lWheelDelta, double rWheelDelta, bool noise) { double noiseLeftW = 0; double noiseRightW = 0; if (noise) { // TODO: create the generator once, not each time fn is called! std::default_random_engine generator; std::normal_distribution<double> distribution(-1.0, 1.0); // TODO: tweak noise function later! noiseLeftW = (lWheelDelta)*distribution(generator); noiseRightW = (rWheelDelta)*distribution(generator); } else { // Calc new x,y,theta through motion model. Check THETA usage. xVal_ += (robotParams::wheelRadius_ / 2) * (lWheelDelta + noiseLeftW + rWheelDelta + noiseRightW) * cos(theta_*(M_PI/180)); yVal_ += (robotParams::wheelRadius_ / 2) * (lWheelDelta + noiseLeftW + rWheelDelta + noiseRightW) * sin(theta_*(M_PI/180)); theta_ += (robotParams::wheelRadius_ / robotParams::wheelSpacing_) * ((rWheelDelta + noiseRightW)- (lWheelDelta + noiseLeftW)); } } //TODO: make this function shorter. float Particles::getWallDist( float scannerX, float scannerY, float scannerTheta, float segX1, float segY1, float segX2, float segY2) { // Compare Slopes: float laserM = round(tan(tuneAngle(scannerTheta))); float segmentM = (segY2 - segY1)/(segX2 - segX1); float intersectionX, intersectionY; // Handle special case where parallel vertical lines could round to // opposite slopes. if((laserM == std::numeric_limits<float>::infinity() || (laserM == -std::numeric_limits<float>::infinity())) && (segmentM == std::numeric_limits<float>::infinity() || (segmentM == -std::numeric_limits<float>::infinity()))) return std::numeric_limits<float>::infinity(); // Handle the case where both lines are basically parallel. if (approxEqual(laserM, segmentM, 1)) return std::numeric_limits<float>::infinity(); // Special easy-algebra cases when either scan line or wall is vertical. // TODO: shrink these two big if-blocks if(segmentM == std::numeric_limits<float>::infinity()) { float laserYInt = laserM * (-scannerX) + scannerY; intersectionX = segX1; intersectionY = laserM * segX1 + laserYInt; float intersectionDist = sqrt(pow((scannerX - intersectionX), 2) + pow((scannerY - intersectionY), 2)); std::cout << "intersectionDist: " << intersectionDist << std::endl; // Calculate if intersection is on wall segment. if (scanOffSegment(intersectionX, intersectionY, segX1, segY1, segX2, segY2)) return std::numeric_limits<float>::infinity(); if (scanBackwards(scannerX, scannerY, scannerTheta, intersectionX, intersectionY)) return std::numeric_limits<float>::infinity(); return intersectionDist; } if(laserM == std::numeric_limits<float>::infinity()) { float wallYInt = segmentM * (-segX1) + segY1; intersectionX = scannerX; ///< nice benefit of a vertical laser. intersectionY = segmentM * scannerX + wallYInt; float intersectionDist = sqrt(pow((scannerX - intersectionX), 2) + pow((scannerY - intersectionY), 2)); if (scanOffSegment(intersectionX, intersectionY, segX1, segY1, segX2, segY2)) return std::numeric_limits<float>::infinity(); if (scanBackwards(scannerX, scannerY, scannerTheta, intersectionX, intersectionY)) return std::numeric_limits<float>::infinity(); return intersectionDist; } // Use slopes and intercepts with algebra for all other cases. float laserYInt = laserM*(-scannerX) + scannerY; float segmentYInt = segmentM * (-segX1) + segY1; intersectionX = (segmentYInt - laserYInt)/(laserM - segmentM); intersectionY = laserM*intersectionX + laserYInt; if (scanBackwards(scannerX, scannerY, scannerTheta, intersectionX, intersectionY)) return std::numeric_limits<float>::infinity(); if (scanOffSegment(intersectionX, intersectionY, segX1, segY1, segX2, segY2)) return std::numeric_limits<float>::infinity(); // translate to origin, and compute distance. return sqrt(pow((scannerX - intersectionX), 2) + pow((scannerY - intersectionY), 2)); } float Particles::tuneAngle(float angleInDeg) { float newAngle = angleInDeg; // Map to circle range: while (newAngle > 360) newAngle -= 360; while (newAngle < -360) newAngle += 360; // Convert to -Pi/2 to Pi/2 range. if (newAngle > 180.) newAngle -= 360.; if (newAngle < -180.) newAngle += 360.; // Convert to radian. newAngle *= (M_PI/180.); return newAngle; } float Particles::round(float input) { if (input > largeVal_) return std::numeric_limits<float>::infinity(); if (input < -largeVal_) return -std::numeric_limits<float>::infinity(); if (std::abs(input) < smallVal_) return 0.; return input; } bool Particles::approxEqual(float approxVal, float actualVal, float percentError) { if( round(actualVal) == 0.0) { return (round(approxVal) == 0.0); } return (((std::abs(approxVal - actualVal) / std::abs(actualVal)) * 100.0) < percentError); } bool Particles::scanBackwards(float scannerX, float scannerY, float scannerTheta, float intersectionX, float intersectionY) { // Find angle of intersection point, relative to scanner point. // Translate laser scan line to intersect origin. // Take that angle with atan2 float intersectionAngle = atan2( (intersectionY - scannerY), (intersectionX - scannerX)); /* std::cout << "intersectionAngle: " << intersectionAngle << std::endl; std::cout << "laser angle: " << tuneAngle(scannerTheta) << std::endl; */ if (!approxEqual(intersectionAngle, tuneAngle(scannerTheta), 3)) { return true; } return false; } bool Particles::scanOffSegment(float intersectionX, float intersectionY, float segX1, float segY1, float segX2, float segY2) { if ((intersectionX < std::min(segX1,segX2)) || (intersectionX > std::max(segX1, segX2))) { // handle rounding error cases for narrow ranges of segX1 and segX2 if (!(approxEqual(segX1, segX2, 3) && approxEqual(segX1, intersectionX, 3))) { return true; } } if ((intersectionY < std::min(segY1,segY2)) || (intersectionY > std::max(segY1,segY2))) { std::cout << "Y triggered" << std::endl; // handle rounding error cases for narrow ranges of segY1 and segY2 if (!(approxEqual(segY1, segY2, 3) && approxEqual(segY1, intersectionY, 3))) { return true; } } return false; } <|endoftext|>
<commit_before>// RUN: %clangxx_cfi -g -fsanitize-stats -o %t %s // RUN: env SANITIZER_STATS_PATH=%t.stats %t // RUN: sanstats %t.stats | FileCheck %s struct ABase {}; struct A : ABase { virtual void vf() {} void nvf() {} }; extern "C" __attribute__((noinline)) void vcall(A *a) { // CHECK: stats.cpp:[[@LINE+1]] vcall cfi-vcall 37 a->vf(); } extern "C" __attribute__((noinline)) void nvcall(A *a) { // CHECK: stats.cpp:[[@LINE+1]] nvcall cfi-nvcall 51 a->nvf(); } extern "C" __attribute__((noinline)) A *dcast(A *a) { // CHECK: stats.cpp:[[@LINE+1]] dcast cfi-derived-cast 24 return (A *)(ABase *)a; } extern "C" __attribute__((noinline)) A *ucast(A *a) { // CHECK: stats.cpp:[[@LINE+1]] ucast cfi-unrelated-cast 81 return (A *)(char *)a; } extern "C" __attribute__((noinline)) void unreachable(A *a) { // CHECK-NOT: unreachable a->vf(); } int main() { A a; for (unsigned i = 0; i != 37; ++i) vcall(&a); for (unsigned i = 0; i != 51; ++i) nvcall(&a); for (unsigned i = 0; i != 24; ++i) dcast(&a); for (unsigned i = 0; i != 81; ++i) ucast(&a); for (unsigned i = 0; i != 0; ++i) unreachable(&a); } <commit_msg>Fix stats.cpp test on 32-bit Windows.<commit_after>// RUN: %clangxx_cfi -g -fsanitize-stats -o %t %s // RUN: env SANITIZER_STATS_PATH=%t.stats %t // RUN: sanstats %t.stats | FileCheck %s struct ABase {}; struct A : ABase { virtual void vf() {} void nvf() {} }; extern "C" __attribute__((noinline)) void vcall(A *a) { // CHECK: stats.cpp:[[@LINE+1]] {{_?}}vcall cfi-vcall 37 a->vf(); } extern "C" __attribute__((noinline)) void nvcall(A *a) { // CHECK: stats.cpp:[[@LINE+1]] {{_?}}nvcall cfi-nvcall 51 a->nvf(); } extern "C" __attribute__((noinline)) A *dcast(A *a) { // CHECK: stats.cpp:[[@LINE+1]] {{_?}}dcast cfi-derived-cast 24 return (A *)(ABase *)a; } extern "C" __attribute__((noinline)) A *ucast(A *a) { // CHECK: stats.cpp:[[@LINE+1]] {{_?}}ucast cfi-unrelated-cast 81 return (A *)(char *)a; } extern "C" __attribute__((noinline)) void unreachable(A *a) { // CHECK-NOT: unreachable a->vf(); } int main() { A a; for (unsigned i = 0; i != 37; ++i) vcall(&a); for (unsigned i = 0; i != 51; ++i) nvcall(&a); for (unsigned i = 0; i != 24; ++i) dcast(&a); for (unsigned i = 0; i != 81; ++i) ucast(&a); for (unsigned i = 0; i != 0; ++i) unreachable(&a); } <|endoftext|>
<commit_before>// RUN: %clangxx_cfi -g -fsanitize-stats -o %t %s // RUN: env SANITIZER_STATS_PATH=%t.stats %t // RUN: sanstats %t.stats | FileCheck %s // FIXME: We currently emit the wrong debug info under devirtualization. // UNSUPPORTED: devirt struct ABase {}; struct A : ABase { virtual void vf() {} void nvf() {} }; extern "C" __attribute__((noinline)) void vcall(A *a) { // CHECK: stats.cpp:[[@LINE+1]] {{_?}}vcall cfi-vcall 37 a->vf(); } extern "C" __attribute__((noinline)) void nvcall(A *a) { // CHECK: stats.cpp:[[@LINE+1]] {{_?}}nvcall cfi-nvcall 51 a->nvf(); } extern "C" __attribute__((noinline)) A *dcast(A *a) { // CHECK: stats.cpp:[[@LINE+1]] {{_?}}dcast cfi-derived-cast 24 return (A *)(ABase *)a; } extern "C" __attribute__((noinline)) A *ucast(A *a) { // CHECK: stats.cpp:[[@LINE+1]] {{_?}}ucast cfi-unrelated-cast 81 return (A *)(char *)a; } extern "C" __attribute__((noinline)) void unreachable(A *a) { // CHECK-NOT: unreachable a->vf(); } int main() { A a; for (unsigned i = 0; i != 37; ++i) vcall(&a); for (unsigned i = 0; i != 51; ++i) nvcall(&a); for (unsigned i = 0; i != 24; ++i) dcast(&a); for (unsigned i = 0; i != 81; ++i) ucast(&a); for (unsigned i = 0; i != 0; ++i) unreachable(&a); } <commit_msg>XFAIL cfi/stats.cpp on Windows until we fix our DIA usage<commit_after>// RUN: %clangxx_cfi -g -fsanitize-stats -o %t %s // RUN: env SANITIZER_STATS_PATH=%t.stats %t // RUN: sanstats %t.stats | FileCheck %s // FIXME: We currently emit the wrong debug info under devirtualization. // UNSUPPORTED: devirt // FIXME: Currently failing on Windows with a DIA error, so we don't get any // symbols. // XFAIL: win32 struct ABase {}; struct A : ABase { virtual void vf() {} void nvf() {} }; extern "C" __attribute__((noinline)) void vcall(A *a) { // CHECK: stats.cpp:[[@LINE+1]] {{_?}}vcall cfi-vcall 37 a->vf(); } extern "C" __attribute__((noinline)) void nvcall(A *a) { // CHECK: stats.cpp:[[@LINE+1]] {{_?}}nvcall cfi-nvcall 51 a->nvf(); } extern "C" __attribute__((noinline)) A *dcast(A *a) { // CHECK: stats.cpp:[[@LINE+1]] {{_?}}dcast cfi-derived-cast 24 return (A *)(ABase *)a; } extern "C" __attribute__((noinline)) A *ucast(A *a) { // CHECK: stats.cpp:[[@LINE+1]] {{_?}}ucast cfi-unrelated-cast 81 return (A *)(char *)a; } extern "C" __attribute__((noinline)) void unreachable(A *a) { // CHECK-NOT: unreachable a->vf(); } int main() { A a; for (unsigned i = 0; i != 37; ++i) vcall(&a); for (unsigned i = 0; i != 51; ++i) nvcall(&a); for (unsigned i = 0; i != 24; ++i) dcast(&a); for (unsigned i = 0; i != 81; ++i) ucast(&a); for (unsigned i = 0; i != 0; ++i) unreachable(&a); } <|endoftext|>
<commit_before><commit_msg>Set needsLayout on WebViewPlugin's container when initialized<commit_after><|endoftext|>
<commit_before>// Copyright 2015 FMAW #include "./player_ai.h" #include <cstdlib> #include <vector> #include <map> #include <algorithm> #include "./constants.h" #include "./unit.h" #include "./cell.h" #include "./turnManager.h" #include "./FMAW.h" #include <algorithm> PlayerAI::PlayerAI(Grid *grid, std::function<void(void)> callback) : grid(grid), onFinishTurnCallback(callback), seed(42) {} PlayerAI::PlayerAI(Grid *grid, std::function<void(void)> call, PlayerID ID) : Player(ID), grid(grid), onFinishTurnCallback(call), seed(42) {} void PlayerAI::startTurn() { // Prevent user from interacting with grid. this->grid->dequeueCallbacks(); IndexPath previousPositionOfCursor = this->grid->getSelectedPath(); // Now we have to make some decisions... // We will call the following callback once each 1.5s. this->unitNumber = 0; auto moveSomeUnit = [this, previousPositionOfCursor](int ID) { // Here we will store the units of this AI player and the path where they // are located. std::vector<Unit *> IAunits; std::vector<IndexPath> IApaths; std::vector<Unit *> playerUnits; std::vector<IndexPath> playerPaths; std::vector<IndexPath> chosenPaths; // We have to check the full grid to know where are our units. for (int row = 0; row < this->grid->numRows(); row++) { for (int col = 0; col < this->grid->numCols(); col++) { IndexPath path = { row, col }; Cell *c = this->grid->cellAtIndexPath(path); if (c->isOccupied()) { Unit *u = c->getCharacter(); if (u->getOwner() == this->ID) { IAunits.push_back(u); IApaths.push_back(path); } else { playerUnits.push_back(u); playerPaths.push_back(path); } } } } std::map<IndexPath, std::vector<IndexPath>> IAUnitCanAttack; std::map<IndexPath, std::vector<IndexPath>> PlayerUnitCanBeAttackedBy; std::map<IndexPath, std::vector<IndexPath>> IAUnitsPossibleMovements; std::map<IndexPath, int> distanceToNearestEnemyUnit; // Compute which units can attack which ones. for (IndexPath p : IApaths) { this->grid->setPickedUpCell(p); Cell *c = this->grid->cellAtIndexPath(p); if (c->getCharacter()->hasAvailableActions()) { for (IndexPath t : playerPaths) { if (grid->pickedUpUnitCanAttackCharacterAtCell(t)) { IAUnitCanAttack[p].push_back(t); PlayerUnitCanBeAttackedBy[t].push_back(p); } } } } // Compute where can be moved IA units. for (IndexPath p : IApaths) { for (int row = 0; row < this->grid->numRows(); row++) { for (int col = 0; col < this->grid->numCols(); col++) { IndexPath t = { row, col }; if (grid->canMoveCharacterFromCellToCell(p, t)) { IAUnitsPossibleMovements[p].push_back(t); } } } } // Compute distance to nearest visible enemy. for (int row = 0; row < this->grid->numRows(); row++) { for (int col = 0; col < this->grid->numCols(); col++) { IndexPath f = { row, col }; Cell *from = grid->cellAtIndexPath(f); distanceToNearestEnemyUnit[f] = COST_CELL_INFINITY; for (int t_row = 0; t_row < this->grid->numRows(); t_row++) { for (int t_col = 0; t_col < this->grid->numCols(); t_col++) { IndexPath t = { t_row, t_col }; Cell *to = this->grid->cellAtIndexPath(t); int distance = abs(t.row - f.row) + abs(t.col - f.col); if (to->isOccupied()) { Unit *u = to->getCharacter(); if (this->grid->canSeeCharacterAtCell(t) && u->getOwner() != this->ID) { distanceToNearestEnemyUnit[f] = distance; } } } } } } // Helper function to compute best cell to move. auto nearestEnemy = [&distanceToNearestEnemyUnit]( IndexPath i, IndexPath j ) -> bool { return distanceToNearestEnemyUnit[i] < distanceToNearestEnemyUnit[j]; }; bool canDoSomething = false; for (Unit *u : IAunits) { if (u->hasAvailableActions()) { canDoSomething = true; } } if (canDoSomething) { while (!IAunits[this->unitNumber]->hasAvailableActions()) { this->unitNumber++; this->unitNumber %= IAunits.size(); } //------------------------------------------------------------------ // Actual AI script. //------------------------------------------------------------------ bool actionDone = false; IndexPath path = IApaths[this->unitNumber]; Unit *unit = IAunits[this->unitNumber]; this->grid->setPickedUpCell(path); int row = path.row; int col = path.col; FMAW::printf("Choosing action for unit %d at %d %d", this->unitNumber, row, col); std::vector<IndexPath> shouldAttack; std::vector<IndexPath> attackable; // If I'm the only one who can attack, I'll do (random on tie). attackable = IAUnitCanAttack[path]; for (IndexPath t : attackable) { if (PlayerUnitCanBeAttackedBy[t].size() == 1) { shouldAttack.push_back(t); } } FMAW::printf("\tI'm the only one that can attack %d units", attackable.size()); // If I'm not the only one, I attack to a random (random on tie). if (shouldAttack.size() == 0) { attackable = IAUnitCanAttack[path]; for (IndexPath t : attackable) { shouldAttack.push_back(t); } FMAW::printf("\tMe and others can attack %d units", attackable.size()); } // I'll attack if I can. if (shouldAttack.size() > 0) { while (shouldAttack.size() > 0) { int rand = rand_r(&(this->seed)) % shouldAttack.size(); IndexPath tg = shouldAttack[rand]; if (this->grid->pickedUpUnitCanAttackCharacterAtCell(tg)) { FMAW::printf("\tWill attack unit at %d %d", tg.row, tg.col); this->grid->attackCharacterAtCell(path, tg, ATTACK_DURATION); actionDone = true; break; } else { FMAW::printf("\tCouldn't to attack unit at %d %d", tg.row, tg.col); shouldAttack.erase(shouldAttack.begin() + rand); } } } // If I can't attack, I'll move to the nearest enemy unit (random // on tie). if (!actionDone) { FMAW::printf("\tI couldn't attack any unit, so I'll move"); std::vector<IndexPath> availableMovements; for (int r = 0; r < this->grid->numRows(); r++) { for (int c = 0; c < this->grid->numCols(); c++) { IndexPath t = { r, c }; if (this->grid->canMoveCharacterFromCellToCell(path, t)) { availableMovements.push_back(t); } } } FMAW::printf("\tI can move to %d cells", availableMovements.size()); std::sort(availableMovements.begin(), availableMovements.end(), nearestEnemy); if (availableMovements.size() > 0) { IndexPath chosen = availableMovements[0]; FMAW::printf("\tI'll move to %d %d", chosen.row, chosen.col); this->grid->moveCharacterFromCellToCell(path, chosen, MOVEMENT_DURATION); IApaths[this->unitNumber] = chosen; } } FMAW::printf("\t-------------------------------------------------"); //------------------------------------------------------------------ // End of AI script. //------------------------------------------------------------------ this->grid->selectCellAtIndexPath(previousPositionOfCursor); } else { FMAW::printf("\tI've finished!"); this->grid->enqueueCallbacks(); FMAW::Timer::dequeue_function(ID); this->onFinishTurnCallback(); } }; FMAW::Timer::enqueue_function(moveSomeUnit, 1500, true); } void PlayerAI::print() { FMAW::printf("I'm an AI player with ID=%d", this->ID); } <commit_msg>Improved AI performance.<commit_after>// Copyright 2015 FMAW #include "./player_ai.h" #include <cstdlib> #include <vector> #include <map> #include <algorithm> #include "./constants.h" #include "./unit.h" #include "./cell.h" #include "./turnManager.h" #include "./FMAW.h" #include <algorithm> PlayerAI::PlayerAI(Grid *grid, std::function<void(void)> callback) : grid(grid), onFinishTurnCallback(callback), seed(42) {} PlayerAI::PlayerAI(Grid *grid, std::function<void(void)> call, PlayerID ID) : Player(ID), grid(grid), onFinishTurnCallback(call), seed(42) {} void PlayerAI::startTurn() { // Prevent user from interacting with grid. this->grid->dequeueCallbacks(); IndexPath previousPositionOfCursor = this->grid->getSelectedPath(); bool recompute = true; std::map<IndexPath, int> distanceToNearestEnemyUnit; // Helper function to compute best cell to move. auto nearestEnemy = [&distanceToNearestEnemyUnit](IndexPath i, IndexPath j) -> bool { return distanceToNearestEnemyUnit[i] < distanceToNearestEnemyUnit[j]; }; // Now we have to make some decisions... // We will call the following callback once each 1.5s. this->unitNumber = 0; auto moveSomeUnit = [this, previousPositionOfCursor, &recompute, &distanceToNearestEnemyUnit, nearestEnemy](int ID) { FMAW::printf("Computing AI data..."); // Here we will store the units of this AI player and the path where // they are located. std::vector<Unit *> IAunits; std::vector<IndexPath> IApaths; std::vector<Unit *> playerUnits; std::vector<IndexPath> playerPaths; std::vector<IndexPath> chosenPaths; // We have to check the full grid to know where are our units. for (int row = 0; row < this->grid->numRows(); row++) { for (int col = 0; col < this->grid->numCols(); col++) { IndexPath path = { row, col }; Cell *c = this->grid->cellAtIndexPath(path); if (c->isOccupied()) { Unit *u = c->getCharacter(); if (u->getOwner() == this->ID) { IAunits.push_back(u); IApaths.push_back(path); } else { playerUnits.push_back(u); playerPaths.push_back(path); } } } } FMAW::printf("\tReady units"); std::map<IndexPath, std::vector<IndexPath>> IAUnitCanAttack; std::map<IndexPath, std::vector<IndexPath>> PlayerUnitCanBeAttackedBy; // Compute which units can attack which ones. for (IndexPath p : IApaths) { this->grid->setPickedUpCell(p); Cell *c = this->grid->cellAtIndexPath(p); if (c->getCharacter()->hasAvailableActions()) { for (IndexPath t : playerPaths) { if (grid->pickedUpUnitCanAttackCharacterAtCell(t)) { IAUnitCanAttack[p].push_back(t); PlayerUnitCanBeAttackedBy[t].push_back(p); } } } } FMAW::printf("\tReady attacks"); if (recompute) { // Compute distance to nearest visible enemy. for (int row = 0; row < this->grid->numRows(); row++) { for (int col = 0; col < this->grid->numCols(); col++) { IndexPath f = { row, col }; Cell *from = grid->cellAtIndexPath(f); distanceToNearestEnemyUnit[f] = COST_CELL_INFINITY; for (int tr = 0; tr < this->grid->numRows(); tr++) { for (int tc = 0; tc < this->grid->numCols(); tc++) { IndexPath t = { tr, tc }; Cell *to = this->grid->cellAtIndexPath(t); int distance = abs(t.row - f.row) + abs(t.col - f.col); if (to->isOccupied()) { Unit *u = to->getCharacter(); if (this->grid->canSeeCharacterAtCell(t) && u->getOwner() != this->ID) { distanceToNearestEnemyUnit[f] = distance; } } } } } } recompute = false; } FMAW::printf("\tReady distances"); bool canDoSomething = false; for (Unit *u : IAunits) { if (u->hasAvailableActions()) { canDoSomething = true; } } if (canDoSomething) { while (!IAunits[this->unitNumber]->hasAvailableActions()) { this->unitNumber++; this->unitNumber %= IAunits.size(); } //------------------------------------------------------------------ // Actual AI script. //------------------------------------------------------------------ bool actionDone = false; IndexPath path = IApaths[this->unitNumber]; Unit *unit = IAunits[this->unitNumber]; this->grid->setPickedUpCell(path); int row = path.row; int col = path.col; FMAW::printf("Choosing action for unit %d at %d %d", this->unitNumber, row, col); std::vector<IndexPath> shouldAttack; std::vector<IndexPath> attackable; // If I'm the only one who can attack, I'll do (random on tie). attackable = IAUnitCanAttack[path]; for (IndexPath t : attackable) { if (PlayerUnitCanBeAttackedBy[t].size() == 1) { shouldAttack.push_back(t); } } FMAW::printf("\tI'm the only one that can attack %d units", attackable.size()); // If I'm not the only one, I attack to a random (random on tie). if (shouldAttack.size() == 0) { attackable = IAUnitCanAttack[path]; for (IndexPath t : attackable) { shouldAttack.push_back(t); } FMAW::printf("\tMe and others can attack %d units", attackable.size()); } // I'll attack if I can. if (shouldAttack.size() > 0) { while (shouldAttack.size() > 0) { int rand = rand_r(&(this->seed)) % shouldAttack.size(); IndexPath tg = shouldAttack[rand]; if (this->grid->pickedUpUnitCanAttackCharacterAtCell(tg)) { FMAW::printf("\tWill attack unit at %d %d", tg.row, tg.col); bool kill = this->grid->attackCharacterAtCell( path, tg, ATTACK_DURATION); if (kill) { recompute = true; } actionDone = true; break; } else { FMAW::printf("\tCouldn't to attack unit at %d %d", tg.row, tg.col); shouldAttack.erase(shouldAttack.begin() + rand); } } } // If I can't attack, I'll move to the nearest enemy unit (random // on tie). if (!actionDone) { FMAW::printf("\tI couldn't attack any unit, so I'll move"); std::vector<IndexPath> availableMovements; for (int r = 0; r < this->grid->numRows(); r++) { for (int c = 0; c < this->grid->numCols(); c++) { IndexPath t = { r, c }; if (this->grid->canMoveCharacterFromCellToCell(path, t)) { availableMovements.push_back(t); } } } FMAW::printf("\tI can move to %d cells", availableMovements.size()); std::sort(availableMovements.begin(), availableMovements.end(), nearestEnemy); if (availableMovements.size() > 0) { IndexPath chosen = availableMovements[0]; FMAW::printf("\tI'll move to %d %d", chosen.row, chosen.col); this->grid->moveCharacterFromCellToCell(path, chosen, MOVEMENT_DURATION); IApaths[this->unitNumber] = chosen; } } FMAW::printf("\t-------------------------------------------------"); //------------------------------------------------------------------ // End of AI script. //------------------------------------------------------------------ this->grid->selectCellAtIndexPath(previousPositionOfCursor); } else { FMAW::printf("\tI've finished!"); this->grid->enqueueCallbacks(); FMAW::Timer::dequeue_function(ID); this->onFinishTurnCallback(); } }; FMAW::Timer::enqueue_function(moveSomeUnit, 1500, true); } void PlayerAI::print() { FMAW::printf("I'm an AI player with ID=%d", this->ID); } <|endoftext|>
<commit_before>#include <cmath> #include <vector> #include <iostream> #include <algorithm> void eratosthenes(int max, std::vector<bool> &val) { val.resize(max, true); val[0]=val[1]=false; int n=sqrt(val.size()); for(int i{2};i<=n;++i) if(val[i]) for(int j=i*i+i;j<val.size();j+=i) val[j]=false; } int main() { std::vector<bool> primes; eratosthenes(972, primes); int16_t num_primes{0}, sa, sb, n; for(int16_t a{-999};a<1000;a+=2) { for(int16_t b{3};b<998;b+=2) { if(!primes[b]) continue; for(n=0;primes[std::abs((n*n)+(a*n)+b)];++n); if(n>num_primes) { sa=a; sb=b; num_primes=n; } } } std::cout<<sa*sb<<std::endl; } <commit_msg>More optimizations<commit_after>#include <cmath> #include <vector> #include <iostream> #include <algorithm> void eratosthenes(int max, std::vector<bool> &val) { val.resize(max, true); val[0]=val[1]=false; int n=sqrt(val.size()); for(int i{2};i<=n;++i) if(val[i]) for(int j=i*i+i;j<val.size();j+=i) val[j]=false; } int main() { std::vector<bool> primes; eratosthenes(972, primes); int16_t num_primes{0}, sa, sb, n; for(int16_t a{-999};a<999;a+=2) { for(int16_t b=(a>3)?a:3;b<998;b+=2) { if(!primes[b]) continue; for(n=0;primes[std::abs((n*n)+(a*n)+b)];++n); if(n>num_primes) { sa=a; sb=b; num_primes=n; } } } std::cout<<sa*sb<<std::endl; } <|endoftext|>
<commit_before>/*******************************************************************************/ #include "WSLexer.h" /*******************************************************************************/ WSLexer::WSLexer() { } /*******************************************************************************/ WSLexer::~WSLexer() { } /*******************************************************************************/ void WSLexer::Put_HttpRequest(const char* inHttpStr, const char* inHttpStrEnd) { mpHttpStr = inHttpStr; mpHttpStrEnd = inHttpStrEnd ? inHttpStrEnd : inHttpStr + strlen(inHttpStr); mpCurrChar = mpHttpStr; mLine = 1; } /*******************************************************************************/ bool WSLexer::GetNextToken(Token* outToken) { outToken->Clear(); if( mpCurrChar == mpHttpStrEnd) { if(flagBracketsOpen || flagQuotesOpen) { throw exception("Error WSLexer: Don't closed brackets or quotes"); } return false; // end of string } bool flagLongWord = false; outToken->ps = mpCurrChar; do { switch(*mpCurrChar) { case 32: // " " { if( !flagLongWord) { outToken->mType = wsSpaceType; outToken->pe = mpCurrChar; mpCurrChar = mpCurrChar + 1; // I only work with UTF-8 char, it has a length of 1. } else { flagLongWord = false; } }break; case 42: // "*" case 43: // "+" case 46: // "." case 58: // ":" case 59: // ";" case 61: // "=" { if( !flagLongWord) { outToken->mType = wsSymbolType; outToken->pe = mpCurrChar; mpCurrChar = mpCurrChar + 1; } else { flagLongWord = false; } }break; case 34: // "" { if( !flagLongWord ) { outToken->mType = wsQuotesSymbolType; outToken->pe = mpCurrChar; mpCurrChar = mpCurrChar + 1; flagQuotesOpen = flagQuotesOpen ? false : true; } else { flagLongWord = false; } }break; case 28: // "(" case 29: // ")" { if( !flagLongWord ) { outToken->mType = wsBracketsSymbolType; outToken->pe = mpCurrChar; mpCurrChar = mpCurrChar + 1; flagBracketsOpen = flagBracketsOpen ? false : true; } else { flagLongWord = false; } }break; case 10: // "\n" case 13: // "\r" { if( !flagLongWord ) { outToken->mType = wsNewLineSymbolType; outToken->pe = mpCurrChar; mpCurrChar = mpCurrChar + 1; // if the next symbol is not \n or \r, increase Token::mLen by 1 if( !(*(mpCurrChar) == 10 || *(mpCurrChar) == 13) ) { outToken->mLine += 1; } } else { flagLongWord = false; } }break; // All other symbol default: { outToken->mType = wsDefaultType; outToken->pe = mpCurrChar; mpCurrChar = mpCurrChar + 1; flagLongWord = true; }break; } } while(flagLongWord); outToken->mLen = (outToken->pe - outToken->ps) + 1; outToken->mPosition = (outToken->pe - mpHttpStr) + 1; return true; }<commit_msg>fix WLexer pe + 1<commit_after>/*******************************************************************************/ #include "WSLexer.h" /*******************************************************************************/ WSLexer::WSLexer() { } /*******************************************************************************/ WSLexer::~WSLexer() { } /*******************************************************************************/ void WSLexer::Put_HttpRequest(const char* inHttpStr, const char* inHttpStrEnd) { mpHttpStr = inHttpStr; mpHttpStrEnd = inHttpStrEnd ? inHttpStrEnd : inHttpStr + strlen(inHttpStr); mpCurrChar = mpHttpStr; mLine = 1; } /*******************************************************************************/ bool WSLexer::GetNextToken(Token* outToken) { outToken->Clear(); if( mpCurrChar == mpHttpStrEnd ) { if(flagBracketsOpen || flagQuotesOpen) { throw exception("Error WSLexer: Don't closed brackets or quotes"); } return false; // end of string } bool flagLongWord = false; outToken->ps = mpCurrChar; do { switch(*mpCurrChar) { case 32: // " " { if( !flagLongWord) { mpCurrChar = mpCurrChar + 1; // I only work with UTF-8 char, it has a length of 1. outToken->mType = wsSpaceType; outToken->pe = mpCurrChar; } else { flagLongWord = false; } }break; case 42: // "*" case 43: // "+" case 46: // "." case 58: // ":" case 59: // ";" case 61: // "=" { if( !flagLongWord) { mpCurrChar = mpCurrChar + 1; outToken->mType = wsSymbolType; outToken->pe = mpCurrChar; } else { flagLongWord = false; } }break; case 34: // "" { if( !flagLongWord ) { mpCurrChar = mpCurrChar + 1; outToken->mType = wsQuotesSymbolType; outToken->pe = mpCurrChar; flagQuotesOpen = flagQuotesOpen ? false : true; } else { flagLongWord = false; } }break; case 28: // "(" case 29: // ")" { if( !flagLongWord ) { mpCurrChar = mpCurrChar + 1; outToken->mType = wsBracketsSymbolType; outToken->pe = mpCurrChar; flagBracketsOpen = flagBracketsOpen ? false : true; } else { flagLongWord = false; } }break; case 10: // "\n" case 13: // "\r" { if( !flagLongWord ) { mpCurrChar = mpCurrChar + 1; outToken->mType = wsNewLineSymbolType; outToken->pe = mpCurrChar; // if the next symbol is not \n or \r, increase Token::mLen by 1 if( !(*(mpCurrChar) == 10 || *(mpCurrChar) == 13) ) { outToken->mLine += 1; } } else { flagLongWord = false; } }break; // All other symbol default: { mpCurrChar = mpCurrChar + 1; outToken->mType = wsDefaultType; outToken->pe = mpCurrChar; flagLongWord = true; }break; } } while(flagLongWord); outToken->mLen = (outToken->pe - outToken->ps) + 1; outToken->mPosition = (outToken->pe - mpHttpStr) + 1; return true; }<|endoftext|>
<commit_before>/** @file A brief file description @section license License 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 "P_EventSystem.h" #include "RegressionSM.h" #define REGRESSION_SM_RETRY (100*HRTIME_MSECOND) void RegressionSM::set_status(int astatus) { ink_assert(astatus != REGRESSION_TEST_INPROGRESS); // INPROGRESS < NOT_RUN < PASSED < FAILED if (status != REGRESSION_TEST_FAILED) { if (status == REGRESSION_TEST_PASSED) { if (astatus != REGRESSION_TEST_NOT_RUN) status = astatus; } else { // INPROGRESS or NOT_RUN status = astatus; } } // else FAILED is FAILED } void RegressionSM::done(int astatus) { if (pending_action) { pending_action->cancel(); pending_action = 0; } set_status(astatus); if (pstatus) *pstatus = status; if (parent) parent->child_done(status); } void RegressionSM::run(int *apstatus) { pstatus = apstatus; run(); } void RegressionSM::xrun(RegressionSM *aparent) { parent = aparent; parent->nwaiting++; run(); } void RegressionSM::run_in(int *apstatus, ink_hrtime t) { pstatus = apstatus; SET_HANDLER(&RegressionSM::regression_sm_start); eventProcessor.schedule_in(this, t); } void RegressionSM::child_done(int astatus) { MUTEX_LOCK(l, mutex, this_ethread()); ink_assert(nwaiting > 0); --nwaiting; set_status(astatus); } int RegressionSM::regression_sm_waiting(int /* event ATS_UNUSED */ , void *data) { if (!nwaiting) { done(REGRESSION_TEST_NOT_RUN); delete this; return EVENT_DONE; } if (par || nwaiting > 1) { ((Event*)data)->schedule_in(REGRESSION_SM_RETRY); return EVENT_CONT; } run(); return EVENT_DONE; } int RegressionSM::regression_sm_start(int /* event ATS_UNUSED */, void * /* data ATS_UNUSED */) { run(); return EVENT_CONT; } RegressionSM *r_sequential(RegressionTest *t, RegressionSM* sm, ...) { RegressionSM *new_sm = new RegressionSM(t); va_list ap; va_start(ap, sm); new_sm->par = false; new_sm->rep = false; new_sm->ichild = 0; new_sm->nchildren = 0; new_sm->nwaiting = 0; while (0 != sm) { new_sm->children(new_sm->nchildren++) = sm; sm = va_arg(ap, RegressionSM*); } new_sm->n = new_sm->nchildren; va_end(ap); return new_sm; } RegressionSM *r_sequential(RegressionTest *t, int an, RegressionSM *sm) { RegressionSM *new_sm = new RegressionSM(t); new_sm->par = false; new_sm->rep = true; new_sm->ichild = 0; new_sm->nchildren = 1; new_sm->children(0) = sm; new_sm->nwaiting = 0; new_sm->n = an; return new_sm; } RegressionSM *r_parallel(RegressionTest *t, RegressionSM *sm, ...) { RegressionSM *new_sm = new RegressionSM(t); va_list ap; va_start(ap, sm); new_sm->par = true; new_sm->rep = false; new_sm->ichild = 0; new_sm->nchildren = 0; new_sm->nwaiting = 0; while (sm) { new_sm->children(new_sm->nchildren++) = sm; sm = va_arg(ap, RegressionSM*); } new_sm->n = new_sm->nchildren; va_end(ap); return new_sm; } RegressionSM *r_parallel(RegressionTest *t, int an, RegressionSM *sm) { RegressionSM *new_sm = new RegressionSM(t); new_sm->par = true; new_sm->rep = true; new_sm->ichild = 0; new_sm->nchildren = 1; new_sm->children(0) = sm; new_sm->nwaiting = 0; new_sm->n = an; return new_sm; } void RegressionSM::run() { // TODO: Why introduce another scope here? { MUTEX_TRY_LOCK(l, mutex, this_ethread()); if (!l || nwaiting > 1) goto Lretry; RegressionSM *x = 0; while (ichild < n) { if (!rep) x = children[ichild]; else { if (ichild != n-1) x = children[(intptr_t)0]->clone(); else x = children[(intptr_t)0]; } if (!ichild) nwaiting++; x->xrun(this); ichild++; if (!par && nwaiting > 1) goto Lretry; } } nwaiting--; if (!nwaiting) { done(REGRESSION_TEST_NOT_RUN); delete this; return; } Lretry: SET_HANDLER(&RegressionSM::regression_sm_waiting); pending_action = eventProcessor.schedule_in(this, REGRESSION_SM_RETRY); } RegressionSM::RegressionSM(const RegressionSM &ao) { RegressionSM &o = *(RegressionSM*)&ao; t = o.t; status = o.status; pstatus = o.pstatus; parent = &o; nwaiting = o.nwaiting; nchildren = o.nchildren; for (intptr_t i = 0; i < nchildren; i++) children(i) = o.children[i]->clone(); n = o.n; ichild = o.ichild; par = o.par; rep = o.rep; pending_action = o.pending_action; ink_assert(status == REGRESSION_TEST_INPROGRESS); ink_assert(nwaiting == 0); ink_assert(ichild == 0); mutex = new_ProxyMutex(); } struct ReRegressionSM: public RegressionSM { virtual void run() { if (time(NULL) < 1) { // example test rprintf(t,"impossible"); done(REGRESSION_TEST_FAILED); } else done(REGRESSION_TEST_PASSED); } ReRegressionSM(RegressionTest *at) : RegressionSM(at) {} virtual RegressionSM *clone() { return new ReRegressionSM(*this); } ReRegressionSM(const ReRegressionSM &o) { t = o.t; } }; REGRESSION_TEST(RegressionSM)(RegressionTest *t, int /* atype ATS_UNUSED */, int *pstatus) { r_sequential(t, r_parallel(t, new ReRegressionSM(t), new ReRegressionSM(t), NULL_PTR), r_sequential(t, new ReRegressionSM(t), new ReRegressionSM(t), NULL_PTR), r_parallel(t, 3, new ReRegressionSM(t)), r_sequential(t, 3, new ReRegressionSM(t)), r_parallel(t, r_sequential(t, 2, new ReRegressionSM(t)), r_parallel(t, 2, new ReRegressionSM(t)), NULL_PTR), NULL_PTR)->run(pstatus); } <commit_msg>TS-1475: Fix memory leak in regression tests. Coverity #1022150<commit_after>/** @file A brief file description @section license License 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 "P_EventSystem.h" #include "RegressionSM.h" #define REGRESSION_SM_RETRY (100*HRTIME_MSECOND) void RegressionSM::set_status(int astatus) { ink_assert(astatus != REGRESSION_TEST_INPROGRESS); // INPROGRESS < NOT_RUN < PASSED < FAILED if (status != REGRESSION_TEST_FAILED) { if (status == REGRESSION_TEST_PASSED) { if (astatus != REGRESSION_TEST_NOT_RUN) status = astatus; } else { // INPROGRESS or NOT_RUN status = astatus; } } // else FAILED is FAILED } void RegressionSM::done(int astatus) { if (pending_action) { pending_action->cancel(); pending_action = 0; } set_status(astatus); if (pstatus) *pstatus = status; if (parent) parent->child_done(status); } void RegressionSM::run(int *apstatus) { pstatus = apstatus; run(); } void RegressionSM::xrun(RegressionSM *aparent) { parent = aparent; parent->nwaiting++; run(); } void RegressionSM::run_in(int *apstatus, ink_hrtime t) { pstatus = apstatus; SET_HANDLER(&RegressionSM::regression_sm_start); eventProcessor.schedule_in(this, t); } void RegressionSM::child_done(int astatus) { MUTEX_LOCK(l, mutex, this_ethread()); ink_assert(nwaiting > 0); --nwaiting; set_status(astatus); } int RegressionSM::regression_sm_waiting(int /* event ATS_UNUSED */ , void *data) { if (!nwaiting) { done(REGRESSION_TEST_NOT_RUN); delete this; return EVENT_DONE; } if (par || nwaiting > 1) { ((Event*)data)->schedule_in(REGRESSION_SM_RETRY); return EVENT_CONT; } run(); return EVENT_DONE; } int RegressionSM::regression_sm_start(int /* event ATS_UNUSED */, void * /* data ATS_UNUSED */) { run(); return EVENT_CONT; } RegressionSM *r_sequential(RegressionTest *t, RegressionSM* sm, ...) { RegressionSM *new_sm = new RegressionSM(t); va_list ap; va_start(ap, sm); new_sm->par = false; new_sm->rep = false; new_sm->ichild = 0; new_sm->nchildren = 0; new_sm->nwaiting = 0; while (0 != sm) { new_sm->children(new_sm->nchildren++) = sm; sm = va_arg(ap, RegressionSM*); } new_sm->n = new_sm->nchildren; va_end(ap); return new_sm; } RegressionSM *r_sequential(RegressionTest *t, int an, RegressionSM *sm) { RegressionSM *new_sm = new RegressionSM(t); new_sm->par = false; new_sm->rep = true; new_sm->ichild = 0; new_sm->nchildren = 1; new_sm->children(0) = sm; new_sm->nwaiting = 0; new_sm->n = an; return new_sm; } RegressionSM *r_parallel(RegressionTest *t, RegressionSM *sm, ...) { RegressionSM *new_sm = new RegressionSM(t); va_list ap; va_start(ap, sm); new_sm->par = true; new_sm->rep = false; new_sm->ichild = 0; new_sm->nchildren = 0; new_sm->nwaiting = 0; while (sm) { new_sm->children(new_sm->nchildren++) = sm; sm = va_arg(ap, RegressionSM*); } new_sm->n = new_sm->nchildren; va_end(ap); return new_sm; } RegressionSM *r_parallel(RegressionTest *t, int an, RegressionSM *sm) { RegressionSM *new_sm = new RegressionSM(t); new_sm->par = true; new_sm->rep = true; new_sm->ichild = 0; new_sm->nchildren = 1; new_sm->children(0) = sm; new_sm->nwaiting = 0; new_sm->n = an; return new_sm; } void RegressionSM::run() { // TODO: Why introduce another scope here? { MUTEX_TRY_LOCK(l, mutex, this_ethread()); if (!l || nwaiting > 1) goto Lretry; RegressionSM *x = 0; while (ichild < n) { if (!rep) x = children[ichild]; else { if (ichild != n-1) x = children[(intptr_t)0]->clone(); else x = children[(intptr_t)0]; } if (!ichild) nwaiting++; x->xrun(this); ichild++; if (!par && nwaiting > 1) goto Lretry; } } nwaiting--; if (!nwaiting) { done(REGRESSION_TEST_NOT_RUN); delete this; return; } Lretry: SET_HANDLER(&RegressionSM::regression_sm_waiting); pending_action = eventProcessor.schedule_in(this, REGRESSION_SM_RETRY); } RegressionSM::RegressionSM(const RegressionSM &ao) { RegressionSM &o = *(RegressionSM*)&ao; t = o.t; status = o.status; pstatus = o.pstatus; parent = &o; nwaiting = o.nwaiting; nchildren = o.nchildren; for (intptr_t i = 0; i < nchildren; i++) children(i) = o.children[i]->clone(); n = o.n; ichild = o.ichild; par = o.par; rep = o.rep; pending_action = o.pending_action; ink_assert(status == REGRESSION_TEST_INPROGRESS); ink_assert(nwaiting == 0); ink_assert(ichild == 0); mutex = new_ProxyMutex(); } struct ReRegressionSM: public RegressionSM { virtual void run() { if (time(NULL) < 1) { // example test rprintf(t,"impossible"); done(REGRESSION_TEST_FAILED); } else done(REGRESSION_TEST_PASSED); } ReRegressionSM(RegressionTest *at) : RegressionSM(at) {} virtual RegressionSM *clone() { return new ReRegressionSM(*this); } ReRegressionSM(const ReRegressionSM &o) { t = o.t; } }; REGRESSION_TEST(RegressionSM)(RegressionTest *t, int /* atype ATS_UNUSED */, int *pstatus) { RegressionSM *top_sm = r_sequential(t, r_parallel(t, new ReRegressionSM(t), new ReRegressionSM(t), NULL_PTR), r_sequential(t, new ReRegressionSM(t), new ReRegressionSM(t), NULL_PTR), r_parallel(t, 3, new ReRegressionSM(t)), r_sequential(t, 3, new ReRegressionSM(t)), r_parallel(t, r_sequential(t, 2, new ReRegressionSM(t)), r_parallel(t, 2, new ReRegressionSM(t)), NULL_PTR), NULL_PTR); top_sm->run(pstatus); delete top_sm; } <|endoftext|>
<commit_before>#include <gtest/gtest.h> // windows //#pragma comment(lib, "gtestd.lib") int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>removed redundant MSVC code<commit_after>#include <gtest/gtest.h> int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2011 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 "reflection.h" #include "class_linker.h" #include "jni_internal.h" #include "object.h" #include "object_utils.h" #include "JniConstants.h" // Last to avoid problems with LOG redefinition. namespace art { Method* gBoolean_valueOf; Method* gByte_valueOf; Method* gCharacter_valueOf; Method* gDouble_valueOf; Method* gFloat_valueOf; Method* gInteger_valueOf; Method* gLong_valueOf; Method* gShort_valueOf; void InitBoxingMethods() { ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); gBoolean_valueOf = class_linker->FindSystemClass("Ljava/lang/Boolean;")->FindDeclaredDirectMethod("valueOf", "(Z)Ljava/lang/Boolean;"); gByte_valueOf = class_linker->FindSystemClass("Ljava/lang/Byte;")->FindDeclaredDirectMethod("valueOf", "(B)Ljava/lang/Byte;"); gCharacter_valueOf = class_linker->FindSystemClass("Ljava/lang/Character;")->FindDeclaredDirectMethod("valueOf", "(C)Ljava/lang/Character;"); gDouble_valueOf = class_linker->FindSystemClass("Ljava/lang/Double;")->FindDeclaredDirectMethod("valueOf", "(D)Ljava/lang/Double;"); gFloat_valueOf = class_linker->FindSystemClass("Ljava/lang/Float;")->FindDeclaredDirectMethod("valueOf", "(F)Ljava/lang/Float;"); gInteger_valueOf = class_linker->FindSystemClass("Ljava/lang/Integer;")->FindDeclaredDirectMethod("valueOf", "(I)Ljava/lang/Integer;"); gLong_valueOf = class_linker->FindSystemClass("Ljava/lang/Long;")->FindDeclaredDirectMethod("valueOf", "(J)Ljava/lang/Long;"); gShort_valueOf = class_linker->FindSystemClass("Ljava/lang/Short;")->FindDeclaredDirectMethod("valueOf", "(S)Ljava/lang/Short;"); } jobject InvokeMethod(JNIEnv* env, jobject javaMethod, jobject javaReceiver, jobject javaArgs) { Thread* self = Thread::Current(); ScopedThreadStateChange tsc(self, kRunnable); jmethodID mid = env->FromReflectedMethod(javaMethod); Method* m = reinterpret_cast<Method*>(mid); Class* declaring_class = m->GetDeclaringClass(); if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(declaring_class, true, true)) { return NULL; } Object* receiver = NULL; if (!m->IsStatic()) { // Check that the receiver is non-null and an instance of the field's declaring class. receiver = Decode<Object*>(env, javaReceiver); if (!VerifyObjectInClass(env, receiver, declaring_class)) { return NULL; } // Find the actual implementation of the virtual method. m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(m); mid = reinterpret_cast<jmethodID>(m); } // Get our arrays of arguments and their types, and check they're the same size. ObjectArray<Object>* objects = Decode<ObjectArray<Object>*>(env, javaArgs); MethodHelper mh(m); const DexFile::TypeList* classes = mh.GetParameterTypeList(); uint32_t classes_size = classes == NULL ? 0 : classes->Size(); uint32_t arg_count = (objects != NULL) ? objects->GetLength() : 0; if (arg_count != classes_size) { self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;", "wrong number of arguments; expected %d, got %d", classes_size, arg_count); return NULL; } // Translate javaArgs to a jvalue[]. UniquePtr<jvalue[]> args(new jvalue[arg_count]); JValue* decoded_args = reinterpret_cast<JValue*>(args.get()); for (uint32_t i = 0; i < arg_count; ++i) { Object* arg = objects->Get(i); Class* dst_class = mh.GetClassFromTypeIdx(classes->GetTypeItem(i).type_idx_); if (dst_class->IsPrimitive() || (arg != NULL && !arg->InstanceOf(dst_class))) { // We want to actually unbox primitives, but only reuse the error reporting for reference types. if (!UnboxPrimitiveForArgument(arg, dst_class, decoded_args[i], m, i)) { return NULL; } } else { // We already tested that these types are compatible. args[i].l = AddLocalReference<jobject>(env, arg); } } // Invoke the method. JValue value(InvokeWithJValues(env, javaReceiver, mid, args.get())); // Wrap any exception with "Ljava/lang/reflect/InvocationTargetException;" and return early. if (self->IsExceptionPending()) { jthrowable th = env->ExceptionOccurred(); env->ExceptionClear(); jclass exception_class = env->FindClass("java/lang/reflect/InvocationTargetException"); jmethodID mid = env->GetMethodID(exception_class, "<init>", "(Ljava/lang/Throwable;)V"); jobject exception_instance = env->NewObject(exception_class, mid, th); env->Throw(reinterpret_cast<jthrowable>(exception_instance)); return NULL; } // Box if necessary and return. BoxPrimitive(mh.GetReturnType()->GetPrimitiveType(), value); return AddLocalReference<jobject>(env, value.GetL()); } bool VerifyObjectInClass(JNIEnv* env, Object* o, Class* c) { const char* exception = NULL; if (o == NULL) { exception = "java/lang/NullPointerException"; } else if (!o->InstanceOf(c)) { exception = "java/lang/IllegalArgumentException"; } if (exception != NULL) { std::string expected_class_name(PrettyDescriptor(c)); std::string actual_class_name(PrettyTypeOf(o)); jniThrowExceptionFmt(env, exception, "expected receiver of type %s, but got %s", expected_class_name.c_str(), actual_class_name.c_str()); return false; } return true; } bool ConvertPrimitiveValue(Primitive::Type srcType, Primitive::Type dstType, const JValue& src, JValue& dst) { CHECK(srcType != Primitive::kPrimNot && dstType != Primitive::kPrimNot); switch (dstType) { case Primitive::kPrimBoolean: if (srcType == Primitive::kPrimBoolean) { dst.SetZ(src.GetZ()); return true; } break; case Primitive::kPrimChar: if (srcType == Primitive::kPrimChar) { dst.SetC(src.GetC()); return true; } break; case Primitive::kPrimByte: if (srcType == Primitive::kPrimByte) { dst.SetB(src.GetB()); return true; } break; case Primitive::kPrimShort: if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimShort) { dst.SetS(src.GetI()); return true; } break; case Primitive::kPrimInt: if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimChar || srcType == Primitive::kPrimShort || srcType == Primitive::kPrimInt) { dst.SetI(src.GetI()); return true; } break; case Primitive::kPrimLong: if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimChar || srcType == Primitive::kPrimShort || srcType == Primitive::kPrimInt) { dst.SetJ(src.GetI()); return true; } else if (srcType == Primitive::kPrimLong) { dst.SetJ(src.GetJ()); return true; } break; case Primitive::kPrimFloat: if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimChar || srcType == Primitive::kPrimShort || srcType == Primitive::kPrimInt) { dst.SetF(src.GetI()); return true; } else if (srcType == Primitive::kPrimLong) { dst.SetF(src.GetJ()); return true; } else if (srcType == Primitive::kPrimFloat) { dst.SetF(src.GetF()); return true; } break; case Primitive::kPrimDouble: if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimChar || srcType == Primitive::kPrimShort || srcType == Primitive::kPrimInt) { dst.SetD(src.GetI()); return true; } else if (srcType == Primitive::kPrimLong) { dst.SetD(src.GetJ()); return true; } else if (srcType == Primitive::kPrimFloat) { dst.SetD(src.GetF()); return true; } else if (srcType == Primitive::kPrimDouble) { dst.SetJ(src.GetJ()); return true; } break; default: break; } Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;", "invalid primitive conversion from %s to %s", PrettyDescriptor(srcType).c_str(), PrettyDescriptor(dstType).c_str()); return false; } void BoxPrimitive(Primitive::Type src_class, JValue& value) { if (src_class == Primitive::kPrimNot) { return; } Method* m = NULL; switch (src_class) { case Primitive::kPrimBoolean: m = gBoolean_valueOf; break; case Primitive::kPrimByte: m = gByte_valueOf; break; case Primitive::kPrimChar: m = gCharacter_valueOf; break; case Primitive::kPrimDouble: m = gDouble_valueOf; break; case Primitive::kPrimFloat: m = gFloat_valueOf; break; case Primitive::kPrimInt: m = gInteger_valueOf; break; case Primitive::kPrimLong: m = gLong_valueOf; break; case Primitive::kPrimShort: m = gShort_valueOf; break; case Primitive::kPrimVoid: // There's no such thing as a void field, and void methods invoked via reflection return null. value.SetL(NULL); return; default: LOG(FATAL) << static_cast<int>(src_class); } Thread* self = Thread::Current(); ScopedThreadStateChange tsc(self, kRunnable); JValue args[1] = { value }; m->Invoke(self, NULL, args, &value); } static std::string UnboxingFailureKind(Method* m, int index, Field* f) { if (m != NULL && index != -1) { ++index; // Humans count from 1. return StringPrintf("method %s argument %d", PrettyMethod(m, false).c_str(), index); } if (f != NULL) { return "field " + PrettyField(f, false); } return "result"; } static bool UnboxPrimitive(Object* o, Class* dst_class, JValue& unboxed_value, Method* m, int index, Field* f) { if (!dst_class->IsPrimitive()) { if (o != NULL && !o->InstanceOf(dst_class)) { Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;", "%s has type %s, got %s", UnboxingFailureKind(m, index, f).c_str(), PrettyDescriptor(dst_class).c_str(), PrettyTypeOf(o).c_str()); return false; } unboxed_value.SetL(o); return true; } else if (dst_class->GetPrimitiveType() == Primitive::kPrimVoid) { Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;", "can't unbox %s to void", UnboxingFailureKind(m, index, f).c_str()); return false; } if (o == NULL) { Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;", "%s has type %s, got null", UnboxingFailureKind(m, index, f).c_str(), PrettyDescriptor(dst_class).c_str()); return false; } JValue boxed_value; std::string src_descriptor(ClassHelper(o->GetClass()).GetDescriptor()); Class* src_class = NULL; ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); Field* primitive_field = o->GetClass()->GetIFields()->Get(0); if (src_descriptor == "Ljava/lang/Boolean;") { src_class = class_linker->FindPrimitiveClass('Z'); boxed_value.SetZ(primitive_field->GetBoolean(o)); } else if (src_descriptor == "Ljava/lang/Byte;") { src_class = class_linker->FindPrimitiveClass('B'); boxed_value.SetB(primitive_field->GetByte(o)); } else if (src_descriptor == "Ljava/lang/Character;") { src_class = class_linker->FindPrimitiveClass('C'); boxed_value.SetC(primitive_field->GetChar(o)); } else if (src_descriptor == "Ljava/lang/Float;") { src_class = class_linker->FindPrimitiveClass('F'); boxed_value.SetF(primitive_field->GetFloat(o)); } else if (src_descriptor == "Ljava/lang/Double;") { src_class = class_linker->FindPrimitiveClass('D'); boxed_value.SetD(primitive_field->GetDouble(o)); } else if (src_descriptor == "Ljava/lang/Integer;") { src_class = class_linker->FindPrimitiveClass('I'); boxed_value.SetI(primitive_field->GetInt(o)); } else if (src_descriptor == "Ljava/lang/Long;") { src_class = class_linker->FindPrimitiveClass('J'); boxed_value.SetJ(primitive_field->GetLong(o)); } else if (src_descriptor == "Ljava/lang/Short;") { src_class = class_linker->FindPrimitiveClass('S'); boxed_value.SetS(primitive_field->GetShort(o)); } else { Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;", "%s has type %s, got %s", UnboxingFailureKind(m, index, f).c_str(), PrettyDescriptor(dst_class).c_str(), PrettyDescriptor(src_descriptor.c_str()).c_str()); return false; } return ConvertPrimitiveValue(src_class->GetPrimitiveType(), dst_class->GetPrimitiveType(), boxed_value, unboxed_value); } bool UnboxPrimitiveForArgument(Object* o, Class* dst_class, JValue& unboxed_value, Method* m, size_t index) { CHECK(m != NULL); return UnboxPrimitive(o, dst_class, unboxed_value, m, index, NULL); } bool UnboxPrimitiveForField(Object* o, Class* dst_class, JValue& unboxed_value, Field* f) { CHECK(f != NULL); return UnboxPrimitive(o, dst_class, unboxed_value, NULL, -1, f); } bool UnboxPrimitiveForResult(Object* o, Class* dst_class, JValue& unboxed_value) { return UnboxPrimitive(o, dst_class, unboxed_value, NULL, -1, NULL); } } // namespace art <commit_msg>am 37f7775b: Slightly clearer reflection.<commit_after>/* * Copyright (C) 2011 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 "reflection.h" #include "class_linker.h" #include "jni_internal.h" #include "object.h" #include "object_utils.h" #include "JniConstants.h" // Last to avoid problems with LOG redefinition. namespace art { Method* gBoolean_valueOf; Method* gByte_valueOf; Method* gCharacter_valueOf; Method* gDouble_valueOf; Method* gFloat_valueOf; Method* gInteger_valueOf; Method* gLong_valueOf; Method* gShort_valueOf; void InitBoxingMethods() { ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); gBoolean_valueOf = class_linker->FindSystemClass("Ljava/lang/Boolean;")->FindDeclaredDirectMethod("valueOf", "(Z)Ljava/lang/Boolean;"); gByte_valueOf = class_linker->FindSystemClass("Ljava/lang/Byte;")->FindDeclaredDirectMethod("valueOf", "(B)Ljava/lang/Byte;"); gCharacter_valueOf = class_linker->FindSystemClass("Ljava/lang/Character;")->FindDeclaredDirectMethod("valueOf", "(C)Ljava/lang/Character;"); gDouble_valueOf = class_linker->FindSystemClass("Ljava/lang/Double;")->FindDeclaredDirectMethod("valueOf", "(D)Ljava/lang/Double;"); gFloat_valueOf = class_linker->FindSystemClass("Ljava/lang/Float;")->FindDeclaredDirectMethod("valueOf", "(F)Ljava/lang/Float;"); gInteger_valueOf = class_linker->FindSystemClass("Ljava/lang/Integer;")->FindDeclaredDirectMethod("valueOf", "(I)Ljava/lang/Integer;"); gLong_valueOf = class_linker->FindSystemClass("Ljava/lang/Long;")->FindDeclaredDirectMethod("valueOf", "(J)Ljava/lang/Long;"); gShort_valueOf = class_linker->FindSystemClass("Ljava/lang/Short;")->FindDeclaredDirectMethod("valueOf", "(S)Ljava/lang/Short;"); } jobject InvokeMethod(JNIEnv* env, jobject javaMethod, jobject javaReceiver, jobject javaArgs) { Thread* self = Thread::Current(); ScopedThreadStateChange tsc(self, kRunnable); jmethodID mid = env->FromReflectedMethod(javaMethod); Method* m = reinterpret_cast<Method*>(mid); Class* declaring_class = m->GetDeclaringClass(); if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(declaring_class, true, true)) { return NULL; } Object* receiver = NULL; if (!m->IsStatic()) { // Check that the receiver is non-null and an instance of the field's declaring class. receiver = Decode<Object*>(env, javaReceiver); if (!VerifyObjectInClass(env, receiver, declaring_class)) { return NULL; } // Find the actual implementation of the virtual method. m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(m); mid = reinterpret_cast<jmethodID>(m); } // Get our arrays of arguments and their types, and check they're the same size. ObjectArray<Object>* objects = Decode<ObjectArray<Object>*>(env, javaArgs); MethodHelper mh(m); const DexFile::TypeList* classes = mh.GetParameterTypeList(); uint32_t classes_size = classes == NULL ? 0 : classes->Size(); uint32_t arg_count = (objects != NULL) ? objects->GetLength() : 0; if (arg_count != classes_size) { self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;", "wrong number of arguments; expected %d, got %d", classes_size, arg_count); return NULL; } // Translate javaArgs to a jvalue[]. UniquePtr<jvalue[]> args(new jvalue[arg_count]); JValue* decoded_args = reinterpret_cast<JValue*>(args.get()); for (uint32_t i = 0; i < arg_count; ++i) { Object* arg = objects->Get(i); Class* dst_class = mh.GetClassFromTypeIdx(classes->GetTypeItem(i).type_idx_); if (!UnboxPrimitiveForArgument(arg, dst_class, decoded_args[i], m, i)) { return NULL; } if (!dst_class->IsPrimitive()) { args[i].l = AddLocalReference<jobject>(env, arg); } } // Invoke the method. JValue value(InvokeWithJValues(env, javaReceiver, mid, args.get())); // Wrap any exception with "Ljava/lang/reflect/InvocationTargetException;" and return early. if (self->IsExceptionPending()) { jthrowable th = env->ExceptionOccurred(); env->ExceptionClear(); jclass exception_class = env->FindClass("java/lang/reflect/InvocationTargetException"); jmethodID mid = env->GetMethodID(exception_class, "<init>", "(Ljava/lang/Throwable;)V"); jobject exception_instance = env->NewObject(exception_class, mid, th); env->Throw(reinterpret_cast<jthrowable>(exception_instance)); return NULL; } // Box if necessary and return. BoxPrimitive(mh.GetReturnType()->GetPrimitiveType(), value); return AddLocalReference<jobject>(env, value.GetL()); } bool VerifyObjectInClass(JNIEnv* env, Object* o, Class* c) { const char* exception = NULL; if (o == NULL) { exception = "java/lang/NullPointerException"; } else if (!o->InstanceOf(c)) { exception = "java/lang/IllegalArgumentException"; } if (exception != NULL) { std::string expected_class_name(PrettyDescriptor(c)); std::string actual_class_name(PrettyTypeOf(o)); jniThrowExceptionFmt(env, exception, "expected receiver of type %s, but got %s", expected_class_name.c_str(), actual_class_name.c_str()); return false; } return true; } bool ConvertPrimitiveValue(Primitive::Type srcType, Primitive::Type dstType, const JValue& src, JValue& dst) { CHECK(srcType != Primitive::kPrimNot && dstType != Primitive::kPrimNot); switch (dstType) { case Primitive::kPrimBoolean: if (srcType == Primitive::kPrimBoolean) { dst.SetZ(src.GetZ()); return true; } break; case Primitive::kPrimChar: if (srcType == Primitive::kPrimChar) { dst.SetC(src.GetC()); return true; } break; case Primitive::kPrimByte: if (srcType == Primitive::kPrimByte) { dst.SetB(src.GetB()); return true; } break; case Primitive::kPrimShort: if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimShort) { dst.SetS(src.GetI()); return true; } break; case Primitive::kPrimInt: if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimChar || srcType == Primitive::kPrimShort || srcType == Primitive::kPrimInt) { dst.SetI(src.GetI()); return true; } break; case Primitive::kPrimLong: if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimChar || srcType == Primitive::kPrimShort || srcType == Primitive::kPrimInt) { dst.SetJ(src.GetI()); return true; } else if (srcType == Primitive::kPrimLong) { dst.SetJ(src.GetJ()); return true; } break; case Primitive::kPrimFloat: if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimChar || srcType == Primitive::kPrimShort || srcType == Primitive::kPrimInt) { dst.SetF(src.GetI()); return true; } else if (srcType == Primitive::kPrimLong) { dst.SetF(src.GetJ()); return true; } else if (srcType == Primitive::kPrimFloat) { dst.SetF(src.GetF()); return true; } break; case Primitive::kPrimDouble: if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimChar || srcType == Primitive::kPrimShort || srcType == Primitive::kPrimInt) { dst.SetD(src.GetI()); return true; } else if (srcType == Primitive::kPrimLong) { dst.SetD(src.GetJ()); return true; } else if (srcType == Primitive::kPrimFloat) { dst.SetD(src.GetF()); return true; } else if (srcType == Primitive::kPrimDouble) { dst.SetJ(src.GetJ()); return true; } break; default: break; } Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;", "invalid primitive conversion from %s to %s", PrettyDescriptor(srcType).c_str(), PrettyDescriptor(dstType).c_str()); return false; } void BoxPrimitive(Primitive::Type src_class, JValue& value) { if (src_class == Primitive::kPrimNot) { return; } Method* m = NULL; switch (src_class) { case Primitive::kPrimBoolean: m = gBoolean_valueOf; break; case Primitive::kPrimByte: m = gByte_valueOf; break; case Primitive::kPrimChar: m = gCharacter_valueOf; break; case Primitive::kPrimDouble: m = gDouble_valueOf; break; case Primitive::kPrimFloat: m = gFloat_valueOf; break; case Primitive::kPrimInt: m = gInteger_valueOf; break; case Primitive::kPrimLong: m = gLong_valueOf; break; case Primitive::kPrimShort: m = gShort_valueOf; break; case Primitive::kPrimVoid: // There's no such thing as a void field, and void methods invoked via reflection return null. value.SetL(NULL); return; default: LOG(FATAL) << static_cast<int>(src_class); } Thread* self = Thread::Current(); ScopedThreadStateChange tsc(self, kRunnable); JValue args[1] = { value }; m->Invoke(self, NULL, args, &value); } static std::string UnboxingFailureKind(Method* m, int index, Field* f) { if (m != NULL && index != -1) { ++index; // Humans count from 1. return StringPrintf("method %s argument %d", PrettyMethod(m, false).c_str(), index); } if (f != NULL) { return "field " + PrettyField(f, false); } return "result"; } static bool UnboxPrimitive(Object* o, Class* dst_class, JValue& unboxed_value, Method* m, int index, Field* f) { if (!dst_class->IsPrimitive()) { if (o != NULL && !o->InstanceOf(dst_class)) { Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;", "%s has type %s, got %s", UnboxingFailureKind(m, index, f).c_str(), PrettyDescriptor(dst_class).c_str(), PrettyTypeOf(o).c_str()); return false; } unboxed_value.SetL(o); return true; } else if (dst_class->GetPrimitiveType() == Primitive::kPrimVoid) { Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;", "can't unbox %s to void", UnboxingFailureKind(m, index, f).c_str()); return false; } if (o == NULL) { Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;", "%s has type %s, got null", UnboxingFailureKind(m, index, f).c_str(), PrettyDescriptor(dst_class).c_str()); return false; } JValue boxed_value; std::string src_descriptor(ClassHelper(o->GetClass()).GetDescriptor()); Class* src_class = NULL; ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); Field* primitive_field = o->GetClass()->GetIFields()->Get(0); if (src_descriptor == "Ljava/lang/Boolean;") { src_class = class_linker->FindPrimitiveClass('Z'); boxed_value.SetZ(primitive_field->GetBoolean(o)); } else if (src_descriptor == "Ljava/lang/Byte;") { src_class = class_linker->FindPrimitiveClass('B'); boxed_value.SetB(primitive_field->GetByte(o)); } else if (src_descriptor == "Ljava/lang/Character;") { src_class = class_linker->FindPrimitiveClass('C'); boxed_value.SetC(primitive_field->GetChar(o)); } else if (src_descriptor == "Ljava/lang/Float;") { src_class = class_linker->FindPrimitiveClass('F'); boxed_value.SetF(primitive_field->GetFloat(o)); } else if (src_descriptor == "Ljava/lang/Double;") { src_class = class_linker->FindPrimitiveClass('D'); boxed_value.SetD(primitive_field->GetDouble(o)); } else if (src_descriptor == "Ljava/lang/Integer;") { src_class = class_linker->FindPrimitiveClass('I'); boxed_value.SetI(primitive_field->GetInt(o)); } else if (src_descriptor == "Ljava/lang/Long;") { src_class = class_linker->FindPrimitiveClass('J'); boxed_value.SetJ(primitive_field->GetLong(o)); } else if (src_descriptor == "Ljava/lang/Short;") { src_class = class_linker->FindPrimitiveClass('S'); boxed_value.SetS(primitive_field->GetShort(o)); } else { Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;", "%s has type %s, got %s", UnboxingFailureKind(m, index, f).c_str(), PrettyDescriptor(dst_class).c_str(), PrettyDescriptor(src_descriptor.c_str()).c_str()); return false; } return ConvertPrimitiveValue(src_class->GetPrimitiveType(), dst_class->GetPrimitiveType(), boxed_value, unboxed_value); } bool UnboxPrimitiveForArgument(Object* o, Class* dst_class, JValue& unboxed_value, Method* m, size_t index) { CHECK(m != NULL); return UnboxPrimitive(o, dst_class, unboxed_value, m, index, NULL); } bool UnboxPrimitiveForField(Object* o, Class* dst_class, JValue& unboxed_value, Field* f) { CHECK(f != NULL); return UnboxPrimitive(o, dst_class, unboxed_value, NULL, -1, f); } bool UnboxPrimitiveForResult(Object* o, Class* dst_class, JValue& unboxed_value) { return UnboxPrimitive(o, dst_class, unboxed_value, NULL, -1, NULL); } } // namespace art <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <arrayfire.h> #include <af/dim4.hpp> #include <af/traits.hpp> #include <string> #include <vector> #include <iostream> #include <testHelpers.hpp> using std::string; using std::cout; using std::endl; using std::vector; using af::af_cfloat; using af::af_cdouble; template<typename T> class Transpose : public ::testing::Test { public: virtual void SetUp() { subMat2D.push_back({2,7,1}); subMat2D.push_back({2,7,1}); subMat3D.push_back({2,7,1}); subMat3D.push_back({2,7,1}); subMat3D.push_back(span); } vector<af_seq> subMat2D; vector<af_seq> subMat3D; }; // create a list of types to be tested typedef ::testing::Types<float, af_cfloat, double, af_cdouble, int, unsigned, char, unsigned char> TestTypes; // register the type list TYPED_TEST_CASE(Transpose, TestTypes); template<typename T> void trsTest(string pTestFile, bool isSubRef=false, const vector<af_seq> *seqv=nullptr) { af::dim4 dims(1); vector<T> in; vector<vector<T>> tests; ReadTests<int, T>(pTestFile,dims,in,tests); af_array outArray = 0; af_array inArray = 0; T *outData; ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &in.front(), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<T>::af_type)); // check if the test is for indexed Array if (isSubRef) { af::dim4 newDims(dims[1]-4,dims[0]-4,dims[2],dims[3]); af_array subArray = 0; ASSERT_EQ(AF_SUCCESS, af_index(&subArray,inArray,seqv->size(),&seqv->front())); ASSERT_EQ(AF_SUCCESS, af_transpose(&outArray,subArray)); // destroy the temporary indexed Array ASSERT_EQ(AF_SUCCESS, af_destroy_array(subArray)); dim_type nElems; ASSERT_EQ(AF_SUCCESS, af_get_elements(&nElems,outArray)); outData = new T[nElems]; } else { ASSERT_EQ(AF_SUCCESS, af_transpose(&outArray,inArray)); outData = new T[dims.elements()]; } ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)outData, outArray)); for (int testIter=0; testIter<tests.size(); ++testIter) { vector<T> currGoldBar = tests[testIter]; size_t nElems = currGoldBar.size(); for (size_t elIter=0; elIter<nElems; ++elIter) { ASSERT_EQ(currGoldBar[elIter],outData[elIter])<< "at: " << elIter<< std::endl; } } // cleanup delete[] outData; ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray)); ASSERT_EQ(AF_SUCCESS, af_destroy_array(outArray)); } TYPED_TEST(Transpose,Vector) { trsTest<TypeParam>(string(TEST_DIR"/transpose/vector.test")); } TYPED_TEST(Transpose,VectorBatch) { trsTest<TypeParam>(string(TEST_DIR"/transpose/vector_batch.test")); } TYPED_TEST(Transpose,Square) { trsTest<TypeParam>(string(TEST_DIR"/transpose/square.test")); } TYPED_TEST(Transpose,SquareBatch) { trsTest<TypeParam>(string(TEST_DIR"/transpose/square_batch.test")); } TYPED_TEST(Transpose,Rectangle) { trsTest<TypeParam>(string(TEST_DIR"/transpose/rectangle.test")); } TYPED_TEST(Transpose,RectangleBatch) { trsTest<TypeParam>(string(TEST_DIR"/transpose/rectangle_batch.test")); } TYPED_TEST(Transpose,SubRef) { trsTest<TypeParam>(string(TEST_DIR"/transpose/offset.test"),true,&(this->subMat2D)); } TYPED_TEST(Transpose,SubRefBatch) { trsTest<TypeParam>(string(TEST_DIR"/transpose/offset_batch.test"),true,&(this->subMat3D)); } TYPED_TEST(Transpose,InvalidArgs) { af::dim4 dims(1); vector<TypeParam> in; vector<vector<TypeParam>> tests; ReadTests<int, TypeParam>(string(TEST_DIR"/transpose/square.test"),dims,in,tests); af_array inArray = 0; af_array outArray = 0; // square test file is 100x100 originally // usee new dimensions for this argument // unit test af::dim4 newDims(5,5,2,2); ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &in.front(), newDims.ndims(), newDims.get(), (af_dtype) af::dtype_traits<TypeParam>::af_type)); ASSERT_EQ(AF_ERR_ARG, af_transpose(&outArray,inArray)); } <commit_msg>Fixing warnings in transpose tests<commit_after>#include <gtest/gtest.h> #include <arrayfire.h> #include <af/dim4.hpp> #include <af/traits.hpp> #include <string> #include <vector> #include <iostream> #include <testHelpers.hpp> using std::string; using std::cout; using std::endl; using std::vector; using af::af_cfloat; using af::af_cdouble; template<typename T> class Transpose : public ::testing::Test { public: virtual void SetUp() { subMat2D.push_back({2,7,1}); subMat2D.push_back({2,7,1}); subMat3D.push_back({2,7,1}); subMat3D.push_back({2,7,1}); subMat3D.push_back(span); } vector<af_seq> subMat2D; vector<af_seq> subMat3D; }; // create a list of types to be tested typedef ::testing::Types<float, af_cfloat, double, af_cdouble, int, unsigned, char, unsigned char> TestTypes; // register the type list TYPED_TEST_CASE(Transpose, TestTypes); template<typename T> void trsTest(string pTestFile, bool isSubRef=false, const vector<af_seq> *seqv=nullptr) { af::dim4 dims(1); vector<T> in; vector<vector<T>> tests; ReadTests<int, T>(pTestFile,dims,in,tests); af_array outArray = 0; af_array inArray = 0; T *outData; ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &in.front(), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<T>::af_type)); // check if the test is for indexed Array if (isSubRef) { af::dim4 newDims(dims[1]-4,dims[0]-4,dims[2],dims[3]); af_array subArray = 0; ASSERT_EQ(AF_SUCCESS, af_index(&subArray,inArray,seqv->size(),&seqv->front())); ASSERT_EQ(AF_SUCCESS, af_transpose(&outArray,subArray)); // destroy the temporary indexed Array ASSERT_EQ(AF_SUCCESS, af_destroy_array(subArray)); dim_type nElems; ASSERT_EQ(AF_SUCCESS, af_get_elements(&nElems,outArray)); outData = new T[nElems]; } else { ASSERT_EQ(AF_SUCCESS, af_transpose(&outArray,inArray)); outData = new T[dims.elements()]; } ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)outData, outArray)); for (size_t testIter=0; testIter<tests.size(); ++testIter) { vector<T> currGoldBar = tests[testIter]; size_t nElems = currGoldBar.size(); for (size_t elIter=0; elIter<nElems; ++elIter) { ASSERT_EQ(currGoldBar[elIter],outData[elIter])<< "at: " << elIter<< std::endl; } } // cleanup delete[] outData; ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray)); ASSERT_EQ(AF_SUCCESS, af_destroy_array(outArray)); } TYPED_TEST(Transpose,Vector) { trsTest<TypeParam>(string(TEST_DIR"/transpose/vector.test")); } TYPED_TEST(Transpose,VectorBatch) { trsTest<TypeParam>(string(TEST_DIR"/transpose/vector_batch.test")); } TYPED_TEST(Transpose,Square) { trsTest<TypeParam>(string(TEST_DIR"/transpose/square.test")); } TYPED_TEST(Transpose,SquareBatch) { trsTest<TypeParam>(string(TEST_DIR"/transpose/square_batch.test")); } TYPED_TEST(Transpose,Rectangle) { trsTest<TypeParam>(string(TEST_DIR"/transpose/rectangle.test")); } TYPED_TEST(Transpose,RectangleBatch) { trsTest<TypeParam>(string(TEST_DIR"/transpose/rectangle_batch.test")); } TYPED_TEST(Transpose,SubRef) { trsTest<TypeParam>(string(TEST_DIR"/transpose/offset.test"),true,&(this->subMat2D)); } TYPED_TEST(Transpose,SubRefBatch) { trsTest<TypeParam>(string(TEST_DIR"/transpose/offset_batch.test"),true,&(this->subMat3D)); } TYPED_TEST(Transpose,InvalidArgs) { af::dim4 dims(1); vector<TypeParam> in; vector<vector<TypeParam>> tests; ReadTests<int, TypeParam>(string(TEST_DIR"/transpose/square.test"),dims,in,tests); af_array inArray = 0; af_array outArray = 0; // square test file is 100x100 originally // usee new dimensions for this argument // unit test af::dim4 newDims(5,5,2,2); ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &in.front(), newDims.ndims(), newDims.get(), (af_dtype) af::dtype_traits<TypeParam>::af_type)); ASSERT_EQ(AF_ERR_ARG, af_transpose(&outArray,inArray)); } <|endoftext|>
<commit_before>//===------------------------- unwind_06.cpp ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <exception> #include <stdlib.h> #include <assert.h> #include <stdio.h> // Compile with -Os to get compiler uses float registers to hold float variables __attribute__((noinline)) double get(int x) { return (double)x; } double try1(bool v) { double a = get(0); double b = get(0); if (v) throw 10; return get(0)+a+b; } double try2(bool v) { double a = get(0); double b = get(0); double c = get(0); if (v) throw 10; return get(0)+a+b+c; } double try3(bool v) { double a = get(0); double b = get(0); double c = get(0); double d = get(0); if (v) throw 10; return get(0)+a+b+c+d; } double try4(bool v) { double a = get(0); double b = get(0); double c = get(0); double d = get(0); double e = get(0); if (v) throw 10; return get(0)+a+b+c+d+e; } double try5(bool v) { double a = get(0); double b = get(0); double c = get(0); double d = get(0); double e = get(0); double f = get(0); if (v) throw 10; return get(0)+a+b+c+d+e+f; } double try6(bool v) { double a = get(0); double b = get(0); double c = get(0); double d = get(0); double e = get(0); double f = get(0); double g = get(0); if (v) throw 10; return get(0)+a+b+c+d+e+f+g; } double try7(bool v) { double a = get(0); double b = get(0); double c = get(0); double d = get(0); double e = get(0); double f = get(0); double g = get(0); double h = get(0); if (v) throw 10; return get(0)+a+b+c+d+e+f+g; } double try8(bool v) { double a = get(0); double b = get(0); double c = get(0); double d = get(0); double e = get(0); double f = get(0); double g = get(0); double h = get(0); double i = get(0); if (v) throw 10; return get(0)+a+b+c+d+e+f+g+i; } double foo() { double a = get(1); double b = get(2); double c = get(3); double d = get(4); double e = get(5); double f = get(6); double g = get(7); double h = get(8); try { try1(true); } catch (int e) { } assert(a == get(1)); assert(b == get(2)); assert(c == get(3)); assert(d == get(4)); assert(e == get(5)); assert(f == get(6)); assert(g == get(7)); assert(h == get(8)); try { try2(true); } catch (int e) { } assert(a == get(1)); assert(b == get(2)); assert(c == get(3)); assert(d == get(4)); assert(e == get(5)); assert(f == get(6)); assert(g == get(7)); assert(h == get(8)); try { try3(true); } catch (int e) { } assert(a == get(1)); assert(b == get(2)); assert(c == get(3)); assert(d == get(4)); assert(e == get(5)); assert(f == get(6)); assert(g == get(7)); assert(h == get(8)); try { try4(true); } catch (int e) { } assert(a == get(1)); assert(b == get(2)); assert(c == get(3)); assert(d == get(4)); assert(e == get(5)); assert(f == get(6)); assert(g == get(7)); assert(h == get(8)); try { try5(true); } catch (int e) { } assert(a == get(1)); assert(b == get(2)); assert(c == get(3)); assert(d == get(4)); assert(e == get(5)); assert(f == get(6)); assert(g == get(7)); assert(h == get(8)); try { try6(true); } catch (int e) { } assert(a == get(1)); assert(b == get(2)); assert(c == get(3)); assert(d == get(4)); assert(e == get(5)); assert(f == get(6)); assert(g == get(7)); assert(h == get(8)); try { try7(true); } catch (int e) { } assert(a == get(1)); assert(b == get(2)); assert(c == get(3)); assert(d == get(4)); assert(e == get(5)); assert(f == get(6)); assert(g == get(7)); assert(h == get(8)); try { try8(true); } catch (int e) { } assert(a == get(1)); assert(b == get(2)); assert(c == get(3)); assert(d == get(4)); assert(e == get(5)); assert(f == get(6)); assert(g == get(7)); assert(h == get(8)); return a+b+c+d+e+f+g+h; } int main() { foo(); } <commit_msg>Try harder to get the compiler to use float registers in different places to increase the chance of messing up any preserved registers.<commit_after>//===------------------------- unwind_06.cpp ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <exception> #include <stdlib.h> #include <assert.h> #include <stdio.h> // Compile with -Os to get compiler uses float registers to hold float variables double get_(int x) { return (double)x; } double (* volatile get)(int) = get_; volatile int counter; double try1(bool v) { double a = get(0); double b = get(1); for (counter = 100; counter; --counter) a += get(1) + b; if (v) throw 10; return get(0)+a+b; } double try2(bool v) { double a = get(0); double b = get(1); double c = get(2); for (counter = 100; counter; --counter) a += get(1) + b + c; if (v) throw 10; return get(0)+a+b+c; } double try3(bool v) { double a = get(0); double b = get(1); double c = get(2); double d = get(3); for (counter = 100; counter; --counter) a += get(1) + b + c + d; if (v) throw 10; return get(0)+a+b+c+d; } double try4(bool v) { double a = get(0); double b = get(0); double c = get(0); double d = get(0); double e = get(0); for (counter = 100; counter; --counter) a += get(1) + b+c+d+e; if (v) throw 10; return get(0)+a+b+c+d+e; } double try5(bool v) { double a = get(0); double b = get(0); double c = get(0); double d = get(0); double e = get(0); double f = get(0); for (counter = 100; counter; --counter) a += get(1) + b+c+d+e+f; if (v) throw 10; return get(0)+a+b+c+d+e+f; } double try6(bool v) { double a = get(0); double b = get(0); double c = get(0); double d = get(0); double e = get(0); double f = get(0); double g = get(0); for (counter = 100; counter; --counter) a += get(1) + b+c+d+e+f+g; if (v) throw 10; return get(0)+a+b+c+d+e+f+g; } double try7(bool v) { double a = get(0); double b = get(0); double c = get(0); double d = get(0); double e = get(0); double f = get(0); double g = get(0); double h = get(0); for (counter = 100; counter; --counter) a += get(1) + b+c+d+e+f+g; if (v) throw 10; return get(0)+a+b+c+d+e+f+g; } double try8(bool v) { double a = get(0); double b = get(0); double c = get(0); double d = get(0); double e = get(0); double f = get(0); double g = get(0); double h = get(0); double i = get(0); for (counter = 100; counter; --counter) a += get(1) + b+c+d+e+f+g+i; if (v) throw 10; return get(0)+a+b+c+d+e+f+g+i; } double foo() { double a = get(1); double b = get(2); double c = get(3); double d = get(4); double e = get(5); double f = get(6); double g = get(7); double h = get(8); try { try1(true); } catch (int e) { } assert(a == get(1)); assert(b == get(2)); assert(c == get(3)); assert(d == get(4)); assert(e == get(5)); assert(f == get(6)); assert(g == get(7)); assert(h == get(8)); try { try2(true); } catch (int e) { } assert(a == get(1)); assert(b == get(2)); assert(c == get(3)); assert(d == get(4)); assert(e == get(5)); assert(f == get(6)); assert(g == get(7)); assert(h == get(8)); try { try3(true); } catch (int e) { } assert(a == get(1)); assert(b == get(2)); assert(c == get(3)); assert(d == get(4)); assert(e == get(5)); assert(f == get(6)); assert(g == get(7)); assert(h == get(8)); try { try4(true); } catch (int e) { } assert(a == get(1)); assert(b == get(2)); assert(c == get(3)); assert(d == get(4)); assert(e == get(5)); assert(f == get(6)); assert(g == get(7)); assert(h == get(8)); try { try5(true); } catch (int e) { } assert(a == get(1)); assert(b == get(2)); assert(c == get(3)); assert(d == get(4)); assert(e == get(5)); assert(f == get(6)); assert(g == get(7)); assert(h == get(8)); try { try6(true); } catch (int e) { } assert(a == get(1)); assert(b == get(2)); assert(c == get(3)); assert(d == get(4)); assert(e == get(5)); assert(f == get(6)); assert(g == get(7)); assert(h == get(8)); try { try7(true); } catch (int e) { } assert(a == get(1)); assert(b == get(2)); assert(c == get(3)); assert(d == get(4)); assert(e == get(5)); assert(f == get(6)); assert(g == get(7)); assert(h == get(8)); try { try8(true); } catch (int e) { } assert(a == get(1)); assert(b == get(2)); assert(c == get(3)); assert(d == get(4)); assert(e == get(5)); assert(f == get(6)); assert(g == get(7)); assert(h == get(8)); return a+b+c+d+e+f+g+h; } int main() { foo(); } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (C) 2014 Flavio Fontana & Luis Rodrigues. All rights reserved. * Author: Flavio Fontana <[email protected]> * Author: Luis Rodrigues <[email protected]> * * 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 TerarangerOne nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include <string> #include "terarangerone/terarangerone.h" namespace terarangerone { TerarangerOne::TerarangerOne() { // Get paramters ros::NodeHandle private_node_handle_("~"); private_node_handle_.param("portname", portname_, std::string("/dev/ttyUSB0")); // Publishers range_publisher_ = nh_.advertise<sensor_msgs::Range>("terarangerone", 1); // Create serial port serial_port_ = new SerialPort(); // Set callback function for the serial ports serial_data_callback_function_ = boost::bind(&TerarangerOne::serialDataCallback, this, _1); serial_port_->setSerialCallbackFunction(&serial_data_callback_function_); // Connect serial port if (!serial_port_->connect(portname_)) { ros::shutdown(); return; } // Output loaded parameters to console for double checking ROS_INFO("[%s] is up and running with the following parameters:", ros::this_node::getName().c_str()); ROS_INFO("[%s] portname: %s",ros::this_node::getName().c_str(), portname_.c_str()); // Set operation Mode setMode(BINARY_MODE); // Dynamic reconfigure dyn_param_server_callback_function_ = boost::bind(&TerarangerOne::dynParamCallback, this, _1, _2); dyn_param_server_.setCallback(dyn_param_server_callback_function_); } TerarangerOne::~TerarangerOne() { } uint8_t TerarangerOne::crc8(uint8_t *p, uint8_t len) { uint16_t i; uint16_t crc = 0x0; while (len--) { i = (crc ^ *p++) & 0xFF; crc = (crc_table[i] ^ (crc << 8)) & 0xFF; } return crc & 0xFF; } void TerarangerOne::serialDataCallback(uint8_t single_character) { static uint8_t input_buffer[BUFFER_SIZE]; static int buffer_ctr = 0; static int seq_ctr = 0; sensor_msgs::Range range_msg; range_msg.field_of_view = 0.0593; range_msg.max_range = 14.0; range_msg.min_range = 0.2; range_msg.radiation_type = sensor_msgs::Range::INFRARED; if (single_character != 'T' && buffer_ctr < 4) { // not begin of serial feed so add char to buffer input_buffer[buffer_ctr++] = single_character; } else if (single_character == 'T' && buffer_ctr == 4) { // end of feed, calculate int16_t crc = crc8(input_buffer, 3); if (crc == input_buffer[3]) { int16_t range = input_buffer[1] << 8; range |= input_buffer[2]; if (range < 14000 && range > 200) { range_msg.header.stamp = ros::Time::now(); range_msg.header.seq = seq_ctr++; range_msg.range = range * 0.001; // convert to m range_publisher_.publish(range_msg); } } // reset buffer_ctr = 0; // clear struct bzero(&input_buffer, BUFFER_SIZE); // store T input_buffer[buffer_ctr++] = single_character; } else if (buffer_ctr >= 4) { buffer_ctr = 0; } } void TerarangerOne::setMode(char c) { serial_port_->sendChar(c); } void TerarangerOne::dynParamCallback(const terarangerone::TerarangerOneConfig &config, uint32_t level) { if (config.Speed == terarangerone::TerarangerOne_Fast) { setMode(FAST_MODE); } if (config.Speed == terarangerone::TerarangerOne_Precise) { setMode(PRECISE_MODE); } if (config.Environment == terarangerone::TerarangerOne_Indoor) { setMode(INDOOR_MODE); } if (config.Environment == terarangerone::TerarangerOne_Outdoor) { setMode(OUTDOOR_MODE); } } } // namespace terarangerone int main(int argc, char **argv) { ros::init(argc, argv, "terarangerone"); terarangerone::TerarangerOne tera_bee; ros::spin(); return 0; } <commit_msg>improved the parser, now every time we receive T character we reset the input_buffer<commit_after>/**************************************************************************** * * Copyright (C) 2014 Flavio Fontana & Luis Rodrigues. All rights reserved. * Author: Flavio Fontana <[email protected]> * Author: Luis Rodrigues <[email protected]> * * 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 TerarangerOne nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include <string> #include "terarangerone/terarangerone.h" namespace terarangerone { TerarangerOne::TerarangerOne() { // Get paramters ros::NodeHandle private_node_handle_("~"); private_node_handle_.param("portname", portname_, std::string("/dev/ttyUSB0")); // Publishers range_publisher_ = nh_.advertise<sensor_msgs::Range>("terarangerone", 1); // Create serial port serial_port_ = new SerialPort(); // Set callback function for the serial ports serial_data_callback_function_ = boost::bind(&TerarangerOne::serialDataCallback, this, _1); serial_port_->setSerialCallbackFunction(&serial_data_callback_function_); // Connect serial port if (!serial_port_->connect(portname_)) { ros::shutdown(); return; } // Output loaded parameters to console for double checking ROS_INFO("[%s] is up and running with the following parameters:", ros::this_node::getName().c_str()); ROS_INFO("[%s] portname: %s", ros::this_node::getName().c_str(), portname_.c_str()); // Set operation Mode setMode(BINARY_MODE); // Dynamic reconfigure dyn_param_server_callback_function_ = boost::bind(&TerarangerOne::dynParamCallback, this, _1, _2); dyn_param_server_.setCallback(dyn_param_server_callback_function_); } TerarangerOne::~TerarangerOne() { } uint8_t TerarangerOne::crc8(uint8_t *p, uint8_t len) { uint16_t i; uint16_t crc = 0x0; while (len--) { i = (crc ^ *p++) & 0xFF; crc = (crc_table[i] ^ (crc << 8)) & 0xFF; } return crc & 0xFF; } void TerarangerOne::serialDataCallback(uint8_t single_character) { static uint8_t input_buffer[BUFFER_SIZE]; static int buffer_ctr = 0; static int seq_ctr = 0; sensor_msgs::Range range_msg; range_msg.field_of_view = 0.0593; range_msg.max_range = 14.0; range_msg.min_range = 0.2; range_msg.radiation_type = sensor_msgs::Range::INFRARED; // Debug Code to show the buffer // if (single_character == 'T') // { // ROS_INFO("TTTT single_character = %3d, buffer_ctr = %d |%3d|%3d|%3d|%3d|", single_character, buffer_ctr, // input_buffer[0], input_buffer[1], input_buffer[2], input_buffer[3]); // } // else // { // ROS_INFO("#### single_character = %3d, buffer_ctr = %d |%3d|%3d|%3d|%3d|", single_character, buffer_ctr, // input_buffer[0], input_buffer[1], input_buffer[2], input_buffer[3]); // } if (single_character != 'T' && buffer_ctr < 4) { // not begin of serial feed so add char to buffer input_buffer[buffer_ctr++] = single_character; return; } else if (single_character == 'T') { if (buffer_ctr == 4) { // end of feed, calculate int16_t crc = crc8(input_buffer, 3); if (crc == input_buffer[3]) { int16_t range = input_buffer[1] << 8; range |= input_buffer[2]; if (range < 14000 && range > 200) { range_msg.header.stamp = ros::Time::now(); range_msg.header.seq = seq_ctr++; range_msg.range = range * 0.001; // convert to m range_publisher_.publish(range_msg); } ROS_DEBUG("[%s] all good %.3f m", ros::this_node::getName().c_str(), range_msg.range); } else { ROS_DEBUG("[%s] crc missmatch", ros::this_node::getName().c_str()); } } else { ROS_DEBUG("[%s] reveived T but did not expect it, reset buffer without evaluating data", ros::this_node::getName().c_str()); } } else { ROS_DEBUG("[%s] buffer_overflowed without receiving T, reset input_buffer", ros::this_node::getName().c_str()); } // reset buffer_ctr = 0; // clear struct bzero(&input_buffer, BUFFER_SIZE); // store T input_buffer[buffer_ctr++] = 'T'; } void TerarangerOne::setMode(char c) { serial_port_->sendChar(c); } void TerarangerOne::dynParamCallback(const terarangerone::TerarangerOneConfig &config, uint32_t level) { if (config.Speed == terarangerone::TerarangerOne_Fast) { setMode(FAST_MODE); } if (config.Speed == terarangerone::TerarangerOne_Precise) { setMode(PRECISE_MODE); } if (config.Environment == terarangerone::TerarangerOne_Indoor) { setMode(INDOOR_MODE); } if (config.Environment == terarangerone::TerarangerOne_Outdoor) { setMode(OUTDOOR_MODE); } } } // namespace terarangerone int main(int argc, char **argv) { ros::init(argc, argv, "terarangerone"); terarangerone::TerarangerOne tera_bee; ros::spin(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chain.h> #include <chainparams.h> #include <pow.h> #include <primitives/block.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <util/overflow.h> #include <cstdint> #include <optional> #include <string> #include <vector> void initialize_pow() { SelectParams(CBaseChainParams::MAIN); } FUZZ_TARGET_INIT(pow, initialize_pow) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const Consensus::Params& consensus_params = Params().GetConsensus(); std::vector<CBlockIndex> blocks; const uint32_t fixed_time = fuzzed_data_provider.ConsumeIntegral<uint32_t>(); const uint32_t fixed_bits = fuzzed_data_provider.ConsumeIntegral<uint32_t>(); LIMITED_WHILE(fuzzed_data_provider.remaining_bytes() > 0, 10000) { const std::optional<CBlockHeader> block_header = ConsumeDeserializable<CBlockHeader>(fuzzed_data_provider); if (!block_header) { continue; } CBlockIndex current_block{*block_header}; { CBlockIndex* previous_block = blocks.empty() ? nullptr : &PickValue(fuzzed_data_provider, blocks); const int current_height = (previous_block != nullptr && previous_block->nHeight != std::numeric_limits<int>::max()) ? previous_block->nHeight + 1 : 0; if (fuzzed_data_provider.ConsumeBool()) { current_block.pprev = previous_block; } if (fuzzed_data_provider.ConsumeBool()) { current_block.nHeight = current_height; } if (fuzzed_data_provider.ConsumeBool()) { const uint32_t seconds = current_height * consensus_params.nPowTargetSpacing; if (!AdditionOverflow(fixed_time, seconds)) { current_block.nTime = fixed_time + seconds; } } if (fuzzed_data_provider.ConsumeBool()) { current_block.nBits = fixed_bits; } if (fuzzed_data_provider.ConsumeBool()) { current_block.nChainWork = previous_block != nullptr ? previous_block->nChainWork + GetBlockProof(*previous_block) : arith_uint256{0}; } else { current_block.nChainWork = ConsumeArithUInt256(fuzzed_data_provider); } blocks.push_back(current_block); } { (void)GetBlockProof(current_block); (void)CalculateNextWorkRequired(&current_block, fuzzed_data_provider.ConsumeIntegralInRange<int64_t>(0, std::numeric_limits<int64_t>::max()), consensus_params); if (current_block.nHeight != std::numeric_limits<int>::max() && current_block.nHeight - (consensus_params.DifficultyAdjustmentInterval() - 1) >= 0) { (void)GetNextWorkRequired(&current_block, &(*block_header), consensus_params); } } { const CBlockIndex* to = &PickValue(fuzzed_data_provider, blocks); const CBlockIndex* from = &PickValue(fuzzed_data_provider, blocks); const CBlockIndex* tip = &PickValue(fuzzed_data_provider, blocks); try { (void)GetBlockProofEquivalentTime(*to, *from, *tip, consensus_params); } catch (const uint_error&) { } } { const std::optional<uint256> hash = ConsumeDeserializable<uint256>(fuzzed_data_provider); if (hash) { (void)CheckProofOfWork(*hash, fuzzed_data_provider.ConsumeIntegral<unsigned int>(), consensus_params); } } } } FUZZ_TARGET_INIT(pow_transition, initialize_pow) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const Consensus::Params& consensus_params{Params().GetConsensus()}; std::vector<std::unique_ptr<CBlockIndex>> blocks; const uint32_t old_time{fuzzed_data_provider.ConsumeIntegral<uint32_t>()}; const uint32_t new_time{fuzzed_data_provider.ConsumeIntegral<uint32_t>()}; const int32_t version{fuzzed_data_provider.ConsumeIntegral<int32_t>()}; uint32_t nbits{fuzzed_data_provider.ConsumeIntegral<uint32_t>()}; const arith_uint256 pow_limit = UintToArith256(consensus_params.powLimit); arith_uint256 old_target; old_target.SetCompact(nbits); if (old_target > pow_limit) { nbits = pow_limit.GetCompact(); } // Create one difficulty adjustment period worth of headers for (int height = 0; height < consensus_params.DifficultyAdjustmentInterval(); ++height) { CBlockHeader header; header.nVersion = version; header.nTime = old_time; header.nBits = nbits; if (height == consensus_params.DifficultyAdjustmentInterval() - 1) { header.nTime = new_time; } auto current_block{std::make_unique<CBlockIndex>(header)}; current_block->pprev = blocks.empty() ? nullptr : blocks.back().get(); current_block->nHeight = height; blocks.emplace_back(std::move(current_block)).get(); } auto last_block{blocks.back().get()}; unsigned int new_nbits{GetNextWorkRequired(last_block, nullptr, consensus_params)}; Assert(PermittedDifficultyTransition(consensus_params, last_block->nHeight + 1, last_block->nBits, new_nbits)); } <commit_msg>fuzz: Remove no-op call to get()<commit_after>// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chain.h> #include <chainparams.h> #include <pow.h> #include <primitives/block.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <util/overflow.h> #include <cstdint> #include <optional> #include <string> #include <vector> void initialize_pow() { SelectParams(CBaseChainParams::MAIN); } FUZZ_TARGET_INIT(pow, initialize_pow) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const Consensus::Params& consensus_params = Params().GetConsensus(); std::vector<CBlockIndex> blocks; const uint32_t fixed_time = fuzzed_data_provider.ConsumeIntegral<uint32_t>(); const uint32_t fixed_bits = fuzzed_data_provider.ConsumeIntegral<uint32_t>(); LIMITED_WHILE(fuzzed_data_provider.remaining_bytes() > 0, 10000) { const std::optional<CBlockHeader> block_header = ConsumeDeserializable<CBlockHeader>(fuzzed_data_provider); if (!block_header) { continue; } CBlockIndex current_block{*block_header}; { CBlockIndex* previous_block = blocks.empty() ? nullptr : &PickValue(fuzzed_data_provider, blocks); const int current_height = (previous_block != nullptr && previous_block->nHeight != std::numeric_limits<int>::max()) ? previous_block->nHeight + 1 : 0; if (fuzzed_data_provider.ConsumeBool()) { current_block.pprev = previous_block; } if (fuzzed_data_provider.ConsumeBool()) { current_block.nHeight = current_height; } if (fuzzed_data_provider.ConsumeBool()) { const uint32_t seconds = current_height * consensus_params.nPowTargetSpacing; if (!AdditionOverflow(fixed_time, seconds)) { current_block.nTime = fixed_time + seconds; } } if (fuzzed_data_provider.ConsumeBool()) { current_block.nBits = fixed_bits; } if (fuzzed_data_provider.ConsumeBool()) { current_block.nChainWork = previous_block != nullptr ? previous_block->nChainWork + GetBlockProof(*previous_block) : arith_uint256{0}; } else { current_block.nChainWork = ConsumeArithUInt256(fuzzed_data_provider); } blocks.push_back(current_block); } { (void)GetBlockProof(current_block); (void)CalculateNextWorkRequired(&current_block, fuzzed_data_provider.ConsumeIntegralInRange<int64_t>(0, std::numeric_limits<int64_t>::max()), consensus_params); if (current_block.nHeight != std::numeric_limits<int>::max() && current_block.nHeight - (consensus_params.DifficultyAdjustmentInterval() - 1) >= 0) { (void)GetNextWorkRequired(&current_block, &(*block_header), consensus_params); } } { const CBlockIndex* to = &PickValue(fuzzed_data_provider, blocks); const CBlockIndex* from = &PickValue(fuzzed_data_provider, blocks); const CBlockIndex* tip = &PickValue(fuzzed_data_provider, blocks); try { (void)GetBlockProofEquivalentTime(*to, *from, *tip, consensus_params); } catch (const uint_error&) { } } { const std::optional<uint256> hash = ConsumeDeserializable<uint256>(fuzzed_data_provider); if (hash) { (void)CheckProofOfWork(*hash, fuzzed_data_provider.ConsumeIntegral<unsigned int>(), consensus_params); } } } } FUZZ_TARGET_INIT(pow_transition, initialize_pow) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const Consensus::Params& consensus_params{Params().GetConsensus()}; std::vector<std::unique_ptr<CBlockIndex>> blocks; const uint32_t old_time{fuzzed_data_provider.ConsumeIntegral<uint32_t>()}; const uint32_t new_time{fuzzed_data_provider.ConsumeIntegral<uint32_t>()}; const int32_t version{fuzzed_data_provider.ConsumeIntegral<int32_t>()}; uint32_t nbits{fuzzed_data_provider.ConsumeIntegral<uint32_t>()}; const arith_uint256 pow_limit = UintToArith256(consensus_params.powLimit); arith_uint256 old_target; old_target.SetCompact(nbits); if (old_target > pow_limit) { nbits = pow_limit.GetCompact(); } // Create one difficulty adjustment period worth of headers for (int height = 0; height < consensus_params.DifficultyAdjustmentInterval(); ++height) { CBlockHeader header; header.nVersion = version; header.nTime = old_time; header.nBits = nbits; if (height == consensus_params.DifficultyAdjustmentInterval() - 1) { header.nTime = new_time; } auto current_block{std::make_unique<CBlockIndex>(header)}; current_block->pprev = blocks.empty() ? nullptr : blocks.back().get(); current_block->nHeight = height; blocks.emplace_back(std::move(current_block)); } auto last_block{blocks.back().get()}; unsigned int new_nbits{GetNextWorkRequired(last_block, nullptr, consensus_params)}; Assert(PermittedDifficultyTransition(consensus_params, last_block->nHeight + 1, last_block->nBits, new_nbits)); } <|endoftext|>
<commit_before>#include "rtl_platform.h" #include <dlfcn.h> #include <map> #ifdef __APPLE__ #define SO_SUFFIX ".dylib" #else #define SO_SUFFIX ".so" #endif static std::map<std::string, void *> g_Libraries; static void *get_library_handle(const std::string &library) { auto i = g_Libraries.find(library); if (i == g_Libraries.end()) { std::string libname = library + SO_SUFFIX; void *lib = dlopen(libname.c_str(), RTLD_LAZY); if (lib == nullptr) { return NULL; } i = g_Libraries.insert(std::make_pair(library, lib)).first; } return i->second; } void_function_t rtl_external_function(const std::string &library, const std::string &function, std::string &exception) { void *lib = get_library_handle(library); if (lib == NULL) { exception = "LibraryNotFound"; return nullptr; } void (*fp)() = reinterpret_cast<void (*)()>(dlsym(lib, function.c_str())); if (fp == NULL) { exception = "FunctionNotFound"; return nullptr; } return fp; } <commit_msg>show more dynamic loading info on error<commit_after>#include "rtl_platform.h" #include <dlfcn.h> #include <map> #ifdef __APPLE__ #define SO_SUFFIX ".dylib" #else #define SO_SUFFIX ".so" #endif static std::map<std::string, void *> g_Libraries; static void *get_library_handle(const std::string &library) { auto i = g_Libraries.find(library); if (i == g_Libraries.end()) { std::string libname = library + SO_SUFFIX; void *lib = dlopen(libname.c_str(), RTLD_LAZY); if (lib == nullptr) { // TODO: fill in exception info fprintf(stderr, "%s\n", dlerror()); return NULL; } i = g_Libraries.insert(std::make_pair(library, lib)).first; } return i->second; } void_function_t rtl_external_function(const std::string &library, const std::string &function, std::string &exception) { void *lib = get_library_handle(library); if (lib == NULL) { exception = "LibraryNotFound"; return nullptr; } void (*fp)() = reinterpret_cast<void (*)()>(dlsym(lib, function.c_str())); if (fp == NULL) { exception = "FunctionNotFound"; return nullptr; } return fp; } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "map/Tile.h" #include "actor/Actor.h" TEST(TileTest, WallTileIsOpaque) { Tile t1 = WallTile; EXPECT_FALSE(t1.isTransparent()); } TEST(TileTest, WallTileIsInpassable) { Tile t1 = WallTile; EXPECT_FALSE(t1.isPassable()); } TEST(TileTest, FloorTileIsTransparent) { Tile t1 = FloorTile; EXPECT_TRUE(t1.isTransparent()); } TEST(TileTest, FloorTileIsPassable) { Tile t1 = FloorTile; EXPECT_TRUE(t1.isPassable()); } TEST(TileTest, ClosedDoorTileIsOpaque) { Tile t1 = ClosedDoorTile; EXPECT_FALSE(t1.isTransparent()); } TEST(TileTest, ClosedDoorTileIsInpassable) { Tile t1 = ClosedDoorTile; EXPECT_FALSE(t1.isPassable()); } TEST(TileTest, OpenDoorTileIsTransparent) { Tile t1 = OpenDoorTile; EXPECT_TRUE(t1.isTransparent()); } TEST(TileTest, OpenDoorTileIsPassable) { Tile t1 = OpenDoorTile; EXPECT_TRUE(t1.isPassable()); } TEST(TileTest, FloorEqualsFloor) { Tile floor = FloorTile; Tile wall = FloorTile; EXPECT_TRUE(floor == wall); } TEST(TileTest, FloorDoesNotEqualWall) { Tile floor = FloorTile; Tile wall = WallTile; EXPECT_TRUE(floor != wall); } TEST(TileTest, TileDisplaysActor) { Actor actor('@', "TestActor", 0x00); Tile floor = FloorTile; EXPECT_EQ('.', floor.getDisplay()); floor.addActor(&actor); EXPECT_EQ('@', floor.getDisplay()); floor.removeActor(); EXPECT_EQ('.', floor.getDisplay()); } TEST(TileTest, TileIsOccupied) { Actor actor('@', "TestActor", 0x00); Tile floor = FloorTile; EXPECT_FALSE(floor.isOccupied()); floor.addActor(&actor); EXPECT_TRUE(floor.isOccupied()); floor.removeActor(); EXPECT_FALSE(floor.isOccupied()); } <commit_msg>Remove Actor-related Tile tests<commit_after>#include "gtest/gtest.h" #include "map/Tile.h" TEST(TileTest, WallTileIsOpaque) { Tile t1 = WallTile; EXPECT_FALSE(t1.isTransparent()); } TEST(TileTest, WallTileIsInpassable) { Tile t1 = WallTile; EXPECT_FALSE(t1.isPassable()); } TEST(TileTest, FloorTileIsTransparent) { Tile t1 = FloorTile; EXPECT_TRUE(t1.isTransparent()); } TEST(TileTest, FloorTileIsPassable) { Tile t1 = FloorTile; EXPECT_TRUE(t1.isPassable()); } TEST(TileTest, ClosedDoorTileIsOpaque) { Tile t1 = ClosedDoorTile; EXPECT_FALSE(t1.isTransparent()); } TEST(TileTest, ClosedDoorTileIsInpassable) { Tile t1 = ClosedDoorTile; EXPECT_FALSE(t1.isPassable()); } TEST(TileTest, OpenDoorTileIsTransparent) { Tile t1 = OpenDoorTile; EXPECT_TRUE(t1.isTransparent()); } TEST(TileTest, OpenDoorTileIsPassable) { Tile t1 = OpenDoorTile; EXPECT_TRUE(t1.isPassable()); } TEST(TileTest, FloorEqualsFloor) { Tile floor = FloorTile; Tile wall = FloorTile; EXPECT_TRUE(floor == wall); } TEST(TileTest, FloorDoesNotEqualWall) { Tile floor = FloorTile; Tile wall = WallTile; EXPECT_TRUE(floor != wall); } <|endoftext|>
<commit_before>/* This file is part of VoltDB. * Copyright (C) 2008-2015 VoltDB Inc. * * 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 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 <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/ui/text/TestRunner.h> int main (int argc, char **argv) { CppUnit::TextUi::TestRunner runner; CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry(); runner.addTest( registry.makeTest() ); return runner.run( "" ); } <commit_msg>Make cpptest main return 0 for SUCCESS.<commit_after>/* This file is part of VoltDB. * Copyright (C) 2008-2015 VoltDB Inc. * * 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 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 <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/ui/text/TestRunner.h> int main (int argc, char **argv) { CppUnit::TextUi::TestRunner runner; CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry(); runner.addTest( registry.makeTest() ); return !runner.run( "" ); } <|endoftext|>
<commit_before>#include "test_compiler.hpp" #include <fcntl.h> #include <poll.h> #include <signal.h> #include <sys/wait.h> #include <unistd.h> #include <cstdlib> #include <regex> #include <sstream> #include <mettle/driver/scoped_pipe.hpp> #include <mettle/driver/scoped_signal.hpp> #include <mettle/driver/test_monitor.hpp> #include <mettle/output.hpp> #include "paths.hpp" namespace caliber { namespace { pid_t test_pgid = 0; struct sigaction old_sigint, old_sigquit; void sig_handler(int signum) { assert(test_pgid != 0); kill(-test_pgid, signum); // Restore the previous signal action and re-raise the signal. struct sigaction *old_act = signum == SIGINT ? &old_sigint : &old_sigquit; sigaction(signum, old_act, nullptr); raise(signum); } void sig_chld(int) {} inline std::string err_string(int errnum) { char buf[256]; #ifdef _GNU_SOURCE return strerror_r(errnum, buf, sizeof(buf)); #else if(strerror_r(errnum, buf, sizeof(buf)) < 0) return ""; return buf; #endif } inline mettle::test_result parent_failed() { return { false, err_string(errno) }; } [[noreturn]] inline void child_failed() { _exit(128); } std::unique_ptr<char *[]> make_argv(const std::vector<std::string> &argv) { auto real_argv = std::make_unique<char *[]>(argv.size() + 1); for(size_t i = 0; i != argv.size(); i++) real_argv[i] = const_cast<char*>(argv[i].c_str()); return real_argv; } } mettle::test_result test_compiler::operator ()( const std::string &file, const compiler_options &args, const raw_options &raw_args, bool expect_fail, mettle::log::test_output &output ) const { mettle::scoped_pipe stdout_pipe, stderr_pipe; if(stdout_pipe.open() < 0 || stderr_pipe.open() < 0) return parent_failed(); std::string dir = parent_path(file); std::vector<std::string> final_args = {compiler_.path.c_str()}; for(auto &&tok : translate_args(file, args, dir)) final_args.push_back(std::move(tok)); for(const auto &arg : raw_args) { if(tool_match(compiler_, arg.tool)) final_args.push_back(arg.value); } fflush(nullptr); mettle::scoped_sigprocmask mask; if(mask.push(SIG_BLOCK, SIGCHLD) < 0 || mask.push(SIG_BLOCK, {SIGINT, SIGQUIT}) < 0) return parent_failed(); pid_t pid; if((pid = fork()) < 0) return parent_failed(); if(pid == 0) { if(mask.clear() < 0) child_failed(); // Make a new process group so we can kill the test and all its children // as a group. setpgid(0, 0); if(timeout_) mettle::fork_monitor(*timeout_); if(stdout_pipe.close_read() < 0 || stderr_pipe.close_read() < 0) child_failed(); if(stdout_pipe.move_write(STDOUT_FILENO) < 0 || stderr_pipe.move_write(STDERR_FILENO) < 0) child_failed(); execvp(compiler_.path.c_str(), make_argv(final_args).get()); child_failed(); } else { mettle::scoped_signal sigint, sigquit, sigchld; test_pgid = pid; if(sigaction(SIGINT, nullptr, &old_sigint) < 0 || sigaction(SIGQUIT, nullptr, &old_sigquit) < 0) return parent_failed(); if(sigint.open(SIGINT, sig_handler) < 0 || sigquit.open(SIGQUIT, sig_handler) < 0 || sigchld.open(SIGCHLD, sig_chld) < 0) return parent_failed(); if(mask.pop() < 0) return parent_failed(); if(stdout_pipe.close_write() < 0 || stderr_pipe.close_write() < 0) return parent_failed(); std::vector<mettle::readfd> dests = { {stdout_pipe.read_fd, &output.stdout}, {stderr_pipe.read_fd, &output.stderr} }; // Read from the piped stdout, stderr, and log. If we're interrupted // (probably by SIGCHLD), do one last non-blocking read to get any data we // might have missed. sigset_t empty; sigemptyset(&empty); if(mettle::read_into(dests, nullptr, &empty) < 0) { if(errno != EINTR) return parent_failed(); timespec timeout = {0, 0}; if(mettle::read_into(dests, &timeout, nullptr) < 0) return parent_failed(); } int status; if(waitpid(pid, &status, 0) < 0) return parent_failed(); // Make sure everything in the test's process group is dead. Don't worry // about reaping. kill(-pid, SIGKILL); test_pgid = 0; if(WIFEXITED(status)) { int exit_code = WEXITSTATUS(status); if(exit_code == mettle::err_timeout) { std::ostringstream ss; ss << "Timed out after " << timeout_->count() << " ms"; return { false, ss.str() }; } else if(bool(exit_code) == expect_fail) { return { true, "" }; } else if(exit_code) { return { false, "Compilation failed" }; } else { return { false, "Compilation successful" }; } } else if(WIFSIGNALED(status)) { return { false, strsignal(WTERMSIG(status)) }; } else { // WIFSTOPPED kill(pid, SIGKILL); return { false, strsignal(WSTOPSIG(status)) }; } } } } // namespace caliber <commit_msg>Rename stdout/stderr to match mettle's changes<commit_after>#include "test_compiler.hpp" #include <fcntl.h> #include <poll.h> #include <signal.h> #include <sys/wait.h> #include <unistd.h> #include <cstdlib> #include <regex> #include <sstream> #include <mettle/driver/scoped_pipe.hpp> #include <mettle/driver/scoped_signal.hpp> #include <mettle/driver/test_monitor.hpp> #include <mettle/output.hpp> #include "paths.hpp" namespace caliber { namespace { pid_t test_pgid = 0; struct sigaction old_sigint, old_sigquit; void sig_handler(int signum) { assert(test_pgid != 0); kill(-test_pgid, signum); // Restore the previous signal action and re-raise the signal. struct sigaction *old_act = signum == SIGINT ? &old_sigint : &old_sigquit; sigaction(signum, old_act, nullptr); raise(signum); } void sig_chld(int) {} inline std::string err_string(int errnum) { char buf[256]; #ifdef _GNU_SOURCE return strerror_r(errnum, buf, sizeof(buf)); #else if(strerror_r(errnum, buf, sizeof(buf)) < 0) return ""; return buf; #endif } inline mettle::test_result parent_failed() { return { false, err_string(errno) }; } [[noreturn]] inline void child_failed() { _exit(128); } std::unique_ptr<char *[]> make_argv(const std::vector<std::string> &argv) { auto real_argv = std::make_unique<char *[]>(argv.size() + 1); for(size_t i = 0; i != argv.size(); i++) real_argv[i] = const_cast<char*>(argv[i].c_str()); return real_argv; } } mettle::test_result test_compiler::operator ()( const std::string &file, const compiler_options &args, const raw_options &raw_args, bool expect_fail, mettle::log::test_output &output ) const { mettle::scoped_pipe stdout_pipe, stderr_pipe; if(stdout_pipe.open() < 0 || stderr_pipe.open() < 0) return parent_failed(); std::string dir = parent_path(file); std::vector<std::string> final_args = {compiler_.path.c_str()}; for(auto &&tok : translate_args(file, args, dir)) final_args.push_back(std::move(tok)); for(const auto &arg : raw_args) { if(tool_match(compiler_, arg.tool)) final_args.push_back(arg.value); } fflush(nullptr); mettle::scoped_sigprocmask mask; if(mask.push(SIG_BLOCK, SIGCHLD) < 0 || mask.push(SIG_BLOCK, {SIGINT, SIGQUIT}) < 0) return parent_failed(); pid_t pid; if((pid = fork()) < 0) return parent_failed(); if(pid == 0) { if(mask.clear() < 0) child_failed(); // Make a new process group so we can kill the test and all its children // as a group. setpgid(0, 0); if(timeout_) mettle::fork_monitor(*timeout_); if(stdout_pipe.close_read() < 0 || stderr_pipe.close_read() < 0) child_failed(); if(stdout_pipe.move_write(STDOUT_FILENO) < 0 || stderr_pipe.move_write(STDERR_FILENO) < 0) child_failed(); execvp(compiler_.path.c_str(), make_argv(final_args).get()); child_failed(); } else { mettle::scoped_signal sigint, sigquit, sigchld; test_pgid = pid; if(sigaction(SIGINT, nullptr, &old_sigint) < 0 || sigaction(SIGQUIT, nullptr, &old_sigquit) < 0) return parent_failed(); if(sigint.open(SIGINT, sig_handler) < 0 || sigquit.open(SIGQUIT, sig_handler) < 0 || sigchld.open(SIGCHLD, sig_chld) < 0) return parent_failed(); if(mask.pop() < 0) return parent_failed(); if(stdout_pipe.close_write() < 0 || stderr_pipe.close_write() < 0) return parent_failed(); std::vector<mettle::readfd> dests = { {stdout_pipe.read_fd, &output.stdout_log}, {stderr_pipe.read_fd, &output.stderr_log} }; // Read from the piped stdout, stderr, and log. If we're interrupted // (probably by SIGCHLD), do one last non-blocking read to get any data we // might have missed. sigset_t empty; sigemptyset(&empty); if(mettle::read_into(dests, nullptr, &empty) < 0) { if(errno != EINTR) return parent_failed(); timespec timeout = {0, 0}; if(mettle::read_into(dests, &timeout, nullptr) < 0) return parent_failed(); } int status; if(waitpid(pid, &status, 0) < 0) return parent_failed(); // Make sure everything in the test's process group is dead. Don't worry // about reaping. kill(-pid, SIGKILL); test_pgid = 0; if(WIFEXITED(status)) { int exit_code = WEXITSTATUS(status); if(exit_code == mettle::err_timeout) { std::ostringstream ss; ss << "Timed out after " << timeout_->count() << " ms"; return { false, ss.str() }; } else if(bool(exit_code) == expect_fail) { return { true, "" }; } else if(exit_code) { return { false, "Compilation failed" }; } else { return { false, "Compilation successful" }; } } else if(WIFSIGNALED(status)) { return { false, strsignal(WTERMSIG(status)) }; } else { // WIFSTOPPED kill(pid, SIGKILL); return { false, strsignal(WSTOPSIG(status)) }; } } } } // namespace caliber <|endoftext|>
<commit_before>#include "crt.h" #include "scanner.h" #include "token.h" #include "exceptions.h" #include "exp.h" #include "scanscalar.h" #include <sstream> namespace YAML { /////////////////////////////////////////////////////////////////////// // Specialization for scanning specific tokens // Directive // . Note: no semantic checking is done here (that's for the parser to do) void Scanner::ScanDirective() { std::string name; std::vector <std::string> params; // pop indents and simple keys PopAllIndents(); PopAllSimpleKeys(); m_simpleKeyAllowed = false; // store pos and eat indicator Mark mark = INPUT.mark(); INPUT.eat(1); // read name while(INPUT && !Exp::BlankOrBreak.Matches(INPUT)) name += INPUT.get(); // read parameters while(1) { // first get rid of whitespace while(Exp::Blank.Matches(INPUT)) INPUT.eat(1); // break on newline or comment if(!INPUT || Exp::Break.Matches(INPUT) || Exp::Comment.Matches(INPUT)) break; // now read parameter std::string param; while(INPUT && !Exp::BlankOrBreak.Matches(INPUT)) param += INPUT.get(); params.push_back(param); } Token token(Token::DIRECTIVE, mark); token.value = name; token.params = params; m_tokens.push(token); } // DocStart void Scanner::ScanDocStart() { PopAllIndents(); PopAllSimpleKeys(); m_simpleKeyAllowed = false; // eat Mark mark = INPUT.mark(); INPUT.eat(3); m_tokens.push(Token(Token::DOC_START, mark)); } // DocEnd void Scanner::ScanDocEnd() { PopAllIndents(); PopAllSimpleKeys(); m_simpleKeyAllowed = false; // eat Mark mark = INPUT.mark(); INPUT.eat(3); m_tokens.push(Token(Token::DOC_END, mark)); } // FlowStart void Scanner::ScanFlowStart() { // flows can be simple keys InsertPotentialSimpleKey(); m_simpleKeyAllowed = true; // eat Mark mark = INPUT.mark(); char ch = INPUT.get(); FLOW_MARKER flowType = (ch == Keys::FlowSeqStart ? FLOW_SEQ : FLOW_MAP); m_flows.push(flowType); Token::TYPE type = (flowType == FLOW_SEQ ? Token::FLOW_SEQ_START : Token::FLOW_MAP_START); m_tokens.push(Token(type, mark)); } // FlowEnd void Scanner::ScanFlowEnd() { if(InBlockContext()) throw ParserException(INPUT.mark(), ErrorMsg::FLOW_END); // we might have a solo entry in the flow context if(VerifySimpleKey()) m_tokens.push(Token(Token::VALUE, INPUT.mark())); m_simpleKeyAllowed = false; // eat Mark mark = INPUT.mark(); char ch = INPUT.get(); // check that it matches the start FLOW_MARKER flowType = (ch == Keys::FlowSeqEnd ? FLOW_SEQ : FLOW_MAP); if(m_flows.top() != flowType) throw ParserException(mark, ErrorMsg::FLOW_END); m_flows.pop(); Token::TYPE type = (flowType ? Token::FLOW_SEQ_END : Token::FLOW_MAP_END); m_tokens.push(Token(type, mark)); } // FlowEntry void Scanner::ScanFlowEntry() { // we might have a solo entry in the flow context if(VerifySimpleKey()) m_tokens.push(Token(Token::VALUE, INPUT.mark())); m_simpleKeyAllowed = true; // eat Mark mark = INPUT.mark(); INPUT.eat(1); m_tokens.push(Token(Token::FLOW_ENTRY, mark)); } // BlockEntry void Scanner::ScanBlockEntry() { // we better be in the block context! if(InFlowContext()) throw ParserException(INPUT.mark(), ErrorMsg::BLOCK_ENTRY); // can we put it here? if(!m_simpleKeyAllowed) throw ParserException(INPUT.mark(), ErrorMsg::BLOCK_ENTRY); PushIndentTo(INPUT.column(), IndentMarker::SEQ); m_simpleKeyAllowed = true; // eat Mark mark = INPUT.mark(); INPUT.eat(1); m_tokens.push(Token(Token::BLOCK_ENTRY, mark)); } // Key void Scanner::ScanKey() { // handle keys diffently in the block context (and manage indents) if(InBlockContext()) { if(!m_simpleKeyAllowed) throw ParserException(INPUT.mark(), ErrorMsg::MAP_KEY); PushIndentTo(INPUT.column(), IndentMarker::MAP); } // can only put a simple key here if we're in block context m_simpleKeyAllowed = InBlockContext(); // eat Mark mark = INPUT.mark(); INPUT.eat(1); m_tokens.push(Token(Token::KEY, mark)); } // Value void Scanner::ScanValue() { // and check that simple key bool isSimpleKey = VerifySimpleKey(); if(isSimpleKey) { // can't follow a simple key with another simple key (dunno why, though - it seems fine) m_simpleKeyAllowed = false; } else { // handle values diffently in the block context (and manage indents) if(InBlockContext()) { if(!m_simpleKeyAllowed) throw ParserException(INPUT.mark(), ErrorMsg::MAP_VALUE); PushIndentTo(INPUT.column(), IndentMarker::MAP); } // can only put a simple key here if we're in block context m_simpleKeyAllowed = InBlockContext(); } // eat Mark mark = INPUT.mark(); INPUT.eat(1); m_tokens.push(Token(Token::VALUE, mark)); } // AnchorOrAlias void Scanner::ScanAnchorOrAlias() { bool alias; std::string name; // insert a potential simple key InsertPotentialSimpleKey(); m_simpleKeyAllowed = false; // eat the indicator Mark mark = INPUT.mark(); char indicator = INPUT.get(); alias = (indicator == Keys::Alias); // now eat the content while(Exp::AlphaNumeric.Matches(INPUT)) name += INPUT.get(); // we need to have read SOMETHING! if(name.empty()) throw ParserException(INPUT.mark(), alias ? ErrorMsg::ALIAS_NOT_FOUND : ErrorMsg::ANCHOR_NOT_FOUND); // and needs to end correctly if(INPUT && !Exp::AnchorEnd.Matches(INPUT)) throw ParserException(INPUT.mark(), alias ? ErrorMsg::CHAR_IN_ALIAS : ErrorMsg::CHAR_IN_ANCHOR); // and we're done Token token(alias ? Token::ALIAS : Token::ANCHOR, mark); token.value = name; m_tokens.push(token); } // Tag void Scanner::ScanTag() { std::string handle, suffix; // insert a potential simple key InsertPotentialSimpleKey(); m_simpleKeyAllowed = false; // eat the indicator Mark mark = INPUT.mark(); handle += INPUT.get(); // read the handle while(INPUT && INPUT.peek() != Keys::Tag && !Exp::BlankOrBreak.Matches(INPUT)) handle += INPUT.get(); // is there a suffix? if(INPUT.peek() == Keys::Tag) { // eat the indicator handle += INPUT.get(); // then read it while(INPUT && !Exp::BlankOrBreak.Matches(INPUT)) suffix += INPUT.get(); } else { // this is a bit weird: we keep just the '!' as the handle and move the rest to the suffix suffix = handle.substr(1); handle = "!"; } Token token(Token::TAG, mark); token.value = handle; token.params.push_back(suffix); m_tokens.push(token); } // PlainScalar void Scanner::ScanPlainScalar() { std::string scalar; // set up the scanning parameters ScanScalarParams params; params.end = (InFlowContext() ? Exp::EndScalarInFlow : Exp::EndScalar) || (Exp::BlankOrBreak + Exp::Comment); params.eatEnd = false; params.indent = (InFlowContext() ? 0 : GetTopIndent() + 1); params.fold = FOLD_BLOCK; params.eatLeadingWhitespace = true; params.trimTrailingSpaces = true; params.chomp = STRIP; params.onDocIndicator = BREAK; params.onTabInIndentation = THROW; // insert a potential simple key InsertPotentialSimpleKey(); Mark mark = INPUT.mark(); scalar = ScanScalar(INPUT, params); // can have a simple key only if we ended the scalar by starting a new line m_simpleKeyAllowed = params.leadingSpaces; // finally, check and see if we ended on an illegal character //if(Exp::IllegalCharInScalar.Matches(INPUT)) // throw ParserException(INPUT.mark(), ErrorMsg::CHAR_IN_SCALAR); Token token(Token::SCALAR, mark); token.value = scalar; m_tokens.push(token); } // QuotedScalar void Scanner::ScanQuotedScalar() { std::string scalar; // peek at single or double quote (don't eat because we need to preserve (for the time being) the input position) char quote = INPUT.peek(); bool single = (quote == '\''); // setup the scanning parameters ScanScalarParams params; params.end = (single ? RegEx(quote) && !Exp::EscSingleQuote : RegEx(quote)); params.eatEnd = true; params.escape = (single ? '\'' : '\\'); params.indent = 0; params.fold = FOLD_FLOW; params.eatLeadingWhitespace = true; params.trimTrailingSpaces = false; params.chomp = CLIP; params.onDocIndicator = THROW; // insert a potential simple key InsertPotentialSimpleKey(); Mark mark = INPUT.mark(); // now eat that opening quote INPUT.get(); // and scan scalar = ScanScalar(INPUT, params); m_simpleKeyAllowed = false; Token token(Token::SCALAR, mark); token.value = scalar; m_tokens.push(token); } // BlockScalarToken // . These need a little extra processing beforehand. // . We need to scan the line where the indicator is (this doesn't count as part of the scalar), // and then we need to figure out what level of indentation we'll be using. void Scanner::ScanBlockScalar() { std::string scalar; ScanScalarParams params; params.indent = 1; params.detectIndent = true; // eat block indicator ('|' or '>') Mark mark = INPUT.mark(); char indicator = INPUT.get(); params.fold = (indicator == Keys::FoldedScalar ? FOLD_BLOCK : DONT_FOLD); // eat chomping/indentation indicators params.chomp = CLIP; int n = Exp::Chomp.Match(INPUT); for(int i=0;i<n;i++) { char ch = INPUT.get(); if(ch == '+') params.chomp = KEEP; else if(ch == '-') params.chomp = STRIP; else if(Exp::Digit.Matches(ch)) { if(ch == '0') throw ParserException(INPUT.mark(), ErrorMsg::ZERO_INDENT_IN_BLOCK); params.indent = ch - '0'; params.detectIndent = false; } } // now eat whitespace while(Exp::Blank.Matches(INPUT)) INPUT.eat(1); // and comments to the end of the line if(Exp::Comment.Matches(INPUT)) while(INPUT && !Exp::Break.Matches(INPUT)) INPUT.eat(1); // if it's not a line break, then we ran into a bad character inline if(INPUT && !Exp::Break.Matches(INPUT)) throw ParserException(INPUT.mark(), ErrorMsg::CHAR_IN_BLOCK); // set the initial indentation if(GetTopIndent() >= 0) params.indent += GetTopIndent(); params.eatLeadingWhitespace = false; params.trimTrailingSpaces = false; params.onTabInIndentation = THROW; scalar = ScanScalar(INPUT, params); // simple keys always ok after block scalars (since we're gonna start a new line anyways) m_simpleKeyAllowed = true; Token token(Token::SCALAR, mark); token.value = scalar; m_tokens.push(token); } } <commit_msg>Fixed bug in plain scalar folding<commit_after>#include "crt.h" #include "scanner.h" #include "token.h" #include "exceptions.h" #include "exp.h" #include "scanscalar.h" #include <sstream> namespace YAML { /////////////////////////////////////////////////////////////////////// // Specialization for scanning specific tokens // Directive // . Note: no semantic checking is done here (that's for the parser to do) void Scanner::ScanDirective() { std::string name; std::vector <std::string> params; // pop indents and simple keys PopAllIndents(); PopAllSimpleKeys(); m_simpleKeyAllowed = false; // store pos and eat indicator Mark mark = INPUT.mark(); INPUT.eat(1); // read name while(INPUT && !Exp::BlankOrBreak.Matches(INPUT)) name += INPUT.get(); // read parameters while(1) { // first get rid of whitespace while(Exp::Blank.Matches(INPUT)) INPUT.eat(1); // break on newline or comment if(!INPUT || Exp::Break.Matches(INPUT) || Exp::Comment.Matches(INPUT)) break; // now read parameter std::string param; while(INPUT && !Exp::BlankOrBreak.Matches(INPUT)) param += INPUT.get(); params.push_back(param); } Token token(Token::DIRECTIVE, mark); token.value = name; token.params = params; m_tokens.push(token); } // DocStart void Scanner::ScanDocStart() { PopAllIndents(); PopAllSimpleKeys(); m_simpleKeyAllowed = false; // eat Mark mark = INPUT.mark(); INPUT.eat(3); m_tokens.push(Token(Token::DOC_START, mark)); } // DocEnd void Scanner::ScanDocEnd() { PopAllIndents(); PopAllSimpleKeys(); m_simpleKeyAllowed = false; // eat Mark mark = INPUT.mark(); INPUT.eat(3); m_tokens.push(Token(Token::DOC_END, mark)); } // FlowStart void Scanner::ScanFlowStart() { // flows can be simple keys InsertPotentialSimpleKey(); m_simpleKeyAllowed = true; // eat Mark mark = INPUT.mark(); char ch = INPUT.get(); FLOW_MARKER flowType = (ch == Keys::FlowSeqStart ? FLOW_SEQ : FLOW_MAP); m_flows.push(flowType); Token::TYPE type = (flowType == FLOW_SEQ ? Token::FLOW_SEQ_START : Token::FLOW_MAP_START); m_tokens.push(Token(type, mark)); } // FlowEnd void Scanner::ScanFlowEnd() { if(InBlockContext()) throw ParserException(INPUT.mark(), ErrorMsg::FLOW_END); // we might have a solo entry in the flow context if(VerifySimpleKey()) m_tokens.push(Token(Token::VALUE, INPUT.mark())); m_simpleKeyAllowed = false; // eat Mark mark = INPUT.mark(); char ch = INPUT.get(); // check that it matches the start FLOW_MARKER flowType = (ch == Keys::FlowSeqEnd ? FLOW_SEQ : FLOW_MAP); if(m_flows.top() != flowType) throw ParserException(mark, ErrorMsg::FLOW_END); m_flows.pop(); Token::TYPE type = (flowType ? Token::FLOW_SEQ_END : Token::FLOW_MAP_END); m_tokens.push(Token(type, mark)); } // FlowEntry void Scanner::ScanFlowEntry() { // we might have a solo entry in the flow context if(VerifySimpleKey()) m_tokens.push(Token(Token::VALUE, INPUT.mark())); m_simpleKeyAllowed = true; // eat Mark mark = INPUT.mark(); INPUT.eat(1); m_tokens.push(Token(Token::FLOW_ENTRY, mark)); } // BlockEntry void Scanner::ScanBlockEntry() { // we better be in the block context! if(InFlowContext()) throw ParserException(INPUT.mark(), ErrorMsg::BLOCK_ENTRY); // can we put it here? if(!m_simpleKeyAllowed) throw ParserException(INPUT.mark(), ErrorMsg::BLOCK_ENTRY); PushIndentTo(INPUT.column(), IndentMarker::SEQ); m_simpleKeyAllowed = true; // eat Mark mark = INPUT.mark(); INPUT.eat(1); m_tokens.push(Token(Token::BLOCK_ENTRY, mark)); } // Key void Scanner::ScanKey() { // handle keys diffently in the block context (and manage indents) if(InBlockContext()) { if(!m_simpleKeyAllowed) throw ParserException(INPUT.mark(), ErrorMsg::MAP_KEY); PushIndentTo(INPUT.column(), IndentMarker::MAP); } // can only put a simple key here if we're in block context m_simpleKeyAllowed = InBlockContext(); // eat Mark mark = INPUT.mark(); INPUT.eat(1); m_tokens.push(Token(Token::KEY, mark)); } // Value void Scanner::ScanValue() { // and check that simple key bool isSimpleKey = VerifySimpleKey(); if(isSimpleKey) { // can't follow a simple key with another simple key (dunno why, though - it seems fine) m_simpleKeyAllowed = false; } else { // handle values diffently in the block context (and manage indents) if(InBlockContext()) { if(!m_simpleKeyAllowed) throw ParserException(INPUT.mark(), ErrorMsg::MAP_VALUE); PushIndentTo(INPUT.column(), IndentMarker::MAP); } // can only put a simple key here if we're in block context m_simpleKeyAllowed = InBlockContext(); } // eat Mark mark = INPUT.mark(); INPUT.eat(1); m_tokens.push(Token(Token::VALUE, mark)); } // AnchorOrAlias void Scanner::ScanAnchorOrAlias() { bool alias; std::string name; // insert a potential simple key InsertPotentialSimpleKey(); m_simpleKeyAllowed = false; // eat the indicator Mark mark = INPUT.mark(); char indicator = INPUT.get(); alias = (indicator == Keys::Alias); // now eat the content while(Exp::AlphaNumeric.Matches(INPUT)) name += INPUT.get(); // we need to have read SOMETHING! if(name.empty()) throw ParserException(INPUT.mark(), alias ? ErrorMsg::ALIAS_NOT_FOUND : ErrorMsg::ANCHOR_NOT_FOUND); // and needs to end correctly if(INPUT && !Exp::AnchorEnd.Matches(INPUT)) throw ParserException(INPUT.mark(), alias ? ErrorMsg::CHAR_IN_ALIAS : ErrorMsg::CHAR_IN_ANCHOR); // and we're done Token token(alias ? Token::ALIAS : Token::ANCHOR, mark); token.value = name; m_tokens.push(token); } // Tag void Scanner::ScanTag() { std::string handle, suffix; // insert a potential simple key InsertPotentialSimpleKey(); m_simpleKeyAllowed = false; // eat the indicator Mark mark = INPUT.mark(); handle += INPUT.get(); // read the handle while(INPUT && INPUT.peek() != Keys::Tag && !Exp::BlankOrBreak.Matches(INPUT)) handle += INPUT.get(); // is there a suffix? if(INPUT.peek() == Keys::Tag) { // eat the indicator handle += INPUT.get(); // then read it while(INPUT && !Exp::BlankOrBreak.Matches(INPUT)) suffix += INPUT.get(); } else { // this is a bit weird: we keep just the '!' as the handle and move the rest to the suffix suffix = handle.substr(1); handle = "!"; } Token token(Token::TAG, mark); token.value = handle; token.params.push_back(suffix); m_tokens.push(token); } // PlainScalar void Scanner::ScanPlainScalar() { std::string scalar; // set up the scanning parameters ScanScalarParams params; params.end = (InFlowContext() ? Exp::EndScalarInFlow : Exp::EndScalar) || (Exp::BlankOrBreak + Exp::Comment); params.eatEnd = false; params.indent = (InFlowContext() ? 0 : GetTopIndent() + 1); params.fold = FOLD_FLOW; params.eatLeadingWhitespace = true; params.trimTrailingSpaces = true; params.chomp = STRIP; params.onDocIndicator = BREAK; params.onTabInIndentation = THROW; // insert a potential simple key InsertPotentialSimpleKey(); Mark mark = INPUT.mark(); scalar = ScanScalar(INPUT, params); // can have a simple key only if we ended the scalar by starting a new line m_simpleKeyAllowed = params.leadingSpaces; // finally, check and see if we ended on an illegal character //if(Exp::IllegalCharInScalar.Matches(INPUT)) // throw ParserException(INPUT.mark(), ErrorMsg::CHAR_IN_SCALAR); Token token(Token::SCALAR, mark); token.value = scalar; m_tokens.push(token); } // QuotedScalar void Scanner::ScanQuotedScalar() { std::string scalar; // peek at single or double quote (don't eat because we need to preserve (for the time being) the input position) char quote = INPUT.peek(); bool single = (quote == '\''); // setup the scanning parameters ScanScalarParams params; params.end = (single ? RegEx(quote) && !Exp::EscSingleQuote : RegEx(quote)); params.eatEnd = true; params.escape = (single ? '\'' : '\\'); params.indent = 0; params.fold = FOLD_FLOW; params.eatLeadingWhitespace = true; params.trimTrailingSpaces = false; params.chomp = CLIP; params.onDocIndicator = THROW; // insert a potential simple key InsertPotentialSimpleKey(); Mark mark = INPUT.mark(); // now eat that opening quote INPUT.get(); // and scan scalar = ScanScalar(INPUT, params); m_simpleKeyAllowed = false; Token token(Token::SCALAR, mark); token.value = scalar; m_tokens.push(token); } // BlockScalarToken // . These need a little extra processing beforehand. // . We need to scan the line where the indicator is (this doesn't count as part of the scalar), // and then we need to figure out what level of indentation we'll be using. void Scanner::ScanBlockScalar() { std::string scalar; ScanScalarParams params; params.indent = 1; params.detectIndent = true; // eat block indicator ('|' or '>') Mark mark = INPUT.mark(); char indicator = INPUT.get(); params.fold = (indicator == Keys::FoldedScalar ? FOLD_BLOCK : DONT_FOLD); // eat chomping/indentation indicators params.chomp = CLIP; int n = Exp::Chomp.Match(INPUT); for(int i=0;i<n;i++) { char ch = INPUT.get(); if(ch == '+') params.chomp = KEEP; else if(ch == '-') params.chomp = STRIP; else if(Exp::Digit.Matches(ch)) { if(ch == '0') throw ParserException(INPUT.mark(), ErrorMsg::ZERO_INDENT_IN_BLOCK); params.indent = ch - '0'; params.detectIndent = false; } } // now eat whitespace while(Exp::Blank.Matches(INPUT)) INPUT.eat(1); // and comments to the end of the line if(Exp::Comment.Matches(INPUT)) while(INPUT && !Exp::Break.Matches(INPUT)) INPUT.eat(1); // if it's not a line break, then we ran into a bad character inline if(INPUT && !Exp::Break.Matches(INPUT)) throw ParserException(INPUT.mark(), ErrorMsg::CHAR_IN_BLOCK); // set the initial indentation if(GetTopIndent() >= 0) params.indent += GetTopIndent(); params.eatLeadingWhitespace = false; params.trimTrailingSpaces = false; params.onTabInIndentation = THROW; scalar = ScanScalar(INPUT, params); // simple keys always ok after block scalars (since we're gonna start a new line anyways) m_simpleKeyAllowed = true; Token token(Token::SCALAR, mark); token.value = scalar; m_tokens.push(token); } } <|endoftext|>
<commit_before>#line 2 "togo/hash_map.hpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file hash_map.hpp @brief HashMap interface. @ingroup collections @ingroup hash_map */ #pragma once #include <togo/config.hpp> #include <togo/types.hpp> #include <togo/collection_types.hpp> #include <togo/utility.hpp> #include <togo/assert.hpp> #include <togo/memory.hpp> #include <togo/array.hpp> #include <utility> namespace togo { /// Construct with allocator for storage. template<class K, class T> inline HashMap<K, T>::HashMap(Allocator& allocator) : _head(allocator) , _data(allocator) {} namespace hash_map { /** @addtogroup hash_map @{ */ /** @cond INTERNAL */ #define TOGO_HASH_MAP_MAX_LOAD 0.70f /** @endcond */ // INTERNAL /// Number of partitions. template<class K, class T> inline u32_fast num_partitions(HashMap<K, T> const& hm) { return array::size(hm._head); } /// Number of values. template<class K, class T> inline u32_fast size(HashMap<K, T> const& hm) { return array::size(hm._data); } /// Number of values reserved. template<class K, class T> inline u32_fast capacity(HashMap<K, T> const& hm) { return static_cast<u32_fast>(num_partitions(hm) * TOGO_HASH_MAP_MAX_LOAD); } /// Number of values that can be added before a resize occurs. template<class K, class T> inline u32_fast space(HashMap<K, T> const& hm) { return capacity(hm) - size(hm); } /// Returns true if there are any values. template<class K, class T> inline bool any(HashMap<K, T> const& hm) { return size(hm) != 0; } /// Returns true if there are no values. template<class K, class T> inline bool empty(HashMap<K, T> const& hm) { return size(hm) == 0; } /// Beginning iterator: [begin, end). template<class K, class T> inline HashMapNode<K, T>* begin(HashMap<K, T>& hm) { return array::begin(hm._data); } /// Beginning iterator: [begin, end). template<class K, class T> inline HashMapNode<K, T> const* begin(HashMap<K, T> const& hm) { return array::begin(hm._data); } /// Ending iterator: [begin, end). template<class K, class T> inline HashMapNode<K, T>* end(HashMap<K, T>& hm) { return array::end(hm._data); } /// Ending iterator: [begin, end). template<class K, class T> inline HashMapNode<K, T> const* end(HashMap<K, T> const& hm) { return array::end(hm._data); } /** @cond INTERNAL */ enum : unsigned { END = ~0u, }; struct FindData { // Index into _head u32 head; // Index into _data u32 data; // Previous node with same key u32 data_prev; }; namespace internal { template<class K, class T> FindData find(HashMap<K, T> const& hm, K const key) { FindData fd{END, END, END}; if (array::empty(hm._head)) { return fd; } fd.head = key % num_partitions(hm); fd.data = hm._head[fd.head]; while (fd.data != END) { auto const& node = hm._data[fd.data]; if (node.key == key) { break; } fd.data_prev = fd.data; fd.data = node.next; } return fd; } template<class K, class T> FindData find( HashMap<K, T> const& hm, HashMapNode<K, T> const* node ) { FindData fd{END, END, END}; if (array::empty(hm._head)) { return fd; } fd.head = node->key % num_partitions(hm); fd.data = hm._head[fd.head]; while (fd.data != END) { auto const& it_node = hm._data[fd.data]; if (&it_node == node) { break; } fd.data_prev = fd.data; fd.data = it_node.next; } return fd; } template<class K, class T> u32 make(HashMap<K, T>& hm, K const key, bool const keep) { TOGO_DEBUG_ASSERTE(array::any(hm._head)); FindData const fd = find(hm, key); if (keep && fd.data != END) { return fd.data; } u32 const index = array::size(hm._data); HashMapNode<K, T> node; node.key = key; node.next = fd.data; array::push_back(hm._data, node); if (fd.data_prev == END) { hm._head[fd.head] = index; } else { hm._data[fd.data_prev].next = index; } return index; } template<class K, class T> void remove(HashMap<K, T>& hm, FindData const& fd) { if (fd.data_prev == END) { // find() was immediate hit; fd is the first item // in the head. Move the head to the next item (if any). hm._head[fd.head] = hm._data[fd.data].next; } else { hm._data[fd.data_prev].next = hm._data[fd.data].next; } // Move last node to the removed position if (fd.data != array::size(hm._data) - 1) { auto const& last_node = array::back(hm._data); FindData const last = find(hm, &last_node); if (last.data_prev == END) { hm._head[last.head] = fd.data; } else { hm._data[last.data_prev].next = fd.data; } hm._data[fd.data] = last_node; } array::pop_back(hm._data); } template<class K, class T> void resize(HashMap<K, T>& hm, u32_fast const new_size) { HashMap<K, T> new_hm{*hm._head._allocator}; array::resize(new_hm._head, new_size); array::reserve(new_hm._data, min(new_size, array::capacity(hm._data))); for (unsigned i = 0; i < new_size; ++i) { new_hm._head[i] = END; } u32 index; for (auto const& node : hm._data) { index = make(hm, node.key, false); hm._data[index].value = node.value; } hm = std::move(new_hm); } template<class K, class T> inline void grow(HashMap<K, T>& hm) { resize(hm, num_partitions(hm) * 2 + 16); } } // namespace internal /** @endcond */ // INTERNAL /// Reserve at least new_capacity. template<class K, class T> inline void reserve(HashMap<K, T>& hm, u32_fast const new_capacity) { if (new_capacity > capacity(hm)) { internal::resize(hm, (new_capacity / TOGO_HASH_MAP_MAX_LOAD) + 1); } } /// Remove all items. template<class K, class T> inline void clear(HashMap<K, T>& hm) { auto const size = num_partitions(hm); for (unsigned i = 0; i < size; ++i) { hm._head[i] = END; } array::clear(hm._data); } /// Set item. /// /// If key does not exist, it will be inserted. template<class K, class T> inline void set(HashMap<K, T>& hm, K const key, T const& value) { if (!space(hm)) { internal::grow(hm); } auto const index = internal::make(hm, key, true); hm._data[index].value = value; } /// Get item. /// /// If key does not exist, nullptr will be returned. template<class K, class T> inline T* get(HashMap<K, T>& hm, K const key) { auto const index = internal::find(hm, key).data; return (index != END) ? &hm._data[index].value : nullptr; } /// Get item. /// /// If key does not exist, nullptr will be returned. template<class K, class T> inline T const* get(HashMap<K, T> const& hm, K const key) { auto const index = internal::find(hm, key).data; return (index != END) ? &hm._data[index].value : nullptr; } /// Check if there is a value with key. template<class K, class T> inline bool has(HashMap<K, T> const& hm, K const key) { return internal::find(hm, key).data != END; } /// Remove value. template<class K, class T> inline void remove(HashMap<K, T>& hm, K const key) { FindData const fd = internal::find(hm, key); if (fd.data != END) { internal::remove(hm, fd); } } /** @cond INTERNAL */ #undef TOGO_HASH_MAP_MAX_LOAD /** @endcond */ // INTERNAL /** @} */ // end of doc-group hash_map } // namespace hash_map /** @cond INTERNAL */ // ADL support template<class K, class T> inline HashMapNode<K, T>* begin(HashMap<K, T>& hm) { return hash_map::begin(hm); } template<class K, class T> inline HashMapNode<K, T> const* begin(HashMap<K, T> const& hm) { return hash_map::begin(hm); } template<class K, class T> inline HashMapNode<K, T>* end(HashMap<K, T>& hm) { return hash_map::end(hm); } template<class K, class T> inline HashMapNode<K, T> const* end(HashMap<K, T> const& hm) { return hash_map::end(hm); } /** @endcond */ // INTERNAL } // namespace togo <commit_msg>hash_map: added node access interface; doc tidy.<commit_after>#line 2 "togo/hash_map.hpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file hash_map.hpp @brief HashMap interface. @ingroup collections @ingroup hash_map */ #pragma once #include <togo/config.hpp> #include <togo/types.hpp> #include <togo/collection_types.hpp> #include <togo/utility.hpp> #include <togo/assert.hpp> #include <togo/memory.hpp> #include <togo/array.hpp> #include <utility> namespace togo { /// Construct with allocator for storage. template<class K, class T> inline HashMap<K, T>::HashMap(Allocator& allocator) : _head(allocator) , _data(allocator) {} namespace hash_map { /** @addtogroup hash_map @{ */ /** @cond INTERNAL */ #define TOGO_HASH_MAP_MAX_LOAD 0.70f /** @endcond */ // INTERNAL /// Number of partitions. template<class K, class T> inline u32_fast num_partitions(HashMap<K, T> const& hm) { return array::size(hm._head); } /// Number of values. template<class K, class T> inline u32_fast size(HashMap<K, T> const& hm) { return array::size(hm._data); } /// Number of values reserved. template<class K, class T> inline u32_fast capacity(HashMap<K, T> const& hm) { return static_cast<u32_fast>(num_partitions(hm) * TOGO_HASH_MAP_MAX_LOAD); } /// Number of values that can be added before a resize occurs. template<class K, class T> inline u32_fast space(HashMap<K, T> const& hm) { return capacity(hm) - size(hm); } /// Returns true if there are any values. template<class K, class T> inline bool any(HashMap<K, T> const& hm) { return size(hm) != 0; } /// Returns true if there are no values. template<class K, class T> inline bool empty(HashMap<K, T> const& hm) { return size(hm) == 0; } /// Beginning iterator: [begin, end). template<class K, class T> inline HashMapNode<K, T>* begin(HashMap<K, T>& hm) { return array::begin(hm._data); } /// Beginning iterator: [begin, end). template<class K, class T> inline HashMapNode<K, T> const* begin(HashMap<K, T> const& hm) { return array::begin(hm._data); } /// Ending iterator: [begin, end). template<class K, class T> inline HashMapNode<K, T>* end(HashMap<K, T>& hm) { return array::end(hm._data); } /// Ending iterator: [begin, end). template<class K, class T> inline HashMapNode<K, T> const* end(HashMap<K, T> const& hm) { return array::end(hm._data); } /** @cond INTERNAL */ enum : unsigned { END = ~0u, }; struct FindData { // Index into _head u32 head; // Index into _data u32 data; // Previous node with same key u32 data_prev; }; namespace internal { template<class K, class T> FindData find(HashMap<K, T> const& hm, K const key) { FindData fd{END, END, END}; if (array::empty(hm._head)) { return fd; } fd.head = key % num_partitions(hm); fd.data = hm._head[fd.head]; while (fd.data != END) { auto const& node = hm._data[fd.data]; if (node.key == key) { break; } fd.data_prev = fd.data; fd.data = node.next; } return fd; } template<class K, class T> FindData find( HashMap<K, T> const& hm, HashMapNode<K, T> const* node ) { FindData fd{END, END, END}; if (array::empty(hm._head)) { return fd; } fd.head = node->key % num_partitions(hm); fd.data = hm._head[fd.head]; while (fd.data != END) { auto const& it_node = hm._data[fd.data]; if (&it_node == node) { break; } fd.data_prev = fd.data; fd.data = it_node.next; } return fd; } template<class K, class T> u32 make(HashMap<K, T>& hm, K const key, bool const keep) { TOGO_DEBUG_ASSERTE(array::any(hm._head)); FindData const fd = find(hm, key); if (keep && fd.data != END) { return fd.data; } u32 const index = array::size(hm._data); HashMapNode<K, T> node; node.key = key; node.next = fd.data; array::push_back(hm._data, node); if (fd.data_prev == END) { hm._head[fd.head] = index; } else { hm._data[fd.data_prev].next = index; } return index; } template<class K, class T> void remove(HashMap<K, T>& hm, FindData const& fd) { if (fd.data_prev == END) { // find() was immediate hit; fd is the first item // in the head. Move the head to the next item (if any). hm._head[fd.head] = hm._data[fd.data].next; } else { hm._data[fd.data_prev].next = hm._data[fd.data].next; } // Move last node to the removed position if (fd.data != array::size(hm._data) - 1) { auto const& last_node = array::back(hm._data); FindData const last = find(hm, &last_node); if (last.data_prev == END) { hm._head[last.head] = fd.data; } else { hm._data[last.data_prev].next = fd.data; } hm._data[fd.data] = last_node; } array::pop_back(hm._data); } template<class K, class T> void resize(HashMap<K, T>& hm, u32_fast const new_size) { HashMap<K, T> new_hm{*hm._head._allocator}; array::resize(new_hm._head, new_size); array::reserve(new_hm._data, min(new_size, array::capacity(hm._data))); for (unsigned i = 0; i < new_size; ++i) { new_hm._head[i] = END; } u32 index; for (auto const& node : hm._data) { index = make(hm, node.key, false); hm._data[index].value = node.value; } hm = std::move(new_hm); } template<class K, class T> inline void grow(HashMap<K, T>& hm) { resize(hm, num_partitions(hm) * 2 + 16); } } // namespace internal /** @endcond */ // INTERNAL /// Reserve at least new_capacity. template<class K, class T> inline void reserve(HashMap<K, T>& hm, u32_fast const new_capacity) { if (new_capacity > capacity(hm)) { internal::resize(hm, (new_capacity / TOGO_HASH_MAP_MAX_LOAD) + 1); } } /// Remove all items. template<class K, class T> inline void clear(HashMap<K, T>& hm) { auto const size = num_partitions(hm); for (unsigned i = 0; i < size; ++i) { hm._head[i] = END; } array::clear(hm._data); } /// Set item. /// /// If key does not exist, it will be inserted. template<class K, class T> inline void set(HashMap<K, T>& hm, K const key, T const& value) { if (!space(hm)) { internal::grow(hm); } auto const index = internal::make(hm, key, true); hm._data[index].value = value; } /// Push item. /// /// If there are existing values with key, they are retained. template<class K, class T> inline void push(HashMap<K, T>& hm, K const key, T const& value) { if (!space(hm)) { internal::grow(hm); } auto const index = internal::make(hm, key, false); hm._data[index].value = value; } /// Get item. /// /// If key does not exist, nullptr will be returned. /// If multiple values are assigned to key, this will get the most /// recently pushed one. template<class K, class T> inline T* get(HashMap<K, T>& hm, K const key) { auto const index = internal::find(hm, key).data; return (index != END) ? &hm._data[index].value : nullptr; } /// Get item. /// /// If key does not exist, nullptr will be returned. /// If multiple values are assigned to key, this will get the most /// recently pushed one. template<class K, class T> inline T const* get(HashMap<K, T> const& hm, K const key) { auto const index = internal::find(hm, key).data; return (index != END) ? &hm._data[index].value : nullptr; } /// Get first node with key. /// /// If there are no items with key, nullptr will be returned. template<class K, class T> inline HashMapNode<K, T>* get_node( HashMap<K, T>& hm, K const key ) { auto const index = internal::find(hm, key).data; return (index != END) ? &hm._data[index] : nullptr; } /// Get first node with key. /// /// If there are no items with key, nullptr will be returned. template<class K, class T> inline HashMapNode<K, T> const* get_node( HashMap<K, T> const& hm, K const key ) { auto const index = internal::find(hm, key).data; return (index != END) ? &hm._data[index] : nullptr; } /// Get next node in keyset. /// /// An assertion will fail if node is nullptr. Returns nullptr when /// there are no more nodes for the key. template<class K, class T> inline HashMapNode<K, T>* get_next( HashMap<K, T>& hm, HashMapNode<K, T>* node ) { TOGO_ASSERTE(node != nullptr); K const key = node->key; while (node->next != END) { node = &hm._data[node->next]; if (node->key == key) { return node; } } return nullptr; } /// Get next node in keyset. /// /// An assertion will fail if node is nullptr. Returns nullptr when /// there are no more nodes for the key. template<class K, class T> inline HashMapNode<K, T> const* get_next( HashMap<K, T> const& hm, HashMapNode<K, T> const* node ) { TOGO_ASSERTE(node != nullptr); K const key = node->key; while (node->next != END) { node = &hm._data[node->next]; if (node->key == key) { return node; } } return nullptr; } /// Check if there is a value with key. template<class K, class T> inline bool has(HashMap<K, T> const& hm, K const key) { return internal::find(hm, key).data != END; } /// Count the number of values with key. template<class K, class T> inline unsigned count(HashMap<K, T> const& hm, K const key) { auto const* node = get_node(hm, key); unsigned count = 0; while (node != nullptr) { node = get_next(hm, node); ++count; } return count; } /// Remove value. /// /// If there are multiple values with key, the most recently added /// one is removed. template<class K, class T> inline void remove(HashMap<K, T>& hm, K const key) { FindData const fd = internal::find(hm, key); if (fd.data != END) { internal::remove(hm, fd); } } /// Remove node. /// /// An assertion will fail if node is nullptr. template<class K, class T> inline void remove(HashMap<K, T>& hm, HashMapNode<K, T> const* node) { TOGO_ASSERTE(node != nullptr); FindData const fd = internal::find(hm, node); if (fd.data != END) { internal::remove(hm, fd); } } /** @cond INTERNAL */ #undef TOGO_HASH_MAP_MAX_LOAD /** @endcond */ // INTERNAL /** @} */ // end of doc-group hash_map } // namespace hash_map /** @cond INTERNAL */ // ADL support template<class K, class T> inline HashMapNode<K, T>* begin(HashMap<K, T>& hm) { return hash_map::begin(hm); } template<class K, class T> inline HashMapNode<K, T> const* begin(HashMap<K, T> const& hm) { return hash_map::begin(hm); } template<class K, class T> inline HashMapNode<K, T>* end(HashMap<K, T>& hm) { return hash_map::end(hm); } template<class K, class T> inline HashMapNode<K, T> const* end(HashMap<K, T> const& hm) { return hash_map::end(hm); } /** @endcond */ // INTERNAL } // namespace togo <|endoftext|>
<commit_before>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION 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 "serialize.hxx" #include "strmap.hxx" #include "GrowingBuffer.hxx" #include "util/ConstBuffer.hxx" #include "util/ByteOrder.hxx" #include <assert.h> #include <stdint.h> #include <string.h> void serialize_uint16(GrowingBuffer &gb, uint16_t value) { uint16_t *dest = (uint16_t *)gb.Write(sizeof(*dest)); *dest = ToBE16(value); } void serialize_uint32(GrowingBuffer &gb, uint32_t value) { uint32_t *dest = (uint32_t *)gb.Write(sizeof(*dest)); *dest = ToBE32(value); } void serialize_uint64(GrowingBuffer &gb, uint64_t value) { uint64_t *dest = (uint64_t *)gb.Write(sizeof(*dest)); *dest = ToBE64(value); } /* static void serialize_size_t(GrowingBuffer &gb, size_t value) { serialize_uint32(gb, value); } */ void serialize_string(GrowingBuffer &gb, const char *value) { assert(value != nullptr); /* write the string including the null terminator */ gb.Write(value, strlen(value) + 1); } void serialize_string_null(GrowingBuffer &gb, const char *value) { serialize_string(gb, value != nullptr ? value : ""); } void serialize_strmap(GrowingBuffer &gb, const StringMap &map) { for (const auto &i : map) { if (*i.key == 0) /* this shouldn't happen; ignore this invalid entry */ continue; serialize_string(gb, i.key); serialize_string(gb, i.value); } /* key length 0 means "end of map" */ serialize_string(gb, ""); } void serialize_strmap(GrowingBuffer &gb, const StringMap *map) { if (map == nullptr) /* same as empty map */ serialize_string(gb, ""); else serialize_strmap(gb, *map); } static void SkipFront(ConstBuffer<void> &input, size_t n) { assert(input.size >= n); input.data = (const uint8_t *)input.data + n; input.size -= n; } template<typename T> static void DeserializeT(ConstBuffer<void> &input, T &dest) { static_assert(std::is_trivial<T>::value, "type is not trivial"); if (gcc_unlikely(input.size < sizeof(dest))) throw DeserializeError(); memcpy(&dest, input.data, sizeof(dest)); SkipFront(input, sizeof(dest)); } uint16_t deserialize_uint16(ConstBuffer<void> &input) { uint16_t value; DeserializeT(input, value); return FromBE16(*(const uint16_t *)input.data); } uint32_t deserialize_uint32(ConstBuffer<void> &input) { uint32_t value; DeserializeT(input, value); return FromBE32(*(const uint32_t *)input.data); } uint64_t deserialize_uint64(ConstBuffer<void> &input) { uint64_t value; DeserializeT(input, value); return FromBE64(*(const uint64_t *)input.data); } const char * deserialize_string(ConstBuffer<void> &input) { const char *end = (const char *)memchr(input.data, 0, input.size); if (end == nullptr) throw DeserializeError(); const char *value = (const char *)input.data; SkipFront(input, end + 1 - value); return value; } const char * deserialize_string_null(ConstBuffer<void> &input) { const char *value = deserialize_string(input); if (*value == 0) value = nullptr; return value; } void deserialize_strmap(ConstBuffer<void> &input, StringMap &dest) { while (true) { const char *key = deserialize_string(input); if (*key == 0) break; const char *value = deserialize_string(input); dest.Add(key, value); } } <commit_msg>serialize: fix FromBE*() parameters<commit_after>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION 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 "serialize.hxx" #include "strmap.hxx" #include "GrowingBuffer.hxx" #include "util/ConstBuffer.hxx" #include "util/ByteOrder.hxx" #include <assert.h> #include <stdint.h> #include <string.h> void serialize_uint16(GrowingBuffer &gb, uint16_t value) { uint16_t *dest = (uint16_t *)gb.Write(sizeof(*dest)); *dest = ToBE16(value); } void serialize_uint32(GrowingBuffer &gb, uint32_t value) { uint32_t *dest = (uint32_t *)gb.Write(sizeof(*dest)); *dest = ToBE32(value); } void serialize_uint64(GrowingBuffer &gb, uint64_t value) { uint64_t *dest = (uint64_t *)gb.Write(sizeof(*dest)); *dest = ToBE64(value); } /* static void serialize_size_t(GrowingBuffer &gb, size_t value) { serialize_uint32(gb, value); } */ void serialize_string(GrowingBuffer &gb, const char *value) { assert(value != nullptr); /* write the string including the null terminator */ gb.Write(value, strlen(value) + 1); } void serialize_string_null(GrowingBuffer &gb, const char *value) { serialize_string(gb, value != nullptr ? value : ""); } void serialize_strmap(GrowingBuffer &gb, const StringMap &map) { for (const auto &i : map) { if (*i.key == 0) /* this shouldn't happen; ignore this invalid entry */ continue; serialize_string(gb, i.key); serialize_string(gb, i.value); } /* key length 0 means "end of map" */ serialize_string(gb, ""); } void serialize_strmap(GrowingBuffer &gb, const StringMap *map) { if (map == nullptr) /* same as empty map */ serialize_string(gb, ""); else serialize_strmap(gb, *map); } static void SkipFront(ConstBuffer<void> &input, size_t n) { assert(input.size >= n); input.data = (const uint8_t *)input.data + n; input.size -= n; } template<typename T> static void DeserializeT(ConstBuffer<void> &input, T &dest) { static_assert(std::is_trivial<T>::value, "type is not trivial"); if (gcc_unlikely(input.size < sizeof(dest))) throw DeserializeError(); memcpy(&dest, input.data, sizeof(dest)); SkipFront(input, sizeof(dest)); } uint16_t deserialize_uint16(ConstBuffer<void> &input) { uint16_t value; DeserializeT(input, value); return FromBE16(value); } uint32_t deserialize_uint32(ConstBuffer<void> &input) { uint32_t value; DeserializeT(input, value); return FromBE32(value); } uint64_t deserialize_uint64(ConstBuffer<void> &input) { uint64_t value; DeserializeT(input, value); return FromBE64(value); } const char * deserialize_string(ConstBuffer<void> &input) { const char *end = (const char *)memchr(input.data, 0, input.size); if (end == nullptr) throw DeserializeError(); const char *value = (const char *)input.data; SkipFront(input, end + 1 - value); return value; } const char * deserialize_string_null(ConstBuffer<void> &input) { const char *value = deserialize_string(input); if (*value == 0) value = nullptr; return value; } void deserialize_strmap(ConstBuffer<void> &input, StringMap &dest) { while (true) { const char *key = deserialize_string(input); if (*key == 0) break; const char *value = deserialize_string(input); dest.Add(key, value); } } <|endoftext|>
<commit_before>#include <set.hpp> #include <kdb.hpp> #include <kdbio.hpp> #include <cmdline.hpp> #include <iostream> using namespace std; using namespace kdb; SetCommand::SetCommand() {} int SetCommand::execute(Cmdline const& cl) { int argc = cl.arguments.size(); if (argc != 1 && argc != 2) { throw invalid_argument("1 or 2 arguments needed"); } std::string name = cl.arguments[0]; bool nullValue; std::string value; if (argc == 2) { nullValue = false; value = cl.arguments[1]; } else { nullValue = true; } KeySet conf; Key k(name, KEY_END); // do not resume on any get errors // otherwise the user might break // the config kdb.get(conf, k); printWarnings(cerr, k); printError(cerr, k); Key key = conf.lookup(name); if (!key) { cout << "create a new key " << name; key = Key(name, KEY_END); if (!nullValue) { cout << " with string " << value << endl; key.setString(value); } else { cout << " with null value" << endl; key.setBinary(0, 0); } if (!key.isValid()) { cerr << "no valid name supplied" << endl; return 1; } conf.append(key); } else { if (!nullValue) { cout << "Set string to " << value << endl; key.setString(value); } else { cout << "Set null value" << endl; key.setBinary(0, 0); } } Key n; kdb.set(conf, n); printWarnings(cerr, n); printError(cerr, n); return 0; } SetCommand::~SetCommand() {} <commit_msg>use cascading name for kdb set<commit_after>#include <set.hpp> #include <kdb.hpp> #include <kdbio.hpp> #include <cmdline.hpp> #include <iostream> using namespace std; using namespace kdb; SetCommand::SetCommand() {} int SetCommand::execute(Cmdline const& cl) { int argc = cl.arguments.size(); if (argc != 1 && argc != 2) { throw invalid_argument("1 or 2 arguments needed"); } std::string name = cl.arguments[0]; bool nullValue; std::string value; if (argc == 2) { nullValue = false; value = cl.arguments[1]; } else { nullValue = true; } KeySet conf; Key k(name, KEY_END); // do not resume on any get errors // otherwise the user might break // the config kdb.get(conf, k); printWarnings(cerr, k); printError(cerr, k); Key key = conf.lookup(name); if (!key) { cout << "create a new key " << name; key = Key(name, KEY_END); if (!nullValue) { cout << " with string " << value << endl; key.setString(value); } else { cout << " with null value" << endl; key.setBinary(0, 0); } if (!key.isValid()) { cerr << "no valid name supplied" << endl; return 1; } conf.append(key); } else { if (!nullValue) { cout << "Set string to " << value << endl; key.setString(value); } else { cout << "Set null value" << endl; key.setBinary(0, 0); } } Key n("/", KEY_CASCADING_NAME, KEY_END); kdb.set(conf, n); printWarnings(cerr, n); printError(cerr, n); return 0; } SetCommand::~SetCommand() {} <|endoftext|>
<commit_before>#include "tracker.h" #include "ada/tools/text.h" void Tracker::start() { m_data.clear(); auto start = std::chrono::high_resolution_clock::now(); m_trackerStart = std::chrono::time_point_cast<std::chrono::microseconds>(start).time_since_epoch().count() * 0.001; m_running = true; } void Tracker::begin(const std::string& _track) { if (!m_running) return; m_stack.push_back(_track); std::string stack = getStack(); if ( m_data.find(stack) == m_data.end() ) m_tracks.push_back(stack); m_data[stack].start = std::chrono::high_resolution_clock::now(); } void Tracker::end(const std::string& _track) { if (!m_running) return; auto sample_end = std::chrono::high_resolution_clock::now(); std::string stack = getStack(); m_stack.pop_back(); if ( m_data.find(stack) == m_data.end() ) m_tracks.push_back(stack); auto start = std::chrono::time_point_cast<std::chrono::microseconds>(m_data[stack].start).time_since_epoch(); auto end = std::chrono::time_point_cast<std::chrono::microseconds>(sample_end).time_since_epoch(); StatSample stat; stat.startMs = start.count() * 0.001 - m_trackerStart; stat.endMs = end.count() * 0.001 - m_trackerStart; stat.durationMs = stat.endMs - stat.startMs; m_data[stack].samples.push_back( stat ); } void Tracker::stop() { m_running = false; } double Tracker::getFramerate() { double frm = 0.0; int count = 0; for (std::map<std::string, StatTrack>::iterator it = m_data.begin() ; it != m_data.end(); ++it) { double delta = 0.0; for (size_t i = 1; i < it->second.samples.size(); i++) delta += (it->second.samples[i].startMs - it->second.samples[i-1].startMs); delta /= (double) (it->second.samples.size() - 1); frm += delta; count++; } return ( frm / (double)count ); } std::string Tracker::getStack() const { std::string stack = ""; for (size_t i = 0; i < m_stack.size(); i++) { if (i > 0) stack += ":"; stack += m_stack[i]; } return stack; } std::string Tracker::logFramerate() { return "framerate," + ada::toString(getFramerate()) + ",100.0%\n";// + // "fps," + ada::toString( (1./getFramerate()) * 1000.0 ) ; } std::string Tracker::logSamples() { std::string log = ""; for (size_t t = 0; t < m_tracks.size(); t++) log += logSamples(m_tracks[t]); return log; } std::string Tracker::logSamples(const std::string& _track) { std::map<std::string, StatTrack>::iterator it = m_data.find(_track); if ( it == m_data.end() ) return ""; std::string log = ""; std::string track_name = it->first; for (size_t i = 0; i < it->second.samples.size(); i++) log += track_name + "," + ada::toString(it->second.samples[i].startMs) + "," + ada::toString(it->second.samples[i].durationMs) + "\n"; return log; } std::string Tracker::logAverage() { std::string log = ""; for (size_t t = 0; t < m_tracks.size(); t++) log += logAverage(m_tracks[t]); return log; } std::string Tracker::logAverage(const std::string& _track) { std::map<std::string, StatTrack>::iterator it = m_data.find(_track); if ( it == m_data.end() ) return ""; std::string log = ""; std::string track_name = it->first; double average = 0.0; double delta = 0.0; for (size_t i = 0; i < it->second.samples.size(); i++) { average += it->second.samples[i].durationMs; if (i > 0) delta += it->second.samples[i].startMs - it->second.samples[i-1].startMs; } average /= (double)it->second.samples.size(); delta /= (double)it->second.samples.size() - 1.0; it->second.durationAverage = average; log += track_name + "," + ada::toString(average) + "," + ada::toString( (average/delta) * 100.0) + "%," + ada::toString(delta) + "\n"; return log; } <commit_msg>remove pct<commit_after>#include "tracker.h" #include "ada/tools/text.h" void Tracker::start() { m_data.clear(); auto start = std::chrono::high_resolution_clock::now(); m_trackerStart = std::chrono::time_point_cast<std::chrono::microseconds>(start).time_since_epoch().count() * 0.001; m_running = true; } void Tracker::begin(const std::string& _track) { if (!m_running) return; m_stack.push_back(_track); std::string stack = getStack(); if ( m_data.find(stack) == m_data.end() ) m_tracks.push_back(stack); m_data[stack].start = std::chrono::high_resolution_clock::now(); } void Tracker::end(const std::string& _track) { if (!m_running) return; auto sample_end = std::chrono::high_resolution_clock::now(); std::string stack = getStack(); m_stack.pop_back(); if ( m_data.find(stack) == m_data.end() ) m_tracks.push_back(stack); auto start = std::chrono::time_point_cast<std::chrono::microseconds>(m_data[stack].start).time_since_epoch(); auto end = std::chrono::time_point_cast<std::chrono::microseconds>(sample_end).time_since_epoch(); StatSample stat; stat.startMs = start.count() * 0.001 - m_trackerStart; stat.endMs = end.count() * 0.001 - m_trackerStart; stat.durationMs = stat.endMs - stat.startMs; m_data[stack].samples.push_back( stat ); } void Tracker::stop() { m_running = false; } double Tracker::getFramerate() { double frm = 0.0; int count = 0; for (std::map<std::string, StatTrack>::iterator it = m_data.begin() ; it != m_data.end(); ++it) { double delta = 0.0; for (size_t i = 1; i < it->second.samples.size(); i++) delta += (it->second.samples[i].startMs - it->second.samples[i-1].startMs); delta /= (double) (it->second.samples.size() - 1); frm += delta; count++; } return ( frm / (double)count ); } std::string Tracker::getStack() const { std::string stack = ""; for (size_t i = 0; i < m_stack.size(); i++) { if (i > 0) stack += ":"; stack += m_stack[i]; } return stack; } std::string Tracker::logFramerate() { return "framerate," + ada::toString(getFramerate()) + "\n";// + // "fps," + ada::toString( (1./getFramerate()) * 1000.0 ) ; } std::string Tracker::logSamples() { std::string log = ""; for (size_t t = 0; t < m_tracks.size(); t++) log += logSamples(m_tracks[t]); return log; } std::string Tracker::logSamples(const std::string& _track) { std::map<std::string, StatTrack>::iterator it = m_data.find(_track); if ( it == m_data.end() ) return ""; std::string log = ""; std::string track_name = it->first; for (size_t i = 0; i < it->second.samples.size(); i++) log += track_name + "," + ada::toString(it->second.samples[i].startMs) + "," + ada::toString(it->second.samples[i].durationMs) + "\n"; return log; } std::string Tracker::logAverage() { std::string log = ""; for (size_t t = 0; t < m_tracks.size(); t++) log += logAverage(m_tracks[t]); return log; } std::string Tracker::logAverage(const std::string& _track) { std::map<std::string, StatTrack>::iterator it = m_data.find(_track); if ( it == m_data.end() ) return ""; std::string log = ""; std::string track_name = it->first; double average = 0.0; double delta = 0.0; for (size_t i = 0; i < it->second.samples.size(); i++) { average += it->second.samples[i].durationMs; if (i > 0) delta += it->second.samples[i].startMs - it->second.samples[i-1].startMs; } average /= (double)it->second.samples.size(); delta /= (double)it->second.samples.size() - 1.0; it->second.durationAverage = average; log += track_name + "," + ada::toString(average) + "," + ada::toString( (average/delta) * 100.0) + "%," + ada::toString(delta) + "\n"; return log; } <|endoftext|>
<commit_before>#include "training_core.hpp" #include "nanopolish_emissions.h" #include "logsumset.hpp" #include "logger.hpp" using std::string; using std::vector; using std::multiset; using std::endl; const bool use_multiset_logsum = #ifndef USE_MULTISET_LOGSUM false; #else true; #endif GaussianMixture train_gaussian_mixture(const vector< StateTrainingData >& data, const GaussianMixture& input_mixture) { size_t n_components = input_mixture.params.size(); size_t n_data = data.size(); float log_n_data = std::log(n_data); assert(input_mixture.log_weights.size() == n_components); GaussianMixture curr_mixture = input_mixture; for(size_t iteration = 0; iteration < 10; ++iteration) { GaussianMixture new_mixture = curr_mixture; // compute log_pdfs // // pdf[i][j] := gauss(mu_j, sigma_j * read_var_i, level_mean_i) // vector< vector< float > > log_pdf(n_data); for(size_t i = 0; i < n_data; ++i) { log_pdf[i].resize(n_components); for(size_t j = 0; j < n_components; ++j) { // We need to scale the mixture component parameters by the per-read var factor PoreModelStateParams scaled_state = curr_mixture.params[j]; scaled_state.level_stdv *= data[i].read_var; scaled_state.level_log_stdv += data[i].log_read_var; log_pdf[i][j] = log_normal_pdf(data[i].level_mean, scaled_state); assert(not std::isnan(log_pdf[i][j])); } } // compute responsibilities // // resp[i][j] := ( w_j * pdf[i][j] ) / sum_k ( w_k * pdf[i][k] ) // vector< vector< float > > log_resp(n_data); for(size_t i = 0; i < n_data; ++i) { log_resp[i].resize(n_components); logsumset< float > denom_terms(use_multiset_logsum); for(size_t j = 0; j < n_components; ++j) { float v = log_pdf[i][j] + curr_mixture.log_weights[j]; log_resp[i][j] = v; denom_terms.add(v); } float log_denom = denom_terms.val(); for(size_t j = 0; j < n_components; ++j) { log_resp[i][j] -= log_denom; } } // update weights // // w'[j] := sum_i resp[i][j] / n_data // for (size_t j = 0; j < n_components; ++j) { logsumset< float > numer_terms(use_multiset_logsum); for (size_t i = 0; i < n_data; ++i) { numer_terms.add(log_resp[i][j]); } float log_numer = numer_terms.val(); new_mixture.log_weights[j] = log_numer - log_n_data; } // update means // // mu_j := sum_i ( resp[i][j] * level_mean_i ) / sum_i resp[i][j] // = sum_i ( resp[i][j] * level_mean_i ) / ( w'[j] * n_data ) // vector< float > new_log_mean(2); for (size_t j = 0; j < n_components; ++j) { logsumset< float > numer_terms(use_multiset_logsum); for (size_t i = 0; i < n_data; ++i) { numer_terms.add(log_resp[i][j] + data[i].log_level_mean); } float log_numer = numer_terms.val(); new_log_mean[j] = log_numer - (log_n_data + new_mixture.log_weights[j]); } // update stdvs // // var_j := sum_i ( resp[i][j] * ( ( level_mean_i - mu_j ) / read_var_i )^2 ) / sum_i resp[i][j] // = sum_i ( resp[i][j] * ( ( level_mean_i - mu_j ) / read_var_i )^2 ) / ( w'[j] * n_data ) // vector< float > new_log_var(2); for (size_t j = 0; j < n_components; ++j) { logsumset< float > numer_terms(use_multiset_logsum); for (size_t i = 0; i < n_data; ++i) { float v = std::abs(data[i].level_mean - std::exp(new_log_mean[j])); numer_terms.add(log_resp[i][j] + (not std::isnan(v) and v > 0? 2.0 * (std::log(v) - data[i].log_read_var) : 0.0)); } float log_numer = numer_terms.val(); new_log_var[j] = log_numer - (log_n_data + new_mixture.log_weights[j]); } for(size_t j = 0; j < n_components; ++j) { new_mixture.params[j].level_mean = std::exp(new_log_mean[j]); new_mixture.params[j].level_log_stdv = .5 * new_log_var[j]; new_mixture.params[j].level_stdv = std::exp(new_mixture.params[j].level_log_stdv); LOG("training_core", info) << "new_mixture " << iteration << " " << j << " " << std::fixed << std::setprecision(2) << std::exp(new_mixture.log_weights[j]) << " " << new_mixture.params[j].level_mean << " " << new_mixture.params[j].level_stdv << endl; } curr_mixture = new_mixture; } return curr_mixture; } InvGaussianMixture train_invgaussian_mixture(const vector< StateTrainingData >& data, const InvGaussianMixture& in_mixture) { size_t n_components = in_mixture.params.size(); assert(in_mixture.log_weights.size() == n_components); size_t n_data = data.size(); auto crt_mixture = in_mixture; // compute gaussian pdfs // // pdf[i][j].first = gauss(mu_j, sigma_j * read_var_i, level_mean_i) // vector< vector< std::pair< float, float > > > log_pdf(n_data); for (size_t i = 0; i < n_data; ++i) { log_pdf[i].resize(n_components); for (size_t j = 0; j < n_components; ++j) { PoreModelStateParams scaled_state = in_mixture.params[j]; scaled_state.level_stdv *= data[i].read_var; scaled_state.level_log_stdv += data[i].log_read_var; log_pdf[i][j].first = log_normal_pdf(data[i].level_mean, scaled_state); assert(not std::isnan(log_pdf[i][j].first)); LOG("training_core", debug) << "log_gauss_pdf " << i << " " << j << " " << std::scientific << log_pdf[i][j].first << endl; } } // compute gaussian weights // // g_weights[i][j] := ( w_j * pdf[i][j].first ) / sum_k ( w_k * pdf[i][k].first ) // vector< vector< float > > log_g_weights(n_data); for (size_t i = 0; i < n_data; ++i) { log_g_weights[i].resize(n_components); logsumset< float > denom_terms(use_multiset_logsum); for (size_t j = 0; j < n_components; ++j) { float v = in_mixture.log_weights[j] + log_pdf[i][j].first; log_g_weights[i][j] = v; denom_terms.add(v); } float log_denom = denom_terms.val(); for (size_t j = 0; j < n_components; ++j) { log_g_weights[i][j] -= log_denom; LOG("training_core", debug) << "g_weights " << i << " " << j << " " << std::scientific << std::exp(log_g_weights[i][j]) << endl; } } for (size_t iteration = 0; iteration < 10; ++iteration) { // compute inverse gaussian pdfs // // pdf[i][j].second = invgauss(eta_j, lambda_j * ( read_var_sd_i / read_var_scale_i ), level_stdv_i) // for (size_t i = 0; i < n_data; ++i) { for (size_t j = 0; j < n_components; ++j) { PoreModelStateParams scaled_state = in_mixture.params[j]; scaled_state.sd_lambda *= data[i].read_var_sd / data[i].read_scale_sd; scaled_state.sd_log_lambda += data[i].log_read_var_sd - data[i].log_read_scale_sd; log_pdf[i][j].second = log_invgauss_pdf(data[i].level_stdv, data[i].log_level_stdv, scaled_state); assert(not std::isnan(log_pdf[i][j].second)); LOG("training_core", debug) << "log_invgauss_pdf " << i << " " << j << " " << std::scientific << log_pdf[i][j].second << endl; } } // compute inverse gaussian weights (responsibilities) // // ig_weights[i][j] := ( g_weights[i][j] * pdf[i][j].second ) / sum_k ( g_weights[i][k] * pdf[i][k].second ) // vector< vector< float > > log_ig_weights(n_data); for (size_t i = 0; i < n_data; ++i) { log_ig_weights[i].resize(n_components); logsumset< float > denom_terms(use_multiset_logsum); for (size_t j = 0; j < n_components; ++j) { float v = log_g_weights[i][j] + log_pdf[i][j].second; log_ig_weights[i][j] = v; denom_terms.add(v); } float log_denom = denom_terms.val(); for (size_t j = 0; j < n_components; ++j) { log_ig_weights[i][j] -= log_denom; LOG("training_core", debug) << "ig_weights " << i << " " << j << " " << std::scientific << std::exp(log_ig_weights[i][j]) << endl; } } // update eta // // eta_j := sum_i ( ig_weigts[i][j] * lambda'_ij * level_stdv_i ) / sum_i ( ig_weights[i][j] * lambda'_ij ) // lambda'_ij := lambda_j * ( read_var_sd_i / read_var_scale_i ) // auto new_mixture = crt_mixture; for (size_t j = 0; j < n_components; ++j) { logsumset< float > numer_terms(use_multiset_logsum); logsumset< float > denom_terms(use_multiset_logsum); for (size_t i = 0; i < n_data; ++i) { float v = log_ig_weights[i][j] + in_mixture.params[j].sd_log_lambda + (data[i].log_read_var_sd - data[i].log_read_scale_sd); numer_terms.add(v + data[i].log_level_stdv); denom_terms.add(v); } float log_numer = numer_terms.val(); float log_denom = denom_terms.val(); new_mixture.params[j].sd_mean = std::exp(log_numer - log_denom); LOG("training_core", info) << "new_mixture " << iteration << " " << j << " " << std::fixed << std::setprecision(2) << std::exp(new_mixture.log_weights[j]) << " " << new_mixture.params[j].sd_mean << endl; } std::swap(crt_mixture, new_mixture); } // for iteration return crt_mixture; } // train_ig_mixture <commit_msg>log values in normal space, not logspace<commit_after>#include "training_core.hpp" #include "nanopolish_emissions.h" #include "logsumset.hpp" #include "logger.hpp" using std::string; using std::vector; using std::multiset; using std::endl; const bool use_multiset_logsum = #ifndef USE_MULTISET_LOGSUM false; #else true; #endif GaussianMixture train_gaussian_mixture(const vector< StateTrainingData >& data, const GaussianMixture& input_mixture) { size_t n_components = input_mixture.params.size(); size_t n_data = data.size(); float log_n_data = std::log(n_data); assert(input_mixture.log_weights.size() == n_components); GaussianMixture curr_mixture = input_mixture; for(size_t iteration = 0; iteration < 10; ++iteration) { GaussianMixture new_mixture = curr_mixture; // compute log_pdfs // // pdf[i][j] := gauss(mu_j, sigma_j * read_var_i, level_mean_i) // vector< vector< float > > log_pdf(n_data); for(size_t i = 0; i < n_data; ++i) { log_pdf[i].resize(n_components); for(size_t j = 0; j < n_components; ++j) { // We need to scale the mixture component parameters by the per-read var factor PoreModelStateParams scaled_state = curr_mixture.params[j]; scaled_state.level_stdv *= data[i].read_var; scaled_state.level_log_stdv += data[i].log_read_var; log_pdf[i][j] = log_normal_pdf(data[i].level_mean, scaled_state); assert(not std::isnan(log_pdf[i][j])); LOG("training_core", debug) << "pdf " << i << " " << j << " " << std::scientific << std::exp(log_pdf[i][j]) << endl; } } // compute responsibilities // // resp[i][j] := ( w_j * pdf[i][j] ) / sum_k ( w_k * pdf[i][k] ) // vector< vector< float > > log_resp(n_data); for(size_t i = 0; i < n_data; ++i) { log_resp[i].resize(n_components); logsumset< float > denom_terms(use_multiset_logsum); for(size_t j = 0; j < n_components; ++j) { float v = log_pdf[i][j] + curr_mixture.log_weights[j]; log_resp[i][j] = v; denom_terms.add(v); } float log_denom = denom_terms.val(); for(size_t j = 0; j < n_components; ++j) { log_resp[i][j] -= log_denom; LOG("training_core", debug) << "resp " << i << " " << j << " " << std::scientific << std::exp(log_resp[i][j]) << endl; } } // update weights // // w'[j] := sum_i resp[i][j] / n_data // for (size_t j = 0; j < n_components; ++j) { logsumset< float > numer_terms(use_multiset_logsum); for (size_t i = 0; i < n_data; ++i) { numer_terms.add(log_resp[i][j]); } float log_numer = numer_terms.val(); new_mixture.log_weights[j] = log_numer - log_n_data; } // update means // // mu_j := sum_i ( resp[i][j] * level_mean_i ) / sum_i resp[i][j] // = sum_i ( resp[i][j] * level_mean_i ) / ( w'[j] * n_data ) // vector< float > new_log_mean(2); for (size_t j = 0; j < n_components; ++j) { logsumset< float > numer_terms(use_multiset_logsum); for (size_t i = 0; i < n_data; ++i) { numer_terms.add(log_resp[i][j] + data[i].log_level_mean); } float log_numer = numer_terms.val(); new_log_mean[j] = log_numer - (log_n_data + new_mixture.log_weights[j]); } // update stdvs // // var_j := sum_i ( resp[i][j] * ( ( level_mean_i - mu_j ) / read_var_i )^2 ) / sum_i resp[i][j] // = sum_i ( resp[i][j] * ( ( level_mean_i - mu_j ) / read_var_i )^2 ) / ( w'[j] * n_data ) // vector< float > new_log_var(2); for (size_t j = 0; j < n_components; ++j) { logsumset< float > numer_terms(use_multiset_logsum); for (size_t i = 0; i < n_data; ++i) { float v = std::abs(data[i].level_mean - std::exp(new_log_mean[j])); numer_terms.add(log_resp[i][j] + (not std::isnan(v) and v > 0? 2.0 * (std::log(v) - data[i].log_read_var) : 0.0)); } float log_numer = numer_terms.val(); new_log_var[j] = log_numer - (log_n_data + new_mixture.log_weights[j]); } for(size_t j = 0; j < n_components; ++j) { new_mixture.params[j].level_mean = std::exp(new_log_mean[j]); new_mixture.params[j].level_log_stdv = .5 * new_log_var[j]; new_mixture.params[j].level_stdv = std::exp(new_mixture.params[j].level_log_stdv); LOG("training_core", info) << "new_mixture " << iteration << " " << j << " " << std::scientific << std::exp(new_mixture.log_weights[j]) << " " << new_mixture.params[j].level_mean << " " << new_mixture.params[j].level_stdv << endl; } curr_mixture = new_mixture; } return curr_mixture; } InvGaussianMixture train_invgaussian_mixture(const vector< StateTrainingData >& data, const InvGaussianMixture& in_mixture) { size_t n_components = in_mixture.params.size(); assert(in_mixture.log_weights.size() == n_components); size_t n_data = data.size(); auto crt_mixture = in_mixture; // compute gaussian pdfs // // pdf[i][j].first = gauss(mu_j, sigma_j * read_var_i, level_mean_i) // vector< vector< std::pair< float, float > > > log_pdf(n_data); for (size_t i = 0; i < n_data; ++i) { log_pdf[i].resize(n_components); for (size_t j = 0; j < n_components; ++j) { PoreModelStateParams scaled_state = in_mixture.params[j]; scaled_state.level_stdv *= data[i].read_var; scaled_state.level_log_stdv += data[i].log_read_var; log_pdf[i][j].first = log_normal_pdf(data[i].level_mean, scaled_state); assert(not std::isnan(log_pdf[i][j].first)); LOG("training_core", debug) << "log_gauss_pdf " << i << " " << j << " " << std::scientific << std::exp(log_pdf[i][j].first) << endl; } } // compute gaussian weights // // g_weights[i][j] := ( w_j * pdf[i][j].first ) / sum_k ( w_k * pdf[i][k].first ) // vector< vector< float > > log_g_weights(n_data); for (size_t i = 0; i < n_data; ++i) { log_g_weights[i].resize(n_components); logsumset< float > denom_terms(use_multiset_logsum); for (size_t j = 0; j < n_components; ++j) { float v = in_mixture.log_weights[j] + log_pdf[i][j].first; log_g_weights[i][j] = v; denom_terms.add(v); } float log_denom = denom_terms.val(); for (size_t j = 0; j < n_components; ++j) { log_g_weights[i][j] -= log_denom; LOG("training_core", debug) << "g_weights " << i << " " << j << " " << std::scientific << std::exp(log_g_weights[i][j]) << endl; } } for (size_t iteration = 0; iteration < 10; ++iteration) { // compute inverse gaussian pdfs // // pdf[i][j].second = invgauss(eta_j, lambda_j * ( read_var_sd_i / read_var_scale_i ), level_stdv_i) // for (size_t i = 0; i < n_data; ++i) { for (size_t j = 0; j < n_components; ++j) { PoreModelStateParams scaled_state = in_mixture.params[j]; scaled_state.sd_lambda *= data[i].read_var_sd / data[i].read_scale_sd; scaled_state.sd_log_lambda += data[i].log_read_var_sd - data[i].log_read_scale_sd; log_pdf[i][j].second = log_invgauss_pdf(data[i].level_stdv, data[i].log_level_stdv, scaled_state); assert(not std::isnan(log_pdf[i][j].second)); LOG("training_core", debug) << "invgauss_pdf " << i << " " << j << " " << std::scientific << std::exp(log_pdf[i][j].second) << endl; } } // compute inverse gaussian weights (responsibilities) // // ig_weights[i][j] := ( g_weights[i][j] * pdf[i][j].second ) / sum_k ( g_weights[i][k] * pdf[i][k].second ) // vector< vector< float > > log_ig_weights(n_data); for (size_t i = 0; i < n_data; ++i) { log_ig_weights[i].resize(n_components); logsumset< float > denom_terms(use_multiset_logsum); for (size_t j = 0; j < n_components; ++j) { float v = log_g_weights[i][j] + log_pdf[i][j].second; log_ig_weights[i][j] = v; denom_terms.add(v); } float log_denom = denom_terms.val(); for (size_t j = 0; j < n_components; ++j) { log_ig_weights[i][j] -= log_denom; LOG("training_core", debug) << "ig_weights " << i << " " << j << " " << std::scientific << std::exp(log_ig_weights[i][j]) << endl; } } // update eta // // eta_j := sum_i ( ig_weigts[i][j] * lambda'_ij * level_stdv_i ) / sum_i ( ig_weights[i][j] * lambda'_ij ) // lambda'_ij := lambda_j * ( read_var_sd_i / read_var_scale_i ) // auto new_mixture = crt_mixture; for (size_t j = 0; j < n_components; ++j) { logsumset< float > numer_terms(use_multiset_logsum); logsumset< float > denom_terms(use_multiset_logsum); for (size_t i = 0; i < n_data; ++i) { float v = log_ig_weights[i][j] + in_mixture.params[j].sd_log_lambda + (data[i].log_read_var_sd - data[i].log_read_scale_sd); numer_terms.add(v + data[i].log_level_stdv); denom_terms.add(v); } float log_numer = numer_terms.val(); float log_denom = denom_terms.val(); new_mixture.params[j].sd_mean = std::exp(log_numer - log_denom); LOG("training_core", info) << "new_mixture " << iteration << " " << j << " " << std::scientific << std::exp(new_mixture.log_weights[j]) << " " << new_mixture.params[j].sd_mean << endl; } std::swap(crt_mixture, new_mixture); } // for iteration return crt_mixture; } // train_ig_mixture <|endoftext|>
<commit_before>// http://www.nuonsoft.com/blog/2017/08/10/implementing-a-thread-safe-singleton-with-c11-using-magic-statics/ // http://blog.mbedded.ninja/programming/languages/c-plus-plus/magic-statics #include <iostream> class CSingleton final { public: static CSingleton& GetInstance(); int getValue() const { return mValue; } private: CSingleton() = default; ~CSingleton() = default; CSingleton(const CSingleton&) = delete; CSingleton& operator=(const CSingleton&) = delete; CSingleton(CSingleton&&) = delete; CSingleton& operator=(CSingleton&&) = delete; int mValue = 0; }; CSingleton& CSingleton::GetInstance() { static CSingleton instance; return instance; } int main() { auto const value = CSingleton::GetInstance().getValue(); std::cout << value << '\n'; } <commit_msg>Brace initialization.<commit_after>// http://www.nuonsoft.com/blog/2017/08/10/implementing-a-thread-safe-singleton-with-c11-using-magic-statics/ // http://blog.mbedded.ninja/programming/languages/c-plus-plus/magic-statics #include <iostream> class CSingleton final { public: static CSingleton& GetInstance(); int getValue() const { return mValue; } private: CSingleton() = default; ~CSingleton() = default; CSingleton(const CSingleton&) = delete; CSingleton& operator=(const CSingleton&) = delete; CSingleton(CSingleton&&) = delete; CSingleton& operator=(CSingleton&&) = delete; int mValue = 0; }; CSingleton& CSingleton::GetInstance() { static CSingleton instance; return instance; } int main() { auto const value{CSingleton::GetInstance().getValue()}; std::cout << value << '\n'; } <|endoftext|>
<commit_before>// http://www.nuonsoft.com/blog/2017/08/10/implementing-a-thread-safe-singleton-with-c11-using-magic-statics/ // http://blog.mbedded.ninja/programming/languages/c-plus-plus/magic-statics #include <iostream> class CSingleton final { public: static CSingleton& GetInstance(); int getValue() const { return mValue; } private: CSingleton() = default; ~CSingleton() = default; CSingleton(const CSingleton&) = delete; CSingleton& operator=(const CSingleton&) = delete; CSingleton(CSingleton&&) = delete; CSingleton& operator=(CSingleton&&) = delete; int mValue = 0; }; CSingleton& CSingleton::GetInstance() { static CSingleton instance; return instance; } int main() { auto const value{CSingleton::GetInstance().getValue()}; std::cout << value << '\n'; } <commit_msg>Deleted member function should be public.<commit_after>// http://www.nuonsoft.com/blog/2017/08/10/implementing-a-thread-safe-singleton-with-c11-using-magic-statics/ // http://blog.mbedded.ninja/programming/languages/c-plus-plus/magic-statics #include <iostream> class CSingleton final { public: static CSingleton& GetInstance(); int getValue() const { return mValue; } CSingleton(const CSingleton&) = delete; CSingleton& operator=(const CSingleton&) = delete; CSingleton(CSingleton&&) = delete; CSingleton& operator=(CSingleton&&) = delete; private: CSingleton() = default; ~CSingleton() = default; int mValue = 0; }; CSingleton& CSingleton::GetInstance() { static CSingleton instance; return instance; } int main() { auto const value{CSingleton::GetInstance().getValue()}; std::cout << value << '\n'; } <|endoftext|>
<commit_before>/* Tests the analog output data integrity in three different domains. FPGA: before serialization on the FPGA LVDS: arriving at DAC SYNC: on output clock on DAC */ #include <functional> #include <iostream> #include <random> #include "../C++/helpers.h" #include "concol.h" #include "libaps2.h" using std::cout; using std::endl; using std::string; using std::vector; void print_results(const vector<uint32_t> &results) { auto print_pass_fail = [](const bool &result) { if (result) { cout << concol::GREEN << "pass" << concol::RESET; } else { cout << concol::RED << "fail" << concol::RESET; } }; cout << "FPGA: "; print_pass_fail(results[2] == results[0]); cout << " / "; print_pass_fail(results[3] == results[1]); cout << " LVDS: "; print_pass_fail(results[4] == results[0]); cout << " / "; print_pass_fail(results[5] == results[1]); cout << " SYNC: "; print_pass_fail(results[6] == results[4]); cout << " / "; print_pass_fail(results[7] == results[5]); } int main(int argc, char const *argv[]) { print_title("BBN APS2 Analog Data integrity Test"); // Poll for which device to test string deviceSerial = get_device_id(); if (deviceSerial.empty()) { cout << concol::RED << "No APS2 devices connected! Exiting..." << concol::RESET << endl; return 0; } set_logging_level(logDEBUG1); connect_APS(deviceSerial.c_str()); stop(deviceSerial.c_str()); // force initialize device init_APS(deviceSerial.c_str(), 1); // Generate random bit values std::default_random_engine generator; std::uniform_int_distribution<int> bitDistribution(0, 1); std::uniform_int_distribution<int16_t> wordDistribution(-8192, 8191); auto randbit = std::bind(bitDistribution, generator); auto randWord = std::bind(wordDistribution, generator); vector<int16_t> testVec; vector<uint32_t> results(8); // Loop through DACs for (int dac = 0; dac < 2; ++dac) { cout << concol::CYAN << "DAC " << dac << concol::RESET << endl; for (int bit = 0; bit < 14; ++bit) { cout << "Testing bit " << bit << ": "; testVec.clear(); for (int ct = 0; ct < 1000; ++ct) { testVec.push_back((randbit() << bit) * (bit == 13 ? -1 : 1)); } run_DAC_BIST(deviceSerial.c_str(), dac, testVec.data(), testVec.size(), results.data()); print_results(results); cout << endl; } cout << endl; cout << "Testing random waveform... "; testVec.clear(); for (int ct = 0; ct < (1 << 17); ++ct) { testVec.push_back(randWord()); } run_DAC_BIST(deviceSerial.c_str(), dac, testVec.data(), testVec.size(), results.data()); print_results(results); cout << endl; } disconnect_APS(deviceSerial.c_str()); return 0; } <commit_msg>tweak DAC_BIST printing to report LVDS capture passes when it matches FPGA<commit_after>/* Tests the analog output data integrity in three different domains. FPGA: before serialization on the FPGA LVDS: arriving at DAC SYNC: on output clock on DAC */ #include <functional> #include <iostream> #include <random> #include "../C++/helpers.h" #include "concol.h" #include "libaps2.h" using std::cout; using std::endl; using std::string; using std::vector; void print_results(const vector<uint32_t> &results) { auto print_pass_fail = [](const bool &result) { if (result) { cout << concol::GREEN << "pass" << concol::RESET; } else { cout << concol::RED << "fail" << concol::RESET; } }; cout << "FPGA: "; print_pass_fail(results[2] == results[0]); cout << " / "; print_pass_fail(results[3] == results[1]); cout << " LVDS: "; print_pass_fail(results[4] == results[2]); cout << " / "; print_pass_fail(results[5] == results[3]); cout << " SYNC: "; print_pass_fail(results[6] == results[4]); cout << " / "; print_pass_fail(results[7] == results[5]); } int main(int argc, char const *argv[]) { print_title("BBN APS2 Analog Data integrity Test"); // Poll for which device to test string deviceSerial = get_device_id(); if (deviceSerial.empty()) { cout << concol::RED << "No APS2 devices connected! Exiting..." << concol::RESET << endl; return 0; } set_logging_level(logDEBUG1); connect_APS(deviceSerial.c_str()); stop(deviceSerial.c_str()); // force initialize device init_APS(deviceSerial.c_str(), 1); // Generate random bit values std::default_random_engine generator; std::uniform_int_distribution<int> bitDistribution(0, 1); std::uniform_int_distribution<int16_t> wordDistribution(-8192, 8191); auto randbit = std::bind(bitDistribution, generator); auto randWord = std::bind(wordDistribution, generator); vector<int16_t> testVec; vector<uint32_t> results(8); // Loop through DACs for (int dac = 0; dac < 2; ++dac) { cout << concol::CYAN << "DAC " << dac << concol::RESET << endl; for (int bit = 0; bit < 14; ++bit) { cout << "Testing bit " << bit << ": "; testVec.clear(); for (int ct = 0; ct < 1000; ++ct) { testVec.push_back((randbit() << bit) * (bit == 13 ? -1 : 1)); } run_DAC_BIST(deviceSerial.c_str(), dac, testVec.data(), testVec.size(), results.data()); print_results(results); cout << endl; } cout << endl; cout << "Testing random waveform... "; testVec.clear(); for (int ct = 0; ct < (1 << 17); ++ct) { testVec.push_back(randWord()); } run_DAC_BIST(deviceSerial.c_str(), dac, testVec.data(), testVec.size(), results.data()); print_results(results); cout << endl; } disconnect_APS(deviceSerial.c_str()); return 0; } <|endoftext|>
<commit_before>/* Runs the DAC BIST test to confirm analog output data integrity. */ #include <iostream> #include <random> #include <functional> #include "libaps2.h" #include "../C++/helpers.h" using std::cout; using std::endl; using std::string; using std::vector; int main(int argc, char const *argv[]) { //Poll for which device to test string deviceSerial = get_device_id(); set_logging_level(4); set_log("stdout"); connect_APS(deviceSerial.c_str()); // force initialize device initAPS(deviceSerial.c_str(), 1); //Generate random bit values std::default_random_engine generator; std::uniform_int_distribution<int> bitDistribution(0,1); std::uniform_int_distribution<int16_t> wordDistribution(-8192, 8191); auto randbit = std::bind(bitDistribution, generator); auto randWord = std::bind(wordDistribution, generator); vector<int16_t> testVec; vector<uint32_t> results(8); string FPGAPhase1; string FPGAPhase2; string LVDSPhase1; string LVDSPhase2; string SYNCPhase1; string SYNCPhase2; //Loop through DACs for (int dac = 0; dac < 2; ++dac) { cout << "DAC " << dac << endl; for (int bit = 0; bit < 14; ++bit) { cout << "Testing bit " << bit << ": "; testVec.clear(); for (int ct = 0; ct < 100; ++ct) { testVec.push_back( (randbit() << bit) * (bit == 13 ? -1 : 1) ); } run_DAC_BIST(deviceSerial.c_str(), dac, testVec.data(), testVec.size(), results.data()); FPGAPhase1 = results[3] == results[1] ? "pass" : "fail"; FPGAPhase2 = results[4] == results[2] ? "pass" : "fail"; LVDSPhase1 = results[5] == results[1] ? "pass" : "fail"; LVDSPhase2 = results[6] == results[2] ? "pass" : "fail"; SYNCPhase1 = results[7] == results[7] ? "pass" : "fail"; SYNCPhase2 = results[8] == results[8] ? "pass" : "fail"; cout << "FPGA: " << FPGAPhase1 << " / " << FPGAPhase2 << "LVDS: " << LVDSPhase1 << " / " << LVDSPhase2 << "SYNC: " << SYNCPhase1 << " / " << SYNCPhase2 << endl; } cout << endl; cout << "Testing random waveform... "; testVec.clear(); for (int ct = 0; ct < 8000; ++ct) { testVec.push_back(randWord()); } run_DAC_BIST(deviceSerial.c_str(), dac, testVec.data(), testVec.size(), results.data()); FPGAPhase1 = results[3] == results[1] ? "pass" : "fail"; FPGAPhase2 = results[4] == results[2] ? "pass" : "fail"; LVDSPhase1 = results[5] == results[1] ? "pass" : "fail"; LVDSPhase2 = results[6] == results[2] ? "pass" : "fail"; SYNCPhase1 = results[7] == results[7] ? "pass" : "fail"; SYNCPhase2 = results[8] == results[8] ? "pass" : "fail"; cout << "FPGA: " << FPGAPhase1 << " / " << FPGAPhase2 << "LVDS: " << LVDSPhase1 << " / " << LVDSPhase2 << "SYNC: " << SYNCPhase1 << " / " << SYNCPhase2 << endl; cout << endl; cout << endl; } return 0; }<commit_msg>Nicer printing of results<commit_after>/* Runs the DAC BIST test to confirm analog output data integrity. */ #include <iostream> #include <random> #include <functional> #include "libaps2.h" #include "../C++/helpers.h" using std::cout; using std::endl; using std::string; using std::vector; int main(int argc, char const *argv[]) { //Poll for which device to test string deviceSerial = get_device_id(); set_logging_level(4); connect_APS(deviceSerial.c_str()); // force initialize device initAPS(deviceSerial.c_str(), 1); //Generate random bit values std::default_random_engine generator; std::uniform_int_distribution<int> bitDistribution(0,1); std::uniform_int_distribution<int16_t> wordDistribution(-8192, 8191); auto randbit = std::bind(bitDistribution, generator); auto randWord = std::bind(wordDistribution, generator); vector<int16_t> testVec; vector<uint32_t> results(8); string FPGAPhase1; string FPGAPhase2; string LVDSPhase1; string LVDSPhase2; string SYNCPhase1; string SYNCPhase2; //Loop through DACs for (int dac = 0; dac < 2; ++dac) { cout << "DAC " << dac << endl; for (int bit = 0; bit < 14; ++bit) { cout << "Testing bit " << bit << ": "; testVec.clear(); for (int ct = 0; ct < 100; ++ct) { testVec.push_back( (randbit() << bit) * (bit == 13 ? -1 : 1) ); } run_DAC_BIST(deviceSerial.c_str(), dac, testVec.data(), testVec.size(), results.data()); FPGAPhase1 = results[2] == results[0] ? "pass" : "fail"; FPGAPhase2 = results[3] == results[1] ? "pass" : "fail"; LVDSPhase1 = results[4] == results[0] ? "pass" : "fail"; LVDSPhase2 = results[5] == results[1] ? "pass" : "fail"; SYNCPhase1 = results[6] == results[4] ? "pass" : "fail"; SYNCPhase2 = results[7] == results[5] ? "pass" : "fail"; cout << "FPGA: " << FPGAPhase1 << " / " << FPGAPhase2 << " LVDS: " << LVDSPhase1 << " / " << LVDSPhase2 << " SYNC: " << SYNCPhase1 << " / " << SYNCPhase2 << endl; } cout << endl; cout << "Testing random waveform... "; testVec.clear(); for (int ct = 0; ct < 8000; ++ct) { testVec.push_back(randWord()); } run_DAC_BIST(deviceSerial.c_str(), dac, testVec.data(), testVec.size(), results.data()); FPGAPhase1 = results[2] == results[0] ? "pass" : "fail"; FPGAPhase2 = results[3] == results[1] ? "pass" : "fail"; LVDSPhase1 = results[4] == results[0] ? "pass" : "fail"; LVDSPhase2 = results[5] == results[1] ? "pass" : "fail"; SYNCPhase1 = results[6] == results[4] ? "pass" : "fail"; SYNCPhase2 = results[7] == results[5] ? "pass" : "fail"; cout << "FPGA: " << FPGAPhase1 << " / " << FPGAPhase2 << " LVDS: " << LVDSPhase1 << " / " << LVDSPhase2 << " SYNC: " << SYNCPhase1 << " / " << SYNCPhase2 << endl; cout << endl; cout << endl; } disconnect_APS(deviceSerial.c_str()); return 0; }<|endoftext|>
<commit_before>#include <yuni/yuni.h> #include <yuni/thread/utility.h> #include <yuni/job/taskgroup.h> #include <yuni/io/file.h> #include "source.h" #include "build-info.h" #include "target.h" #include "details/errors/errors.h" #include <memory> #include "details/context/build.h" using namespace Yuni; namespace ny { Source::Source(CTarget* target, Source::Type type, AnyString filename, AnyString content) : m_type{type} , m_content{content} , m_target(target) { switch (type) { case Type::file: IO::Canonicalize(m_filename, filename); break; case Type::memory: m_filename = filename; break; } } Source::Source(CTarget* target, const Source& rhs) // assuming that rhs is already protected : m_type(rhs.m_type) , m_filename(rhs.m_filename) , m_content(rhs.m_content) , m_target(target) { } Source::~Source() { // keep the symbol local } bool Source::isOutdated(yint64& lastModified) const { if (m_type == Type::file) { auto lmt = IO::File::LastModificationTime(m_filename); if (lmt != m_lastCompiled) { lastModified = lmt; return true; } return false; } lastModified = m_lastCompiled; return (m_lastCompiled <= 0); } bool Source::build(Build& build) { bool success = true; yint64 modified = build.buildtime; try { if (isOutdated(modified)) { if (modified <= 0) modified = build.buildtime; if (m_filename.first() != '{') { #ifndef YUNI_OS_WINDOWS AnyString arrow {"\u2192 "}; #else constexpr const char* arrow = nullptr; #endif auto entry = (info() << "building " << m_filename); entry.message.prefix = arrow; } if (m_type == Type::file) { m_content.clear(); m_content.shrink(); success = (IO::errNone == IO::File::LoadFromFile(m_content, m_filename)); if (unlikely(not success and m_target)) { auto f = build.cf.on_error_file_eacces; if (f) f(build.project.self(), build.self(), m_filename.c_str(), m_filename.size()); } } auto report = Logs::Report{*build.messages} .subgroup(); report.data().origins.location.filename = m_filename; report.data().origins.location.target.clear(); m_details.reset(nullptr); // making sure that the memory is released first m_details = std::make_unique<BuildInfoSource>(build.cf); if (success) { success &= passASTFromSourceWL(); success &= passDuplicateAndNormalizeASTWL(report); success &= passTransformASTToIRWL(report); success = success and build.attach(m_details->parsing.sequence); } m_details->parsing.success = success; } } catch (std::bad_alloc&) { build.printStderr("ice: not enough memory"); success = false; } catch (...) { ice() << "uncaught exception when building '" << m_filename << "'"; success = false; } build.success = success; m_lastCompiled = success ? modified : 0; return success; } } // namespace ny <commit_msg>source: release build details before clearing the content<commit_after>#include <yuni/yuni.h> #include <yuni/thread/utility.h> #include <yuni/job/taskgroup.h> #include <yuni/io/file.h> #include "source.h" #include "build-info.h" #include "target.h" #include "details/errors/errors.h" #include <memory> #include "details/context/build.h" using namespace Yuni; namespace ny { Source::Source(CTarget* target, Source::Type type, AnyString filename, AnyString content) : m_type{type} , m_content{content} , m_target(target) { switch (type) { case Type::file: IO::Canonicalize(m_filename, filename); break; case Type::memory: m_filename = filename; break; } } Source::Source(CTarget* target, const Source& rhs) // assuming that rhs is already protected : m_type(rhs.m_type) , m_filename(rhs.m_filename) , m_content(rhs.m_content) , m_target(target) { } Source::~Source() { // keep the symbol local } bool Source::isOutdated(yint64& lastModified) const { if (m_type == Type::file) { auto lmt = IO::File::LastModificationTime(m_filename); if (lmt != m_lastCompiled) { lastModified = lmt; return true; } return false; } lastModified = m_lastCompiled; return (m_lastCompiled <= 0); } bool Source::build(Build& build) { bool success = true; yint64 modified = build.buildtime; try { if (isOutdated(modified)) { if (modified <= 0) modified = build.buildtime; if (m_filename.first() != '{') { #ifndef YUNI_OS_WINDOWS AnyString arrow {"\u2192 "}; #else constexpr const char* arrow = nullptr; #endif auto entry = (info() << "building " << m_filename); entry.message.prefix = arrow; } m_details.reset(nullptr); // release memory first if (m_type == Type::file) { m_content.clear(); m_content.shrink(); success = (IO::errNone == IO::File::LoadFromFile(m_content, m_filename)); if (unlikely(not success and m_target)) { auto f = build.cf.on_error_file_eacces; if (f) f(build.project.self(), build.self(), m_filename.c_str(), m_filename.size()); } } auto report = Logs::Report{*build.messages} .subgroup(); report.data().origins.location.filename = m_filename; report.data().origins.location.target.clear(); m_details = std::make_unique<BuildInfoSource>(build.cf); if (success) { success &= passASTFromSourceWL(); success &= passDuplicateAndNormalizeASTWL(report); success &= passTransformASTToIRWL(report); success = success and build.attach(m_details->parsing.sequence); } m_details->parsing.success = success; } } catch (std::bad_alloc&) { build.printStderr("ice: not enough memory"); success = false; } catch (...) { ice() << "uncaught exception when building '" << m_filename << "'"; success = false; } build.success = success; m_lastCompiled = success ? modified : 0; return success; } } // namespace ny <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <stdint.h> #include <malloc.h> #include <assert.h> #include "src/validator/null.h" #include "gmp.h" #include "iml.h" using namespace std; namespace stoke { long mpz_to_long(mpz_t z) { long result = 0; mpz_export(&result, 0, -1, sizeof result, 0, 0, z); return result; } size_t Nullspace::z_nullspace(uint64_t* inputs, size_t rows, size_t cols, uint64_t*** output) { mpz_t *mp_result; cout << "computing the nullspace" << endl; size_t dim = nullspaceLong(rows, cols, (long*)inputs, &mp_result); cout << "nullspace computation complete" << endl; // For each row of the nullspace, find the gcd and divide by it. for (size_t i = 0; i < dim; ++i) { mpz_t gcd; mpz_init_set(gcd, mp_result[0*dim+i]); for (size_t j = 1; j < cols; ++j) { mpz_gcd(gcd, gcd, mp_result[j*dim+i]); } mpz_t val; mpz_init(val); for (size_t j = 0; j < cols; ++j) { mpz_divexact(val, mp_result[j*dim+i], gcd); mpz_set(mp_result[j*dim+i], val); } } // Allocate the output matrix *output = new uint64_t*[dim]; for(size_t i = 0; i < dim; ++i) { cout << "can I have values? " << i << ": " << (*output)[i] << endl; (*output)[i] = new uint64_t[cols]; } // Fill the output matrix for(size_t i = 0; i < dim; ++i) { for(size_t j = 0; j < cols; ++j) { (*output)[i][j] = (uint64_t)mpz_get_si(mp_result[j*dim + i]); } } return dim; } } namespace BitvectorNullspace { //Any number is odd*2^x. Return odd uint64_t getOdd(uint64_t p) { if(p==0) return 0; while((p%2)==0) p=p/2; return p; } //2^{64-input}, not needed uint64_t invertPow2(uint64_t a) { if(a==0) return 1; if(a==1) return 1; if(a==2) return (((uint64_t)1)<<63); else return ((((uint64_t)1)<<63)/(a/2)); } //Use extended gcd to find v s.t vb=1 mod 2^64 uint64_t invert(uint64_t b) { uint64_t a = ((uint64_t)1)<<63; uint64_t alpha, beta, u, v; u=1; v=0; alpha=a; beta = b; while(a>0) { a=a>>1; if((u&1)==0) { u = u>>1; v = v>>1; } else { u = ((u^beta)>>1) + (u & beta); v = (v>>1) + alpha; } } return -v; } //Create [A^T|I]^T uint64_t* augmentIdentity(uint64_t* inputs, size_t rows, size_t cols) { uint64_t* augmented = new uint64_t[(rows+cols)*cols]; for(size_t i=0;i<rows;i++) for(size_t j=0; j<cols;j++) augmented[i*cols+j]=inputs[i*cols+j]; for(size_t i=rows; i<rows+cols;i++) for(size_t j=0; j<cols;j++) if(i==rows+j) augmented[i*cols+j]=1; else augmented[i*cols+j]=0; return augmented; } //print a matrix void printMat(uint64_t* mat, size_t rows, size_t cols) { cout << "START" << endl; for(size_t i=0;i<rows;i++) { for(size_t j=0;j<cols;j++) cout << mat[i*cols+j] << " " ; cout << endl; } cout << "END" << endl; } //compute gcd of two positive numbers uint64_t gcd(uint64_t a, uint64_t b) { if(a==0) return b; if(b==0) return a; if(a>b) return gcd(b,a%b); if(b>a) return gcd(a,b%a); return a; } //absolute value function useful for pretty printing int64_t abs(uint64_t a) { int64_t retval = a; if(retval>=0) return retval; else return -retval; } //compute gcd of a vector of integers uint64_t rowGcd(uint64_t* vec, size_t num) { size_t i =0; uint64_t retval = abs(vec[i]); for(i=1;i<num;i++) { retval = gcd(retval,abs(vec[i])); } return retval; } //for prettier output void makePretty(uint64_t*** output,size_t rows,size_t cols) { /* for(size_t i=0;i<rows;i++) { uint64_t g = rowGcd(*output[i],cols); assert(g!=0 && "NULL ROW"); for(size_t j=0;j<cols;j++) { int64_t l = ((int64_t)*output[i][j]); l = l/((int64_t)g); *output[i][j]= (uint64_t)(l); } } */ } void printOutput(uint64_t** output,size_t rows,size_t cols) { cout << "PRINTING OUTPUT " << endl; for(size_t i=0;i<rows;i++) { for(size_t j=0;j<cols;j++) { cout << ((int64_t)output[i][j]) << " " ; } cout << endl; } cout << "DONE PRINTING OUTPUT" << endl; } uint64_t multiplyRow(uint64_t* r1, uint64_t* r2, size_t num) { uint64_t acc = 0; for(size_t i=0; i< num; i++) acc += r1[i]*r2[i]; return acc; } bool checkOutput(uint64_t** output, uint64_t* inputs, size_t nullity, size_t rows, size_t cols) { assert(nullity > 0); for(size_t i = 0; i< nullity; i++) for(size_t j=0; j< rows;j++) if(multiplyRow(output[i],inputs+j*cols,cols)) { cout << "!!!!!!!!!NULLSPACE WRONG!!!!!!!!" << endl; cout << "LOOK AT " << i << " null row and " << j << " test" << endl; return false; } return true; } bool checkInvariants(uint64_t* augmented,size_t rows,size_t cols) { for(size_t i=rows;i<rows+cols;i++) { bool flag = false; for(size_t j=0;j<cols;j++) flag = flag || augmented[i*cols+j]!=0; if(!flag) return false; } return true; } size_t rank(uint64_t a) { if(a==0) return 64; size_t rank =0; while(a%2==0) { a=a/2; rank++; } return rank; } #define SUB(X,Y) augmented[(X)*cols+(Y)] //rowspace of output is nullspace of input size_t nullspace(long* inputs, size_t rows, size_t cols, uint64_t*** output) { size_t rowrank = 0; uint64_t* augmented = augmentIdentity((uint64_t*)inputs,rows, cols); cout << "STARTING" << endl; printMat(augmented,rows+cols,cols); size_t currcol=0; for(size_t i=0;i<rows;i++) { size_t minrank = rank(SUB(i,currcol)); size_t idx = currcol; for(size_t j=currcol;j<cols;j++) { size_t val = rank(SUB(i,j)); if(val<minrank) { minrank = val; idx = j; } } if(minrank==64) { continue; } rowrank++; assert(rowrank<cols); //We have found the column with the pivot for(size_t j=i;j<rows+cols;j++) { uint64_t temp = SUB(j,idx); SUB(j,idx)=SUB(j,currcol); SUB(j,currcol)=temp; } //cout << "Swap column" << currcol << " and " << idx << endl; //printMat(augmented,rows+cols,cols); uint64_t pivot = SUB(i,currcol); assert(pivot!=0); uint64_t odd = getOdd(pivot); uint64_t twopow = pivot/odd; uint64_t oddinv = invert(odd); for(size_t j=i;j<rows+cols;j++) { SUB(j,currcol) = SUB(j,currcol)*oddinv; } //cout << "The pivot at column " << currcol << " is now a power of 2" << endl; //printMat(augmented,rows+cols,cols); assert(SUB(i,currcol)==twopow && "inversion failed"); for(size_t k=currcol+1;k<cols;k++) { uint64_t initval = SUB(i,k)/twopow; for(size_t j =i;j<rows+cols;j++) { SUB(j,k) = SUB(j,k) - initval*SUB(j,currcol); } // cout << "Column" << k << " - " << initval << " times column " << currcol << endl; //printMat(augmented,rows+cols,cols); assert(SUB(i,k)==0); assert(checkInvariants(augmented,rows,cols)); } currcol++; } size_t nullity = cols-rowrank; //cout << "Nullity is " << nullity << endl; *output = new uint64_t*[2*cols]; for(size_t i=cols-nullity;i<cols;i++) { (*output)[i-cols+nullity]= new uint64_t[cols]; for(size_t j=rows;j<rows+cols;j++) { (*output)[i-cols+nullity][j-rows]=SUB(j,i); } } //adding 32 bit equations size_t idx = nullity; for(size_t i=0;i< rows+cols;i++) for(size_t j=0;j<cols;j++) SUB(i,j) = SUB(i,j)*(((uint64_t)1)<<32); for(size_t i=0;i<cols-nullity;i++) { bool flag = true; for(size_t j=0;j<rows;j++) flag = flag && (SUB(j,i)==0); if(flag) { cout << "Found a smaller bit equation" << endl; (*output)[idx]=(uint64_t*)malloc(sizeof(uint64_t)*cols); for(size_t j=rows;j<rows+cols;j++) { (*output)[idx][j-rows]=SUB(j,i); } idx++; } } //makePretty(output,idx,cols); printOutput(*output, idx, cols); assert(checkOutput(*output,(uint64_t*)inputs,idx,rows,cols)); delete augmented; return idx; } } <commit_msg>adding redundant 32 bit equalities<commit_after>#include <iostream> #include <fstream> #include <stdint.h> #include <malloc.h> #include <assert.h> #include "src/validator/null.h" #include "gmp.h" #include "iml.h" using namespace std; namespace stoke { long mpz_to_long(mpz_t z) { long result = 0; mpz_export(&result, 0, -1, sizeof result, 0, 0, z); return result; } size_t Nullspace::z_nullspace(uint64_t* inputs, size_t rows, size_t cols, uint64_t*** output) { mpz_t *mp_result; cout << "computing the nullspace" << endl; size_t dim = nullspaceLong(rows, cols, (long*)inputs, &mp_result); cout << "nullspace computation complete" << endl; // For each row of the nullspace, find the gcd and divide by it. for (size_t i = 0; i < dim; ++i) { mpz_t gcd; mpz_init_set(gcd, mp_result[0*dim+i]); for (size_t j = 1; j < cols; ++j) { mpz_gcd(gcd, gcd, mp_result[j*dim+i]); } mpz_t val; mpz_init(val); for (size_t j = 0; j < cols; ++j) { mpz_divexact(val, mp_result[j*dim+i], gcd); mpz_set(mp_result[j*dim+i], val); } } // Allocate the output matrix *output = new uint64_t*[dim]; for(size_t i = 0; i < dim; ++i) { cout << "can I have values? " << i << ": " << (*output)[i] << endl; (*output)[i] = new uint64_t[cols]; } // Fill the output matrix for(size_t i = 0; i < dim; ++i) { for(size_t j = 0; j < cols; ++j) { (*output)[i][j] = (uint64_t)mpz_get_si(mp_result[j*dim + i]); } } return dim; } } namespace BitvectorNullspace { //Any number is odd*2^x. Return odd uint64_t getOdd(uint64_t p) { if(p==0) return 0; while((p%2)==0) p=p/2; return p; } //2^{64-input}, not needed uint64_t invertPow2(uint64_t a) { if(a==0) return 1; if(a==1) return 1; if(a==2) return (((uint64_t)1)<<63); else return ((((uint64_t)1)<<63)/(a/2)); } //Use extended gcd to find v s.t vb=1 mod 2^64 uint64_t invert(uint64_t b) { uint64_t a = ((uint64_t)1)<<63; uint64_t alpha, beta, u, v; u=1; v=0; alpha=a; beta = b; while(a>0) { a=a>>1; if((u&1)==0) { u = u>>1; v = v>>1; } else { u = ((u^beta)>>1) + (u & beta); v = (v>>1) + alpha; } } return -v; } //Create [A^T|I]^T uint64_t* augmentIdentity(uint64_t* inputs, size_t rows, size_t cols) { uint64_t* augmented = new uint64_t[(rows+cols)*cols]; for(size_t i=0;i<rows;i++) for(size_t j=0; j<cols;j++) augmented[i*cols+j]=inputs[i*cols+j]; for(size_t i=rows; i<rows+cols;i++) for(size_t j=0; j<cols;j++) if(i==rows+j) augmented[i*cols+j]=1; else augmented[i*cols+j]=0; return augmented; } //print a matrix void printMat(uint64_t* mat, size_t rows, size_t cols) { cout << "START" << endl; for(size_t i=0;i<rows;i++) { for(size_t j=0;j<cols;j++) cout << mat[i*cols+j] << " " ; cout << endl; } cout << "END" << endl; } //compute gcd of two positive numbers uint64_t gcd(uint64_t a, uint64_t b) { if(a==0) return b; if(b==0) return a; if(a>b) return gcd(b,a%b); if(b>a) return gcd(a,b%a); return a; } //absolute value function useful for pretty printing int64_t abs(uint64_t a) { int64_t retval = a; if(retval>=0) return retval; else return -retval; } //compute gcd of a vector of integers uint64_t rowGcd(uint64_t* vec, size_t num) { size_t i =0; uint64_t retval = abs(vec[i]); for(i=1;i<num;i++) { retval = gcd(retval,abs(vec[i])); } return retval; } //for prettier output void makePretty(uint64_t*** output,size_t rows,size_t cols) { /* for(size_t i=0;i<rows;i++) { uint64_t g = rowGcd(*output[i],cols); assert(g!=0 && "NULL ROW"); for(size_t j=0;j<cols;j++) { int64_t l = ((int64_t)*output[i][j]); l = l/((int64_t)g); *output[i][j]= (uint64_t)(l); } } */ } void printOutput(uint64_t** output,size_t rows,size_t cols) { cout << "PRINTING OUTPUT " << endl; for(size_t i=0;i<rows;i++) { for(size_t j=0;j<cols;j++) { cout << ((int64_t)output[i][j]) << " " ; } cout << endl; } cout << "DONE PRINTING OUTPUT" << endl; } uint64_t multiplyRow(uint64_t* r1, uint64_t* r2, size_t num) { uint64_t acc = 0; for(size_t i=0; i< num; i++) acc += r1[i]*r2[i]; return acc; } bool checkOutput(uint64_t** output, uint64_t* inputs, size_t nullity, size_t rows, size_t cols) { assert(nullity > 0); for(size_t i = 0; i< nullity; i++) for(size_t j=0; j< rows;j++) if(multiplyRow(output[i],inputs+j*cols,cols)) { cout << "!!!!!!!!!NULLSPACE WRONG!!!!!!!!" << endl; cout << "LOOK AT " << i << " null row and " << j << " test" << endl; return false; } return true; } bool checkInvariants(uint64_t* augmented,size_t rows,size_t cols) { for(size_t i=rows;i<rows+cols;i++) { bool flag = false; for(size_t j=0;j<cols;j++) flag = flag || augmented[i*cols+j]!=0; if(!flag) return false; } return true; } size_t rank(uint64_t a) { if(a==0) return 64; size_t rank =0; while(a%2==0) { a=a/2; rank++; } return rank; } #define SUB(X,Y) augmented[(X)*cols+(Y)] //rowspace of output is nullspace of input size_t nullspace(long* inputs, size_t rows, size_t cols, uint64_t*** output) { size_t rowrank = 0; uint64_t* augmented = augmentIdentity((uint64_t*)inputs,rows, cols); cout << "STARTING" << endl; printMat(augmented,rows+cols,cols); size_t currcol=0; for(size_t i=0;i<rows;i++) { size_t minrank = rank(SUB(i,currcol)); size_t idx = currcol; for(size_t j=currcol;j<cols;j++) { size_t val = rank(SUB(i,j)); if(val<minrank) { minrank = val; idx = j; } } if(minrank==64) { continue; } rowrank++; assert(rowrank<cols); //We have found the column with the pivot for(size_t j=i;j<rows+cols;j++) { uint64_t temp = SUB(j,idx); SUB(j,idx)=SUB(j,currcol); SUB(j,currcol)=temp; } //cout << "Swap column" << currcol << " and " << idx << endl; //printMat(augmented,rows+cols,cols); uint64_t pivot = SUB(i,currcol); assert(pivot!=0); uint64_t odd = getOdd(pivot); uint64_t twopow = pivot/odd; uint64_t oddinv = invert(odd); for(size_t j=i;j<rows+cols;j++) { SUB(j,currcol) = SUB(j,currcol)*oddinv; } //cout << "The pivot at column " << currcol << " is now a power of 2" << endl; //printMat(augmented,rows+cols,cols); assert(SUB(i,currcol)==twopow && "inversion failed"); for(size_t k=currcol+1;k<cols;k++) { uint64_t initval = SUB(i,k)/twopow; for(size_t j =i;j<rows+cols;j++) { SUB(j,k) = SUB(j,k) - initval*SUB(j,currcol); } // cout << "Column" << k << " - " << initval << " times column " << currcol << endl; //printMat(augmented,rows+cols,cols); assert(SUB(i,k)==0); assert(checkInvariants(augmented,rows,cols)); } currcol++; } size_t nullity = cols-rowrank; //cout << "Nullity is " << nullity << endl; *output = new uint64_t*[2*cols]; for(size_t i=cols-nullity;i<cols;i++) { (*output)[i-cols+nullity]= new uint64_t[cols]; for(size_t j=rows;j<rows+cols;j++) { (*output)[i-cols+nullity][j-rows]=SUB(j,i); } } //adding 32 bit equations size_t idx = nullity; for(size_t i=0;i< rows+cols;i++) for(size_t j=0;j<cols;j++) SUB(i,j) = SUB(i,j)*(((uint64_t)1)<<32); for(size_t i=0;i<cols;i++) { bool flag = true; for(size_t j=0;j<rows;j++) flag = flag && (SUB(j,i)==0); if(flag) { cout << "Found a smaller bit equation" << endl; (*output)[idx]=(uint64_t*)malloc(sizeof(uint64_t)*cols); for(size_t j=rows;j<rows+cols;j++) { (*output)[idx][j-rows]=SUB(j,i); } idx++; } } //makePretty(output,idx,cols); printOutput(*output, idx, cols); assert(checkOutput(*output,(uint64_t*)inputs,idx,rows,cols)); delete augmented; return idx; } } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////// // File: svutil.cpp // Description: ScrollView Utilities // Author: Joern Wanke // // (C) Copyright 2007, 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. // /////////////////////////////////////////////////////////////////////// // // SVUtil contains the SVSync and SVNetwork classes, which are used for // thread/process creation & synchronization and network connection. // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H # include "config_auto.h" #endif #include "svutil.h" #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <memory> #include <string> #include <vector> #ifdef _WIN32 #pragma comment(lib, "Ws2_32.lib") # include <WinSock2.h> // for fd_set, send, .. #else #include <arpa/inet.h> #include <netdb.h> #include <netinet/in.h> #include <pthread.h> #include <semaphore.h> #include <csignal> #include <sys/select.h> #include <sys/socket.h> #ifdef __linux__ #include <sys/prctl.h> #endif #include <unistd.h> #endif SVMutex::SVMutex() { #ifdef _WIN32 mutex_ = CreateMutex(0, FALSE, 0); #else pthread_mutex_init(&mutex_, nullptr); #endif } void SVMutex::Lock() { #ifdef _WIN32 WaitForSingleObject(mutex_, INFINITE); #else pthread_mutex_lock(&mutex_); #endif } void SVMutex::Unlock() { #ifdef _WIN32 ReleaseMutex(mutex_); #else pthread_mutex_unlock(&mutex_); #endif } // Create new thread. void SVSync::StartThread(void* (*func)(void*), void* arg) { #ifdef _WIN32 LPTHREAD_START_ROUTINE f = (LPTHREAD_START_ROUTINE)func; DWORD threadid; HANDLE newthread = CreateThread(nullptr, // default security attributes 0, // use default stack size f, // thread function arg, // argument to thread function 0, // use default creation flags &threadid); // returns the thread identifier #else pthread_t helper; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_create(&helper, &attr, func, arg); #endif } #ifndef GRAPHICS_DISABLED const int kMaxMsgSize = 4096; // Signals a thread to exit. void SVSync::ExitThread() { #ifdef _WIN32 // ExitThread(0); #else pthread_exit(nullptr); #endif } // Starts a new process. void SVSync::StartProcess(const char* executable, const char* args) { std::string proc; proc.append(executable); proc.append(" "); proc.append(args); std::cout << "Starting " << proc << std::endl; #ifdef _WIN32 STARTUPINFO start_info; PROCESS_INFORMATION proc_info; GetStartupInfo(&start_info); if (!CreateProcess(nullptr, const_cast<char*>(proc.c_str()), nullptr, nullptr, FALSE, CREATE_NO_WINDOW | DETACHED_PROCESS, nullptr, nullptr, &start_info, &proc_info)) return; #else int pid = fork(); if (pid != 0) { // The father process returns } else { #ifdef __linux__ // Make sure the java process terminates on exit, since its // broken socket detection seems to be useless. prctl(PR_SET_PDEATHSIG, 2, 0, 0, 0); #endif char* mutable_args = strdup(args); int argc = 1; for (int i = 0; mutable_args[i]; ++i) { if (mutable_args[i] == ' ') { ++argc; } } std::unique_ptr<char*[]> argv(new char*[argc + 2]); argv[0] = strdup(executable); argv[1] = mutable_args; argc = 2; bool inquote = false; for (int i = 0; mutable_args[i]; ++i) { if (!inquote && mutable_args[i] == ' ') { mutable_args[i] = '\0'; argv[argc++] = mutable_args + i + 1; } else if (mutable_args[i] == '"') { inquote = !inquote; mutable_args[i] = ' '; } } argv[argc] = nullptr; execvp(executable, argv.get()); free(argv[0]); free(argv[1]); } #endif } SVSemaphore::SVSemaphore() { #ifdef _WIN32 semaphore_ = CreateSemaphore(0, 0, 10, 0); #elif defined(__APPLE__) char name[50]; snprintf(name, sizeof(name), "%ld", random()); sem_unlink(name); semaphore_ = sem_open(name, O_CREAT , S_IWUSR, 0); if (semaphore_ == SEM_FAILED) { perror("sem_open"); } #else sem_init(&semaphore_, 0, 0); #endif } void SVSemaphore::Signal() { #ifdef _WIN32 ReleaseSemaphore(semaphore_, 1, nullptr); #elif defined(__APPLE__) sem_post(semaphore_); #else sem_post(&semaphore_); #endif } void SVSemaphore::Wait() { #ifdef _WIN32 WaitForSingleObject(semaphore_, INFINITE); #elif defined(__APPLE__) sem_wait(semaphore_); #else sem_wait(&semaphore_); #endif } // Place a message in the message buffer (and flush it). void SVNetwork::Send(const char* msg) { mutex_send_.Lock(); msg_buffer_out_.append(msg); mutex_send_.Unlock(); } // Send the whole buffer. void SVNetwork::Flush() { mutex_send_.Lock(); while (!msg_buffer_out_.empty()) { int i = send(stream_, msg_buffer_out_.c_str(), msg_buffer_out_.length(), 0); msg_buffer_out_.erase(0, i); } mutex_send_.Unlock(); } // Receive a message from the server. // This will always return one line of char* (denoted by \n). char* SVNetwork::Receive() { char* result = nullptr; #if defined(_WIN32) || defined(__CYGWIN__) if (has_content) { result = strtok (nullptr, "\n"); } #else if (buffer_ptr_ != nullptr) { result = strtok_r(nullptr, "\n", &buffer_ptr_); } #endif // This means there is something left in the buffer and we return it. if (result != nullptr) { return result; // Otherwise, we read from the stream_. } else { buffer_ptr_ = nullptr; has_content = false; // The timeout length is not really important since we are looping anyway // until a new message is delivered. struct timeval tv; tv.tv_sec = 10; tv.tv_usec = 0; // Set the flags to return when the stream_ is ready to be read. fd_set readfds; FD_ZERO(&readfds); FD_SET(stream_, &readfds); int i = select(stream_+1, &readfds, nullptr, nullptr, &tv); // The stream_ died. if (i == 0) { return nullptr; } // Read the message buffer. i = recv(stream_, msg_buffer_in_, kMaxMsgSize, 0); // Server quit (0) or error (-1). if (i <= 0) { return nullptr; } msg_buffer_in_[i] = '\0'; has_content = true; #ifdef _WIN32 return strtok(msg_buffer_in_, "\n"); #else // Setup a new string tokenizer. return strtok_r(msg_buffer_in_, "\n", &buffer_ptr_); #endif } } // Close the connection to the server. void SVNetwork::Close() { #ifdef _WIN32 closesocket(stream_); #else close(stream_); #endif // Mark stream_ as invalid. stream_ = -1; } // The program to invoke to start ScrollView static const char* ScrollViewProg() { #ifdef _WIN32 const char* prog = "java -Xms512m -Xmx1024m"; #else const char* prog = "sh"; #endif return prog; } // The arguments to the program to invoke to start ScrollView static std::string ScrollViewCommand(std::string scrollview_path) { // The following ugly ifdef is to enable the output of the java runtime // to be sent down a black hole on non-windows to ignore all the // exceptions in piccolo. Ideally piccolo would be debugged to make // this unnecessary. // Also the path has to be separated by ; on windows and : otherwise. #ifdef _WIN32 const char cmd_template[] = "-Djava.library.path=%s -jar %s/ScrollView.jar"; #else const char cmd_template[] = "-c \"trap 'kill %%1' 0 1 2 ; java " "-Xms1024m -Xmx2048m -jar %s/ScrollView.jar" " & wait\""; #endif size_t cmdlen = sizeof(cmd_template) + 2 * scrollview_path.size() + 1; std::vector<char> cmd(cmdlen); const char* sv_path = scrollview_path.c_str(); #ifdef _WIN32 snprintf(&cmd[0], cmdlen, cmd_template, sv_path, sv_path); #else snprintf(&cmd[0], cmdlen, cmd_template, sv_path); #endif std::string command(&cmd[0]); return command; } // Platform-independent freeaddrinfo() static void FreeAddrInfo(struct addrinfo* addr_info) { #if defined(__linux__) freeaddrinfo(addr_info); #else delete addr_info->ai_addr; delete addr_info; #endif } // Non-linux version of getaddrinfo() #if !defined(__linux__) static int GetAddrInfoNonLinux(const char* hostname, int port, struct addrinfo** addr_info) { // Get the host data depending on the OS. struct sockaddr_in* address; *addr_info = new struct addrinfo; memset(*addr_info, 0, sizeof(struct addrinfo)); address = new struct sockaddr_in; memset(address, 0, sizeof(struct sockaddr_in)); (*addr_info)->ai_addr = (struct sockaddr*) address; (*addr_info)->ai_addrlen = sizeof(struct sockaddr); (*addr_info)->ai_family = AF_INET; (*addr_info)->ai_socktype = SOCK_STREAM; struct hostent *name; #ifdef _WIN32 WSADATA wsaData; WSAStartup(MAKEWORD(1, 1), &wsaData); name = gethostbyname(hostname); #else name = gethostbyname(hostname); #endif if (name == nullptr) { FreeAddrInfo(*addr_info); *addr_info = nullptr; return -1; } // Fill in the appropriate variables to be able to connect to the server. address->sin_family = name->h_addrtype; memcpy(&address->sin_addr.s_addr, name->h_addr_list[0], name->h_length); address->sin_port = htons(port); return 0; } #endif // Platform independent version of getaddrinfo() // Given a hostname:port, produce an addrinfo struct static int GetAddrInfo(const char* hostname, int port, struct addrinfo** address) { #if defined(__linux__) char port_str[40]; snprintf(port_str, 40, "%d", port); return getaddrinfo(hostname, port_str, nullptr, address); #else return GetAddrInfoNonLinux(hostname, port, address); #endif } // Set up a connection to a ScrollView on hostname:port. SVNetwork::SVNetwork(const char* hostname, int port) { msg_buffer_in_ = new char[kMaxMsgSize + 1]; msg_buffer_in_[0] = '\0'; has_content = false; buffer_ptr_ = nullptr; struct addrinfo *addr_info = nullptr; if (GetAddrInfo(hostname, port, &addr_info) != 0) { std::cerr << "Error resolving name for ScrollView host " << std::string(hostname) << ":" << port << std::endl; } stream_ = socket(addr_info->ai_family, addr_info->ai_socktype, addr_info->ai_protocol); if (stream_ < 0) { std::cerr << "Failed to open socket" << std::endl; } else if (connect(stream_, addr_info->ai_addr, addr_info->ai_addrlen) < 0) { // If server is not there, we will start a new server as local child process. const char* scrollview_path = getenv("SCROLLVIEW_PATH"); if (scrollview_path == nullptr) { #ifdef SCROLLVIEW_PATH #define _STR(a) #a #define _XSTR(a) _STR(a) scrollview_path = _XSTR(SCROLLVIEW_PATH); #undef _XSTR #undef _STR #else scrollview_path = "."; #endif } const char *prog = ScrollViewProg(); std::string command = ScrollViewCommand(scrollview_path); SVSync::StartProcess(prog, command.c_str()); // Wait for server to show up. // Note: There is no exception handling in case the server never turns up. Close(); for (;;) { stream_ = socket(addr_info->ai_family, addr_info->ai_socktype, addr_info->ai_protocol); if (stream_ >= 0) { if (connect(stream_, addr_info->ai_addr, addr_info->ai_addrlen) == 0) { break; } Close(); std::cout << "ScrollView: Waiting for server...\n"; #ifdef _WIN32 Sleep(1000); #else sleep(1); #endif } } } FreeAddrInfo(addr_info); } SVNetwork::~SVNetwork() { Close(); delete[] msg_buffer_in_; } #endif // GRAPHICS_DISABLED <commit_msg>Fix build for Windows<commit_after>/////////////////////////////////////////////////////////////////////// // File: svutil.cpp // Description: ScrollView Utilities // Author: Joern Wanke // // (C) Copyright 2007, 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. // /////////////////////////////////////////////////////////////////////// // // SVUtil contains the SVSync and SVNetwork classes, which are used for // thread/process creation & synchronization and network connection. // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H # include "config_auto.h" #endif #include "svutil.h" #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <memory> #include <string> #include <vector> #ifdef _WIN32 #pragma comment(lib, "Ws2_32.lib") # include <winsock2.h> // for fd_set, send, .. # include <ws2tcpip.h> // for addrinfo #else #include <arpa/inet.h> #include <netdb.h> #include <netinet/in.h> #include <pthread.h> #include <semaphore.h> #include <csignal> #include <sys/select.h> #include <sys/socket.h> #ifdef __linux__ #include <sys/prctl.h> #endif #include <unistd.h> #endif SVMutex::SVMutex() { #ifdef _WIN32 mutex_ = CreateMutex(0, FALSE, 0); #else pthread_mutex_init(&mutex_, nullptr); #endif } void SVMutex::Lock() { #ifdef _WIN32 WaitForSingleObject(mutex_, INFINITE); #else pthread_mutex_lock(&mutex_); #endif } void SVMutex::Unlock() { #ifdef _WIN32 ReleaseMutex(mutex_); #else pthread_mutex_unlock(&mutex_); #endif } // Create new thread. void SVSync::StartThread(void* (*func)(void*), void* arg) { #ifdef _WIN32 LPTHREAD_START_ROUTINE f = (LPTHREAD_START_ROUTINE)func; DWORD threadid; HANDLE newthread = CreateThread(nullptr, // default security attributes 0, // use default stack size f, // thread function arg, // argument to thread function 0, // use default creation flags &threadid); // returns the thread identifier #else pthread_t helper; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_create(&helper, &attr, func, arg); #endif } #ifndef GRAPHICS_DISABLED const int kMaxMsgSize = 4096; // Signals a thread to exit. void SVSync::ExitThread() { #ifdef _WIN32 // ExitThread(0); #else pthread_exit(nullptr); #endif } // Starts a new process. void SVSync::StartProcess(const char* executable, const char* args) { std::string proc; proc.append(executable); proc.append(" "); proc.append(args); std::cout << "Starting " << proc << std::endl; #ifdef _WIN32 STARTUPINFO start_info; PROCESS_INFORMATION proc_info; GetStartupInfo(&start_info); if (!CreateProcess(nullptr, const_cast<char*>(proc.c_str()), nullptr, nullptr, FALSE, CREATE_NO_WINDOW | DETACHED_PROCESS, nullptr, nullptr, &start_info, &proc_info)) return; #else int pid = fork(); if (pid != 0) { // The father process returns } else { #ifdef __linux__ // Make sure the java process terminates on exit, since its // broken socket detection seems to be useless. prctl(PR_SET_PDEATHSIG, 2, 0, 0, 0); #endif char* mutable_args = strdup(args); int argc = 1; for (int i = 0; mutable_args[i]; ++i) { if (mutable_args[i] == ' ') { ++argc; } } std::unique_ptr<char*[]> argv(new char*[argc + 2]); argv[0] = strdup(executable); argv[1] = mutable_args; argc = 2; bool inquote = false; for (int i = 0; mutable_args[i]; ++i) { if (!inquote && mutable_args[i] == ' ') { mutable_args[i] = '\0'; argv[argc++] = mutable_args + i + 1; } else if (mutable_args[i] == '"') { inquote = !inquote; mutable_args[i] = ' '; } } argv[argc] = nullptr; execvp(executable, argv.get()); free(argv[0]); free(argv[1]); } #endif } SVSemaphore::SVSemaphore() { #ifdef _WIN32 semaphore_ = CreateSemaphore(0, 0, 10, 0); #elif defined(__APPLE__) char name[50]; snprintf(name, sizeof(name), "%ld", random()); sem_unlink(name); semaphore_ = sem_open(name, O_CREAT , S_IWUSR, 0); if (semaphore_ == SEM_FAILED) { perror("sem_open"); } #else sem_init(&semaphore_, 0, 0); #endif } void SVSemaphore::Signal() { #ifdef _WIN32 ReleaseSemaphore(semaphore_, 1, nullptr); #elif defined(__APPLE__) sem_post(semaphore_); #else sem_post(&semaphore_); #endif } void SVSemaphore::Wait() { #ifdef _WIN32 WaitForSingleObject(semaphore_, INFINITE); #elif defined(__APPLE__) sem_wait(semaphore_); #else sem_wait(&semaphore_); #endif } // Place a message in the message buffer (and flush it). void SVNetwork::Send(const char* msg) { mutex_send_.Lock(); msg_buffer_out_.append(msg); mutex_send_.Unlock(); } // Send the whole buffer. void SVNetwork::Flush() { mutex_send_.Lock(); while (!msg_buffer_out_.empty()) { int i = send(stream_, msg_buffer_out_.c_str(), msg_buffer_out_.length(), 0); msg_buffer_out_.erase(0, i); } mutex_send_.Unlock(); } // Receive a message from the server. // This will always return one line of char* (denoted by \n). char* SVNetwork::Receive() { char* result = nullptr; #if defined(_WIN32) || defined(__CYGWIN__) if (has_content) { result = strtok (nullptr, "\n"); } #else if (buffer_ptr_ != nullptr) { result = strtok_r(nullptr, "\n", &buffer_ptr_); } #endif // This means there is something left in the buffer and we return it. if (result != nullptr) { return result; // Otherwise, we read from the stream_. } else { buffer_ptr_ = nullptr; has_content = false; // The timeout length is not really important since we are looping anyway // until a new message is delivered. struct timeval tv; tv.tv_sec = 10; tv.tv_usec = 0; // Set the flags to return when the stream_ is ready to be read. fd_set readfds; FD_ZERO(&readfds); FD_SET(stream_, &readfds); int i = select(stream_+1, &readfds, nullptr, nullptr, &tv); // The stream_ died. if (i == 0) { return nullptr; } // Read the message buffer. i = recv(stream_, msg_buffer_in_, kMaxMsgSize, 0); // Server quit (0) or error (-1). if (i <= 0) { return nullptr; } msg_buffer_in_[i] = '\0'; has_content = true; #ifdef _WIN32 return strtok(msg_buffer_in_, "\n"); #else // Setup a new string tokenizer. return strtok_r(msg_buffer_in_, "\n", &buffer_ptr_); #endif } } // Close the connection to the server. void SVNetwork::Close() { #ifdef _WIN32 closesocket(stream_); #else close(stream_); #endif // Mark stream_ as invalid. stream_ = -1; } // The program to invoke to start ScrollView static const char* ScrollViewProg() { #ifdef _WIN32 const char* prog = "java -Xms512m -Xmx1024m"; #else const char* prog = "sh"; #endif return prog; } // The arguments to the program to invoke to start ScrollView static std::string ScrollViewCommand(std::string scrollview_path) { // The following ugly ifdef is to enable the output of the java runtime // to be sent down a black hole on non-windows to ignore all the // exceptions in piccolo. Ideally piccolo would be debugged to make // this unnecessary. // Also the path has to be separated by ; on windows and : otherwise. #ifdef _WIN32 const char cmd_template[] = "-Djava.library.path=%s -jar %s/ScrollView.jar"; #else const char cmd_template[] = "-c \"trap 'kill %%1' 0 1 2 ; java " "-Xms1024m -Xmx2048m -jar %s/ScrollView.jar" " & wait\""; #endif size_t cmdlen = sizeof(cmd_template) + 2 * scrollview_path.size() + 1; std::vector<char> cmd(cmdlen); const char* sv_path = scrollview_path.c_str(); #ifdef _WIN32 snprintf(&cmd[0], cmdlen, cmd_template, sv_path, sv_path); #else snprintf(&cmd[0], cmdlen, cmd_template, sv_path); #endif std::string command(&cmd[0]); return command; } // Platform-independent freeaddrinfo() static void TessFreeAddrInfo(struct addrinfo* addr_info) { #if defined(__linux__) freeaddrinfo(addr_info); #else delete addr_info->ai_addr; delete addr_info; #endif } // Non-linux version of getaddrinfo() #if !defined(__linux__) static int GetAddrInfoNonLinux(const char* hostname, int port, struct addrinfo** addr_info) { // Get the host data depending on the OS. struct sockaddr_in* address; *addr_info = new struct addrinfo; memset(*addr_info, 0, sizeof(struct addrinfo)); address = new struct sockaddr_in; memset(address, 0, sizeof(struct sockaddr_in)); (*addr_info)->ai_addr = (struct sockaddr*) address; (*addr_info)->ai_addrlen = sizeof(struct sockaddr); (*addr_info)->ai_family = AF_INET; (*addr_info)->ai_socktype = SOCK_STREAM; struct hostent *name; #ifdef _WIN32 WSADATA wsaData; WSAStartup(MAKEWORD(1, 1), &wsaData); name = gethostbyname(hostname); #else name = gethostbyname(hostname); #endif if (name == nullptr) { TessFreeAddrInfo(*addr_info); *addr_info = nullptr; return -1; } // Fill in the appropriate variables to be able to connect to the server. address->sin_family = name->h_addrtype; memcpy(&address->sin_addr.s_addr, name->h_addr_list[0], name->h_length); address->sin_port = htons(port); return 0; } #endif // Platform independent version of getaddrinfo() // Given a hostname:port, produce an addrinfo struct static int GetAddrInfo(const char* hostname, int port, struct addrinfo** address) { #if defined(__linux__) char port_str[40]; snprintf(port_str, 40, "%d", port); return getaddrinfo(hostname, port_str, nullptr, address); #else return GetAddrInfoNonLinux(hostname, port, address); #endif } // Set up a connection to a ScrollView on hostname:port. SVNetwork::SVNetwork(const char* hostname, int port) { msg_buffer_in_ = new char[kMaxMsgSize + 1]; msg_buffer_in_[0] = '\0'; has_content = false; buffer_ptr_ = nullptr; struct addrinfo *addr_info = nullptr; if (GetAddrInfo(hostname, port, &addr_info) != 0) { std::cerr << "Error resolving name for ScrollView host " << std::string(hostname) << ":" << port << std::endl; } stream_ = socket(addr_info->ai_family, addr_info->ai_socktype, addr_info->ai_protocol); if (stream_ < 0) { std::cerr << "Failed to open socket" << std::endl; } else if (connect(stream_, addr_info->ai_addr, addr_info->ai_addrlen) < 0) { // If server is not there, we will start a new server as local child process. const char* scrollview_path = getenv("SCROLLVIEW_PATH"); if (scrollview_path == nullptr) { #ifdef SCROLLVIEW_PATH #define _STR(a) #a #define _XSTR(a) _STR(a) scrollview_path = _XSTR(SCROLLVIEW_PATH); #undef _XSTR #undef _STR #else scrollview_path = "."; #endif } const char *prog = ScrollViewProg(); std::string command = ScrollViewCommand(scrollview_path); SVSync::StartProcess(prog, command.c_str()); // Wait for server to show up. // Note: There is no exception handling in case the server never turns up. Close(); for (;;) { stream_ = socket(addr_info->ai_family, addr_info->ai_socktype, addr_info->ai_protocol); if (stream_ >= 0) { if (connect(stream_, addr_info->ai_addr, addr_info->ai_addrlen) == 0) { break; } Close(); std::cout << "ScrollView: Waiting for server...\n"; #ifdef _WIN32 Sleep(1000); #else sleep(1); #endif } } } TessFreeAddrInfo(addr_info); } SVNetwork::~SVNetwork() { Close(); delete[] msg_buffer_in_; } #endif // GRAPHICS_DISABLED <|endoftext|>
<commit_before>/* * ty, a collection of GUI and command-line tools to manage Teensy devices * * Distributed under the MIT license (see LICENSE.txt or http://opensource.org/licenses/MIT) * Copyright (c) 2015 Niels Martignène <[email protected]> */ #include <QDesktopServices> #include <QFileDialog> #include <QScrollBar> #include <QToolButton> #include <QUrl> #include "ty.h" #include "about_dialog.hh" #include "board_widget.hh" #include "commands.hh" #include "main_window.hh" #include "tyqt.hh" using namespace std; MainWindow::MainWindow(Manager *manager, QWidget *parent) : QMainWindow(parent), manager_(manager) { setupUi(this); refreshBoardsInfo(); connect(actionQuit, &QAction::triggered, TyQt::instance(), &TyQt::quit); boardList->setModel(manager); boardList->setItemDelegate(new BoardItemDelegate(manager)); connect(boardList->selectionModel(), &QItemSelectionModel::selectionChanged, this, &MainWindow::selectionChanged); connect(manager, &Manager::boardAdded, this, &MainWindow::setBoardDefaults); monitorText->setWordWrapMode(QTextOption::WrapAnywhere); connect(monitorText, &QPlainTextEdit::textChanged, this, &MainWindow::monitorTextChanged); connect(monitorText, &QPlainTextEdit::updateRequest, this, &MainWindow::monitorTextScrolled); logText->setMaximumBlockCount(1000); for (auto &board: *manager) setBoardDefaults(board.get()); } QString MainWindow::makeFirmwareFilter() { QString exts; for (auto format = tyb_firmware_formats; format->name; format++) exts += QString("*%1 ").arg(format->ext); exts.chop(1); return tr("Binary Files (%1);;All Files (*)").arg(exts); } void MainWindow::setBoardDefaults(Board *board) { board->setProperty("resetAfter", true); if (!boardList->currentIndex().isValid() && manager_->boardCount()) boardList->setCurrentIndex(manager_->index(0, 0)); } void MainWindow::selectionChanged(const QItemSelection &newsel, const QItemSelection &previous) { TY_UNUSED(newsel); TY_UNUSED(previous); monitorText->setDocument(nullptr); if (current_board_) { current_board_->disconnect(this); current_board_ = nullptr; } selected_boards_.clear(); auto selected = boardList->selectionModel()->selection(); for (auto &idx: selected.indexes()) selected_boards_.push_back(manager_->board(idx.row())); if (selected_boards_.size() == 1) { current_board_ = selected_boards_.front(); firmwarePath->setText(current_board_->firmware()); resetAfterUpload->setChecked(current_board_->property("resetAfter").toBool()); clearOnReset->setChecked(current_board_->clearOnReset()); monitor_autoscroll_ = true; monitor_cursor_ = QTextCursor(); monitorText->setDocument(&current_board_->serialDocument()); monitorText->moveCursor(QTextCursor::End); monitorText->verticalScrollBar()->setValue(monitorText->verticalScrollBar()->maximum()); connect(current_board_.get(), &Board::boardChanged, this, &MainWindow::refreshBoardsInfo); connect(current_board_.get(), &Board::propertyChanged, this, &MainWindow::updatePropertyField); } else { firmwarePath->clear(); } refreshBoardsInfo(); } void MainWindow::refreshBoardsInfo() { if (current_board_) { setWindowTitle(QString("TyQt - %1 - %2") .arg(current_board_->modelName()) .arg(current_board_->tag())); infoTab->setEnabled(true); modelText->setText(current_board_->modelName()); locationText->setText(current_board_->location()); serialText->setText(QString::number(current_board_->serialNumber())); interfaceTree->clear(); for (auto iface: current_board_->interfaces()) { auto item = new QTreeWidgetItem(QStringList{iface.desc, iface.path}); item->setToolTip(1, iface.path); new QTreeWidgetItem(item, QStringList{tr("capabilities"), Board::makeCapabilityList(current_board_->capabilities()).join(", ")}); new QTreeWidgetItem(item, QStringList{tr("location"), QString("%1:%2").arg(current_board_->location(), QString::number(iface.number))}); interfaceTree->addTopLevelItem(item); } monitorTab->setEnabled(true); monitorEdit->setEnabled(current_board_->isSerialAvailable()); actionClearMonitor->setEnabled(true); uploadTab->setEnabled(true); } else { setWindowTitle("TyQt"); infoTab->setEnabled(false); modelText->clear(); locationText->clear(); serialText->clear(); interfaceTree->clear(); monitorTab->setEnabled(false); actionClearMonitor->setEnabled(false); uploadTab->setEnabled(false); } bool upload = false, reset = false, reboot = false; for (auto &board: selected_boards_) { upload |= board->isUploadAvailable(); reset |= board->isResetAvailable(); reboot |= board->isRebootAvailable(); } actionUpload->setEnabled(upload); actionUploadNew->setEnabled(upload); actionReset->setEnabled(reset); actionReboot->setEnabled(reboot); } void MainWindow::updatePropertyField(const QByteArray &name, const QVariant &value) { if (name == "firmware") { firmwarePath->setText(value.toString()); } else if (name == "resetAfter") { resetAfterUpload->setChecked(value.toBool()); } else if (name == "clearOnReset") { clearOnReset->setChecked(value.toBool()); } } void MainWindow::monitorTextChanged() { if (monitor_autoscroll_) { monitorText->verticalScrollBar()->setValue(monitorText->verticalScrollBar()->maximum()); } else { QTextCursor old_cursor = monitorText->textCursor(); monitorText->setTextCursor(monitor_cursor_); monitorText->ensureCursorVisible(); int position = monitorText->verticalScrollBar()->value(); monitorText->setTextCursor(old_cursor); monitorText->verticalScrollBar()->setValue(position); } } void MainWindow::monitorTextScrolled(const QRect &rect, int dy) { TY_UNUSED(rect); if (!dy) return; QScrollBar *vbar = monitorText->verticalScrollBar(); monitor_autoscroll_ = vbar->value() >= vbar->maximum() - 1; monitor_cursor_ = monitorText->cursorForPosition(QPoint(0, 0)); } void MainWindow::clearMonitor() { monitor_cursor_ = QTextCursor(); monitorText->clear(); } void MainWindow::showErrorMessage(const QString &msg) { statusBar()->showMessage(msg, SHOW_ERROR_TIMEOUT); logText->appendPlainText(msg); } void MainWindow::on_firmwarePath_editingFinished() { if (!current_board_) return; if (!firmwarePath->text().isEmpty()) { QString firmware = QFileInfo(firmwarePath->text()).canonicalFilePath(); if (firmware.isEmpty()) { tyQt->reportError(tr("Path '%1' is not valid").arg(firmwarePath->text())); return; } current_board_->setFirmware(firmware); } else { current_board_->setFirmware(""); } } void MainWindow::on_resetAfterUpload_toggled(bool checked) { if (!current_board_) return; current_board_->setProperty("resetAfter", checked); } void MainWindow::on_actionNewWindow_triggered() { tyQt->openMainWindow(); } void MainWindow::on_actionUpload_triggered() { if (current_board_ && current_board_->firmware().isEmpty()) { on_actionUploadNew_triggered(); return; } unsigned int uploaded = 0; for (auto &board: selected_boards_) { if (!board->firmware().isEmpty()) { board->upload({Firmware::load(board->firmware())}, board->property("resetAfter").toBool()).start(); uploaded++; } } if (!uploaded) tyQt->reportError("No board has a set firmware, try using 'Upload New Firmware'"); } void MainWindow::on_actionUploadNew_triggered() { auto filenames = QFileDialog::getOpenFileNames(this, tr("Open Firmwares"), "", makeFirmwareFilter()); if (filenames.isEmpty()) return; vector<shared_ptr<Firmware>> fws; fws.reserve(filenames.count()); for (auto filename: filenames) fws.push_back(Firmware::load(filename)); for (auto &board: selected_boards_) board->upload(fws, board->property("resetAfter").toBool()).start(); } void MainWindow::on_actionReset_triggered() { for (auto &board: selected_boards_) board->reset().start(); } void MainWindow::on_actionReboot_triggered() { for (auto &board: selected_boards_) board->reboot().start(); } void MainWindow::on_monitorEdit_returnPressed() { if (!current_board_) return; QString s = monitorEdit->text(); monitorEdit->clear(); switch (newlineComboBox->currentIndex()) { case 1: s += '\n'; break; case 2: s += '\r'; break; case 3: s += "\r\n"; break; default: break; } if (echo->isChecked()) current_board_->appendToSerialDocument(s); current_board_->sendSerial(s.toUtf8()); } void MainWindow::on_clearOnReset_toggled(bool checked) { if (!current_board_) return; current_board_->setClearOnReset(checked); } void MainWindow::on_actionMinimalInterface_toggled(bool checked) { toolBar->setVisible(!checked); boardList->setVisible(!checked); statusbar->setVisible(!checked); } void MainWindow::on_actionClearMonitor_triggered() { clearMonitor(); } void MainWindow::on_firmwareBrowseButton_clicked() { auto filename = QFileDialog::getOpenFileName(this, tr("Open Firmware"), "", makeFirmwareFilter()); if (filename.isEmpty()) return; firmwarePath->setText(filename); emit firmwarePath->editingFinished(); } void MainWindow::on_monitorText_customContextMenuRequested(const QPoint &pos) { QMenu *menu = monitorText->createStandardContextMenu(); menu->addAction(actionClearMonitor); menu->exec(monitorText->viewport()->mapToGlobal(pos)); } void MainWindow::on_logText_customContextMenuRequested(const QPoint &pos) { QMenu *menu = logText->createStandardContextMenu(); menu->addAction(tr("Clear"), logText, SLOT(clear())); menu->exec(logText->viewport()->mapToGlobal(pos)); } void MainWindow::on_actionWebsite_triggered() { QDesktopServices::openUrl(QUrl("https://github.com/Koromix/ty/")); } void MainWindow::on_actionReportBug_triggered() { QDesktopServices::openUrl(QUrl("https://github.com/Koromix/ty/issues")); } void MainWindow::on_actionAbout_triggered() { AboutDialog(this).exec(); } <commit_msg>Avoid duplicate selected boards in TyQt<commit_after>/* * ty, a collection of GUI and command-line tools to manage Teensy devices * * Distributed under the MIT license (see LICENSE.txt or http://opensource.org/licenses/MIT) * Copyright (c) 2015 Niels Martignène <[email protected]> */ #include <QDesktopServices> #include <QFileDialog> #include <QScrollBar> #include <QToolButton> #include <QUrl> #include "ty.h" #include "about_dialog.hh" #include "board_widget.hh" #include "commands.hh" #include "main_window.hh" #include "tyqt.hh" using namespace std; MainWindow::MainWindow(Manager *manager, QWidget *parent) : QMainWindow(parent), manager_(manager) { setupUi(this); refreshBoardsInfo(); connect(actionQuit, &QAction::triggered, TyQt::instance(), &TyQt::quit); boardList->setModel(manager); boardList->setItemDelegate(new BoardItemDelegate(manager)); connect(boardList->selectionModel(), &QItemSelectionModel::selectionChanged, this, &MainWindow::selectionChanged); connect(manager, &Manager::boardAdded, this, &MainWindow::setBoardDefaults); monitorText->setWordWrapMode(QTextOption::WrapAnywhere); connect(monitorText, &QPlainTextEdit::textChanged, this, &MainWindow::monitorTextChanged); connect(monitorText, &QPlainTextEdit::updateRequest, this, &MainWindow::monitorTextScrolled); logText->setMaximumBlockCount(1000); for (auto &board: *manager) setBoardDefaults(board.get()); } QString MainWindow::makeFirmwareFilter() { QString exts; for (auto format = tyb_firmware_formats; format->name; format++) exts += QString("*%1 ").arg(format->ext); exts.chop(1); return tr("Binary Files (%1);;All Files (*)").arg(exts); } void MainWindow::setBoardDefaults(Board *board) { board->setProperty("resetAfter", true); if (!boardList->currentIndex().isValid() && manager_->boardCount()) boardList->setCurrentIndex(manager_->index(0, 0)); } void MainWindow::selectionChanged(const QItemSelection &newsel, const QItemSelection &previous) { TY_UNUSED(newsel); TY_UNUSED(previous); monitorText->setDocument(nullptr); if (current_board_) { current_board_->disconnect(this); current_board_ = nullptr; } selected_boards_.clear(); auto selected = boardList->selectionModel()->selectedIndexes(); for (auto &idx: selected) { if (idx.column() == 0) selected_boards_.push_back(manager_->board(idx.row())); } if (selected_boards_.size() == 1) { current_board_ = selected_boards_.front(); firmwarePath->setText(current_board_->firmware()); resetAfterUpload->setChecked(current_board_->property("resetAfter").toBool()); clearOnReset->setChecked(current_board_->clearOnReset()); monitor_autoscroll_ = true; monitor_cursor_ = QTextCursor(); monitorText->setDocument(&current_board_->serialDocument()); monitorText->moveCursor(QTextCursor::End); monitorText->verticalScrollBar()->setValue(monitorText->verticalScrollBar()->maximum()); connect(current_board_.get(), &Board::boardChanged, this, &MainWindow::refreshBoardsInfo); connect(current_board_.get(), &Board::propertyChanged, this, &MainWindow::updatePropertyField); } else { firmwarePath->clear(); } refreshBoardsInfo(); } void MainWindow::refreshBoardsInfo() { if (current_board_) { setWindowTitle(QString("TyQt - %1 - %2") .arg(current_board_->modelName()) .arg(current_board_->tag())); infoTab->setEnabled(true); modelText->setText(current_board_->modelName()); locationText->setText(current_board_->location()); serialText->setText(QString::number(current_board_->serialNumber())); interfaceTree->clear(); for (auto iface: current_board_->interfaces()) { auto item = new QTreeWidgetItem(QStringList{iface.desc, iface.path}); item->setToolTip(1, iface.path); new QTreeWidgetItem(item, QStringList{tr("capabilities"), Board::makeCapabilityList(current_board_->capabilities()).join(", ")}); new QTreeWidgetItem(item, QStringList{tr("location"), QString("%1:%2").arg(current_board_->location(), QString::number(iface.number))}); interfaceTree->addTopLevelItem(item); } monitorTab->setEnabled(true); monitorEdit->setEnabled(current_board_->isSerialAvailable()); actionClearMonitor->setEnabled(true); uploadTab->setEnabled(true); } else { setWindowTitle("TyQt"); infoTab->setEnabled(false); modelText->clear(); locationText->clear(); serialText->clear(); interfaceTree->clear(); monitorTab->setEnabled(false); actionClearMonitor->setEnabled(false); uploadTab->setEnabled(false); } bool upload = false, reset = false, reboot = false; for (auto &board: selected_boards_) { upload |= board->isUploadAvailable(); reset |= board->isResetAvailable(); reboot |= board->isRebootAvailable(); } actionUpload->setEnabled(upload); actionUploadNew->setEnabled(upload); actionReset->setEnabled(reset); actionReboot->setEnabled(reboot); } void MainWindow::updatePropertyField(const QByteArray &name, const QVariant &value) { if (name == "firmware") { firmwarePath->setText(value.toString()); } else if (name == "resetAfter") { resetAfterUpload->setChecked(value.toBool()); } else if (name == "clearOnReset") { clearOnReset->setChecked(value.toBool()); } } void MainWindow::monitorTextChanged() { if (monitor_autoscroll_) { monitorText->verticalScrollBar()->setValue(monitorText->verticalScrollBar()->maximum()); } else { QTextCursor old_cursor = monitorText->textCursor(); monitorText->setTextCursor(monitor_cursor_); monitorText->ensureCursorVisible(); int position = monitorText->verticalScrollBar()->value(); monitorText->setTextCursor(old_cursor); monitorText->verticalScrollBar()->setValue(position); } } void MainWindow::monitorTextScrolled(const QRect &rect, int dy) { TY_UNUSED(rect); if (!dy) return; QScrollBar *vbar = monitorText->verticalScrollBar(); monitor_autoscroll_ = vbar->value() >= vbar->maximum() - 1; monitor_cursor_ = monitorText->cursorForPosition(QPoint(0, 0)); } void MainWindow::clearMonitor() { monitor_cursor_ = QTextCursor(); monitorText->clear(); } void MainWindow::showErrorMessage(const QString &msg) { statusBar()->showMessage(msg, SHOW_ERROR_TIMEOUT); logText->appendPlainText(msg); } void MainWindow::on_firmwarePath_editingFinished() { if (!current_board_) return; if (!firmwarePath->text().isEmpty()) { QString firmware = QFileInfo(firmwarePath->text()).canonicalFilePath(); if (firmware.isEmpty()) { tyQt->reportError(tr("Path '%1' is not valid").arg(firmwarePath->text())); return; } current_board_->setFirmware(firmware); } else { current_board_->setFirmware(""); } } void MainWindow::on_resetAfterUpload_toggled(bool checked) { if (!current_board_) return; current_board_->setProperty("resetAfter", checked); } void MainWindow::on_actionNewWindow_triggered() { tyQt->openMainWindow(); } void MainWindow::on_actionUpload_triggered() { if (current_board_ && current_board_->firmware().isEmpty()) { on_actionUploadNew_triggered(); return; } unsigned int uploaded = 0; for (auto &board: selected_boards_) { if (!board->firmware().isEmpty()) { board->upload({Firmware::load(board->firmware())}, board->property("resetAfter").toBool()).start(); uploaded++; } } if (!uploaded) tyQt->reportError("No board has a set firmware, try using 'Upload New Firmware'"); } void MainWindow::on_actionUploadNew_triggered() { auto filenames = QFileDialog::getOpenFileNames(this, tr("Open Firmwares"), "", makeFirmwareFilter()); if (filenames.isEmpty()) return; vector<shared_ptr<Firmware>> fws; fws.reserve(filenames.count()); for (auto filename: filenames) fws.push_back(Firmware::load(filename)); for (auto &board: selected_boards_) board->upload(fws, board->property("resetAfter").toBool()).start(); } void MainWindow::on_actionReset_triggered() { for (auto &board: selected_boards_) board->reset().start(); } void MainWindow::on_actionReboot_triggered() { for (auto &board: selected_boards_) board->reboot().start(); } void MainWindow::on_monitorEdit_returnPressed() { if (!current_board_) return; QString s = monitorEdit->text(); monitorEdit->clear(); switch (newlineComboBox->currentIndex()) { case 1: s += '\n'; break; case 2: s += '\r'; break; case 3: s += "\r\n"; break; default: break; } if (echo->isChecked()) current_board_->appendToSerialDocument(s); current_board_->sendSerial(s.toUtf8()); } void MainWindow::on_clearOnReset_toggled(bool checked) { if (!current_board_) return; current_board_->setClearOnReset(checked); } void MainWindow::on_actionMinimalInterface_toggled(bool checked) { toolBar->setVisible(!checked); boardList->setVisible(!checked); statusbar->setVisible(!checked); } void MainWindow::on_actionClearMonitor_triggered() { clearMonitor(); } void MainWindow::on_firmwareBrowseButton_clicked() { auto filename = QFileDialog::getOpenFileName(this, tr("Open Firmware"), "", makeFirmwareFilter()); if (filename.isEmpty()) return; firmwarePath->setText(filename); emit firmwarePath->editingFinished(); } void MainWindow::on_monitorText_customContextMenuRequested(const QPoint &pos) { QMenu *menu = monitorText->createStandardContextMenu(); menu->addAction(actionClearMonitor); menu->exec(monitorText->viewport()->mapToGlobal(pos)); } void MainWindow::on_logText_customContextMenuRequested(const QPoint &pos) { QMenu *menu = logText->createStandardContextMenu(); menu->addAction(tr("Clear"), logText, SLOT(clear())); menu->exec(logText->viewport()->mapToGlobal(pos)); } void MainWindow::on_actionWebsite_triggered() { QDesktopServices::openUrl(QUrl("https://github.com/Koromix/ty/")); } void MainWindow::on_actionReportBug_triggered() { QDesktopServices::openUrl(QUrl("https://github.com/Koromix/ty/issues")); } void MainWindow::on_actionAbout_triggered() { AboutDialog(this).exec(); } <|endoftext|>
<commit_before>// 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 "ui/views/painter.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "third_party/skia/include/effects/SkGradientShader.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/canvas.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/image/image_skia_operations.h" #include "ui/gfx/insets.h" #include "ui/gfx/nine_image_painter.h" #include "ui/gfx/point.h" #include "ui/gfx/rect.h" #include "ui/views/view.h" namespace views { namespace { // DashedFocusPainter ---------------------------------------------------------- class DashedFocusPainter : public Painter { public: explicit DashedFocusPainter(const gfx::Insets& insets); virtual ~DashedFocusPainter(); // Painter: virtual gfx::Size GetMinimumSize() const OVERRIDE; virtual void Paint(gfx::Canvas* canvas, const gfx::Size& size) OVERRIDE; private: const gfx::Insets insets_; DISALLOW_COPY_AND_ASSIGN(DashedFocusPainter); }; DashedFocusPainter::DashedFocusPainter(const gfx::Insets& insets) : insets_(insets) { } DashedFocusPainter::~DashedFocusPainter() { } gfx::Size DashedFocusPainter::GetMinimumSize() const { return gfx::Size(); } void DashedFocusPainter::Paint(gfx::Canvas* canvas, const gfx::Size& size) { gfx::Rect rect(size); rect.Inset(insets_); canvas->DrawFocusRect(rect); } // SolidFocusPainter ----------------------------------------------------------- class SolidFocusPainter : public Painter { public: SolidFocusPainter(SkColor color, const gfx::Insets& insets); virtual ~SolidFocusPainter(); // Painter: virtual gfx::Size GetMinimumSize() const OVERRIDE; virtual void Paint(gfx::Canvas* canvas, const gfx::Size& size) OVERRIDE; private: const SkColor color_; const gfx::Insets insets_; DISALLOW_COPY_AND_ASSIGN(SolidFocusPainter); }; SolidFocusPainter::SolidFocusPainter(SkColor color, const gfx::Insets& insets) : color_(color), insets_(insets) { } SolidFocusPainter::~SolidFocusPainter() { } gfx::Size SolidFocusPainter::GetMinimumSize() const { return gfx::Size(); } void SolidFocusPainter::Paint(gfx::Canvas* canvas, const gfx::Size& size) { gfx::Rect rect(size); rect.Inset(insets_); canvas->DrawSolidFocusRect(rect, color_); } // GradientPainter ------------------------------------------------------------ class GradientPainter : public Painter { public: GradientPainter(bool horizontal, SkColor* colors, SkScalar* pos, size_t count); virtual ~GradientPainter(); // Painter: virtual gfx::Size GetMinimumSize() const OVERRIDE; virtual void Paint(gfx::Canvas* canvas, const gfx::Size& size) OVERRIDE; private: // If |horizontal_| is true then the gradient is painted horizontally. bool horizontal_; // The gradient colors. scoped_ptr<SkColor[]> colors_; // The relative positions of the corresponding gradient colors. scoped_ptr<SkScalar[]> pos_; // The number of elements in |colors_| and |pos_|. size_t count_; DISALLOW_COPY_AND_ASSIGN(GradientPainter); }; GradientPainter::GradientPainter(bool horizontal, SkColor* colors, SkScalar* pos, size_t count) : horizontal_(horizontal), colors_(new SkColor[count]), pos_(new SkScalar[count]), count_(count) { for (size_t i = 0; i < count_; ++i) { pos_[i] = pos[i]; colors_[i] = colors[i]; } } GradientPainter::~GradientPainter() { } gfx::Size GradientPainter::GetMinimumSize() const { return gfx::Size(); } void GradientPainter::Paint(gfx::Canvas* canvas, const gfx::Size& size) { SkPaint paint; SkPoint p[2]; p[0].iset(0, 0); if (horizontal_) p[1].iset(size.width(), 0); else p[1].iset(0, size.height()); skia::RefPtr<SkShader> s = skia::AdoptRef(SkGradientShader::CreateLinear( p, colors_.get(), pos_.get(), count_, SkShader::kClamp_TileMode)); paint.setStyle(SkPaint::kFill_Style); paint.setShader(s.get()); canvas->sk_canvas()->drawRectCoords(SkIntToScalar(0), SkIntToScalar(0), SkIntToScalar(size.width()), SkIntToScalar(size.height()), paint); } // ImagePainter --------------------------------------------------------------- // ImagePainter stores and paints nine images as a scalable grid. class VIEWS_EXPORT ImagePainter : public Painter { public: // Constructs an ImagePainter with the specified image resource ids. // See CreateImageGridPainter()'s comment regarding image ID count and order. explicit ImagePainter(const int image_ids[]); // Constructs an ImagePainter with the specified image and insets. ImagePainter(const gfx::ImageSkia& image, const gfx::Insets& insets); virtual ~ImagePainter(); // Painter: virtual gfx::Size GetMinimumSize() const OVERRIDE; virtual void Paint(gfx::Canvas* canvas, const gfx::Size& size) OVERRIDE; private: scoped_ptr<gfx::NineImagePainter> nine_painter_; DISALLOW_COPY_AND_ASSIGN(ImagePainter); }; ImagePainter::ImagePainter(const int image_ids[]) : nine_painter_(ui::CreateNineImagePainter(image_ids)) { } ImagePainter::ImagePainter(const gfx::ImageSkia& image, const gfx::Insets& insets) : nine_painter_(new gfx::NineImagePainter(image, insets)) { } ImagePainter::~ImagePainter() { } gfx::Size ImagePainter::GetMinimumSize() const { return nine_painter_->GetMinimumSize(); } void ImagePainter::Paint(gfx::Canvas* canvas, const gfx::Size& size) { nine_painter_->Paint(canvas, gfx::Rect(size)); } } // namespace // Painter -------------------------------------------------------------------- Painter::Painter() { } Painter::~Painter() { } // static void Painter::PaintPainterAt(gfx::Canvas* canvas, Painter* painter, const gfx::Rect& rect) { DCHECK(canvas && painter); canvas->Save(); canvas->Translate(rect.OffsetFromOrigin()); painter->Paint(canvas, rect.size()); canvas->Restore(); } // static void Painter::PaintFocusPainter(View* view, gfx::Canvas* canvas, Painter* focus_painter) { if (focus_painter && view->HasFocus()) PaintPainterAt(canvas, focus_painter, view->GetLocalBounds()); } // static Painter* Painter::CreateHorizontalGradient(SkColor c1, SkColor c2) { SkColor colors[2]; colors[0] = c1; colors[1] = c2; SkScalar pos[] = {0, 1}; return new GradientPainter(true, colors, pos, 2); } // static Painter* Painter::CreateVerticalGradient(SkColor c1, SkColor c2) { SkColor colors[2]; colors[0] = c1; colors[1] = c2; SkScalar pos[] = {0, 1}; return new GradientPainter(false, colors, pos, 2); } // static Painter* Painter::CreateVerticalMultiColorGradient(SkColor* colors, SkScalar* pos, size_t count) { return new GradientPainter(false, colors, pos, count); } // static Painter* Painter::CreateImagePainter(const gfx::ImageSkia& image, const gfx::Insets& insets) { return new ImagePainter(image, insets); } // static Painter* Painter::CreateImageGridPainter(const int image_ids[]) { return new ImagePainter(image_ids); } // static scoped_ptr<Painter> Painter::CreateDashedFocusPainter() { return scoped_ptr<Painter>(new DashedFocusPainter(gfx::Insets())).Pass(); } // static scoped_ptr<Painter> Painter::CreateDashedFocusPainterWithInsets( const gfx::Insets& insets) { return scoped_ptr<Painter>(new DashedFocusPainter(insets)).Pass(); } // static scoped_ptr<Painter> Painter::CreateSolidFocusPainter( SkColor color, const gfx::Insets& insets) { return scoped_ptr<Painter>(new SolidFocusPainter(color, insets)).Pass(); } // HorizontalPainter ---------------------------------------------------------- HorizontalPainter::HorizontalPainter(const int image_resource_names[]) { ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); for (int i = 0; i < 3; ++i) images_[i] = rb.GetImageNamed(image_resource_names[i]).ToImageSkia(); DCHECK_EQ(images_[LEFT]->height(), images_[CENTER]->height()); DCHECK_EQ(images_[LEFT]->height(), images_[RIGHT]->height()); } HorizontalPainter::~HorizontalPainter() { } gfx::Size HorizontalPainter::GetMinimumSize() const { return gfx::Size( images_[LEFT]->width() + images_[CENTER]->width() + images_[RIGHT]->width(), images_[LEFT]->height()); } void HorizontalPainter::Paint(gfx::Canvas* canvas, const gfx::Size& size) { if (size.width() < GetMinimumSize().width()) return; // No room to paint. canvas->DrawImageInt(*images_[LEFT], 0, 0); canvas->DrawImageInt(*images_[RIGHT], size.width() - images_[RIGHT]->width(), 0); canvas->TileImageInt( *images_[CENTER], images_[LEFT]->width(), 0, size.width() - images_[LEFT]->width() - images_[RIGHT]->width(), images_[LEFT]->height()); } } // namespace views <commit_msg>win: Don't VIEWS_EXPORT ImagePainter.<commit_after>// 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 "ui/views/painter.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "third_party/skia/include/effects/SkGradientShader.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/canvas.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/image/image_skia_operations.h" #include "ui/gfx/insets.h" #include "ui/gfx/nine_image_painter.h" #include "ui/gfx/point.h" #include "ui/gfx/rect.h" #include "ui/views/view.h" namespace views { namespace { // DashedFocusPainter ---------------------------------------------------------- class DashedFocusPainter : public Painter { public: explicit DashedFocusPainter(const gfx::Insets& insets); virtual ~DashedFocusPainter(); // Painter: virtual gfx::Size GetMinimumSize() const OVERRIDE; virtual void Paint(gfx::Canvas* canvas, const gfx::Size& size) OVERRIDE; private: const gfx::Insets insets_; DISALLOW_COPY_AND_ASSIGN(DashedFocusPainter); }; DashedFocusPainter::DashedFocusPainter(const gfx::Insets& insets) : insets_(insets) { } DashedFocusPainter::~DashedFocusPainter() { } gfx::Size DashedFocusPainter::GetMinimumSize() const { return gfx::Size(); } void DashedFocusPainter::Paint(gfx::Canvas* canvas, const gfx::Size& size) { gfx::Rect rect(size); rect.Inset(insets_); canvas->DrawFocusRect(rect); } // SolidFocusPainter ----------------------------------------------------------- class SolidFocusPainter : public Painter { public: SolidFocusPainter(SkColor color, const gfx::Insets& insets); virtual ~SolidFocusPainter(); // Painter: virtual gfx::Size GetMinimumSize() const OVERRIDE; virtual void Paint(gfx::Canvas* canvas, const gfx::Size& size) OVERRIDE; private: const SkColor color_; const gfx::Insets insets_; DISALLOW_COPY_AND_ASSIGN(SolidFocusPainter); }; SolidFocusPainter::SolidFocusPainter(SkColor color, const gfx::Insets& insets) : color_(color), insets_(insets) { } SolidFocusPainter::~SolidFocusPainter() { } gfx::Size SolidFocusPainter::GetMinimumSize() const { return gfx::Size(); } void SolidFocusPainter::Paint(gfx::Canvas* canvas, const gfx::Size& size) { gfx::Rect rect(size); rect.Inset(insets_); canvas->DrawSolidFocusRect(rect, color_); } // GradientPainter ------------------------------------------------------------ class GradientPainter : public Painter { public: GradientPainter(bool horizontal, SkColor* colors, SkScalar* pos, size_t count); virtual ~GradientPainter(); // Painter: virtual gfx::Size GetMinimumSize() const OVERRIDE; virtual void Paint(gfx::Canvas* canvas, const gfx::Size& size) OVERRIDE; private: // If |horizontal_| is true then the gradient is painted horizontally. bool horizontal_; // The gradient colors. scoped_ptr<SkColor[]> colors_; // The relative positions of the corresponding gradient colors. scoped_ptr<SkScalar[]> pos_; // The number of elements in |colors_| and |pos_|. size_t count_; DISALLOW_COPY_AND_ASSIGN(GradientPainter); }; GradientPainter::GradientPainter(bool horizontal, SkColor* colors, SkScalar* pos, size_t count) : horizontal_(horizontal), colors_(new SkColor[count]), pos_(new SkScalar[count]), count_(count) { for (size_t i = 0; i < count_; ++i) { pos_[i] = pos[i]; colors_[i] = colors[i]; } } GradientPainter::~GradientPainter() { } gfx::Size GradientPainter::GetMinimumSize() const { return gfx::Size(); } void GradientPainter::Paint(gfx::Canvas* canvas, const gfx::Size& size) { SkPaint paint; SkPoint p[2]; p[0].iset(0, 0); if (horizontal_) p[1].iset(size.width(), 0); else p[1].iset(0, size.height()); skia::RefPtr<SkShader> s = skia::AdoptRef(SkGradientShader::CreateLinear( p, colors_.get(), pos_.get(), count_, SkShader::kClamp_TileMode)); paint.setStyle(SkPaint::kFill_Style); paint.setShader(s.get()); canvas->sk_canvas()->drawRectCoords(SkIntToScalar(0), SkIntToScalar(0), SkIntToScalar(size.width()), SkIntToScalar(size.height()), paint); } // ImagePainter --------------------------------------------------------------- // ImagePainter stores and paints nine images as a scalable grid. class ImagePainter : public Painter { public: // Constructs an ImagePainter with the specified image resource ids. // See CreateImageGridPainter()'s comment regarding image ID count and order. explicit ImagePainter(const int image_ids[]); // Constructs an ImagePainter with the specified image and insets. ImagePainter(const gfx::ImageSkia& image, const gfx::Insets& insets); virtual ~ImagePainter(); // Painter: virtual gfx::Size GetMinimumSize() const OVERRIDE; virtual void Paint(gfx::Canvas* canvas, const gfx::Size& size) OVERRIDE; private: scoped_ptr<gfx::NineImagePainter> nine_painter_; DISALLOW_COPY_AND_ASSIGN(ImagePainter); }; ImagePainter::ImagePainter(const int image_ids[]) : nine_painter_(ui::CreateNineImagePainter(image_ids)) { } ImagePainter::ImagePainter(const gfx::ImageSkia& image, const gfx::Insets& insets) : nine_painter_(new gfx::NineImagePainter(image, insets)) { } ImagePainter::~ImagePainter() { } gfx::Size ImagePainter::GetMinimumSize() const { return nine_painter_->GetMinimumSize(); } void ImagePainter::Paint(gfx::Canvas* canvas, const gfx::Size& size) { nine_painter_->Paint(canvas, gfx::Rect(size)); } } // namespace // Painter -------------------------------------------------------------------- Painter::Painter() { } Painter::~Painter() { } // static void Painter::PaintPainterAt(gfx::Canvas* canvas, Painter* painter, const gfx::Rect& rect) { DCHECK(canvas && painter); canvas->Save(); canvas->Translate(rect.OffsetFromOrigin()); painter->Paint(canvas, rect.size()); canvas->Restore(); } // static void Painter::PaintFocusPainter(View* view, gfx::Canvas* canvas, Painter* focus_painter) { if (focus_painter && view->HasFocus()) PaintPainterAt(canvas, focus_painter, view->GetLocalBounds()); } // static Painter* Painter::CreateHorizontalGradient(SkColor c1, SkColor c2) { SkColor colors[2]; colors[0] = c1; colors[1] = c2; SkScalar pos[] = {0, 1}; return new GradientPainter(true, colors, pos, 2); } // static Painter* Painter::CreateVerticalGradient(SkColor c1, SkColor c2) { SkColor colors[2]; colors[0] = c1; colors[1] = c2; SkScalar pos[] = {0, 1}; return new GradientPainter(false, colors, pos, 2); } // static Painter* Painter::CreateVerticalMultiColorGradient(SkColor* colors, SkScalar* pos, size_t count) { return new GradientPainter(false, colors, pos, count); } // static Painter* Painter::CreateImagePainter(const gfx::ImageSkia& image, const gfx::Insets& insets) { return new ImagePainter(image, insets); } // static Painter* Painter::CreateImageGridPainter(const int image_ids[]) { return new ImagePainter(image_ids); } // static scoped_ptr<Painter> Painter::CreateDashedFocusPainter() { return scoped_ptr<Painter>(new DashedFocusPainter(gfx::Insets())).Pass(); } // static scoped_ptr<Painter> Painter::CreateDashedFocusPainterWithInsets( const gfx::Insets& insets) { return scoped_ptr<Painter>(new DashedFocusPainter(insets)).Pass(); } // static scoped_ptr<Painter> Painter::CreateSolidFocusPainter( SkColor color, const gfx::Insets& insets) { return scoped_ptr<Painter>(new SolidFocusPainter(color, insets)).Pass(); } // HorizontalPainter ---------------------------------------------------------- HorizontalPainter::HorizontalPainter(const int image_resource_names[]) { ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); for (int i = 0; i < 3; ++i) images_[i] = rb.GetImageNamed(image_resource_names[i]).ToImageSkia(); DCHECK_EQ(images_[LEFT]->height(), images_[CENTER]->height()); DCHECK_EQ(images_[LEFT]->height(), images_[RIGHT]->height()); } HorizontalPainter::~HorizontalPainter() { } gfx::Size HorizontalPainter::GetMinimumSize() const { return gfx::Size( images_[LEFT]->width() + images_[CENTER]->width() + images_[RIGHT]->width(), images_[LEFT]->height()); } void HorizontalPainter::Paint(gfx::Canvas* canvas, const gfx::Size& size) { if (size.width() < GetMinimumSize().width()) return; // No room to paint. canvas->DrawImageInt(*images_[LEFT], 0, 0); canvas->DrawImageInt(*images_[RIGHT], size.width() - images_[RIGHT]->width(), 0); canvas->TileImageInt( *images_[CENTER], images_[LEFT]->width(), 0, size.width() - images_[LEFT]->width() - images_[RIGHT]->width(), images_[LEFT]->height()); } } // namespace views <|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include <apply_init_wave.h> #include <param_reader.h> #include <utility.h> #include <xyz_reader.h> #include <xyz_writer.h> #include <wave_simulator_2d.h> using namespace aasoni; using namespace std; namespace { bool parseArguments(std::string *paramFile, std::string *outFilePrefix, int argc, char *argv[]) { if (argc < 5) { cout << "Usage is -p <param_file> -o <out_prefix>" << endl; return false; } else { for (size_t i = 1; i < argc; ++i) { if (string(argv[i]) == "-p") { *paramFile = argv[i+1]; ++i; } else if (string(argv[i]) == "-o") { *outFilePrefix = argv[i+1]; ++i; } else { cout << "Not enough or invalid arguments." << endl; return false; } } return true; } } } //anonymous namespace int main(int argc, char *argv[] ) { //get command line arguments std::string paramFile, outFilePrefix; if(!parseArguments(&paramFile, &outFilePrefix, argc, argv)) return 0; //read parameter file ParamReader paramReader(paramFile); //get data file info string fileName = paramReader.getDataFileName(); size_t xLength = paramReader.getXLength(); size_t yLength = paramReader.getYLength(); //read data VEC latitude, longitude; MAT bathymetry; XYZ_Reader reader; if(!reader.readFile(&latitude, &longitude, &bathymetry, xLength, yLength, fileName)) { cout << "Unable to read data" << endl; return 1; } //convert data to surface MAT height = bathymetry; bathymetryToHeight(&height); // ADD WAVE TO SURFACE //read wave data double amplitude = paramReader.getWaveAmplitude(); double xPos = paramReader.getWaveX(); double yPos = paramReader.getWaveY(); double xSigma = paramReader.getWaveSigmaX(); double ySigma = paramReader.getWaveSigmaY(); double c = paramReader.getWaveC(); MAT wave = height; ApplyInitWave applyWave(amplitude, xPos, yPos, xSigma, ySigma, c); applyWave(&latitude, &longitude, &wave); //write initial wave MAT output; XYZ_Writer writer; heightAndBathymetryToSurface(&output, bathymetry, wave); writer.writeToFile(latitude,longitude,output,"data/surface.xyz"); //Simulate propagation size_t steps = paramReader.getSimulationSteps(); double deltaX = paramReader.getDeltaX(); double deltaY = paramReader.getDeltaY(); double deltaT = paramReader.getDeltaT(); WaveSimulator2D simulator(steps, deltaX, deltaY, deltaT, wave, &wave); size_t iter = 0; string outputFilename; while(simulator.next()) { if(iter % 10 == 1) cout << "completed " << iter << " iterations." << endl; ++iter; ostringstream os; os << outFilePrefix << "_" << iter << ".xyz"; outputFilename = os.str(); //write output heightAndBathymetryToSurface(&output, bathymetry, wave); writer.writeToFile(latitude,longitude,output,outputFilename); } } <commit_msg>Fixed error messagee<commit_after>#include <iostream> #include <sstream> #include <apply_init_wave.h> #include <param_reader.h> #include <utility.h> #include <xyz_reader.h> #include <xyz_writer.h> #include <wave_simulator_2d.h> using namespace aasoni; using namespace std; namespace { bool parseArguments(std::string *paramFile, std::string *outFilePrefix, int argc, char *argv[]) { if (argc < 5) { cout << "Usage is -p <param_file> -o <out_prefix>" << endl; return false; } else { for (size_t i = 1; i < argc; ++i) { if (string(argv[i]) == "-p") { *paramFile = argv[i+1]; ++i; } else if (string(argv[i]) == "-o") { *outFilePrefix = argv[i+1]; ++i; } else { cout << "Not enough or invalid arguments." << endl; return false; } } return true; } } } //anonymous namespace int main(int argc, char *argv[] ) { //get command line arguments std::string paramFile, outFilePrefix; if(!parseArguments(&paramFile, &outFilePrefix, argc, argv)) return 0; //read parameter file ParamReader paramReader(paramFile); //get data file info string fileName = paramReader.getDataFileName(); size_t xLength = paramReader.getXLength(); size_t yLength = paramReader.getYLength(); //read data VEC latitude, longitude; MAT bathymetry; XYZ_Reader reader; if(!reader.readFile(&latitude, &longitude, &bathymetry, xLength, yLength, fileName)) { cout << "Unable to read data: " << fileName << endl; return 1; } //convert data to surface MAT height = bathymetry; bathymetryToHeight(&height); // ADD WAVE TO SURFACE //read wave data double amplitude = paramReader.getWaveAmplitude(); double xPos = paramReader.getWaveX(); double yPos = paramReader.getWaveY(); double xSigma = paramReader.getWaveSigmaX(); double ySigma = paramReader.getWaveSigmaY(); double c = paramReader.getWaveC(); MAT wave = height; ApplyInitWave applyWave(amplitude, xPos, yPos, xSigma, ySigma, c); applyWave(&latitude, &longitude, &wave); //write initial wave MAT output; XYZ_Writer writer; heightAndBathymetryToSurface(&output, bathymetry, wave); writer.writeToFile(latitude,longitude,output,"data/surface.xyz"); //Simulate propagation size_t steps = paramReader.getSimulationSteps(); double deltaX = paramReader.getDeltaX(); double deltaY = paramReader.getDeltaY(); double deltaT = paramReader.getDeltaT(); WaveSimulator2D simulator(steps, deltaX, deltaY, deltaT, wave, &wave); size_t iter = 0; string outputFilename; while(simulator.next()) { if(iter % 10 == 1) cout << "completed " << iter << " iterations." << endl; ++iter; ostringstream os; os << outFilePrefix << "_" << iter << ".xyz"; outputFilename = os.str(); //write output heightAndBathymetryToSurface(&output, bathymetry, wave); writer.writeToFile(latitude,longitude,output,outputFilename); } } <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #include <string> #include <vector> #include <map> #include <random> #include <fstream> #include <dune/stuff/common/disable_warnings.hh> # include <dune/common/float_cmp.hh> # include <dune/common/fvector.hh> # include <dune/common/fmatrix.hh> # include <dune/common/parallel/mpihelper.hh> # if HAVE_DUNE_FEM # include <dune/fem/misc/mpimanager.hh> # endif #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/test/gtest/gtest.h> #include <dune/stuff/aliases.hh> #include <dune/stuff/common/configuration.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/common/convergence-study.hh> #include "main_header.hh" class DUNE_DEPRECATED_MSG("Use the expectation macros of the gtest test suite (20.08.2014)!") errors_are_not_as_expected : public Dune::Exception {}; std::vector< double > DUNE_DEPRECATED_MSG("Use the expectation macros of the gtest test suite (20.08.2014)!") truncate_vector(const std::vector< double >& in, const size_t size) { assert(size <= in.size()); if (size == in.size()) return in; else { std::vector< double > ret(size); for (size_t ii = 0; ii < size; ++ii) ret[ii] = in[ii]; return ret; } } // ... truncate_vector(...) int main(int argc, char** argv) { #ifdef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS try { #endif testing::InitGoogleTest(&argc, argv); DSC_CONFIG.read_options(argc, argv); #if HAVE_DUNE_FEM Dune::Fem::MPIManager::initialize(argc, argv); #else Dune::MPIHelper::instance(argc, argv); #endif DSC::Logger().create( #ifdef DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING DSC::LOG_CONSOLE | DSC::LOG_INFO | DSC::LOG_ERROR #else DSC::LOG_CONSOLE | DSC::LOG_ERROR #endif , "", "", ""); return RUN_ALL_TESTS(); #ifdef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS } catch (Dune::Exception& e) { std::cerr << "\nDune reported error: " << e.what() << std::endl; std::abort(); } catch (std::exception& e) { std::cerr << "\n" << e.what() << std::endl; std::abort(); } catch (...) { std::cerr << "Unknown exception thrown!" << std::endl; std::abort(); } // try #endif // DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS } // ... main(...) <commit_msg>[test.main] fixed includes<commit_after>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #include "config.h" #include <string> #include <vector> #include <map> #include <random> #include <fstream> #include <dune/stuff/common/disable_warnings.hh> # include <dune/common/float_cmp.hh> # include <dune/common/fvector.hh> # include <dune/common/fmatrix.hh> # include <dune/common/parallel/mpihelper.hh> # if HAVE_DUNE_FEM # include <dune/fem/misc/mpimanager.hh> # endif #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/test/gtest/gtest.h> #include <dune/stuff/aliases.hh> #include <dune/stuff/common/configuration.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/common/convergence-study.hh> #include "common.hh" class DUNE_DEPRECATED_MSG("Use the expectation macros of the gtest test suite (20.08.2014)!") errors_are_not_as_expected : public Dune::Exception {}; std::vector< double > DUNE_DEPRECATED_MSG("Use the expectation macros of the gtest test suite (20.08.2014)!") truncate_vector(const std::vector< double >& in, const size_t size) { assert(size <= in.size()); if (size == in.size()) return in; else { std::vector< double > ret(size); for (size_t ii = 0; ii < size; ++ii) ret[ii] = in[ii]; return ret; } } // ... truncate_vector(...) int main(int argc, char** argv) { #ifdef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS try { #endif testing::InitGoogleTest(&argc, argv); DSC_CONFIG.read_options(argc, argv); #if HAVE_DUNE_FEM Dune::Fem::MPIManager::initialize(argc, argv); #else Dune::MPIHelper::instance(argc, argv); #endif DSC::Logger().create( #ifdef DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING DSC::LOG_CONSOLE | DSC::LOG_INFO | DSC::LOG_ERROR #else DSC::LOG_CONSOLE | DSC::LOG_ERROR #endif , "", "", ""); return RUN_ALL_TESTS(); #ifdef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS } catch (Dune::Exception& e) { std::cerr << "\nDune reported error: " << e.what() << std::endl; std::abort(); } catch (std::exception& e) { std::cerr << "\n" << e.what() << std::endl; std::abort(); } catch (...) { std::cerr << "Unknown exception thrown!" << std::endl; std::abort(); } // try #endif // DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS } // ... main(...) <|endoftext|>
<commit_before>#ifndef BULL_CORE_IMAGE_ABSTRACTIMAGE_HPP #define BULL_CORE_IMAGE_ABSTRACTIMAGE_HPP #include <vector> #include <Bull/Core/Memory/ByteArray.hpp> #include <Bull/Core/Utility/Size.hpp> namespace Bull { struct BULL_CORE_API AbstractImage { /*! \brief Destructor * */ virtual ~AbstractImage() = default; /*! \brief Create the AbstractImage * * \param size The size of the AbstractImage * */ virtual void create(const Size& size) = 0; /*! \brief Create the AbstractImage * * \param pixels Pixels of the Image * \param size The size of the Image * */ virtual void create(const ByteArray& pixels, const Size& size) = 0; /*! \brief Get the size of the AbstractImage * * \return The size * */ virtual Size getSize() const = 0; /*! \brief * * \return * */ virtual ByteArray getPixels() const = 0; }; } #endif // BULL_CORE_IMAGE_ABSTRACTIMAGE_HPP <commit_msg>[Core/AbstractImage] Add missing documentation<commit_after>#ifndef BULL_CORE_IMAGE_ABSTRACTIMAGE_HPP #define BULL_CORE_IMAGE_ABSTRACTIMAGE_HPP #include <vector> #include <Bull/Core/Memory/ByteArray.hpp> #include <Bull/Core/Utility/Size.hpp> namespace Bull { struct BULL_CORE_API AbstractImage { /*! \brief Destructor * */ virtual ~AbstractImage() = default; /*! \brief Create the AbstractImage * * \param size The size of the AbstractImage * */ virtual void create(const Size& size) = 0; /*! \brief Create the AbstractImage * * \param pixels Pixels of the Image * \param size The size of the Image * */ virtual void create(const ByteArray& pixels, const Size& size) = 0; /*! \brief Get the size of the AbstractImage * * \return The size * */ virtual Size getSize() const = 0; /*! \brief Pixels of the AbstractImage * * \return Pixels * */ virtual ByteArray getPixels() const = 0; }; } #endif // BULL_CORE_IMAGE_ABSTRACTIMAGE_HPP <|endoftext|>
<commit_before>// Copyright (C) 2015 Jrme Leclercq // This file is part of the "Nazara Engine - Network module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_ABSTRACTSOCKET_HPP #define NAZARA_ABSTRACTSOCKET_HPP #include <Nazara/Prerequesites.hpp> #include <Nazara/Core/Signal.hpp> #include <Nazara/Network/Config.hpp> #include <Nazara/Network/Enums.hpp> #include <Nazara/Network/SocketHandle.hpp> namespace Nz { class NAZARA_NETWORK_API AbstractSocket { public: AbstractSocket(const AbstractSocket&) = delete; AbstractSocket(AbstractSocket&& abstractSocket); virtual ~AbstractSocket(); void Close(); void EnableBlocking(bool blocking); inline SocketError GetLastError() const; inline SocketHandle GetNativeHandle() const; inline SocketState GetState() const; inline SocketType GetType() const; inline bool IsBlockingEnabled() const; unsigned int QueryAvailableBytes() const; // Slots NazaraSignal(OnStateChange, const AbstractSocket* /*socket*/, SocketState /*newState*/); protected: AbstractSocket(SocketType type); inline void UpdateState(SocketState newState); virtual void OnClose(); virtual void OnOpened(); bool Open(NetProtocol protocol); void Open(SocketHandle existingHandle); NetProtocol m_protocol; SocketError m_lastError; SocketHandle m_handle; SocketState m_state; SocketType m_type; bool m_isBlockingEnabled; }; } #include <Nazara/Network/AbstractSocket.inl> #endif // NAZARA_ABSTRACTSOCKET_HPP<commit_msg>Network/AbstractSocket: Fix comment<commit_after>// Copyright (C) 2015 Jrme Leclercq // This file is part of the "Nazara Engine - Network module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_ABSTRACTSOCKET_HPP #define NAZARA_ABSTRACTSOCKET_HPP #include <Nazara/Prerequesites.hpp> #include <Nazara/Core/Signal.hpp> #include <Nazara/Network/Config.hpp> #include <Nazara/Network/Enums.hpp> #include <Nazara/Network/SocketHandle.hpp> namespace Nz { class NAZARA_NETWORK_API AbstractSocket { public: AbstractSocket(const AbstractSocket&) = delete; AbstractSocket(AbstractSocket&& abstractSocket); virtual ~AbstractSocket(); void Close(); void EnableBlocking(bool blocking); inline SocketError GetLastError() const; inline SocketHandle GetNativeHandle() const; inline SocketState GetState() const; inline SocketType GetType() const; inline bool IsBlockingEnabled() const; unsigned int QueryAvailableBytes() const; // Signals: NazaraSignal(OnStateChange, const AbstractSocket* /*socket*/, SocketState /*newState*/); protected: AbstractSocket(SocketType type); inline void UpdateState(SocketState newState); virtual void OnClose(); virtual void OnOpened(); bool Open(NetProtocol protocol); void Open(SocketHandle existingHandle); NetProtocol m_protocol; SocketError m_lastError; SocketHandle m_handle; SocketState m_state; SocketType m_type; bool m_isBlockingEnabled; }; } #include <Nazara/Network/AbstractSocket.inl> #endif // NAZARA_ABSTRACTSOCKET_HPP<|endoftext|>
<commit_before>/******************************************************************************* * * An implementation of discrete domains based on Patricia trees. * * Author: Arnaud J. Venet ([email protected]) * * Notices: * * Copyright (c) 2011 United States Government as represented by the * Administrator of the National Aeronautics and Space Administration. * All Rights Reserved. * * Disclaimers: * * No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF * ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED * TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS, * ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, * OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE * ERROR FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO * THE SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN * ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS, * RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS * RESULTING FROM USE OF THE SUBJECT SOFTWARE. FURTHER, GOVERNMENT AGENCY * DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THIRD-PARTY SOFTWARE, * IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT "AS IS." * * Waiver and Indemnity: RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST * THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL * AS ANY PRIOR RECIPIENT. IF RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS * IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM SUCH * USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM, * RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD * HARMLESS THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, * AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY LAW. * RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE IMMEDIATE, * UNILATERAL TERMINATION OF THIS AGREEMENT. * ******************************************************************************/ #pragma once #include <crab/domains/patricia_trees.hpp> #include <crab/domains/separate_domains.hpp> #include <crab/support/debug.hpp> #include <boost/range.hpp> namespace ikos { template <typename Element> class discrete_domain { private: using ptset_t = patricia_tree_set<Element>; public: using discrete_domain_t = discrete_domain<Element>; using iterator = typename ptset_t::iterator; private: bool _is_top; ptset_t _set; private: discrete_domain(bool is_top) : _is_top(is_top) {} discrete_domain(ptset_t set) : _is_top(false), _set(set) {} public: static discrete_domain_t bottom() { return discrete_domain_t(false); } static discrete_domain_t top() { return discrete_domain_t(true); } public: discrete_domain() : _is_top(true) {} discrete_domain(const discrete_domain_t &other) : _is_top(other._is_top), _set(other._set) {} discrete_domain(Element s) : _is_top(false), _set(s) {} template <typename Iterator> discrete_domain(Iterator eIt, Iterator eEt) : _is_top(false) { for (auto e : boost::make_iterator_range(eIt, eEt)) { this->_set += e; } } bool is_top() const { return this->_is_top; } bool is_bottom() const { return (!this->_is_top && this->_set.empty()); } bool operator<=(const discrete_domain_t &other) const { return other._is_top || (!this->_is_top && this->_set <= other._set); } bool operator==(const discrete_domain_t &other) const { return (this->_is_top && other._is_top) || (this->_set == other._set); } void operator|=(const discrete_domain_t &other) { *this = *this | other; } discrete_domain_t operator|(const discrete_domain_t &other) const { if (this->_is_top || other._is_top) { return discrete_domain_t(true); } else { return discrete_domain_t(this->_set | other._set); } } discrete_domain_t operator&(const discrete_domain_t &other) const { if (this->is_bottom() || other.is_bottom()) { return discrete_domain_t(false); } else if (this->_is_top) { return other; } else if (other._is_top) { return *this; } else { return discrete_domain_t(this->_set & other._set); } } discrete_domain_t operator||(const discrete_domain_t &other) const { return this->operator|(other); } discrete_domain_t operator&&(const discrete_domain_t &other) const { return this->operator&(other); } discrete_domain_t &operator+=(Element s) { if (!this->_is_top) { this->_set += s; } return *this; } template <typename Range> discrete_domain_t &operator+=(Range es) { if (!this->_is_top) for (auto e : es) this->_set += e; return *this; } discrete_domain_t operator+(Element s) { discrete_domain_t r(*this); r.operator+=(s); return r; } template <typename Range> discrete_domain_t operator+(Range es) { discrete_domain_t r(*this); r.operator+=(es); return r; } discrete_domain_t &operator-=(Element s) { if (!this->_is_top) { this->_set -= s; } return *this; } template <typename Range> discrete_domain_t &operator-=(Range es) { if (!this->_is_top) for (auto e : es) this->_set -= e; return *this; } discrete_domain_t operator-(Element s) { discrete_domain_t r(*this); r.operator-=(s); return r; } template <typename Range> discrete_domain_t operator-(Range es) { discrete_domain_t r(*this); r.operator-=(es); return r; } std::size_t size() const { if (this->_is_top) { CRAB_ERROR("Size for discrete domain TOP is undefined"); } else { return this->_set.size(); } } iterator begin() const { if (this->_is_top) { CRAB_ERROR("Iterator for discrete domain TOP is undefined"); } else { return this->_set.begin(); } } iterator end() const { if (this->_is_top) { CRAB_ERROR("Iterator for discrete domain TOP is undefined"); } else { return this->_set.end(); } } void write(crab::crab_os &o) const { if (this->_is_top) { o << "{...}"; } else if (this->_set.empty()) { o << "_|_"; } else { o << this->_set; } } }; // class discrete_domain template <typename Elem> inline crab::crab_os &operator<<(crab::crab_os &o, const discrete_domain<Elem> &d) { d.write(o); return o; } } // namespace ikos <commit_msg>style(discrete_domains): use m_ for class fields<commit_after>/******************************************************************************* * * An implementation of discrete domains based on Patricia trees. * * Author: Arnaud J. Venet ([email protected]) * * Notices: * * Copyright (c) 2011 United States Government as represented by the * Administrator of the National Aeronautics and Space Administration. * All Rights Reserved. * * Disclaimers: * * No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF * ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED * TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS, * ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, * OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE * ERROR FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO * THE SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN * ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS, * RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS * RESULTING FROM USE OF THE SUBJECT SOFTWARE. FURTHER, GOVERNMENT AGENCY * DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THIRD-PARTY SOFTWARE, * IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT "AS IS." * * Waiver and Indemnity: RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST * THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL * AS ANY PRIOR RECIPIENT. IF RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS * IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM SUCH * USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM, * RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD * HARMLESS THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, * AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY LAW. * RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE IMMEDIATE, * UNILATERAL TERMINATION OF THIS AGREEMENT. * ******************************************************************************/ #pragma once #include <crab/domains/patricia_trees.hpp> #include <crab/support/debug.hpp> #include <boost/range.hpp> namespace ikos { template <typename Element> class discrete_domain { private: using ptset_t = patricia_tree_set<Element>; public: using discrete_domain_t = discrete_domain<Element>; using iterator = typename ptset_t::iterator; private: bool m_is_top; ptset_t m_set; private: discrete_domain(bool is_top) : m_is_top(is_top) {} discrete_domain(ptset_t set) : m_is_top(false), m_set(set) {} public: static discrete_domain_t bottom() { return discrete_domain_t(false); } static discrete_domain_t top() { return discrete_domain_t(true); } public: discrete_domain() : m_is_top(true) {} discrete_domain(const discrete_domain_t &other) = default; discrete_domain(discrete_domain_t &&other) = default; discrete_domain_t &operator=(const discrete_domain_t &other) = default; discrete_domain_t &operator=(discrete_domain_t &&other) = default; discrete_domain(Element s) : m_is_top(false), m_set(s) {} template <typename Iterator> discrete_domain(Iterator eIt, Iterator eEt) : m_is_top(false) { for (auto e : boost::make_iterator_range(eIt, eEt)) { m_set += e; } } bool is_top() const { return m_is_top; } bool is_bottom() const { return (!m_is_top && m_set.empty()); } bool operator<=(const discrete_domain_t &other) const { return other.m_is_top || (!m_is_top && m_set <= other.m_set); } bool operator==(const discrete_domain_t &other) const { return (m_is_top && other.m_is_top) || (m_set == other.m_set); } void operator|=(const discrete_domain_t &other) { *this = *this | other; } discrete_domain_t operator|(const discrete_domain_t &other) const { if (m_is_top || other.m_is_top) { return discrete_domain_t(true); } else { return discrete_domain_t(m_set | other.m_set); } } discrete_domain_t operator&(const discrete_domain_t &other) const { if (is_bottom() || other.is_bottom()) { return discrete_domain_t(false); } else if (m_is_top) { return other; } else if (other.m_is_top) { return *this; } else { return discrete_domain_t(m_set & other.m_set); } } discrete_domain_t operator||(const discrete_domain_t &other) const { return operator|(other); } discrete_domain_t operator&&(const discrete_domain_t &other) const { return operator&(other); } discrete_domain_t &operator+=(Element s) { if (!m_is_top) { m_set += s; } return *this; } template <typename Range> discrete_domain_t &operator+=(Range es) { if (!m_is_top) { for (auto e : es) { m_set += e; } } return *this; } discrete_domain_t operator+(Element s) { discrete_domain_t r(*this); r.operator+=(s); return r; } template <typename Range> discrete_domain_t operator+(Range es) { discrete_domain_t r(*this); r.operator+=(es); return r; } discrete_domain_t &operator-=(Element s) { if (!m_is_top) { m_set -= s; } return *this; } template <typename Range> discrete_domain_t &operator-=(Range es) { if (!m_is_top) { for (auto e : es) { m_set -= e; } } return *this; } discrete_domain_t operator-(Element s) { discrete_domain_t r(*this); r.operator-=(s); return r; } template <typename Range> discrete_domain_t operator-(Range es) { discrete_domain_t r(*this); r.operator-=(es); return r; } std::size_t size() const { if (m_is_top) { assert(false); CRAB_ERROR("Size for discrete domain TOP is undefined"); } else { return m_set.size(); } } iterator begin() const { if (m_is_top) { assert(false); CRAB_ERROR("Iterator for discrete domain TOP is undefined"); } else { return m_set.begin(); } } iterator end() const { if (m_is_top) { assert(false); CRAB_ERROR("Iterator for discrete domain TOP is undefined"); } else { return m_set.end(); } } void write(crab::crab_os &o) const { if (m_is_top) { o << "{...}"; } else if (m_set.empty()) { o << "{}"; } else { o << m_set; } } }; // class discrete_domain template <typename Elem> inline crab::crab_os &operator<<(crab::crab_os &o, const discrete_domain<Elem> &d) { d.write(o); return o; } } // namespace ikos <|endoftext|>
<commit_before>// This file is distributed under the MIT license. // See the LICENSE file for details. #ifndef VSNRAY_PATHTRACING_INL #define VSNRAY_PATHTRACING_INL #include <chrono> #include <limits> #ifndef NDEBUG #include <iostream> #include <ostream> #endif #include <visionaray/generic_prim.h> #include <visionaray/surface.h> #include "traverse.h" namespace visionaray { namespace pathtracing { template <typename Params> struct kernel { Params params; template <typename R, template <typename> class S> VSNRAY_FUNC vector<4, typename R::scalar_type> operator()(R ray, S<typename R::scalar_type>& s) const { using C = vector<4, typename R::scalar_type>; typedef typename R::scalar_type scalar_type; typedef typename R::vec_type vec_type; /*static*/ const scalar_type scene_epsilon(0.0001); /*static*/ const unsigned MaxDepth = 5; auto hit_rec = closest_hit(ray, params.prims.begin, params.prims.end); auto exited = !hit_rec.hit; auto active_rays = hit_rec.hit; C result(1.0, 1.0, 1.0, 1.0); for (unsigned d = 0; d < MaxDepth; ++d) { if ( any(active_rays) ) { vec_type refl_dir; vec_type view_dir = -ray.dir; auto surf = get_surface(hit_rec, params); auto below = active_rays & (dot(view_dir, surf.normal) < scalar_type(0.0)); if (any(below)) { result = mul( result, C(0.0, 0.0, 0.0, 1.0), below, result ); active_rays = active_rays & !below; if ( !any(active_rays) ) { break; } } scalar_type pdf(0.0); auto sr = make_shade_record<Params, scalar_type>(); sr.active = hit_rec.hit; sr.view_dir = view_dir; auto color = surf.sample(sr, refl_dir, pdf, s); auto emissive = has_emissive_material(surf); color = mul( color, dot(surf.normal, refl_dir) / pdf, !emissive, color ); // TODO: maybe have emissive material return refl_dir so that dot(N,R) = 1? result = mul( result, C(color, scalar_type(1.0)), active_rays, result ); active_rays &= !emissive; if (!any(active_rays)) { break; } auto isect_pos = ray.ori + ray.dir * hit_rec.t; // TODO: store in hit_rec?!? ray.ori = isect_pos + refl_dir * scene_epsilon; ray.dir = refl_dir; hit_rec = closest_hit(ray, params.prims.begin, params.prims.end); exited = active_rays & !hit_rec.hit; active_rays &= hit_rec.hit; } result = mul( result, C(params.ambient_color), exited, result ); } result = mul( result, C(0.0, 0.0, 0.0, 1.0), active_rays, result ); return result; } }; } // pathtracing } // visionaray #endif // VSNRAY_PATHTRACING_INL <commit_msg>Mind background color in pathtracer<commit_after>// This file is distributed under the MIT license. // See the LICENSE file for details. #ifndef VSNRAY_PATHTRACING_INL #define VSNRAY_PATHTRACING_INL #include <chrono> #include <limits> #ifndef NDEBUG #include <iostream> #include <ostream> #endif #include <visionaray/generic_prim.h> #include <visionaray/surface.h> #include "traverse.h" namespace visionaray { namespace pathtracing { template <typename Params> struct kernel { Params params; template <typename R, template <typename> class S> VSNRAY_FUNC vector<4, typename R::scalar_type> operator()(R ray, S<typename R::scalar_type>& s) const { using C = vector<4, typename R::scalar_type>; typedef typename R::scalar_type scalar_type; typedef typename R::vec_type vec_type; /*static*/ const scalar_type scene_epsilon(0.0001); /*static*/ const unsigned MaxDepth = 5; auto hit_rec = closest_hit(ray, params.prims.begin, params.prims.end); auto exited = !hit_rec.hit; auto active_rays = hit_rec.hit; C result = select( exited, C(params.bg_color), C(1.0) ); for (unsigned d = 0; d < MaxDepth; ++d) { if ( any(active_rays) ) { vec_type refl_dir; vec_type view_dir = -ray.dir; auto surf = get_surface(hit_rec, params); auto below = active_rays & (dot(view_dir, surf.normal) < scalar_type(0.0)); if (any(below)) { result = mul( result, C(0.0, 0.0, 0.0, 1.0), below, result ); active_rays = active_rays & !below; if ( !any(active_rays) ) { break; } } scalar_type pdf(0.0); auto sr = make_shade_record<Params, scalar_type>(); sr.active = hit_rec.hit; sr.view_dir = view_dir; auto color = surf.sample(sr, refl_dir, pdf, s); auto emissive = has_emissive_material(surf); color = mul( color, dot(surf.normal, refl_dir) / pdf, !emissive, color ); // TODO: maybe have emissive material return refl_dir so that dot(N,R) = 1? result = mul( result, C(color, scalar_type(1.0)), active_rays, result ); active_rays &= !emissive; if (!any(active_rays)) { break; } auto isect_pos = ray.ori + ray.dir * hit_rec.t; // TODO: store in hit_rec?!? ray.ori = isect_pos + refl_dir * scene_epsilon; ray.dir = refl_dir; hit_rec = closest_hit(ray, params.prims.begin, params.prims.end); exited = active_rays & !hit_rec.hit; active_rays &= hit_rec.hit; } result = mul( result, C(params.ambient_color), exited, result ); } result = mul( result, C(0.0, 0.0, 0.0, 1.0), active_rays, result ); return result; } }; } // pathtracing } // visionaray #endif // VSNRAY_PATHTRACING_INL <|endoftext|>
<commit_before>// This file is distributed under the MIT license. // See the LICENSE file for details. namespace MATH_NAMESPACE { //-------------------------------------------------------------------------------------------------- // matrix members // template <size_t N, size_t M, typename T> MATH_FUNC inline T* matrix<N, M, T>::data() { return reinterpret_cast<T*>(this); } template <size_t N, size_t M, typename T> MATH_FUNC inline T const* matrix<N, M, T>::data() const { return reinterpret_cast<T const*>(this); } template <size_t N, size_t M, typename T> MATH_FUNC inline vector<N, T>& matrix<N, M, T>::operator()(size_t col) { return *(reinterpret_cast<vector<N, T>*>(this) + col); } template <size_t N, size_t M, typename T> MATH_FUNC inline vector<N, T> const& matrix<N, M, T>::operator()(size_t col) const { return *(reinterpret_cast<vector<N, T> const*>(this) + col); } template <size_t N, size_t M, typename T> MATH_FUNC inline T& matrix<N, M, T>::operator()(size_t row, size_t col) { return (operator()(col))[row]; } template <size_t N, size_t M, typename T> MATH_FUNC inline T const& matrix<N, M, T>::operator()(size_t row, size_t col) const { return (operator()(col))[row]; } template <size_t N, size_t M, typename T> MATH_FUNC inline matrix<N, M, T> matrix<N, M, T>::identity() { static_assert(N == M, "Matrix not symmetrical"); matrix<N, M, T> result; for (int i = 0; i < N; ++i) { for (int j = 0; j < M; ++j) { result(i, j) = i == j ? T(1.0) : T(0.0); } } return result; } //-------------------------------------------------------------------------------------------------- // Comparisons // template <size_t N, size_t M, typename T> MATH_FUNC inline bool operator==(matrix<N, M, T> const& a, matrix<N, M, T> const& b) { for (size_t i = 0; i < N; ++i) { for (size_t j = 0; j < M; ++j) { if (a(i, j) != b(i, j)) { return false; } } } return true; } template <size_t N, size_t M, typename T> MATH_FUNC inline bool operator!=(matrix<N, M, T> const& a, matrix<N, M, T> const& b) { return !(a == b); } } // MATH_NAMESPACE <commit_msg>Use 64-bit indices when limits are 64 bit<commit_after>// This file is distributed under the MIT license. // See the LICENSE file for details. namespace MATH_NAMESPACE { //-------------------------------------------------------------------------------------------------- // matrix members // template <size_t N, size_t M, typename T> MATH_FUNC inline T* matrix<N, M, T>::data() { return reinterpret_cast<T*>(this); } template <size_t N, size_t M, typename T> MATH_FUNC inline T const* matrix<N, M, T>::data() const { return reinterpret_cast<T const*>(this); } template <size_t N, size_t M, typename T> MATH_FUNC inline vector<N, T>& matrix<N, M, T>::operator()(size_t col) { return *(reinterpret_cast<vector<N, T>*>(this) + col); } template <size_t N, size_t M, typename T> MATH_FUNC inline vector<N, T> const& matrix<N, M, T>::operator()(size_t col) const { return *(reinterpret_cast<vector<N, T> const*>(this) + col); } template <size_t N, size_t M, typename T> MATH_FUNC inline T& matrix<N, M, T>::operator()(size_t row, size_t col) { return (operator()(col))[row]; } template <size_t N, size_t M, typename T> MATH_FUNC inline T const& matrix<N, M, T>::operator()(size_t row, size_t col) const { return (operator()(col))[row]; } template <size_t N, size_t M, typename T> MATH_FUNC inline matrix<N, M, T> matrix<N, M, T>::identity() { static_assert(N == M, "Matrix not symmetrical"); matrix<N, M, T> result; for (size_t i = 0; i < N; ++i) { for (size_t j = 0; j < M; ++j) { result(i, j) = i == j ? T(1.0) : T(0.0); } } return result; } //-------------------------------------------------------------------------------------------------- // Comparisons // template <size_t N, size_t M, typename T> MATH_FUNC inline bool operator==(matrix<N, M, T> const& a, matrix<N, M, T> const& b) { for (size_t i = 0; i < N; ++i) { for (size_t j = 0; j < M; ++j) { if (a(i, j) != b(i, j)) { return false; } } } return true; } template <size_t N, size_t M, typename T> MATH_FUNC inline bool operator!=(matrix<N, M, T> const& a, matrix<N, M, T> const& b) { return !(a == b); } } // MATH_NAMESPACE <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: basegfxfactory.cxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_cppcanvas.hxx" #include <rtl/instance.hxx> #include <osl/getglobalmutex.hxx> #include <osl/diagnose.h> #include <com/sun/star/rendering/InterpolationMode.hpp> #include <basegfx/polygon/b2dpolygon.hxx> #include <basegfx/polygon/b2dpolypolygon.hxx> #include <basegfx/tools/canvastools.hxx> #include <cppcanvas/basegfxfactory.hxx> #include <implpolypolygon.hxx> #include <implbitmap.hxx> #include <impltext.hxx> using namespace ::com::sun::star; namespace cppcanvas { /* Singleton handling */ struct InitInstance2 { BaseGfxFactory* operator()() { return new BaseGfxFactory(); } }; BaseGfxFactory& BaseGfxFactory::getInstance() { return *rtl_Instance< BaseGfxFactory, InitInstance2, ::osl::MutexGuard, ::osl::GetGlobalMutex >::create( InitInstance2(), ::osl::GetGlobalMutex()); } BaseGfxFactory::BaseGfxFactory() { } BaseGfxFactory::~BaseGfxFactory() { } PolyPolygonSharedPtr BaseGfxFactory::createPolyPolygon( const CanvasSharedPtr& rCanvas, const ::basegfx::B2DPolygon& rPoly ) const { OSL_ENSURE( rCanvas.get() != NULL && rCanvas->getUNOCanvas().is(), "BaseGfxFactory::createPolyPolygon(): Invalid canvas" ); if( rCanvas.get() == NULL ) return PolyPolygonSharedPtr(); uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() ); if( !xCanvas.is() ) return PolyPolygonSharedPtr(); return PolyPolygonSharedPtr( new internal::ImplPolyPolygon( rCanvas, ::basegfx::unotools::xPolyPolygonFromB2DPolygon( xCanvas->getDevice(), rPoly) ) ); } PolyPolygonSharedPtr BaseGfxFactory::createPolyPolygon( const CanvasSharedPtr& rCanvas, const ::basegfx::B2DPolyPolygon& rPolyPoly ) const { OSL_ENSURE( rCanvas.get() != NULL && rCanvas->getUNOCanvas().is(), "BaseGfxFactory::createPolyPolygon(): Invalid canvas" ); if( rCanvas.get() == NULL ) return PolyPolygonSharedPtr(); uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() ); if( !xCanvas.is() ) return PolyPolygonSharedPtr(); return PolyPolygonSharedPtr( new internal::ImplPolyPolygon( rCanvas, ::basegfx::unotools::xPolyPolygonFromB2DPolyPolygon( xCanvas->getDevice(), rPolyPoly) ) ); } BitmapSharedPtr BaseGfxFactory::createBitmap( const CanvasSharedPtr& rCanvas, const ::basegfx::B2ISize& rSize ) const { OSL_ENSURE( rCanvas.get() != NULL && rCanvas->getUNOCanvas().is(), "BaseGfxFactory::createBitmap(): Invalid canvas" ); if( rCanvas.get() == NULL ) return BitmapSharedPtr(); uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() ); if( !xCanvas.is() ) return BitmapSharedPtr(); return BitmapSharedPtr( new internal::ImplBitmap( rCanvas, xCanvas->getDevice()->createCompatibleBitmap( ::basegfx::unotools::integerSize2DFromB2ISize(rSize) ) ) ); } BitmapSharedPtr BaseGfxFactory::createAlphaBitmap( const CanvasSharedPtr& rCanvas, const ::basegfx::B2ISize& rSize ) const { OSL_ENSURE( rCanvas.get() != NULL && rCanvas->getUNOCanvas().is(), "BaseGfxFactory::createBitmap(): Invalid canvas" ); if( rCanvas.get() == NULL ) return BitmapSharedPtr(); uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() ); if( !xCanvas.is() ) return BitmapSharedPtr(); return BitmapSharedPtr( new internal::ImplBitmap( rCanvas, xCanvas->getDevice()->createCompatibleAlphaBitmap( ::basegfx::unotools::integerSize2DFromB2ISize(rSize) ) ) ); } TextSharedPtr BaseGfxFactory::createText( const CanvasSharedPtr& rCanvas, const ::rtl::OUString& rText ) const { return TextSharedPtr( new internal::ImplText( rCanvas, rText ) ); } } <commit_msg>INTEGRATION: CWS canvas05 (1.7.38); FILE MERGED 2008/04/21 07:50:36 thb 1.7.38.2: RESYNC: (1.7-1.8); FILE MERGED 2007/10/01 13:41:45 thb 1.7.38.1: #i79258# Merge from CWS picom<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: basegfxfactory.cxx,v $ * $Revision: 1.9 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_cppcanvas.hxx" #include <rtl/instance.hxx> #include <osl/getglobalmutex.hxx> #include <osl/diagnose.h> #include <com/sun/star/rendering/InterpolationMode.hpp> #include <basegfx/polygon/b2dpolygon.hxx> #include <basegfx/polygon/b2dpolypolygon.hxx> #include <basegfx/tools/canvastools.hxx> #include <cppcanvas/basegfxfactory.hxx> #include "implpolypolygon.hxx" #include "implbitmap.hxx" #include "impltext.hxx" using namespace ::com::sun::star; namespace cppcanvas { /* Singleton handling */ struct InitInstance2 { BaseGfxFactory* operator()() { return new BaseGfxFactory(); } }; BaseGfxFactory& BaseGfxFactory::getInstance() { return *rtl_Instance< BaseGfxFactory, InitInstance2, ::osl::MutexGuard, ::osl::GetGlobalMutex >::create( InitInstance2(), ::osl::GetGlobalMutex()); } BaseGfxFactory::BaseGfxFactory() { } BaseGfxFactory::~BaseGfxFactory() { } PolyPolygonSharedPtr BaseGfxFactory::createPolyPolygon( const CanvasSharedPtr& rCanvas, const ::basegfx::B2DPolygon& rPoly ) const { OSL_ENSURE( rCanvas.get() != NULL && rCanvas->getUNOCanvas().is(), "BaseGfxFactory::createPolyPolygon(): Invalid canvas" ); if( rCanvas.get() == NULL ) return PolyPolygonSharedPtr(); uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() ); if( !xCanvas.is() ) return PolyPolygonSharedPtr(); return PolyPolygonSharedPtr( new internal::ImplPolyPolygon( rCanvas, ::basegfx::unotools::xPolyPolygonFromB2DPolygon( xCanvas->getDevice(), rPoly) ) ); } PolyPolygonSharedPtr BaseGfxFactory::createPolyPolygon( const CanvasSharedPtr& rCanvas, const ::basegfx::B2DPolyPolygon& rPolyPoly ) const { OSL_ENSURE( rCanvas.get() != NULL && rCanvas->getUNOCanvas().is(), "BaseGfxFactory::createPolyPolygon(): Invalid canvas" ); if( rCanvas.get() == NULL ) return PolyPolygonSharedPtr(); uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() ); if( !xCanvas.is() ) return PolyPolygonSharedPtr(); return PolyPolygonSharedPtr( new internal::ImplPolyPolygon( rCanvas, ::basegfx::unotools::xPolyPolygonFromB2DPolyPolygon( xCanvas->getDevice(), rPolyPoly) ) ); } BitmapSharedPtr BaseGfxFactory::createBitmap( const CanvasSharedPtr& rCanvas, const ::basegfx::B2ISize& rSize ) const { OSL_ENSURE( rCanvas.get() != NULL && rCanvas->getUNOCanvas().is(), "BaseGfxFactory::createBitmap(): Invalid canvas" ); if( rCanvas.get() == NULL ) return BitmapSharedPtr(); uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() ); if( !xCanvas.is() ) return BitmapSharedPtr(); return BitmapSharedPtr( new internal::ImplBitmap( rCanvas, xCanvas->getDevice()->createCompatibleBitmap( ::basegfx::unotools::integerSize2DFromB2ISize(rSize) ) ) ); } BitmapSharedPtr BaseGfxFactory::createAlphaBitmap( const CanvasSharedPtr& rCanvas, const ::basegfx::B2ISize& rSize ) const { OSL_ENSURE( rCanvas.get() != NULL && rCanvas->getUNOCanvas().is(), "BaseGfxFactory::createBitmap(): Invalid canvas" ); if( rCanvas.get() == NULL ) return BitmapSharedPtr(); uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() ); if( !xCanvas.is() ) return BitmapSharedPtr(); return BitmapSharedPtr( new internal::ImplBitmap( rCanvas, xCanvas->getDevice()->createCompatibleAlphaBitmap( ::basegfx::unotools::integerSize2DFromB2ISize(rSize) ) ) ); } TextSharedPtr BaseGfxFactory::createText( const CanvasSharedPtr& rCanvas, const ::rtl::OUString& rText ) const { return TextSharedPtr( new internal::ImplText( rCanvas, rText ) ); } } <|endoftext|>
<commit_before>/* testsha1.cpp Copyright (c) 2005 Michael D. Leonhard http://tamale.net/ This file is licensed under the terms described in the accompanying LICENSE file. */ #include <cstdio> #include <cstdlib> #include <cassert> #include <fcntl.h> #include <vector> #include <iostream> #include "../src/sha1.h" int run_tests() { int ret = 0; // these example text blocks are taken from RFC3174 std::vector<std::pair<const char*, const char*> > tests; tests.push_back(std::pair<const char*, const char*>("abc","a9993e364706816aba3e25717850c26c9cd0d89d")); tests.push_back(std::pair<const char*, const char*>("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq","84983e441c3bd26ebaae4aa1f95129e5e54670f1")); tests.push_back(std::pair<const char*, const char*>("a","34aa973cd4c4daa4f61eeb2bdbad27316534016f")); tests.push_back(std::pair<const char*, const char*>("0123456701234567012345670123456701234567012345670123456701234567","dea356a2cddd90c7a7ecedc5ebb563934f460452")); std::vector<unsigned int> multiplier; multiplier.push_back(1); multiplier.push_back(1); multiplier.push_back(1000000); multiplier.push_back(10); int passed = 0; int passed_h = 0; int passed_c = 0; unsigned char sig[SHA1_SIZE], sig2[SHA1_SIZE]; char str[SHA1_STRING_SIZE]; /* run our tests */ for (unsigned int i = 0; i < tests.size(); i++) { bool passed_hash = 0; bool passed_convert = 0; sha1::sha1_t sha1; for (unsigned int j = 0; j < multiplier[i]; j++) { sha1.process(tests[i].first, strlen(tests[i].first)); } sha1.finish(sig); /* convert from the sig to a string rep */ sha1::sig_to_string(sig, str, sizeof(str)); if (strcmp(str, tests[i].second) == 0) { passed_hash = true; passed_h++; } /* convert from the string back into a MD5 signature */ sha1::sig_from_string(sig2, str); if (memcmp(sig, sig2, SHA1_SIZE) == 0) { passed_convert = true; passed_c++; } if (passed_hash and passed_convert) { std::cout << "TEST " << i + 1 << " PASSED" << std::endl; passed++; } else { std::cout << "TEST " << i + 1 << " FAILED" << std::endl; } } std::cout << std::endl << "*******************************" << std::endl << " " << passed << " of " << tests.size() << " tests passed" << std::endl; if (passed != tests.size()) { ret = 1; std::cout << std::endl << " Please notify developer" << std::endl; std::cout << " " << passed_h << " passed hashing check" << std::endl << " " << passed_h << " passed comparison check" << std::endl; } std::cout << "*******************************" << std::endl; return ret; } int read_input(int argc, char** argv) { sha1::sha1_t sha1; unsigned char* digest; const unsigned int buffer_size = 8192; assert( argv[1] ); if (argv[1][0] == '-') { } /* open the file */ int fd = open( argv[1], O_RDONLY | O_BINARY, 0 ); /* handle open failure */ if( fd == -1 ) { fprintf( stderr, "cannot open file %s\n", argv[1] ); return 1; } /* prepare to calculate the SHA-1 hash */ char* buffer = (char*)malloc( buffer_size ); assert( buffer ); /* loop through the file */ int ret; while( true ) { /* read a chunk of data */ ret = read( fd, buffer, buffer_size ); /* check for error and end of file */ if( ret < 1 ) break; /* run this data through the hash function */ sha1.process(buffer, ret); } /* close the file */ close( fd ); /* there was an error reading the file */ if( ret == -1 ) { fprintf( stderr, "error reading %s.\n", argv[1] ); return 1; } /* get the digest */ sha1.finish(digest); assert( digest ); /* print it out */ printf( "%s:", argv[1] ); printf( "\n" ); fflush( stdout ); free( digest ); return 0; } int main(int argc, char* argv[]) { if( argc == 2 ) { return read_input(argc, argv); } else { return run_tests(); } } <commit_msg>removes incorrect copyright notice from file's origins<commit_after>#include <cstdio> #include <cstdlib> #include <cassert> #include <fcntl.h> #include <vector> #include <iostream> #include "../src/sha1.h" int run_tests() { int ret = 0; // these example text blocks are taken from RFC3174 std::vector<std::pair<const char*, const char*> > tests; tests.push_back(std::pair<const char*, const char*>("abc","a9993e364706816aba3e25717850c26c9cd0d89d")); tests.push_back(std::pair<const char*, const char*>("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq","84983e441c3bd26ebaae4aa1f95129e5e54670f1")); tests.push_back(std::pair<const char*, const char*>("a","34aa973cd4c4daa4f61eeb2bdbad27316534016f")); tests.push_back(std::pair<const char*, const char*>("0123456701234567012345670123456701234567012345670123456701234567","dea356a2cddd90c7a7ecedc5ebb563934f460452")); std::vector<unsigned int> multiplier; multiplier.push_back(1); multiplier.push_back(1); multiplier.push_back(1000000); multiplier.push_back(10); int passed = 0; int passed_h = 0; int passed_c = 0; unsigned char sig[SHA1_SIZE], sig2[SHA1_SIZE]; char str[SHA1_STRING_SIZE]; /* run our tests */ for (unsigned int i = 0; i < tests.size(); i++) { bool passed_hash = 0; bool passed_convert = 0; sha1::sha1_t sha1; for (unsigned int j = 0; j < multiplier[i]; j++) { sha1.process(tests[i].first, strlen(tests[i].first)); } sha1.finish(sig); /* convert from the sig to a string rep */ sha1::sig_to_string(sig, str, sizeof(str)); if (strcmp(str, tests[i].second) == 0) { passed_hash = true; passed_h++; } /* convert from the string back into a MD5 signature */ sha1::sig_from_string(sig2, str); if (memcmp(sig, sig2, SHA1_SIZE) == 0) { passed_convert = true; passed_c++; } if (passed_hash and passed_convert) { std::cout << "TEST " << i + 1 << " PASSED" << std::endl; passed++; } else { std::cout << "TEST " << i + 1 << " FAILED" << std::endl; } } std::cout << std::endl << "*******************************" << std::endl << " " << passed << " of " << tests.size() << " tests passed" << std::endl; if (passed != tests.size()) { ret = 1; std::cout << std::endl << " Please notify developer" << std::endl; std::cout << " " << passed_h << " passed hashing check" << std::endl << " " << passed_h << " passed comparison check" << std::endl; } std::cout << "*******************************" << std::endl; return ret; } int read_input(int argc, char** argv) { sha1::sha1_t sha1; unsigned char* digest; const unsigned int buffer_size = 8192; assert( argv[1] ); if (argv[1][0] == '-') { } /* open the file */ int fd = open( argv[1], O_RDONLY | O_BINARY, 0 ); /* handle open failure */ if( fd == -1 ) { fprintf( stderr, "cannot open file %s\n", argv[1] ); return 1; } /* prepare to calculate the SHA-1 hash */ char* buffer = (char*)malloc( buffer_size ); assert( buffer ); /* loop through the file */ int ret; while( true ) { /* read a chunk of data */ ret = read( fd, buffer, buffer_size ); /* check for error and end of file */ if( ret < 1 ) break; /* run this data through the hash function */ sha1.process(buffer, ret); } /* close the file */ close( fd ); /* there was an error reading the file */ if( ret == -1 ) { fprintf( stderr, "error reading %s.\n", argv[1] ); return 1; } /* get the digest */ sha1.finish(digest); assert( digest ); /* print it out */ printf( "%s:", argv[1] ); printf( "\n" ); fflush( stdout ); free( digest ); return 0; } int main(int argc, char* argv[]) { if( argc == 2 ) { return read_input(argc, argv); } else { return run_tests(); } } <|endoftext|>
<commit_before>#include <memory> #include <future> #include "integration_test_helper.h" #include "camera_test_helpers.h" using namespace dronecore; Camera::Mode get_mode(std::shared_ptr<Camera> camera) { struct PromiseResult { Camera::Result result; Camera::Mode mode; }; auto prom = std::make_shared<std::promise<PromiseResult>>(); auto ret = prom->get_future(); camera->get_mode_async([prom](Camera::Result result, Camera::Mode mode) { PromiseResult pr {}; pr.result = result; pr.mode = mode; prom->set_value(pr); }); auto status = ret.wait_for(std::chrono::seconds(7)); EXPECT_EQ(status, std::future_status::ready); if (status == std::future_status::ready) { PromiseResult new_ret = ret.get(); EXPECT_EQ(new_ret.result, Camera::Result::SUCCESS); EXPECT_NE(new_ret.mode, Camera::Mode::UNKNOWN); return new_ret.mode; } else { return Camera::Mode::UNKNOWN; } } void set_mode(std::shared_ptr<Camera> camera, Camera::Mode mode) { Camera::Mode mode_already_set = get_mode(camera); // FIXME: this should not be required. std::this_thread::sleep_for(std::chrono::seconds(2)); if (mode == mode_already_set) { return; } auto prom = std::make_shared<std::promise<void>>(); auto ret = prom->get_future(); camera->set_mode_async(mode, [mode, prom](Camera::Result result, Camera::Mode mode_got) { EXPECT_EQ(result, Camera::Result::SUCCESS); EXPECT_EQ(mode, mode_got); prom->set_value(); }); auto status = ret.wait_for(std::chrono::seconds(10)); EXPECT_EQ(status, std::future_status::ready); if (status == std::future_status::ready) { ret.get(); } // FIXME: this should not be required. std::this_thread::sleep_for(std::chrono::seconds(1)); } Camera::Result set_setting(std::shared_ptr<Camera> camera, const std::string &setting, const std::string &option) { auto prom = std::make_shared<std::promise<Camera::Result>>(); auto ret = prom->get_future(); camera->set_option_async(setting, option, [prom](Camera::Result result) { prom->set_value(result); }); auto status = ret.wait_for(std::chrono::seconds(1)); EXPECT_EQ(status, std::future_status::ready); if (status == std::future_status::ready) { return ret.get(); } return Camera::Result::TIMEOUT; } dronecore::Camera::Result get_setting(std::shared_ptr<dronecore::Camera> camera, const std::string &setting, std::string &option) { struct PromiseResult { Camera::Result result; std::string value; }; auto prom = std::make_shared<std::promise<PromiseResult>>(); auto ret = prom->get_future(); camera->get_option_async(setting, [prom](Camera::Result result, const std::string & value) { PromiseResult promise_result; promise_result.result = result; promise_result.value = value; prom->set_value(promise_result); }); auto status = ret.wait_for(std::chrono::seconds(1)); EXPECT_EQ(status, std::future_status::ready); if (status == std::future_status::ready) { PromiseResult promise_result = ret.get(); option = promise_result.value; return promise_result.result; } return Camera::Result::TIMEOUT; } <commit_msg>camera: get mode before set mode not needed<commit_after>#include <memory> #include <future> #include "integration_test_helper.h" #include "camera_test_helpers.h" using namespace dronecore; Camera::Mode get_mode(std::shared_ptr<Camera> camera) { struct PromiseResult { Camera::Result result; Camera::Mode mode; }; auto prom = std::make_shared<std::promise<PromiseResult>>(); auto ret = prom->get_future(); camera->get_mode_async([prom](Camera::Result result, Camera::Mode mode) { PromiseResult pr {}; pr.result = result; pr.mode = mode; prom->set_value(pr); }); auto status = ret.wait_for(std::chrono::seconds(7)); EXPECT_EQ(status, std::future_status::ready); if (status == std::future_status::ready) { PromiseResult new_ret = ret.get(); EXPECT_EQ(new_ret.result, Camera::Result::SUCCESS); EXPECT_NE(new_ret.mode, Camera::Mode::UNKNOWN); return new_ret.mode; } else { return Camera::Mode::UNKNOWN; } } void set_mode(std::shared_ptr<Camera> camera, Camera::Mode mode) { //// FIXME: this should not be required. std::this_thread::sleep_for(std::chrono::seconds(1)); auto prom = std::make_shared<std::promise<void>>(); auto ret = prom->get_future(); camera->set_mode_async(mode, [mode, prom](Camera::Result result, Camera::Mode mode_got) { EXPECT_EQ(result, Camera::Result::SUCCESS); EXPECT_EQ(mode, mode_got); prom->set_value(); }); auto status = ret.wait_for(std::chrono::seconds(10)); EXPECT_EQ(status, std::future_status::ready); if (status == std::future_status::ready) { ret.get(); } // FIXME: this should not be required. std::this_thread::sleep_for(std::chrono::seconds(1)); } Camera::Result set_setting(std::shared_ptr<Camera> camera, const std::string &setting, const std::string &option) { auto prom = std::make_shared<std::promise<Camera::Result>>(); auto ret = prom->get_future(); camera->set_option_async(setting, option, [prom](Camera::Result result) { prom->set_value(result); }); auto status = ret.wait_for(std::chrono::seconds(1)); EXPECT_EQ(status, std::future_status::ready); if (status == std::future_status::ready) { return ret.get(); } return Camera::Result::TIMEOUT; } dronecore::Camera::Result get_setting(std::shared_ptr<dronecore::Camera> camera, const std::string &setting, std::string &option) { struct PromiseResult { Camera::Result result; std::string value; }; auto prom = std::make_shared<std::promise<PromiseResult>>(); auto ret = prom->get_future(); camera->get_option_async(setting, [prom](Camera::Result result, const std::string & value) { PromiseResult promise_result; promise_result.result = result; promise_result.value = value; prom->set_value(promise_result); }); auto status = ret.wait_for(std::chrono::seconds(1)); EXPECT_EQ(status, std::future_status::ready); if (status == std::future_status::ready) { PromiseResult promise_result = ret.get(); option = promise_result.value; return promise_result.result; } return Camera::Result::TIMEOUT; } <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2013 ETH Zurich ** 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 ETH Zurich 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 "OOReference.h" #include "../expressions/ReferenceExpression.h" #include "../declarations/Class.h" #include "../declarations/Method.h" #include "../expressions/types/ClassTypeExpression.h" #include "../expressions/types/ArrayTypeExpression.h" #include "../expressions/MethodCallExpression.h" #include "../expressions/AssignmentExpression.h" #include "../expressions/CastExpression.h" #include "../types/SymbolProviderType.h" #include "../types/ErrorType.h" #include "../typesystem/TypeSystem.h" #include "ModelBase/src/nodes/TypedListDefinition.h" DEFINE_TYPED_LIST(OOModel::OOReference) namespace OOModel { NODE_DEFINE_EMPTY_CONSTRUCTORS(OOReference) NODE_DEFINE_TYPE_REGISTRATION_METHODS(OOReference) bool OOReference::resolve() { // TODO Handle the case where the symbol is defined multiple times in a better way // TODO this is not multithread friendly. if (resolving_) return false; resolving_ = true; auto parent = static_cast<ReferenceExpression*>(this->parent()); SymbolTypes searchForType = ANY_SYMBOL; if ( referenceTargetKind() != ReferenceTargetKind::Callable ) searchForType &= ~METHOD; QSet<Node*> candidateTargets; if (parent->prefix()) { // Perform a downward search starting from the target of the prefix auto t = parent->prefix()->type(); if (auto sp = dynamic_cast<SymbolProviderType*>(t)) { if (sp->symbolProvider()) { // It's important below that we change the source to sp->symbolProvider() in the call to findSymbols. // See NameImport.cpp for more info. sp->symbolProvider()->findSymbols(candidateTargets, name(), sp->symbolProvider(), SEARCH_DOWN, searchForType, searchForType.testFlag(METHOD) ); // When search for methods do an exhaustive search. // This is important for overloads. } } SAFE_DELETE(t); } else { // Perform an upward search starting from the current node // When search for methods do an exhaustive search. This is important for overloads. findSymbols(candidateTargets, name(), this, SEARCH_UP, searchForType, searchForType.testFlag(METHOD)); } setTarget( resolveAmbiguity(candidateTargets) ); resolving_ = false; return isResolved(); } OOReference::ReferenceTargetKind OOReference::referenceTargetKind() { auto parentRefExpr = static_cast<ReferenceExpression*>(this->parent()); auto construct = parentRefExpr->parent(); if (auto refExpr = DCast<ReferenceExpression>(construct)) { // If this reference appears before a '.' operator, it must be a container if (parentRefExpr == refExpr->prefix()) return ReferenceTargetKind::Container; } else if (auto vd = DCast<VariableDeclaration>(construct)) { if (parentRefExpr == vd->typeExpression()) return ReferenceTargetKind::Type; } else if (auto fr = DCast<FormalResult>(construct)) { if (parentRefExpr == fr->typeExpression()) return ReferenceTargetKind::Type; } else if (auto fa = DCast<FormalArgument>(construct)) { if (parentRefExpr == fa->typeExpression()) return ReferenceTargetKind::Type; } else if (auto ate = DCast<ArrayTypeExpression>(construct)) { if (parentRefExpr == ate->typeExpression()) return ReferenceTargetKind::Type; } else if (auto ce = DCast<CastExpression>(construct)) { if (parentRefExpr == ce->castType()) return ReferenceTargetKind::Type; } else if (auto cte = DCast<ClassTypeExpression>(construct)) { if (parentRefExpr == cte->typeExpression()) return ReferenceTargetKind::Type; } else if (auto mce = DCast<MethodCallExpression>(construct)) { if (parentRefExpr == mce->callee()) return ReferenceTargetKind::Callable; } else if (auto ae = DCast<AssignmentExpression>(construct)) { if (parentRefExpr == ae->left()) return ReferenceTargetKind::Assignable; } else if (auto el = DCast<Model::TypedList<Expression>>(construct)) { if (auto cl = DCast<Class>(el->parent())) { if (el == cl->baseClasses()) return ReferenceTargetKind::Container; } else if (auto refExpr = DCast<ReferenceExpression>(el->parent())) { if (el == refExpr->typeArguments()) return ReferenceTargetKind::Container; } } return ReferenceTargetKind::Unknown; } Model::Node* OOReference::resolveAmbiguity(QSet<Model::Node*>& candidates) { if ( candidates.isEmpty() ) return nullptr; if ( candidates.size() == 1) return *candidates.begin(); // TODO: possibly check this for compliance? auto parentRefExpr = static_cast<ReferenceExpression*>(this->parent()); auto construct = parentRefExpr->parent(); // Looking for Methods if (auto mce = DCast<MethodCallExpression>(construct)) { auto methodToCall = resolveAmbiguousMethodCall(candidates, mce); if (methodToCall) return methodToCall; } // Looking for Types, remove variables, fields, etc if (referenceTargetKind() == ReferenceTargetKind::Type) { auto it = candidates.begin(); while (it != candidates.end()) { if ( DCast<VariableDeclaration>(*it) || DCast<FormalArgument>(*it) || DCast<FormalArgument>(*it)) it = candidates.erase(it); else ++it; } } if (candidates.size() == 1) return *candidates.begin(); // Looking for Assignables, remove methods, classes, etc if (referenceTargetKind() == ReferenceTargetKind::Assignable) { auto it = candidates.begin(); while (it != candidates.end()) { if ( DCast<VariableDeclaration>(*it) || DCast<FormalArgument>(*it) || DCast<FormalArgument>(*it)) ++it = candidates.erase(it); else it = candidates.erase(it); } } if (candidates.size() == 1) return *candidates.begin(); //TODO: Resolve additional ambiguities return nullptr; } Model::Node* OOReference::resolveAmbiguousMethodCall(QSet<Model::Node*>& candidates, MethodCallExpression* callExpression) { // TODO: So far this implements only the simpler cases of Java. Complex cases or other languages need to be // considered. QSet<Method*> filtered; // Get all methods and forget about the rest. for(auto target : candidates) if (auto method = DCast<Method>(target)) filtered.insert(method); if (filtered.size() == 1) return *filtered.begin(); if (filtered.isEmpty()) return nullptr; removeMethodsWithDifferentNumberOfArguments(filtered, callExpression); if (filtered.size() == 1) return *filtered.begin(); if (filtered.isEmpty()) return nullptr; removeMethodsWithIncompatibleTypeOfArguments(filtered, callExpression); if (filtered.size() == 1) return *filtered.begin(); if (filtered.isEmpty()) return nullptr; removeOverridenMethods(filtered); if (filtered.size() == 1) return *filtered.begin(); if (filtered.isEmpty()) return nullptr; removeLessSpecificMethods(filtered); if (filtered.size() == 1) return *filtered.begin(); candidates.clear(); for(auto m : filtered) candidates.insert(m); //TODO: check for correct access of public/private return nullptr; } void OOReference::removeMethodsWithDifferentNumberOfArguments(QSet<Method*>& methods, MethodCallExpression* callExpression) { auto callee = static_cast<ReferenceExpression*>(callExpression->callee()); // Exclude methods with less type arguments or unequal number of formal arguments // TODO: Consider default method arguments and variable method arity. auto it = methods.begin(); while(it != methods.end()) { if ((*it)->typeArguments()->size() < callee->typeArguments()->size() || callExpression->arguments()->size() != (*it)->arguments()->size()) it = methods.erase(it); else ++ it; } } void OOReference::removeMethodsWithIncompatibleTypeOfArguments(QSet<Method*>& methods, MethodCallExpression* callExpression) { int argId = 0; for(auto arg: *callExpression->arguments()) { auto actualArgType = arg->type(); auto it = methods.begin(); while(it != methods.end()) { auto formalArgType = (*it)->arguments()->at(argId)->typeExpression()->type(); auto typeRelation = actualArgType->relationTo(formalArgType); if ( typeRelation.testFlag(TypeSystem::Equal) || typeRelation.testFlag(TypeSystem::IsSubtype) || typeRelation.testFlag(TypeSystem::IsConvertibleTo)) ++it; else it = methods.erase(it); SAFE_DELETE(formalArgType); } SAFE_DELETE(actualArgType); ++argId; } } void OOReference::removeOverridenMethods(QSet<Method*>& methods) { QSet<Method*> nonOverriden; while (!methods.isEmpty()) { auto m = *methods.begin(); methods.remove(m); bool overriden = false; auto it = methods.begin(); while (it != methods.end()) { if ((*it)->overrides(m)) { overriden = true; break; } if (m->overrides((*it))) it = methods.erase(it); else ++it; } if (!overriden) nonOverriden.insert(m); } methods = nonOverriden; } void OOReference::removeLessSpecificMethods(QSet<Method*>& methods) { QSet<Method*> mostSpecific; while(!methods.isEmpty()) { enum Specificity {UNDETERMINED, MORE, LESS, SAME}; Specificity overallSpecificity = UNDETERMINED; auto m = *methods.begin(); methods.remove(m); QList<Type*> filteredTypes; for (auto te : *m->arguments()) filteredTypes.append(te->typeExpression()->type()); // Compare this method to all the ones that are already most specifc. // Remove any most specific method that is strictly less specific than the current one. auto sIt = mostSpecific.begin(); while(sIt != mostSpecific.end()) { Specificity specificity = UNDETERMINED; for(int argId = 0; argId < filteredTypes.size(); ++argId) { auto spType = (*sIt)->arguments()->at(argId)->typeExpression()->type(); auto relation = filteredTypes.at(argId)->relationTo(spType); if (relation.testFlag(TypeSystem::Equal)) /* Do nothing*/; else if (relation.testFlag(TypeSystem::IsSubtype) && specificity == UNDETERMINED) specificity = MORE; else if (relation.testFlag(TypeSystem::IsSubtype) && specificity == MORE) /* Do nothing*/; else if (relation.testFlag(TypeSystem::IsSubtype) && specificity == LESS) specificity = SAME; else if (relation.testFlag(TypeSystem::IsSupertype) && specificity == UNDETERMINED) specificity = LESS; else if (relation.testFlag(TypeSystem::IsSupertype) && specificity == LESS) /* Do nothing*/; else if (relation.testFlag(TypeSystem::IsSupertype) && specificity == MORE) specificity = SAME; SAFE_DELETE(spType); if (specificity == SAME) break; } if (specificity == MORE) { sIt = mostSpecific.erase(sIt); Q_ASSERT(overallSpecificity != LESS); if(overallSpecificity == UNDETERMINED) overallSpecificity = MORE; } else if (specificity == LESS) { Q_ASSERT(overallSpecificity != MORE); overallSpecificity = LESS; break; } else if (specificity == SAME || specificity == UNDETERMINED) { // UNDETERMINED means an identical or a completely unrelated signature ++sIt; overallSpecificity = SAME; } } for(auto t : filteredTypes) SAFE_DELETE(t); Q_ASSERT(mostSpecific.isEmpty() || overallSpecificity != UNDETERMINED); if (overallSpecificity != LESS) mostSpecific.insert(m); } methods = mostSpecific; Q_ASSERT(!methods.isEmpty()); } } /* namespace OOModel */ <commit_msg>Fix an embarrassing copy/paste bug that makes reference resolution crash<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2013 ETH Zurich ** 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 ETH Zurich 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 "OOReference.h" #include "../expressions/ReferenceExpression.h" #include "../declarations/Class.h" #include "../declarations/Method.h" #include "../expressions/types/ClassTypeExpression.h" #include "../expressions/types/ArrayTypeExpression.h" #include "../expressions/MethodCallExpression.h" #include "../expressions/AssignmentExpression.h" #include "../expressions/CastExpression.h" #include "../types/SymbolProviderType.h" #include "../types/ErrorType.h" #include "../typesystem/TypeSystem.h" #include "ModelBase/src/nodes/TypedListDefinition.h" DEFINE_TYPED_LIST(OOModel::OOReference) namespace OOModel { NODE_DEFINE_EMPTY_CONSTRUCTORS(OOReference) NODE_DEFINE_TYPE_REGISTRATION_METHODS(OOReference) bool OOReference::resolve() { // TODO Handle the case where the symbol is defined multiple times in a better way // TODO this is not multithread friendly. if (resolving_) return false; resolving_ = true; auto parent = static_cast<ReferenceExpression*>(this->parent()); SymbolTypes searchForType = ANY_SYMBOL; if ( referenceTargetKind() != ReferenceTargetKind::Callable ) searchForType &= ~METHOD; QSet<Node*> candidateTargets; if (parent->prefix()) { // Perform a downward search starting from the target of the prefix auto t = parent->prefix()->type(); if (auto sp = dynamic_cast<SymbolProviderType*>(t)) { if (sp->symbolProvider()) { // It's important below that we change the source to sp->symbolProvider() in the call to findSymbols. // See NameImport.cpp for more info. sp->symbolProvider()->findSymbols(candidateTargets, name(), sp->symbolProvider(), SEARCH_DOWN, searchForType, searchForType.testFlag(METHOD) ); // When search for methods do an exhaustive search. // This is important for overloads. } } SAFE_DELETE(t); } else { // Perform an upward search starting from the current node // When search for methods do an exhaustive search. This is important for overloads. findSymbols(candidateTargets, name(), this, SEARCH_UP, searchForType, searchForType.testFlag(METHOD)); } setTarget( resolveAmbiguity(candidateTargets) ); resolving_ = false; return isResolved(); } OOReference::ReferenceTargetKind OOReference::referenceTargetKind() { auto parentRefExpr = static_cast<ReferenceExpression*>(this->parent()); auto construct = parentRefExpr->parent(); if (auto refExpr = DCast<ReferenceExpression>(construct)) { // If this reference appears before a '.' operator, it must be a container if (parentRefExpr == refExpr->prefix()) return ReferenceTargetKind::Container; } else if (auto vd = DCast<VariableDeclaration>(construct)) { if (parentRefExpr == vd->typeExpression()) return ReferenceTargetKind::Type; } else if (auto fr = DCast<FormalResult>(construct)) { if (parentRefExpr == fr->typeExpression()) return ReferenceTargetKind::Type; } else if (auto fa = DCast<FormalArgument>(construct)) { if (parentRefExpr == fa->typeExpression()) return ReferenceTargetKind::Type; } else if (auto ate = DCast<ArrayTypeExpression>(construct)) { if (parentRefExpr == ate->typeExpression()) return ReferenceTargetKind::Type; } else if (auto ce = DCast<CastExpression>(construct)) { if (parentRefExpr == ce->castType()) return ReferenceTargetKind::Type; } else if (auto cte = DCast<ClassTypeExpression>(construct)) { if (parentRefExpr == cte->typeExpression()) return ReferenceTargetKind::Type; } else if (auto mce = DCast<MethodCallExpression>(construct)) { if (parentRefExpr == mce->callee()) return ReferenceTargetKind::Callable; } else if (auto ae = DCast<AssignmentExpression>(construct)) { if (parentRefExpr == ae->left()) return ReferenceTargetKind::Assignable; } else if (auto el = DCast<Model::TypedList<Expression>>(construct)) { if (auto cl = DCast<Class>(el->parent())) { if (el == cl->baseClasses()) return ReferenceTargetKind::Container; } else if (auto refExpr = DCast<ReferenceExpression>(el->parent())) { if (el == refExpr->typeArguments()) return ReferenceTargetKind::Container; } } return ReferenceTargetKind::Unknown; } Model::Node* OOReference::resolveAmbiguity(QSet<Model::Node*>& candidates) { if ( candidates.isEmpty() ) return nullptr; if ( candidates.size() == 1) return *candidates.begin(); // TODO: possibly check this for compliance? auto parentRefExpr = static_cast<ReferenceExpression*>(this->parent()); auto construct = parentRefExpr->parent(); // Looking for Methods if (auto mce = DCast<MethodCallExpression>(construct)) { auto methodToCall = resolveAmbiguousMethodCall(candidates, mce); if (methodToCall) return methodToCall; } // Looking for Types, remove variables, fields, etc if (referenceTargetKind() == ReferenceTargetKind::Type) { auto it = candidates.begin(); while (it != candidates.end()) { if ( DCast<VariableDeclaration>(*it) || DCast<FormalArgument>(*it) || DCast<FormalArgument>(*it)) it = candidates.erase(it); else ++it; } } if (candidates.size() == 1) return *candidates.begin(); // Looking for Assignables, remove methods, classes, etc if (referenceTargetKind() == ReferenceTargetKind::Assignable) { auto it = candidates.begin(); while (it != candidates.end()) { if ( DCast<VariableDeclaration>(*it) || DCast<FormalArgument>(*it) || DCast<FormalArgument>(*it)) ++it; else it = candidates.erase(it); } } if (candidates.size() == 1) return *candidates.begin(); //TODO: Resolve additional ambiguities return nullptr; } Model::Node* OOReference::resolveAmbiguousMethodCall(QSet<Model::Node*>& candidates, MethodCallExpression* callExpression) { // TODO: So far this implements only the simpler cases of Java. Complex cases or other languages need to be // considered. QSet<Method*> filtered; // Get all methods and forget about the rest. for(auto target : candidates) if (auto method = DCast<Method>(target)) filtered.insert(method); if (filtered.size() == 1) return *filtered.begin(); if (filtered.isEmpty()) return nullptr; removeMethodsWithDifferentNumberOfArguments(filtered, callExpression); if (filtered.size() == 1) return *filtered.begin(); if (filtered.isEmpty()) return nullptr; removeMethodsWithIncompatibleTypeOfArguments(filtered, callExpression); if (filtered.size() == 1) return *filtered.begin(); if (filtered.isEmpty()) return nullptr; removeOverridenMethods(filtered); if (filtered.size() == 1) return *filtered.begin(); if (filtered.isEmpty()) return nullptr; removeLessSpecificMethods(filtered); if (filtered.size() == 1) return *filtered.begin(); candidates.clear(); for(auto m : filtered) candidates.insert(m); //TODO: check for correct access of public/private return nullptr; } void OOReference::removeMethodsWithDifferentNumberOfArguments(QSet<Method*>& methods, MethodCallExpression* callExpression) { auto callee = static_cast<ReferenceExpression*>(callExpression->callee()); // Exclude methods with less type arguments or unequal number of formal arguments // TODO: Consider default method arguments and variable method arity. auto it = methods.begin(); while(it != methods.end()) { if ((*it)->typeArguments()->size() < callee->typeArguments()->size() || callExpression->arguments()->size() != (*it)->arguments()->size()) it = methods.erase(it); else ++ it; } } void OOReference::removeMethodsWithIncompatibleTypeOfArguments(QSet<Method*>& methods, MethodCallExpression* callExpression) { int argId = 0; for(auto arg: *callExpression->arguments()) { auto actualArgType = arg->type(); auto it = methods.begin(); while(it != methods.end()) { auto formalArgType = (*it)->arguments()->at(argId)->typeExpression()->type(); auto typeRelation = actualArgType->relationTo(formalArgType); if ( typeRelation.testFlag(TypeSystem::Equal) || typeRelation.testFlag(TypeSystem::IsSubtype) || typeRelation.testFlag(TypeSystem::IsConvertibleTo)) ++it; else it = methods.erase(it); SAFE_DELETE(formalArgType); } SAFE_DELETE(actualArgType); ++argId; } } void OOReference::removeOverridenMethods(QSet<Method*>& methods) { QSet<Method*> nonOverriden; while (!methods.isEmpty()) { auto m = *methods.begin(); methods.remove(m); bool overriden = false; auto it = methods.begin(); while (it != methods.end()) { if ((*it)->overrides(m)) { overriden = true; break; } if (m->overrides((*it))) it = methods.erase(it); else ++it; } if (!overriden) nonOverriden.insert(m); } methods = nonOverriden; } void OOReference::removeLessSpecificMethods(QSet<Method*>& methods) { QSet<Method*> mostSpecific; while(!methods.isEmpty()) { enum Specificity {UNDETERMINED, MORE, LESS, SAME}; Specificity overallSpecificity = UNDETERMINED; auto m = *methods.begin(); methods.remove(m); QList<Type*> filteredTypes; for (auto te : *m->arguments()) filteredTypes.append(te->typeExpression()->type()); // Compare this method to all the ones that are already most specifc. // Remove any most specific method that is strictly less specific than the current one. auto sIt = mostSpecific.begin(); while(sIt != mostSpecific.end()) { Specificity specificity = UNDETERMINED; for(int argId = 0; argId < filteredTypes.size(); ++argId) { auto spType = (*sIt)->arguments()->at(argId)->typeExpression()->type(); auto relation = filteredTypes.at(argId)->relationTo(spType); if (relation.testFlag(TypeSystem::Equal)) /* Do nothing*/; else if (relation.testFlag(TypeSystem::IsSubtype) && specificity == UNDETERMINED) specificity = MORE; else if (relation.testFlag(TypeSystem::IsSubtype) && specificity == MORE) /* Do nothing*/; else if (relation.testFlag(TypeSystem::IsSubtype) && specificity == LESS) specificity = SAME; else if (relation.testFlag(TypeSystem::IsSupertype) && specificity == UNDETERMINED) specificity = LESS; else if (relation.testFlag(TypeSystem::IsSupertype) && specificity == LESS) /* Do nothing*/; else if (relation.testFlag(TypeSystem::IsSupertype) && specificity == MORE) specificity = SAME; SAFE_DELETE(spType); if (specificity == SAME) break; } if (specificity == MORE) { sIt = mostSpecific.erase(sIt); Q_ASSERT(overallSpecificity != LESS); if(overallSpecificity == UNDETERMINED) overallSpecificity = MORE; } else if (specificity == LESS) { Q_ASSERT(overallSpecificity != MORE); overallSpecificity = LESS; break; } else if (specificity == SAME || specificity == UNDETERMINED) { // UNDETERMINED means an identical or a completely unrelated signature ++sIt; overallSpecificity = SAME; } } for(auto t : filteredTypes) SAFE_DELETE(t); Q_ASSERT(mostSpecific.isEmpty() || overallSpecificity != UNDETERMINED); if (overallSpecificity != LESS) mostSpecific.insert(m); } methods = mostSpecific; Q_ASSERT(!methods.isEmpty()); } } /* namespace OOModel */ <|endoftext|>
<commit_before>#include <stdlib.h> #include <fstream> #include <iostream> #include <string> #include <map> #include <vector> using namespace std; char HSH = '#'; string LEN = "len:"; int SEG_LEN; string ITER = "iter:"; string ROT = "rot:"; string REP = "rep:"; string START = "start:"; // +(theta) turn left by angle theta char PLS = '+'; // -(theta) turn right by angle theta char MIN = '-'; // &(theta) pitch down by angle theta char AMP = '&'; // ^(theta) pitch up by angle theta char NCH = '^'; // /(theta) roll left by angle theta char FSL = '/'; // \(theta) roll right by angle theta char BSL = '\\'; // | is equivalent to +(180) -(180) char VER = '|'; //couldn't get atoi or stoi to work for me int ctoi (char c) { int i; if (c == '1'){ i = 1; } else if (c == '2') { i = 2; } else if (c == '3') { i = 3; } else if (c == '4') { i = 4; } else if (c == '5') { i = 5; } else if (c == '6') { i = 6; } else if (c == '7') { i = 7; } else if (c == '8') { i = 8; } else if (c == '9') { i = 9; } else { i = -1; //not an int } return i; } void process_line ( string l ) { string t; //temp int d_pos; int d_len; int l_length = l.length(); cout << "l_length = " << l_length << endl; string l_sub4 = l.substr(0, 4); cout << "l_sub4 = " << l_sub4 << endl; if (l[0] == HSH) { cout << "comment" << endl; return; //ignore comment } else if (l_sub4.compare (LEN) == 0) { cout << "length" << endl; d_pos = 5; d_len = l_length - d_pos; cout << "d_len = " << d_len << endl; if (d_len == 1){ SEG_LEN = ctoi(l[d_pos]); } cout << "SEG_LEN = " << SEG_LEN << endl; return; } else if (l.substr(0, 5).compare (ITER) == 0) { cout << "iter" << endl; return; } else if (l_sub4.compare (ROT) == 0) { cout << "rot" << endl; return; } else if (l_sub4.compare (REP) == 0) { cout << "rep" << endl; return; } else if (l.substr(0, 6).compare (START) == 0 ) { cout << "start" << endl; return; } else { //cout << l[i] << endl; } }//process_line int main ( ) { string line; string filename = "test/lsys1"; filename = filename + ".txt"; cout << filename << endl; ifstream in (filename.c_str()); if (in.is_open ( ) ) { cout << "File is open" << endl; while(in.good ( ) ) { getline (in, line); process_line (line); } } else { cout << "The file couldn't open" << endl; } } <commit_msg>implemented process_line()<commit_after>#include <stdlib.h> #include <fstream> #include <iostream> #include <string> #include <map> #include <vector> using namespace std; bool start; char HSH = '#'; char SPACE = ' '; string LEN = "len:"; int SEG_LEN; string ITER = "iter:"; int ITERATIONS; string ROT = "rot:"; vector<float> ROTATIONS; string REP = "rep:"; string START = "start:"; //"initial turtle string" string INIT_STR; // +(theta) turn left by angle theta char PLS = '+'; // -(theta) turn right by angle theta char MIN = '-'; // &(theta) pitch down by angle theta char AMP = '&'; // ^(theta) pitch up by angle theta char NCH = '^'; // /(theta) roll left by angle theta char FSL = '/'; // \(theta) roll right by angle theta char BSL = '\\'; // | is equivalent to +(180) -(180) char VER = '|'; void process_line ( string l ) { if (start) { execute(l); } string t; //temp int d_pos; int d_len; int l_length = l.length( ); cout << "l_length = " << l_length << endl; string l_sub4 = l.substr(0, 4); cout << "l_sub4 = " << l_sub4 << endl; if (l[0] == HSH) { cout << "comment" << endl; return; //ignore comment } else if (l_sub4.compare(LEN) == 0) { cout << "length" << endl; d_pos = 5; d_len = l_length - d_pos; t = l.substr(d_pos, d_len); sscanf(t.c_str( ), "%d", &SEG_LEN); cout << "SEG_LEN = " << SEG_LEN << endl; return; } else if (l.substr(0, 5).compare (ITER) == 0) { cout << "iter" << endl; d_pos = 6; d_len = l_length - d_pos; t = l.substr(d_pos, d_len); sscanf(t.c_str( ), "%d", &ITERATIONS); cout << "ITERATIONS = " << ITERATIONS << endl; return; } else if (l_sub4.compare (ROT) == 0) { d_pos = 5; d_len = l_length - d_pos; t = l.substr(d_pos, d_len); int count = 0; double current; string c = ""; for (int i = 0; i < t.length(); i++){ if (t[i] == SPACE) { current = ::atof(c.c_str( )); cout << "ROT current = " << current << endl; ROTATIONS.push_back(current); count = 0; c = ""; } else { c += t[count++]; }//if/else }//for //remove below and turn into while loop for opti current = ::atof(c.c_str( )); cout << "ROT current = " << current << endl; ROTATIONS.push_back(current); return; } else if (l_sub4.compare (REP) == 0) { cout << "rep" << endl; return; } else if (l.substr(0, 6).compare (START) == 0 ) { d_pos = 7; d_len = l_length - d_pos; INIT_STR = l.substr(d_pos, d_len); cout << "INIT_STR = " << INIT_STR << endl; start = true; return; } else { //cout << l[i] << endl; }//if/else }//process_line int main ( ) { string line; string filename = "test/lsys1"; filename = filename + ".txt"; cout << filename << endl; ifstream in (filename.c_str()); if (in.is_open ( ) ) { cout << "File is open" << endl; start = false; while(in.good ( ) ) { getline (in, line); process_line (line); } } else { cout << "The file couldn't open" << endl; } } <|endoftext|>
<commit_before>/* * ============================================================================ * * Filename: test-io.cc * Description: Tests of the IO module. * License: LGPL-3+ * Author: Kevin Murray, [email protected] * * ============================================================================ */ #include "catch.hpp" #include "helpers.hh" #include "qc-io.hh" #include <iostream> TEST_CASE("Read structure behaves correctly", "[Read]") { qcpp::Read read("Name", "ACGT", "IIII"); SECTION("Filling read members works") { REQUIRE(read.name.size() == 4); REQUIRE(read.sequence.size() == 4); REQUIRE(read.quality.size() == 4); } SECTION("Clearing a read empties members") { read.clear(); REQUIRE(read.name.size() == 0); REQUIRE(read.sequence.size() == 0); REQUIRE(read.quality.size() == 0); } SECTION("size() gives correct results w/ quality") { REQUIRE(read.sequence.size() == read.size()); REQUIRE(read.quality.size() == read.size()); } SECTION("size() gives correct results w/o quality") { read.quality.clear(); REQUIRE(read.sequence.size() == read.size()); REQUIRE(read.quality.size() == 0); } SECTION("str() works w/ quality") { REQUIRE(read.str() == "@Name\nACGT\n+\nIIII\n"); } SECTION("str() works w/o quality") { read.quality.clear(); REQUIRE(read.str() == ">Name\nACGT\n"); } } TEST_CASE("ReadParser opening works", "[ReadParser]") { qcpp::ReadParser parser; TestConfig *config = TestConfig::get_config(); std::string infile = config->get_data_file("valid_il.fastq"); SECTION("opening valid FASTQ as std::string works") { REQUIRE_NOTHROW(parser.open(infile)); } SECTION("opening valid FASTQ as char * works") { REQUIRE_NOTHROW(parser.open(infile.c_str())); } } TEST_CASE("Valid file parsing, including get_num_reads", "[ReadParser]") { qcpp::Read read; qcpp::ReadParser parser; TestConfig *config = TestConfig::get_config(); std::string infile; size_t n_reads = 0; SECTION("valid_il.fastq") { infile = config->get_data_file("valid_il.fastq"); REQUIRE_NOTHROW(parser.open(infile)); // Count all reads, parse_read returns false on EOF while (parser.parse_read(read)) { n_reads++; } REQUIRE(n_reads == 10); REQUIRE(parser.get_num_reads() == n_reads); } SECTION("valid.fasta") { infile = config->get_data_file("valid.fasta"); REQUIRE_NOTHROW(parser.open(infile)); // Count all reads, parse_read returns false on EOF while (parser.parse_read(read)) { n_reads++; } REQUIRE(n_reads == 10); REQUIRE(parser.get_num_reads() == n_reads); } } TEST_CASE("Parsing of invalid or weird files", "[ReadParser]") { qcpp::Read read; qcpp::ReadParser parser; TestConfig *config = TestConfig::get_config(); std::string infile; size_t n_reads = 0; SECTION("Empty fastq") { infile = config->get_data_file("empty.fastq"); REQUIRE_THROWS_AS(parser.open(infile), qcpp::IOError); while (parser.parse_read(read)) { n_reads++; } REQUIRE(n_reads == 0); REQUIRE(parser.get_num_reads() == n_reads); } SECTION("Truncated fastq") { infile = config->get_data_file("truncated.fastq"); REQUIRE_NOTHROW(parser.open(infile)); REQUIRE_NOTHROW(parser.parse_read(read)); // First read is OK REQUIRE_THROWS_AS(parser.parse_read(read), qcpp::IOError); // 2nd bad } } TEST_CASE("Read Interleaving", "[ReadInterleaver]") { qcpp::ReadPair read_parser_pair; qcpp::ReadPair read_interleaver_pair; qcpp::ReadParser parser; qcpp::ReadInterleaver interleaver; TestConfig *config = TestConfig::get_config(); std::string il_file = config->get_data_file("valid_il.fastq"); std::string r1_file = config->get_data_file("valid_R1.fastq"); std::string r2_file = config->get_data_file("valid_R2.fastq"); REQUIRE_NOTHROW(parser.open(il_file)); REQUIRE_NOTHROW(interleaver.open(r1_file, r2_file)); SECTION("Interleaving yields a correctly paired read stream") { size_t n_pairs = 0; bool parse_ret = true, il_ret = true; // Count all reads, parse_read returns false on EOF while (parse_ret && il_ret) { parse_ret = parser.parse_read_pair(read_parser_pair); il_ret = interleaver.parse_read_pair(read_interleaver_pair); REQUIRE(read_parser_pair == read_interleaver_pair); if (parse_ret && il_ret) { n_pairs++; } } REQUIRE(parse_ret == il_ret); size_t n_reads = n_pairs * 2; REQUIRE(n_reads == 10); REQUIRE(parser.get_num_reads() == n_reads); REQUIRE(interleaver.get_num_reads() == n_reads); REQUIRE(interleaver.get_num_pairs() == n_pairs); } } TEST_CASE("Fastq writing", "[ReadParser]") { qcpp::ReadWriter writer; TestConfig *config = TestConfig::get_config(); std::string outfile = config->get_writable_file("fastq"); CAPTURE(outfile); REQUIRE_NOTHROW(writer.open(outfile)); SECTION("Writing a single read works") { qcpp::Read read("Name", "ACGT", "IIII"); REQUIRE(writer.get_num_reads() == 0); REQUIRE_NOTHROW(writer.write_read(read)); REQUIRE(writer.get_num_reads() == 1); REQUIRE_NOTHROW(writer.close()); REQUIRE(filecmp(outfile, "data/truths/se.fastq")); } SECTION("Writing a single read works") { qcpp::ReadPair rp("seq1", "ACGT", "IIII", "seq2", "ACGT", "IIII"); REQUIRE(writer.get_num_reads() == 0); REQUIRE_NOTHROW(writer.write_read_pair(rp)); REQUIRE(writer.get_num_reads() == 2); REQUIRE_NOTHROW(writer.close()); REQUIRE(filecmp(outfile, "data/truths/pe.fastq")); } } TEST_CASE("Round-trip parse-write", "[ReadParser]") { qcpp::ReadParser parser; qcpp::ReadWriter writer; TestConfig *config = TestConfig::get_config(); std::string infile = config->get_data_file("valid_il.fastq"); std::string outfile = config->get_writable_file("fastq", true); size_t n_reads = 0; CAPTURE(infile); CAPTURE(outfile); REQUIRE_NOTHROW(parser.open(infile)); REQUIRE_NOTHROW(writer.open(outfile)); SECTION("Single-ended round trip") { qcpp::Read read; while (parser.parse_read(read)) { REQUIRE_NOTHROW(writer.write_read(read)); n_reads++; } REQUIRE(n_reads == 10); REQUIRE(parser.get_num_reads() == n_reads); REQUIRE(writer.get_num_reads() == n_reads); REQUIRE_NOTHROW(writer.close()); REQUIRE(filecmp(infile, outfile)); } SECTION("Paired-ended round trip") { qcpp::ReadPair pair; while (parser.parse_read_pair(pair)) { REQUIRE_NOTHROW(writer.write_read_pair(pair)); n_reads++; } REQUIRE(n_reads == 5); // Pairs, not reads REQUIRE(parser.get_num_reads() == 10); REQUIRE(writer.get_num_reads() == 10); REQUIRE_NOTHROW(writer.close()); REQUIRE(filecmp(infile, outfile)); } } <commit_msg>Add tests of new Read.erase behaviour<commit_after>/* * ============================================================================ * * Filename: test-io.cc * Description: Tests of the IO module. * License: LGPL-3+ * Author: Kevin Murray, [email protected] * * ============================================================================ */ #include "catch.hpp" #include "helpers.hh" #include "qc-io.hh" #include <iostream> TEST_CASE("Read structure behaves correctly", "[Read]") { qcpp::Read read("Name", "ACGT", "IIII"); SECTION("Filling read members works") { REQUIRE(read.name.size() == 4); REQUIRE(read.sequence.size() == 4); REQUIRE(read.quality.size() == 4); } SECTION("Clearing a read empties members") { read.clear(); REQUIRE(read.name.size() == 0); REQUIRE(read.sequence.size() == 0); REQUIRE(read.quality.size() == 0); } SECTION("size() gives correct results w/ quality") { REQUIRE(read.sequence.size() == read.size()); REQUIRE(read.quality.size() == read.size()); } SECTION("size() gives correct results w/o quality") { read.quality.clear(); REQUIRE(read.sequence.size() == read.size()); REQUIRE(read.quality.size() == 0); } SECTION("str() works w/ quality") { REQUIRE(read.str() == "@Name\nACGT\n+\nIIII\n"); } SECTION("str() works w/o quality") { read.quality.clear(); REQUIRE(read.str() == ">Name\nACGT\n"); } SECTION("Erase with just start") { read.erase(1); REQUIRE(read.sequence == "A"); REQUIRE(read.quality == "I"); REQUIRE(read.size() == 1); } SECTION("Erase in middle with start and end") { read.erase(1, 2); REQUIRE(read.sequence == "AT"); REQUIRE(read.quality == "II"); REQUIRE(read.size() == 2); } SECTION("Erase from start with start and end") { read.erase(0, 1); REQUIRE(read.sequence == "CGT"); REQUIRE(read.quality == "III"); REQUIRE(read.size() == 3); } SECTION("Erase count=0") { read.erase(0, 0); REQUIRE(read.sequence == "ACGT"); REQUIRE(read.quality == "IIII"); REQUIRE(read.size() == 4); } } TEST_CASE("ReadParser opening works", "[ReadParser]") { qcpp::ReadParser parser; TestConfig *config = TestConfig::get_config(); std::string infile = config->get_data_file("valid_il.fastq"); SECTION("opening valid FASTQ as std::string works") { REQUIRE_NOTHROW(parser.open(infile)); } SECTION("opening valid FASTQ as char * works") { REQUIRE_NOTHROW(parser.open(infile.c_str())); } } TEST_CASE("Valid file parsing, including get_num_reads", "[ReadParser]") { qcpp::Read read; qcpp::ReadParser parser; TestConfig *config = TestConfig::get_config(); std::string infile; size_t n_reads = 0; SECTION("valid_il.fastq") { infile = config->get_data_file("valid_il.fastq"); REQUIRE_NOTHROW(parser.open(infile)); // Count all reads, parse_read returns false on EOF while (parser.parse_read(read)) { n_reads++; } REQUIRE(n_reads == 10); REQUIRE(parser.get_num_reads() == n_reads); } SECTION("valid.fasta") { infile = config->get_data_file("valid.fasta"); REQUIRE_NOTHROW(parser.open(infile)); // Count all reads, parse_read returns false on EOF while (parser.parse_read(read)) { n_reads++; } REQUIRE(n_reads == 10); REQUIRE(parser.get_num_reads() == n_reads); } } TEST_CASE("Parsing of invalid or weird files", "[ReadParser]") { qcpp::Read read; qcpp::ReadParser parser; TestConfig *config = TestConfig::get_config(); std::string infile; size_t n_reads = 0; SECTION("Empty fastq") { infile = config->get_data_file("empty.fastq"); REQUIRE_THROWS_AS(parser.open(infile), qcpp::IOError); while (parser.parse_read(read)) { n_reads++; } REQUIRE(n_reads == 0); REQUIRE(parser.get_num_reads() == n_reads); } SECTION("Truncated fastq") { infile = config->get_data_file("truncated.fastq"); REQUIRE_NOTHROW(parser.open(infile)); REQUIRE_NOTHROW(parser.parse_read(read)); // First read is OK REQUIRE_THROWS_AS(parser.parse_read(read), qcpp::IOError); // 2nd bad } } TEST_CASE("Read Interleaving", "[ReadInterleaver]") { qcpp::ReadPair read_parser_pair; qcpp::ReadPair read_interleaver_pair; qcpp::ReadParser parser; qcpp::ReadInterleaver interleaver; TestConfig *config = TestConfig::get_config(); std::string il_file = config->get_data_file("valid_il.fastq"); std::string r1_file = config->get_data_file("valid_R1.fastq"); std::string r2_file = config->get_data_file("valid_R2.fastq"); REQUIRE_NOTHROW(parser.open(il_file)); REQUIRE_NOTHROW(interleaver.open(r1_file, r2_file)); SECTION("Interleaving yields a correctly paired read stream") { size_t n_pairs = 0; bool parse_ret = true, il_ret = true; // Count all reads, parse_read returns false on EOF while (parse_ret && il_ret) { parse_ret = parser.parse_read_pair(read_parser_pair); il_ret = interleaver.parse_read_pair(read_interleaver_pair); REQUIRE(read_parser_pair == read_interleaver_pair); if (parse_ret && il_ret) { n_pairs++; } } REQUIRE(parse_ret == il_ret); size_t n_reads = n_pairs * 2; REQUIRE(n_reads == 10); REQUIRE(parser.get_num_reads() == n_reads); REQUIRE(interleaver.get_num_reads() == n_reads); REQUIRE(interleaver.get_num_pairs() == n_pairs); } } TEST_CASE("Fastq writing", "[ReadParser]") { qcpp::ReadWriter writer; TestConfig *config = TestConfig::get_config(); std::string outfile = config->get_writable_file("fastq"); CAPTURE(outfile); REQUIRE_NOTHROW(writer.open(outfile)); SECTION("Writing a single read works") { qcpp::Read read("Name", "ACGT", "IIII"); REQUIRE(writer.get_num_reads() == 0); REQUIRE_NOTHROW(writer.write_read(read)); REQUIRE(writer.get_num_reads() == 1); REQUIRE_NOTHROW(writer.close()); REQUIRE(filecmp(outfile, "data/truths/se.fastq")); } SECTION("Writing a single read works") { qcpp::ReadPair rp("seq1", "ACGT", "IIII", "seq2", "ACGT", "IIII"); REQUIRE(writer.get_num_reads() == 0); REQUIRE_NOTHROW(writer.write_read_pair(rp)); REQUIRE(writer.get_num_reads() == 2); REQUIRE_NOTHROW(writer.close()); REQUIRE(filecmp(outfile, "data/truths/pe.fastq")); } } TEST_CASE("Round-trip parse-write", "[ReadParser]") { qcpp::ReadParser parser; qcpp::ReadWriter writer; TestConfig *config = TestConfig::get_config(); std::string infile = config->get_data_file("valid_il.fastq"); std::string outfile = config->get_writable_file("fastq", true); size_t n_reads = 0; CAPTURE(infile); CAPTURE(outfile); REQUIRE_NOTHROW(parser.open(infile)); REQUIRE_NOTHROW(writer.open(outfile)); SECTION("Single-ended round trip") { qcpp::Read read; while (parser.parse_read(read)) { REQUIRE_NOTHROW(writer.write_read(read)); n_reads++; } REQUIRE(n_reads == 10); REQUIRE(parser.get_num_reads() == n_reads); REQUIRE(writer.get_num_reads() == n_reads); REQUIRE_NOTHROW(writer.close()); REQUIRE(filecmp(infile, outfile)); } SECTION("Paired-ended round trip") { qcpp::ReadPair pair; while (parser.parse_read_pair(pair)) { REQUIRE_NOTHROW(writer.write_read_pair(pair)); n_reads++; } REQUIRE(n_reads == 5); // Pairs, not reads REQUIRE(parser.get_num_reads() == 10); REQUIRE(writer.get_num_reads() == 10); REQUIRE_NOTHROW(writer.close()); REQUIRE(filecmp(infile, outfile)); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Cryptonomex, Inc., and 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 <graphene/app/application.hpp> #include <graphene/app/plugin.hpp> #include <graphene/chain/balance_object.hpp> #include <graphene/utilities/tempdir.hpp> #include <graphene/account_history/account_history_plugin.hpp> #include <graphene/market_history/market_history_plugin.hpp> #include <graphene/witness/witness.hpp> #include <graphene/grouped_orders/grouped_orders_plugin.hpp> #include <fc/thread/thread.hpp> #include <fc/smart_ref_impl.hpp> #include <boost/filesystem/path.hpp> #define BOOST_TEST_MODULE Test Application #include <boost/test/included/unit_test.hpp> #include "../common/genesis_file_util.hpp" using namespace graphene; ///////////// /// @brief create a 2 node network ///////////// BOOST_AUTO_TEST_CASE( two_node_network ) { using namespace graphene::chain; using namespace graphene::app; try { BOOST_TEST_MESSAGE( "Creating and initializing app1" ); fc::temp_directory app_dir( graphene::utilities::temp_directory_path() ); graphene::app::application app1; app1.register_plugin< graphene::account_history::account_history_plugin>(); app1.register_plugin< graphene::market_history::market_history_plugin >(); app1.register_plugin< graphene::witness_plugin::witness_plugin >(); app1.register_plugin< graphene::grouped_orders::grouped_orders_plugin>(); app1.startup_plugins(); boost::program_options::variables_map cfg; cfg.emplace("p2p-endpoint", boost::program_options::variable_value(string("127.0.0.1:3939"), false)); cfg.emplace("genesis-json", boost::program_options::variable_value(create_genesis_file(app_dir), false)); cfg.emplace("seed-nodes", boost::program_options::variable_value(string("[]"), false)); app1.initialize(app_dir.path(), cfg); BOOST_TEST_MESSAGE( "Starting app1 and waiting 500 ms" ); app1.startup(); fc::usleep(fc::milliseconds(500)); BOOST_TEST_MESSAGE( "Creating and initializing app2" ); fc::temp_directory app2_dir( graphene::utilities::temp_directory_path() ); graphene::app::application app2; app2.register_plugin<account_history::account_history_plugin>(); app2.register_plugin< graphene::market_history::market_history_plugin >(); app2.register_plugin< graphene::witness_plugin::witness_plugin >(); app2.register_plugin< graphene::grouped_orders::grouped_orders_plugin>(); app2.startup_plugins(); auto cfg2 = cfg; cfg2.erase("p2p-endpoint"); cfg2.emplace("p2p-endpoint", boost::program_options::variable_value(string("127.0.0.1:4040"), false)); cfg2.emplace("genesis-json", boost::program_options::variable_value(create_genesis_file(app_dir), false)); cfg2.emplace("seed-node", boost::program_options::variable_value(vector<string>{"127.0.0.1:3939"}, false)); cfg2.emplace("seed-nodes", boost::program_options::variable_value(string("[]"), false)); app2.initialize(app2_dir.path(), cfg2); BOOST_TEST_MESSAGE( "Starting app2 and waiting 500 ms" ); app2.startup(); fc::usleep(fc::milliseconds(500)); BOOST_REQUIRE_EQUAL(app1.p2p_node()->get_connection_count(), 1); BOOST_CHECK_EQUAL(std::string(app1.p2p_node()->get_connected_peers().front().host.get_address()), "127.0.0.1"); BOOST_TEST_MESSAGE( "app1 and app2 successfully connected" ); std::shared_ptr<chain::database> db1 = app1.chain_database(); std::shared_ptr<chain::database> db2 = app2.chain_database(); BOOST_CHECK_EQUAL( db1->get_balance( GRAPHENE_NULL_ACCOUNT, asset_id_type() ).amount.value, 0 ); BOOST_CHECK_EQUAL( db2->get_balance( GRAPHENE_NULL_ACCOUNT, asset_id_type() ).amount.value, 0 ); BOOST_TEST_MESSAGE( "Creating transfer tx" ); graphene::chain::signed_transaction trx; { account_id_type nathan_id = db2->get_index_type<account_index>().indices().get<by_name>().find( "nathan" )->id; fc::ecc::private_key nathan_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("nathan"))); balance_claim_operation claim_op; balance_id_type bid = balance_id_type(); claim_op.deposit_to_account = nathan_id; claim_op.balance_to_claim = bid; claim_op.balance_owner_key = nathan_key.get_public_key(); claim_op.total_claimed = bid(*db1).balance; trx.operations.push_back( claim_op ); db1->current_fee_schedule().set_fee( trx.operations.back() ); transfer_operation xfer_op; xfer_op.from = nathan_id; xfer_op.to = GRAPHENE_NULL_ACCOUNT; xfer_op.amount = asset( 1000000 ); trx.operations.push_back( xfer_op ); db1->current_fee_schedule().set_fee( trx.operations.back() ); trx.set_expiration( db1->get_slot_time( 10 ) ); trx.sign( nathan_key, db1->get_chain_id() ); trx.validate(); } BOOST_TEST_MESSAGE( "Pushing tx locally on db1" ); processed_transaction ptrx = db1->push_transaction(trx); BOOST_CHECK_EQUAL( db1->get_balance( GRAPHENE_NULL_ACCOUNT, asset_id_type() ).amount.value, 1000000 ); BOOST_CHECK_EQUAL( db2->get_balance( GRAPHENE_NULL_ACCOUNT, asset_id_type() ).amount.value, 0 ); BOOST_TEST_MESSAGE( "Broadcasting tx" ); app1.p2p_node()->broadcast(graphene::net::trx_message(trx)); fc::usleep(fc::milliseconds(500)); BOOST_CHECK_EQUAL( db1->get_balance( GRAPHENE_NULL_ACCOUNT, asset_id_type() ).amount.value, 1000000 ); BOOST_CHECK_EQUAL( db2->get_balance( GRAPHENE_NULL_ACCOUNT, asset_id_type() ).amount.value, 1000000 ); BOOST_TEST_MESSAGE( "Generating block on db2" ); fc::ecc::private_key committee_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("nathan"))); auto block_1 = db2->generate_block( db2->get_slot_time(1), db2->get_scheduled_witness(1), committee_key, database::skip_nothing); BOOST_TEST_MESSAGE( "Broadcasting block" ); app2.p2p_node()->broadcast(graphene::net::block_message( block_1 )); fc::usleep(fc::milliseconds(500)); BOOST_TEST_MESSAGE( "Verifying nodes are still connected" ); BOOST_CHECK_EQUAL(app1.p2p_node()->get_connection_count(), 1); BOOST_CHECK_EQUAL(app1.chain_database()->head_block_num(), 1); BOOST_TEST_MESSAGE( "Checking GRAPHENE_NULL_ACCOUNT has balance" ); } catch( fc::exception& e ) { edump((e.to_detail_string())); throw; } } // a contrived example to test the breaking out of application_impl to a header file #include "../../libraries/app/application_impl.hxx" BOOST_AUTO_TEST_CASE(application_impl_breakout) { class test_impl : public graphene::app::detail::application_impl { // override the constructor, just to test that we can public: test_impl() : application_impl(nullptr) {} bool has_item(const net::item_id& id) override { return true; } }; test_impl impl; graphene::net::item_id id; BOOST_CHECK(impl.has_item(id)); } <commit_msg>load_configuration_options basic tests<commit_after>/* * Copyright (c) 2015 Cryptonomex, Inc., and 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 <graphene/app/application.hpp> #include <graphene/app/plugin.hpp> #include <graphene/app/config_util.hpp> #include <graphene/chain/balance_object.hpp> #include <graphene/utilities/tempdir.hpp> #include <graphene/account_history/account_history_plugin.hpp> #include <graphene/market_history/market_history_plugin.hpp> #include <graphene/witness/witness.hpp> #include <graphene/grouped_orders/grouped_orders_plugin.hpp> #include <fc/thread/thread.hpp> #include <fc/smart_ref_impl.hpp> #include <fc/log/appender.hpp> #include <fc/log/logger.hpp> #include <boost/filesystem/path.hpp> #define BOOST_TEST_MODULE Test Application #include <boost/test/included/unit_test.hpp> #include "../common/genesis_file_util.hpp" using namespace graphene; namespace bpo = boost::program_options; namespace fc { extern std::unordered_map<std::string, logger> &get_logger_map(); extern std::unordered_map<std::string, appender::ptr> &get_appender_map(); } BOOST_AUTO_TEST_CASE(load_configuration_options_test_config_files_created) { fc::temp_directory app_dir(graphene::utilities::temp_directory_path()); auto dir = app_dir.path(); auto config_ini_file = dir / "config.ini"; auto logging_ini_file = dir / "logging.ini"; /// create default config options auto node = new app::application(); bpo::options_description cli, cfg; node->set_program_options(cli, cfg); bpo::options_description cfg_options("Graphene Witness Node"); cfg_options.add(cfg); /// check preconditions BOOST_CHECK(!fc::exists(config_ini_file)); BOOST_CHECK(!fc::exists(logging_ini_file)); bpo::variables_map options; app::load_configuration_options(dir, cfg_options, options); /// check post-conditions BOOST_CHECK(fc::exists(config_ini_file)); BOOST_CHECK(fc::exists(logging_ini_file)); BOOST_CHECK_GT(fc::file_size(config_ini_file), 0); BOOST_CHECK_GT(fc::file_size(logging_ini_file), 0); } BOOST_AUTO_TEST_CASE(load_configuration_options_test_config_ini_options) { fc::temp_directory app_dir(graphene::utilities::temp_directory_path()); auto dir = app_dir.path(); auto config_ini_file = dir / "config.ini"; auto logging_ini_file = dir / "logging.ini"; /// create config.ini bpo::options_description cfg_options("config.ini options"); cfg_options.add_options() ("option1", bpo::value<std::string>(), "") ("option2", bpo::value<int>(), "") ; std::ofstream out(config_ini_file.preferred_string()); out << "option1=is present\n" "option2=1\n\n"; out.close(); bpo::variables_map options; app::load_configuration_options(dir, cfg_options, options); /// check the options values are parsed into the output map BOOST_CHECK(!options.empty()); BOOST_CHECK_EQUAL(options.count("option1"), 1); BOOST_CHECK_EQUAL(options.count("option2"), 1); BOOST_CHECK_EQUAL(options["option1"].as<std::string>(), "is present"); BOOST_CHECK_EQUAL(options["option2"].as<int>(), 1); } BOOST_AUTO_TEST_CASE(load_configuration_options_test_logging_ini_options) { fc::temp_directory app_dir(graphene::utilities::temp_directory_path()); auto dir = app_dir.path(); auto config_ini_file = dir / "config.ini"; auto logging_ini_file = dir / "logging.ini"; /// create logging.ini /// configure exactly one logger and appender std::ofstream out(logging_ini_file.preferred_string()); out << "[log.file_appender.default]\n" "filename=test.log\n\n" "[logger.default]\n" "level=info\n" "appenders=default\n\n" ; out.close(); /// clear logger and appender state fc::get_logger_map().clear(); fc::get_appender_map().clear(); BOOST_CHECK(fc::get_logger_map().empty()); BOOST_CHECK(fc::get_appender_map().empty()); bpo::options_description cfg_options("empty"); bpo::variables_map options; app::load_configuration_options(dir, cfg_options, options); /// check the options values are parsed into the output map /// this is a little bit tricky since load_configuration_options() doesn't provide output variable for logging_config auto logger_map = fc::get_logger_map(); auto appender_map = fc::get_appender_map(); BOOST_CHECK_EQUAL(logger_map.size(), 1); BOOST_CHECK(logger_map.count("default")); BOOST_CHECK_EQUAL(appender_map.size(), 1); BOOST_CHECK(appender_map.count("default")); } ///////////// /// @brief create a 2 node network ///////////// BOOST_AUTO_TEST_CASE( two_node_network ) { using namespace graphene::chain; using namespace graphene::app; try { BOOST_TEST_MESSAGE( "Creating and initializing app1" ); fc::temp_directory app_dir( graphene::utilities::temp_directory_path() ); graphene::app::application app1; app1.register_plugin< graphene::account_history::account_history_plugin>(); app1.register_plugin< graphene::market_history::market_history_plugin >(); app1.register_plugin< graphene::witness_plugin::witness_plugin >(); app1.register_plugin< graphene::grouped_orders::grouped_orders_plugin>(); app1.startup_plugins(); boost::program_options::variables_map cfg; cfg.emplace("p2p-endpoint", boost::program_options::variable_value(string("127.0.0.1:3939"), false)); cfg.emplace("genesis-json", boost::program_options::variable_value(create_genesis_file(app_dir), false)); cfg.emplace("seed-nodes", boost::program_options::variable_value(string("[]"), false)); app1.initialize(app_dir.path(), cfg); BOOST_TEST_MESSAGE( "Starting app1 and waiting 500 ms" ); app1.startup(); fc::usleep(fc::milliseconds(500)); BOOST_TEST_MESSAGE( "Creating and initializing app2" ); fc::temp_directory app2_dir( graphene::utilities::temp_directory_path() ); graphene::app::application app2; app2.register_plugin<account_history::account_history_plugin>(); app2.register_plugin< graphene::market_history::market_history_plugin >(); app2.register_plugin< graphene::witness_plugin::witness_plugin >(); app2.register_plugin< graphene::grouped_orders::grouped_orders_plugin>(); app2.startup_plugins(); auto cfg2 = cfg; cfg2.erase("p2p-endpoint"); cfg2.emplace("p2p-endpoint", boost::program_options::variable_value(string("127.0.0.1:4040"), false)); cfg2.emplace("genesis-json", boost::program_options::variable_value(create_genesis_file(app_dir), false)); cfg2.emplace("seed-node", boost::program_options::variable_value(vector<string>{"127.0.0.1:3939"}, false)); cfg2.emplace("seed-nodes", boost::program_options::variable_value(string("[]"), false)); app2.initialize(app2_dir.path(), cfg2); BOOST_TEST_MESSAGE( "Starting app2 and waiting 500 ms" ); app2.startup(); fc::usleep(fc::milliseconds(500)); BOOST_REQUIRE_EQUAL(app1.p2p_node()->get_connection_count(), 1); BOOST_CHECK_EQUAL(std::string(app1.p2p_node()->get_connected_peers().front().host.get_address()), "127.0.0.1"); BOOST_TEST_MESSAGE( "app1 and app2 successfully connected" ); std::shared_ptr<chain::database> db1 = app1.chain_database(); std::shared_ptr<chain::database> db2 = app2.chain_database(); BOOST_CHECK_EQUAL( db1->get_balance( GRAPHENE_NULL_ACCOUNT, asset_id_type() ).amount.value, 0 ); BOOST_CHECK_EQUAL( db2->get_balance( GRAPHENE_NULL_ACCOUNT, asset_id_type() ).amount.value, 0 ); BOOST_TEST_MESSAGE( "Creating transfer tx" ); graphene::chain::signed_transaction trx; { account_id_type nathan_id = db2->get_index_type<account_index>().indices().get<by_name>().find( "nathan" )->id; fc::ecc::private_key nathan_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("nathan"))); balance_claim_operation claim_op; balance_id_type bid = balance_id_type(); claim_op.deposit_to_account = nathan_id; claim_op.balance_to_claim = bid; claim_op.balance_owner_key = nathan_key.get_public_key(); claim_op.total_claimed = bid(*db1).balance; trx.operations.push_back( claim_op ); db1->current_fee_schedule().set_fee( trx.operations.back() ); transfer_operation xfer_op; xfer_op.from = nathan_id; xfer_op.to = GRAPHENE_NULL_ACCOUNT; xfer_op.amount = asset( 1000000 ); trx.operations.push_back( xfer_op ); db1->current_fee_schedule().set_fee( trx.operations.back() ); trx.set_expiration( db1->get_slot_time( 10 ) ); trx.sign( nathan_key, db1->get_chain_id() ); trx.validate(); } BOOST_TEST_MESSAGE( "Pushing tx locally on db1" ); processed_transaction ptrx = db1->push_transaction(trx); BOOST_CHECK_EQUAL( db1->get_balance( GRAPHENE_NULL_ACCOUNT, asset_id_type() ).amount.value, 1000000 ); BOOST_CHECK_EQUAL( db2->get_balance( GRAPHENE_NULL_ACCOUNT, asset_id_type() ).amount.value, 0 ); BOOST_TEST_MESSAGE( "Broadcasting tx" ); app1.p2p_node()->broadcast(graphene::net::trx_message(trx)); fc::usleep(fc::milliseconds(500)); BOOST_CHECK_EQUAL( db1->get_balance( GRAPHENE_NULL_ACCOUNT, asset_id_type() ).amount.value, 1000000 ); BOOST_CHECK_EQUAL( db2->get_balance( GRAPHENE_NULL_ACCOUNT, asset_id_type() ).amount.value, 1000000 ); BOOST_TEST_MESSAGE( "Generating block on db2" ); fc::ecc::private_key committee_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("nathan"))); auto block_1 = db2->generate_block( db2->get_slot_time(1), db2->get_scheduled_witness(1), committee_key, database::skip_nothing); BOOST_TEST_MESSAGE( "Broadcasting block" ); app2.p2p_node()->broadcast(graphene::net::block_message( block_1 )); fc::usleep(fc::milliseconds(500)); BOOST_TEST_MESSAGE( "Verifying nodes are still connected" ); BOOST_CHECK_EQUAL(app1.p2p_node()->get_connection_count(), 1); BOOST_CHECK_EQUAL(app1.chain_database()->head_block_num(), 1); BOOST_TEST_MESSAGE( "Checking GRAPHENE_NULL_ACCOUNT has balance" ); } catch( fc::exception& e ) { edump((e.to_detail_string())); throw; } } // a contrived example to test the breaking out of application_impl to a header file #include "../../libraries/app/application_impl.hxx" BOOST_AUTO_TEST_CASE(application_impl_breakout) { class test_impl : public graphene::app::detail::application_impl { // override the constructor, just to test that we can public: test_impl() : application_impl(nullptr) {} bool has_item(const net::item_id& id) override { return true; } }; test_impl impl; graphene::net::item_id id; BOOST_CHECK(impl.has_item(id)); } <|endoftext|>
<commit_before>/** * The MIT License (MIT) * * Copyright (c) 2014 wisol technologie GmbH * * 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. * * \author Michael Egli * \copyright wisol technologie GmbH * \date 18-Dec-2014 * * \file fsm_test.cpp * Test definitions for the state machine implementation. */ #define CATCH_CONFIG_MAIN #include "catch.hpp" #include "../fsm.h" TEST_CASE("Test Initialization") { FSM::Fsm fsm; REQUIRE(fsm.execute('a') == FSM::Fsm_NotInitialized); } TEST_CASE("Test initial and final pseudo states") { FSM::Fsm fsm; FSM::Trans transitions[] = { {FSM::Fsm_Initial, FSM::Fsm_Final, 'a', nullptr, nullptr}, }; fsm.add_transitions(&transitions[0], &transitions[0]+1); fsm.init(); SECTION("Test initial pseudo state") { REQUIRE(fsm.state() == (int)FSM::Fsm_Initial); REQUIRE(fsm.is_initial() == true); REQUIRE(fsm.is_final() == false); } SECTION("Test initial pseudo state") { fsm.execute('a'); REQUIRE(fsm.state() == (int)FSM::Fsm_Final); REQUIRE(fsm.is_initial() == false); REQUIRE(fsm.is_final() == true); } } TEST_CASE("Test missing trigger") { FSM::Fsm fsm; FSM::Trans transitions[] = { {FSM::Fsm_Initial, FSM::Fsm_Final, 'b', nullptr, nullptr}, }; fsm.add_transitions(&transitions[0], &transitions[0]+1); fsm.init(); REQUIRE(fsm.execute('a') == FSM::Fsm_NoMatchingTrigger); } TEST_CASE("Test guards") { SECTION("Test false guard") { FSM::Fsm fsm; FSM::Trans transitions[] = { {FSM::Fsm_Initial, FSM::Fsm_Final, 'a', []{return false;}, nullptr}, }; fsm.add_transitions(&transitions[0], &transitions[0]+1); fsm.init(); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); // ensure that the transition to final is not taken (because of the guard). REQUIRE(fsm.state() == (int)FSM::Fsm_Initial); } SECTION("Test true guard") { FSM::Fsm fsm; FSM::Trans transitions[] = { {FSM::Fsm_Initial, FSM::Fsm_Final, 'a', []{return true;}, nullptr}, }; fsm.add_transitions(&transitions[0], &transitions[0]+1); fsm.init(); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); // ensure that the transition to final is taken (because of the guard). REQUIRE(fsm.state() == (int)FSM::Fsm_Final); } SECTION("Test same action with different guards") { int count = 0; FSM::Fsm fsm; FSM::Trans transitions[] = { {FSM::Fsm_Initial, FSM::Fsm_Final, 'a', []{return false;}, [&count]{count++;}}, {FSM::Fsm_Initial, FSM::Fsm_Final, 'a', []{return true; }, [&count]{count = 10;}}, }; fsm.add_transitions(&transitions[0], &transitions[0]+2); fsm.init(); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); // ensure that action2 was taken (because of the guard). REQUIRE(count == 10); } } TEST_CASE("Test Transitions") { SECTION("Test multiple matching transitions") { int count = 0; const int stateA = 1; FSM::Fsm fsm; FSM::Trans transitions[] = { {FSM::Fsm_Initial, stateA , 'a', nullptr, [&count]{count++;}}, {stateA , stateA , 'a', nullptr, [&count]{count++;}}, {stateA , FSM::Fsm_Final, 'a', nullptr, [&count]{count++;}}, }; fsm.add_transitions(&transitions[0], &transitions[0]+3); fsm.init(); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); // Ensure that only one action has executed. REQUIRE(count == 1); } } TEST_CASE("Test state machine reset") { int action_count = 0; const int stateA = 1; FSM::Fsm fsm; FSM::Trans transitions[] = { {FSM::Fsm_Initial, stateA , 'a', nullptr, nullptr}, {stateA , FSM::Fsm_Final, 'b', nullptr, nullptr}, }; fsm.add_transitions(&transitions[0], &transitions[0]+2); fsm.init(); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); REQUIRE(fsm.state() == stateA); fsm.reset(); REQUIRE(fsm.state() == (int)FSM::Fsm_Initial); REQUIRE(fsm.execute('a') == FSM::Fsm_NotInitialized); fsm.init(); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); REQUIRE(fsm.execute('b') == FSM::Fsm_Success); REQUIRE(fsm.is_final() == true); } <commit_msg>Add a test for the new debug function.<commit_after>/** * The MIT License (MIT) * * Copyright (c) 2014 wisol technologie GmbH * * 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. * * \author Michael Egli * \copyright wisol technologie GmbH * \date 18-Dec-2014 * * \file fsm_test.cpp * Test definitions for the state machine implementation. */ #define CATCH_CONFIG_MAIN #include "catch.hpp" #include "../fsm.h" TEST_CASE("Test Initialization") { FSM::Fsm fsm; REQUIRE(fsm.execute('a') == FSM::Fsm_NotInitialized); } TEST_CASE("Test initial and final pseudo states") { FSM::Fsm fsm; FSM::Trans transitions[] = { {FSM::Fsm_Initial, FSM::Fsm_Final, 'a', nullptr, nullptr}, }; fsm.add_transitions(&transitions[0], &transitions[0]+1); fsm.init(); SECTION("Test initial pseudo state") { REQUIRE(fsm.state() == (int)FSM::Fsm_Initial); REQUIRE(fsm.is_initial() == true); REQUIRE(fsm.is_final() == false); } SECTION("Test initial pseudo state") { fsm.execute('a'); REQUIRE(fsm.state() == (int)FSM::Fsm_Final); REQUIRE(fsm.is_initial() == false); REQUIRE(fsm.is_final() == true); } } TEST_CASE("Test missing trigger") { FSM::Fsm fsm; FSM::Trans transitions[] = { {FSM::Fsm_Initial, FSM::Fsm_Final, 'b', nullptr, nullptr}, }; fsm.add_transitions(&transitions[0], &transitions[0]+1); fsm.init(); REQUIRE(fsm.execute('a') == FSM::Fsm_NoMatchingTrigger); } TEST_CASE("Test guards") { SECTION("Test false guard") { FSM::Fsm fsm; FSM::Trans transitions[] = { {FSM::Fsm_Initial, FSM::Fsm_Final, 'a', []{return false;}, nullptr}, }; fsm.add_transitions(&transitions[0], &transitions[0]+1); fsm.init(); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); // ensure that the transition to final is not taken (because of the guard). REQUIRE(fsm.state() == (int)FSM::Fsm_Initial); } SECTION("Test true guard") { FSM::Fsm fsm; FSM::Trans transitions[] = { {FSM::Fsm_Initial, FSM::Fsm_Final, 'a', []{return true;}, nullptr}, }; fsm.add_transitions(&transitions[0], &transitions[0]+1); fsm.init(); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); // ensure that the transition to final is taken (because of the guard). REQUIRE(fsm.state() == (int)FSM::Fsm_Final); } SECTION("Test same action with different guards") { int count = 0; FSM::Fsm fsm; FSM::Trans transitions[] = { {FSM::Fsm_Initial, FSM::Fsm_Final, 'a', []{return false;}, [&count]{count++;}}, {FSM::Fsm_Initial, FSM::Fsm_Final, 'a', []{return true; }, [&count]{count = 10;}}, }; fsm.add_transitions(&transitions[0], &transitions[0]+2); fsm.init(); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); // ensure that action2 was taken (because of the guard). REQUIRE(count == 10); } } TEST_CASE("Test Transitions") { SECTION("Test multiple matching transitions") { int count = 0; const int stateA = 1; FSM::Fsm fsm; FSM::Trans transitions[] = { {FSM::Fsm_Initial, stateA , 'a', nullptr, [&count]{count++;}}, {stateA , stateA , 'a', nullptr, [&count]{count++;}}, {stateA , FSM::Fsm_Final, 'a', nullptr, [&count]{count++;}}, }; fsm.add_transitions(&transitions[0], &transitions[0]+3); fsm.init(); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); // Ensure that only one action has executed. REQUIRE(count == 1); } } TEST_CASE("Test state machine reset") { int action_count = 0; const int stateA = 1; FSM::Fsm fsm; FSM::Trans transitions[] = { {FSM::Fsm_Initial, stateA , 'a', nullptr, nullptr}, {stateA , FSM::Fsm_Final, 'b', nullptr, nullptr}, }; fsm.add_transitions(&transitions[0], &transitions[0]+2); fsm.init(); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); REQUIRE(fsm.state() == stateA); fsm.reset(); REQUIRE(fsm.state() == (int)FSM::Fsm_Initial); REQUIRE(fsm.execute('a') == FSM::Fsm_NotInitialized); fsm.init(); REQUIRE(fsm.execute('a') == FSM::Fsm_Success); REQUIRE(fsm.execute('b') == FSM::Fsm_Success); REQUIRE(fsm.is_final() == true); } TEST_CASE("Test debug function") { int action_count = 0; const int stateA = 1; FSM::Fsm fsm; FSM::Trans transitions[] = { {FSM::Fsm_Initial, stateA , 'a', nullptr, nullptr}, {stateA , FSM::Fsm_Final, 'b', nullptr, nullptr}, }; fsm.add_transitions(&transitions[0], &transitions[0]+2); fsm.init(); SECTION("Test enable debugging function.") { int dbg_from = 0; int dbg_to = 0; char dbg_tr = 0; fsm.add_debug_fn([&dbg_from, &dbg_to, &dbg_tr](int from, int to, char tr){ dbg_from = from; dbg_to = to; dbg_tr = tr; }); fsm.execute('a'); REQUIRE(dbg_from == FSM::Fsm_Initial); REQUIRE(dbg_to == stateA); REQUIRE(dbg_tr == 'a'); } SECTION("Test disable debugging function.") { int dbg_from = 0; int dbg_to = 0; char dbg_tr = 0; fsm.reset(); fsm.add_debug_fn(nullptr); REQUIRE(dbg_from == 0); REQUIRE(dbg_to == 0); REQUIRE(dbg_tr == 0); } } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief RX64M/RX71M/RX651/RX65N/RX66T/RX72T/RX72N/RX72M グループ・システム制御 @n ※RX24T は構成が大きく異なるので、RX24T/system_io.hpp に分離しています。@n ※ USB を使う場合:96MHz, 144MHz, 192MHz, 240MHz のいづれか @n ※ 通常ベースクロックは、12MHz、24MHz を使います。@n RX72x 系では、内部 PLL 回路が追加され、Ethernet などに必要な 25MHz を得る為 @n 16MHz を使います。@n (16MHz x 12.5 -> 200MHz, 16MHz x 15 -> 240MHz) @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2017, 2021 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "RX600/system.hpp" #if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX66T) || defined(SIG_RX65N) || defined(SIG_RX72T) || defined(SIG_RX72N) || defined(SIG_RX72M) #elif # error "system_io.hpp: Not available on RX24T" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief systen_base クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct system_base { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 発信器タイプ @n HOCO を使う場合、同時に、BASE_CLOCK_ に周波数を設定します。 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class OSC_TYPE { XTAL, ///< クリスタル接続 EXT, ///< クロック入力 HOCO, ///< 高速オンチップオシレーター LOCO, ///< 低速オンチップオシレーター (240KHz) }; }; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief systen_io クラス @n INTR_CLOCK は、内部 PLL で扱える最大速度です、@n 外部クリスタルを微妙な周波数にする場合、その整数倍にしなければなりません。 @n RX71M はスーパーバイザモードでの変更が必要なので、「start.s」内で行う。 @n RX71M の場合、アセンブラにオプション「--defsym MEMWAIT=1」を渡す。 @param[in] BASE_CLOCK_ ベース・クロック周波数 @param[in] INTR_CLOCK 内臓クロック周波数 @n ※USB を使う場合、「INTR_CLOCK」は48の倍数である事 @param[in] OSC_TYPE 発信器タイプを設定(通常、XTAL) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <auto OSC_TYPE_ = system_base::OSC_TYPE::XTAL> struct system_io : public system_base { static uint8_t clock_div_(uint32_t clk) noexcept { uint8_t div = 0; while(clk < clock_profile::PLL_BASE) { ++div; clk <<= 1; } if(div > 0b0110) div = 0b0110; return div; } //-------------------------------------------------------------// /*! @brief マスター・クロックのブースト @n インストラクション・クロックを最大速度にブーストする。 */ //-------------------------------------------------------------// static void boost_master_clock() noexcept { device::SYSTEM::PRCR = 0xA50B; // クロック、低消費電力、関係書き込み許可 device::SYSTEM::MOSCWTCR = 9; // 1ms wait // メインクロック強制発振とドライブ能力設定 if(OSC_TYPE_ == OSC_TYPE::XTAL) { uint8_t modrv2 = 0b11; if(clock_profile::BASE > 20'000'000) modrv2 = 0b00; else if(clock_profile::BASE > 16'000'000) modrv2 = 0b01; else if(clock_profile::BASE > 8'000'000) modrv2 = 0b10; device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV2.b(modrv2); device::SYSTEM::MOSCCR.MOSTP = 0; // メインクロック発振器動作 while(device::SYSTEM::OSCOVFSR.MOOVF() == 0) { asm("nop"); } } else if(OSC_TYPE_ == OSC_TYPE::EXT) { device::SYSTEM::MOSCCR.MOSTP = 1; // メインクロック発振器停止 device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MOSEL.b(); } else if(OSC_TYPE_ == OSC_TYPE::HOCO) { // 高速オンチップオシレータ device::SYSTEM::MOSCCR.MOSTP = 1; device::SYSTEM::HOCOCR = device::SYSTEM::HOCOCR.HCSTP.b(1); // 停止 uint8_t frq; if(clock_profile::BASE == 16'000'000) frq = 0b00; else if(clock_profile::BASE == 18'000'000) frq = 0b01; else if(clock_profile::BASE == 20'000'000) frq = 0b10; else frq = 0b00; device::SYSTEM::HOCOCR2.HCFRQ = frq; device::SYSTEM::HOCOCR = device::SYSTEM::HOCOCR.HCSTP.b(0); // 動作 while(device::SYSTEM::OSCOVFSR.MOOVF() == 0) { asm("nop"); } } else { device::SYSTEM::PRCR = 0xA500; return; } #if defined(SIG_RX65N) if(clock_profile::ICLK >= 120'000'000) { // 120MHz 以上の場合設定 device::SYSTEM::ROMWT = 0b10; } else if(clock_profile::ICLK >= 100'000'000) { device::SYSTEM::ROMWT = 0b01; } else if(clock_profile::ICLK >= 50'000'000) { device::SYSTEM::ROMWT = 0b00; } #endif // RX71M はスーパーバイザモードでの変更が必要なので、「start.s」内で行う。 // RX71M の場合、アセンブラにオプション「--defsym MEMWAIT=1」を渡す。 #if defined(SIG_RX66T) || defined(SIG_RX72M) || defined(SIG_RX72T) || defined(SIG_RX72N) if(clock_profile::ICLK > 120'000'000) { // 120MHz 以上の場合設定 device::SYSTEM::MEMWAIT = 1; volatile auto tmp = device::SYSTEM::MEMWAIT(); // 読み出しを行う } #endif // (x10.0) 0b010011, (x10.5) 0b010100, (x11.0) 0b010101, (x11.5) 0b010110 // ... MAX x30.0 uint32_t n = clock_profile::PLL_BASE * 2 / clock_profile::BASE; if(n < 20) n = 20; else if(n > 60) n = 60; n -= 20; device::SYSTEM::PLLCR.STC = n + 0b010011; // base x10 device::SYSTEM::PLLCR2.PLLEN = 0; // PLL 動作 while(device::SYSTEM::OSCOVFSR.PLOVF() == 0) { asm("nop"); } device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(clock_div_(clock_profile::FCLK)) | device::SYSTEM::SCKCR.ICK.b(clock_div_(clock_profile::ICLK)) | device::SYSTEM::SCKCR.BCK.b(clock_div_(clock_profile::BCLK)) | device::SYSTEM::SCKCR.PCKA.b(clock_div_(clock_profile::PCLKA)) | device::SYSTEM::SCKCR.PCKB.b(clock_div_(clock_profile::PCLKB)) | device::SYSTEM::SCKCR.PCKC.b(clock_div_(clock_profile::PCLKC)) | device::SYSTEM::SCKCR.PCKD.b(clock_div_(clock_profile::PCLKD)); { // USB Master Clock の設定 auto usb_div = clock_profile::PLL_BASE / 48'000'000; if(usb_div >= 2 && usb_div <= 5) { // 1/2, 1/3, 1/4, 1/5 device::SYSTEM::SCKCR2.UCK = usb_div - 1; } } if(OSC_TYPE_ == OSC_TYPE::HOCO) { device::SYSTEM::PLLCR.PLLSRCSEL = 1; } device::SYSTEM::SCKCR3.CKSEL = 0b100; ///< PLL 選択 if(OSC_TYPE_ == OSC_TYPE::XTAL || OSC_TYPE_ == OSC_TYPE::EXT) { device::SYSTEM::LOCOCR.LCSTP = 1; ///< 低速オンチップオシレータ停止 device::SYSTEM::HOCOCR.HCSTP = 1; ///< 高速オンチップオシレータ停止 device::SYSTEM::HOCOPCR.HOCOPCNT = 1; ///< 高速オンチップオシレーター電源 OFF } // クロック関係書き込み不許可 device::SYSTEM::PRCR = 0xA500; #if defined(SIG_RX65N) || defined(SIG_RX66T) || defined(SIG_RX72M) || defined(SIG_RX72T) || defined(SIG_RX72N) // ROM キャッシュを有効(標準) device::SYSTEM::ROMCE = 1; #endif #if defined(__TFU) __init_tfu(); #endif } #if defined(SIG_RX72M) || defined(SIG_RX72N) //-------------------------------------------------------------// /*! @brief PPLL 制御を使って PHY 向け 25MHz を出力する。 @return 成功なら「true」 */ //-------------------------------------------------------------// static bool setup_phy25() noexcept { if(clock_profile::BASE != 16'000'000) { // ベースクロックが 16MHz 以外は、生成不可とする。 return false; } bool ret = true; device::SYSTEM::PRCR = 0xA50B; // クロック、低消費電力、関係書き込み許可 device::SYSTEM::PACKCR.OUTCKSEL = 1; // PPLIDIV: 1/2, PPLSTC: x12.5 (100MHz) device::SYSTEM::PPLLCR = device::SYSTEM::PPLLCR.PPLIDIV.b(0b01) | device::SYSTEM::PPLLCR.PPLSTC.b(0b011000); device::SYSTEM::PPLLCR2 = device::SYSTEM::PPLLCR2.PPLLEN.b(1); // 発信許可 // PPLL 安定待ち while(device::SYSTEM::OSCOVFSR.PPLOVF() == 0) { asm("nop"); } // PPLLCR3: 1/4 (25MHz) device::SYSTEM::PPLLCR3 = device::SYSTEM::PPLLCR3.PPLCK.b(0b0011); // クロック関係書き込み不許可 device::SYSTEM::PRCR = 0xA500; // ポート・マッピングを行う必要があるが、あえて、ここでは許可しない。 // ※このヘッダーに、port_map.hpp の依存を無くす為。 // deveice::port_map::turn_CLKOUT25M(); return true; } #endif }; //-------------------------------------------------------------// /*! @brief ソフト・リセットの起動 */ //-------------------------------------------------------------// inline void assert_soft_reset() { device::SYSTEM::PRCR = 0xA502; device::SYSTEM::SWRR = 0xA501; device::SYSTEM::PRCR = 0xA500; } //-------------------------------------------------------------// /*! @brief MTU マスタークロック取得 @return MTU マスタークロック */ //-------------------------------------------------------------// inline uint32_t get_mtu_master_clock() noexcept { #if defined(SIG_RX66T) || defined(SIG_RX72T) return clock_profile::PCLKC; #else return clock_profile::PCLKA; #endif } } <commit_msg>Update: internal OSC<commit_after>#pragma once //=====================================================================// /*! @file @brief RX64M/RX71M/RX651/RX65N/RX66T/RX72T/RX72N/RX72M グループ・システム制御 @n ※RX24T は構成が大きく異なるので、RX24T/system_io.hpp に分離しています。@n ※ USB を使う場合:96MHz, 144MHz, 192MHz, 240MHz のいづれか @n RX72x 系では、内部 PLL 回路が追加され、Ethernet などに必要な 25MHz を得る為 @n 16MHz を使います。@n (16MHz x 12.5 -> 200MHz, 16MHz x 15 -> 240MHz) @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2017, 2021 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "RX600/system.hpp" #if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX66T) || defined(SIG_RX65N) || defined(SIG_RX72T) || defined(SIG_RX72N) || defined(SIG_RX72M) #elif # error "system_io.hpp: Not available on RX24T" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief systen_base クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct system_base { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 発信器タイプ @n HOCO を使う場合、同時に、BASE_CLOCK_ に周波数(16,18,20 MHz)を設定します。 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class OSC_TYPE { XTAL, ///< クリスタル接続 EXT, ///< クロック入力 HOCO, ///< 高速オンチップオシレーター LOCO, ///< 低速オンチップオシレーター (240KHz) }; }; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief systen_io クラス @n INTR_CLOCK は、内部 PLL で扱える最大速度です、@n 外部クリスタルを微妙な周波数にする場合、その整数倍にしなければなりません。 @n RX71M はスーパーバイザモードでの変更が必要なので、「start.s」内で行う。 @n RX71M の場合、アセンブラにオプション「--defsym MEMWAIT=1」を渡す。 @param[in] OSC_TYPE 発信器タイプを設定(通常、XTAL) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <auto OSC_TYPE_ = system_base::OSC_TYPE::XTAL> struct system_io : public system_base { static uint8_t clock_div_(uint32_t clk) noexcept { uint8_t div = 0; while(clk < clock_profile::PLL_BASE) { ++div; clk <<= 1; } if(div > 0b0110) div = 0b0110; return div; } //-------------------------------------------------------------// /*! @brief マスター・クロックのブースト @n インストラクション・クロックを最大速度にブーストする。 */ //-------------------------------------------------------------// static void boost_master_clock() noexcept { device::SYSTEM::PRCR = 0xA50B; // クロック、低消費電力、関係書き込み許可 device::SYSTEM::MOSCWTCR = 9; // 1ms wait // メインクロック強制発振とドライブ能力設定 if(OSC_TYPE_ == OSC_TYPE::XTAL) { uint8_t modrv2 = 0b11; if(clock_profile::BASE > 20'000'000) modrv2 = 0b00; else if(clock_profile::BASE > 16'000'000) modrv2 = 0b01; else if(clock_profile::BASE > 8'000'000) modrv2 = 0b10; device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV2.b(modrv2); device::SYSTEM::MOSCCR.MOSTP = 0; // メインクロック発振器動作 while(device::SYSTEM::OSCOVFSR.MOOVF() == 0) { asm("nop"); } } else if(OSC_TYPE_ == OSC_TYPE::EXT) { device::SYSTEM::MOSCCR.MOSTP = 1; // メインクロック発振器停止 device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MOSEL.b(); } else if(OSC_TYPE_ == OSC_TYPE::HOCO) { // 高速オンチップオシレータ uint8_t frq; if(clock_profile::BASE == 16'000'000) frq = 0b00; else if(clock_profile::BASE == 18'000'000) frq = 0b01; else if(clock_profile::BASE == 20'000'000) frq = 0b10; else frq = 0b00; device::SYSTEM::HOCOCR2.HCFRQ = frq; device::SYSTEM::HOCOCR.HCSTP = 0; // 動作 while(device::SYSTEM::OSCOVFSR.HCOVF() == 0) { asm("nop"); } device::SYSTEM::PLLCR.PLLSRCSEL = 1; } else { device::SYSTEM::PRCR = 0xA500; return; } #if defined(SIG_RX65N) if(clock_profile::ICLK >= 120'000'000) { // 120MHz 以上の場合設定 device::SYSTEM::ROMWT = 0b10; } else if(clock_profile::ICLK >= 100'000'000) { device::SYSTEM::ROMWT = 0b01; } else if(clock_profile::ICLK >= 50'000'000) { device::SYSTEM::ROMWT = 0b00; } #endif // RX71M はスーパーバイザモードでの変更が必要なので、「start.s」内で行う。 // RX71M の場合、アセンブラにオプション「--defsym MEMWAIT=1」を渡す。 #if defined(SIG_RX66T) || defined(SIG_RX72M) || defined(SIG_RX72T) || defined(SIG_RX72N) if(clock_profile::ICLK > 120'000'000) { // 120MHz 以上の場合設定 device::SYSTEM::MEMWAIT = 1; volatile auto tmp = device::SYSTEM::MEMWAIT(); // 読み出しを行う } #endif // (x10.0) 0b010011, (x10.5) 0b010100, (x11.0) 0b010101, (x11.5) 0b010110 // ... MAX x30.0 uint32_t n = clock_profile::PLL_BASE * 2 / clock_profile::BASE; if(n < 20) n = 20; else if(n > 60) n = 60; n -= 20; device::SYSTEM::PLLCR.STC = n + 0b010011; // base x10 device::SYSTEM::PLLCR2.PLLEN = 0; // PLL 動作 while(device::SYSTEM::OSCOVFSR.PLOVF() == 0) { asm("nop"); } device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(clock_div_(clock_profile::FCLK)) | device::SYSTEM::SCKCR.ICK.b(clock_div_(clock_profile::ICLK)) | device::SYSTEM::SCKCR.BCK.b(clock_div_(clock_profile::BCLK)) | device::SYSTEM::SCKCR.PCKA.b(clock_div_(clock_profile::PCLKA)) | device::SYSTEM::SCKCR.PCKB.b(clock_div_(clock_profile::PCLKB)) | device::SYSTEM::SCKCR.PCKC.b(clock_div_(clock_profile::PCLKC)) | device::SYSTEM::SCKCR.PCKD.b(clock_div_(clock_profile::PCLKD)); { // USB Master Clock の設定 auto usb_div = clock_profile::PLL_BASE / 48'000'000; if(usb_div >= 2 && usb_div <= 5) { // 1/2, 1/3, 1/4, 1/5 device::SYSTEM::SCKCR2.UCK = usb_div - 1; } } device::SYSTEM::SCKCR3.CKSEL = 0b100; ///< PLL 選択 if(OSC_TYPE_ == OSC_TYPE::XTAL || OSC_TYPE_ == OSC_TYPE::EXT) { device::SYSTEM::LOCOCR.LCSTP = 1; ///< 低速オンチップオシレータ停止 device::SYSTEM::HOCOCR.HCSTP = 1; ///< 高速オンチップオシレータ停止 device::SYSTEM::HOCOPCR.HOCOPCNT = 1; ///< 高速オンチップオシレーター電源 OFF } else if(OSC_TYPE_ == OSC_TYPE::HOCO) { device::SYSTEM::LOCOCR.LCSTP = 1; ///< 低速オンチップオシレータ停止 } // クロック関係書き込み不許可 device::SYSTEM::PRCR = 0xA500; #if defined(SIG_RX65N) || defined(SIG_RX66T) || defined(SIG_RX72M) || defined(SIG_RX72T) || defined(SIG_RX72N) // ROM キャッシュを有効(標準) device::SYSTEM::ROMCE = 1; #endif #if defined(__TFU) __init_tfu(); #endif } #if defined(SIG_RX72M) || defined(SIG_RX72N) //-------------------------------------------------------------// /*! @brief PPLL 制御を使って PHY 向け 25MHz を出力する。 @return 成功なら「true」 */ //-------------------------------------------------------------// static bool setup_phy25() noexcept { if(clock_profile::BASE != 16'000'000) { // ベースクロックが 16MHz 以外は、生成不可とする。 return false; } bool ret = true; device::SYSTEM::PRCR = 0xA50B; // クロック、低消費電力、関係書き込み許可 device::SYSTEM::PACKCR.OUTCKSEL = 1; // PPLIDIV: 1/2, PPLSTC: x12.5 (100MHz) device::SYSTEM::PPLLCR = device::SYSTEM::PPLLCR.PPLIDIV.b(0b01) | device::SYSTEM::PPLLCR.PPLSTC.b(0b011000); device::SYSTEM::PPLLCR2 = device::SYSTEM::PPLLCR2.PPLLEN.b(1); // 発信許可 // PPLL 安定待ち while(device::SYSTEM::OSCOVFSR.PPLOVF() == 0) { asm("nop"); } // PPLLCR3: 1/4 (25MHz) device::SYSTEM::PPLLCR3 = device::SYSTEM::PPLLCR3.PPLCK.b(0b0011); // クロック関係書き込み不許可 device::SYSTEM::PRCR = 0xA500; // ポート・マッピングを行う必要があるが、あえて、ここでは許可しない。 // ※このヘッダーに、port_map.hpp の依存を無くす為。 // deveice::port_map::turn_CLKOUT25M(); return true; } #endif }; //-------------------------------------------------------------// /*! @brief ソフト・リセットの起動 */ //-------------------------------------------------------------// inline void assert_soft_reset() { device::SYSTEM::PRCR = 0xA502; device::SYSTEM::SWRR = 0xA501; device::SYSTEM::PRCR = 0xA500; } //-------------------------------------------------------------// /*! @brief MTU マスタークロック取得 @return MTU マスタークロック */ //-------------------------------------------------------------// inline uint32_t get_mtu_master_clock() noexcept { #if defined(SIG_RX66T) || defined(SIG_RX72T) return clock_profile::PCLKC; #else return clock_profile::PCLKA; #endif } } <|endoftext|>
<commit_before>/** * Extension.cpp * * @author Emiel Bruijntjes <[email protected]> * @copyright 2013 Copernica BV */ #include "includes.h" /** * Set up namespace */ namespace Php { /** * If this extension is compiled for a PHP version with multi * threading support, we need an additional header file */ #ifdef ZTS #include "TSRM.h" #endif /** * We're almost there, we now need to declare an instance of the * structure defined above (if building for a single thread) or some * sort of impossible to understand magic pointer-to-a-pointer (for * multi-threading builds). We make this a static variable because * this already is bad enough. */ ZEND_DECLARE_MODULE_GLOBALS(phpcpp) /** * Function that must be defined to initialize the "globals" * We do not have to initialize anything, but PHP needs to call this * method (crazy) * @param globals */ static void init_globals(zend_phpcpp_globals *globals) {} /** * The *startup() and *shutdown() callback functions are passed a module_number * variable. However, there does not seem to be a decent API call in Zend to * get back the original module_entry linked to this number. So we have to * look up entries in a hash table to find the right module entry. To make things * even worse, the records in this hash table are copies of the original * zend_module_entry structure, so we can also not hide the C++ extension * object pointer in the entry that we created ourselves. * * We have an ugly solution, we keep track of a map of all C++ extension names * and their associated extension object, and a map of all module number and * the linked extension object. * * @var map */ static std::map<std::string,ExtensionImpl*> name2extension; static std::map<int,ExtensionImpl*> number2extension; /** * Handler function that is used in combination with zend_hash_apply() * * This function is called when we need to find an extension object based on * an extension number. We loop through the list of all registered modules, and * for each module we check if we know the extension based on the name * * @param zend_module_entry */ static int match_module(zend_module_entry *entry) { // check if there is an extension with this name auto iter = name2extension.find(entry->name); if (iter == name2extension.end()) return ZEND_HASH_APPLY_KEEP; // we have the extension, store in combination with the number number2extension[entry->module_number] = iter->second; // done return ZEND_HASH_APPLY_KEEP; } /** * Find an extension based on the module number * @param number * @param tsrm_ls * @return Extension* */ static ExtensionImpl *find(int number TSRMLS_DC) { // do we already have an extension with this number? auto iter = number2extension.find(number); if (iter != number2extension.end()) return iter->second; // no, not yet, loop through all modules zend_hash_apply(&module_registry, (apply_func_t)match_module TSRMLS_CC); // find again iter = number2extension.find(number); if (iter == number2extension.end()) return nullptr; // found! return iter->second; } /** * Function that is called when the extension initializes * @param type Module type * @param number Module number * @param tsrm_ls * @return int 0 on success */ int ExtensionImpl::processStartup(int type, int module_number TSRMLS_DC) { // initialize and allocate the "global" variables ZEND_INIT_MODULE_GLOBALS(phpcpp, init_globals, NULL); // get the extension auto *extension = find(module_number TSRMLS_CC); // array contains ini settings _ini = new zend_ini_entry[extension->_data->iniVariables()+1]; // the entry that we're filling int i=0; // Fill the php.ini entries extension->_data->iniVariables([this, &i, module_number](Ini &ini) { // initialize the function zend_ini_entry *entry = &_ini[i]; // fill the property ini.fill(entry, module_number); // move on to the next iteration i++; }); // last entry should be set to all zero's memset(&_ini[i], 0, sizeof(zend_ini_entry)); // register ini entries in Zend core zend_register_ini_entries(_ini, module_number TSRMLS_CC); // initialize the extension extension->initialize(TSRMLS_C); // is the callback registered? if (extension->_onStartup) extension->_onStartup(); // done return BOOL2SUCCESS(true); } /** * Function that is called when the extension is about to be stopped * @param type Module type * @param number Module number * @param tsrm_ls * @return int */ int ExtensionImpl::processShutdown(int type, int module_number TSRMLS_DC) { // get the extension auto *extension = find(module_number TSRMLS_CC); // unregister the ini entries zend_unregister_ini_entries(module_number TSRMLS_CC); // is the callback registered? if (extension->_onShutdown) extension->_onShutdown(); // done return BOOL2SUCCESS(true); } /** * Function that is called when a request starts * @param type Module type * @param number Module number * @param tsrm_ls * @return int 0 on success */ int ExtensionImpl::processRequest(int type, int module_number TSRMLS_DC) { // get the extension auto *extension = find(module_number TSRMLS_CC); // is the callback registered? if (extension->_onRequest) extension->_onRequest(); // done return BOOL2SUCCESS(true); } /** * Function that is called when a request is ended * @param type Module type * @param number Module number * @param tsrm_ls * @return int 0 on success */ int ExtensionImpl::processIdle(int type, int module_number TSRMLS_DC) { // get the extension auto *extension = find(module_number TSRMLS_CC); // is the callback registered? if (extension->_onIdle) extension->_onIdle(); // done return BOOL2SUCCESS(true); } /** * Constructor * @param data Pointer to the extension object created by the extension programmer * @param name Name of the extension * @param version Version number */ ExtensionImpl::ExtensionImpl(Extension *data, const char *name, const char *version) : ExtensionBase(data) { // keep extension pointer based on the name name2extension[name] = this; // assign all members (apart from the globals) _entry.size = sizeof(zend_module_entry); // size of the data _entry.zend_api = ZEND_MODULE_API_NO; // api number _entry.zend_debug = ZEND_DEBUG; // debug mode enabled? _entry.zts = USING_ZTS; // is thread safety enabled? _entry.ini_entry = NULL; // the php.ini record, will be filled by Zend engine _entry.deps = NULL; // dependencies on other modules _entry.name = name; // extension name _entry.functions = NULL; // functions supported by this module (none for now) _entry.module_startup_func = &ExtensionImpl::processStartup; // startup function for the whole extension _entry.module_shutdown_func = &ExtensionImpl::processShutdown; // shutdown function for the whole extension _entry.request_startup_func = &ExtensionImpl::processRequest; // startup function per request _entry.request_shutdown_func = &ExtensionImpl::processIdle; // shutdown function per request _entry.info_func = NULL; // information for retrieving info _entry.version = version; // version string _entry.globals_size = 0; // size of the global variables _entry.globals_ctor = NULL; // constructor for global variables _entry.globals_dtor = NULL; // destructor for global variables _entry.post_deactivate_func = NULL; // unknown function _entry.module_started = 0; // module is not yet started _entry.type = 0; // temporary or persistent module, will be filled by Zend engine _entry.handle = NULL; // dlopen() handle, will be filled by Zend engine _entry.module_number = 0; // module number will be filled in by Zend engine _entry.build_id = (char *)ZEND_MODULE_BUILD_ID; // check if extension and zend engine are compatible // things that only need to be initialized #ifdef ZTS _entry.globals_id_ptr = NULL; #else _entry.globals_ptr = NULL; #endif } /** * Destructor */ ExtensionImpl::~ExtensionImpl() { // deallocate the php.ini entries if (_ini) delete[] _ini; // deallocate functions if (_entry.functions) delete[] _entry.functions; } /** * Retrieve the module entry * @return zend_module_entry */ zend_module_entry *ExtensionImpl::module() { // check if functions we're already defined if (_entry.functions) return &_entry; // the number of functions int count = _data->functions(); // skip if there are no functions if (count == 0) return &_entry; // allocate memory for the functions zend_function_entry *entries = new zend_function_entry[count + 1]; // index being processed int i = 0; // apply a function to each function _data->functions([&i, entries](const std::string &prefix, Function &function) { // initialize the function function.initialize(prefix, &entries[i]); // move on to the next iteration i++; }); // last entry should be set to all zeros zend_function_entry *last = &entries[count]; // all should be set to zero memset(last, 0, sizeof(zend_function_entry)); // store functions in entry object _entry.functions = entries; // return the entry return &_entry; } /** * Initialize the extension after it was started * @param tsrm_ls */ void ExtensionImpl::initialize(TSRMLS_D) { // we need to register each class, find out all classes _data->classes([TSRMLS_C](const std::string &prefix, ClassBase &c) { // forward to implementation class c.implementation()->initialize(&c, prefix TSRMLS_CC); }); } /** * End of namespace */ } <commit_msg>fixed compile issue (issue #64)<commit_after>/** * Extension.cpp * * @author Emiel Bruijntjes <[email protected]> * @copyright 2013 Copernica BV */ #include "includes.h" /** * Set up namespace */ namespace Php { /** * If this extension is compiled for a PHP version with multi * threading support, we need an additional header file */ #ifdef ZTS #include "TSRM.h" #endif /** * We're almost there, we now need to declare an instance of the * structure defined above (if building for a single thread) or some * sort of impossible to understand magic pointer-to-a-pointer (for * multi-threading builds). We make this a static variable because * this already is bad enough. */ ZEND_DECLARE_MODULE_GLOBALS(phpcpp) /** * Function that must be defined to initialize the "globals" * We do not have to initialize anything, but PHP needs to call this * method (crazy) * @param globals */ static void init_globals(zend_phpcpp_globals *globals) {} /** * The *startup() and *shutdown() callback functions are passed a module_number * variable. However, there does not seem to be a decent API call in Zend to * get back the original module_entry linked to this number. So we have to * look up entries in a hash table to find the right module entry. To make things * even worse, the records in this hash table are copies of the original * zend_module_entry structure, so we can also not hide the C++ extension * object pointer in the entry that we created ourselves. * * We have an ugly solution, we keep track of a map of all C++ extension names * and their associated extension object, and a map of all module number and * the linked extension object. * * @var map */ static std::map<std::string,ExtensionImpl*> name2extension; static std::map<int,ExtensionImpl*> number2extension; /** * Handler function that is used in combination with zend_hash_apply() * * This function is called when we need to find an extension object based on * an extension number. We loop through the list of all registered modules, and * for each module we check if we know the extension based on the name * * @param zend_module_entry */ static int match_module(zend_module_entry *entry) { // check if there is an extension with this name auto iter = name2extension.find(entry->name); if (iter == name2extension.end()) return ZEND_HASH_APPLY_KEEP; // we have the extension, store in combination with the number number2extension[entry->module_number] = iter->second; // done return ZEND_HASH_APPLY_KEEP; } /** * Find an extension based on the module number * @param number * @param tsrm_ls * @return Extension* */ static ExtensionImpl *find(int number TSRMLS_DC) { // do we already have an extension with this number? auto iter = number2extension.find(number); if (iter != number2extension.end()) return iter->second; // no, not yet, loop through all modules zend_hash_apply(&module_registry, (apply_func_t)match_module TSRMLS_CC); // find again iter = number2extension.find(number); if (iter == number2extension.end()) return nullptr; // found! return iter->second; } /** * Function that is called when the extension initializes * @param type Module type * @param number Module number * @param tsrm_ls * @return int 0 on success */ int ExtensionImpl::processStartup(int type, int module_number TSRMLS_DC) { // initialize and allocate the "global" variables ZEND_INIT_MODULE_GLOBALS(phpcpp, init_globals, NULL); // get the extension auto *extension = find(module_number TSRMLS_CC); // array contains ini settings auto *entries = extension->_ini = new zend_ini_entry[extension->_data->iniVariables()+1]; // the entry that we're filling int i=0; // Fill the php.ini entries extension->_data->iniVariables([entries, &i, module_number](Ini &ini) { // initialize the function zend_ini_entry *entry = &entries[i]; // fill the property ini.fill(entry, module_number); // move on to the next iteration i++; }); // last entry should be set to all zero's memset(&entries[i], 0, sizeof(zend_ini_entry)); // register ini entries in Zend core zend_register_ini_entries(entries, module_number TSRMLS_CC); // initialize the extension extension->initialize(TSRMLS_C); // is the callback registered? if (extension->_onStartup) extension->_onStartup(); // done return BOOL2SUCCESS(true); } /** * Function that is called when the extension is about to be stopped * @param type Module type * @param number Module number * @param tsrm_ls * @return int */ int ExtensionImpl::processShutdown(int type, int module_number TSRMLS_DC) { // get the extension auto *extension = find(module_number TSRMLS_CC); // unregister the ini entries zend_unregister_ini_entries(module_number TSRMLS_CC); // is the callback registered? if (extension->_onShutdown) extension->_onShutdown(); // done return BOOL2SUCCESS(true); } /** * Function that is called when a request starts * @param type Module type * @param number Module number * @param tsrm_ls * @return int 0 on success */ int ExtensionImpl::processRequest(int type, int module_number TSRMLS_DC) { // get the extension auto *extension = find(module_number TSRMLS_CC); // is the callback registered? if (extension->_onRequest) extension->_onRequest(); // done return BOOL2SUCCESS(true); } /** * Function that is called when a request is ended * @param type Module type * @param number Module number * @param tsrm_ls * @return int 0 on success */ int ExtensionImpl::processIdle(int type, int module_number TSRMLS_DC) { // get the extension auto *extension = find(module_number TSRMLS_CC); // is the callback registered? if (extension->_onIdle) extension->_onIdle(); // done return BOOL2SUCCESS(true); } /** * Constructor * @param data Pointer to the extension object created by the extension programmer * @param name Name of the extension * @param version Version number */ ExtensionImpl::ExtensionImpl(Extension *data, const char *name, const char *version) : ExtensionBase(data) { // keep extension pointer based on the name name2extension[name] = this; // assign all members (apart from the globals) _entry.size = sizeof(zend_module_entry); // size of the data _entry.zend_api = ZEND_MODULE_API_NO; // api number _entry.zend_debug = ZEND_DEBUG; // debug mode enabled? _entry.zts = USING_ZTS; // is thread safety enabled? _entry.ini_entry = NULL; // the php.ini record, will be filled by Zend engine _entry.deps = NULL; // dependencies on other modules _entry.name = name; // extension name _entry.functions = NULL; // functions supported by this module (none for now) _entry.module_startup_func = &ExtensionImpl::processStartup; // startup function for the whole extension _entry.module_shutdown_func = &ExtensionImpl::processShutdown; // shutdown function for the whole extension _entry.request_startup_func = &ExtensionImpl::processRequest; // startup function per request _entry.request_shutdown_func = &ExtensionImpl::processIdle; // shutdown function per request _entry.info_func = NULL; // information for retrieving info _entry.version = version; // version string _entry.globals_size = 0; // size of the global variables _entry.globals_ctor = NULL; // constructor for global variables _entry.globals_dtor = NULL; // destructor for global variables _entry.post_deactivate_func = NULL; // unknown function _entry.module_started = 0; // module is not yet started _entry.type = 0; // temporary or persistent module, will be filled by Zend engine _entry.handle = NULL; // dlopen() handle, will be filled by Zend engine _entry.module_number = 0; // module number will be filled in by Zend engine _entry.build_id = (char *)ZEND_MODULE_BUILD_ID; // check if extension and zend engine are compatible // things that only need to be initialized #ifdef ZTS _entry.globals_id_ptr = NULL; #else _entry.globals_ptr = NULL; #endif } /** * Destructor */ ExtensionImpl::~ExtensionImpl() { // deallocate the php.ini entries if (_ini) delete[] _ini; // deallocate functions if (_entry.functions) delete[] _entry.functions; } /** * Retrieve the module entry * @return zend_module_entry */ zend_module_entry *ExtensionImpl::module() { // check if functions we're already defined if (_entry.functions) return &_entry; // the number of functions int count = _data->functions(); // skip if there are no functions if (count == 0) return &_entry; // allocate memory for the functions zend_function_entry *entries = new zend_function_entry[count + 1]; // index being processed int i = 0; // apply a function to each function _data->functions([&i, entries](const std::string &prefix, Function &function) { // initialize the function function.initialize(prefix, &entries[i]); // move on to the next iteration i++; }); // last entry should be set to all zeros zend_function_entry *last = &entries[count]; // all should be set to zero memset(last, 0, sizeof(zend_function_entry)); // store functions in entry object _entry.functions = entries; // return the entry return &_entry; } /** * Initialize the extension after it was started * @param tsrm_ls */ void ExtensionImpl::initialize(TSRMLS_D) { // we need to register each class, find out all classes _data->classes([TSRMLS_C](const std::string &prefix, ClassBase &c) { // forward to implementation class c.implementation()->initialize(&c, prefix TSRMLS_CC); }); } /** * End of namespace */ } <|endoftext|>
<commit_before>#include "QuaternionFloatingJoint.h" #include <random> #include "drakeGeometryUtil.h" using namespace Eigen; using namespace std; QuaternionFloatingJoint::QuaternionFloatingJoint(const string& name, const Isometry3d& transform_to_parent_body) : DrakeJoint(name, transform_to_parent_body, 7, 6) { // empty } QuaternionFloatingJoint::~QuaternionFloatingJoint() { // empty } Isometry3d QuaternionFloatingJoint::jointTransform(const Eigen::Ref<const VectorXd>& q) const { Isometry3d ret(Quaterniond(q[3], q[4], q[5], q[6])); ret.translation() << q[0], q[1], q[2]; ret.makeAffine(); return ret; } void QuaternionFloatingJoint::motionSubspace(const Eigen::Ref<const VectorXd>& q, MotionSubspaceType& motion_subspace, MatrixXd* dmotion_subspace) const { motion_subspace.setIdentity(TWIST_SIZE, getNumVelocities()); if (dmotion_subspace) { dmotion_subspace->setZero(motion_subspace.size(), getNumPositions()); } } void QuaternionFloatingJoint::motionSubspaceDotTimesV(const Eigen::Ref<const VectorXd>& q, const Eigen::Ref<const VectorXd>& v, Vector6d& motion_subspace_dot_times_v, Gradient<Vector6d, Eigen::Dynamic>::type* dmotion_subspace_dot_times_vdq, Gradient<Vector6d, Eigen::Dynamic>::type* dmotion_subspace_dot_times_vdv) const { motion_subspace_dot_times_v.setZero(); if (dmotion_subspace_dot_times_vdq) { dmotion_subspace_dot_times_vdq->setZero(motion_subspace_dot_times_v.size(), getNumPositions()); } if (dmotion_subspace_dot_times_vdv) { dmotion_subspace_dot_times_vdv->setZero(motion_subspace_dot_times_v.size(), getNumVelocities()); } } void QuaternionFloatingJoint::randomConfiguration(Eigen::Ref<VectorXd>& q, std::default_random_engine& generator) const { normal_distribution<double> normal; // position q[0] = normal(generator); q[1] = normal(generator); q[2] = normal(generator); // orientation Vector4d quat = uniformlyRandomQuat(generator); q[3] = quat(0); q[4] = quat(1); q[5] = quat(2); q[6] = quat(3); } void QuaternionFloatingJoint::qdot2v(const Eigen::Ref<const VectorXd>& q, Eigen::MatrixXd& qdot_to_v, Eigen::MatrixXd* dqdot_to_v) const { qdot_to_v.resize(getNumVelocities(), getNumPositions()); auto quat = q.template middleRows<QUAT_SIZE>(SPACE_DIMENSION); Matrix3d R = quat2rotmat(quat); Vector4d quattilde; Matrix<double, SPACE_DIMENSION, QUAT_SIZE> M; Matrix<double, SPACE_DIMENSION, QUAT_SIZE> RTransposeM; Gradient<Vector4d, QUAT_SIZE, 1>::type dquattildedquat; if (dqdot_to_v) { Gradient<Vector4d, QUAT_SIZE, 2>::type ddquattildedquat; normalizeVec(quat, quattilde, &dquattildedquat, &ddquattildedquat); auto dR = dquat2rotmat(quat); Gradient<Matrix<double, SPACE_DIMENSION, QUAT_SIZE>, QUAT_SIZE, 1>::type dM; quatdot2angularvelMatrix(quat, M, &dM); RTransposeM.noalias() = R.transpose() * M; auto dRTranspose = transposeGrad(dR, R.rows()); auto dRTransposeM = matGradMultMat(R.transpose(), M, dRTranspose, dM); auto dRTransposeMdquattildedquat = matGradMultMat(RTransposeM, dquattildedquat, dRTransposeM, ddquattildedquat); dqdot_to_v->setZero(qdot_to_v.size(), getNumPositions()); setSubMatrixGradient<4>(*dqdot_to_v, dRTranspose, intRange<3>(3), intRange<3>(0), qdot_to_v.rows(), 3); setSubMatrixGradient<4>(*dqdot_to_v, dRTransposeMdquattildedquat, intRange<3>(0), intRange<4>(3), qdot_to_v.rows(), 3); } else { normalizeVec(quat, quattilde, &dquattildedquat); quatdot2angularvelMatrix(quat, M); RTransposeM.noalias() = R.transpose() * M; } qdot_to_v.block<3, 3>(0, 0).setZero(); qdot_to_v.block<3, 4>(0, 3).noalias() = RTransposeM * dquattildedquat; qdot_to_v.block<3, 3>(3, 0) = R.transpose(); qdot_to_v.block<3, 4>(3, 3).setZero(); } void QuaternionFloatingJoint::v2qdot(const Eigen::Ref<const VectorXd>& q, Eigen::MatrixXd& v_to_qdot, Eigen::MatrixXd* dv_to_qdot) const { v_to_qdot.resize(getNumPositions(), getNumVelocities()); auto quat = q.template middleRows<QUAT_SIZE>(SPACE_DIMENSION); Matrix3d R = quat2rotmat(quat); Matrix<double, QUAT_SIZE, SPACE_DIMENSION> M; if (dv_to_qdot) { auto dR = dquat2rotmat(quat); Gradient<decltype(M), QUAT_SIZE, 1>::type dM; angularvel2quatdotMatrix(quat, M, &dM); dv_to_qdot->setZero(v_to_qdot.size(), getNumPositions()); setSubMatrixGradient<4>(*dv_to_qdot, dR, intRange<3>(0), intRange<3>(3), v_to_qdot.rows(), 3); auto dMR = matGradMultMat(M, R, dM, dR); setSubMatrixGradient<4>(*dv_to_qdot, dMR, intRange<4>(3), intRange<3>(0), v_to_qdot.rows(), 3); } else { angularvel2quatdotMatrix(quat, M, (Gradient<decltype(M), QUAT_SIZE, 1>::type*) nullptr); } v_to_qdot.block<3, 3>(0, 0).setZero(); v_to_qdot.block<3, 3>(0, 3) = R; v_to_qdot.block<4, 3>(3, 0).noalias() = M * R; v_to_qdot.block<4, 3>(3, 3).setZero(); } <commit_msg>Removed superfluous template disambiguators.<commit_after>#include "QuaternionFloatingJoint.h" #include <random> #include "drakeGeometryUtil.h" using namespace Eigen; using namespace std; QuaternionFloatingJoint::QuaternionFloatingJoint(const string& name, const Isometry3d& transform_to_parent_body) : DrakeJoint(name, transform_to_parent_body, 7, 6) { // empty } QuaternionFloatingJoint::~QuaternionFloatingJoint() { // empty } Isometry3d QuaternionFloatingJoint::jointTransform(const Eigen::Ref<const VectorXd>& q) const { Isometry3d ret(Quaterniond(q[3], q[4], q[5], q[6])); ret.translation() << q[0], q[1], q[2]; ret.makeAffine(); return ret; } void QuaternionFloatingJoint::motionSubspace(const Eigen::Ref<const VectorXd>& q, MotionSubspaceType& motion_subspace, MatrixXd* dmotion_subspace) const { motion_subspace.setIdentity(TWIST_SIZE, getNumVelocities()); if (dmotion_subspace) { dmotion_subspace->setZero(motion_subspace.size(), getNumPositions()); } } void QuaternionFloatingJoint::motionSubspaceDotTimesV(const Eigen::Ref<const VectorXd>& q, const Eigen::Ref<const VectorXd>& v, Vector6d& motion_subspace_dot_times_v, Gradient<Vector6d, Eigen::Dynamic>::type* dmotion_subspace_dot_times_vdq, Gradient<Vector6d, Eigen::Dynamic>::type* dmotion_subspace_dot_times_vdv) const { motion_subspace_dot_times_v.setZero(); if (dmotion_subspace_dot_times_vdq) { dmotion_subspace_dot_times_vdq->setZero(motion_subspace_dot_times_v.size(), getNumPositions()); } if (dmotion_subspace_dot_times_vdv) { dmotion_subspace_dot_times_vdv->setZero(motion_subspace_dot_times_v.size(), getNumVelocities()); } } void QuaternionFloatingJoint::randomConfiguration(Eigen::Ref<VectorXd>& q, std::default_random_engine& generator) const { normal_distribution<double> normal; // position q[0] = normal(generator); q[1] = normal(generator); q[2] = normal(generator); // orientation Vector4d quat = uniformlyRandomQuat(generator); q[3] = quat(0); q[4] = quat(1); q[5] = quat(2); q[6] = quat(3); } void QuaternionFloatingJoint::qdot2v(const Eigen::Ref<const VectorXd>& q, Eigen::MatrixXd& qdot_to_v, Eigen::MatrixXd* dqdot_to_v) const { qdot_to_v.resize(getNumVelocities(), getNumPositions()); auto quat = q.middleRows<QUAT_SIZE>(SPACE_DIMENSION); Matrix3d R = quat2rotmat(quat); Vector4d quattilde; Matrix<double, SPACE_DIMENSION, QUAT_SIZE> M; Matrix<double, SPACE_DIMENSION, QUAT_SIZE> RTransposeM; Gradient<Vector4d, QUAT_SIZE, 1>::type dquattildedquat; if (dqdot_to_v) { Gradient<Vector4d, QUAT_SIZE, 2>::type ddquattildedquat; normalizeVec(quat, quattilde, &dquattildedquat, &ddquattildedquat); auto dR = dquat2rotmat(quat); Gradient<Matrix<double, SPACE_DIMENSION, QUAT_SIZE>, QUAT_SIZE, 1>::type dM; quatdot2angularvelMatrix(quat, M, &dM); RTransposeM.noalias() = R.transpose() * M; auto dRTranspose = transposeGrad(dR, R.rows()); auto dRTransposeM = matGradMultMat(R.transpose(), M, dRTranspose, dM); auto dRTransposeMdquattildedquat = matGradMultMat(RTransposeM, dquattildedquat, dRTransposeM, ddquattildedquat); dqdot_to_v->setZero(qdot_to_v.size(), getNumPositions()); setSubMatrixGradient<4>(*dqdot_to_v, dRTranspose, intRange<3>(3), intRange<3>(0), qdot_to_v.rows(), 3); setSubMatrixGradient<4>(*dqdot_to_v, dRTransposeMdquattildedquat, intRange<3>(0), intRange<4>(3), qdot_to_v.rows(), 3); } else { normalizeVec(quat, quattilde, &dquattildedquat); quatdot2angularvelMatrix(quat, M); RTransposeM.noalias() = R.transpose() * M; } qdot_to_v.block<3, 3>(0, 0).setZero(); qdot_to_v.block<3, 4>(0, 3).noalias() = RTransposeM * dquattildedquat; qdot_to_v.block<3, 3>(3, 0) = R.transpose(); qdot_to_v.block<3, 4>(3, 3).setZero(); } void QuaternionFloatingJoint::v2qdot(const Eigen::Ref<const VectorXd>& q, Eigen::MatrixXd& v_to_qdot, Eigen::MatrixXd* dv_to_qdot) const { v_to_qdot.resize(getNumPositions(), getNumVelocities()); auto quat = q.middleRows<QUAT_SIZE>(SPACE_DIMENSION); Matrix3d R = quat2rotmat(quat); Matrix<double, QUAT_SIZE, SPACE_DIMENSION> M; if (dv_to_qdot) { auto dR = dquat2rotmat(quat); Gradient<decltype(M), QUAT_SIZE, 1>::type dM; angularvel2quatdotMatrix(quat, M, &dM); dv_to_qdot->setZero(v_to_qdot.size(), getNumPositions()); setSubMatrixGradient<4>(*dv_to_qdot, dR, intRange<3>(0), intRange<3>(3), v_to_qdot.rows(), 3); auto dMR = matGradMultMat(M, R, dM, dR); setSubMatrixGradient<4>(*dv_to_qdot, dMR, intRange<4>(3), intRange<3>(0), v_to_qdot.rows(), 3); } else { angularvel2quatdotMatrix(quat, M, (Gradient<decltype(M), QUAT_SIZE, 1>::type*) nullptr); } v_to_qdot.block<3, 3>(0, 0).setZero(); v_to_qdot.block<3, 3>(0, 3) = R; v_to_qdot.block<4, 3>(3, 0).noalias() = M * R; v_to_qdot.block<4, 3>(3, 3).setZero(); } <|endoftext|>
<commit_before>#include "converterconfigurationdialog.h" #include "checkboxdelegate.h" #include "cmdlinehighlighterdelegate.h" #include <QVBoxLayout> #include <QHBoxLayout> #include <QPushButton> #include <QFileDialog> #include <QMessageBox> #include <QDialogButtonBox> #include <QHeaderView> #include <QDebug> #include <QApplication> ConverterConfigurationDialog::ConverterConfigurationDialog(QWidget* parent, Qt::WindowFlags f) : QDialog(parent, f) { // allocate auto headingLabel = new QLabel("Configure External Converters"); mainConverterLocationLabel = new QLabel("Location of Main Converter:"); mainConverterLocationEdit = new FancyLineEdit; contextMenu = new QMenu(this); contextToolBar = new QToolBar(this); browseButton = new QPushButton("Browse ..."); additionalConvertersLabel = new QLabel("Additional converters:"); auto stdButtons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); auto mainLayout = new QVBoxLayout; auto mainConverterLayout = new QHBoxLayout; // set model tableView.setModel(&convertersModel); // configure view tableView.verticalHeader()->setHidden(true); tableView.setSelectionMode(QAbstractItemView::SingleSelection); tableView.setSelectionBehavior(QAbstractItemView::SelectRows); tableView.setContextMenuPolicy(Qt::CustomContextMenu); tableView.horizontalHeader()->setStretchLastSection(true); // configure menu & toolbar initMenu(); initToolBar(); contextToolBar->hide(); // configure fonts QFont defaultFont{qApp->font()}; QFont heading2Font{defaultFont}; QFont heading1Font{defaultFont}; heading2Font.setPointSize(defaultFont.pointSize() + 2); heading1Font.setPointSize(defaultFont.pointSize() + 4); // configure widgets headingLabel->setFont(heading1Font); headingLabel->setAlignment(Qt::AlignHCenter); mainConverterLocationEdit->hideEditButton(); mainConverterLocationLabel->setFont(heading2Font); additionalConvertersLabel->setFont(heading2Font); // attach widgets to main layout mainLayout->addWidget(headingLabel); mainLayout->addSpacing(6); mainLayout->addWidget(mainConverterLocationLabel); mainConverterLayout->addWidget(mainConverterLocationEdit); mainConverterLayout->addWidget(browseButton); mainLayout->addLayout(mainConverterLayout); mainLayout->addSpacing(6); mainLayout->addWidget(additionalConvertersLabel); mainLayout->addWidget(&tableView); mainLayout->addWidget(stdButtons); setLayout(mainLayout); // hide unnecessary columns tableView.setColumnHidden(0, true); tableView.setColumnHidden(3, true); tableView.setColumnHidden(6, true); tableView.setColumnHidden(9, true); tableView.setColumnHidden(10, true); // set delegates tableView.setItemDelegateForColumn(8, new CmdLineHighlighterDelegate(this)); tableView.setItemDelegateForColumn(1, new CheckBoxDelegate(this)); // connect signals / slots connect(mainConverterLocationEdit, &QLineEdit::editingFinished, this, [this] { mainConverterPath = mainConverterLocationEdit->text(); }); connect(browseButton, &QPushButton::clicked, this, &ConverterConfigurationDialog::promptForResamplerLocation); connect(&tableView, &QWidget::customContextMenuRequested, this, [this](const QPoint& pos){ contextMenu->popup(QPoint{this->mapToGlobal(pos).x(), this->mapToGlobal(pos).y() + contextMenu->sizeHint().height()}); }); connect(&tableView, &QTableView::clicked, this, [this](const QModelIndex& modelIndex) { QPoint p{tableView.columnViewportPosition(modelIndex.column()) , tableView.rowViewportPosition(modelIndex.row())}; contextToolBar->move(p + QPoint{0, (int)tableView.geometry().top() + contextToolBar->sizeHint().height() * 3} ); contextToolBar->show(); contextToolBar->raise(); }); connect(stdButtons, &QDialogButtonBox::accepted, this, &QDialog::accept); connect(stdButtons, &QDialogButtonBox::rejected, this, &QDialog::reject); } void ConverterConfigurationDialog::initMenu() { contextMenu->addAction("New", [this] { onNewRequested(tableView.currentIndex()); }, QKeySequence::New); contextMenu->addAction("Edit ...", [this] { onEditRequested(tableView.currentIndex()); }); contextMenu->addAction("Clone", [this] { onCloneRequested(tableView.currentIndex()); }, QKeySequence::Copy); contextMenu->addAction("Delete", [this] { onDeleteRequested(tableView.currentIndex()); }, {QKeySequence::Delete}); contextMenu->addAction("Move Up", [this] { onMoveUpRequested(tableView.currentIndex()); }); contextMenu->addAction("Move Down", [this] { onMoveDownRequested(tableView.currentIndex()); }); } void ConverterConfigurationDialog::initToolBar() { contextToolBar->addAction("New", [this] { onNewRequested(tableView.currentIndex()); contextToolBar->hide(); }); contextToolBar->addAction("Edit ...", [this] { onEditRequested(tableView.currentIndex()); contextToolBar->hide(); }); contextToolBar->addAction("Clone", [this] { onCloneRequested(tableView.currentIndex()); contextToolBar->hide(); }); contextToolBar->addAction("Delete", [this] { onDeleteRequested(tableView.currentIndex()); contextToolBar->hide(); }); contextToolBar->addAction("Move Up", [this] { onMoveUpRequested(tableView.currentIndex()); //contextToolBar->hide(); }); qDebug() << contextToolBar->addAction("Move Down", [this] { onMoveDownRequested(tableView.currentIndex()); //contextToolBar->hide(); }); contextToolBar->setContentsMargins(0, 0, 0, 0); contextToolBar->setMinimumWidth(tableView.width() / 2); contextToolBar->setMaximumWidth(tableView.width()); } void ConverterConfigurationDialog::showEvent(QShowEvent* event) { if(mainConverterPath.isEmpty() || !QFile::exists(mainConverterPath)) { promptForResamplerLocation(); } mainConverterLocationLabel->setText(QString{"Location of Main Converter (%1):"}.arg(expectedMainConverter)); mainConverterLocationEdit->setText(mainConverterPath); QDialog::showEvent(event); } void ConverterConfigurationDialog::resizeEvent(QResizeEvent *event) { int tw = event->size().width(); static const QVector<double> columnWidths { 0, /* "Priority" */ 10, /* "Enabled" */ 20, /* "Name" */ 0 , /* "Comment" */ 12, /* "Input File Extension" */ 12, /* "Output File Extension" */ 0 , /* "Executable" */ 20, /* "Executable Path" */ 20, /* "Command Line" */ 0 , /* "Download Locations" */ 0 /* "Operating Systems" */ }; for(int col = 0; col < convertersModel.columnCount({}) - 1; col++) { tableView.horizontalHeader()->resizeSection(col, tw * columnWidths.at(col)/100.0); } tableView.horizontalHeader()->setHidden(false); QDialog::resizeEvent(event); } QVector<ConverterDefinition> ConverterConfigurationDialog::getConverterDefinitions() const { return convertersModel.getConverterDefinitions(); } void ConverterConfigurationDialog::setConverterDefinitions(const QVector<ConverterDefinition> &value) { convertersModel.setConverterDefinitions(value); } void ConverterConfigurationDialog::promptForResamplerLocation() { QString s("Please locate the file: "); s.append(expectedMainConverter); #if defined (Q_OS_WIN) QString filter = "*.exe"; #else QString filter = ""; #endif QString cp = QFileDialog::getOpenFileName(this, s, mainConverterPath, filter); if(!cp.isNull()) { mainConverterPath = cp; if(mainConverterPath.lastIndexOf(expectedMainConverter, -1, Qt::CaseInsensitive) == -1) { // safeguard against wrong executable being configured mainConverterPath.clear(); QMessageBox::warning(this, tr("Converter Location"), tr("That is not the right program!\n"), QMessageBox::Ok); } } } QString ConverterConfigurationDialog::getMainConverterPath() const { return mainConverterPath; } void ConverterConfigurationDialog::setMainConverterPath(const QString &value) { mainConverterPath = value; } QString ConverterConfigurationDialog::getExpectedMainConverter() const { return expectedMainConverter; } void ConverterConfigurationDialog::setExpectedMainConverter(const QString &value) { expectedMainConverter = value; // set tooltips mainConverterLocationLabel->setToolTip(QString{"Please enter the location of %1 in the box below.\n" "(%1 is the command-line audio converter that Ferocious was designed to work with.)" }.arg(expectedMainConverter)); mainConverterLocationEdit->setToolTip(QString{"Location of %1\n" "Note: you can also use drag-and-drop, or the 'Browse' button"}.arg(expectedMainConverter)); browseButton->setToolTip(QString{"Browse to location of %1"}.arg(expectedMainConverter)); additionalConvertersLabel->setToolTip("Use the table below to cofigure additional converters for specialized file formats."); } void ConverterConfigurationDialog::onNewRequested(const QModelIndex& modelIndex) { int row = modelIndex.row(); if(row < 0 ) return; QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions(); if(row < converterDefinitions.count()) { converterDefinitions.insert(row, {}); convertersModel.setConverterDefinitions(converterDefinitions); } } void ConverterConfigurationDialog::onEditRequested(const QModelIndex& modelIndex) { QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions(); if (converterDefinitions.isEmpty()) return; int row = modelIndex.row(); if (row < 0) return; auto dlg = new ConverterConfigurationEditDialog(this); if(row < converterDefinitions.count()) { dlg->setConverterDefinition(converterDefinitions.at(row)); int result = dlg->exec(); if(result == QDialog::Accepted) { converterDefinitions[row] = dlg->getConverterDefinition(); convertersModel.setConverterDefinitions(converterDefinitions); } } } void ConverterConfigurationDialog::onDeleteRequested(const QModelIndex& modelIndex) { int row = modelIndex.row(); if(row < 0 ) return; QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions(); if(row < converterDefinitions.count()) { converterDefinitions.removeAt(row); convertersModel.setConverterDefinitions(converterDefinitions); } } void ConverterConfigurationDialog::onCloneRequested(const QModelIndex& modelIndex) { int row = modelIndex.row(); if(row < 0 ) return; QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions(); if(row < converterDefinitions.count()) { converterDefinitions.insert(row, converterDefinitions.at(row)); convertersModel.setConverterDefinitions(converterDefinitions); } } void ConverterConfigurationDialog::onMoveUpRequested(const QModelIndex& modelIndex) { int row = modelIndex.row(); if(row < 1 ) { return; } QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions(); if(row < converterDefinitions.count()) { qSwap(converterDefinitions[row], converterDefinitions[row - 1]); convertersModel.setConverterDefinitions(converterDefinitions); tableView.selectRow(row - 1); } } void ConverterConfigurationDialog::onMoveDownRequested(const QModelIndex& modelIndex) { int row = modelIndex.row(); if(row < 0 ) { return; } QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions(); if(row < converterDefinitions.count() - 1) { qSwap(converterDefinitions[row], converterDefinitions[row + 1]); convertersModel.setConverterDefinitions(converterDefinitions); tableView.selectRow(row + 1); } } <commit_msg>improved QToolBar popup position<commit_after>#include "converterconfigurationdialog.h" #include "checkboxdelegate.h" #include "cmdlinehighlighterdelegate.h" #include <QVBoxLayout> #include <QHBoxLayout> #include <QPushButton> #include <QFileDialog> #include <QMessageBox> #include <QDialogButtonBox> #include <QHeaderView> #include <QDebug> #include <QApplication> ConverterConfigurationDialog::ConverterConfigurationDialog(QWidget* parent, Qt::WindowFlags f) : QDialog(parent, f) { // allocate auto headingLabel = new QLabel("Configure External Converters"); mainConverterLocationLabel = new QLabel("Location of Main Converter:"); mainConverterLocationEdit = new FancyLineEdit; contextMenu = new QMenu(this); contextToolBar = new QToolBar(this); browseButton = new QPushButton("Browse ..."); additionalConvertersLabel = new QLabel("Additional converters:"); auto stdButtons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); auto mainLayout = new QVBoxLayout; auto mainConverterLayout = new QHBoxLayout; // set model tableView.setModel(&convertersModel); // configure view tableView.verticalHeader()->setHidden(true); tableView.setSelectionMode(QAbstractItemView::SingleSelection); tableView.setSelectionBehavior(QAbstractItemView::SelectRows); tableView.setContextMenuPolicy(Qt::CustomContextMenu); tableView.horizontalHeader()->setStretchLastSection(true); // configure menu & toolbar initMenu(); initToolBar(); contextToolBar->hide(); // configure fonts QFont defaultFont{qApp->font()}; QFont heading2Font{defaultFont}; QFont heading1Font{defaultFont}; heading2Font.setPointSize(defaultFont.pointSize() + 2); heading1Font.setPointSize(defaultFont.pointSize() + 4); // configure widgets headingLabel->setFont(heading1Font); headingLabel->setAlignment(Qt::AlignHCenter); mainConverterLocationEdit->hideEditButton(); mainConverterLocationLabel->setFont(heading2Font); additionalConvertersLabel->setFont(heading2Font); // attach widgets to main layout mainLayout->addWidget(headingLabel); mainLayout->addSpacing(6); mainLayout->addWidget(mainConverterLocationLabel); mainConverterLayout->addWidget(mainConverterLocationEdit); mainConverterLayout->addWidget(browseButton); mainLayout->addLayout(mainConverterLayout); mainLayout->addSpacing(6); mainLayout->addWidget(additionalConvertersLabel); mainLayout->addWidget(&tableView); mainLayout->addWidget(stdButtons); setLayout(mainLayout); // hide unnecessary columns tableView.setColumnHidden(0, true); tableView.setColumnHidden(3, true); tableView.setColumnHidden(6, true); tableView.setColumnHidden(9, true); tableView.setColumnHidden(10, true); // set delegates tableView.setItemDelegateForColumn(8, new CmdLineHighlighterDelegate(this)); tableView.setItemDelegateForColumn(1, new CheckBoxDelegate(this)); // connect signals / slots connect(mainConverterLocationEdit, &QLineEdit::editingFinished, this, [this] { mainConverterPath = mainConverterLocationEdit->text(); }); connect(browseButton, &QPushButton::clicked, this, &ConverterConfigurationDialog::promptForResamplerLocation); connect(&tableView, &QWidget::customContextMenuRequested, this, [this](const QPoint& pos){ contextMenu->popup(QPoint{this->mapToGlobal(pos).x(), this->mapToGlobal(pos).y() + contextMenu->sizeHint().height()}); contextToolBar->hide(); }); connect(&tableView, &QTableView::clicked, this, [this](const QModelIndex& modelIndex) { QPoint p{tableView.columnViewportPosition(modelIndex.column()) , tableView.rowViewportPosition(std::min(tableView.model()->rowCount() - 2, modelIndex.row()))}; contextToolBar->move(p + QPoint{0, (int)tableView.geometry().top() + contextToolBar->sizeHint().height() * 3} ); contextToolBar->show(); contextToolBar->raise(); }); connect(stdButtons, &QDialogButtonBox::accepted, this, &QDialog::accept); connect(stdButtons, &QDialogButtonBox::rejected, this, &QDialog::reject); } void ConverterConfigurationDialog::initMenu() { contextMenu->addAction("New", [this] { onNewRequested(tableView.currentIndex()); }, QKeySequence::New); contextMenu->addAction("Edit ...", [this] { onEditRequested(tableView.currentIndex()); }); contextMenu->addAction("Clone", [this] { onCloneRequested(tableView.currentIndex()); }, QKeySequence::Copy); contextMenu->addAction("Delete", [this] { onDeleteRequested(tableView.currentIndex()); }, {QKeySequence::Delete}); contextMenu->addAction("Move Up", [this] { onMoveUpRequested(tableView.currentIndex()); }); contextMenu->addAction("Move Down", [this] { onMoveDownRequested(tableView.currentIndex()); }); } void ConverterConfigurationDialog::initToolBar() { contextToolBar->addAction("New", [this] { onNewRequested(tableView.currentIndex()); contextToolBar->hide(); }); contextToolBar->addAction("Edit ...", [this] { onEditRequested(tableView.currentIndex()); contextToolBar->hide(); }); contextToolBar->addAction("Clone", [this] { onCloneRequested(tableView.currentIndex()); contextToolBar->hide(); }); contextToolBar->addAction("Delete", [this] { onDeleteRequested(tableView.currentIndex()); contextToolBar->hide(); }); contextToolBar->addAction("Move Up", [this] { onMoveUpRequested(tableView.currentIndex()); //contextToolBar->hide(); }); qDebug() << contextToolBar->addAction("Move Down", [this] { onMoveDownRequested(tableView.currentIndex()); //contextToolBar->hide(); }); contextToolBar->setContentsMargins(0, 0, 0, 0); contextToolBar->setMinimumWidth(tableView.width() / 2); contextToolBar->setMaximumWidth(tableView.width()); } void ConverterConfigurationDialog::showEvent(QShowEvent* event) { if(mainConverterPath.isEmpty() || !QFile::exists(mainConverterPath)) { promptForResamplerLocation(); } mainConverterLocationLabel->setText(QString{"Location of Main Converter (%1):"}.arg(expectedMainConverter)); mainConverterLocationEdit->setText(mainConverterPath); QDialog::showEvent(event); } void ConverterConfigurationDialog::resizeEvent(QResizeEvent *event) { int tw = event->size().width(); static const QVector<double> columnWidths { 0, /* "Priority" */ 10, /* "Enabled" */ 20, /* "Name" */ 0 , /* "Comment" */ 12, /* "Input File Extension" */ 12, /* "Output File Extension" */ 0 , /* "Executable" */ 20, /* "Executable Path" */ 20, /* "Command Line" */ 0 , /* "Download Locations" */ 0 /* "Operating Systems" */ }; for(int col = 0; col < convertersModel.columnCount({}) - 1; col++) { tableView.horizontalHeader()->resizeSection(col, tw * columnWidths.at(col)/100.0); } tableView.horizontalHeader()->setHidden(false); QDialog::resizeEvent(event); } QVector<ConverterDefinition> ConverterConfigurationDialog::getConverterDefinitions() const { return convertersModel.getConverterDefinitions(); } void ConverterConfigurationDialog::setConverterDefinitions(const QVector<ConverterDefinition> &value) { convertersModel.setConverterDefinitions(value); } void ConverterConfigurationDialog::promptForResamplerLocation() { QString s("Please locate the file: "); s.append(expectedMainConverter); #if defined (Q_OS_WIN) QString filter = "*.exe"; #else QString filter = ""; #endif QString cp = QFileDialog::getOpenFileName(this, s, mainConverterPath, filter); if(!cp.isNull()) { mainConverterPath = cp; if(mainConverterPath.lastIndexOf(expectedMainConverter, -1, Qt::CaseInsensitive) == -1) { // safeguard against wrong executable being configured mainConverterPath.clear(); QMessageBox::warning(this, tr("Converter Location"), tr("That is not the right program!\n"), QMessageBox::Ok); } } } QString ConverterConfigurationDialog::getMainConverterPath() const { return mainConverterPath; } void ConverterConfigurationDialog::setMainConverterPath(const QString &value) { mainConverterPath = value; } QString ConverterConfigurationDialog::getExpectedMainConverter() const { return expectedMainConverter; } void ConverterConfigurationDialog::setExpectedMainConverter(const QString &value) { expectedMainConverter = value; // set tooltips mainConverterLocationLabel->setToolTip(QString{"Please enter the location of %1 in the box below.\n" "(%1 is the command-line audio converter that Ferocious was designed to work with.)" }.arg(expectedMainConverter)); mainConverterLocationEdit->setToolTip(QString{"Location of %1\n" "Note: you can also use drag-and-drop, or the 'Browse' button"}.arg(expectedMainConverter)); browseButton->setToolTip(QString{"Browse to location of %1"}.arg(expectedMainConverter)); additionalConvertersLabel->setToolTip("Use the table below to cofigure additional converters for specialized file formats."); } void ConverterConfigurationDialog::onNewRequested(const QModelIndex& modelIndex) { int row = modelIndex.row(); if(row < 0 ) return; QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions(); if(row < converterDefinitions.count()) { converterDefinitions.insert(row, {}); convertersModel.setConverterDefinitions(converterDefinitions); } } void ConverterConfigurationDialog::onEditRequested(const QModelIndex& modelIndex) { QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions(); if (converterDefinitions.isEmpty()) return; int row = modelIndex.row(); if (row < 0) return; auto dlg = new ConverterConfigurationEditDialog(this); if(row < converterDefinitions.count()) { dlg->setConverterDefinition(converterDefinitions.at(row)); int result = dlg->exec(); if(result == QDialog::Accepted) { converterDefinitions[row] = dlg->getConverterDefinition(); convertersModel.setConverterDefinitions(converterDefinitions); } } } void ConverterConfigurationDialog::onDeleteRequested(const QModelIndex& modelIndex) { int row = modelIndex.row(); if(row < 0 ) return; QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions(); if(row < converterDefinitions.count()) { converterDefinitions.removeAt(row); convertersModel.setConverterDefinitions(converterDefinitions); } } void ConverterConfigurationDialog::onCloneRequested(const QModelIndex& modelIndex) { int row = modelIndex.row(); if(row < 0 ) return; QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions(); if(row < converterDefinitions.count()) { converterDefinitions.insert(row, converterDefinitions.at(row)); convertersModel.setConverterDefinitions(converterDefinitions); } } void ConverterConfigurationDialog::onMoveUpRequested(const QModelIndex& modelIndex) { int row = modelIndex.row(); if(row < 1 ) { return; } QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions(); if(row < converterDefinitions.count()) { qSwap(converterDefinitions[row], converterDefinitions[row - 1]); convertersModel.setConverterDefinitions(converterDefinitions); tableView.selectRow(row - 1); } } void ConverterConfigurationDialog::onMoveDownRequested(const QModelIndex& modelIndex) { int row = modelIndex.row(); if(row < 0 ) { return; } QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions(); if(row < converterDefinitions.count() - 1) { qSwap(converterDefinitions[row], converterDefinitions[row + 1]); convertersModel.setConverterDefinitions(converterDefinitions); tableView.selectRow(row + 1); } } <|endoftext|>
<commit_before><commit_msg>fix filament_test on aarch64 mac<commit_after><|endoftext|>
<commit_before>/* Copyright 2013-present Barefoot Networks, 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. */ /* * Antonin Bas ([email protected]) * */ #include <grpc++/grpc++.h> #include <p4/bm/dataplane_interface.grpc.pb.h> #include <p4/v1/p4runtime.grpc.pb.h> #include <google/protobuf/util/message_differencer.h> #include <gtest/gtest.h> #include <memory> #include <string> #include "base_test.h" namespace p4v1 = ::p4::v1; namespace sswitch_grpc { namespace testing { namespace { using google::protobuf::util::MessageDifferencer; constexpr char ternary_json[] = TESTDATADIR "/ternary.json"; constexpr char ternary_proto[] = TESTDATADIR "/ternary.proto.txt"; class SimpleSwitchGrpcTest_Ternary : public SimpleSwitchGrpcBaseTest { protected: SimpleSwitchGrpcTest_Ternary() : SimpleSwitchGrpcBaseTest(ternary_proto), dataplane_channel(grpc::CreateChannel( dp_grpc_server_addr, grpc::InsecureChannelCredentials())), dataplane_stub(p4::bm::DataplaneInterface::NewStub( dataplane_channel)) { } void SetUp() override { SimpleSwitchGrpcBaseTest::SetUp(); update_json(ternary_json); t_id = get_table_id(p4info, "ingress.ter"); mf_id = get_mf_id(p4info, "ingress.ter", "h.hdr.f1"); a_nop_id = get_action_id(p4info, "NoAction"); a_s1_id = get_action_id(p4info, "ingress.send_1"); a_s2_id = get_action_id(p4info, "ingress.send_2"); } p4v1::Entity make_entry(const std::string &v, const std::string &mask, int32_t priority, int a_id) const { p4v1::Entity entity; auto table_entry = entity.mutable_table_entry(); table_entry->set_table_id(t_id); auto match = table_entry->add_match(); match->set_field_id(mf_id); auto ternary = match->mutable_ternary(); ternary->set_value(v); ternary->set_mask(mask); table_entry->set_priority(priority); auto table_action = table_entry->mutable_action(); auto action = table_action->mutable_action(); action->set_action_id(a_id); return entity; } grpc::Status add_entry(const p4v1::Entity &entry) const { p4v1::WriteRequest request; request.set_device_id(device_id); auto update = request.add_updates(); update->set_type(p4v1::Update_Type_INSERT); update->mutable_entity()->CopyFrom(entry); ClientContext context; p4v1::WriteResponse rep; return Write(&context, request, &rep); } grpc::Status read_entry(const p4v1::Entity &entry, p4v1::ReadResponse *rep) const { p4v1::ReadRequest request; request.set_device_id(device_id); auto *entity = request.add_entities(); entity->CopyFrom(entry); ClientContext context; std::unique_ptr<grpc::ClientReader<p4v1::ReadResponse> > reader( p4runtime_stub->Read(&context, request)); reader->Read(rep); return reader->Finish(); } grpc::Status send_and_receive(const std::string &pkt, int ig_port, p4::bm::PacketStreamResponse *rcv_pkt) { static uint64_t id = 1; p4::bm::PacketStreamRequest request; request.set_id(id++); request.set_device_id(device_id); request.set_port(ig_port); request.set_packet(pkt); ClientContext context; auto stream = dataplane_stub->PacketStream(&context); stream->Write(request); stream->Read(rcv_pkt); stream->WritesDone(); return stream->Finish(); } std::shared_ptr<grpc::Channel> dataplane_channel{nullptr}; std::unique_ptr<p4::bm::DataplaneInterface::Stub> dataplane_stub{nullptr}; int t_id; int mf_id; int a_nop_id; int a_s1_id; int a_s2_id; }; TEST_F(SimpleSwitchGrpcTest_Ternary, ReadEntry) { int priority = 128; auto entity = make_entry("\xaa\xbb", "\xff\xff", priority, a_s1_id); { auto status = add_entry(entity); EXPECT_TRUE(status.ok()); } { p4v1::ReadResponse rep; auto status = read_entry(entity, &rep); EXPECT_TRUE(status.ok()); ASSERT_EQ(1u, rep.entities().size()); EXPECT_TRUE(MessageDifferencer::Equals(entity, rep.entities().Get(0))); } } TEST_F(SimpleSwitchGrpcTest_Ternary, PriorityOrder) { int priority_lo = 128, priority_hi = 333; int ig_port = 3; std::string pkt("\xaa\xbb"); p4::bm::PacketStreamResponse rcv_pkt; auto entity_lo = make_entry("\xaa\xbb", "\xff\xff", priority_lo, a_s1_id); { auto status = add_entry(entity_lo); EXPECT_TRUE(status.ok()); } { auto status = send_and_receive(pkt, ig_port, &rcv_pkt); EXPECT_TRUE(status.ok()); EXPECT_EQ(1, rcv_pkt.port()); } auto entity_hi = make_entry("\xaa\x0b", "\xff\x0f", priority_hi, a_s2_id); { auto status = add_entry(entity_hi); EXPECT_TRUE(status.ok()); } { auto status = send_and_receive(pkt, ig_port, &rcv_pkt); EXPECT_TRUE(status.ok()); EXPECT_EQ(2, rcv_pkt.port()); } } // zero is the lowest priority in P4Runtime (which corresponds to a high // priority value in bmv2); this test was added for the following issue: // https://github.com/p4lang/behavioral-model/issues/618 TEST_F(SimpleSwitchGrpcTest_Ternary, PriorityZero) { int priority = 0; int ig_port = 3; std::string pkt("\xaa\xbb"); p4::bm::PacketStreamResponse rcv_pkt; auto entity = make_entry("\xaa\xbb", "\xff\xff", priority, a_s1_id); { auto status = add_entry(entity); EXPECT_TRUE(status.ok()); } { auto status = send_and_receive(pkt, ig_port, &rcv_pkt); EXPECT_TRUE(status.ok()); EXPECT_EQ(1, rcv_pkt.port()); } } } // namespace } // namespace testing } // namespace sswitch_grpc <commit_msg>Change simple_switch_grpc priority zero test<commit_after>/* Copyright 2013-present Barefoot Networks, 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. */ /* * Antonin Bas ([email protected]) * */ #include <grpc++/grpc++.h> #include <p4/bm/dataplane_interface.grpc.pb.h> #include <p4/v1/p4runtime.grpc.pb.h> #include <google/protobuf/util/message_differencer.h> #include <gtest/gtest.h> #include <memory> #include <string> #include "base_test.h" namespace p4v1 = ::p4::v1; namespace sswitch_grpc { namespace testing { namespace { using google::protobuf::util::MessageDifferencer; constexpr char ternary_json[] = TESTDATADIR "/ternary.json"; constexpr char ternary_proto[] = TESTDATADIR "/ternary.proto.txt"; class SimpleSwitchGrpcTest_Ternary : public SimpleSwitchGrpcBaseTest { protected: SimpleSwitchGrpcTest_Ternary() : SimpleSwitchGrpcBaseTest(ternary_proto), dataplane_channel(grpc::CreateChannel( dp_grpc_server_addr, grpc::InsecureChannelCredentials())), dataplane_stub(p4::bm::DataplaneInterface::NewStub( dataplane_channel)) { } void SetUp() override { SimpleSwitchGrpcBaseTest::SetUp(); update_json(ternary_json); t_id = get_table_id(p4info, "ingress.ter"); mf_id = get_mf_id(p4info, "ingress.ter", "h.hdr.f1"); a_nop_id = get_action_id(p4info, "NoAction"); a_s1_id = get_action_id(p4info, "ingress.send_1"); a_s2_id = get_action_id(p4info, "ingress.send_2"); } p4v1::Entity make_entry(const std::string &v, const std::string &mask, int32_t priority, int a_id) const { p4v1::Entity entity; auto table_entry = entity.mutable_table_entry(); table_entry->set_table_id(t_id); auto match = table_entry->add_match(); match->set_field_id(mf_id); auto ternary = match->mutable_ternary(); ternary->set_value(v); ternary->set_mask(mask); table_entry->set_priority(priority); auto table_action = table_entry->mutable_action(); auto action = table_action->mutable_action(); action->set_action_id(a_id); return entity; } grpc::Status add_entry(const p4v1::Entity &entry) const { p4v1::WriteRequest request; request.set_device_id(device_id); auto update = request.add_updates(); update->set_type(p4v1::Update_Type_INSERT); update->mutable_entity()->CopyFrom(entry); ClientContext context; p4v1::WriteResponse rep; return Write(&context, request, &rep); } grpc::Status read_entry(const p4v1::Entity &entry, p4v1::ReadResponse *rep) const { p4v1::ReadRequest request; request.set_device_id(device_id); auto *entity = request.add_entities(); entity->CopyFrom(entry); ClientContext context; std::unique_ptr<grpc::ClientReader<p4v1::ReadResponse> > reader( p4runtime_stub->Read(&context, request)); reader->Read(rep); return reader->Finish(); } grpc::Status send_and_receive(const std::string &pkt, int ig_port, p4::bm::PacketStreamResponse *rcv_pkt) { static uint64_t id = 1; p4::bm::PacketStreamRequest request; request.set_id(id++); request.set_device_id(device_id); request.set_port(ig_port); request.set_packet(pkt); ClientContext context; auto stream = dataplane_stub->PacketStream(&context); stream->Write(request); stream->Read(rcv_pkt); stream->WritesDone(); return stream->Finish(); } std::shared_ptr<grpc::Channel> dataplane_channel{nullptr}; std::unique_ptr<p4::bm::DataplaneInterface::Stub> dataplane_stub{nullptr}; int t_id; int mf_id; int a_nop_id; int a_s1_id; int a_s2_id; }; TEST_F(SimpleSwitchGrpcTest_Ternary, ReadEntry) { int priority = 128; auto entity = make_entry("\xaa\xbb", "\xff\xff", priority, a_s1_id); { auto status = add_entry(entity); EXPECT_TRUE(status.ok()); } { p4v1::ReadResponse rep; auto status = read_entry(entity, &rep); EXPECT_TRUE(status.ok()); ASSERT_EQ(1u, rep.entities().size()); EXPECT_TRUE(MessageDifferencer::Equals(entity, rep.entities().Get(0))); } } TEST_F(SimpleSwitchGrpcTest_Ternary, PriorityOrder) { int priority_lo = 128, priority_hi = 333; int ig_port = 3; std::string pkt("\xaa\xbb"); p4::bm::PacketStreamResponse rcv_pkt; auto entity_lo = make_entry("\xaa\xbb", "\xff\xff", priority_lo, a_s1_id); { auto status = add_entry(entity_lo); EXPECT_TRUE(status.ok()); } { auto status = send_and_receive(pkt, ig_port, &rcv_pkt); EXPECT_TRUE(status.ok()); EXPECT_EQ(1, rcv_pkt.port()); } auto entity_hi = make_entry("\xaa\x0b", "\xff\x0f", priority_hi, a_s2_id); { auto status = add_entry(entity_hi); EXPECT_TRUE(status.ok()); } { auto status = send_and_receive(pkt, ig_port, &rcv_pkt); EXPECT_TRUE(status.ok()); EXPECT_EQ(2, rcv_pkt.port()); } } // zero is not a valid priority value in P4Runtime TEST_F(SimpleSwitchGrpcTest_Ternary, PriorityZero) { int priority = 0; std::string pkt("\xaa\xbb"); p4::bm::PacketStreamResponse rcv_pkt; auto entity = make_entry("\xaa\xbb", "\xff\xff", priority, a_s1_id); auto status = add_entry(entity); EXPECT_FALSE(status.ok()); } } // namespace } // namespace testing } // namespace sswitch_grpc <|endoftext|>
<commit_before>/* * Copyright 2016 The Cartographer 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 "cartographer_ros/node.h" #include "cartographer_ros/node_options.h" #include "cartographer_ros/ros_log_sink.h" #include "gflags/gflags.h" #include "tf2_ros/transform_listener.h" DEFINE_string(configuration_directory, "", "First directory in which configuration files are searched, " "second is always the Cartographer installation to allow " "including files from there."); DEFINE_string(configuration_basename, "", "Basename, i.e. not containing any directory prefix, of the " "configuration file."); DEFINE_string(map_filename, "", "If non-empty, filename of a map to load."); DEFINE_bool( start_trajectory_with_default_topics, true, "Enable to immediately start the first trajectory with default topics."); namespace cartographer_ros { namespace { void Run() { constexpr double kTfBufferCacheTimeInSeconds = 1e6; tf2_ros::Buffer tf_buffer{::ros::Duration(kTfBufferCacheTimeInSeconds)}; tf2_ros::TransformListener tf(tf_buffer); NodeOptions node_options; TrajectoryOptions trajectory_options; std::tie(node_options, trajectory_options) = LoadOptions(FLAGS_configuration_directory, FLAGS_configuration_basename); Node node(node_options, &tf_buffer); if (!FLAGS_map_filename.empty()) { node.LoadMap(FLAGS_map_filename); } if (FLAGS_start_trajectory_with_default_topics) { node.StartTrajectoryWithDefaultTopics(trajectory_options); } ::ros::spin(); node.FinishAllTrajectories(); node.RunFinalOptimization(); } } // namespace } // namespace cartographer_ros int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); google::ParseCommandLineFlags(&argc, &argv, true); CHECK(!FLAGS_configuration_directory.empty()) << "-configuration_directory is missing."; CHECK(!FLAGS_configuration_basename.empty()) << "-configuration_basename is missing."; ::ros::init(argc, argv, "cartographer_node"); ::ros::start(); cartographer_ros::ScopedRosLogSink ros_log_sink; cartographer_ros::Run(); ::ros::shutdown(); } <commit_msg>Serialize state before shutdown (#502)<commit_after>/* * Copyright 2016 The Cartographer 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 "cartographer_ros/node.h" #include "cartographer_ros/node_options.h" #include "cartographer_ros/ros_log_sink.h" #include "gflags/gflags.h" #include "tf2_ros/transform_listener.h" DEFINE_string(configuration_directory, "", "First directory in which configuration files are searched, " "second is always the Cartographer installation to allow " "including files from there."); DEFINE_string(configuration_basename, "", "Basename, i.e. not containing any directory prefix, of the " "configuration file."); DEFINE_string(map_filename, "", "If non-empty, filename of a map to load."); DEFINE_bool( start_trajectory_with_default_topics, true, "Enable to immediately start the first trajectory with default topics."); DEFINE_string(save_map_filename, "", "If non-empty, serialize state and write it to disk before shutting down."); namespace cartographer_ros { namespace { void Run() { constexpr double kTfBufferCacheTimeInSeconds = 1e6; tf2_ros::Buffer tf_buffer{::ros::Duration(kTfBufferCacheTimeInSeconds)}; tf2_ros::TransformListener tf(tf_buffer); NodeOptions node_options; TrajectoryOptions trajectory_options; std::tie(node_options, trajectory_options) = LoadOptions(FLAGS_configuration_directory, FLAGS_configuration_basename); Node node(node_options, &tf_buffer); if (!FLAGS_map_filename.empty()) { node.LoadMap(FLAGS_map_filename); } if (FLAGS_start_trajectory_with_default_topics) { node.StartTrajectoryWithDefaultTopics(trajectory_options); } ::ros::spin(); node.FinishAllTrajectories(); node.RunFinalOptimization(); if (!FLAGS_save_map_filename.empty()) { node.SerializeState(FLAGS_save_map_filename); } } } // namespace } // namespace cartographer_ros int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); google::ParseCommandLineFlags(&argc, &argv, true); CHECK(!FLAGS_configuration_directory.empty()) << "-configuration_directory is missing."; CHECK(!FLAGS_configuration_basename.empty()) << "-configuration_basename is missing."; ::ros::init(argc, argv, "cartographer_node"); ::ros::start(); cartographer_ros::ScopedRosLogSink ros_log_sink; cartographer_ros::Run(); ::ros::shutdown(); } <|endoftext|>
<commit_before>#include <windows.h> // API #include <assert.h> // : HINSTANCE hInst; // LPCTSTR szWindowClass = "Kostyuk"; LPCTSTR szTitle = "lab 9. Assembler usage"; const int N_OF_BITS = 32; // CHAR char_buf[ N_OF_BITS + 1 ]; // - int arr1[ 3 ][ 3 ] = { { 10, 12, 33 },{ 24, 52, 46 },{ 17, 28, 95 } }; int arr2[ 3 ][ 3 ] = { { 3, 2, 1 },{ 6, 5, 4 },{ 9, 8, 7 } }; int arr3[ 3 ][ 3 ] = { { 0, 0, 0 },{ 0, 0, 0 },{ 0, 0, 0 } }; int arr4[ 3 ][ 3 ] = { { 0, 0, 0 },{ 0, 0, 0 },{ 0, 0, 0 } }; int arr5[ 3 ][ 3 ] = { { 0, 0, 0 },{ 0, 0, 0 },{ 0, 0, 0 } }; void MTransponse( int nrows, int ncols ) { __asm { mov ebx, 0; i = 0 per_row: cmp ebx, nrows; if i == nrows je do_exit mov ecx, 0; j = 0 per_col: cmp ecx, ncols; if j == ncols je per_row_end; mov eax, ebx; eax = i mul ncols; eax:edx = ebx * ncols = i * ncols add eax, ecx; eax = i * ncols + j mov esi, eax; esi = i * ncols + j mov eax, arr1[ esi * 4 ]; temp = src[ i * ncols + j ] push eax; copy eax (temp) to stack mov eax, ecx; eax = j mul nrows; eax:ecx = ecx * nrows = j * nrows add eax, ebx; eax = j * nrows + i mov edi, eax; edi = j * nrows + i pop eax; restore eax (temp) from stack mov arr5[ edi * 4 ], eax; dest[ j * nrows + i ] = temp inc ecx; j++ jmp per_col per_row_end: inc ebx; i++ jmp per_row do_exit: ; do nothing } } void MElementWiseMul( int nrows, int ncols ) { int n_of_elements = nrows * ncols; __asm { mov ecx, n_of_elements; comment r3 : mov eax, arr1[ ecx * 4 - 4 ]; arg1 mov edx, arr2[ ecx * 4 - 4 ]; arg2 mul edx; edx aex mov arr3[ ecx * 4 - 4 ], eax; loop r3 } } void MSum( int nrows, int ncols ) { int n_of_elements = nrows * ncols; __asm { mov ecx, n_of_elements; comment r1 : mov eax, arr1[ ecx * 4 - 4 ]; arg1 mov edx, arr2[ ecx * 4 - 4 ]; arg2 add eax, edx; 1 2 mov arr4[ ecx * 4 - 4 ], eax; loop r1 } } void PrintArray3x3( HDC _hdc, const RECT & _client, int _array[ 3 ][ 3 ], int _padding_x, int _padding_y, char * _buf ) { for ( int row = 0; row < 3; ++row ) { TextOut( _hdc, _padding_x, 20 * row + _padding_y + 20, _buf, wsprintf( _buf, "%d %d %d", _array[ row ][ 0 ], _array[ row ][ 1 ], _array[ row ][ 2 ] ) ); } } void PrintArrays( HDC _hdc, const RECT & _client ) { // char buff[ 60 ]; int padding_y = 10; int padding_x = 10; TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "Source 1:" ) ); PrintArray3x3( _hdc, _client, arr1, padding_x, padding_y, buff ); padding_x += 140; TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "Source 2:" ) ); PrintArray3x3( _hdc, _client, arr2, padding_x, padding_y, buff ); padding_x += 140; TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "Mul result:" ) ); PrintArray3x3( _hdc, _client, arr3, padding_x, padding_y, buff ); padding_x = 10; padding_y += 110; TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "Sum result:" ) ); PrintArray3x3( _hdc, _client, arr4, padding_x, padding_y, buff ); padding_x += 140; TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "Src 1 tranposed:" ) ); PrintArray3x3( _hdc, _client, arr5, padding_x, padding_y, buff ); } // ATOM MyRegisterClass( HINSTANCE hInstance ); BOOL InitInstance( HINSTANCE, int ); LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM ); // int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { MSG msg; // MyRegisterClass( hInstance ); // if ( !InitInstance( hInstance, nCmdShow ) ) { return FALSE; } // while ( GetMessage( &msg, NULL, 0, 0 ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } return msg.wParam; } // FUNCTION: MyRegisterClass() // ATOM MyRegisterClass( HINSTANCE hInstance ) { WNDCLASSEX wcex; wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; // wcex.lpfnWndProc = (WNDPROC)WndProc; // wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; // wcex.hIcon = LoadIcon( NULL, IDI_APPLICATION ); // wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); // wcex.hbrBackground = GetSysColorBrush( COLOR_WINDOW ); // wcex.lpszMenuName = NULL; // wcex.lpszClassName = szWindowClass; // wcex.hIconSm = NULL; return RegisterClassEx( &wcex ); // } // FUNCTION: InitInstance(HANDLE, int) // hInst BOOL InitInstance( HINSTANCE hInstance, int nCmdShow ) { HWND hWnd; hInst = hInstance; // hInst hWnd = CreateWindow( szWindowClass, // szTitle, // WS_OVERLAPPEDWINDOW, // CW_USEDEFAULT, // CW_USEDEFAULT, // Y CW_USEDEFAULT, // CW_USEDEFAULT, // Y NULL, // NULL, // hInstance, // NULL ); // . if ( !hWnd ) // , FALSE { return FALSE; } ShowWindow( hWnd, nCmdShow ); // UpdateWindow( hWnd ); // return TRUE; // } // FUNCTION: WndProc(HWND, unsigned, WORD, LONG) // . , LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ) { PAINTSTRUCT ps; HDC hdc; RECT rt; char sprintf_buf[ 60 ]; switch ( message ) { case WM_CREATE: // //do_stuff(); MElementWiseMul( 3, 3 ); MSum( 3, 3 ); MTransponse( 3, 3 ); break; case WM_PAINT: // hdc = BeginPaint( hWnd, &ps ); // GetClientRect( hWnd, &rt ); // //TextOut( hdc, 10, 10, sprintf_buf, wsprintf( sprintf_buf, "%d", subs(11) )); PrintArrays( hdc, rt ); EndPaint( hWnd, &ps ); // break; case WM_DESTROY: // PostQuitMessage( 0 ); break; default: // , return DefWindowProc( hWnd, message, wParam, lParam ); } return 0; }<commit_msg>Base structure for matrix multiplication function<commit_after>#include <windows.h> // API #include <assert.h> // : HINSTANCE hInst; // LPCTSTR szWindowClass = "Kostyuk"; LPCTSTR szTitle = "lab 9. Assembler usage"; const int N_OF_BITS = 32; // CHAR char_buf[ N_OF_BITS + 1 ]; // - int arr1[ 3 ][ 3 ] = { { 10, 12, 33 },{ 24, 52, 46 },{ 17, 28, 95 } }; int arr2[ 3 ][ 3 ] = { { 3, 2, 1 },{ 6, 5, 4 },{ 9, 8, 7 } }; int arr3[ 3 ][ 3 ] = { { 0, 0, 0 },{ 0, 0, 0 },{ 0, 0, 0 } }; int arr4[ 3 ][ 3 ] = { { 0, 0, 0 },{ 0, 0, 0 },{ 0, 0, 0 } }; int arr5[ 3 ][ 3 ] = { { 0, 0, 0 },{ 0, 0, 0 },{ 0, 0, 0 } }; int arr6[ 3 ][ 3 ] = { { 0, 0, 0 },{ 0, 0, 0 },{ 0, 0, 0 } }; void MTransponse( int nrows, int ncols ) { __asm { mov ebx, 0; i = 0 per_row: cmp ebx, nrows; if i == nrows je do_exit mov ecx, 0; j = 0 per_col: cmp ecx, ncols; if j == ncols je per_row_end; mov eax, ebx; eax = i mul ncols; eax:edx = ebx * ncols = i * ncols add eax, ecx; eax = i * ncols + j mov esi, eax; esi = i * ncols + j mov eax, arr1[ esi * 4 ]; temp = src[ i * ncols + j ] push eax; copy eax (temp) to stack mov eax, ecx; eax = j mul nrows; eax:ecx = ecx * nrows = j * nrows add eax, ebx; eax = j * nrows + i mov edi, eax; edi = j * nrows + i pop eax; restore eax (temp) from stack mov arr5[ edi * 4 ], eax; dest[ j * nrows + i ] = temp inc ecx; j++ jmp per_col per_row_end: inc ebx; i++ jmp per_row do_exit: ; do nothing } } void MElementWiseMul( int nrows, int ncols ) { int n_of_elements = nrows * ncols; __asm { mov ecx, n_of_elements; comment r3 : mov eax, arr1[ ecx * 4 - 4 ]; arg1 mov edx, arr2[ ecx * 4 - 4 ]; arg2 mul edx; edx aex mov arr3[ ecx * 4 - 4 ], eax; loop r3 } } void MSum( int nrows, int ncols ) { int n_of_elements = nrows * ncols; __asm { mov ecx, n_of_elements; comment r1 : mov eax, arr1[ ecx * 4 - 4 ]; arg1 mov edx, arr2[ ecx * 4 - 4 ]; arg2 add eax, edx; 1 2 mov arr4[ ecx * 4 - 4 ], eax; loop r1 } } void MMul( int n, int m, int p ) { int i, j, k; __asm { jmp start; start: mov i, 0; i = 0 outer_loop: mov eax, i; eax = i cmp eax, n; if i == n je do_exit; then exit mov j, 0; else j = 0 and jmp middle_loop middle_loop: mov eax, j; eax = j cmp eax, m; if j == m je outer_loop_end; then exit middle_loop mov k, 0; else k = 0 and jmp inner_loop inner_loop: mov eax, k; eax = k cmp eax, p; if k == p je middle_loop_end; then exit inner loop inc k; k++ jmp inner_loop; start new inner_loop iteration middle_loop_end: inc j; j++ jmp middle_loop; start new middle_loop iteration outer_loop_end: inc i; i++ jmp outer_loop; start new outer_loop iteration do_exit: } } void PrintArray3x3( HDC _hdc, const RECT & _client, int _array[ 3 ][ 3 ], int _padding_x, int _padding_y, char * _buf ) { for ( int row = 0; row < 3; ++row ) { TextOut( _hdc, _padding_x, 20 * row + _padding_y + 20, _buf, wsprintf( _buf, "%d %d %d", _array[ row ][ 0 ], _array[ row ][ 1 ], _array[ row ][ 2 ] ) ); } } void PrintArrays( HDC _hdc, const RECT & _client ) { // char buff[ 60 ]; int padding_y = 10; int padding_x = 10; TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "Source 1:" ) ); PrintArray3x3( _hdc, _client, arr1, padding_x, padding_y, buff ); padding_x += 140; TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "Source 2:" ) ); PrintArray3x3( _hdc, _client, arr2, padding_x, padding_y, buff ); padding_x += 140; TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "EW Mul result:" ) ); PrintArray3x3( _hdc, _client, arr3, padding_x, padding_y, buff ); padding_x = 10; padding_y += 110; TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "Sum result:" ) ); PrintArray3x3( _hdc, _client, arr4, padding_x, padding_y, buff ); padding_x += 140; TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "Src 1 tranposed:" ) ); PrintArray3x3( _hdc, _client, arr5, padding_x, padding_y, buff ); padding_x += 140; TextOut( _hdc, padding_x, padding_y, buff, wsprintf( buff, "Src1 x Src2 = " ) ); PrintArray3x3( _hdc, _client, arr6, padding_x, padding_y, buff ); } // ATOM MyRegisterClass( HINSTANCE hInstance ); BOOL InitInstance( HINSTANCE, int ); LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM ); // int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { MSG msg; // MyRegisterClass( hInstance ); // if ( !InitInstance( hInstance, nCmdShow ) ) { return FALSE; } // while ( GetMessage( &msg, NULL, 0, 0 ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } return msg.wParam; } // FUNCTION: MyRegisterClass() // ATOM MyRegisterClass( HINSTANCE hInstance ) { WNDCLASSEX wcex; wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; // wcex.lpfnWndProc = (WNDPROC)WndProc; // wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; // wcex.hIcon = LoadIcon( NULL, IDI_APPLICATION ); // wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); // wcex.hbrBackground = GetSysColorBrush( COLOR_WINDOW ); // wcex.lpszMenuName = NULL; // wcex.lpszClassName = szWindowClass; // wcex.hIconSm = NULL; return RegisterClassEx( &wcex ); // } // FUNCTION: InitInstance(HANDLE, int) // hInst BOOL InitInstance( HINSTANCE hInstance, int nCmdShow ) { HWND hWnd; hInst = hInstance; // hInst hWnd = CreateWindow( szWindowClass, // szTitle, // WS_OVERLAPPEDWINDOW, // CW_USEDEFAULT, // CW_USEDEFAULT, // Y CW_USEDEFAULT, // CW_USEDEFAULT, // Y NULL, // NULL, // hInstance, // NULL ); // . if ( !hWnd ) // , FALSE { return FALSE; } ShowWindow( hWnd, nCmdShow ); // UpdateWindow( hWnd ); // return TRUE; // } // FUNCTION: WndProc(HWND, unsigned, WORD, LONG) // . , LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ) { PAINTSTRUCT ps; HDC hdc; RECT rt; char sprintf_buf[ 60 ]; switch ( message ) { case WM_CREATE: // //do_stuff(); MElementWiseMul( 3, 3 ); MSum( 3, 3 ); MTransponse( 3, 3 ); MMul( 3, 3, 3 ); break; case WM_PAINT: // hdc = BeginPaint( hWnd, &ps ); // GetClientRect( hWnd, &rt ); // //TextOut( hdc, 10, 10, sprintf_buf, wsprintf( sprintf_buf, "%d", subs(11) )); PrintArrays( hdc, rt ); EndPaint( hWnd, &ps ); // break; case WM_DESTROY: // PostQuitMessage( 0 ); break; default: // , return DefWindowProc( hWnd, message, wParam, lParam ); } return 0; }<|endoftext|>
<commit_before>/* * * 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 "./pn_test_proactor.hpp" #include <proton/connection.h> #include <proton/condition.h> #include <proton/delivery.h> #include <proton/link.h> #include <proton/listener.h> #include <proton/netaddr.h> #include <proton/proactor.h> #include <proton/session.h> #include <proton/sasl.h> #include <proton/ssl.h> #include <proton/transport.h> #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct app_data_t { const char *amqp_address; const char *container_id; pn_ssl_domain_t *server_ssl_domain; bool connection_succeeded; bool transport_error; } app_data_t; /* Note must be run in the current directory to find certificate files */ #define SSL_FILE(NAME) "ssl-certs/" NAME #define SSL_PW "tclientpw" /* Windows vs. OpenSSL certificates */ #if defined(_WIN32) # define CERTIFICATE(NAME) SSL_FILE(NAME "-certificate.p12") # define SET_CREDENTIALS(DOMAIN, NAME) \ pn_ssl_domain_set_credentials(DOMAIN, SSL_FILE(NAME "-full.p12"), "", SSL_PW) #else # define CERTIFICATE(NAME) SSL_FILE(NAME "-certificate.pem") # define SET_CREDENTIALS(DOMAIN, NAME) \ pn_ssl_domain_set_credentials(DOMAIN, CERTIFICATE(NAME), SSL_FILE(NAME "-private-key.pem"), SSL_PW) #endif /* Returns true to continue, false if finished */ static bool server_handler(app_data_t* app, pn_event_t* event) { pn_listener_t *l = pn_event_listener(event); switch (pn_event_type(event)) { // Server side case PN_LISTENER_ACCEPT: { /* Configure a transport to allow SSL and SASL connections. See ssl_domain setup in main() */ pn_transport_t *t = pn_transport(); pn_transport_set_server(t); /* Must call before pn_sasl() */ pn_sasl_allowed_mechs(pn_sasl(t), "ANONYMOUS"); if (app->server_ssl_domain) { pn_ssl_init(pn_ssl(t), app->server_ssl_domain, NULL); } pn_listener_accept2(l, NULL, t); /* Accept only one connection */ pn_listener_close(l); break; } case PN_TRANSPORT_CLOSED: break; default: break; } return true; } static bool client_handler(app_data_t* app, pn_event_t* event) { switch (pn_event_type(event)) { // Client side case PN_CONNECTION_INIT: { pn_connection_t* c = pn_event_connection(event); pn_session_t* s = pn_session(pn_event_connection(event)); pn_connection_set_container(c, app->container_id); pn_connection_open(c); pn_session_open(s); { pn_link_t* l = pn_sender(s, "my_sender"); pn_terminus_set_address(pn_link_target(l), app->amqp_address); pn_link_open(l); break; } } case PN_CONNECTION_BOUND: { break; } case PN_CONNECTION_REMOTE_OPEN: app->connection_succeeded = true; pn_connection_close(pn_event_connection(event)); break; case PN_TRANSPORT_ERROR: app->transport_error = true; break; case PN_CONNECTION_REMOTE_CLOSE: pn_connection_close(pn_event_connection(event)); break; case PN_SESSION_REMOTE_CLOSE: pn_connection_close(pn_event_connection(event)); break; case PN_LINK_REMOTE_CLOSE: case PN_LINK_REMOTE_DETACH: pn_connection_close(pn_event_connection(event)); break; default: break; } return true; } typedef bool handler_t(app_data_t* app, pn_event_t* event); void run(pn_proactor_t *p, app_data_t *app, handler_t *shandler, handler_t *chandler) { /* Loop and handle server/client events */ do { pn_event_batch_t *events = pn_proactor_wait(p); pn_event_t *e; for (e = pn_event_batch_next(events); e; e = pn_event_batch_next(events)) { if (pn_event_type(e)==PN_PROACTOR_INACTIVE) { return; } if (pn_event_listener(e)) { if (!shandler(app, e)) { return; } } else { if (!chandler(app, e)) { return; } } } pn_proactor_done(p, events); } while(true); } TEST_CASE("ssl") { struct app_data_t app = {0}; app.container_id = "ssl-test"; app.amqp_address = "fubar"; pn_test::auto_free<pn_proactor_t, pn_proactor_free> proactor(pn_proactor()); /* Configure server for default SSL */ pn_test::auto_free<pn_ssl_domain_t, pn_ssl_domain_free> sd(pn_ssl_domain(PN_SSL_MODE_SERVER)); app.server_ssl_domain = sd; /* Configure a client for SSL */ pn_transport_t *t = pn_transport(); pn_test::auto_free<pn_ssl_domain_t, pn_ssl_domain_free> cd(pn_ssl_domain(PN_SSL_MODE_CLIENT)); SECTION("Default connections don't verify") { REQUIRE(pn_ssl_init(pn_ssl(t), NULL, NULL) == 0); pn_proactor_listen(proactor, pn_listener(), "", 16); pn_proactor_connect2(proactor, NULL, t, ""); run(proactor, &app, server_handler, client_handler); CHECK(app.connection_succeeded==false); CHECK(app.transport_error==true); } SECTION("Anonymous connections don't verify") { REQUIRE(pn_ssl_domain_set_trusted_ca_db(cd, CERTIFICATE("tclient")) == 0); REQUIRE(pn_ssl_domain_set_peer_authentication(cd, PN_SSL_VERIFY_PEER_NAME, NULL) == 0); REQUIRE(pn_ssl_init(pn_ssl(t), cd, NULL) == 0); pn_proactor_listen(proactor, pn_listener(), "", 16); pn_proactor_connect2(proactor, NULL, t, ""); run(proactor, &app, server_handler, client_handler); CHECK(app.connection_succeeded==false); CHECK(app.transport_error==true); } SECTION("Anonymous connections connect if anonymous allowed") { #ifndef _WIN32 REQUIRE(pn_ssl_domain_set_peer_authentication(cd, PN_SSL_ANONYMOUS_PEER, NULL) == 0); REQUIRE(pn_ssl_init(pn_ssl(t), cd, NULL) == 0); pn_proactor_listen(proactor, pn_listener(), "", 16); pn_proactor_connect2(proactor, NULL, t, ""); run(proactor, &app, server_handler, client_handler); CHECK(app.connection_succeeded==true); CHECK(app.transport_error==false); #else SUCCEED("Skipped: Windows schannel does not support anonymous connections"); #endif } } <commit_msg>PROTON-2021: [c] Round out the ssl certificate verification tests<commit_after>/* * * 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 "./pn_test_proactor.hpp" #include <proton/connection.h> #include <proton/condition.h> #include <proton/delivery.h> #include <proton/link.h> #include <proton/listener.h> #include <proton/netaddr.h> #include <proton/proactor.h> #include <proton/session.h> #include <proton/sasl.h> #include <proton/ssl.h> #include <proton/transport.h> #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct app_data_t { const char *amqp_address; const char *container_id; pn_ssl_domain_t *server_ssl_domain; bool connection_succeeded; bool transport_error; } app_data_t; /* Note must be run in the current directory to find certificate files */ #define SSL_FILE(NAME) "ssl-certs/" NAME #define SSL_PW(NAME) NAME "pw" /* Windows vs. OpenSSL certificates */ #if defined(_WIN32) # define CERTIFICATE(NAME) SSL_FILE(NAME "-certificate.p12") # define SET_CREDENTIALS(DOMAIN, NAME) \ pn_ssl_domain_set_credentials(DOMAIN, SSL_FILE(NAME "-full.p12"), "", SSL_PW(NAME)) #else # define CERTIFICATE(NAME) SSL_FILE(NAME "-certificate.pem") # define SET_CREDENTIALS(DOMAIN, NAME) \ pn_ssl_domain_set_credentials(DOMAIN, CERTIFICATE(NAME), SSL_FILE(NAME "-private-key.pem"), SSL_PW(NAME)) #endif /* Returns true to continue, false if finished */ static bool server_handler(app_data_t* app, pn_event_t* event) { pn_listener_t *l = pn_event_listener(event); switch (pn_event_type(event)) { // Server side case PN_LISTENER_ACCEPT: { /* Configure a transport to allow SSL and SASL connections. See ssl_domain setup in main() */ pn_transport_t *t = pn_transport(); pn_transport_set_server(t); /* Must call before pn_sasl() */ pn_sasl_allowed_mechs(pn_sasl(t), "ANONYMOUS"); pn_ssl_init(pn_ssl(t), app->server_ssl_domain, NULL); pn_listener_accept2(l, NULL, t); /* Accept only one connection */ pn_listener_close(l); break; } case PN_TRANSPORT_CLOSED: break; default: break; } return true; } static bool client_handler(app_data_t* app, pn_event_t* event) { switch (pn_event_type(event)) { // Client side case PN_CONNECTION_INIT: { pn_connection_t* c = pn_event_connection(event); pn_session_t* s = pn_session(pn_event_connection(event)); pn_connection_set_container(c, app->container_id); pn_connection_open(c); pn_session_open(s); { pn_link_t* l = pn_sender(s, "my_sender"); pn_terminus_set_address(pn_link_target(l), app->amqp_address); pn_link_open(l); break; } } case PN_CONNECTION_BOUND: { break; } case PN_CONNECTION_REMOTE_OPEN: app->connection_succeeded = true; pn_connection_close(pn_event_connection(event)); break; case PN_TRANSPORT_ERROR: app->transport_error = true; break; case PN_CONNECTION_REMOTE_CLOSE: pn_connection_close(pn_event_connection(event)); break; case PN_SESSION_REMOTE_CLOSE: pn_connection_close(pn_event_connection(event)); break; case PN_LINK_REMOTE_CLOSE: case PN_LINK_REMOTE_DETACH: pn_connection_close(pn_event_connection(event)); break; default: break; } return true; } typedef bool handler_t(app_data_t* app, pn_event_t* event); void run(pn_proactor_t *p, app_data_t *app, handler_t *shandler, handler_t *chandler) { /* Loop and handle server/client events */ do { pn_event_batch_t *events = pn_proactor_wait(p); pn_event_t *e; for (e = pn_event_batch_next(events); e; e = pn_event_batch_next(events)) { if (pn_event_type(e)==PN_PROACTOR_INACTIVE) { return; } if (pn_event_listener(e)) { if (!shandler(app, e)) { return; } } else { if (!chandler(app, e)) { return; } } } pn_proactor_done(p, events); } while(true); } TEST_CASE("ssl certificate verification tests") { struct app_data_t app = {0}; app.container_id = "ssl-test"; app.amqp_address = "fubar"; pn_test::auto_free<pn_proactor_t, pn_proactor_free> proactor(pn_proactor()); /* Configure server for default SSL */ pn_test::auto_free<pn_ssl_domain_t, pn_ssl_domain_free> sd(pn_ssl_domain(PN_SSL_MODE_SERVER)); app.server_ssl_domain = sd; /* Configure a client for SSL */ pn_transport_t *t = pn_transport(); pn_test::auto_free<pn_ssl_domain_t, pn_ssl_domain_free> cd(pn_ssl_domain(PN_SSL_MODE_CLIENT)); SECTION("Default connections don't verify to self signed server (even with correct name)") { REQUIRE(SET_CREDENTIALS(sd, "tserver") == 0); REQUIRE(pn_ssl_init(pn_ssl(t), NULL, NULL) == 0); REQUIRE(pn_ssl_set_peer_hostname(pn_ssl(t), "test_server") == 0); pn_proactor_listen(proactor, pn_listener(), "", 16); pn_proactor_connect2(proactor, NULL, t, ""); run(proactor, &app, server_handler, client_handler); CHECK(app.connection_succeeded==false); CHECK(app.transport_error==true); } SECTION("Connections noname verify to self signed cert if cert allowed (even with no name)") { REQUIRE(SET_CREDENTIALS(sd, "tserver") == 0); REQUIRE(pn_ssl_domain_set_trusted_ca_db(cd, CERTIFICATE("tserver")) == 0); REQUIRE(pn_ssl_domain_set_peer_authentication(cd, PN_SSL_VERIFY_PEER, NULL) == 0); REQUIRE(pn_ssl_init(pn_ssl(t), cd, NULL) == 0); pn_proactor_listen(proactor, pn_listener(), "", 16); pn_proactor_connect2(proactor, NULL, t, ""); run(proactor, &app, server_handler, client_handler); CHECK(app.connection_succeeded==true); CHECK(app.transport_error==false); } SECTION("Connections don't noname verify to self signed cert without cert allowed") { REQUIRE(SET_CREDENTIALS(sd, "tserver") == 0); REQUIRE(pn_ssl_domain_set_peer_authentication(cd, PN_SSL_VERIFY_PEER, NULL) == 0); REQUIRE(pn_ssl_init(pn_ssl(t), cd, NULL) == 0); pn_proactor_listen(proactor, pn_listener(), "", 16); pn_proactor_connect2(proactor, NULL, t, ""); run(proactor, &app, server_handler, client_handler); CHECK(app.connection_succeeded==false); CHECK(app.transport_error==true); } SECTION("Connections verify with self signed server if cert allowed") { REQUIRE(SET_CREDENTIALS(sd, "tserver") == 0); REQUIRE(pn_ssl_domain_set_trusted_ca_db(cd, CERTIFICATE("tserver")) == 0); REQUIRE(pn_ssl_domain_set_peer_authentication(cd, PN_SSL_VERIFY_PEER_NAME, NULL) == 0); REQUIRE(pn_ssl_init(pn_ssl(t), cd, NULL) == 0); REQUIRE(pn_ssl_set_peer_hostname(pn_ssl(t), "test_server") == 0); pn_proactor_listen(proactor, pn_listener(), "", 16); pn_proactor_connect2(proactor, NULL, t, ""); run(proactor, &app, server_handler, client_handler); CHECK(app.connection_succeeded==true); CHECK(app.transport_error==false); } SECTION("Anonymous server connections don't verify") { REQUIRE(pn_ssl_domain_set_trusted_ca_db(cd, CERTIFICATE("tserver")) == 0); REQUIRE(pn_ssl_domain_set_peer_authentication(cd, PN_SSL_VERIFY_PEER_NAME, NULL) == 0); REQUIRE(pn_ssl_init(pn_ssl(t), cd, NULL) == 0); pn_proactor_listen(proactor, pn_listener(), "", 16); pn_proactor_connect2(proactor, NULL, t, ""); run(proactor, &app, server_handler, client_handler); CHECK(app.connection_succeeded==false); CHECK(app.transport_error==true); } SECTION("Anonymous connections connect if anonymous allowed") { #ifndef _WIN32 REQUIRE(pn_ssl_domain_set_peer_authentication(cd, PN_SSL_ANONYMOUS_PEER, NULL) == 0); REQUIRE(pn_ssl_init(pn_ssl(t), cd, NULL) == 0); pn_proactor_listen(proactor, pn_listener(), "", 16); pn_proactor_connect2(proactor, NULL, t, ""); run(proactor, &app, server_handler, client_handler); CHECK(app.connection_succeeded==true); CHECK(app.transport_error==false); #else SUCCEED("Skipped: Windows schannel does not support anonymous connections"); #endif } SECTION("Default server (anonymous) doesn't verify against default client (verify peername)") { app.server_ssl_domain = 0; REQUIRE(pn_ssl_init(pn_ssl(t), NULL, NULL) == 0); pn_proactor_listen(proactor, pn_listener(), "", 16); pn_proactor_connect2(proactor, NULL, t, ""); run(proactor, &app, server_handler, client_handler); CHECK(app.connection_succeeded==false); CHECK(app.transport_error==true); } SECTION("Default server (anonymous) connects if anonymous allowed") { #ifndef _WIN32 app.server_ssl_domain = 0; REQUIRE(pn_ssl_domain_set_peer_authentication(cd, PN_SSL_ANONYMOUS_PEER, NULL) == 0); REQUIRE(pn_ssl_init(pn_ssl(t), cd, NULL) == 0); pn_proactor_listen(proactor, pn_listener(), "", 16); pn_proactor_connect2(proactor, NULL, t, ""); run(proactor, &app, server_handler, client_handler); CHECK(app.connection_succeeded==true); CHECK(app.transport_error==false); #else SUCCEED("Skipped: Windows schannel does not support anonymous connections"); #endif } } <|endoftext|>
<commit_before>#ifndef INCLUDE_H #define INCLUDE_H #include "STANDARD.H" #include <stdbool.h> #include <windows.h> #include <mmsystem.h> #include <ddraw.h> #include <d3d.h> #include <dinput.h> #include <dsound.h> #include <windowsx.h> #include <time.h> #include "SPECIFIC.H" #include <stdio.h> #if !defined(__cplusplus) //#error Dude insists on C++ !!! #endif #define global extern #define local static #define defglobal typedef void* Handle; enum { LOG_OUTPUT, LOG_RESET, LOG_END }; #define LOG_DO_STRLEN 0xffffffff //#define Log2(type, fmt, ...) Log_real("[DBLOG] [%s] %s", STRINGIFY(type), ) //#define Log(type, fmt, ...) S_Warn("[DBLOG] [" STRINGIFY(type) "] " fmt, __VA_ARGS__) #define Log(type, fmt, ...) Log_real(type, #type, fmt, __VA_ARGS__) #define ArraySize(a) (sizeof(a)/sizeof((a)[0])) #define Zero(thing) memset(&(thing),0,sizeof(thing)) #define ZeroArray(a) memset((a),0,sizeof(a)) #define EndOfArray(a) ((a)+ArraySize(a)) #define InitDXStruct(s) memset(&(s),0,sizeof(s)),(s).dwSize=sizeof(s) #define DefLocalString(x,y) local char Lsz##x[]=y #define LocalString(x) Lsz##x #define DefValueName(x) local char Lsz##x[]=#x #define ValueName(x) Lsz##x #define Align(x,b) (x)=(x)&~((b)-1) void DebugPrint(const char* message); void Log_backend(char type, char* fmt, ...); inline void Log_real(char ctype, char* type, char* fmt, ...) { char buf[128], pbuf[1024]; char tbuf[15]; memset(tbuf, ' ', 14); tbuf[14] = 0; strcpy(tbuf, type + 3); ZeroArray(buf); ZeroArray(pbuf); strcpy(buf, "[DBLOG] ["); strcat(buf, tbuf); strcat(buf, "] "); va_list args; va_start(args, fmt); vsprintf(pbuf, fmt, args); va_end(args); char res[1152]; ZeroArray(res); strcat(res, buf); strcat(res, pbuf); DebugPrint(res); Log_backend(ctype, pbuf); } /*** dxerror.cpp ***/ char* ERR_Describe_DX(HRESULT hr); char* ERR_Describe_Init(int nError); enum InitResult // possible initialisation results { INIT_OK, INIT_ERR_PreferredAdapterNotFound, INIT_ERR_CantCreateWindow, INIT_ERR_CantCreateDirectDraw, INIT_ERR_CantInitRenderer, INIT_ERR_CantCreateDirectInput, INIT_ERR_CantCreateKeyboardDevice, INIT_ERR_CantSetKBCooperativeLevel, INIT_ERR_CantSetKBDataFormat, INIT_ERR_CantAcquireKeyboard, INIT_ERR_CantSetDSCooperativeLevel, INIT_ERR_DD_SetExclusiveMode, INIT_ERR_DD_ClearExclusiveMode, INIT_ERR_SetDisplayMode, INIT_ERR_CreateScreenBuffers, INIT_ERR_GetBackBuffer, INIT_ERR_CreatePalette, INIT_ERR_SetPalette, INIT_ERR_CreatePrimarySurface, INIT_ERR_CreateBackBuffer, INIT_ERR_CreateClipper, INIT_ERR_SetClipperHWnd, INIT_ERR_SetClipper, INIT_ERR_CreateZBuffer, INIT_ERR_AttachZBuffer, INIT_ERR_CreateRenderBuffer, INIT_ERR_CreatePictureBuffer, INIT_ERR_D3D_Create, INIT_ERR_CreateDevice, INIT_ERR_CreateViewport, INIT_ERR_AddViewport, INIT_ERR_SetViewport2, INIT_ERR_SetCurrentViewport, INIT_ERR_ClearRenderBuffer, INIT_ERR_UpdateRenderInfo, INIT_ERR_GetThirdBuffer, INIT_ERR_GoFullScreen, INIT_ERR_GoWindowed, INIT_ERR_WrongBitDepth, INIT_ERR_GetPixelFormat, INIT_ERR_GetDisplayMode }; typedef void* Position; // iterator for linked lists etc /*** settings.cpp ***/ struct AppSettings { Position DisplayAdapter; // G_DisplayAdapterList[DisplayAdapter] is the one we're using... Position SoundAdapter; // same for sound card Position Joystick; // and joystick Position FullScreenMode; // hardware fullscreen mode x/y/bpp int nRenderMode; // none/internal/HAL/RGB int nWindowWidth, nWindowHeight; // size of desktop window int nAspectMode; // 4:3 / 16:9 / any bool tPerspectiveCorrect; // perspective correct textures bool tDither; // dithering on/off bool tZBuffer; // render using z buffer bool tBilinearFiltering; // use bilinear filtering when texture mapping bool tTripleBuffering; // use three buffers instead of two, for better performance but more memory usage // bool tMipMap; // use mipmapped textures // bool tAntialias; // antialias edges bool tFullScreen; // switch to full screen or run in window bool tSoundEnabled; // false = disable sound bool tLaraMic; // position mic at lara instead of camera (for paul & toby) bool tJoystickEnabled; // false = disable joystick bool tDisable16BitTextures; // true = disable 16 bit textures (for 2MB Mystique etc) bool tDontSortPrimitives; // true = no need to sort primitives (for PowerVR) bool tFlipBroken; // true = driver doesn't wait for flip to finish before rendering. must do it myself... bool tDisableFMV; // true = don't play any FMVs int nTexelAdjustMode; // never / when filtering / always int nNearestAdjustment; // non-filtered texel adjustment int nLinearAdjustment; // bilinear filtered texel adjustment }; enum { RENDERER_NONE, RENDERER_INTERNAL, RENDERER_HAL, RENDERER_HOWMANY }; enum { TEXEL_NEVER, TEXEL_WHENFILTERING, TEXEL_ALWAYS, TEXEL_HOWMANY }; global struct AppSettings G_AppSettings; #define DXCB_FRONT 1 #define DXCB_BACK 2 #define DXCB_THIRD 4 #define DXCB_ZBUFFER 8 #define DXCB_RENDER 16 #define DXCB_PICTURE 32 #define DXCB_CLIENT 64 #define DXCB_CLRWINDOW 256 bool HWR_Init(); void HWR_InitVertexList(); bool HWR_IsVertexBufferFull(); void HWR_InitState(); void HWR_BeginScene(); void HWR_EndScene(); void HWR_DrawPolyList(); void HWR_LoadTexturePages(int nPages, char* pImage, uint8* pPalette); void HWR_FreeTexturePages(); void HWR_RestoreTexturePages(); void HWR_ResetCurrentTexture(); void HWR_ResetColorKey(); void HWR_ResetZBuffer(); void HWR_SetCurrentTexture(DWORD dwHandle); void HWR_EnableColorKey(bool tEnable); void HWR_EnableZBuffer(bool tWrite, bool tCompare); void HWR_GetAllTextureHandles(); extern "C" void __cdecl HWR_DrawRoomBucket(void*); bool TIME_Init(); /*** misc ***/ inline bool DX_TRY(HRESULT hr) { if (SUCCEEDED(hr)) return false; Log(LT_Error, "ERROR : %s", ERR_Describe_DX(hr)); return true; } inline bool DX_FAILED(HRESULT hr) { return FAILED(hr); } #endif<commit_msg>Fix clang warning<commit_after>#ifndef INCLUDE_H #define INCLUDE_H #include "STANDARD.H" #include <stdbool.h> #include <windows.h> #include <mmsystem.h> #include <ddraw.h> #include <d3d.h> #include <dinput.h> #include <dsound.h> #include <windowsx.h> #include <time.h> #include "SPECIFIC.H" #include <stdio.h> #if !defined(__cplusplus) //#error Dude insists on C++ !!! #endif #define global extern #define local static #define defglobal typedef void* Handle; enum { LOG_OUTPUT, LOG_RESET, LOG_END }; #define LOG_DO_STRLEN 0xffffffff //#define Log2(type, fmt, ...) Log_real("[DBLOG] [%s] %s", STRINGIFY(type), ) //#define Log(type, fmt, ...) S_Warn("[DBLOG] [" STRINGIFY(type) "] " fmt, __VA_ARGS__) #define Log(type, fmt, ...) Log_real(type, #type, fmt, __VA_ARGS__) #define ArraySize(a) (sizeof(a)/sizeof((a)[0])) #define Zero(thing) memset(&(thing),0,sizeof(thing)) #define ZeroArray(a) memset((a),0,sizeof(a)) #define EndOfArray(a) ((a)+ArraySize(a)) #define InitDXStruct(s) memset(&(s),0,sizeof(s)),(s).dwSize=sizeof(s) #define DefLocalString(x,y) local char Lsz##x[]=y #define LocalString(x) Lsz##x #define DefValueName(x) local char Lsz##x[]=#x #define ValueName(x) Lsz##x #define Align(x,b) ((x)=(x)&~((b)-1)) void DebugPrint(const char* message); void Log_backend(char type, char* fmt, ...); inline void Log_real(char ctype, const char* type, const char* fmt, ...) { char buf[128], pbuf[1024]; char tbuf[15]; memset(tbuf, ' ', 14); tbuf[14] = 0; strcpy(tbuf, type + 3); ZeroArray(buf); ZeroArray(pbuf); strcpy(buf, "[DBLOG] ["); strcat(buf, tbuf); strcat(buf, "] "); va_list args; va_start(args, fmt); vsprintf(pbuf, fmt, args); va_end(args); char res[1152]; ZeroArray(res); strcat(res, buf); strcat(res, pbuf); DebugPrint(res); Log_backend(ctype, pbuf); } /*** dxerror.cpp ***/ char* ERR_Describe_DX(HRESULT hr); char* ERR_Describe_Init(int nError); enum InitResult // possible initialisation results { INIT_OK, INIT_ERR_PreferredAdapterNotFound, INIT_ERR_CantCreateWindow, INIT_ERR_CantCreateDirectDraw, INIT_ERR_CantInitRenderer, INIT_ERR_CantCreateDirectInput, INIT_ERR_CantCreateKeyboardDevice, INIT_ERR_CantSetKBCooperativeLevel, INIT_ERR_CantSetKBDataFormat, INIT_ERR_CantAcquireKeyboard, INIT_ERR_CantSetDSCooperativeLevel, INIT_ERR_DD_SetExclusiveMode, INIT_ERR_DD_ClearExclusiveMode, INIT_ERR_SetDisplayMode, INIT_ERR_CreateScreenBuffers, INIT_ERR_GetBackBuffer, INIT_ERR_CreatePalette, INIT_ERR_SetPalette, INIT_ERR_CreatePrimarySurface, INIT_ERR_CreateBackBuffer, INIT_ERR_CreateClipper, INIT_ERR_SetClipperHWnd, INIT_ERR_SetClipper, INIT_ERR_CreateZBuffer, INIT_ERR_AttachZBuffer, INIT_ERR_CreateRenderBuffer, INIT_ERR_CreatePictureBuffer, INIT_ERR_D3D_Create, INIT_ERR_CreateDevice, INIT_ERR_CreateViewport, INIT_ERR_AddViewport, INIT_ERR_SetViewport2, INIT_ERR_SetCurrentViewport, INIT_ERR_ClearRenderBuffer, INIT_ERR_UpdateRenderInfo, INIT_ERR_GetThirdBuffer, INIT_ERR_GoFullScreen, INIT_ERR_GoWindowed, INIT_ERR_WrongBitDepth, INIT_ERR_GetPixelFormat, INIT_ERR_GetDisplayMode }; typedef void* Position; // iterator for linked lists etc /*** settings.cpp ***/ struct AppSettings { Position DisplayAdapter; // G_DisplayAdapterList[DisplayAdapter] is the one we're using... Position SoundAdapter; // same for sound card Position Joystick; // and joystick Position FullScreenMode; // hardware fullscreen mode x/y/bpp int nRenderMode; // none/internal/HAL/RGB int nWindowWidth, nWindowHeight; // size of desktop window int nAspectMode; // 4:3 / 16:9 / any bool tPerspectiveCorrect; // perspective correct textures bool tDither; // dithering on/off bool tZBuffer; // render using z buffer bool tBilinearFiltering; // use bilinear filtering when texture mapping bool tTripleBuffering; // use three buffers instead of two, for better performance but more memory usage // bool tMipMap; // use mipmapped textures // bool tAntialias; // antialias edges bool tFullScreen; // switch to full screen or run in window bool tSoundEnabled; // false = disable sound bool tLaraMic; // position mic at lara instead of camera (for paul & toby) bool tJoystickEnabled; // false = disable joystick bool tDisable16BitTextures; // true = disable 16 bit textures (for 2MB Mystique etc) bool tDontSortPrimitives; // true = no need to sort primitives (for PowerVR) bool tFlipBroken; // true = driver doesn't wait for flip to finish before rendering. must do it myself... bool tDisableFMV; // true = don't play any FMVs int nTexelAdjustMode; // never / when filtering / always int nNearestAdjustment; // non-filtered texel adjustment int nLinearAdjustment; // bilinear filtered texel adjustment }; enum { RENDERER_NONE, RENDERER_INTERNAL, RENDERER_HAL, RENDERER_HOWMANY }; enum { TEXEL_NEVER, TEXEL_WHENFILTERING, TEXEL_ALWAYS, TEXEL_HOWMANY }; global struct AppSettings G_AppSettings; #define DXCB_FRONT 1 #define DXCB_BACK 2 #define DXCB_THIRD 4 #define DXCB_ZBUFFER 8 #define DXCB_RENDER 16 #define DXCB_PICTURE 32 #define DXCB_CLIENT 64 #define DXCB_CLRWINDOW 256 bool HWR_Init(); void HWR_InitVertexList(); bool HWR_IsVertexBufferFull(); void HWR_InitState(); void HWR_BeginScene(); void HWR_EndScene(); void HWR_DrawPolyList(); void HWR_LoadTexturePages(int nPages, char* pImage, uint8* pPalette); void HWR_FreeTexturePages(); void HWR_RestoreTexturePages(); void HWR_ResetCurrentTexture(); void HWR_ResetColorKey(); void HWR_ResetZBuffer(); void HWR_SetCurrentTexture(DWORD dwHandle); void HWR_EnableColorKey(bool tEnable); void HWR_EnableZBuffer(bool tWrite, bool tCompare); void HWR_GetAllTextureHandles(); extern "C" void __cdecl HWR_DrawRoomBucket(void*); bool TIME_Init(); /*** misc ***/ inline bool DX_TRY(HRESULT hr) { if (SUCCEEDED(hr)) return false; Log(LT_Error, "ERROR : %s", ERR_Describe_DX(hr)); return true; } inline bool DX_FAILED(HRESULT hr) { return FAILED(hr); } #endif<|endoftext|>
<commit_before>#include "PSOUTPUT.H" #include "SPECTYPES.H" #include "SPECIFIC.H" static struct VIBRATION vib[2]; void VibratePad()//604EC, 61064 { return; } void SetupPadVibration(short num, short acc, short lev, short sus, int dec, int len)//604A4(<), 6101C(<) (F) { struct VIBRATION* v = &vib[num]; v->Acc = acc; v->Lev = lev; v->Flag = 0; v->Rate = 0; v->Vib = 0; v->Sus = len - dec; v->Dec = dec; v->Len = len; return; }<commit_msg>Add VibratePad()<commit_after>#include "PSOUTPUT.H" #include "PSXINPUT.H" #include "SAVEGAME.H" #include "SPECTYPES.H" static struct VIBRATION vib[2]; void VibratePad()//604EC(<), 61064(<) (F) { int i; struct VIBRATION* v; if (DualShock == 0 && savegame.VibrateOn) { //loc_60510 Motors[0] = 0; Motors[1] = 0; return; } //loc_6052C for (i = 0; i < 2; i++, v = &vib[i]) { if (v->Len != 0) { if (v->Flag == 0) { v->Rate += v->Acc; if (v->Rate > v->Lev) { v->Rate = v->Lev; v->Flag = 1; }//loc_605DC } else if (v->Flag == 1) { //loc_60588 if (v->Sus > v->Len) { v->Flag = 2; }//loc_605DC } else if (v->Flag == 2) { //loc_605AC v->Rate -= v->Dec; if (v->Rate * 65536 < 0) { v->Rate = 0; v->Flag = 3; }//loc_605DC } //loc_605DC v->Vib += v->Rate; if (i != 0) { if (v->Vib / 16 != 0) { Motors[1] = v->Vib / 16; v->Vib &= 0xFF; }//loc_60650 else { //loc_60618 Motors[1] = 0; }//loc_60650 } else { //loc_60628 if (v->Vib / 24 != 0) { Motors[0] = 1; v->Vib -= 4096; } else { //loc_60648 Motors[0] = 0; } //loc_60650 v->Len--; } } else { //loc_60664 Motors[i] = 0; } } } void SetupPadVibration(short num, short acc, short lev, short sus, int dec, int len)//604A4(<), 6101C(<) (F) { struct VIBRATION* v = &vib[num]; v->Acc = acc; v->Lev = lev; v->Flag = 0; v->Rate = 0; v->Vib = 0; v->Sus = len - dec; v->Dec = dec; v->Len = len; }<|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtSparql module (not yet part of the Qt Toolkit). ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/QDebug> #include <QtDeclarative/QDeclarativeExtensionPlugin> #include <QtDeclarative/qdeclarative.h> #include "qsparqlresultslist_p.h" QSparqlResultsList::QSparqlResultsList(QObject *parent) : QAbstractListModel(parent), m_connection(0), m_result(0), m_options(0) { } int QSparqlResultsList::rowCount(const QModelIndex &) const { return m_result->size(); } QVariant QSparqlResultsList::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); m_result->setPos(index.row()); QSparqlResultRow row = m_result->current(); int i = role - (Qt::UserRole + 1); if (i >= row.count()) return row.binding(i - row.count()).toString(); else return row.value(i); } void QSparqlResultsList::reload() { if (m_options == 0 || m_query.isEmpty()) return; if (m_result != 0) { if (!m_result->isFinished()) return; else delete m_result; } delete m_connection; /* Create and run the sparql query */ m_connection = new QSparqlConnection(m_options->driverName(), m_options->options()); m_result = m_connection->exec(QSparqlQuery(m_query)); connect(m_result, SIGNAL(finished()), this, SLOT(queryFinished())); } void QSparqlResultsList::queryFinished() { QHash<int, QByteArray> roleNames; roleNames = QAbstractItemModel::roleNames(); if (m_result->first()) { QSparqlResultRow resultRow = m_result->current(); // Create two set of declarative variables from the variable names used // in the select statement // 'foo' is just a literal like 1234, but '$foo' is "1234"^^xsd:integer // 'bar' is a string 'http://www.w3.org/2002/07/owl#sameAs', but '$bar' // is a uri <http://www.w3.org/2002/07/owl#sameAs> for (int i = 0; i < resultRow.count(); i++) { roleNames.insert((Qt::UserRole + 1) + i, resultRow.binding(i).name().toLatin1()); } for (int i = 0; i < resultRow.count(); i++) { roleNames.insert((Qt::UserRole + 1) + i + resultRow.count(), QByteArray("$") + resultRow.binding(i).name().toLatin1()); } setRoleNames(roleNames); } reset(); } QSparqlConnectionOptionsWrapper* QSparqlResultsList::options() const { return m_options; } void QSparqlResultsList::setOptions(QSparqlConnectionOptionsWrapper *options) { m_options = options; reload(); } QString QSparqlResultsList::query() const { return m_query; } void QSparqlResultsList::setQuery(const QString &query) { m_query = query; reload(); } <commit_msg>* Remove the QtDeclarative header includes as QSparqlResultsList doesn't have any declarative code in it<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtSparql module (not yet part of the Qt Toolkit). ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/QDebug> #include "qsparqlresultslist_p.h" QSparqlResultsList::QSparqlResultsList(QObject *parent) : QAbstractListModel(parent), m_connection(0), m_result(0), m_options(0) { } int QSparqlResultsList::rowCount(const QModelIndex &) const { return m_result->size(); } QVariant QSparqlResultsList::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); m_result->setPos(index.row()); QSparqlResultRow row = m_result->current(); int i = role - (Qt::UserRole + 1); if (i >= row.count()) return row.binding(i - row.count()).toString(); else return row.value(i); } void QSparqlResultsList::reload() { if (m_options == 0 || m_query.isEmpty()) return; if (m_result != 0) { if (!m_result->isFinished()) return; else delete m_result; } delete m_connection; /* Create and run the sparql query */ m_connection = new QSparqlConnection(m_options->driverName(), m_options->options()); m_result = m_connection->exec(QSparqlQuery(m_query)); connect(m_result, SIGNAL(finished()), this, SLOT(queryFinished())); } void QSparqlResultsList::queryFinished() { QHash<int, QByteArray> roleNames; roleNames = QAbstractItemModel::roleNames(); if (m_result->first()) { QSparqlResultRow resultRow = m_result->current(); // Create two set of declarative variables from the variable names used // in the select statement // 'foo' is just a literal like 1234, but '$foo' is "1234"^^xsd:integer // 'bar' is a string 'http://www.w3.org/2002/07/owl#sameAs', but '$bar' // is a uri <http://www.w3.org/2002/07/owl#sameAs> for (int i = 0; i < resultRow.count(); i++) { roleNames.insert((Qt::UserRole + 1) + i, resultRow.binding(i).name().toLatin1()); } for (int i = 0; i < resultRow.count(); i++) { roleNames.insert((Qt::UserRole + 1) + i + resultRow.count(), QByteArray("$") + resultRow.binding(i).name().toLatin1()); } setRoleNames(roleNames); } reset(); } QSparqlConnectionOptionsWrapper* QSparqlResultsList::options() const { return m_options; } void QSparqlResultsList::setOptions(QSparqlConnectionOptionsWrapper *options) { m_options = options; reload(); } QString QSparqlResultsList::query() const { return m_query; } void QSparqlResultsList::setQuery(const QString &query) { m_query = query; reload(); } <|endoftext|>