text
stringlengths
54
60.6k
<commit_before>#include <Utils/GL+/Models/Mesh.h> #include <Utils/GL+/Models/Material.h> namespace GL { namespace Model { Mesh::Mesh() : Mesh("defaultMaterial") { } Mesh::Mesh(const std::string& materialName) { this->materialName = materialName; } Mesh::Mesh(Mesh&& mesh) : materialName(std::move(mesh.materialName)), vertices(std::move(mesh.vertices)), texCoords(std::move(mesh.texCoords)), normals(std::move(mesh.normals)), _vao(std::move(mesh._vao)), _vboV(std::move(mesh._vboV)), _vboT(std::move(mesh._vboT)), _vboN(std::move(mesh._vboN)), _aabb(std::move(mesh._aabb)) { } void Mesh::build() { _vao.bind(); _vboV.bind(); _vboV.setData(vertices); _vao.enableAttrib(0); _vao.setAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); _vboV.unbind(); _vboT.bind(); _vboT.setData(texCoords); _vao.enableAttrib(1); _vao.setAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0); _vboT.unbind(); _vboN.bind(); _vboN.setData(normals); _vao.enableAttrib(2); _vao.setAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, 0); _vboN.unbind(); _vao.unbind(); _vao.setDrawCount(vertices.size()); _vao.setDrawTarget(GL::VertexArray::DrawTarget::Triangles); } void Mesh::computeNormals(Util::Interface::Model::NormalType type, bool overwrite) { if(hasNormals() == false || overwrite) { normals.clear(); glm::vec3 normal = glm::vec3(0.0); glm::vec3 edge1; glm::vec3 edge2; if(type == Util::Interface::Model::NormalType::Smooth) { for(int i = 0; i < vertices.size(); ++i) { for(int j = 0; j < vertices.size(); ++j) { if(i != j) { if(vertices[i] == vertices[j]) { int k = j - (j % 3); edge1 = vertices[k + 1] - vertices[k]; edge2 = vertices[k + 2] - vertices[k]; normal += glm::normalize(glm::cross(edge1, edge2)); } } } normal = glm::normalize(normal); normals.push_back(normal); } } else { for(int i = 0; i < vertices.size(); i += 3) { edge1 = vertices[i + 1] - vertices[i]; edge2 = vertices[i + 2] - vertices[i]; normal = glm::normalize(glm::cross(edge1, edge2)); normals.push_back(normal); normals.push_back(normal); normals.push_back(normal); } } } } void Mesh::render(const GL::Pipeline& pipeline, const GL::Program& program, const Material& material) const { glm::ivec4 hasTextures = glm::ivec4(0); // Transparent objects not supported if(material.alphaFactor < 1.0f - 0.01f) return; // Texture query hasTextures.x = (material.textureDiffuse != "") ? true : false; hasTextures.y = (material.textureAmbient != "") ? true : false; //hasTextures.z = (material.textureSpecular != "") ? true : false; // not supported yet //hasTextures.w = (material.textureBumpmap != "") ? true : false; // not supported yet /* if(hasTextures.x) model.getTextures().at(material->textureDiffuse).bind(); else if(hasTextures.y) model.getTextures().at(material->textureAmbient).bind(); */ program.use(); program["matrixMVP"] = pipeline.getMVP(); program["uColorD"] = glm::vec4(material.colorDiffuse, 1.0f); program["uColorA"] = glm::vec4(material.colorAmbient, material.alphaFactor); program["uColorS"] = glm::vec4(material.colorSpecular, material.exponentSpecular); program["hasTextures"] = hasTextures; program["texSampler"] = 0; _vao.bind(); _vao.drawArrays(); _vao.unbind(); program.unbind(); /* if(hasTextures.x) model.getTextures().at(material->textureDiffuse).unbind(); else if(hasTextures.y) model.getTextures().at(material->textureAmbient).unbind(); */ } void Mesh::renderAABB(const GL::Pipeline& pipeline) const { getAABB().render(pipeline); } void Mesh::addData(const glm::vec3& vertex) { vertices.push_back(vertex); _aabb.updateBy(vertex); } void Mesh::addData(const glm::vec3& vertex, const glm::vec2& texCoord) { vertices.push_back(vertex); texCoords.push_back(texCoord); _aabb.updateBy(vertex); } void Mesh::addData(const glm::vec3& vertex, const glm::vec2& texCoord, const glm::vec3& normal) { vertices.push_back(vertex); texCoords.push_back(texCoord); normals.push_back(normal); _aabb.updateBy(vertex); } void Mesh::addData(const glm::vec3& vertex, const glm::vec3& normal) { vertices.push_back(vertex); normals.push_back(normal); _aabb.updateBy(vertex); } bool Mesh::hasNormals() const { return (vertices.size() == normals.size()); } const Util::AABB& Mesh::getAABB() const { return _aabb; } } }<commit_msg>[#7] Fixed initializing VBOs for models - unused VBOs are not enabled to prevent crash on nVidia graphic cards.<commit_after>#include <Utils/GL+/Models/Mesh.h> #include <Utils/GL+/Models/Material.h> namespace GL { namespace Model { Mesh::Mesh() : Mesh("defaultMaterial") { } Mesh::Mesh(const std::string& materialName) { this->materialName = materialName; } Mesh::Mesh(Mesh&& mesh) : materialName(std::move(mesh.materialName)), vertices(std::move(mesh.vertices)), texCoords(std::move(mesh.texCoords)), normals(std::move(mesh.normals)), _vao(std::move(mesh._vao)), _vboV(std::move(mesh._vboV)), _vboT(std::move(mesh._vboT)), _vboN(std::move(mesh._vboN)), _aabb(std::move(mesh._aabb)) { } void Mesh::build() { _vao.bind(); if(vertices.size() > 0) { _vboV.bind(); _vboV.setData(vertices); _vao.enableAttrib(0); _vao.setAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); _vboV.unbind(); } if(texCoords.size() > 0) { _vboT.bind(); _vboT.setData(texCoords); _vao.enableAttrib(1); _vao.setAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0); _vboT.unbind(); } if(normals.size() > 0) { _vboN.bind(); _vboN.setData(normals); _vao.enableAttrib(2); _vao.setAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, 0); _vboN.unbind(); } _vao.unbind(); _vao.setDrawCount(vertices.size()); _vao.setDrawTarget(GL::VertexArray::DrawTarget::Triangles); } void Mesh::computeNormals(Util::Interface::Model::NormalType type, bool overwrite) { if(hasNormals() == false || overwrite) { normals.clear(); glm::vec3 normal = glm::vec3(0.0); glm::vec3 edge1; glm::vec3 edge2; if(type == Util::Interface::Model::NormalType::Smooth) { for(int i = 0; i < vertices.size(); ++i) { for(int j = 0; j < vertices.size(); ++j) { if(i != j) { if(vertices[i] == vertices[j]) { int k = j - (j % 3); edge1 = vertices[k + 1] - vertices[k]; edge2 = vertices[k + 2] - vertices[k]; normal += glm::normalize(glm::cross(edge1, edge2)); } } } normal = glm::normalize(normal); normals.push_back(normal); } } else { for(int i = 0; i < vertices.size(); i += 3) { edge1 = vertices[i + 1] - vertices[i]; edge2 = vertices[i + 2] - vertices[i]; normal = glm::normalize(glm::cross(edge1, edge2)); normals.push_back(normal); normals.push_back(normal); normals.push_back(normal); } } } } void Mesh::render(const GL::Pipeline& pipeline, const GL::Program& program, const Material& material) const { glm::ivec4 hasTextures = glm::ivec4(0); // Transparent objects not supported if(material.alphaFactor < 1.0f - 0.01f) return; // Texture query hasTextures.x = (material.textureDiffuse != "") ? true : false; hasTextures.y = (material.textureAmbient != "") ? true : false; //hasTextures.z = (material.textureSpecular != "") ? true : false; // not supported yet //hasTextures.w = (material.textureBumpmap != "") ? true : false; // not supported yet /* if(hasTextures.x) model.getTextures().at(material->textureDiffuse).bind(); else if(hasTextures.y) model.getTextures().at(material->textureAmbient).bind(); */ program.use(); program["matrixMVP"] = pipeline.getMVP(); program["uColorD"] = glm::vec4(material.colorDiffuse, 1.0f); program["uColorA"] = glm::vec4(material.colorAmbient, material.alphaFactor); program["uColorS"] = glm::vec4(material.colorSpecular, material.exponentSpecular); program["hasTextures"] = hasTextures; program["texSampler"] = 0; _vao.bind(); _vao.drawArrays(); _vao.unbind(); program.unbind(); /* if(hasTextures.x) model.getTextures().at(material->textureDiffuse).unbind(); else if(hasTextures.y) model.getTextures().at(material->textureAmbient).unbind(); */ } void Mesh::renderAABB(const GL::Pipeline& pipeline) const { getAABB().render(pipeline); } void Mesh::addData(const glm::vec3& vertex) { vertices.push_back(vertex); _aabb.updateBy(vertex); } void Mesh::addData(const glm::vec3& vertex, const glm::vec2& texCoord) { vertices.push_back(vertex); texCoords.push_back(texCoord); _aabb.updateBy(vertex); } void Mesh::addData(const glm::vec3& vertex, const glm::vec2& texCoord, const glm::vec3& normal) { vertices.push_back(vertex); texCoords.push_back(texCoord); normals.push_back(normal); _aabb.updateBy(vertex); } void Mesh::addData(const glm::vec3& vertex, const glm::vec3& normal) { vertices.push_back(vertex); normals.push_back(normal); _aabb.updateBy(vertex); } bool Mesh::hasNormals() const { return (vertices.size() == normals.size()); } const Util::AABB& Mesh::getAABB() const { return _aabb; } } }<|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. * * Modified by Cloudius Systems. * Copyright 2015 Cloudius Systems. */ #pragma once #include "gms/inet_address.hh" #include "streaming/stream_session.hh" #include "streaming/session_info.hh" #include <map> #include <algorithm> namespace streaming { /** * {@link StreamCoordinator} is a helper class that abstracts away maintaining multiple * StreamSession and ProgressInfo instances per peer. * * This class coordinates multiple SessionStreams per peer in both the outgoing StreamPlan context and on the * inbound StreamResultFuture context. */ class stream_coordinator { class host_streaming_data; private: using inet_address = gms::inet_address; std::map<inet_address, host_streaming_data> _peer_sessions; int _connections_per_host; bool _keep_ss_table_level; public: stream_coordinator(int connections_per_host, bool keep_ss_table_level) : _connections_per_host(connections_per_host) , _keep_ss_table_level(keep_ss_table_level) { } #if 0 public void setConnectionFactory(StreamConnectionFactory factory) { this.factory = factory; } #endif public: /** * @return true if any stream session is active */ bool has_active_sessions(); #if 0 public synchronized Collection<StreamSession> getAllStreamSessions() { Collection<StreamSession> results = new ArrayList<>(); for (HostStreamingData data : peerSessions.values()) { results.addAll(data.getAllStreamSessions()); } return results; } public boolean isReceiving() { return connectionsPerHost == 0; } public void connectAllStreamSessions() { for (HostStreamingData data : peerSessions.values()) data.connectAllStreamSessions(); } public synchronized Set<InetAddress> getPeers() { return new HashSet<>(peerSessions.keySet()); } #endif public: stream_session& get_or_create_next_session(inet_address peer, inet_address connecting) { return get_or_create_host_data(peer).get_or_create_next_session(peer, connecting); } stream_session& get_or_create_session_by_id(inet_address peer, int id, inet_address connecting) { return get_or_create_host_data(peer).get_or_create_session_by_id(peer, id, connecting); } void update_progress(progress_info info) { get_host_data(info.peer).update_progress(info); } void add_session_info(session_info session) { auto& data = get_or_create_host_data(session.peer); data.add_session_info(std::move(session)); } std::vector<session_info> get_all_session_info() { std::vector<session_info> result; for (auto& x : _peer_sessions) { auto s = x.second.get_all_session_info(); std::move(s.begin(), s.end(), std::back_inserter(result)); } return result; } public: void transfer_files(inet_address to, std::vector<stream_session::ss_table_streaming_sections> sstable_details) { host_streaming_data& session_list = get_or_create_host_data(to); if (_connections_per_host > 1) { abort(); #if 0 List<List<StreamSession.SSTableStreamingSections>> buckets = sliceSSTableDetails(sstableDetails); for (List<StreamSession.SSTableStreamingSections> subList : buckets) { StreamSession session = sessionList.get_or_create_next_session(to, to); session.addTransferFiles(subList); } #endif } else { auto& session = session_list.get_or_create_next_session(to, to); session.add_transfer_files(sstable_details); } } private: #if 0 private List<List<StreamSession.SSTableStreamingSections>> sliceSSTableDetails(Collection<StreamSession.SSTableStreamingSections> sstableDetails) { // There's no point in divvying things up into more buckets than we have sstableDetails int targetSlices = Math.min(sstableDetails.size(), connectionsPerHost); int step = Math.round((float) sstableDetails.size() / (float) targetSlices); int index = 0; List<List<StreamSession.SSTableStreamingSections>> result = new ArrayList<>(); List<StreamSession.SSTableStreamingSections> slice = null; Iterator<StreamSession.SSTableStreamingSections> iter = sstableDetails.iterator(); while (iter.hasNext()) { StreamSession.SSTableStreamingSections streamSession = iter.next(); if (index % step == 0) { slice = new ArrayList<>(); result.add(slice); } slice.add(streamSession); ++index; iter.remove(); } return result; } #endif host_streaming_data& get_host_data(inet_address peer) { auto it = _peer_sessions.find(peer); if (it == _peer_sessions.end()) { throw std::runtime_error(sprint("Unknown peer requested: %s", peer)); } return it->second; } host_streaming_data& get_or_create_host_data(inet_address peer) { _peer_sessions[peer] = host_streaming_data(_connections_per_host, _keep_ss_table_level); return _peer_sessions[peer]; } #if 0 private static class StreamSessionConnector implements Runnable { private final StreamSession session; public StreamSessionConnector(StreamSession session) { this.session = session; } @Override public void run() { session.start(); logger.info("[Stream #{}, ID#{}] Beginning stream session with {}", session.planId(), session.sessionIndex(), session.peer); } } #endif private: class host_streaming_data { using inet_address = gms::inet_address; private: std::map<int, stream_session> _stream_sessions; std::map<int, session_info> _session_infos; int _last_returned = -1; int _connections_per_host; bool _keep_ss_table_level; public: host_streaming_data() = default; host_streaming_data(int connections_per_host, bool keep_ss_table_level) : _connections_per_host(connections_per_host) , _keep_ss_table_level(keep_ss_table_level) { } bool has_active_sessions(); stream_session& get_or_create_next_session(inet_address peer, inet_address connecting) { // create int size = _stream_sessions.size(); if (size < _connections_per_host) { auto session = stream_session(peer, connecting, size, _keep_ss_table_level); _stream_sessions.emplace(++_last_returned, std::move(session)); return _stream_sessions[_last_returned]; // get } else { if (_last_returned >= (size - 1)) { _last_returned = 0; } return _stream_sessions[_last_returned++]; } } #if 0 public void connectAllStreamSessions() { for (StreamSession session : streamSessions.values()) { streamExecutor.execute(new StreamSessionConnector(session)); } } public Collection<StreamSession> getAllStreamSessions() { return Collections.unmodifiableCollection(streamSessions.values()); } #endif stream_session& get_or_create_session_by_id(inet_address peer, int id, inet_address connecting) { auto it = _stream_sessions.find(id); if (it == _stream_sessions.end()) { it = _stream_sessions.emplace(id, stream_session(peer, connecting, id, _keep_ss_table_level)).first; } return it->second; } void update_progress(progress_info info) { auto it = _session_infos.find(info.session_index); if (it != _session_infos.end()) { it->second.update_progress(std::move(info)); } } void add_session_info(session_info info) { _session_infos[info.session_index] = std::move(info); } std::vector<session_info> get_all_session_info() { std::vector<session_info> sessions; for (auto& x : _session_infos) { sessions.push_back(x.second); } return sessions; } }; }; } // namespace streaming <commit_msg>streaming: Add stream_coordinator::get_all_stream_sessions<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. * * Modified by Cloudius Systems. * Copyright 2015 Cloudius Systems. */ #pragma once #include "gms/inet_address.hh" #include "streaming/stream_session.hh" #include "streaming/session_info.hh" #include <map> #include <algorithm> namespace streaming { /** * {@link StreamCoordinator} is a helper class that abstracts away maintaining multiple * StreamSession and ProgressInfo instances per peer. * * This class coordinates multiple SessionStreams per peer in both the outgoing StreamPlan context and on the * inbound StreamResultFuture context. */ class stream_coordinator { class host_streaming_data; private: using inet_address = gms::inet_address; std::map<inet_address, host_streaming_data> _peer_sessions; int _connections_per_host; bool _keep_ss_table_level; public: stream_coordinator(int connections_per_host, bool keep_ss_table_level) : _connections_per_host(connections_per_host) , _keep_ss_table_level(keep_ss_table_level) { } #if 0 public void setConnectionFactory(StreamConnectionFactory factory) { this.factory = factory; } #endif public: /** * @return true if any stream session is active */ bool has_active_sessions(); std::vector<stream_session> get_all_stream_sessions() { std::vector<stream_session> results; for (auto& x : _peer_sessions) { auto s = x.second.get_all_stream_sessions(); std::move(s.begin(), s.end(), std::back_inserter(results)); } return results; } #if 0 public boolean isReceiving() { return connectionsPerHost == 0; } public void connectAllStreamSessions() { for (HostStreamingData data : peerSessions.values()) data.connectAllStreamSessions(); } public synchronized Set<InetAddress> getPeers() { return new HashSet<>(peerSessions.keySet()); } #endif public: stream_session& get_or_create_next_session(inet_address peer, inet_address connecting) { return get_or_create_host_data(peer).get_or_create_next_session(peer, connecting); } stream_session& get_or_create_session_by_id(inet_address peer, int id, inet_address connecting) { return get_or_create_host_data(peer).get_or_create_session_by_id(peer, id, connecting); } void update_progress(progress_info info) { get_host_data(info.peer).update_progress(info); } void add_session_info(session_info session) { auto& data = get_or_create_host_data(session.peer); data.add_session_info(std::move(session)); } std::vector<session_info> get_all_session_info() { std::vector<session_info> result; for (auto& x : _peer_sessions) { auto s = x.second.get_all_session_info(); std::move(s.begin(), s.end(), std::back_inserter(result)); } return result; } public: void transfer_files(inet_address to, std::vector<stream_session::ss_table_streaming_sections> sstable_details) { host_streaming_data& session_list = get_or_create_host_data(to); if (_connections_per_host > 1) { abort(); #if 0 List<List<StreamSession.SSTableStreamingSections>> buckets = sliceSSTableDetails(sstableDetails); for (List<StreamSession.SSTableStreamingSections> subList : buckets) { StreamSession session = sessionList.get_or_create_next_session(to, to); session.addTransferFiles(subList); } #endif } else { auto& session = session_list.get_or_create_next_session(to, to); session.add_transfer_files(sstable_details); } } private: #if 0 private List<List<StreamSession.SSTableStreamingSections>> sliceSSTableDetails(Collection<StreamSession.SSTableStreamingSections> sstableDetails) { // There's no point in divvying things up into more buckets than we have sstableDetails int targetSlices = Math.min(sstableDetails.size(), connectionsPerHost); int step = Math.round((float) sstableDetails.size() / (float) targetSlices); int index = 0; List<List<StreamSession.SSTableStreamingSections>> result = new ArrayList<>(); List<StreamSession.SSTableStreamingSections> slice = null; Iterator<StreamSession.SSTableStreamingSections> iter = sstableDetails.iterator(); while (iter.hasNext()) { StreamSession.SSTableStreamingSections streamSession = iter.next(); if (index % step == 0) { slice = new ArrayList<>(); result.add(slice); } slice.add(streamSession); ++index; iter.remove(); } return result; } #endif host_streaming_data& get_host_data(inet_address peer) { auto it = _peer_sessions.find(peer); if (it == _peer_sessions.end()) { throw std::runtime_error(sprint("Unknown peer requested: %s", peer)); } return it->second; } host_streaming_data& get_or_create_host_data(inet_address peer) { _peer_sessions[peer] = host_streaming_data(_connections_per_host, _keep_ss_table_level); return _peer_sessions[peer]; } #if 0 private static class StreamSessionConnector implements Runnable { private final StreamSession session; public StreamSessionConnector(StreamSession session) { this.session = session; } @Override public void run() { session.start(); logger.info("[Stream #{}, ID#{}] Beginning stream session with {}", session.planId(), session.sessionIndex(), session.peer); } } #endif private: class host_streaming_data { using inet_address = gms::inet_address; private: std::map<int, stream_session> _stream_sessions; std::map<int, session_info> _session_infos; int _last_returned = -1; int _connections_per_host; bool _keep_ss_table_level; public: host_streaming_data() = default; host_streaming_data(int connections_per_host, bool keep_ss_table_level) : _connections_per_host(connections_per_host) , _keep_ss_table_level(keep_ss_table_level) { } bool has_active_sessions(); stream_session& get_or_create_next_session(inet_address peer, inet_address connecting) { // create int size = _stream_sessions.size(); if (size < _connections_per_host) { auto session = stream_session(peer, connecting, size, _keep_ss_table_level); _stream_sessions.emplace(++_last_returned, std::move(session)); return _stream_sessions[_last_returned]; // get } else { if (_last_returned >= (size - 1)) { _last_returned = 0; } return _stream_sessions[_last_returned++]; } } #if 0 public void connectAllStreamSessions() { for (StreamSession session : streamSessions.values()) { streamExecutor.execute(new StreamSessionConnector(session)); } } #endif std::vector<stream_session> get_all_stream_sessions() { std::vector<stream_session> sessions; for (auto& x : _stream_sessions) { sessions.push_back(x.second); } return sessions; } stream_session& get_or_create_session_by_id(inet_address peer, int id, inet_address connecting) { auto it = _stream_sessions.find(id); if (it == _stream_sessions.end()) { it = _stream_sessions.emplace(id, stream_session(peer, connecting, id, _keep_ss_table_level)).first; } return it->second; } void update_progress(progress_info info) { auto it = _session_infos.find(info.session_index); if (it != _session_infos.end()) { it->second.update_progress(std::move(info)); } } void add_session_info(session_info info) { _session_infos[info.session_index] = std::move(info); } std::vector<session_info> get_all_session_info() { std::vector<session_info> sessions; for (auto& x : _session_infos) { sessions.push_back(x.second); } return sessions; } }; }; } // namespace streaming <|endoftext|>
<commit_before>/* * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h" #include "base/compiler_specific.h" #define WIN32_COMPILE_HACK MSVC_PUSH_WARNING_LEVEL(0); #include "SSLKeyGenerator.h" #include "KURL.h" #include "NotImplemented.h" #include "SharedBuffer.h" MSVC_POP_WARNING(); using namespace WebCore; String WebCore::signedPublicKeyAndChallengeString(unsigned, const String&, const KURL&) { notImplemented(); return String(); } void WebCore::getSupportedKeySizes(Vector<String>&) { notImplemented(); } String KURL::fileSystemPath() const { notImplemented(); return String(); } PassRefPtr<SharedBuffer> SharedBuffer::createWithContentsOfFile(const String& filePath) { notImplemented(); return 0; } namespace WTF { #if !defined(__linux__) void scheduleDispatchFunctionsOnMainThread() { notImplemented(); } #endif } <commit_msg>Cleanup TemporaryLinkStubs.cpp.<commit_after>/* * Copyright (c) 2008, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "KURL.h" #include "NotImplemented.h" #include "SharedBuffer.h" namespace WebCore { String signedPublicKeyAndChallengeString(unsigned, const String&, const KURL&) { notImplemented(); return String(); } void getSupportedKeySizes(Vector<String>&) { notImplemented(); } String KURL::fileSystemPath() const { notImplemented(); return String(); } PassRefPtr<SharedBuffer> SharedBuffer::createWithContentsOfFile(const String&) { notImplemented(); return 0; } } // namespace WebCore // Required to use notImplemented() outside of the WebCore namespace. using namespace WebCore; namespace WTF { #if !defined(__linux__) void scheduleDispatchFunctionsOnMainThread() { notImplemented(); } #endif } // namespace WTF <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "jsonkitspage.h" #include "jsonwizard.h" #include "../iprojectmanager.h" #include "../kit.h" #include "../project.h" #include "../projectexplorer.h" #include <coreplugin/featureprovider.h> #include <coreplugin/mimedatabase.h> #include <extensionsystem/pluginmanager.h> #include <utils/macroexpander.h> #include <utils/qtcassert.h> namespace ProjectExplorer { JsonKitsPage::JsonKitsPage(QWidget *parent) : TargetSetupPage(parent) { } void ProjectExplorer::JsonKitsPage::initializePage() { JsonWizard *wiz = qobject_cast<JsonWizard *>(wizard()); QTC_ASSERT(wiz, return); connect(wiz, &JsonWizard::filesReady, this, &JsonKitsPage::setupProjectFiles); const QString platform = wiz->value(QLatin1String("Platform")).toString(); const Core::FeatureSet preferred = Core::FeatureSet::fromStringList(wiz->value(QLatin1String("PreferredFeatures")).toStringList()); const Core::FeatureSet required = Core::FeatureSet::fromStringList(wiz->value(QLatin1String("RequiredFeatures")).toStringList()); const QString path = Utils::expandMacros(m_projectFilePath, wiz->expander()); setProjectPath(path); setRequiredKitMatcher(KitMatcher([required](const Kit *k) { return k->hasFeatures(required); })); setPreferredKitMatcher(KitMatcher([platform, preferred](const Kit *k) { return k->hasPlatform(platform) && k->hasFeatures(preferred); })); TargetSetupPage::initializePage(); } void JsonKitsPage::cleanupPage() { JsonWizard *wiz = qobject_cast<JsonWizard *>(wizard()); QTC_ASSERT(wiz, return); disconnect(wiz, &JsonWizard::filesReady, this, 0); TargetSetupPage::cleanupPage(); } void JsonKitsPage::setupProjectFiles(const JsonWizard::GeneratorFiles &files) { Project *project = 0; QList<IProjectManager *> managerList = ExtensionSystem::PluginManager::getObjects<IProjectManager>(); foreach (const JsonWizard::GeneratorFile &f, files) { if (f.file.attributes() & Core::GeneratedFile::OpenProjectAttribute) { QString errorMessage; QString path = f.file.path(); const QFileInfo fi(path); if (fi.exists()) path = fi.canonicalFilePath(); Core::MimeType mt = Core::MimeDatabase::findByFile(fi); if (mt.isNull()) continue; foreach (IProjectManager *manager, managerList) { if (manager->mimeType() == mt.type()) { project = manager->openProject(path, &errorMessage); break; } } if (project) { bool success = setupProject(project); if (success) project->saveSettings(); delete project; } } } } } // namespace ProjectExplorer <commit_msg>Fix compilation<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "jsonkitspage.h" #include "jsonwizard.h" #include "../iprojectmanager.h" #include "../kit.h" #include "../project.h" #include "../projectexplorer.h" #include <coreplugin/featureprovider.h> #include <coreplugin/mimedatabase.h> #include <extensionsystem/pluginmanager.h> #include <utils/macroexpander.h> #include <utils/qtcassert.h> namespace ProjectExplorer { JsonKitsPage::JsonKitsPage(QWidget *parent) : TargetSetupPage(parent) { } void JsonKitsPage::initializePage() { JsonWizard *wiz = qobject_cast<JsonWizard *>(wizard()); QTC_ASSERT(wiz, return); connect(wiz, &JsonWizard::filesReady, this, &JsonKitsPage::setupProjectFiles); const QString platform = wiz->value(QLatin1String("Platform")).toString(); const Core::FeatureSet preferred = Core::FeatureSet::fromStringList(wiz->value(QLatin1String("PreferredFeatures")).toStringList()); const Core::FeatureSet required = Core::FeatureSet::fromStringList(wiz->value(QLatin1String("RequiredFeatures")).toStringList()); const QString path = wiz->expander()->expand(m_projectFilePath); setProjectPath(path); setRequiredKitMatcher(KitMatcher([required](const Kit *k) { return k->hasFeatures(required); })); setPreferredKitMatcher(KitMatcher([platform, preferred](const Kit *k) { return k->hasPlatform(platform) && k->hasFeatures(preferred); })); TargetSetupPage::initializePage(); } void JsonKitsPage::cleanupPage() { JsonWizard *wiz = qobject_cast<JsonWizard *>(wizard()); QTC_ASSERT(wiz, return); disconnect(wiz, &JsonWizard::filesReady, this, 0); TargetSetupPage::cleanupPage(); } void JsonKitsPage::setupProjectFiles(const JsonWizard::GeneratorFiles &files) { Project *project = 0; QList<IProjectManager *> managerList = ExtensionSystem::PluginManager::getObjects<IProjectManager>(); foreach (const JsonWizard::GeneratorFile &f, files) { if (f.file.attributes() & Core::GeneratedFile::OpenProjectAttribute) { QString errorMessage; QString path = f.file.path(); const QFileInfo fi(path); if (fi.exists()) path = fi.canonicalFilePath(); Core::MimeType mt = Core::MimeDatabase::findByFile(fi); if (mt.isNull()) continue; foreach (IProjectManager *manager, managerList) { if (manager->mimeType() == mt.type()) { project = manager->openProject(path, &errorMessage); break; } } if (project) { bool success = setupProject(project); if (success) project->saveSettings(); delete project; } } } } } // namespace ProjectExplorer <|endoftext|>
<commit_before>#include "command.hh" #include "shared.hh" #include "store-api.hh" #include "sync.hh" #include "thread-pool.hh" #include <atomic> using namespace nix; struct CmdCopy : StorePathsCommand { std::string srcUri, dstUri; CheckSigsFlag checkSigs = CheckSigs; CmdCopy() { mkFlag(0, "from", "store-uri", "URI of the source Nix store", &srcUri); mkFlag(0, "to", "store-uri", "URI of the destination Nix store", &dstUri); mkFlag() .longName("no-check-sigs") .description("do not require that paths are signed by trusted keys") .set(&checkSigs, NoCheckSigs); } std::string name() override { return "copy"; } std::string description() override { return "copy paths between Nix stores"; } Examples examples() override { return { Example{ "To copy Firefox to the local store to a binary cache in file:///tmp/cache:", "nix copy --to file:///tmp/cache -r $(type -p firefox)" }, }; } ref<Store> createStore() override { return srcUri.empty() ? StoreCommand::createStore() : openStore(srcUri); } void run(ref<Store> srcStore, Paths storePaths) override { if (srcUri.empty() && dstUri.empty()) throw UsageError("you must pass '--from' and/or '--to'"); ref<Store> dstStore = dstUri.empty() ? openStore() : openStore(dstUri); copyPaths(srcStore, dstStore, PathSet(storePaths.begin(), storePaths.end()), NoRepair, checkSigs); } }; static RegisterCommand r1(make_ref<CmdCopy>()); <commit_msg>nix copy: Add examples<commit_after>#include "command.hh" #include "shared.hh" #include "store-api.hh" #include "sync.hh" #include "thread-pool.hh" #include <atomic> using namespace nix; struct CmdCopy : StorePathsCommand { std::string srcUri, dstUri; CheckSigsFlag checkSigs = CheckSigs; CmdCopy() { mkFlag(0, "from", "store-uri", "URI of the source Nix store", &srcUri); mkFlag(0, "to", "store-uri", "URI of the destination Nix store", &dstUri); mkFlag() .longName("no-check-sigs") .description("do not require that paths are signed by trusted keys") .set(&checkSigs, NoCheckSigs); } std::string name() override { return "copy"; } std::string description() override { return "copy paths between Nix stores"; } Examples examples() override { return { Example{ "To copy Firefox from the local store to a binary cache in file:///tmp/cache:", "nix copy --to file:///tmp/cache -r $(type -p firefox)" }, Example{ "To copy the entire current NixOS system closure to another machine via SSH:", "nix copy --to ssh://server -r /run/current-system" }, Example{ "To copy a closure from another machine via SSH:", "nix copy --from ssh://server -r /nix/store/a6cnl93nk1wxnq84brbbwr6hxw9gp2w9-blender-2.79-rc2" }, }; } ref<Store> createStore() override { return srcUri.empty() ? StoreCommand::createStore() : openStore(srcUri); } void run(ref<Store> srcStore, Paths storePaths) override { if (srcUri.empty() && dstUri.empty()) throw UsageError("you must pass '--from' and/or '--to'"); ref<Store> dstStore = dstUri.empty() ? openStore() : openStore(dstUri); copyPaths(srcStore, dstStore, PathSet(storePaths.begin(), storePaths.end()), NoRepair, checkSigs); } }; static RegisterCommand r1(make_ref<CmdCopy>()); <|endoftext|>
<commit_before>#include "command.hh" #include "common-args.hh" #include "shared.hh" #include "store-api.hh" #include "eval.hh" #include "json.hh" #include "value-to-json.hh" using namespace nix; struct CmdEval : MixJSON, InstallablesCommand { bool raw = false; CmdEval() { mkFlag(0, "raw", "print strings unquoted", &raw); } std::string name() override { return "eval"; } std::string description() override { return "evaluate a Nix expression"; } void run(ref<Store> store) override { if (raw && json) throw UsageError("--raw and --json are mutually exclusive"); auto state = getEvalState(); auto jsonOut = json ? std::make_unique<JSONList>(std::cout) : nullptr; for (auto & i : installables) { auto v = i->toValue(*state); if (raw) { std::cout << state->forceString(*v); } else if (json) { PathSet context; auto jsonElem = jsonOut->placeholder(); printValueAsJSON(*state, true, *v, jsonElem, context); } else { state->forceValueDeep(*v); std::cout << *v << "\n"; } } } }; static RegisterCommand r1(make_ref<CmdEval>()); <commit_msg>nix eval: Add examples<commit_after>#include "command.hh" #include "common-args.hh" #include "shared.hh" #include "store-api.hh" #include "eval.hh" #include "json.hh" #include "value-to-json.hh" using namespace nix; struct CmdEval : MixJSON, InstallablesCommand { bool raw = false; CmdEval() { mkFlag(0, "raw", "print strings unquoted", &raw); } std::string name() override { return "eval"; } std::string description() override { return "evaluate a Nix expression"; } Examples examples() override { return { Example{ "To evaluate a Nix expression given on the command line:", "nix eval '(1 + 2)'" }, Example{ "To evaluate a Nix expression from a file or URI:", "nix eval -f channel:nixos-17.09 hello.name" }, Example{ "To get the current version of Nixpkgs:", "nix eval --raw nixpkgs.lib.nixpkgsVersion" }, }; } void run(ref<Store> store) override { if (raw && json) throw UsageError("--raw and --json are mutually exclusive"); auto state = getEvalState(); auto jsonOut = json ? std::make_unique<JSONList>(std::cout) : nullptr; for (auto & i : installables) { auto v = i->toValue(*state); if (raw) { std::cout << state->forceString(*v); } else if (json) { PathSet context; auto jsonElem = jsonOut->placeholder(); printValueAsJSON(*state, true, *v, jsonElem, context); } else { state->forceValueDeep(*v); std::cout << *v << "\n"; } } } }; static RegisterCommand r1(make_ref<CmdEval>()); <|endoftext|>
<commit_before>#include "notebook.h" #include "config.h" #include "directories.h" #include "logging.h" #include <fstream> #include <regex> #include "cmake.h" #include "filesystem.h" #if GTKSOURCEVIEWMM_MAJOR_VERSION > 2 & GTKSOURCEVIEWMM_MINOR_VERSION > 17 #include "gtksourceview-3.0/gtksourceview/gtksourcemap.h" #endif namespace sigc { #ifndef SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE template <typename Functor> struct functor_trait<Functor, false> { typedef decltype (::sigc::mem_fun(std::declval<Functor&>(), &Functor::operator())) _intermediate; typedef typename _intermediate::result_type result_type; typedef Functor functor_type; }; #else SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE #endif } Notebook::TabLabel::TabLabel(const std::string &title) : Gtk::Box(Gtk::ORIENTATION_HORIZONTAL) { set_can_focus(false); label.set_text(title); label.set_can_focus(false); button.set_image_from_icon_name("window-close-symbolic", Gtk::ICON_SIZE_MENU); button.set_can_focus(false); button.set_relief(Gtk::ReliefStyle::RELIEF_NONE); //Based on http://www.micahcarrick.com/gtk-notebook-tabs-with-close-button.html std::string data = ".button {\n" "-GtkButton-default-border : 0px;\n" "-GtkButton-default-outside-border : 0px;\n" "-GtkButton-inner-border: 0px;\n" "-GtkWidget-focus-line-width : 0px;\n" "-GtkWidget-focus-padding : 0px;\n" "padding: 0px;\n" "}"; auto provider = Gtk::CssProvider::create(); provider->load_from_data(data); button.get_style_context()->add_provider(provider, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); pack_start(label, Gtk::PACK_SHRINK); pack_end(button, Gtk::PACK_SHRINK); show_all(); } Notebook::Notebook() : Gtk::Notebook(), last_index(-1) { Gsv::init(); signal_switch_page().connect([this](Gtk::Widget* page, guint page_num) { last_index=-1; }); } int Notebook::size() { return get_n_pages(); } Source::View* Notebook::get_view(int page) { return source_views.at(get_index(page)); } size_t Notebook::get_index(int page) { for(size_t c=0;c<hboxes.size();c++) { if(page_num(*hboxes.at(c))==page) return c; } return -1; } Source::View* Notebook::get_current_view() { return get_view(get_current_page()); } void Notebook::open(const boost::filesystem::path &file_path) { JDEBUG("start"); for(int c=0;c<size();c++) { if(file_path==get_view(c)->file_path) { set_current_page(c); get_current_view()->grab_focus(); return; } } if(boost::filesystem::exists(file_path)) { std::ifstream can_read(file_path.string()); if(!can_read) { Terminal::get().print("Error: could not open "+file_path.string()+"\n", true); return; } can_read.close(); } auto language=Source::guess_language(file_path); boost::filesystem::path project_path; auto &directories=Directories::get(); if(directories.cmake && directories.cmake->project_path!="" && file_path.generic_string().substr(0, directories.cmake->project_path.generic_string().size()+1)==directories.cmake->project_path.generic_string()+'/') project_path=directories.cmake->project_path; else { project_path=file_path.parent_path(); CMake cmake(project_path); if(cmake.project_path!="") { project_path=cmake.project_path; Terminal::get().print("Project path for "+file_path.string()+" set to "+project_path.string()+"\n"); } } if(language && (language->get_id()=="chdr" || language->get_id()=="cpphdr" || language->get_id()=="c" || language->get_id()=="cpp" || language->get_id()=="objc")) { if(boost::filesystem::exists(project_path.string()+"/CMakeLists.txt") && !boost::filesystem::exists(CMake::get_default_build_path(project_path)/"compile_commands.json")) CMake::create_compile_commands(project_path); source_views.emplace_back(new Source::ClangView(file_path, project_path, language)); } else source_views.emplace_back(new Source::GenericView(file_path, project_path, language)); source_views.back()->on_update_status=[this](Source::View* view, const std::string &status_text) { if(get_current_page()!=-1 && get_current_view()==view) status.set_text(status_text+" "); }; source_views.back()->on_update_info=[this](Source::View* view, const std::string &info_text) { if(get_current_page()!=-1 && get_current_view()==view) info.set_text(" "+info_text); }; scrolled_windows.emplace_back(new Gtk::ScrolledWindow()); hboxes.emplace_back(new Gtk::HBox()); scrolled_windows.back()->add(*source_views.back()); hboxes.back()->pack_start(*scrolled_windows.back()); #if GTKSOURCEVIEWMM_MAJOR_VERSION > 2 & GTKSOURCEVIEWMM_MINOR_VERSION > 17 source_maps.emplace_back(Glib::wrap(gtk_source_map_new())); gtk_source_map_set_view(GTK_SOURCE_MAP(source_maps.back()->gobj()), source_views.back()->gobj()); #endif configure(source_views.size()-1); //Set up tab label std::string title=file_path.filename().string(); tab_labels.emplace_back(new TabLabel(title)); auto source_view=source_views.back(); tab_labels.back()->button.signal_clicked().connect([this, source_view](){ for(int c=0;c<size();c++) { if(get_view(c)==source_view) { close(c); break; } } }); append_page(*hboxes.back(), *tab_labels.back()); set_tab_reorderable(*hboxes.back(), true); show_all_children(); size_t last_index_tmp=-1; if(get_current_page()!=-1) last_index_tmp=get_index(get_current_page()); set_current_page(size()-1); last_index=last_index_tmp; set_focus_child(*source_views.back()); get_current_view()->get_buffer()->set_modified(false); get_current_view()->grab_focus(); //Add star on tab label when the page is not saved: get_current_view()->get_buffer()->signal_modified_changed().connect([this, source_view]() { std::string title=source_view->file_path.filename().string(); if(source_view->get_buffer()->get_modified()) title+="*"; int page=-1; for(int c=0;c<size();c++) { if(get_view(c)==source_view) { page=c; break; } } if(page!=-1) tab_labels.at(get_index(page))->label.set_text(title); }); JDEBUG("end"); } void Notebook::configure(int view_nr) { #if GTKSOURCEVIEWMM_MAJOR_VERSION > 2 & GTKSOURCEVIEWMM_MINOR_VERSION > 17 auto source_font_description=Pango::FontDescription(Config::get().source.font); auto source_map_font_desc=Pango::FontDescription(static_cast<std::string>(source_font_description.get_family())+" "+Config::get().source.map_font_size); source_maps.at(view_nr)->override_font(source_map_font_desc); if(Config::get().source.show_map) { if(hboxes.at(view_nr)->get_children().size()==1) hboxes.at(view_nr)->pack_end(*source_maps.at(view_nr), Gtk::PACK_SHRINK); } else if(hboxes.at(view_nr)->get_children().size()==2) hboxes.at(view_nr)->remove(*source_maps.at(view_nr)); #endif } bool Notebook::save(int page) { JDEBUG("start"); if(page>=size()) { JDEBUG("end false"); return false; } auto view=get_view(page); if (view->file_path != "" && view->get_buffer()->get_modified()) { //Remove trailing whitespace characters on save, and add trailing newline if missing if(Config::get().source.cleanup_whitespace_characters) { auto buffer=view->get_buffer(); buffer->begin_user_action(); for(int line=0;line<buffer->get_line_count();line++) { auto iter=buffer->get_iter_at_line(line); auto end_iter=iter; while(!end_iter.ends_line()) end_iter.forward_char(); if(iter==end_iter) continue; iter=end_iter; while(!iter.starts_line() && (*iter==' ' || *iter=='\t' || iter.ends_line())) iter.backward_char(); if(*iter!=' ' && *iter!='\t') iter.forward_char(); if(iter==end_iter) continue; buffer->erase(iter, end_iter); } auto iter=buffer->end(); if(!iter.starts_line()) buffer->insert(buffer->end(), "\n"); buffer->end_user_action(); } if(filesystem::write(view->file_path, view->get_buffer())) { if(auto clang_view=dynamic_cast<Source::ClangView*>(view)) { if(clang_view->language->get_id()=="chdr" || clang_view->language->get_id()=="cpphdr") { for(auto a_view: source_views) { if(auto a_clang_view=dynamic_cast<Source::ClangView*>(a_view)) { if(clang_view!=a_clang_view) a_clang_view->soft_reparse_needed=true; } } } } view->get_buffer()->set_modified(false); //If CMakeLists.txt have been modified: boost::filesystem::path project_path; if(view->file_path.filename()=="CMakeLists.txt") { auto &directories=Directories::get(); if(directories.cmake && directories.cmake->project_path!="" && view->file_path.generic_string().substr(0, directories.cmake->project_path.generic_string().size()+1)==directories.cmake->project_path.generic_string()+'/' && CMake::create_compile_commands(directories.cmake->project_path)) { project_path=directories.cmake->project_path; } else { CMake cmake(view->file_path.parent_path()); if(cmake.project_path!="" && CMake::create_compile_commands(cmake.project_path)) { project_path=cmake.project_path; } } if(project_path!="") { for(auto source_view: source_views) { if(auto source_clang_view=dynamic_cast<Source::ClangView*>(source_view)) { if(project_path==source_clang_view->project_path) source_clang_view->full_reparse_needed=true; } } } } JDEBUG("end true"); return true; } Terminal::get().print("Error: could not save file " +view->file_path.string()+"\n", true); } JDEBUG("end false"); return false; } bool Notebook::save_current() { if(get_current_page()==-1) return false; return save(get_current_page()); } bool Notebook::close(int page) { JDEBUG("start"); if (page!=-1) { auto view=get_view(page); if(view->get_buffer()->get_modified()){ if(!save_modified_dialog(page)) { JDEBUG("end false"); return false; } } auto index=get_index(page); if(page==get_current_page()) { if(last_index!=static_cast<size_t>(-1)) { set_current_page(page_num(*hboxes.at(last_index))); last_index=-1; } } else if(index==last_index) last_index=-1; else if(index<last_index && last_index!=static_cast<size_t>(-1)) last_index--; remove_page(page); #if GTKSOURCEVIEWMM_MAJOR_VERSION > 2 & GTKSOURCEVIEWMM_MINOR_VERSION > 17 source_maps.erase(source_maps.begin()+index); #endif auto source_view=source_views.at(index); if(auto source_clang_view=dynamic_cast<Source::ClangView*>(source_view)) source_clang_view->async_delete(); else delete source_view; source_views.erase(source_views.begin()+index); scrolled_windows.erase(scrolled_windows.begin()+index); hboxes.erase(hboxes.begin()+index); tab_labels.erase(tab_labels.begin()+index); } JDEBUG("end true"); return true; } bool Notebook::close_current_page() { if(get_current_page()==-1) return false; return close(get_current_page()); } boost::filesystem::path Notebook::get_current_folder() { boost::filesystem::path current_path; if(get_current_page()!=-1) current_path=get_current_view()->project_path; else current_path=Directories::get().current_path; return current_path; } bool Notebook::save_modified_dialog(int page) { Gtk::MessageDialog dialog((Gtk::Window&)(*get_toplevel()), "Save file!", false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_YES_NO); dialog.set_default_response(Gtk::RESPONSE_YES); dialog.set_secondary_text("Do you want to save: " + get_view(page)->file_path.string()+" ?"); int result = dialog.run(); if(result==Gtk::RESPONSE_YES) { save(page); return true; } else if(result==Gtk::RESPONSE_NO) { return true; } else { return false; } } <commit_msg>cmake error messages no longer appear twice when saving CMakeLists.txt<commit_after>#include "notebook.h" #include "config.h" #include "directories.h" #include "logging.h" #include <fstream> #include <regex> #include "cmake.h" #include "filesystem.h" #if GTKSOURCEVIEWMM_MAJOR_VERSION > 2 & GTKSOURCEVIEWMM_MINOR_VERSION > 17 #include "gtksourceview-3.0/gtksourceview/gtksourcemap.h" #endif namespace sigc { #ifndef SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE template <typename Functor> struct functor_trait<Functor, false> { typedef decltype (::sigc::mem_fun(std::declval<Functor&>(), &Functor::operator())) _intermediate; typedef typename _intermediate::result_type result_type; typedef Functor functor_type; }; #else SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE #endif } Notebook::TabLabel::TabLabel(const std::string &title) : Gtk::Box(Gtk::ORIENTATION_HORIZONTAL) { set_can_focus(false); label.set_text(title); label.set_can_focus(false); button.set_image_from_icon_name("window-close-symbolic", Gtk::ICON_SIZE_MENU); button.set_can_focus(false); button.set_relief(Gtk::ReliefStyle::RELIEF_NONE); //Based on http://www.micahcarrick.com/gtk-notebook-tabs-with-close-button.html std::string data = ".button {\n" "-GtkButton-default-border : 0px;\n" "-GtkButton-default-outside-border : 0px;\n" "-GtkButton-inner-border: 0px;\n" "-GtkWidget-focus-line-width : 0px;\n" "-GtkWidget-focus-padding : 0px;\n" "padding: 0px;\n" "}"; auto provider = Gtk::CssProvider::create(); provider->load_from_data(data); button.get_style_context()->add_provider(provider, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); pack_start(label, Gtk::PACK_SHRINK); pack_end(button, Gtk::PACK_SHRINK); show_all(); } Notebook::Notebook() : Gtk::Notebook(), last_index(-1) { Gsv::init(); signal_switch_page().connect([this](Gtk::Widget* page, guint page_num) { last_index=-1; }); } int Notebook::size() { return get_n_pages(); } Source::View* Notebook::get_view(int page) { return source_views.at(get_index(page)); } size_t Notebook::get_index(int page) { for(size_t c=0;c<hboxes.size();c++) { if(page_num(*hboxes.at(c))==page) return c; } return -1; } Source::View* Notebook::get_current_view() { return get_view(get_current_page()); } void Notebook::open(const boost::filesystem::path &file_path) { JDEBUG("start"); for(int c=0;c<size();c++) { if(file_path==get_view(c)->file_path) { set_current_page(c); get_current_view()->grab_focus(); return; } } if(boost::filesystem::exists(file_path)) { std::ifstream can_read(file_path.string()); if(!can_read) { Terminal::get().print("Error: could not open "+file_path.string()+"\n", true); return; } can_read.close(); } auto language=Source::guess_language(file_path); boost::filesystem::path project_path; auto &directories=Directories::get(); if(directories.cmake && directories.cmake->project_path!="" && file_path.generic_string().substr(0, directories.cmake->project_path.generic_string().size()+1)==directories.cmake->project_path.generic_string()+'/') project_path=directories.cmake->project_path; else { project_path=file_path.parent_path(); CMake cmake(project_path); if(cmake.project_path!="") { project_path=cmake.project_path; Terminal::get().print("Project path for "+file_path.string()+" set to "+project_path.string()+"\n"); } } if(language && (language->get_id()=="chdr" || language->get_id()=="cpphdr" || language->get_id()=="c" || language->get_id()=="cpp" || language->get_id()=="objc")) { if(boost::filesystem::exists(project_path.string()+"/CMakeLists.txt") && !boost::filesystem::exists(CMake::get_default_build_path(project_path)/"compile_commands.json")) CMake::create_compile_commands(project_path); source_views.emplace_back(new Source::ClangView(file_path, project_path, language)); } else source_views.emplace_back(new Source::GenericView(file_path, project_path, language)); source_views.back()->on_update_status=[this](Source::View* view, const std::string &status_text) { if(get_current_page()!=-1 && get_current_view()==view) status.set_text(status_text+" "); }; source_views.back()->on_update_info=[this](Source::View* view, const std::string &info_text) { if(get_current_page()!=-1 && get_current_view()==view) info.set_text(" "+info_text); }; scrolled_windows.emplace_back(new Gtk::ScrolledWindow()); hboxes.emplace_back(new Gtk::HBox()); scrolled_windows.back()->add(*source_views.back()); hboxes.back()->pack_start(*scrolled_windows.back()); #if GTKSOURCEVIEWMM_MAJOR_VERSION > 2 & GTKSOURCEVIEWMM_MINOR_VERSION > 17 source_maps.emplace_back(Glib::wrap(gtk_source_map_new())); gtk_source_map_set_view(GTK_SOURCE_MAP(source_maps.back()->gobj()), source_views.back()->gobj()); #endif configure(source_views.size()-1); //Set up tab label std::string title=file_path.filename().string(); tab_labels.emplace_back(new TabLabel(title)); auto source_view=source_views.back(); tab_labels.back()->button.signal_clicked().connect([this, source_view](){ for(int c=0;c<size();c++) { if(get_view(c)==source_view) { close(c); break; } } }); append_page(*hboxes.back(), *tab_labels.back()); set_tab_reorderable(*hboxes.back(), true); show_all_children(); size_t last_index_tmp=-1; if(get_current_page()!=-1) last_index_tmp=get_index(get_current_page()); set_current_page(size()-1); last_index=last_index_tmp; set_focus_child(*source_views.back()); get_current_view()->get_buffer()->set_modified(false); get_current_view()->grab_focus(); //Add star on tab label when the page is not saved: get_current_view()->get_buffer()->signal_modified_changed().connect([this, source_view]() { std::string title=source_view->file_path.filename().string(); if(source_view->get_buffer()->get_modified()) title+="*"; int page=-1; for(int c=0;c<size();c++) { if(get_view(c)==source_view) { page=c; break; } } if(page!=-1) tab_labels.at(get_index(page))->label.set_text(title); }); JDEBUG("end"); } void Notebook::configure(int view_nr) { #if GTKSOURCEVIEWMM_MAJOR_VERSION > 2 & GTKSOURCEVIEWMM_MINOR_VERSION > 17 auto source_font_description=Pango::FontDescription(Config::get().source.font); auto source_map_font_desc=Pango::FontDescription(static_cast<std::string>(source_font_description.get_family())+" "+Config::get().source.map_font_size); source_maps.at(view_nr)->override_font(source_map_font_desc); if(Config::get().source.show_map) { if(hboxes.at(view_nr)->get_children().size()==1) hboxes.at(view_nr)->pack_end(*source_maps.at(view_nr), Gtk::PACK_SHRINK); } else if(hboxes.at(view_nr)->get_children().size()==2) hboxes.at(view_nr)->remove(*source_maps.at(view_nr)); #endif } bool Notebook::save(int page) { JDEBUG("start"); if(page>=size()) { JDEBUG("end false"); return false; } auto view=get_view(page); if (view->file_path != "" && view->get_buffer()->get_modified()) { //Remove trailing whitespace characters on save, and add trailing newline if missing if(Config::get().source.cleanup_whitespace_characters) { auto buffer=view->get_buffer(); buffer->begin_user_action(); for(int line=0;line<buffer->get_line_count();line++) { auto iter=buffer->get_iter_at_line(line); auto end_iter=iter; while(!end_iter.ends_line()) end_iter.forward_char(); if(iter==end_iter) continue; iter=end_iter; while(!iter.starts_line() && (*iter==' ' || *iter=='\t' || iter.ends_line())) iter.backward_char(); if(*iter!=' ' && *iter!='\t') iter.forward_char(); if(iter==end_iter) continue; buffer->erase(iter, end_iter); } auto iter=buffer->end(); if(!iter.starts_line()) buffer->insert(buffer->end(), "\n"); buffer->end_user_action(); } if(filesystem::write(view->file_path, view->get_buffer())) { if(auto clang_view=dynamic_cast<Source::ClangView*>(view)) { if(clang_view->language->get_id()=="chdr" || clang_view->language->get_id()=="cpphdr") { for(auto a_view: source_views) { if(auto a_clang_view=dynamic_cast<Source::ClangView*>(a_view)) { if(clang_view!=a_clang_view) a_clang_view->soft_reparse_needed=true; } } } } view->get_buffer()->set_modified(false); //If CMakeLists.txt have been modified: boost::filesystem::path project_path; if(view->file_path.filename()=="CMakeLists.txt") { auto &directories=Directories::get(); if(directories.cmake && directories.cmake->project_path!="" && view->file_path.generic_string().substr(0, directories.cmake->project_path.generic_string().size()+1)==directories.cmake->project_path.generic_string()+'/') { if(CMake::create_compile_commands(directories.cmake->project_path)) project_path=directories.cmake->project_path; } else { CMake cmake(view->file_path.parent_path()); if(cmake.project_path!="" && CMake::create_compile_commands(cmake.project_path)) project_path=cmake.project_path; } if(project_path!="") { for(auto source_view: source_views) { if(auto source_clang_view=dynamic_cast<Source::ClangView*>(source_view)) { if(project_path==source_clang_view->project_path) source_clang_view->full_reparse_needed=true; } } } } JDEBUG("end true"); return true; } Terminal::get().print("Error: could not save file " +view->file_path.string()+"\n", true); } JDEBUG("end false"); return false; } bool Notebook::save_current() { if(get_current_page()==-1) return false; return save(get_current_page()); } bool Notebook::close(int page) { JDEBUG("start"); if (page!=-1) { auto view=get_view(page); if(view->get_buffer()->get_modified()){ if(!save_modified_dialog(page)) { JDEBUG("end false"); return false; } } auto index=get_index(page); if(page==get_current_page()) { if(last_index!=static_cast<size_t>(-1)) { set_current_page(page_num(*hboxes.at(last_index))); last_index=-1; } } else if(index==last_index) last_index=-1; else if(index<last_index && last_index!=static_cast<size_t>(-1)) last_index--; remove_page(page); #if GTKSOURCEVIEWMM_MAJOR_VERSION > 2 & GTKSOURCEVIEWMM_MINOR_VERSION > 17 source_maps.erase(source_maps.begin()+index); #endif auto source_view=source_views.at(index); if(auto source_clang_view=dynamic_cast<Source::ClangView*>(source_view)) source_clang_view->async_delete(); else delete source_view; source_views.erase(source_views.begin()+index); scrolled_windows.erase(scrolled_windows.begin()+index); hboxes.erase(hboxes.begin()+index); tab_labels.erase(tab_labels.begin()+index); } JDEBUG("end true"); return true; } bool Notebook::close_current_page() { if(get_current_page()==-1) return false; return close(get_current_page()); } boost::filesystem::path Notebook::get_current_folder() { boost::filesystem::path current_path; if(get_current_page()!=-1) current_path=get_current_view()->project_path; else current_path=Directories::get().current_path; return current_path; } bool Notebook::save_modified_dialog(int page) { Gtk::MessageDialog dialog((Gtk::Window&)(*get_toplevel()), "Save file!", false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_YES_NO); dialog.set_default_response(Gtk::RESPONSE_YES); dialog.set_secondary_text("Do you want to save: " + get_view(page)->file_path.string()+" ?"); int result = dialog.run(); if(result==Gtk::RESPONSE_YES) { save(page); return true; } else if(result==Gtk::RESPONSE_NO) { return true; } else { return false; } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $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 Technology Preview License Agreement accompanying ** this package. ** ** 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. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qmessageservice.h" #include "qmessageservice_symbian_p.h" #include "qfsengine_symbian_p.h" #include "qmessage_symbian_p.h" #include "symbianhelpers_p.h" #include "qmessageaccount.h" #include "qmessageaccount_p.h" #include "qmessageaccountfilter.h" #include "qmessageaccountfilter_p.h" #include <emailinterfacefactory.h> #include <QTextCodec> #include <emailapidefs.h> #include <memailmailbox.h> using namespace EmailInterface; QTM_BEGIN_NAMESPACE CFSEngine::CFSEngine() { CEmailInterfaceFactory* factory = CEmailInterfaceFactory::NewL(); CleanupStack::PushL(factory); MEmailInterface* ifPtr = factory->InterfaceL(KEmailClientApiInterface); m_clientApi = static_cast<MEmailClientApi*>(ifPtr); /*CleanupReleasePushL(clientApi); RMailboxPtrArray mailboxes; clientApi->GetMailboxesL(mailboxes); CleanupStack::PopAndDestroy(2); // clientApi and factory*/ CleanupStack::PopAndDestroy(factory); // factory } CFSEngine::~CFSEngine() { m_clientApi->Release(); } CFSEngine* CFSEngine::instance() { } QMessageAccountIdList CFSEngine::queryAccounts(const QMessageAccountFilter &filter, const QMessageAccountSortOrder &sortOrder, uint limit, uint offset) const { QMessageAccountIdList accountIds; TRAPD(err, updateEmailAccountsL()); QMessageAccountFilterPrivate* privateMessageAccountFilter = QMessageAccountFilterPrivate::implementation(filter); if (filter.isEmpty()) { if (!privateMessageAccountFilter->_notFilter) { // All accounts are returned for empty filter foreach (QMessageAccount value, m_accounts) { accountIds.append(value.id()); } } } else { if (privateMessageAccountFilter->_valid) { foreach (QMessageAccount value, m_accounts) { if (privateMessageAccountFilter->filter(value)) { accountIds.append(value.id()); } } } else { foreach (QMessageAccount value, m_accounts) { if (privateMessageAccountFilter->filter(value)) { accountIds.append(value.id()); } } } } //TODO: Sort accounts according to QMessageAccountSortOrder return accountIds; } int CFSEngine::countAccounts(const QMessageAccountFilter &filter) const { return 0; } QMessageAccount CFSEngine::account(const QMessageAccountId &id) const { TRAPD(err, updateEmailAccountsL()); Q_UNUSED(err) return m_accounts[id.toString()]; } QMessageAccountId CFSEngine::defaultAccount(QMessage::Type type) const { return QMessageAccountId(); } void CFSEngine::updateEmailAccountsL() const { QStringList keys = m_accounts.keys(); RMailboxPtrArray mailboxes; m_clientApi->GetMailboxesL(mailboxes); CleanupClosePushL(mailboxes); for (TInt i = 0; i < mailboxes.Count(); i++) { MEmailMailbox *mailbox = mailboxes[i]; QString idAsString = QString::number(mailbox->MailboxId().iId); QString fsIdAsString = SymbianHelpers::addFreestylePrefix(idAsString); if (!m_accounts.contains(fsIdAsString)) { QMessageAccount account = QMessageAccountPrivate::from( QMessageAccountId(SymbianHelpers::addFreestylePrefix(fsIdAsString)), QString::fromUtf16(mailbox->MailboxName().Ptr(), mailbox->MailboxName().Length()), 0, //TODO: ID for IMAP service if needed 0, //TODO: ID for SMTP service if needed QMessage::Email); m_accounts.insert(fsIdAsString, account); } else { keys.removeOne(fsIdAsString); } } CleanupStack::PopAndDestroy(&mailboxes); // mailboxes for (int i=0; i < keys.count(); i++) { m_accounts.remove(keys[i]); } } bool CFSEngine::addMessage(QMessage* message) { bool retVal = false; return retVal; } bool CFSEngine::updateMessage(QMessage* message) { bool retVal = false; return retVal; } bool CFSEngine::removeMessage(const QMessageId &id, QMessageManager::RemovalOption option) { bool retVal = false; return retVal; } bool CFSEngine::showMessage(const QMessageId &id) { return false; } bool CFSEngine::composeMessage(const QMessage &message) { bool retVal = true; return retVal; } bool CFSEngine::retrieve(const QMessageId &messageId, const QMessageContentContainerId& id) { return false; } bool CFSEngine::retrieveBody(const QMessageId& id) { return false; } bool CFSEngine::retrieveHeader(const QMessageId& id) { return false; } bool CFSEngine::exportUpdates(const QMessageAccountId &id) { return false; } bool CFSEngine::removeMessages(const QMessageFilter& /*filter*/, QMessageManager::RemovalOption /*option*/) { return false; } bool CFSEngine::queryMessages(QMessageServicePrivate& privateService, const QMessageFilter &filter, const QMessageSortOrder &sortOrder, uint limit, uint offset) const { return false; } bool CFSEngine::queryMessages(QMessageServicePrivate& privateService, const QMessageFilter &filter, const QString &body, QMessageDataComparator::MatchFlags matchFlags, const QMessageSortOrder &sortOrder, uint limit, uint offset) const { return false; } bool CFSEngine::countMessages(QMessageServicePrivate& privateService, const QMessageFilter &filter) { return false; } void CFSEngine::filterAndOrderMessagesReady(bool success, int operationId, QMessageIdList ids, int numberOfHandledFilters, bool resultSetOrdered) { } QMessageFolderIdList CFSEngine::queryFolders(const QMessageFolderFilter &filter, const QMessageFolderSortOrder &sortOrder, uint limit, uint offset) const { QMessageFolderIdList ids; return ids; } int CFSEngine::countFolders(const QMessageFolderFilter &filter) const { return queryFolders(filter, QMessageFolderSortOrder(), 0, 0).count(); } QMessageFolder CFSEngine::folder(const QMessageFolderId &id) const { QMessageFolder folder; return folder; } QMessage CFSEngine::message(const QMessageId& id) const { QMessage message; return message; } bool CFSEngine::storeEmail(QMessage &message) { return false; } bool CFSEngine::sendEmail(QMessage &message) { return false; } QString CFSEngine::attachmentTextContent(long int messageId, unsigned int attachmentId, const QByteArray &charset) { QString result; QByteArray data = attachmentContent(messageId, attachmentId); if (!data.isEmpty()) { // Convert attachment data to string form QTextCodec *codec; if (!charset.isEmpty()) { codec = QTextCodec::codecForName(charset); } else { codec = QTextCodec::codecForLocale(); } if (codec) { result = codec->toUnicode(data); } } return result; } QByteArray CFSEngine::attachmentContent(long int messageId, unsigned int attachmentId) { // TODO: QByteArray result; return result; } QMessageManager::NotificationFilterId CFSEngine::registerNotificationFilter(QMessageStorePrivate& aPrivateStore, const QMessageFilter &filter) { int filterId; return filterId; } void CFSEngine::unregisterNotificationFilter(QMessageManager::NotificationFilterId notificationFilterId) { } QTM_END_NAMESPACE <commit_msg>Symbian: count accounts for fs messaging<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $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 Technology Preview License Agreement accompanying ** this package. ** ** 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. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qmessageservice.h" #include "qmessageservice_symbian_p.h" #include "qfsengine_symbian_p.h" #include "qmessage_symbian_p.h" #include "symbianhelpers_p.h" #include "qmessageaccount.h" #include "qmessageaccount_p.h" #include "qmessageaccountfilter.h" #include "qmessageaccountfilter_p.h" #include <emailinterfacefactory.h> #include <QTextCodec> #include <emailapidefs.h> #include <memailmailbox.h> using namespace EmailInterface; QTM_BEGIN_NAMESPACE CFSEngine::CFSEngine() { CEmailInterfaceFactory* factory = CEmailInterfaceFactory::NewL(); CleanupStack::PushL(factory); MEmailInterface* ifPtr = factory->InterfaceL(KEmailClientApiInterface); m_clientApi = static_cast<MEmailClientApi*>(ifPtr); /*CleanupReleasePushL(clientApi); RMailboxPtrArray mailboxes; clientApi->GetMailboxesL(mailboxes); CleanupStack::PopAndDestroy(2); // clientApi and factory*/ CleanupStack::PopAndDestroy(factory); // factory } CFSEngine::~CFSEngine() { m_clientApi->Release(); } CFSEngine* CFSEngine::instance() { } QMessageAccountIdList CFSEngine::queryAccounts(const QMessageAccountFilter &filter, const QMessageAccountSortOrder &sortOrder, uint limit, uint offset) const { QMessageAccountIdList accountIds; TRAPD(err, updateEmailAccountsL()); QMessageAccountFilterPrivate* privateMessageAccountFilter = QMessageAccountFilterPrivate::implementation(filter); if (filter.isEmpty()) { if (!privateMessageAccountFilter->_notFilter) { // All accounts are returned for empty filter foreach (QMessageAccount value, m_accounts) { accountIds.append(value.id()); } } } else { if (privateMessageAccountFilter->_valid) { foreach (QMessageAccount value, m_accounts) { if (privateMessageAccountFilter->filter(value)) { accountIds.append(value.id()); } } } else { foreach (QMessageAccount value, m_accounts) { if (privateMessageAccountFilter->filter(value)) { accountIds.append(value.id()); } } } } //TODO: Sort accounts according to QMessageAccountSortOrder return accountIds; } int CFSEngine::countAccounts(const QMessageAccountFilter &filter) const { return queryAccounts(filter, QMessageAccountSortOrder(), 0, 0).count(); } QMessageAccount CFSEngine::account(const QMessageAccountId &id) const { TRAPD(err, updateEmailAccountsL()); Q_UNUSED(err) return m_accounts[id.toString()]; } QMessageAccountId CFSEngine::defaultAccount(QMessage::Type type) const { return QMessageAccountId(); } void CFSEngine::updateEmailAccountsL() const { QStringList keys = m_accounts.keys(); RMailboxPtrArray mailboxes; m_clientApi->GetMailboxesL(mailboxes); CleanupClosePushL(mailboxes); for (TInt i = 0; i < mailboxes.Count(); i++) { MEmailMailbox *mailbox = mailboxes[i]; QString idAsString = QString::number(mailbox->MailboxId().iId); QString fsIdAsString = SymbianHelpers::addFreestylePrefix(idAsString); if (!m_accounts.contains(fsIdAsString)) { QMessageAccount account = QMessageAccountPrivate::from( QMessageAccountId(SymbianHelpers::addFreestylePrefix(fsIdAsString)), QString::fromUtf16(mailbox->MailboxName().Ptr(), mailbox->MailboxName().Length()), 0, //TODO: ID for IMAP service if needed 0, //TODO: ID for SMTP service if needed QMessage::Email); m_accounts.insert(fsIdAsString, account); } else { keys.removeOne(fsIdAsString); } } CleanupStack::PopAndDestroy(&mailboxes); // mailboxes for (int i=0; i < keys.count(); i++) { m_accounts.remove(keys[i]); } } bool CFSEngine::addMessage(QMessage* message) { bool retVal = false; return retVal; } bool CFSEngine::updateMessage(QMessage* message) { bool retVal = false; return retVal; } bool CFSEngine::removeMessage(const QMessageId &id, QMessageManager::RemovalOption option) { bool retVal = false; return retVal; } bool CFSEngine::showMessage(const QMessageId &id) { return false; } bool CFSEngine::composeMessage(const QMessage &message) { bool retVal = true; return retVal; } bool CFSEngine::retrieve(const QMessageId &messageId, const QMessageContentContainerId& id) { return false; } bool CFSEngine::retrieveBody(const QMessageId& id) { return false; } bool CFSEngine::retrieveHeader(const QMessageId& id) { return false; } bool CFSEngine::exportUpdates(const QMessageAccountId &id) { return false; } bool CFSEngine::removeMessages(const QMessageFilter& /*filter*/, QMessageManager::RemovalOption /*option*/) { return false; } bool CFSEngine::queryMessages(QMessageServicePrivate& privateService, const QMessageFilter &filter, const QMessageSortOrder &sortOrder, uint limit, uint offset) const { return false; } bool CFSEngine::queryMessages(QMessageServicePrivate& privateService, const QMessageFilter &filter, const QString &body, QMessageDataComparator::MatchFlags matchFlags, const QMessageSortOrder &sortOrder, uint limit, uint offset) const { return false; } bool CFSEngine::countMessages(QMessageServicePrivate& privateService, const QMessageFilter &filter) { return false; } void CFSEngine::filterAndOrderMessagesReady(bool success, int operationId, QMessageIdList ids, int numberOfHandledFilters, bool resultSetOrdered) { } QMessageFolderIdList CFSEngine::queryFolders(const QMessageFolderFilter &filter, const QMessageFolderSortOrder &sortOrder, uint limit, uint offset) const { QMessageFolderIdList ids; return ids; } int CFSEngine::countFolders(const QMessageFolderFilter &filter) const { return queryFolders(filter, QMessageFolderSortOrder(), 0, 0).count(); } QMessageFolder CFSEngine::folder(const QMessageFolderId &id) const { QMessageFolder folder; return folder; } QMessage CFSEngine::message(const QMessageId& id) const { QMessage message; return message; } bool CFSEngine::storeEmail(QMessage &message) { return false; } bool CFSEngine::sendEmail(QMessage &message) { return false; } QString CFSEngine::attachmentTextContent(long int messageId, unsigned int attachmentId, const QByteArray &charset) { QString result; QByteArray data = attachmentContent(messageId, attachmentId); if (!data.isEmpty()) { // Convert attachment data to string form QTextCodec *codec; if (!charset.isEmpty()) { codec = QTextCodec::codecForName(charset); } else { codec = QTextCodec::codecForLocale(); } if (codec) { result = codec->toUnicode(data); } } return result; } QByteArray CFSEngine::attachmentContent(long int messageId, unsigned int attachmentId) { // TODO: QByteArray result; return result; } QMessageManager::NotificationFilterId CFSEngine::registerNotificationFilter(QMessageStorePrivate& aPrivateStore, const QMessageFilter &filter) { int filterId; return filterId; } void CFSEngine::unregisterNotificationFilter(QMessageManager::NotificationFilterId notificationFilterId) { } QTM_END_NAMESPACE <|endoftext|>
<commit_before>#ifndef RBX_VM_H #define RBX_VM_H #include "missing/time.h" #include "globals.hpp" #include "memory/object_mark.hpp" #include "memory/managed.hpp" #include "vm_thread_state.hpp" #include "thread_nexus.hpp" #include "metrics.hpp" #include "util/thread.hpp" #include "memory/variable_buffer.hpp" #include "memory/root_buffer.hpp" #include "memory/slab.hpp" #include "shared_state.hpp" #include "unwind_info.hpp" #include "fiber_stack.hpp" #include "sodium/randombytes.h" #include <vector> #include <setjmp.h> #include <stdint.h> namespace llvm { class Module; } namespace rbxti { class Env; } namespace rubinius { class Exception; class LLVMState; namespace event { class Loop; } namespace memory { class GarbageCollector; class WriteBarrier; } class Assertion; class CallSiteInformation; class Channel; class CompiledCode; class ConfigParser; class Configuration; class Fiber; class GlobalCache; class LookupTable; class Memory; class NativeMethodEnvironment; class Object; class Park; class Primitives; class SharedState; class String; class Symbol; class SymbolTable; class Tuple; class TypeError; class TypeInfo; class VariableScope; struct CallFrame; enum MethodMissingReason { eNone, ePrivate, eProtected, eSuper, eVCall, eNormal }; enum ConstantMissingReason { vFound, vPrivate, vNonExistent }; /** * Represents an execution context for running Ruby code. * * Each Ruby thread is backed by an instance of this class, as well as an * instance of the Thread class. Thread manages the (Ruby visible) thread- * related state, while this class manages the execution machinery for * running Ruby code. */ class VM : public memory::ManagedThread { friend class State; private: UnwindInfoSet unwinds_; CallFrame* call_frame_; ThreadNexus* thread_nexus_; CallSiteInformation* saved_call_site_information_; FiberStacks fiber_stacks_; Park* park_; void* stack_start_; size_t stack_size_; void* current_stack_start_; size_t current_stack_size_; bool interrupt_with_signal_; bool interrupt_by_kill_; bool check_local_interrupts_; bool thread_step_; utilities::thread::SpinLock interrupt_lock_; MethodMissingReason method_missing_reason_; ConstantMissingReason constant_missing_reason_; bool zombie_; bool allocation_tracking_; bool main_thread_; ThreadNexus::Phase thread_phase_; uint32_t profile_interval_; uint32_t profile_counter_; CompiledCode** profile_; uint64_t profile_sample_count_; uint64_t profile_report_interval_; native_int max_profile_entries_; native_int min_profile_sample_count_; public: /* Data members */ SharedState& shared; memory::TypedRoot<Channel*> waiting_channel_; memory::TypedRoot<Exception*> interrupted_exception_; /// The Thread object for this VM state memory::TypedRoot<Thread*> thread; /// The current fiber running on this thread memory::TypedRoot<Fiber*> current_fiber; /// Root fiber, if any (lazily initialized) memory::TypedRoot<Fiber*> root_fiber; /// Object that waits for inflation memory::TypedRoot<Object*> waiting_object_; uint64_t start_time_; NativeMethodEnvironment* native_method_environment; void (*custom_wakeup_)(void*); void* custom_wakeup_data_; VMThreadState thread_state_; public: /* Inline methods */ UnwindInfoSet& unwinds() { return unwinds_; } uint32_t thread_id() const { return id_; } ThreadNexus::Phase thread_phase() { return thread_phase_; } ThreadNexus* thread_nexus() { return thread_nexus_; } void set_thread_phase(ThreadNexus::Phase thread_phase) { thread_phase_ = thread_phase; } void restore_thread_phase(ThreadNexus::Phase thread_phase) { switch(thread_phase) { case ThreadNexus::cManaged: become_managed(); break; case ThreadNexus::cBlocking: case ThreadNexus::cUnmanaged: case ThreadNexus::cWaiting: case ThreadNexus::cSleeping: default: thread_phase_ = thread_phase; } } utilities::thread::SpinLock& interrupt_lock() { return interrupt_lock_; } void set_zombie(STATE); bool zombie_p() { return zombie_; } void set_main_thread() { main_thread_ = true; } bool main_thread_p() { return main_thread_; } VMThreadState* thread_state() { return &thread_state_; } Memory* memory() { return shared.memory(); } void set_start_time(); double run_time(); void raise_stack_error(STATE); size_t stack_size() { return current_stack_size_; } void restore_stack_bounds() { current_stack_start_ = stack_start_; current_stack_size_ = stack_size_; } void set_stack_bounds(void* start, size_t size) { current_stack_start_ = start; current_stack_size_ = size; } void set_stack_bounds(size_t size); bool check_stack(STATE, void* stack_address) { ssize_t stack_used = (reinterpret_cast<intptr_t>(current_stack_start_) - reinterpret_cast<intptr_t>(stack_address)); if(stack_used < 0) stack_used = -stack_used; if(static_cast<size_t>(stack_used) > stack_size_) { raise_stack_error(state); return false; } return true; } bool push_call_frame(STATE, CallFrame* frame, CallFrame*& previous_frame); bool pop_call_frame(STATE, CallFrame* frame) { call_frame_ = frame; return !thread_interrupted_p(state); } bool thread_interrupted_p(STATE) { if(check_local_interrupts()) { return check_thread_raise_or_kill(state); } return false; } bool check_thread_raise_or_kill(STATE); // Do NOT de-duplicate void set_call_frame(CallFrame* frame) { call_frame_ = frame; } CallFrame* call_frame() { return call_frame_; } CallFrame* get_call_frame(ssize_t up=0); CallFrame* get_ruby_frame(ssize_t up=0); CallFrame* get_variables_frame(ssize_t up=0); CallFrame* get_scope_frame(ssize_t up=0); bool scope_valid_p(VariableScope* scope); void set_call_site_information(CallSiteInformation* info) { saved_call_site_information_ = info; } CallSiteInformation* saved_call_site_information() { return saved_call_site_information_; } GlobalCache* global_cache() const { return shared.global_cache; } Globals& globals() { return shared.globals; } MethodMissingReason method_missing_reason() const { return method_missing_reason_; } void set_method_missing_reason(MethodMissingReason reason) { method_missing_reason_ = reason; } ConstantMissingReason constant_missing_reason() const { return constant_missing_reason_; } void set_constant_missing_reason(ConstantMissingReason reason) { constant_missing_reason_ = reason; } void after_fork_child(STATE); bool thread_step() const { return thread_step_; } void clear_thread_step() { clear_check_local_interrupts(); thread_step_ = false; } void set_thread_step() { set_check_local_interrupts(); thread_step_ = true; } bool check_local_interrupts() const { return check_local_interrupts_; } void clear_check_local_interrupts() { check_local_interrupts_ = false; } void set_check_local_interrupts() { check_local_interrupts_ = true; } bool interrupt_by_kill() const { return interrupt_by_kill_; } void clear_interrupt_by_kill() { interrupt_by_kill_ = false; } void set_interrupt_by_kill() { interrupt_by_kill_ = true; } Exception* interrupted_exception() const { return interrupted_exception_.get(); } void clear_interrupted_exception() { interrupted_exception_.set(cNil); } bool allocation_tracking() const { return allocation_tracking_; } void enable_allocation_tracking() { allocation_tracking_ = true; } void disable_allocation_tracking() { allocation_tracking_ = false; } FiberStack* allocate_fiber_stack() { return fiber_stacks_.allocate(); } void* fiber_trampoline() { return fiber_stacks_.trampoline(); } FiberData* new_fiber_data(bool root=false) { return fiber_stacks_.new_data(root); } void remove_fiber_data(FiberData* data) { fiber_stacks_.remove_data(data); } memory::VariableRootBuffers& current_root_buffers(); public: static VM* current(); static void discard(STATE, VM*); public: /* Prototypes */ VM(uint32_t id, SharedState& shared, const char* name = NULL); ~VM(); void bootstrap_class(STATE); void bootstrap_ontology(STATE); void bootstrap_symbol(STATE); void collect_maybe(STATE); native_int max_profile_entries() { return max_profile_entries_; } uint64_t profile_sample_count() { return profile_sample_count_; } CompiledCode** profile() { return profile_; } void update_profile(STATE); void sort_profile(); #define RBX_PROFILE_MAX_SHIFT 0xf #define RBX_PROFILE_MAX_INTERVAL 0x1fff void set_profile_interval() { profile_interval_ = randombytes_random(); profile_interval_ >>= (profile_interval_ & RBX_PROFILE_MAX_SHIFT); profile_interval_ &= RBX_PROFILE_MAX_INTERVAL; profile_counter_ = 0; } void checkpoint(STATE) { metrics().machine.checkpoints++; if(thread_nexus_->stop_lock(this)) { metrics().machine.stops++; collect_maybe(state); thread_nexus_->unlock(); } if(profile_counter_++ >= profile_interval_) { update_profile(state); set_profile_interval(); } } void blocking_suspend(STATE, metrics::metric& counter); void sleeping_suspend(STATE, metrics::metric& counter); void become_managed(); void become_unmanaged() { thread_phase_ = ThreadNexus::cUnmanaged; } void set_current_thread(); void setup_errno(STATE, int num, const char* name, Class* sce, Module* ern); void bootstrap_exceptions(STATE); void initialize_fundamental_constants(STATE); void initialize_builtin_classes(STATE); void initialize_platform_data(STATE); Object* ruby_lib_version(); void set_current_fiber(Fiber* fib); TypeInfo* find_type(int type); static void init_ffi(STATE); void raise_from_errno(const char* reason); void raise_exception(Exception* exc); Exception* new_exception(Class* cls, const char* msg); Object* current_block(); void set_const(const char* name, Object* val); void set_const(Module* mod, const char* name, Object* val); Object* path2class(const char* name); llvm::Module* llvm_module(); void llvm_cleanup(); void print_backtrace(); void wait_on_channel(Channel* channel); void wait_on_inflated_lock(Object* wait); void wait_on_custom_function(void (*func)(void*), void* data); void clear_waiter(); bool wakeup(STATE); void reset_parked(); void set_sleeping(); void clear_sleeping(); void interrupt_with_signal() { interrupt_with_signal_ = true; } void register_raise(STATE, Exception* exc); void register_kill(STATE); void gc_scan(memory::GarbageCollector* gc); void gc_fiber_clear_mark(); void gc_fiber_scan(memory::GarbageCollector* gc, bool only_marked = true); void gc_verify(memory::GarbageCollector* gc); }; } #endif <commit_msg>Fixed stack depth checking with Fiber.<commit_after>#ifndef RBX_VM_H #define RBX_VM_H #include "missing/time.h" #include "globals.hpp" #include "memory/object_mark.hpp" #include "memory/managed.hpp" #include "vm_thread_state.hpp" #include "thread_nexus.hpp" #include "metrics.hpp" #include "util/thread.hpp" #include "memory/variable_buffer.hpp" #include "memory/root_buffer.hpp" #include "memory/slab.hpp" #include "shared_state.hpp" #include "unwind_info.hpp" #include "fiber_stack.hpp" #include "sodium/randombytes.h" #include <vector> #include <setjmp.h> #include <stdint.h> namespace llvm { class Module; } namespace rbxti { class Env; } namespace rubinius { class Exception; class LLVMState; namespace event { class Loop; } namespace memory { class GarbageCollector; class WriteBarrier; } class Assertion; class CallSiteInformation; class Channel; class CompiledCode; class ConfigParser; class Configuration; class Fiber; class GlobalCache; class LookupTable; class Memory; class NativeMethodEnvironment; class Object; class Park; class Primitives; class SharedState; class String; class Symbol; class SymbolTable; class Tuple; class TypeError; class TypeInfo; class VariableScope; struct CallFrame; enum MethodMissingReason { eNone, ePrivate, eProtected, eSuper, eVCall, eNormal }; enum ConstantMissingReason { vFound, vPrivate, vNonExistent }; /** * Represents an execution context for running Ruby code. * * Each Ruby thread is backed by an instance of this class, as well as an * instance of the Thread class. Thread manages the (Ruby visible) thread- * related state, while this class manages the execution machinery for * running Ruby code. */ class VM : public memory::ManagedThread { friend class State; private: UnwindInfoSet unwinds_; CallFrame* call_frame_; ThreadNexus* thread_nexus_; CallSiteInformation* saved_call_site_information_; FiberStacks fiber_stacks_; Park* park_; void* stack_start_; size_t stack_size_; void* current_stack_start_; size_t current_stack_size_; bool interrupt_with_signal_; bool interrupt_by_kill_; bool check_local_interrupts_; bool thread_step_; utilities::thread::SpinLock interrupt_lock_; MethodMissingReason method_missing_reason_; ConstantMissingReason constant_missing_reason_; bool zombie_; bool allocation_tracking_; bool main_thread_; ThreadNexus::Phase thread_phase_; uint32_t profile_interval_; uint32_t profile_counter_; CompiledCode** profile_; uint64_t profile_sample_count_; uint64_t profile_report_interval_; native_int max_profile_entries_; native_int min_profile_sample_count_; public: /* Data members */ SharedState& shared; memory::TypedRoot<Channel*> waiting_channel_; memory::TypedRoot<Exception*> interrupted_exception_; /// The Thread object for this VM state memory::TypedRoot<Thread*> thread; /// The current fiber running on this thread memory::TypedRoot<Fiber*> current_fiber; /// Root fiber, if any (lazily initialized) memory::TypedRoot<Fiber*> root_fiber; /// Object that waits for inflation memory::TypedRoot<Object*> waiting_object_; uint64_t start_time_; NativeMethodEnvironment* native_method_environment; void (*custom_wakeup_)(void*); void* custom_wakeup_data_; VMThreadState thread_state_; public: /* Inline methods */ UnwindInfoSet& unwinds() { return unwinds_; } uint32_t thread_id() const { return id_; } ThreadNexus::Phase thread_phase() { return thread_phase_; } ThreadNexus* thread_nexus() { return thread_nexus_; } void set_thread_phase(ThreadNexus::Phase thread_phase) { thread_phase_ = thread_phase; } void restore_thread_phase(ThreadNexus::Phase thread_phase) { switch(thread_phase) { case ThreadNexus::cManaged: become_managed(); break; case ThreadNexus::cBlocking: case ThreadNexus::cUnmanaged: case ThreadNexus::cWaiting: case ThreadNexus::cSleeping: default: thread_phase_ = thread_phase; } } utilities::thread::SpinLock& interrupt_lock() { return interrupt_lock_; } void set_zombie(STATE); bool zombie_p() { return zombie_; } void set_main_thread() { main_thread_ = true; } bool main_thread_p() { return main_thread_; } VMThreadState* thread_state() { return &thread_state_; } Memory* memory() { return shared.memory(); } void set_start_time(); double run_time(); void raise_stack_error(STATE); size_t stack_size() { return current_stack_size_; } void restore_stack_bounds() { current_stack_start_ = stack_start_; current_stack_size_ = stack_size_; } void set_stack_bounds(void* start, size_t size) { current_stack_start_ = start; current_stack_size_ = size; } void set_stack_bounds(size_t size); bool check_stack(STATE, void* stack_address) { ssize_t stack_used = (reinterpret_cast<intptr_t>(current_stack_start_) - reinterpret_cast<intptr_t>(stack_address)); if(stack_used < 0) stack_used = -stack_used; if(static_cast<size_t>(stack_used) > current_stack_size_) { raise_stack_error(state); return false; } return true; } bool push_call_frame(STATE, CallFrame* frame, CallFrame*& previous_frame); bool pop_call_frame(STATE, CallFrame* frame) { call_frame_ = frame; return !thread_interrupted_p(state); } bool thread_interrupted_p(STATE) { if(check_local_interrupts()) { return check_thread_raise_or_kill(state); } return false; } bool check_thread_raise_or_kill(STATE); // Do NOT de-duplicate void set_call_frame(CallFrame* frame) { call_frame_ = frame; } CallFrame* call_frame() { return call_frame_; } CallFrame* get_call_frame(ssize_t up=0); CallFrame* get_ruby_frame(ssize_t up=0); CallFrame* get_variables_frame(ssize_t up=0); CallFrame* get_scope_frame(ssize_t up=0); bool scope_valid_p(VariableScope* scope); void set_call_site_information(CallSiteInformation* info) { saved_call_site_information_ = info; } CallSiteInformation* saved_call_site_information() { return saved_call_site_information_; } GlobalCache* global_cache() const { return shared.global_cache; } Globals& globals() { return shared.globals; } MethodMissingReason method_missing_reason() const { return method_missing_reason_; } void set_method_missing_reason(MethodMissingReason reason) { method_missing_reason_ = reason; } ConstantMissingReason constant_missing_reason() const { return constant_missing_reason_; } void set_constant_missing_reason(ConstantMissingReason reason) { constant_missing_reason_ = reason; } void after_fork_child(STATE); bool thread_step() const { return thread_step_; } void clear_thread_step() { clear_check_local_interrupts(); thread_step_ = false; } void set_thread_step() { set_check_local_interrupts(); thread_step_ = true; } bool check_local_interrupts() const { return check_local_interrupts_; } void clear_check_local_interrupts() { check_local_interrupts_ = false; } void set_check_local_interrupts() { check_local_interrupts_ = true; } bool interrupt_by_kill() const { return interrupt_by_kill_; } void clear_interrupt_by_kill() { interrupt_by_kill_ = false; } void set_interrupt_by_kill() { interrupt_by_kill_ = true; } Exception* interrupted_exception() const { return interrupted_exception_.get(); } void clear_interrupted_exception() { interrupted_exception_.set(cNil); } bool allocation_tracking() const { return allocation_tracking_; } void enable_allocation_tracking() { allocation_tracking_ = true; } void disable_allocation_tracking() { allocation_tracking_ = false; } FiberStack* allocate_fiber_stack() { return fiber_stacks_.allocate(); } void* fiber_trampoline() { return fiber_stacks_.trampoline(); } FiberData* new_fiber_data(bool root=false) { return fiber_stacks_.new_data(root); } void remove_fiber_data(FiberData* data) { fiber_stacks_.remove_data(data); } memory::VariableRootBuffers& current_root_buffers(); public: static VM* current(); static void discard(STATE, VM*); public: /* Prototypes */ VM(uint32_t id, SharedState& shared, const char* name = NULL); ~VM(); void bootstrap_class(STATE); void bootstrap_ontology(STATE); void bootstrap_symbol(STATE); void collect_maybe(STATE); native_int max_profile_entries() { return max_profile_entries_; } uint64_t profile_sample_count() { return profile_sample_count_; } CompiledCode** profile() { return profile_; } void update_profile(STATE); void sort_profile(); #define RBX_PROFILE_MAX_SHIFT 0xf #define RBX_PROFILE_MAX_INTERVAL 0x1fff void set_profile_interval() { profile_interval_ = randombytes_random(); profile_interval_ >>= (profile_interval_ & RBX_PROFILE_MAX_SHIFT); profile_interval_ &= RBX_PROFILE_MAX_INTERVAL; profile_counter_ = 0; } void checkpoint(STATE) { metrics().machine.checkpoints++; if(thread_nexus_->stop_lock(this)) { metrics().machine.stops++; collect_maybe(state); thread_nexus_->unlock(); } if(profile_counter_++ >= profile_interval_) { update_profile(state); set_profile_interval(); } } void blocking_suspend(STATE, metrics::metric& counter); void sleeping_suspend(STATE, metrics::metric& counter); void become_managed(); void become_unmanaged() { thread_phase_ = ThreadNexus::cUnmanaged; } void set_current_thread(); void setup_errno(STATE, int num, const char* name, Class* sce, Module* ern); void bootstrap_exceptions(STATE); void initialize_fundamental_constants(STATE); void initialize_builtin_classes(STATE); void initialize_platform_data(STATE); Object* ruby_lib_version(); void set_current_fiber(Fiber* fib); TypeInfo* find_type(int type); static void init_ffi(STATE); void raise_from_errno(const char* reason); void raise_exception(Exception* exc); Exception* new_exception(Class* cls, const char* msg); Object* current_block(); void set_const(const char* name, Object* val); void set_const(Module* mod, const char* name, Object* val); Object* path2class(const char* name); llvm::Module* llvm_module(); void llvm_cleanup(); void print_backtrace(); void wait_on_channel(Channel* channel); void wait_on_inflated_lock(Object* wait); void wait_on_custom_function(void (*func)(void*), void* data); void clear_waiter(); bool wakeup(STATE); void reset_parked(); void set_sleeping(); void clear_sleeping(); void interrupt_with_signal() { interrupt_with_signal_ = true; } void register_raise(STATE, Exception* exc); void register_kill(STATE); void gc_scan(memory::GarbageCollector* gc); void gc_fiber_clear_mark(); void gc_fiber_scan(memory::GarbageCollector* gc, bool only_marked = true); void gc_verify(memory::GarbageCollector* gc); }; } #endif <|endoftext|>
<commit_before>/* --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2015-2016, Numenta, Inc. Unless you have an agreement * with Numenta, Inc., for a separate license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero Public License for more details. * * You should have received a copy of the GNU Affero Public License * along with this program. If not, see http://www.gnu.org/licenses. * * http://numenta.org/licenses/ * --------------------------------------------------------------------- */ #include "gtest/gtest.h" /** @file * Implementation of performance tests for Connections */ #include <fstream> #include <iostream> #include <cmath> //for sin #include <nupic/algorithms/Connections.hpp> #include <nupic/algorithms/TemporalMemory.hpp> #include <nupic/utils/Random.hpp> #include <nupic/os/Timer.hpp> namespace testing { using namespace std; using namespace nupic; using ::nupic::algorithms::connections::Segment; using ::nupic::algorithms::temporal_memory::TemporalMemory; #define SEED 42 Random rng(SEED); std::vector<UInt32> _randomSDR(UInt n, UInt w); void _feedTM(TemporalMemory &tm, vector<CellIdx> sdr, bool learn = true); std::vector<CellIdx> _computeSPWinnerCells(Connections &connections, UInt numCells, const vector<UInt> &numActiveSynapsesForSegment); float runTemporalMemoryTest(UInt numColumns, UInt w, int numSequences, int numElements, string label) { Timer timer(true); // Initialize TemporalMemory tm; vector<UInt> columnDim; columnDim.push_back(numColumns); tm.initialize(columnDim); cout << (float)timer.getElapsed() << " in " << label << ": initialize" << endl; // Learn vector<vector<vector<CellIdx>>> sequences; vector<vector<CellIdx>> sequence; vector<CellIdx> sdr; for (int i = 0; i < numSequences; i++) { for (int j = 0; j < numElements; j++) { sdr = _randomSDR(numColumns, w); sequence.push_back(sdr); } sequences.push_back(sequence); } for (int i = 0; i < 5; i++) { for (auto sequence : sequences) { for (auto sdr : sequence) { _feedTM(tm, sdr); tm.reset(); } } } cout << (float)timer.getElapsed() << " in " << label << ": initialize + learn" << endl; // Test for (auto sequence : sequences) { for (auto sdr : sequence) { _feedTM(tm, sdr, false); tm.reset(); } } cout << (float)timer.getElapsed() << " in " << label << ": initialize + learn + test" << endl; timer.stop(); return timer.getElapsed(); } float runSpatialPoolerTest(UInt numCells, UInt numInputs, UInt w, UInt numWinners, string label) { Timer timer; timer.start(); Connections connections(numCells); Segment segment; vector<CellIdx> sdr; // Initialize for (UInt c = 0; c < numCells; c++) { segment = connections.createSegment(c); for (UInt i = 0; i < numInputs; i++) { const Permanence permanence = (Permanence)rng.getReal64(); connections.createSynapse(segment, i, permanence); } } cout << (float)timer.getElapsed() << " in " << label << ": initialize" << endl; // Learn vector<CellIdx> winnerCells; Permanence permanence; for (int i = 0; i < 500; i++) { sdr = _randomSDR(numInputs, w); vector<UInt32> numActiveConnectedSynapsesForSegment( connections.segmentFlatListLength(), 0); vector<UInt32> numActivePotentialSynapsesForSegment( connections.segmentFlatListLength(), 0); connections.computeActivity(numActiveConnectedSynapsesForSegment, numActivePotentialSynapsesForSegment, sdr, 0.5); winnerCells = _computeSPWinnerCells(connections, numWinners, numActiveConnectedSynapsesForSegment); for (CellIdx winnerCell : winnerCells) { segment = connections.getSegment(winnerCell, 0); const vector<Synapse> &synapses = connections.synapsesForSegment(segment); for (SynapseIdx i = 0; i < (SynapseIdx)synapses.size();) { const Synapse synapse = synapses[i]; const SynapseData &synapseData = connections.dataForSynapse(synapse); permanence = synapseData.permanence; if (find(sdr.begin(), sdr.end(), synapseData.presynapticCell) != sdr.end()) { permanence += 0.2; } else { permanence -= 0.1; } permanence = max(permanence, (Permanence)0); permanence = min(permanence, (Permanence)1); if (permanence == 0) { connections.destroySynapse(synapse); // The synapses list is updated in-place, so don't update `i`. } else { connections.updateSynapsePermanence(synapse, permanence); i++; } } } } cout << (float)timer.getElapsed() << " in " << label << ": initialize + learn" << endl; // Test for (int i = 0; i < 500; i++) { sdr = _randomSDR(numInputs, w); vector<UInt32> numActiveConnectedSynapsesForSegment( connections.segmentFlatListLength(), 0); vector<UInt32> numActivePotentialSynapsesForSegment( connections.segmentFlatListLength(), 0); connections.computeActivity(numActiveConnectedSynapsesForSegment, numActivePotentialSynapsesForSegment, sdr, 0.5); winnerCells = _computeSPWinnerCells(connections, numWinners, numActiveConnectedSynapsesForSegment); } cout << (float)timer.getElapsed() << " in " << label << ": initialize + learn + test" << endl; timer.stop(); return timer.getElapsed(); } vector<CellIdx> _randomSDR(UInt n, UInt w) { set<UInt> sdrSet = set<UInt>(); vector<CellIdx> sdr; for (UInt i = 0; i < w; i++) { sdrSet.insert(rng.getUInt32(n)); } for (UInt c : sdrSet) { sdr.push_back(c); } return sdr; } void _feedTM(TemporalMemory &tm, vector<CellIdx> sdr, bool learn) { vector<UInt> activeColumns; for (auto c : sdr) { activeColumns.push_back(c); } tm.compute(activeColumns.size(), activeColumns.data(), learn); } vector<CellIdx> _computeSPWinnerCells(Connections &connections, UInt numCells, const vector<UInt> &numActiveSynapsesForSegment) { // Activate every segment, then choose the top few. vector<Segment> activeSegments; for (Segment segment = 0; segment < numActiveSynapsesForSegment.size(); segment++) { activeSegments.push_back(segment); } set<CellIdx> winnerCells; std::sort( activeSegments.begin(), activeSegments.end(), [&](Segment a, Segment b) { return numActiveSynapsesForSegment[a] > numActiveSynapsesForSegment[b]; }); for (Segment segment : activeSegments) { winnerCells.insert(connections.cellForSegment(segment)); if (winnerCells.size() >= numCells) { break; } } return vector<CellIdx>(winnerCells.begin(), winnerCells.end()); } float _SPEED = -1; /** * estimate speed (CPU & load) of the current system. * Tests must perform relative to this value */ float getSpeed() { if (_SPEED == -1) { Timer t(true); //this code just wastes CPU time to estimate speed vector<UInt> data(10000000); for(UInt i=0; i<data.size(); i++) { data[i]=rng.getUInt32(80085); auto t = data[i]; data[i] = data[data.size()-i]; data[data.size()-i]=t; } rng.shuffle(begin(data), end(data)); vector<Real> sins; for (auto d : data) { sins.push_back(sin(d)/cos(d)); } rng.sample(sins.data(), sins.size(), (float*)data.data(), 666); t.stop(); _SPEED = max(1.0, t.getElapsed()); } return _SPEED; } #ifdef NDEBUG //disable performance tests in debug mode // TESTS const UInt SEQ = 100; //number of sequences ran in tests const UInt EPOCHS = 20; //epochs tests run const UInt COLS = 2048; //standard num of columns in SP/TM /** * Tests typical usage of Connections with Temporal Memory. * format is: COLS, W(bits), EPOCHS, SEQUENCES */ TEST(ConnectionsPerformanceTest, testTM) { auto tim = runTemporalMemoryTest(COLS, 40, EPOCHS, SEQ, "temporal memory"); ASSERT_LE(tim, 2.0*getSpeed()); //there are times, we must be better. Bit underestimated for slow CI } /** * Tests typical usage of Connections with a large Temporal Memory. */ TEST(ConnectionsPerformanceTest, testTMLarge) { auto tim = runTemporalMemoryTest(2*COLS, 328, 10, SEQ, "temporal memory (large)"); ASSERT_LE(tim, 3.6*getSpeed()); } /** * Tests typical usage of Connections with Spatial Pooler. */ TEST(ConnectionsPerformanceTest, testSP) { auto tim = runSpatialPoolerTest(COLS, COLS, EPOCHS, SEQ, "spatial pooler"); ASSERT_LE(tim, 6.3*getSpeed()); } /** * Tests typical usage of Connections with Temporal Pooler. */ TEST(ConnectionsPerformanceTest, testTP) { auto tim = runSpatialPoolerTest(COLS, 16384, 10, SEQ, "temporal pooler"); ASSERT_LE(tim, 77*getSpeed()); } #endif //DEBUG } // end namespace <commit_msg>bump values more<commit_after>/* --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2015-2016, Numenta, Inc. Unless you have an agreement * with Numenta, Inc., for a separate license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero Public License for more details. * * You should have received a copy of the GNU Affero Public License * along with this program. If not, see http://www.gnu.org/licenses. * * http://numenta.org/licenses/ * --------------------------------------------------------------------- */ #include "gtest/gtest.h" /** @file * Implementation of performance tests for Connections */ #include <fstream> #include <iostream> #include <cmath> //for sin #include <nupic/algorithms/Connections.hpp> #include <nupic/algorithms/TemporalMemory.hpp> #include <nupic/utils/Random.hpp> #include <nupic/os/Timer.hpp> namespace testing { using namespace std; using namespace nupic; using ::nupic::algorithms::connections::Segment; using ::nupic::algorithms::temporal_memory::TemporalMemory; #define SEED 42 Random rng(SEED); std::vector<UInt32> _randomSDR(UInt n, UInt w); void _feedTM(TemporalMemory &tm, vector<CellIdx> sdr, bool learn = true); std::vector<CellIdx> _computeSPWinnerCells(Connections &connections, UInt numCells, const vector<UInt> &numActiveSynapsesForSegment); float runTemporalMemoryTest(UInt numColumns, UInt w, int numSequences, int numElements, string label) { Timer timer(true); // Initialize TemporalMemory tm; vector<UInt> columnDim; columnDim.push_back(numColumns); tm.initialize(columnDim); cout << (float)timer.getElapsed() << " in " << label << ": initialize" << endl; // Learn vector<vector<vector<CellIdx>>> sequences; vector<vector<CellIdx>> sequence; vector<CellIdx> sdr; for (int i = 0; i < numSequences; i++) { for (int j = 0; j < numElements; j++) { sdr = _randomSDR(numColumns, w); sequence.push_back(sdr); } sequences.push_back(sequence); } for (int i = 0; i < 5; i++) { for (auto sequence : sequences) { for (auto sdr : sequence) { _feedTM(tm, sdr); tm.reset(); } } } cout << (float)timer.getElapsed() << " in " << label << ": initialize + learn" << endl; // Test for (auto sequence : sequences) { for (auto sdr : sequence) { _feedTM(tm, sdr, false); tm.reset(); } } cout << (float)timer.getElapsed() << " in " << label << ": initialize + learn + test" << endl; timer.stop(); return timer.getElapsed(); } float runSpatialPoolerTest(UInt numCells, UInt numInputs, UInt w, UInt numWinners, string label) { Timer timer; timer.start(); Connections connections(numCells); Segment segment; vector<CellIdx> sdr; // Initialize for (UInt c = 0; c < numCells; c++) { segment = connections.createSegment(c); for (UInt i = 0; i < numInputs; i++) { const Permanence permanence = (Permanence)rng.getReal64(); connections.createSynapse(segment, i, permanence); } } cout << (float)timer.getElapsed() << " in " << label << ": initialize" << endl; // Learn vector<CellIdx> winnerCells; Permanence permanence; for (int i = 0; i < 500; i++) { sdr = _randomSDR(numInputs, w); vector<UInt32> numActiveConnectedSynapsesForSegment( connections.segmentFlatListLength(), 0); vector<UInt32> numActivePotentialSynapsesForSegment( connections.segmentFlatListLength(), 0); connections.computeActivity(numActiveConnectedSynapsesForSegment, numActivePotentialSynapsesForSegment, sdr, 0.5); winnerCells = _computeSPWinnerCells(connections, numWinners, numActiveConnectedSynapsesForSegment); for (CellIdx winnerCell : winnerCells) { segment = connections.getSegment(winnerCell, 0); const vector<Synapse> &synapses = connections.synapsesForSegment(segment); for (SynapseIdx i = 0; i < (SynapseIdx)synapses.size();) { const Synapse synapse = synapses[i]; const SynapseData &synapseData = connections.dataForSynapse(synapse); permanence = synapseData.permanence; if (find(sdr.begin(), sdr.end(), synapseData.presynapticCell) != sdr.end()) { permanence += 0.2; } else { permanence -= 0.1; } permanence = max(permanence, (Permanence)0); permanence = min(permanence, (Permanence)1); if (permanence == 0) { connections.destroySynapse(synapse); // The synapses list is updated in-place, so don't update `i`. } else { connections.updateSynapsePermanence(synapse, permanence); i++; } } } } cout << (float)timer.getElapsed() << " in " << label << ": initialize + learn" << endl; // Test for (int i = 0; i < 500; i++) { sdr = _randomSDR(numInputs, w); vector<UInt32> numActiveConnectedSynapsesForSegment( connections.segmentFlatListLength(), 0); vector<UInt32> numActivePotentialSynapsesForSegment( connections.segmentFlatListLength(), 0); connections.computeActivity(numActiveConnectedSynapsesForSegment, numActivePotentialSynapsesForSegment, sdr, 0.5); winnerCells = _computeSPWinnerCells(connections, numWinners, numActiveConnectedSynapsesForSegment); } cout << (float)timer.getElapsed() << " in " << label << ": initialize + learn + test" << endl; timer.stop(); return timer.getElapsed(); } vector<CellIdx> _randomSDR(UInt n, UInt w) { set<UInt> sdrSet = set<UInt>(); vector<CellIdx> sdr; for (UInt i = 0; i < w; i++) { sdrSet.insert(rng.getUInt32(n)); } for (UInt c : sdrSet) { sdr.push_back(c); } return sdr; } void _feedTM(TemporalMemory &tm, vector<CellIdx> sdr, bool learn) { vector<UInt> activeColumns; for (auto c : sdr) { activeColumns.push_back(c); } tm.compute(activeColumns.size(), activeColumns.data(), learn); } vector<CellIdx> _computeSPWinnerCells(Connections &connections, UInt numCells, const vector<UInt> &numActiveSynapsesForSegment) { // Activate every segment, then choose the top few. vector<Segment> activeSegments; for (Segment segment = 0; segment < numActiveSynapsesForSegment.size(); segment++) { activeSegments.push_back(segment); } set<CellIdx> winnerCells; std::sort( activeSegments.begin(), activeSegments.end(), [&](Segment a, Segment b) { return numActiveSynapsesForSegment[a] > numActiveSynapsesForSegment[b]; }); for (Segment segment : activeSegments) { winnerCells.insert(connections.cellForSegment(segment)); if (winnerCells.size() >= numCells) { break; } } return vector<CellIdx>(winnerCells.begin(), winnerCells.end()); } float _SPEED = -1; /** * estimate speed (CPU & load) of the current system. * Tests must perform relative to this value */ float getSpeed() { if (_SPEED == -1) { Timer t(true); //this code just wastes CPU time to estimate speed vector<UInt> data(10000000); for(UInt i=0; i<data.size(); i++) { data[i]=rng.getUInt32(80085); auto t = data[i]; data[i] = data[data.size()-i]; data[data.size()-i]=t; } rng.shuffle(begin(data), end(data)); vector<Real> sins; for (auto d : data) { sins.push_back(sin(d)/cos(d)); } rng.sample(sins.data(), sins.size(), (float*)data.data(), 666); t.stop(); _SPEED = max(1.0, t.getElapsed()); } return _SPEED; } #ifdef NDEBUG //disable performance tests in debug mode // TESTS const UInt SEQ = 100; //number of sequences ran in tests const UInt EPOCHS = 20; //epochs tests run const UInt COLS = 2048; //standard num of columns in SP/TM /** * Tests typical usage of Connections with Temporal Memory. * format is: COLS, W(bits), EPOCHS, SEQUENCES */ TEST(ConnectionsPerformanceTest, testTM) { auto tim = runTemporalMemoryTest(COLS, 40, EPOCHS, SEQ, "temporal memory"); ASSERT_LE(tim, 2.0*getSpeed()); //there are times, we must be better. Bit underestimated for slow CI } /** * Tests typical usage of Connections with a large Temporal Memory. */ TEST(ConnectionsPerformanceTest, testTMLarge) { auto tim = runTemporalMemoryTest(2*COLS, 328, 10, SEQ, "temporal memory (large)"); ASSERT_LE(tim, 3.8*getSpeed()); } /** * Tests typical usage of Connections with Spatial Pooler. */ TEST(ConnectionsPerformanceTest, testSP) { auto tim = runSpatialPoolerTest(COLS, COLS, EPOCHS, SEQ, "spatial pooler"); ASSERT_LE(tim, 6.3*getSpeed()); } /** * Tests typical usage of Connections with Temporal Pooler. */ TEST(ConnectionsPerformanceTest, testTP) { auto tim = runSpatialPoolerTest(COLS, 16384, 10, SEQ, "temporal pooler"); ASSERT_LE(tim, 77*getSpeed()); } #endif //DEBUG } // end namespace <|endoftext|>
<commit_before>#include "xmlreader.h" #include "../base64.h" #include "../file.h" #include "../string.h" #include <algorithm> #include <cstring> #include <sstream> #include <stdexcept> using namespace UnTech; using namespace UnTech::Xml; namespace UnTech { namespace XmlPrivate { inline bool isWhitespace(char c) { return (c == ' ' || c == '\t' || c == '\r' || c == '\n'); } inline std::string unescapeXmlString(const char* start, const char* end) { std::string ret; ret.reserve(end - start); const char* source = start; while (source < end) { if (*source == '&') { const char* s = source + 1; if (memcmp(s, "lt;", 3) == 0) { source += 4; ret += '<'; continue; } else if (memcmp(s, "gt;", 3) == 0) { source += 4; ret += '>'; continue; } else if (memcmp(s, "amp;", 4) == 0) { source += 5; ret += '&'; continue; } else if (memcmp(s, "apos;", 5) == 0) { source += 6; ret += '\''; continue; } else if (memcmp(s, "quot;", 5) == 0) { source += 6; ret += '\"'; continue; } } ret += *source; source++; } return ret; } std::string xmlFilepart(const XmlReader* xml) { auto fp = xml->filepart(); if (fp.empty()) { return "XML"; } return fp; } auto buildXmlParseError(const XmlReader* xml, const char* msg) { std::stringstream stream; stream << xmlFilepart(xml) << ":" << xml->lineNo() << ": " << msg; return std::runtime_error(stream.str()); } auto buildXmlParseError(const XmlReader* xml, const std::string& tagName, const char* msg) { std::stringstream stream; stream << xmlFilepart(xml) << ":" << xml->lineNo() << " (" << tagName << "): " << msg; return std::runtime_error(stream.str()); } auto buildXmlParseError(const XmlReader* xml, const std::string& tagName, const std::string& attributeName, const char* msg) { std::stringstream stream; stream << xmlFilepart(xml) << ":" << xml->lineNo() << " (" << tagName << " " << attributeName << "): " << msg; return std::runtime_error(stream.str()); } auto buildXmlParseError(const XmlReader* xml, const std::string& tagName, const char* msg, const std::string& after) { std::stringstream stream; stream << xmlFilepart(xml) << ":" << xml->lineNo() << " (" << tagName << "): " << msg << " '" << after << "'"; return std::runtime_error(stream.str()); } auto buildXmlParseError(const XmlReader* xml, const std::string& tagName, const char* msg, const char c) { std::stringstream stream; stream << xmlFilepart(xml) << ":" << xml->lineNo() << " (" << tagName << "): " << msg << " '" << c << "'"; return std::runtime_error(stream.str()); } } } using namespace UnTech::XmlPrivate; XmlReader::XmlReader(const std::string& xml, const std::string& filename) : _inputString(xml) , _filename(filename) { if (xml.empty()) { throw std::runtime_error("Empty XML file"); } std::tie(_dirname, _filepart) = File::splitFilename(filename); parseDocument(); } std::unique_ptr<XmlReader> XmlReader::fromFile(const std::string& filename) { std::string xml = File::readUtf8TextFile(filename); return std::make_unique<XmlReader>(xml, filename); } void XmlReader::parseDocument() { _pos = _inputString.c_str(); _tagStack = std::stack<std::string>(); _inSelfClosingTag = false; _lineNo = 1; skipWhitespace(); // ignore XML header if (memcmp(_pos, "<?xml", 5) == 0) { _pos += 5; while (*_pos != '>') { if (*_pos == 0) { throw buildXmlParseError(this, "Unclosed XML header"); } if (*_pos == '\n') { _lineNo++; } _pos++; } _pos++; } skipWhitespace(); // ignore DOCTYPE if (memcmp(_pos, "<!DOCTYPE", 9) == 0) { _pos += 9; while (*_pos != '>') { if (*_pos == 0) { throw buildXmlParseError(this, "Unclosed DOCTYPE header"); } if (*_pos == '\n') { _lineNo++; } _pos++; } _pos++; } } std::unique_ptr<XmlTag> XmlReader::parseTag() { if (_inSelfClosingTag) { return nullptr; } // skip whitespace/text skipText(); if (_pos[0] == '<' && _pos[1] == '/') { // no more tags return nullptr; } if (*_pos == 0) { throw buildXmlParseError(this, "Unexpected end of file"); } if (*_pos != '<') { throw std::logic_error("Not a tag"); } _pos++; std::string tagName = parseName(); // tag must be followed by whitespace or a close tag. if (!(isWhitespace(*_pos) || (_pos[0] == '>') || (_pos[0] == '/' || _pos[1] != '>'))) { throw buildXmlParseError(this, "Invalid tag name"); } auto tag = std::make_unique<XmlTag>(this, tagName, _lineNo); while (*_pos) { skipWhitespace(); if (*_pos == 0) { throw buildXmlParseError(this, tagName, "Unclosed tag"); } if (isName(*_pos)) { // attribute std::string attributeName = parseName(); skipWhitespace(); if (*_pos != '=') { throw buildXmlParseError(this, tagName, attributeName, "Missing attribute value"); } _pos++; skipWhitespace(); std::string value = parseAttributeValue(); tag->attributes.insert({ attributeName, value }); } else if (*_pos == '?' || *_pos == '/') { // end of self closing tag if (_pos[1] != '>') { throw buildXmlParseError(this, tagName, "Missing '>'"); } _pos += 2; _inSelfClosingTag = true; return tag; } else if (*_pos == '>') { // end of tag _pos++; _tagStack.push(tagName); return tag; } else { throw buildXmlParseError(this, tagName, "Unknown character", *_pos); } } throw buildXmlParseError(this, tagName, "Incomplete tag"); } std::string XmlReader::parseText() { if (_inSelfClosingTag) { return std::string(); } std::string text; const char* startText = _pos; while (*_pos) { if (memcmp(_pos, "<!--", 4) == 0) { text += unescapeXmlString(startText, _pos); // skip comment while (memcmp(_pos, "-->", 4) != 0) { if (*_pos == 0) { throw buildXmlParseError(this, "Unclosed comment"); } if (*_pos == '\n') { _lineNo++; } _pos++; } _pos += 3; startText = _pos; } else if (memcmp(_pos, "<![CDATA[", 9) == 0) { text += unescapeXmlString(startText, _pos); _pos += 9; const char* startCData = _pos; while (memcmp(_pos, "]]>", 3) != 0) { if (*_pos == 0) { throw buildXmlParseError(this, "Unclosed CDATA"); } if (*_pos == '\n') { _lineNo++; } _pos++; } text.append(startCData, _pos - startCData); _pos += 3; startText = _pos; } else if (*_pos == '<') { // start/end new tag. break; } if (*_pos == '\n') { _lineNo++; _pos++; } else { _pos++; } } text += unescapeXmlString(startText, _pos); return text; } std::vector<uint8_t> XmlReader::parseBase64() { return Base64::decode(parseText()); } void XmlReader::parseCloseTag() { if (_inSelfClosingTag) { _inSelfClosingTag = false; return; } // skip all child nodes of current level while (_pos[0] != '<' || _pos[1] != '/') { // more nodes/text to parse parseTag(); if (_inSelfClosingTag) { // save a function call. _inSelfClosingTag = false; } else { parseCloseTag(); } } _pos += 2; auto closeTagName = parseName(); auto expectedTagName = _tagStack.top(); if (closeTagName != expectedTagName) { throw buildXmlParseError(this, expectedTagName, "Close tag mismatch"); } _tagStack.pop(); skipWhitespace(); if (*_pos != '>') { throw buildXmlParseError(this, closeTagName, "Expected '>'"); } } inline void XmlReader::skipWhitespace() { while (isWhitespace(*_pos)) { if (*_pos == '\n') { _lineNo++; } _pos++; } } void XmlReader::skipText() { if (_inSelfClosingTag) { return; } while (*_pos) { if (memcmp(_pos, "<!--", 4) == 0) { // skip comment while (memcmp(_pos, "-->", 4) != 0) { if (*_pos == 0) { throw buildXmlParseError(this, "Unclosed comment"); } if (*_pos == '\n') { _lineNo++; } _pos++; } _pos += 3; } else if (memcmp(_pos, "<![CDATA[", 9) == 0) { _pos += 9; while (memcmp(_pos, "]]>", 3) != 0) { if (*_pos == 0) { throw buildXmlParseError(this, "Unclosed CDATA"); } if (*_pos == '\n') { _lineNo++; } _pos++; } _pos += 3; } else if (*_pos == '<') { // start/end new tag. break; } if (*_pos == '\n') { _lineNo++; _pos++; } else { _pos++; } } } inline std::string XmlReader::parseName() { const char* nameStart = _pos; while (isName(*_pos)) { _pos++; } if (nameStart == _pos) { throw buildXmlParseError(this, "Missing identifier"); } std::string ret(nameStart, _pos - nameStart); std::transform(ret.begin(), ret.end(), ret.begin(), ::tolower); return ret; } inline std::string XmlReader::parseAttributeValue() { if (*_pos != '\'' && *_pos != '\"') { throw buildXmlParseError(this, "Attribute not quoted"); } const char terminator = *_pos; _pos++; const char* valueStart = _pos; while (*_pos != terminator) { if (*_pos == 0) { throw buildXmlParseError(this, "Incomplete attribute value"); } if (*_pos == '\n') { _lineNo++; } _pos++; } std::string value = unescapeXmlString(valueStart, _pos); _pos++; return value; } <commit_msg>fix: Bug reading XML comments<commit_after>#include "xmlreader.h" #include "../base64.h" #include "../file.h" #include "../string.h" #include <algorithm> #include <cstring> #include <sstream> #include <stdexcept> using namespace UnTech; using namespace UnTech::Xml; namespace UnTech { namespace XmlPrivate { inline bool isWhitespace(char c) { return (c == ' ' || c == '\t' || c == '\r' || c == '\n'); } inline std::string unescapeXmlString(const char* start, const char* end) { std::string ret; ret.reserve(end - start); const char* source = start; while (source < end) { if (*source == '&') { const char* s = source + 1; if (memcmp(s, "lt;", 3) == 0) { source += 4; ret += '<'; continue; } else if (memcmp(s, "gt;", 3) == 0) { source += 4; ret += '>'; continue; } else if (memcmp(s, "amp;", 4) == 0) { source += 5; ret += '&'; continue; } else if (memcmp(s, "apos;", 5) == 0) { source += 6; ret += '\''; continue; } else if (memcmp(s, "quot;", 5) == 0) { source += 6; ret += '\"'; continue; } } ret += *source; source++; } return ret; } std::string xmlFilepart(const XmlReader* xml) { auto fp = xml->filepart(); if (fp.empty()) { return "XML"; } return fp; } auto buildXmlParseError(const XmlReader* xml, const char* msg) { std::stringstream stream; stream << xmlFilepart(xml) << ":" << xml->lineNo() << ": " << msg; return std::runtime_error(stream.str()); } auto buildXmlParseError(const XmlReader* xml, const std::string& tagName, const char* msg) { std::stringstream stream; stream << xmlFilepart(xml) << ":" << xml->lineNo() << " (" << tagName << "): " << msg; return std::runtime_error(stream.str()); } auto buildXmlParseError(const XmlReader* xml, const std::string& tagName, const std::string& attributeName, const char* msg) { std::stringstream stream; stream << xmlFilepart(xml) << ":" << xml->lineNo() << " (" << tagName << " " << attributeName << "): " << msg; return std::runtime_error(stream.str()); } auto buildXmlParseError(const XmlReader* xml, const std::string& tagName, const char* msg, const std::string& after) { std::stringstream stream; stream << xmlFilepart(xml) << ":" << xml->lineNo() << " (" << tagName << "): " << msg << " '" << after << "'"; return std::runtime_error(stream.str()); } auto buildXmlParseError(const XmlReader* xml, const std::string& tagName, const char* msg, const char c) { std::stringstream stream; stream << xmlFilepart(xml) << ":" << xml->lineNo() << " (" << tagName << "): " << msg << " '" << c << "'"; return std::runtime_error(stream.str()); } } } using namespace UnTech::XmlPrivate; XmlReader::XmlReader(const std::string& xml, const std::string& filename) : _inputString(xml) , _filename(filename) { if (xml.empty()) { throw std::runtime_error("Empty XML file"); } std::tie(_dirname, _filepart) = File::splitFilename(filename); parseDocument(); } std::unique_ptr<XmlReader> XmlReader::fromFile(const std::string& filename) { std::string xml = File::readUtf8TextFile(filename); return std::make_unique<XmlReader>(xml, filename); } void XmlReader::parseDocument() { _pos = _inputString.c_str(); _tagStack = std::stack<std::string>(); _inSelfClosingTag = false; _lineNo = 1; skipWhitespace(); // ignore XML header if (memcmp(_pos, "<?xml", 5) == 0) { _pos += 5; while (*_pos != '>') { if (*_pos == 0) { throw buildXmlParseError(this, "Unclosed XML header"); } if (*_pos == '\n') { _lineNo++; } _pos++; } _pos++; } skipWhitespace(); // ignore DOCTYPE if (memcmp(_pos, "<!DOCTYPE", 9) == 0) { _pos += 9; while (*_pos != '>') { if (*_pos == 0) { throw buildXmlParseError(this, "Unclosed DOCTYPE header"); } if (*_pos == '\n') { _lineNo++; } _pos++; } _pos++; } } std::unique_ptr<XmlTag> XmlReader::parseTag() { if (_inSelfClosingTag) { return nullptr; } // skip whitespace/text skipText(); if (_pos[0] == '<' && _pos[1] == '/') { // no more tags return nullptr; } if (*_pos == 0) { throw buildXmlParseError(this, "Unexpected end of file"); } if (*_pos != '<') { throw std::logic_error("Not a tag"); } _pos++; std::string tagName = parseName(); // tag must be followed by whitespace or a close tag. if (!(isWhitespace(*_pos) || (_pos[0] == '>') || (_pos[0] == '/' || _pos[1] != '>'))) { throw buildXmlParseError(this, "Invalid tag name"); } auto tag = std::make_unique<XmlTag>(this, tagName, _lineNo); while (*_pos) { skipWhitespace(); if (*_pos == 0) { throw buildXmlParseError(this, tagName, "Unclosed tag"); } if (isName(*_pos)) { // attribute std::string attributeName = parseName(); skipWhitespace(); if (*_pos != '=') { throw buildXmlParseError(this, tagName, attributeName, "Missing attribute value"); } _pos++; skipWhitespace(); std::string value = parseAttributeValue(); tag->attributes.insert({ attributeName, value }); } else if (*_pos == '?' || *_pos == '/') { // end of self closing tag if (_pos[1] != '>') { throw buildXmlParseError(this, tagName, "Missing '>'"); } _pos += 2; _inSelfClosingTag = true; return tag; } else if (*_pos == '>') { // end of tag _pos++; _tagStack.push(tagName); return tag; } else { throw buildXmlParseError(this, tagName, "Unknown character", *_pos); } } throw buildXmlParseError(this, tagName, "Incomplete tag"); } std::string XmlReader::parseText() { if (_inSelfClosingTag) { return std::string(); } std::string text; const char* startText = _pos; while (*_pos) { if (memcmp(_pos, "<!--", 4) == 0) { text += unescapeXmlString(startText, _pos); // skip comment while (memcmp(_pos, "-->", 3) != 0) { if (*_pos == 0) { throw buildXmlParseError(this, "Unclosed comment"); } if (*_pos == '\n') { _lineNo++; } _pos++; } _pos += 3; startText = _pos; } else if (memcmp(_pos, "<![CDATA[", 9) == 0) { text += unescapeXmlString(startText, _pos); _pos += 9; const char* startCData = _pos; while (memcmp(_pos, "]]>", 3) != 0) { if (*_pos == 0) { throw buildXmlParseError(this, "Unclosed CDATA"); } if (*_pos == '\n') { _lineNo++; } _pos++; } text.append(startCData, _pos - startCData); _pos += 3; startText = _pos; } else if (*_pos == '<') { // start/end new tag. break; } if (*_pos == '\n') { _lineNo++; _pos++; } else { _pos++; } } text += unescapeXmlString(startText, _pos); return text; } std::vector<uint8_t> XmlReader::parseBase64() { return Base64::decode(parseText()); } void XmlReader::parseCloseTag() { if (_inSelfClosingTag) { _inSelfClosingTag = false; return; } // skip all child nodes of current level while (_pos[0] != '<' || _pos[1] != '/') { // more nodes/text to parse parseTag(); if (_inSelfClosingTag) { // save a function call. _inSelfClosingTag = false; } else { parseCloseTag(); } } _pos += 2; auto closeTagName = parseName(); auto expectedTagName = _tagStack.top(); if (closeTagName != expectedTagName) { throw buildXmlParseError(this, expectedTagName, "Close tag mismatch"); } _tagStack.pop(); skipWhitespace(); if (*_pos != '>') { throw buildXmlParseError(this, closeTagName, "Expected '>'"); } } inline void XmlReader::skipWhitespace() { while (isWhitespace(*_pos)) { if (*_pos == '\n') { _lineNo++; } _pos++; } } void XmlReader::skipText() { if (_inSelfClosingTag) { return; } while (*_pos) { if (memcmp(_pos, "<!--", 4) == 0) { // skip comment while (memcmp(_pos, "-->", 3) != 0) { if (*_pos == 0) { throw buildXmlParseError(this, "Unclosed comment"); } if (*_pos == '\n') { _lineNo++; } _pos++; } _pos += 3; } else if (memcmp(_pos, "<![CDATA[", 9) == 0) { _pos += 9; while (memcmp(_pos, "]]>", 3) != 0) { if (*_pos == 0) { throw buildXmlParseError(this, "Unclosed CDATA"); } if (*_pos == '\n') { _lineNo++; } _pos++; } _pos += 3; } else if (*_pos == '<') { // start/end new tag. break; } if (*_pos == '\n') { _lineNo++; _pos++; } else { _pos++; } } } inline std::string XmlReader::parseName() { const char* nameStart = _pos; while (isName(*_pos)) { _pos++; } if (nameStart == _pos) { throw buildXmlParseError(this, "Missing identifier"); } std::string ret(nameStart, _pos - nameStart); std::transform(ret.begin(), ret.end(), ret.begin(), ::tolower); return ret; } inline std::string XmlReader::parseAttributeValue() { if (*_pos != '\'' && *_pos != '\"') { throw buildXmlParseError(this, "Attribute not quoted"); } const char terminator = *_pos; _pos++; const char* valueStart = _pos; while (*_pos != terminator) { if (*_pos == 0) { throw buildXmlParseError(this, "Incomplete attribute value"); } if (*_pos == '\n') { _lineNo++; } _pos++; } std::string value = unescapeXmlString(valueStart, _pos); _pos++; return value; } <|endoftext|>
<commit_before>#include "types.h" #include "kernel.hh" #include "spinlock.h" #include "amd64.h" #include "cpu.hh" #include "wq.hh" #define NSLOTS (1 << WQSHIFT) struct wqueue { struct work *w[NSLOTS]; volatile int head __mpalign__; volatile int tail; struct spinlock lock; __padout__; } __mpalign__;; struct wqstat { u64 push; u64 full; u64 pop; u64 steal; __padout__; } __mpalign__; struct wqueue queue[NCPU] __mpalign__; struct wqstat stat[NCPU] __mpalign__; static inline struct wqueue * getwq(void) { pushcli(); return &queue[mycpu()->id]; } static inline void putwq(struct wqueue *wq) { popcli(); } static inline struct wqstat * wq_stat(void) { return &stat[mycpu()->id]; } struct work * allocwork(void) { return (struct work *)kalloc(); } void freework(struct work *w) { kfree(w); } int wq_push(struct work *w) { int i; struct wqueue *wq = getwq(); i = wq->head; if ((i - wq->tail) == NSLOTS) { wq_stat()->full++; return -1; } i = i & (NSLOTS-1); wq->w[i] = w; barrier(); wq->head++; wq_stat()->push++; putwq(wq); return 0; } int wq_push1(void (*fn)(struct work *w, void *a0), void *a0) { struct work *w = allocwork(); if (w == NULL) return -1; w->rip = (void*) fn; w->arg0 = a0; if (wq_push(w) < 0) { freework(w); return -1; } return 0; } int wq_push2(void (*fn)(struct work*, void*, void*), void *a0, void *a1) { struct work *w = allocwork(); if (w == NULL) return -1; w->rip = (void*) fn; w->arg0 = a0; w->arg1 = a1; if (wq_push(w) < 0) { freework(w); return -1; } return 0; } static struct work * __wq_pop(int c) { // Called with cli struct wqueue *wq = &queue[c]; struct work *w; int i; i = wq->head; if ((i - wq->tail) == 0) return 0; acquire(&wq->lock); i = wq->head; if ((i - wq->tail) == 0) { release(&wq->lock); return 0; } i = (i-1) & (NSLOTS-1); w = wq->w[i]; wq->head--; release(&wq->lock); wq_stat()->pop++; return w; } static struct work * __wq_steal(int c) { // Called with cli struct wqueue *wq = &queue[c]; struct work *w; int i; if (tryacquire(&wq->lock) == 0) return 0; i = wq->tail; if ((i - wq->head) == 0) { release(&wq->lock); return 0; } i = i & (NSLOTS-1); w = wq->w[i]; wq->tail++; release(&wq->lock); wq_stat()->steal++; return w; } static void __wq_run(struct work *w) { void (*fn)(struct work*, void*, void*, void*, void*, void*) = (void(*)(work*,void*,void*,void*,void*,void*))w->rip; fn(w, w->arg0, w->arg1, w->arg2, w->arg3, w->arg4); freework(w); } int wq_trywork(void) { struct work *w; int i; pushcli(); w = __wq_pop(mycpu()->id); if (w != NULL) { __wq_run(w); popcli(); return 1; } // XXX(sbw) should be random for (i = 0; i < NCPU; i++) { if (i == mycpu()->id) continue; w = __wq_steal(i); if (w != NULL) { __wq_run(w); popcli(); return 1; } } popcli(); return 0; } void wq_dump(void) { int i; for (i = 0; i < NCPU; i++) cprintf("push %lu full %lu pop %lu steal %lu\n", stat[i].push, stat[i].full, stat[i].pop, stat[i].steal); } static void __test_stub(struct work *w, void *a0, void *a1) { //long i = (long)a0; //cprintf("%u: %lu\n", cpunum(), i); volatile atomic<int> *running = (volatile atomic<int>*) a1; (*running)--; } void testwq(void) { enum { iters = 10 }; static volatile atomic<int> running(iters); u64 e, s; long i; pushcli(); if (mycpu()->id == 0) { microdelay(1); s = rdtsc(); for (i = 0; i < iters; i++) { if (wq_push2(__test_stub, (void*)i, (void*)&running) < 0) panic("testwq: oops"); } e = rdtsc(); cprintf("testwq: %lu\n", (e-s)/iters); while (running) nop_pause(); wq_dump(); } else { while (running) wq_trywork(); } popcli(); } void initwq(void) { int i; for (i = 0; i < NCPU; i++) initlock(&queue[i].lock, "wq lock", LOCKSTAT_WQ); } <commit_msg>Some wq benchmarking<commit_after>#include "types.h" #include "kernel.hh" #include "spinlock.h" #include "amd64.h" #include "cpu.hh" #include "wq.hh" #define NSLOTS (1 << WQSHIFT) struct wqueue { struct work *w[NSLOTS]; volatile int head __mpalign__; volatile int tail; struct spinlock lock; __padout__; } __mpalign__;; struct wqstat { u64 push; u64 full; u64 pop; u64 steal; __padout__; } __mpalign__; struct wqueue queue[NCPU] __mpalign__; struct wqstat stat[NCPU] __mpalign__; static inline struct wqueue * getwq(void) { pushcli(); return &queue[mycpu()->id]; } static inline void putwq(struct wqueue *wq) { popcli(); } static inline struct wqstat * wq_stat(void) { return &stat[mycpu()->id]; } struct work * allocwork(void) { return (struct work *)kalloc(); } void freework(struct work *w) { kfree(w); } int wq_push(struct work *w) { int i; struct wqueue *wq = getwq(); i = wq->head; if ((i - wq->tail) == NSLOTS) { wq_stat()->full++; return -1; } i = i & (NSLOTS-1); wq->w[i] = w; barrier(); wq->head++; wq_stat()->push++; putwq(wq); return 0; } int wq_push1(void (*fn)(struct work *w, void *a0), void *a0) { struct work *w = allocwork(); if (w == NULL) return -1; w->rip = (void*) fn; w->arg0 = a0; if (wq_push(w) < 0) { freework(w); return -1; } return 0; } int wq_push2(void (*fn)(struct work*, void*, void*), void *a0, void *a1) { struct work *w = allocwork(); if (w == NULL) return -1; w->rip = (void*) fn; w->arg0 = a0; w->arg1 = a1; if (wq_push(w) < 0) { freework(w); return -1; } return 0; } static struct work * __wq_pop(int c) { // Called with cli struct wqueue *wq = &queue[c]; struct work *w; int i; i = wq->head; if ((i - wq->tail) == 0) return 0; acquire(&wq->lock); i = wq->head; if ((i - wq->tail) == 0) { release(&wq->lock); return 0; } i = (i-1) & (NSLOTS-1); w = wq->w[i]; wq->head--; release(&wq->lock); wq_stat()->pop++; return w; } static struct work * __wq_steal(int c) { // Called with cli struct wqueue *wq = &queue[c]; struct work *w; int i; if (tryacquire(&wq->lock) == 0) return 0; i = wq->tail; if ((i - wq->head) == 0) { release(&wq->lock); return 0; } i = i & (NSLOTS-1); w = wq->w[i]; wq->tail++; release(&wq->lock); wq_stat()->steal++; return w; } static void __wq_run(struct work *w) { void (*fn)(struct work*, void*, void*, void*, void*, void*) = (void(*)(work*,void*,void*,void*,void*,void*))w->rip; fn(w, w->arg0, w->arg1, w->arg2, w->arg3, w->arg4); freework(w); } int wq_trywork(void) { struct work *w; int i; pushcli(); w = __wq_pop(mycpu()->id); if (w != NULL) { __wq_run(w); popcli(); return 1; } // XXX(sbw) should be random for (i = 0; i < NCPU; i++) { if (i == mycpu()->id) continue; w = __wq_steal(i); if (w != NULL) { __wq_run(w); popcli(); return 1; } } popcli(); return 0; } void wq_dump(void) { int i; for (i = 0; i < NCPU; i++) cprintf("push %lu full %lu pop %lu steal %lu\n", stat[i].push, stat[i].full, stat[i].pop, stat[i].steal); } static void __test_stub(struct work *w, void *a0, void *a1) { //long i = (long)a0; //cprintf("%u: %lu\n", cpunum(), i); volatile atomic<int> *running = (volatile atomic<int>*) a1; (*running)--; } void testwq(void) { enum { iters = 10 }; static volatile atomic<int> running(iters); u64 e, s; long i; pushcli(); if (mycpu()->id == 0) { microdelay(1); s = rdtsc(); for (i = 0; i < iters; i++) { if (wq_push2(__test_stub, (void*)i, (void*)&running) < 0) panic("testwq: oops"); } while (running) nop_pause(); e = rdtsc(); cprintf("testwq: %lu\n", (e-s)/iters); wq_dump(); } else { while (running) wq_trywork(); } popcli(); } static struct work ** do_allocwork(struct work **w, int iters) { int i; for (i = 0; i < iters; i++) w[i] = allocwork(); return w; } static struct work ** do_freework(struct work **w, int iters) { int i; for (i = 0; i < iters; i++) freework(w[i]); return w; } void benchwq(void) { enum { alloc_iters = 100 }; static volatile atomic<int> running(alloc_iters); static struct work *w[alloc_iters]; u64 e2, e, s; long i; pushcli(); if (mycpu()->id == 0) { microdelay(1); // Warm up do_allocwork(w, alloc_iters); do_freework(w, alloc_iters); s = rdtsc(); do_allocwork(w, alloc_iters); e = rdtsc(); cprintf("allocwork: %lu\n", (e-s)/alloc_iters); s = rdtsc(); do_freework(w, alloc_iters); e = rdtsc(); cprintf("freework: %lu\n", (e-s)/alloc_iters); do_allocwork(w, alloc_iters); for (i = 0;i < alloc_iters; i++) { w[i]->rip = (void*)__test_stub; w[i]->arg1 = (void*)&running; } s = rdtsc(); for (i = 0; i < alloc_iters; i++) { if (wq_push(w[i]) < 0) panic("testwq: oops"); } e = rdtsc(); while (running) nop_pause(); e2 = rdtsc(); cprintf("wq_push: %lu\n", (e-s)/alloc_iters); cprintf("wq finished: %lu\n", (e2-s)/alloc_iters); do_allocwork(w, alloc_iters); for (i = 0;i < alloc_iters; i++) { w[i]->rip = (void*)__test_stub; w[i]->arg1 = (void*)&running; } s = rdtsc(); for (i = 0; i < alloc_iters; i++) { running = 1; if (wq_push(w[i]) < 0) panic("testwq: oops"); while (running) nop_pause(); } e = rdtsc(); cprintf("wq_push one: %lu\n", (e-s)/alloc_iters); wq_dump(); } else { while (running) wq_trywork(); } popcli(); } void initwq(void) { int i; for (i = 0; i < NCPU; i++) initlock(&queue[i].lock, "wq lock", LOCKSTAT_WQ); } <|endoftext|>
<commit_before>// Copyright 2016 Etix Labs // // 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 "server.h" #include <iostream> #include <string.h> // Set config defaults or from env void parse_env(std::shared_ptr<t_config> config) { // Address config->address = DEFAULT_ADDRESS; if (const char *address = std::getenv("RTSP_ADDRESS")) { config->address = address; } // Port config->port = DEFAULT_PORT; if (const char *port = std::getenv("RTSP_PORT")) { config->port = port; } // Route config->route = DEFAULT_ROUTE; if (const char *route = std::getenv("RTSP_ROUTE")) { config->route = route; } // Username config->username = DEFAULT_USERNAME; if (const char *username = std::getenv("RTSP_USERNAME")) { config->username = username; } // Password config->password = DEFAULT_PASSWORD; if (const char *password = std::getenv("RTSP_PASSWORD")) { config->password = password; } // Framerate config->framerate = DEFAULT_FRAMERATE; if (const char *framerate = std::getenv("RTSP_FRAMERATE")) { config->framerate = framerate; } // Scale config->scale = std::make_pair<std::string, std::string>(DEFAULT_WIDTH, DEFAULT_HEIGHT); if (const char *scale = std::getenv("RTSP_RESOLUTION")) { size_t pos = 0; std::string scale_str(scale); if ((pos = scale_str.find("x")) == std::string::npos) { std::cerr << "No x token found between width and height in the scale argument: " << scale_str << std::endl << "Using default values"; } else { config->scale = std::make_pair<std::string, std::string>( scale_str.substr(0, pos), scale_str.substr(pos + 1)); } } // Input config->input = DEFAULT_INPUT; if (const char *input = std::getenv("INPUT")) { config->input = input; } config->time = DEFAULT_TIME_ENABLED; if (const char *time = std::getenv("ENABLE_TIME_OVERLAY")) { if (strcmp(time, "false") == 0) { config->time = false; } else { config->time = true; } } } // Overwrite default parameters via cmd line bool parse_args(std::shared_ptr<t_config> config, int argc, char **argv) { int c; opterr = 0; while ((c = getopt(argc, argv, "r:u:l:p:b:f:s:i:ht")) != -1) { switch (c) { case 'r': // Route if (optarg && optarg[0] == '-') { break; } if (not optarg[0] == '/') config->route = "/"; config->route += optarg; break; case 'u': // Username if (optarg && optarg[0] == '-') { break; } config->username = optarg; break; case 'p': // Password if (optarg && optarg[0] == '-') break; config->password = optarg; break; case 'i': // Input if (optarg && optarg[0] == '-') break; config->input = optarg; break; case 'l': // Listen address if (optarg && optarg[0] == '-') break; config->address = optarg; break; case 'b': // Port if (optarg && optarg[0] == '-') break; config->port = optarg; break; case 'f': // Framerate if (optarg && optarg[0] == '-') break; config->framerate = optarg; break; case 's': { // Scale if (optarg && optarg[0] == '-') break; size_t pos = 0; std::string scale = optarg; if ((pos = scale.find("x")) == std::string::npos) { std::cerr << "No x token found between width and height in the scale " "argument: " << scale << std::endl << "Using default values instead"; return false; } config->scale.first = scale.substr(0, pos); config->scale.second = scale.substr(pos + 1); break; } case 't': // Time Overlay config->time = true; break; case 'h': // help fprintf(stdout, "Usage: %s [-l address] [-b port] [-r route] [-i " "input] [-u username] [-p password] [-f framerate] [-s " "'width'x'height'] [-t] [-h]\n", argv[0]); return true; case '?': if (optopt == 'r' || optopt == 'l' || optopt == 'p' || optopt == 'u' || optopt == 'i' || optopt == 'a' || optopt == 'b' || optopt == 'f' || optopt == 's') fprintf(stderr, "Option -%c requires an argument.\n", optopt); else if (isprint(optopt)) fprintf(stderr, "Unknown option `-%c'.\n", optopt); else fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt); return false; default: return false; ; } } return true; } <commit_msg>v1.2.0: Fix codacy warnings (#25)<commit_after>// Copyright 2016 Etix Labs // // 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 "server.h" #include <iostream> #include <string.h> // Set config defaults or from env void parse_env(std::shared_ptr<t_config> config) { // Address config->address = DEFAULT_ADDRESS; if (const char *address = std::getenv("RTSP_ADDRESS")) { config->address = address; } // Port config->port = DEFAULT_PORT; if (const char *port = std::getenv("RTSP_PORT")) { config->port = port; } // Route config->route = DEFAULT_ROUTE; if (const char *route = std::getenv("RTSP_ROUTE")) { config->route = route; } // Username config->username = DEFAULT_USERNAME; if (const char *username = std::getenv("RTSP_USERNAME")) { config->username = username; } // Password config->password = DEFAULT_PASSWORD; if (const char *password = std::getenv("RTSP_PASSWORD")) { config->password = password; } // Framerate config->framerate = DEFAULT_FRAMERATE; if (const char *framerate = std::getenv("RTSP_FRAMERATE")) { config->framerate = framerate; } // Scale config->scale = std::make_pair<std::string, std::string>(DEFAULT_WIDTH, DEFAULT_HEIGHT); if (const char *scale = std::getenv("RTSP_RESOLUTION")) { size_t pos = 0; std::string scale_str(scale); if ((pos = scale_str.find("x")) == std::string::npos) { std::cerr << "No x token found between width and height in the scale argument: " << scale_str << std::endl << "Using default values"; } else { config->scale = std::make_pair<std::string, std::string>( scale_str.substr(0, pos), scale_str.substr(pos + 1)); } } // Input config->input = DEFAULT_INPUT; if (const char *input = std::getenv("INPUT")) { config->input = input; } config->time = DEFAULT_TIME_ENABLED; if (const char *time = std::getenv("ENABLE_TIME_OVERLAY")) { if (strcmp(time, "false") == 0) { config->time = false; } else { config->time = true; } } } // Overwrite default parameters via cmd line bool parse_args(std::shared_ptr<t_config> config, int argc, char **argv) { int c; opterr = 0; while ((c = getopt(argc, argv, "r:u:l:p:b:f:s:i:ht")) != -1) { switch (c) { case 'r': // Route if (optarg && optarg[0] == '-') { break; } if (not optarg[0] == '/') { config->route = "/"; } config->route += optarg; break; case 'u': // Username if (optarg && optarg[0] == '-') { break; } config->username = optarg; break; case 'p': // Password if (optarg && optarg[0] == '-') { break; } config->password = optarg; break; case 'i': // Input if (optarg && optarg[0] == '-') { break; } config->input = optarg; break; case 'l': // Listen address if (optarg && optarg[0] == '-') { break; } config->address = optarg; break; case 'b': // Port if (optarg && optarg[0] == '-') { break; } config->port = optarg; break; case 'f': // Framerate if (optarg && optarg[0] == '-') { break; } config->framerate = optarg; break; case 's': { // Scale if (optarg && optarg[0] == '-') { break; } size_t pos = 0; std::string scale = optarg; if ((pos = scale.find("x")) == std::string::npos) { std::cerr << "No x token found between width and height in the scale " "argument: " << scale << std::endl << "Using default values instead"; return false; } config->scale.first = scale.substr(0, pos); config->scale.second = scale.substr(pos + 1); break; } case 't': // Time Overlay config->time = true; break; case 'h': // help fprintf(stdout, "Usage: %s [-l address] [-b port] [-r route] [-i " "input] [-u username] [-p password] [-f framerate] [-s " "'width'x'height'] [-t] [-h]\n", argv[0]); return true; case '?': if (optopt == 'r' || optopt == 'l' || optopt == 'p' || optopt == 'u' || optopt == 'i' || optopt == 'a' || optopt == 'b' || optopt == 'f' || optopt == 's') { fprintf(stderr, "Option -%c requires an argument.\n", optopt); } else if (isprint(optopt)) { fprintf(stderr, "Unknown option `-%c'.\n", optopt); } else { fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt); } return false; default: return false; ; } } return true; } <|endoftext|>
<commit_before>/* * Copyright 2006-2008 The FLWOR Foundation. * * 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 "compiler/rewriter/framework/rule_driver.h" #include "compiler/rewriter/rules/ruleset.h" #include "compiler/rewriter/rewriters/common_rewriter.h" #include "compiler/rewriter/rewriters/default_optimizer.h" #include "util/properties.h" namespace zorba { class FoldRules : public RuleMajorDriver { public: FoldRules() { ADD_RULE(MarkExpensiveOps); ADD_RULE(MarkUnfoldableExprs); ADD_RULE(MarkImpureExprs); // Most rules try to update the freevars annotations, but for now let's stay on the safe side ADD_RULE(MarkFreeVars); ADD_RULE(FoldConst (false)); ADD_RULE(PartialEval); ADD_RULE(RefactorPredFLWOR); ADD_RULE(EliminateUnusedLetVars); } }; DefaultOptimizer::DefaultOptimizer() { if (Properties::instance ()->inlineUdf ()) ADD_SINGLETON_DRIVER(InlineFunctions); ADD_SINGLETON_DRIVER(InferVarTypes); ADD_SINGLETON_DRIVER(EliminateTypeEnforcingOperations); ADD_SINGLETON_DRIVER(EliminateExtraneousPathSteps); ADD_DRIVER(FoldRules); ADD_SINGLETON_DRIVER(ReplaceExprWithConstantOneWhenPossible); ADD_SINGLETON_DRIVER(MarkFreeVars); ADD_SINGLETON_DRIVER(EliminateUnusedLetVars); ADD_SINGLETON_DRIVER(MarkConsumerNodeProps); ADD_SINGLETON_DRIVER(MarkProducerNodeProps); ADD_SINGLETON_DRIVER(EliminateNodeOps); ADD_SINGLETON_DRIVER(SpecializeOperations); ADD_DRIVER(FoldRules); if (Properties::instance ()->loopHoisting ()) ADD_SINGLETON_DRIVER(HoistExprsOutOfLoops); // For UDFs, which need this annotation in udf::requires_dyn_ctx() // TODO: only do this for UDFs ADD_SINGLETON_DRIVER(MarkUnfoldableExprs); if (Properties::instance ()->inferJoins ()) ADD_ONCE_DRIVER(IndexJoin); ADD_SINGLETON_DRIVER(ExpandBuildIndex); } DefaultOptimizer::~DefaultOptimizer() throw () { } } <commit_msg>fixed hashjoin rule<commit_after>/* * Copyright 2006-2008 The FLWOR Foundation. * * 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 "compiler/rewriter/framework/rule_driver.h" #include "compiler/rewriter/rules/ruleset.h" #include "compiler/rewriter/rewriters/common_rewriter.h" #include "compiler/rewriter/rewriters/default_optimizer.h" #include "util/properties.h" namespace zorba { class FoldRules : public RuleMajorDriver { public: FoldRules() { ADD_RULE(MarkExpensiveOps); ADD_RULE(MarkUnfoldableExprs); ADD_RULE(MarkImpureExprs); // Most rules try to update the freevars annotations, but for now let's stay on the safe side ADD_RULE(MarkFreeVars); ADD_RULE(FoldConst (false)); ADD_RULE(PartialEval); ADD_RULE(RefactorPredFLWOR); ADD_RULE(EliminateUnusedLetVars); } }; DefaultOptimizer::DefaultOptimizer() { if (Properties::instance ()->inlineUdf ()) ADD_SINGLETON_DRIVER(InlineFunctions); ADD_SINGLETON_DRIVER(InferVarTypes); ADD_SINGLETON_DRIVER(EliminateTypeEnforcingOperations); ADD_SINGLETON_DRIVER(EliminateExtraneousPathSteps); ADD_DRIVER(FoldRules); ADD_SINGLETON_DRIVER(ReplaceExprWithConstantOneWhenPossible); ADD_SINGLETON_DRIVER(MarkFreeVars); ADD_SINGLETON_DRIVER(EliminateUnusedLetVars); ADD_SINGLETON_DRIVER(MarkConsumerNodeProps); ADD_SINGLETON_DRIVER(MarkProducerNodeProps); ADD_SINGLETON_DRIVER(EliminateNodeOps); ADD_SINGLETON_DRIVER(SpecializeOperations); ADD_DRIVER(FoldRules); if (Properties::instance ()->loopHoisting ()) ADD_SINGLETON_DRIVER(HoistExprsOutOfLoops); // For UDFs, which need this annotation in udf::requires_dyn_ctx() // TODO: only do this for UDFs ADD_SINGLETON_DRIVER(MarkUnfoldableExprs); if (Properties::instance ()->inferJoins ()) ADD_ONCE_DRIVER(IndexJoin); ADD_SINGLETON_DRIVER(ExpandBuildIndex); } DefaultOptimizer::~DefaultOptimizer() throw () { } } <|endoftext|>
<commit_before>/* * Arithmetic for point groups of elliptic curves over GF(p) * * (C) 2007 Martin Doering, Christoph Ludwig, Falko Strenzke * 2008-2010 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/point_gfp.h> #include <botan/numthry.h> #include <botan/mp_asm.h> #include <botan/mp_asmi.h> #include <botan/mp_core.h> namespace Botan { PointGFp::PointGFp(const CurveGFp& curve) : curve(curve), coord_x(0), coord_y(curve.get_r()), coord_z(0) { } PointGFp::PointGFp(const CurveGFp& curve, const BigInt& x, const BigInt& y) : curve(curve) { const Modular_Reducer& mod_p = curve.mod_p(); coord_x = mod_p.multiply(curve.get_r(), x); coord_y = mod_p.multiply(curve.get_r(), y); coord_z = curve.get_r(); } BigInt PointGFp::monty_mult(const BigInt& a, const BigInt& b) { if(a.is_zero() || b.is_zero()) return 0; const BigInt& p = curve.get_p(); const u32bit p_size = p.sig_words(); const word p_dash = curve.get_p_dash(); SecureVector<word> t; t.grow_to(2*p_size+1); if(a > 0 && b > 0 && a < p && b < p) { bigint_simple_mul(t, a.data(), a.sig_words(), b.data(), b.sig_words()); } else { const Modular_Reducer& mod_p = curve.mod_p(); BigInt a2 = mod_p.reduce(a); BigInt b2 = mod_p.reduce(b); a2.grow_to(p_size); b2.grow_to(p_size); bigint_simple_mul(t, a2.data(), a2.sig_words(), b2.data(), b2.sig_words()); } BigInt result; std::swap(result.get_reg(), t); bigint_monty_redc(result.get_reg(), result.size(), p.data(), p_size, p_dash); result >>= p_size*BOTAN_MP_WORD_BITS; return result; } // arithmetic operators PointGFp& PointGFp::operator+=(const PointGFp& rhs) { if(rhs.is_zero()) return *this; if(is_zero()) { *this = rhs; return *this; } const Modular_Reducer& mod_p = curve.mod_p(); BigInt rhs_z2 = monty_mult(rhs.coord_z, rhs.coord_z); BigInt U1 = monty_mult(coord_x, rhs_z2); BigInt S1 = monty_mult(coord_y, monty_mult(rhs.coord_z, rhs_z2)); BigInt lhs_z2 = monty_mult(coord_z, coord_z); BigInt U2 = monty_mult(rhs.coord_x, lhs_z2); BigInt S2 = monty_mult(rhs.coord_y, monty_mult(coord_z, lhs_z2)); BigInt H = mod_p.reduce(U2 - U1); BigInt r = mod_p.reduce(S2 - S1); if(H.is_zero()) { if(r.is_zero()) { mult2(); return *this; } *this = PointGFp(curve); // setting myself to zero return *this; } U2 = monty_mult(H, H); S2 = monty_mult(U2, H); U2 = monty_mult(U1, U2); BigInt x = mod_p.reduce(monty_mult(r, r) - S2 - U2*2); U2 = mod_p.reduce(U2 - x); BigInt y = monty_mult(r, U2) - monty_mult(S1, S2); BigInt z = monty_mult(monty_mult(coord_z, rhs.coord_z), H); coord_x = x; coord_y = y; coord_z = z; return *this; } PointGFp& PointGFp::operator-=(const PointGFp& rhs) { PointGFp minus_rhs = PointGFp(rhs).negate(); if(is_zero()) *this = minus_rhs; else *this += minus_rhs; return *this; } PointGFp& PointGFp::operator*=(const BigInt& scalar) { if(scalar.abs() <= 2) // special cases for small values { u32bit value = scalar.abs().to_u32bit(); if(value == 0) *this = PointGFp(curve); // set to zero point else if(value == 1) { if(scalar.is_negative()) this->negate(); } else if(value == 2) { this->mult2(); if(scalar.is_negative()) this->negate(); } return *this; } PointGFp H(this->curve); // create as zero PointGFp P(*this); if(scalar.is_negative()) P.negate(); for(int i = scalar.bits() - 1; i >= 0; --i) { H.mult2(); if(scalar.get_bit(i)) H += P; } *this = H; return *this; } // *this *= 2 void PointGFp::mult2() { if(is_zero()) return; else if(coord_y.is_zero()) { *this = PointGFp(curve); // setting myself to zero return; } const Modular_Reducer& mod_p = curve.mod_p(); BigInt y_2 = monty_mult(coord_y, coord_y); BigInt S = mod_p.reduce(4 * monty_mult(coord_x, y_2)); BigInt z4 = monty_mult(coord_z, coord_z); z4 = monty_mult(z4, z4); BigInt a_z4 = monty_mult(curve.get_a_r(), z4); BigInt M = mod_p.reduce(a_z4 + 3 * monty_mult(coord_x, coord_x)); BigInt x = monty_mult(M, M) - 2*S; BigInt U = 8 * monty_mult(y_2, y_2); BigInt y = monty_mult(M, S - x) - U; BigInt z = 2 * monty_mult(coord_y, coord_z); coord_x = x; coord_y = y; coord_z = z; } BigInt PointGFp::get_affine_x() const { if(is_zero()) throw Illegal_Transformation("Cannot convert zero point to affine"); const Modular_Reducer& mod_p = curve.mod_p(); BigInt x = mod_p.multiply(curve.get_r_inv(), coord_x); BigInt z = mod_p.multiply(curve.get_r_inv(), coord_z); BigInt z2 = mod_p.square(z); return mod_p.multiply(x, inverse_mod(z2, curve.get_p())); } BigInt PointGFp::get_affine_y() const { if(is_zero()) throw Illegal_Transformation("Cannot convert zero point to affine"); const Modular_Reducer& mod_p = curve.mod_p(); BigInt y = mod_p.multiply(curve.get_r_inv(), coord_y); BigInt z = mod_p.multiply(curve.get_r_inv(), coord_z); BigInt z3 = mod_p.cube(z); return mod_p.multiply(y, inverse_mod(z3, curve.get_p())); } void PointGFp::check_invariants() const { /* Is the point still on the curve?? (If everything is correct, the point is always on its curve; then the function will return silently. If Oskar managed to corrupt this object's state, then it will throw an exception.) */ if(is_zero()) return; const Modular_Reducer& mod_p = curve.mod_p(); BigInt x = mod_p.multiply(curve.get_r_inv(), coord_x); BigInt y = mod_p.multiply(curve.get_r_inv(), coord_y); BigInt z = mod_p.multiply(curve.get_r_inv(), coord_z); BigInt y2 = mod_p.square(y); BigInt x3 = mod_p.cube(x); BigInt ax = mod_p.multiply(x, curve.get_a()); if(z == 1) { if(mod_p.reduce(x3 + ax + curve.get_b()) != y2) throw Illegal_Point("Invalid ECP point: y^2 != x^3 + a*x + b"); } BigInt z2 = mod_p.square(z); BigInt z3 = mod_p.multiply(z, z2); BigInt ax_z4 = mod_p.multiply(mod_p.multiply(z3, z), ax); BigInt b_z6 = mod_p.multiply(curve.get_b(), mod_p.square(z3)); if(y2 != mod_p.reduce(x3 + ax_z4 + b_z6)) throw Illegal_Point("Invalid ECP point: y^2 != x^3 + a*x*z^4 + b*z^6"); } // swaps the states of *this and other, does not throw! void PointGFp::swap(PointGFp& other) { curve.swap(other.curve); coord_x.swap(other.coord_x); coord_y.swap(other.coord_y); coord_z.swap(other.coord_z); } bool PointGFp::operator==(const PointGFp& other) const { if(get_curve() != other.get_curve()) return false; // If this is zero, only equal if other is also zero if(is_zero()) return other.is_zero(); return (get_affine_x() == other.get_affine_x() && get_affine_y() == other.get_affine_y()); } // encoding and decoding SecureVector<byte> EC2OSP(const PointGFp& point, byte format) { if(point.is_zero()) return SecureVector<byte>(1); // single 0 byte const u32bit p_bytes = point.get_curve().get_p().bytes(); BigInt x = point.get_affine_x(); BigInt y = point.get_affine_y(); SecureVector<byte> bX = BigInt::encode_1363(x, p_bytes); SecureVector<byte> bY = BigInt::encode_1363(y, p_bytes); if(format == PointGFp::UNCOMPRESSED) { SecureVector<byte> result(2*p_bytes+1); result[0] = 4; result.copy(1, bX.begin(), p_bytes); result.copy(p_bytes+1, bY.begin(), p_bytes); return result; } else if(format == PointGFp::COMPRESSED) { SecureVector<byte> result(p_bytes+1); result[0] = 2; result.copy(1, bX.begin(), bX.size()); if(y.get_bit(0)) result[0] |= 1; return result; } else if(format == PointGFp::HYBRID) { SecureVector<byte> result(2*p_bytes+1); result[0] = 6; result.copy(1, bX.begin(), bX.size()); result.copy(p_bytes+1, bY.begin(), bY.size()); if(y.get_bit(0)) result[0] |= 1; return result; } else throw Invalid_Argument("illegal point encoding format specification"); } namespace { BigInt decompress_point(bool yMod2, const BigInt& x, const CurveGFp& curve) { BigInt xpow3 = x * x * x; BigInt g = curve.get_a() * x; g += xpow3; g += curve.get_b(); g = g % curve.get_p(); BigInt z = ressol(g, curve.get_p()); if(z < 0) throw Illegal_Point("error during decompression"); if(z.get_bit(0) != yMod2) z = curve.get_p() - z; return z; } } PointGFp OS2ECP(const byte data[], u32bit data_len, const CurveGFp& curve) { if(data_len <= 1) return PointGFp(curve); // return zero const byte pc = data[0]; BigInt x, y; if(pc == 2 || pc == 3) { //compressed form x = BigInt::decode(&data[1], data_len - 1); bool yMod2 = ((pc & 0x01) == 1); y = decompress_point(yMod2, x, curve); } else if(pc == 4) { const u32bit l = (data_len - 1) / 2; // uncompressed form x = BigInt::decode(&data[1], l); y = BigInt::decode(&data[l+1], l); } else if(pc == 6 || pc == 7) { const u32bit l = (data_len - 1) / 2; // hybrid form x = BigInt::decode(&data[1], l); y = BigInt::decode(&data[l+1], l); bool yMod2 = ((pc & 0x01) == 1); if(decompress_point(yMod2, x, curve) != y) throw Illegal_Point("OS2ECP: Decoding error in hybrid format"); } else throw Invalid_Argument("OS2ECP: Unknown format type"); PointGFp result(curve, x, y); result.check_invariants(); return result; } } <commit_msg>Unroll point multiply to look at two bits of scalar each iteration. Helps out quite a bit.<commit_after>/* * Arithmetic for point groups of elliptic curves over GF(p) * * (C) 2007 Martin Doering, Christoph Ludwig, Falko Strenzke * 2008-2010 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/point_gfp.h> #include <botan/numthry.h> #include <botan/mp_asm.h> #include <botan/mp_asmi.h> #include <botan/mp_core.h> #include <stdio.h> namespace Botan { PointGFp::PointGFp(const CurveGFp& curve) : curve(curve), coord_x(0), coord_y(curve.get_r()), coord_z(0) { } PointGFp::PointGFp(const CurveGFp& curve, const BigInt& x, const BigInt& y) : curve(curve) { const Modular_Reducer& mod_p = curve.mod_p(); coord_x = mod_p.multiply(curve.get_r(), x); coord_y = mod_p.multiply(curve.get_r(), y); coord_z = curve.get_r(); } BigInt PointGFp::monty_mult(const BigInt& a, const BigInt& b) { if(a.is_zero() || b.is_zero()) return 0; const BigInt& p = curve.get_p(); const u32bit p_size = p.sig_words(); const word p_dash = curve.get_p_dash(); SecureVector<word> t; t.grow_to(2*p_size+1); if(a > 0 && b > 0 && a < p && b < p) { bigint_simple_mul(t, a.data(), a.sig_words(), b.data(), b.sig_words()); } else { const Modular_Reducer& mod_p = curve.mod_p(); BigInt a2 = mod_p.reduce(a); BigInt b2 = mod_p.reduce(b); a2.grow_to(p_size); b2.grow_to(p_size); bigint_simple_mul(t, a2.data(), a2.sig_words(), b2.data(), b2.sig_words()); } BigInt result; std::swap(result.get_reg(), t); bigint_monty_redc(result.get_reg(), result.size(), p.data(), p_size, p_dash); result >>= p_size*BOTAN_MP_WORD_BITS; return result; } // arithmetic operators PointGFp& PointGFp::operator+=(const PointGFp& rhs) { if(rhs.is_zero()) return *this; if(is_zero()) { *this = rhs; return *this; } const Modular_Reducer& mod_p = curve.mod_p(); BigInt rhs_z2 = monty_mult(rhs.coord_z, rhs.coord_z); BigInt U1 = monty_mult(coord_x, rhs_z2); BigInt S1 = monty_mult(coord_y, monty_mult(rhs.coord_z, rhs_z2)); BigInt lhs_z2 = monty_mult(coord_z, coord_z); BigInt U2 = monty_mult(rhs.coord_x, lhs_z2); BigInt S2 = monty_mult(rhs.coord_y, monty_mult(coord_z, lhs_z2)); BigInt H = mod_p.reduce(U2 - U1); BigInt r = mod_p.reduce(S2 - S1); if(H.is_zero()) { if(r.is_zero()) { mult2(); return *this; } *this = PointGFp(curve); // setting myself to zero return *this; } U2 = monty_mult(H, H); S2 = monty_mult(U2, H); U2 = monty_mult(U1, U2); BigInt x = mod_p.reduce(monty_mult(r, r) - S2 - U2*2); U2 = mod_p.reduce(U2 - x); BigInt y = monty_mult(r, U2) - monty_mult(S1, S2); BigInt z = monty_mult(monty_mult(coord_z, rhs.coord_z), H); coord_x = x; coord_y = y; coord_z = z; return *this; } PointGFp& PointGFp::operator-=(const PointGFp& rhs) { PointGFp minus_rhs = PointGFp(rhs).negate(); if(is_zero()) *this = minus_rhs; else *this += minus_rhs; return *this; } PointGFp& PointGFp::operator*=(const BigInt& scalar) { if(scalar.abs() <= 2) // special cases for small values { u32bit value = scalar.abs().to_u32bit(); if(value == 0) *this = PointGFp(curve); // set to zero point else if(value == 1) { if(scalar.is_negative()) this->negate(); } else if(value == 2) { this->mult2(); if(scalar.is_negative()) this->negate(); } return *this; } PointGFp H(this->curve); // create as zero PointGFp P(*this); if(scalar.is_negative()) P.negate(); u32bit scalar_bits = scalar.bits(); PointGFp P2 = P * 2; PointGFp P3 = P2 + P; for(u32bit i = 0; i < scalar_bits - 1; i += 2) { u32bit twobits = scalar.get_substring(scalar_bits - i - 2, 2); H.mult2(); H.mult2(); if(twobits == 3) H += P3; else if(twobits == 2) H += P2; else if(twobits == 1) H += P; } if(scalar_bits % 2) { H.mult2(); if(scalar.get_bit(0)) H += P; } *this = H; return *this; } // *this *= 2 void PointGFp::mult2() { if(is_zero()) return; else if(coord_y.is_zero()) { *this = PointGFp(curve); // setting myself to zero return; } const Modular_Reducer& mod_p = curve.mod_p(); BigInt y_2 = monty_mult(coord_y, coord_y); BigInt S = mod_p.reduce(4 * monty_mult(coord_x, y_2)); BigInt z4 = monty_mult(coord_z, coord_z); z4 = monty_mult(z4, z4); BigInt a_z4 = monty_mult(curve.get_a_r(), z4); BigInt M = mod_p.reduce(a_z4 + 3 * monty_mult(coord_x, coord_x)); BigInt x = monty_mult(M, M) - 2*S; BigInt U = 8 * monty_mult(y_2, y_2); BigInt y = monty_mult(M, S - x) - U; BigInt z = 2 * monty_mult(coord_y, coord_z); coord_x = x; coord_y = y; coord_z = z; } BigInt PointGFp::get_affine_x() const { if(is_zero()) throw Illegal_Transformation("Cannot convert zero point to affine"); const Modular_Reducer& mod_p = curve.mod_p(); BigInt x = mod_p.multiply(curve.get_r_inv(), coord_x); BigInt z = mod_p.multiply(curve.get_r_inv(), coord_z); BigInt z2 = mod_p.square(z); return mod_p.multiply(x, inverse_mod(z2, curve.get_p())); } BigInt PointGFp::get_affine_y() const { if(is_zero()) throw Illegal_Transformation("Cannot convert zero point to affine"); const Modular_Reducer& mod_p = curve.mod_p(); BigInt y = mod_p.multiply(curve.get_r_inv(), coord_y); BigInt z = mod_p.multiply(curve.get_r_inv(), coord_z); BigInt z3 = mod_p.cube(z); return mod_p.multiply(y, inverse_mod(z3, curve.get_p())); } void PointGFp::check_invariants() const { /* Is the point still on the curve?? (If everything is correct, the point is always on its curve; then the function will return silently. If Oskar managed to corrupt this object's state, then it will throw an exception.) */ if(is_zero()) return; const Modular_Reducer& mod_p = curve.mod_p(); BigInt x = mod_p.multiply(curve.get_r_inv(), coord_x); BigInt y = mod_p.multiply(curve.get_r_inv(), coord_y); BigInt z = mod_p.multiply(curve.get_r_inv(), coord_z); BigInt y2 = mod_p.square(y); BigInt x3 = mod_p.cube(x); BigInt ax = mod_p.multiply(x, curve.get_a()); if(z == 1) { if(mod_p.reduce(x3 + ax + curve.get_b()) != y2) throw Illegal_Point("Invalid ECP point: y^2 != x^3 + a*x + b"); } BigInt z2 = mod_p.square(z); BigInt z3 = mod_p.multiply(z, z2); BigInt ax_z4 = mod_p.multiply(mod_p.multiply(z3, z), ax); BigInt b_z6 = mod_p.multiply(curve.get_b(), mod_p.square(z3)); if(y2 != mod_p.reduce(x3 + ax_z4 + b_z6)) throw Illegal_Point("Invalid ECP point: y^2 != x^3 + a*x*z^4 + b*z^6"); } // swaps the states of *this and other, does not throw! void PointGFp::swap(PointGFp& other) { curve.swap(other.curve); coord_x.swap(other.coord_x); coord_y.swap(other.coord_y); coord_z.swap(other.coord_z); } bool PointGFp::operator==(const PointGFp& other) const { if(get_curve() != other.get_curve()) return false; // If this is zero, only equal if other is also zero if(is_zero()) return other.is_zero(); return (get_affine_x() == other.get_affine_x() && get_affine_y() == other.get_affine_y()); } // encoding and decoding SecureVector<byte> EC2OSP(const PointGFp& point, byte format) { if(point.is_zero()) return SecureVector<byte>(1); // single 0 byte const u32bit p_bytes = point.get_curve().get_p().bytes(); BigInt x = point.get_affine_x(); BigInt y = point.get_affine_y(); SecureVector<byte> bX = BigInt::encode_1363(x, p_bytes); SecureVector<byte> bY = BigInt::encode_1363(y, p_bytes); if(format == PointGFp::UNCOMPRESSED) { SecureVector<byte> result(2*p_bytes+1); result[0] = 4; result.copy(1, bX.begin(), p_bytes); result.copy(p_bytes+1, bY.begin(), p_bytes); return result; } else if(format == PointGFp::COMPRESSED) { SecureVector<byte> result(p_bytes+1); result[0] = 2; result.copy(1, bX.begin(), bX.size()); if(y.get_bit(0)) result[0] |= 1; return result; } else if(format == PointGFp::HYBRID) { SecureVector<byte> result(2*p_bytes+1); result[0] = 6; result.copy(1, bX.begin(), bX.size()); result.copy(p_bytes+1, bY.begin(), bY.size()); if(y.get_bit(0)) result[0] |= 1; return result; } else throw Invalid_Argument("illegal point encoding format specification"); } namespace { BigInt decompress_point(bool yMod2, const BigInt& x, const CurveGFp& curve) { BigInt xpow3 = x * x * x; BigInt g = curve.get_a() * x; g += xpow3; g += curve.get_b(); g = g % curve.get_p(); BigInt z = ressol(g, curve.get_p()); if(z < 0) throw Illegal_Point("error during decompression"); if(z.get_bit(0) != yMod2) z = curve.get_p() - z; return z; } } PointGFp OS2ECP(const byte data[], u32bit data_len, const CurveGFp& curve) { if(data_len <= 1) return PointGFp(curve); // return zero const byte pc = data[0]; BigInt x, y; if(pc == 2 || pc == 3) { //compressed form x = BigInt::decode(&data[1], data_len - 1); bool yMod2 = ((pc & 0x01) == 1); y = decompress_point(yMod2, x, curve); } else if(pc == 4) { const u32bit l = (data_len - 1) / 2; // uncompressed form x = BigInt::decode(&data[1], l); y = BigInt::decode(&data[l+1], l); } else if(pc == 6 || pc == 7) { const u32bit l = (data_len - 1) / 2; // hybrid form x = BigInt::decode(&data[1], l); y = BigInt::decode(&data[l+1], l); bool yMod2 = ((pc & 0x01) == 1); if(decompress_point(yMod2, x, curve) != y) throw Illegal_Point("OS2ECP: Decoding error in hybrid format"); } else throw Invalid_Argument("OS2ECP: Unknown format type"); PointGFp result(curve, x, y); result.check_invariants(); return result; } } <|endoftext|>
<commit_before>#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_ROWWISE_REDUCTION_HPP #define STAN_MATH_OPENCL_KERNEL_GENERATOR_ROWWISE_REDUCTION_HPP #ifdef STAN_OPENCL #include <stan/math/opencl/matrix_cl_view.hpp> #include <stan/math/prim/meta.hpp> #include <stan/math/opencl/kernel_generator/type_str.hpp> #include <stan/math/opencl/kernel_generator/name_generator.hpp> #include <stan/math/opencl/kernel_generator/operation_cl.hpp> #include <stan/math/opencl/kernel_generator/as_operation_cl.hpp> #include <stan/math/opencl/kernel_generator/is_valid_expression.hpp> #include <string> #include <type_traits> #include <set> #include <utility> namespace stan { namespace math { /** * Represents a rowwise reduction in kernel generator expressions. * @tparam Derived derived type * @tparam T type of first argument * @tparam operation type with member function generate that accepts two * variable names and returns OpenCL source code for reduction operation_cl * @tparam PassZero whether \c operation passes trough zeros * @tparam Rowwise whether this is row wise reduction * @tparam Colwise whether this is column wise reduction */ template <typename Derived, typename T, typename operation, bool PassZero> class rowwise_reduction : public operation_cl<Derived, typename std::remove_reference_t<T>::Scalar, T> { public: using Scalar = typename std::remove_reference_t<T>::Scalar; using base = operation_cl<Derived, Scalar, T>; using base::var_name; protected: std::string init_; using base::arguments_; public: /** * Constructor * @param a the expression to reduce * @param init OpenCL source code of initialization value for reduction */ rowwise_reduction(T&& a, const std::string& init) : base(std::forward<T>(a)), init_(init) {} /** * Generates kernel code for this expression. * @param i row index variable name * @param j column index variable name * @param var_name_arg name of the variable in kernel that holds argument to * this expression * @return part of kernel with code for this expression */ inline kernel_parts generate(const std::string& i, const std::string& j, const std::string& var_name_arg) const { kernel_parts res; res.body_start = type_str<Scalar>() + " " + var_name + " = " + init_ + ";\n"; if (PassZero) { res.body_start += "for(int " + var_name + "_j = contains_nonzero(" + var_name + "_view, LOWER) ? 0 : " + i + "; " + var_name + "_j < (contains_nonzero(" + var_name + "_view, UPPER) ? " + var_name + "_cols : " + i + " + 1); " + var_name + "_j++){\n"; } else { res.body_start += "for(int " + var_name + "_j = 0; " + var_name + "_j < " + var_name + "_cols; " + var_name + "_j++){\n"; } res.body += var_name + " = " + operation::generate(var_name, var_name_arg) + ";\n}\n"; res.args = "int " + var_name + "_view, int " + var_name + "_cols, "; return res; } /** * Sets offset of block to indices of the argument expression * @param[in, out] i row index * @param[in, out] j column index */ inline void modify_argument_indices(std::string& i, std::string& j) const { j = var_name + "_j"; } /** * Sets kernel arguments for this and nested expressions. * @param[in,out] generated set of expressions that already set their kernel * arguments * @param kernel kernel to set arguments on * @param[in,out] arg_num consecutive number of the first argument to set. * This is incremented for each argument set by this function. */ inline void set_args(std::set<const operation_cl_base*>& generated, cl::Kernel& kernel, int& arg_num) const { if (generated.count(this) == 0) { generated.insert(this); std::get<0>(arguments_).set_args(generated, kernel, arg_num); kernel.setArg(arg_num++, std::get<0>(arguments_).view()); kernel.setArg(arg_num++, std::get<0>(arguments_).cols()); } } /** * Number of columns of a matrix that would be the result of evaluating this * expression. * @return number of columns */ inline int cols() const { return 1; } /** * View of a matrix that would be the result of evaluating this expression. * @return view */ matrix_cl_view view() const { return matrix_cl_view::Entire; } /** * Determine index of top diagonal written. * @return number of columns */ inline int top_diagonal() const { return 1; } }; /** * Operation for sum reduction. */ struct sum_op { /** * Generates sum reduction kernel code. * @param a first variable * @param b second variable * @return reduction code */ inline static std::string generate(const std::string& a, const std::string& b) { return a + " + " + b; } }; /** * Represents rowwise sum reduction in kernel generator expressions. * @tparam T type of expression */ template <typename T> class rowwise_sum_ : public rowwise_reduction<rowwise_sum_<T>, T, sum_op, true> { public: explicit rowwise_sum_(T&& a) : rowwise_reduction<rowwise_sum_<T>, T, sum_op, true>(std::forward<T>(a), "0") {} }; /** * Rowwise sum reduction of a kernel generator expression. * @tparam T type of input expression * @param a expression to reduce * @return sum */ template <typename T, typename = require_all_valid_expressions_and_none_scalar_t<T>> inline rowwise_sum_<as_operation_cl_t<T>> rowwise_sum(T&& a) { return rowwise_sum_<as_operation_cl_t<T>>( as_operation_cl(std::forward<T>(a))); } /** * Operation for max reduction. * @tparam T type to reduce */ template <typename T> struct max_op { /** * Generates max reduction kernel code. * @param a first variable * @param b second variable * @return reduction code */ inline static std::string generate(const std::string& a, const std::string& b) { if (std::is_floating_point<T>()) { return "fmax(" + a + ", " + b + ")"; } return "max(" + a + ", " + b + ")"; } inline static std::string init() { if (std::is_floating_point<T>()) { return "-INFINITY"; } return "INT_MIN"; } }; /** * Represents rowwise max reduction in kernel generator expressions. * @tparam T type of expression */ template <typename T> class rowwise_max_ : public rowwise_reduction< rowwise_max_<T>, T, max_op<typename std::remove_reference_t<T>::Scalar>, false> { public: using op = max_op<typename std::remove_reference_t<T>::Scalar>; explicit rowwise_max_(T&& a) : rowwise_reduction<rowwise_max_<T>, T, op, false>(std::forward<T>(a), op::init()) {} }; /** * Rowwise max reduction of a kernel generator expression. * @tparam T type of input expression * @param a expression to reduce * @return max */ template <typename T, typename = require_all_valid_expressions_and_none_scalar_t<T>> inline rowwise_max_<as_operation_cl_t<T>> rowwise_max(T&& a) { return rowwise_max_<as_operation_cl_t<T>>( as_operation_cl(std::forward<T>(a))); } /** * Operation for min reduction. * @tparam T type to reduce */ template <typename T> struct min_op { /** * Generates min reduction kernel code. * @param a first variable * @param b second variable * @return reduction code */ inline static std::string generate(const std::string& a, const std::string& b) { if (std::is_floating_point<T>()) { return "fmin(" + a + ", " + b + ")"; } return "min(" + a + ", " + b + ")"; } inline static std::string init() { if (std::is_floating_point<T>()) { return "INFINITY"; } return "INT_MAX"; } }; /** * Represents rowwise min reduction in kernel generator expressions. * @tparam T type of expression */ template <typename T> class rowwise_min_ : public rowwise_reduction< rowwise_min_<T>, T, min_op<typename std::remove_reference_t<T>::Scalar>, false> { public: using op = min_op<typename std::remove_reference_t<T>::Scalar>; explicit rowwise_min_(T&& a) : rowwise_reduction<rowwise_min_<T>, T, op, false>(std::forward<T>(a), op::init()) {} }; /** * Min reduction of a kernel generator expression. * @tparam T type of input expression * @param a expression to reduce * @return min */ template <typename T, typename = require_all_valid_expressions_and_none_scalar_t<T>> inline rowwise_min_<as_operation_cl_t<T>> rowwise_min(T&& a) { return rowwise_min_<as_operation_cl_t<T>>( as_operation_cl(std::forward<T>(a))); } } // namespace math } // namespace stan #endif #endif <commit_msg>bugfix reading memory out of matrix bounds.<commit_after>#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_ROWWISE_REDUCTION_HPP #define STAN_MATH_OPENCL_KERNEL_GENERATOR_ROWWISE_REDUCTION_HPP #ifdef STAN_OPENCL #include <stan/math/opencl/matrix_cl_view.hpp> #include <stan/math/prim/meta.hpp> #include <stan/math/opencl/kernel_generator/type_str.hpp> #include <stan/math/opencl/kernel_generator/name_generator.hpp> #include <stan/math/opencl/kernel_generator/operation_cl.hpp> #include <stan/math/opencl/kernel_generator/as_operation_cl.hpp> #include <stan/math/opencl/kernel_generator/is_valid_expression.hpp> #include <string> #include <type_traits> #include <set> #include <utility> namespace stan { namespace math { /** * Represents a rowwise reduction in kernel generator expressions. * @tparam Derived derived type * @tparam T type of first argument * @tparam operation type with member function generate that accepts two * variable names and returns OpenCL source code for reduction operation_cl * @tparam PassZero whether \c operation passes trough zeros * @tparam Rowwise whether this is row wise reduction * @tparam Colwise whether this is column wise reduction */ template <typename Derived, typename T, typename operation, bool PassZero> class rowwise_reduction : public operation_cl<Derived, typename std::remove_reference_t<T>::Scalar, T> { public: using Scalar = typename std::remove_reference_t<T>::Scalar; using base = operation_cl<Derived, Scalar, T>; using base::var_name; protected: std::string init_; using base::arguments_; public: /** * Constructor * @param a the expression to reduce * @param init OpenCL source code of initialization value for reduction */ rowwise_reduction(T&& a, const std::string& init) : base(std::forward<T>(a)), init_(init) {} /** * Generates kernel code for this expression. * @param i row index variable name * @param j column index variable name * @param var_name_arg name of the variable in kernel that holds argument to * this expression * @return part of kernel with code for this expression */ inline kernel_parts generate(const std::string& i, const std::string& j, const std::string& var_name_arg) const { kernel_parts res; res.body_start = type_str<Scalar>() + " " + var_name + " = " + init_ + ";\n"; if (PassZero) { res.body_start += "for(int " + var_name + "_j = contains_nonzero(" + var_name + "_view, LOWER) ? 0 : " + i + "; " + var_name + "_j < (contains_nonzero(" + var_name + "_view, UPPER) ? " + var_name + "_cols : min(" + var_name + "_cols, " + i + " + 1)); " + var_name + "_j++){\n"; } else { res.body_start += "for(int " + var_name + "_j = 0; " + var_name + "_j < " + var_name + "_cols; " + var_name + "_j++){\n"; } res.body += var_name + " = " + operation::generate(var_name, var_name_arg) + ";\n}\n"; res.args = "int " + var_name + "_view, int " + var_name + "_cols, "; return res; } /** * Sets offset of block to indices of the argument expression * @param[in, out] i row index * @param[in, out] j column index */ inline void modify_argument_indices(std::string& i, std::string& j) const { j = var_name + "_j"; } /** * Sets kernel arguments for this and nested expressions. * @param[in,out] generated set of expressions that already set their kernel * arguments * @param kernel kernel to set arguments on * @param[in,out] arg_num consecutive number of the first argument to set. * This is incremented for each argument set by this function. */ inline void set_args(std::set<const operation_cl_base*>& generated, cl::Kernel& kernel, int& arg_num) const { if (generated.count(this) == 0) { generated.insert(this); std::get<0>(arguments_).set_args(generated, kernel, arg_num); kernel.setArg(arg_num++, std::get<0>(arguments_).view()); kernel.setArg(arg_num++, std::get<0>(arguments_).cols()); } } /** * Number of columns of a matrix that would be the result of evaluating this * expression. * @return number of columns */ inline int cols() const { return 1; } /** * View of a matrix that would be the result of evaluating this expression. * @return view */ matrix_cl_view view() const { return matrix_cl_view::Entire; } /** * Determine index of top diagonal written. * @return number of columns */ inline int top_diagonal() const { return 1; } }; /** * Operation for sum reduction. */ struct sum_op { /** * Generates sum reduction kernel code. * @param a first variable * @param b second variable * @return reduction code */ inline static std::string generate(const std::string& a, const std::string& b) { return a + " + " + b; } }; /** * Represents rowwise sum reduction in kernel generator expressions. * @tparam T type of expression */ template <typename T> class rowwise_sum_ : public rowwise_reduction<rowwise_sum_<T>, T, sum_op, true> { public: explicit rowwise_sum_(T&& a) : rowwise_reduction<rowwise_sum_<T>, T, sum_op, true>(std::forward<T>(a), "0") {} }; /** * Rowwise sum reduction of a kernel generator expression. * @tparam T type of input expression * @param a expression to reduce * @return sum */ template <typename T, typename = require_all_valid_expressions_and_none_scalar_t<T>> inline rowwise_sum_<as_operation_cl_t<T>> rowwise_sum(T&& a) { return rowwise_sum_<as_operation_cl_t<T>>( as_operation_cl(std::forward<T>(a))); } /** * Operation for max reduction. * @tparam T type to reduce */ template <typename T> struct max_op { /** * Generates max reduction kernel code. * @param a first variable * @param b second variable * @return reduction code */ inline static std::string generate(const std::string& a, const std::string& b) { if (std::is_floating_point<T>()) { return "fmax(" + a + ", " + b + ")"; } return "max(" + a + ", " + b + ")"; } inline static std::string init() { if (std::is_floating_point<T>()) { return "-INFINITY"; } return "INT_MIN"; } }; /** * Represents rowwise max reduction in kernel generator expressions. * @tparam T type of expression */ template <typename T> class rowwise_max_ : public rowwise_reduction< rowwise_max_<T>, T, max_op<typename std::remove_reference_t<T>::Scalar>, false> { public: using op = max_op<typename std::remove_reference_t<T>::Scalar>; explicit rowwise_max_(T&& a) : rowwise_reduction<rowwise_max_<T>, T, op, false>(std::forward<T>(a), op::init()) {} }; /** * Rowwise max reduction of a kernel generator expression. * @tparam T type of input expression * @param a expression to reduce * @return max */ template <typename T, typename = require_all_valid_expressions_and_none_scalar_t<T>> inline rowwise_max_<as_operation_cl_t<T>> rowwise_max(T&& a) { return rowwise_max_<as_operation_cl_t<T>>( as_operation_cl(std::forward<T>(a))); } /** * Operation for min reduction. * @tparam T type to reduce */ template <typename T> struct min_op { /** * Generates min reduction kernel code. * @param a first variable * @param b second variable * @return reduction code */ inline static std::string generate(const std::string& a, const std::string& b) { if (std::is_floating_point<T>()) { return "fmin(" + a + ", " + b + ")"; } return "min(" + a + ", " + b + ")"; } inline static std::string init() { if (std::is_floating_point<T>()) { return "INFINITY"; } return "INT_MAX"; } }; /** * Represents rowwise min reduction in kernel generator expressions. * @tparam T type of expression */ template <typename T> class rowwise_min_ : public rowwise_reduction< rowwise_min_<T>, T, min_op<typename std::remove_reference_t<T>::Scalar>, false> { public: using op = min_op<typename std::remove_reference_t<T>::Scalar>; explicit rowwise_min_(T&& a) : rowwise_reduction<rowwise_min_<T>, T, op, false>(std::forward<T>(a), op::init()) {} }; /** * Min reduction of a kernel generator expression. * @tparam T type of input expression * @param a expression to reduce * @return min */ template <typename T, typename = require_all_valid_expressions_and_none_scalar_t<T>> inline rowwise_min_<as_operation_cl_t<T>> rowwise_min(T&& a) { return rowwise_min_<as_operation_cl_t<T>>( as_operation_cl(std::forward<T>(a))); } } // namespace math } // namespace stan #endif #endif <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_MAT_PROB_NEG_BINOMIAL_2_LOG_GLM_LPMF_HPP #define STAN_MATH_PRIM_MAT_PROB_NEG_BINOMIAL_2_LOG_GLM_LPMF_HPP #include <stan/math/prim/scal/meta/is_constant_struct.hpp> #include <stan/math/prim/scal/meta/partials_return_type.hpp> #include <stan/math/prim/scal/meta/operands_and_partials.hpp> #include <stan/math/prim/scal/err/check_consistent_sizes.hpp> #include <stan/math/prim/scal/err/check_positive_finite.hpp> #include <stan/math/prim/scal/err/check_nonnegative.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/scal/fun/constants.hpp> #include <stan/math/prim/scal/fun/multiply_log.hpp> #include <stan/math/prim/scal/fun/digamma.hpp> #include <stan/math/prim/mat/fun/lgamma.hpp> #include <stan/math/prim/scal/fun/log_sum_exp.hpp> #include <stan/math/prim/mat/fun/value_of.hpp> #include <stan/math/prim/arr/fun/value_of.hpp> #include <stan/math/prim/scal/meta/include_summand.hpp> #include <stan/math/prim/mat/meta/is_vector.hpp> #include <stan/math/prim/scal/meta/scalar_seq_view.hpp> #include <stan/math/prim/scal/fun/as_array_or_scalar.hpp> #include <stan/math/prim/scal/fun/as_scalar.hpp> #include <stan/math/prim/mat/fun/as_scalar.hpp> #include <stan/math/prim/arr/fun/as_scalar.hpp> #include <stan/math/prim/mat/fun/as_column_vector_or_scalar.hpp> #include <stan/math/prim/scal/fun/as_column_vector_or_scalar.hpp> #include <stan/math/prim/scal/fun/sum.hpp> #include <vector> #include <cmath> namespace stan { namespace math { /** * Returns the log PMF of the Generalized Linear Model (GLM) * with Negative-Binomial-2 distribution and log link function. * The idea is that neg_binomial_2_log_glm_lpmf(y, x, alpha, beta, phi) should * compute a more efficient version of * neg_binomial_2_log_lpmf(y, alpha + x * beta, phi) by using analytically * simplified gradients. * If containers are supplied, returns the log sum of the probabilities. * @tparam T_y type of positive int vector of variates (labels); * this can also be a single positive integer value; * @tparam T_x type of the matrix of covariates (features); this * should be an Eigen::Matrix type whose number of rows should match the * length of y and whose number of columns should match the length of beta * @tparam T_alpha type of the intercept(s); * this can be a vector (of the same length as y) of intercepts or a single * value (for models with constant intercept); * @tparam T_beta type of the weight vector; * this can also be a scalar; * @tparam T_precision type of the (positive) precision(s); * this can be a vector (of the same length as y, for heteroskedasticity) * or a scalar. * @param y failures count vector parameter * @param x design matrix * @param alpha intercept (in log odds) * @param beta weight vector * @param phi (vector of) precision parameter(s) * @return log probability or log sum of probabilities * @throw std::invalid_argument if container sizes mismatch. * @throw std::domain_error if x, beta or alpha is infinite. * @throw std::domain_error if phi is infinite or non-positive. * @throw std::domain_error if y is negative. */ template <bool propto, typename T_y, typename T_x, typename T_alpha, typename T_beta, typename T_precision> typename return_type<T_x, T_alpha, T_beta, T_precision>::type neg_binomial_2_log_glm_lpmf(const T_y& y, const T_x& x, const T_alpha& alpha, const T_beta& beta, const T_precision& phi) { static const char* function = "neg_binomial_2_log_glm_lpmf"; typedef typename stan::partials_return_type<T_y, T_x, T_alpha, T_beta, T_precision>::type T_partials_return; typedef typename std::conditional< is_vector<T_precision>::value, typename std::conditional< std::is_same<std::vector<typename scalar_type<T_precision>::type>, T_precision>::value, std::vector<typename stan::partials_return_type<T_precision>::type>, Eigen::Matrix<typename stan::partials_return_type<T_precision>::type, -1, 1>>::type, typename stan::partials_return_type<T_precision>::type>::type T_precision_mat; typedef typename std::conditional< is_vector<T_precision>::value, Eigen::Array<typename stan::partials_return_type<T_precision>::type, -1, 1>, typename stan::partials_return_type<T_precision>::type>::type T_precision_val; typedef typename std::conditional< is_vector<T_y>::value || is_vector<T_precision>::value, Eigen::Array<typename stan::partials_return_type<T_y, T_precision>::type, -1, 1>, typename stan::partials_return_type<T_y, T_precision>::type>::type T_sum_val; using Eigen::Array; using Eigen::Dynamic; using Eigen::Matrix; if (!(stan::length(y) && stan::length(x) && stan::length(beta) && stan::length(phi))) return 0.0; T_partials_return logp(0.0); const size_t N = x.rows(); const size_t M = x.cols(); check_nonnegative(function, "Failures variables", y); check_finite(function, "Weight vector", beta); check_finite(function, "Intercept", alpha); check_positive_finite(function, "Precision parameter", phi); check_consistent_size(function, "Vector of dependent variables", y, N); check_consistent_size(function, "Weight vector", beta, M); if (is_vector<T_precision>::value) check_consistent_sizes(function, "Vector of precision parameters", phi, "Vector of dependent variables", y); if (is_vector<T_alpha>::value) check_consistent_sizes(function, "Vector of intercepts", alpha, "Vector of dependent variables", y); if (!include_summand<propto, T_x, T_alpha, T_beta, T_precision>::value) return 0.0; const auto& x_val = value_of(x); const auto& y_val = value_of(y); const auto& beta_val = value_of(beta); const auto& alpha_val = value_of(alpha); const auto& phi_val = value_of(phi); const auto& y_val_vec = as_column_vector_or_scalar(y_val); const auto& beta_val_vec = as_column_vector_or_scalar(beta_val); const auto& alpha_val_vec = as_column_vector_or_scalar(alpha_val); const auto& phi_val_vec = as_column_vector_or_scalar(phi_val); const auto& y_arr = as_array_or_scalar(y_val_vec); const auto& phi_arr = as_array_or_scalar(phi_val_vec); Array<T_partials_return, Dynamic, 1> theta = value_of(x) * beta_val_vec; theta += as_array_or_scalar(alpha_val_vec); for (size_t n = 0; n < N; ++n) check_finite(function, "Matrix of independent variables", theta[n]); T_precision_val log_phi = log(phi_arr); Array<T_partials_return, Dynamic, 1> logsumexp_theta_logphi = (theta > log_phi) .select(theta + Eigen::log1p(Eigen::exp(log_phi - theta)), log_phi + Eigen::log1p(Eigen::exp(theta - log_phi))); T_sum_val y_plus_phi = y_arr + phi_arr; // Compute the log-density. if (include_summand<propto>::value) { logp -= sum(lgamma(y_arr + 1)); } if (include_summand<propto, T_precision>::value) { if(is_vector<T_precision>::value) { scalar_seq_view<decltype(phi_val)> phi_vec(phi_val); for (size_t n = 0; n < N; ++n) logp += multiply_log(phi_vec[n], phi_vec[n]) - lgamma(phi_vec[n]); } else{ logp += N * (multiply_log(as_scalar(phi_val), as_scalar(phi_val)) - lgamma(as_scalar(phi_val))); } } if (include_summand<propto, T_x, T_alpha, T_beta, T_precision>::value) logp -= (y_plus_phi * logsumexp_theta_logphi).sum(); if (include_summand<propto, T_x, T_alpha, T_beta>::value) logp += (y_arr * theta).sum(); if (include_summand<propto, T_precision>::value) { logp += sum(lgamma(y_plus_phi)); } // Compute the necessary derivatives. operands_and_partials<T_x, T_alpha, T_beta, T_precision> ops_partials( x, alpha, beta, phi); if (!(is_constant_struct<T_x>::value && is_constant_struct<T_beta>::value && is_constant_struct<T_alpha>::value && is_constant_struct<T_precision>::value)) { Array<T_partials_return, Dynamic, 1> theta_exp = theta.exp(); if (!(is_constant_struct<T_x>::value && is_constant_struct<T_beta>::value && is_constant_struct<T_alpha>::value)) { Matrix<T_partials_return, Dynamic, 1> theta_derivative = y_arr - theta_exp * y_plus_phi / (theta_exp + phi_arr); if (!is_constant_struct<T_beta>::value) { ops_partials.edge3_.partials_ = x_val.transpose() * theta_derivative; } if (!is_constant_struct<T_x>::value) { ops_partials.edge1_.partials_ = (beta_val_vec * theta_derivative.transpose()).transpose(); } if (!is_constant_struct<T_alpha>::value) { if (is_vector<T_alpha>::value) ops_partials.edge2_.partials_ = theta_derivative; else ops_partials.edge2_.partials_[0] = theta_derivative.sum(); } } if (!is_constant_struct<T_precision>::value) { if (is_vector<T_precision>::value) { ops_partials.edge4_.partials_ = 1 - y_plus_phi / (theta_exp + phi_arr) + log_phi - logsumexp_theta_logphi + as_array_or_scalar(digamma(y_plus_phi)) - as_array_or_scalar(digamma(phi_val_vec)); } else { ops_partials.edge4_.partials_[0] = (1 - y_plus_phi / (theta_exp + phi_arr) + log_phi - logsumexp_theta_logphi + as_array_or_scalar(digamma(y_plus_phi)) - as_array_or_scalar(digamma(phi_val_vec))) .sum(); } } } return ops_partials.build(logp); } template <typename T_y, typename T_x, typename T_alpha, typename T_beta, typename T_precision> inline typename return_type<T_x, T_alpha, T_beta, T_precision>::type neg_binomial_2_log_glm_lpmf(const T_y& y, const T_x& x, const T_alpha& alpha, const T_beta& beta, const T_precision& phi) { return neg_binomial_2_log_glm_lpmf<false>(y, x, alpha, beta, phi); } } // namespace math } // namespace stan #endif <commit_msg>[Jenkins] auto-formatting by clang-format version 5.0.0-3~16.04.1 (tags/RELEASE_500/final)<commit_after>#ifndef STAN_MATH_PRIM_MAT_PROB_NEG_BINOMIAL_2_LOG_GLM_LPMF_HPP #define STAN_MATH_PRIM_MAT_PROB_NEG_BINOMIAL_2_LOG_GLM_LPMF_HPP #include <stan/math/prim/scal/meta/is_constant_struct.hpp> #include <stan/math/prim/scal/meta/partials_return_type.hpp> #include <stan/math/prim/scal/meta/operands_and_partials.hpp> #include <stan/math/prim/scal/err/check_consistent_sizes.hpp> #include <stan/math/prim/scal/err/check_positive_finite.hpp> #include <stan/math/prim/scal/err/check_nonnegative.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/scal/fun/constants.hpp> #include <stan/math/prim/scal/fun/multiply_log.hpp> #include <stan/math/prim/scal/fun/digamma.hpp> #include <stan/math/prim/mat/fun/lgamma.hpp> #include <stan/math/prim/scal/fun/log_sum_exp.hpp> #include <stan/math/prim/mat/fun/value_of.hpp> #include <stan/math/prim/arr/fun/value_of.hpp> #include <stan/math/prim/scal/meta/include_summand.hpp> #include <stan/math/prim/mat/meta/is_vector.hpp> #include <stan/math/prim/scal/meta/scalar_seq_view.hpp> #include <stan/math/prim/scal/fun/as_array_or_scalar.hpp> #include <stan/math/prim/scal/fun/as_scalar.hpp> #include <stan/math/prim/mat/fun/as_scalar.hpp> #include <stan/math/prim/arr/fun/as_scalar.hpp> #include <stan/math/prim/mat/fun/as_column_vector_or_scalar.hpp> #include <stan/math/prim/scal/fun/as_column_vector_or_scalar.hpp> #include <stan/math/prim/scal/fun/sum.hpp> #include <vector> #include <cmath> namespace stan { namespace math { /** * Returns the log PMF of the Generalized Linear Model (GLM) * with Negative-Binomial-2 distribution and log link function. * The idea is that neg_binomial_2_log_glm_lpmf(y, x, alpha, beta, phi) should * compute a more efficient version of * neg_binomial_2_log_lpmf(y, alpha + x * beta, phi) by using analytically * simplified gradients. * If containers are supplied, returns the log sum of the probabilities. * @tparam T_y type of positive int vector of variates (labels); * this can also be a single positive integer value; * @tparam T_x type of the matrix of covariates (features); this * should be an Eigen::Matrix type whose number of rows should match the * length of y and whose number of columns should match the length of beta * @tparam T_alpha type of the intercept(s); * this can be a vector (of the same length as y) of intercepts or a single * value (for models with constant intercept); * @tparam T_beta type of the weight vector; * this can also be a scalar; * @tparam T_precision type of the (positive) precision(s); * this can be a vector (of the same length as y, for heteroskedasticity) * or a scalar. * @param y failures count vector parameter * @param x design matrix * @param alpha intercept (in log odds) * @param beta weight vector * @param phi (vector of) precision parameter(s) * @return log probability or log sum of probabilities * @throw std::invalid_argument if container sizes mismatch. * @throw std::domain_error if x, beta or alpha is infinite. * @throw std::domain_error if phi is infinite or non-positive. * @throw std::domain_error if y is negative. */ template <bool propto, typename T_y, typename T_x, typename T_alpha, typename T_beta, typename T_precision> typename return_type<T_x, T_alpha, T_beta, T_precision>::type neg_binomial_2_log_glm_lpmf(const T_y& y, const T_x& x, const T_alpha& alpha, const T_beta& beta, const T_precision& phi) { static const char* function = "neg_binomial_2_log_glm_lpmf"; typedef typename stan::partials_return_type<T_y, T_x, T_alpha, T_beta, T_precision>::type T_partials_return; typedef typename std::conditional< is_vector<T_precision>::value, typename std::conditional< std::is_same<std::vector<typename scalar_type<T_precision>::type>, T_precision>::value, std::vector<typename stan::partials_return_type<T_precision>::type>, Eigen::Matrix<typename stan::partials_return_type<T_precision>::type, -1, 1>>::type, typename stan::partials_return_type<T_precision>::type>::type T_precision_mat; typedef typename std::conditional< is_vector<T_precision>::value, Eigen::Array<typename stan::partials_return_type<T_precision>::type, -1, 1>, typename stan::partials_return_type<T_precision>::type>::type T_precision_val; typedef typename std::conditional< is_vector<T_y>::value || is_vector<T_precision>::value, Eigen::Array<typename stan::partials_return_type<T_y, T_precision>::type, -1, 1>, typename stan::partials_return_type<T_y, T_precision>::type>::type T_sum_val; using Eigen::Array; using Eigen::Dynamic; using Eigen::Matrix; if (!(stan::length(y) && stan::length(x) && stan::length(beta) && stan::length(phi))) return 0.0; T_partials_return logp(0.0); const size_t N = x.rows(); const size_t M = x.cols(); check_nonnegative(function, "Failures variables", y); check_finite(function, "Weight vector", beta); check_finite(function, "Intercept", alpha); check_positive_finite(function, "Precision parameter", phi); check_consistent_size(function, "Vector of dependent variables", y, N); check_consistent_size(function, "Weight vector", beta, M); if (is_vector<T_precision>::value) check_consistent_sizes(function, "Vector of precision parameters", phi, "Vector of dependent variables", y); if (is_vector<T_alpha>::value) check_consistent_sizes(function, "Vector of intercepts", alpha, "Vector of dependent variables", y); if (!include_summand<propto, T_x, T_alpha, T_beta, T_precision>::value) return 0.0; const auto& x_val = value_of(x); const auto& y_val = value_of(y); const auto& beta_val = value_of(beta); const auto& alpha_val = value_of(alpha); const auto& phi_val = value_of(phi); const auto& y_val_vec = as_column_vector_or_scalar(y_val); const auto& beta_val_vec = as_column_vector_or_scalar(beta_val); const auto& alpha_val_vec = as_column_vector_or_scalar(alpha_val); const auto& phi_val_vec = as_column_vector_or_scalar(phi_val); const auto& y_arr = as_array_or_scalar(y_val_vec); const auto& phi_arr = as_array_or_scalar(phi_val_vec); Array<T_partials_return, Dynamic, 1> theta = value_of(x) * beta_val_vec; theta += as_array_or_scalar(alpha_val_vec); for (size_t n = 0; n < N; ++n) check_finite(function, "Matrix of independent variables", theta[n]); T_precision_val log_phi = log(phi_arr); Array<T_partials_return, Dynamic, 1> logsumexp_theta_logphi = (theta > log_phi) .select(theta + Eigen::log1p(Eigen::exp(log_phi - theta)), log_phi + Eigen::log1p(Eigen::exp(theta - log_phi))); T_sum_val y_plus_phi = y_arr + phi_arr; // Compute the log-density. if (include_summand<propto>::value) { logp -= sum(lgamma(y_arr + 1)); } if (include_summand<propto, T_precision>::value) { if (is_vector<T_precision>::value) { scalar_seq_view<decltype(phi_val)> phi_vec(phi_val); for (size_t n = 0; n < N; ++n) logp += multiply_log(phi_vec[n], phi_vec[n]) - lgamma(phi_vec[n]); } else { logp += N * (multiply_log(as_scalar(phi_val), as_scalar(phi_val)) - lgamma(as_scalar(phi_val))); } } if (include_summand<propto, T_x, T_alpha, T_beta, T_precision>::value) logp -= (y_plus_phi * logsumexp_theta_logphi).sum(); if (include_summand<propto, T_x, T_alpha, T_beta>::value) logp += (y_arr * theta).sum(); if (include_summand<propto, T_precision>::value) { logp += sum(lgamma(y_plus_phi)); } // Compute the necessary derivatives. operands_and_partials<T_x, T_alpha, T_beta, T_precision> ops_partials( x, alpha, beta, phi); if (!(is_constant_struct<T_x>::value && is_constant_struct<T_beta>::value && is_constant_struct<T_alpha>::value && is_constant_struct<T_precision>::value)) { Array<T_partials_return, Dynamic, 1> theta_exp = theta.exp(); if (!(is_constant_struct<T_x>::value && is_constant_struct<T_beta>::value && is_constant_struct<T_alpha>::value)) { Matrix<T_partials_return, Dynamic, 1> theta_derivative = y_arr - theta_exp * y_plus_phi / (theta_exp + phi_arr); if (!is_constant_struct<T_beta>::value) { ops_partials.edge3_.partials_ = x_val.transpose() * theta_derivative; } if (!is_constant_struct<T_x>::value) { ops_partials.edge1_.partials_ = (beta_val_vec * theta_derivative.transpose()).transpose(); } if (!is_constant_struct<T_alpha>::value) { if (is_vector<T_alpha>::value) ops_partials.edge2_.partials_ = theta_derivative; else ops_partials.edge2_.partials_[0] = theta_derivative.sum(); } } if (!is_constant_struct<T_precision>::value) { if (is_vector<T_precision>::value) { ops_partials.edge4_.partials_ = 1 - y_plus_phi / (theta_exp + phi_arr) + log_phi - logsumexp_theta_logphi + as_array_or_scalar(digamma(y_plus_phi)) - as_array_or_scalar(digamma(phi_val_vec)); } else { ops_partials.edge4_.partials_[0] = (1 - y_plus_phi / (theta_exp + phi_arr) + log_phi - logsumexp_theta_logphi + as_array_or_scalar(digamma(y_plus_phi)) - as_array_or_scalar(digamma(phi_val_vec))) .sum(); } } } return ops_partials.build(logp); } template <typename T_y, typename T_x, typename T_alpha, typename T_beta, typename T_precision> inline typename return_type<T_x, T_alpha, T_beta, T_precision>::type neg_binomial_2_log_glm_lpmf(const T_y& y, const T_x& x, const T_alpha& alpha, const T_beta& beta, const T_precision& phi) { return neg_binomial_2_log_glm_lpmf<false>(y, x, alpha, beta, phi); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: LayerDialogContent.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2007-04-03 15:39: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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "LayerDialogContent.hxx" #ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONEFFECT_HPP_ #include <com/sun/star/presentation/AnimationEffect.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONSPEED_HPP_ #include <com/sun/star/presentation/AnimationSpeed.hpp> #endif #define ITEMID_COLOR SID_COLOR_TABLE #include <svx/gallery.hxx> #include <svx/colritem.hxx> #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #ifndef _AEITEM_HXX //autogen #include <svtools/aeitem.hxx> #endif #ifndef _SV_MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #include "sdattr.hxx" #include "LayerDialog.hrc" #include "app.hrc" #include "strings.hrc" #include "res_bmp.hrc" #include "sdresid.hxx" #ifndef SD_VIEW_HXX #include "View.hxx" #endif #include "drawdoc.hxx" #include "ViewShellBase.hxx" #include "DrawViewShell.hxx" #include "framework/FrameworkHelper.hxx" using namespace ::com::sun::star; namespace sd { LayerDialogContent::LayerDialogContent ( SfxBindings* pInBindings, SfxChildWindow *pCW, Window* pParent, const SdResId& rSdResId, ViewShellBase& rBase) : SfxDockingWindow (pInBindings, pCW, pParent, rSdResId), maLayerTabBar( dynamic_cast<DrawViewShell*>( framework::FrameworkHelper::Instance(rBase)->GetViewShell( framework::FrameworkHelper::msCenterPaneURL).get()), this, SdResId(TB_LAYERS)) { FreeResource(); maLayerTabBar.Show(); } LayerDialogContent::~LayerDialogContent (void) { } LayerTabBar& LayerDialogContent::GetLayerTabBar (void) { return maLayerTabBar; } BOOL LayerDialogContent::Close (void) { return SfxDockingWindow::Close(); } void LayerDialogContent::Resize (void) { maLayerTabBar.SetPosSizePixel ( Point(0,0), Size(GetSizePixel().Width(), 17)); SfxDockingWindow::Resize(); } } // end of namespace sd <commit_msg>INTEGRATION: CWS pchfix04 (1.4.64); FILE MERGED 2007/04/25 22:23:36 hjs 1.4.64.3: RESYNC: (1.4-1.5); FILE MERGED 2007/02/05 08:38:55 os 1.4.64.2: #i73604# usage of ITEMID_* removed 2007/01/19 10:49:55 hjs 1.4.64.1: #i73650# warning free with pch<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: LayerDialogContent.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2007-05-10 15:26:08 $ * * 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_sd.hxx" #include "LayerDialogContent.hxx" #ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONEFFECT_HPP_ #include <com/sun/star/presentation/AnimationEffect.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONSPEED_HPP_ #include <com/sun/star/presentation/AnimationSpeed.hpp> #endif #include <svx/gallery.hxx> #include <svx/colritem.hxx> #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #ifndef _AEITEM_HXX //autogen #include <svtools/aeitem.hxx> #endif #ifndef _SV_MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #include "sdattr.hxx" #include "LayerDialog.hrc" #include "app.hrc" #include "strings.hrc" #include "res_bmp.hrc" #include "sdresid.hxx" #ifndef SD_VIEW_HXX #include "View.hxx" #endif #include "drawdoc.hxx" #include "ViewShellBase.hxx" #include "DrawViewShell.hxx" #include "framework/FrameworkHelper.hxx" using namespace ::com::sun::star; namespace sd { LayerDialogContent::LayerDialogContent ( SfxBindings* pInBindings, SfxChildWindow *pCW, Window* pParent, const SdResId& rSdResId, ViewShellBase& rBase) : SfxDockingWindow (pInBindings, pCW, pParent, rSdResId), maLayerTabBar( dynamic_cast<DrawViewShell*>( framework::FrameworkHelper::Instance(rBase)->GetViewShell( framework::FrameworkHelper::msCenterPaneURL).get()), this, SdResId(TB_LAYERS)) { FreeResource(); maLayerTabBar.Show(); } LayerDialogContent::~LayerDialogContent (void) { } LayerTabBar& LayerDialogContent::GetLayerTabBar (void) { return maLayerTabBar; } BOOL LayerDialogContent::Close (void) { return SfxDockingWindow::Close(); } void LayerDialogContent::Resize (void) { maLayerTabBar.SetPosSizePixel ( Point(0,0), Size(GetSizePixel().Width(), 17)); SfxDockingWindow::Resize(); } } // end of namespace sd <|endoftext|>
<commit_before>#ifndef _PITO_INTERCEPTOR_LOG_HELPER_ #define _PITO_INTERCEPTOR_LOG_HELPER_ #include <pito/interceptor/SystemCall.hpp> #include <iostream> namespace pito { namespace interceptor { namespace log { template <class LibraryTag, class Ret, class... Args> struct SystemCall; template <class LibraryTag, class Ret, class... Args> struct SystemCall<LibraryTag, Ret (Args...)> : SystemCallHelper<LibraryTag, Ret(Args...)> { typedef SystemCallHelper<LibraryTag, Ret(Args...)> base_t; SystemCall(std::string const& name) : base_t(name) {} Ret operator()(Args... args) { std::cout << "calling " << base_t::name() << std::endl; return base_t::operator()(args...); } }; } } } #endif <commit_msg>log arguments in addition to call<commit_after>#ifndef _PITO_INTERCEPTOR_LOG_HELPER_ #define _PITO_INTERCEPTOR_LOG_HELPER_ #include <pito/interceptor/SystemCall.hpp> #include <iostream> namespace pito { namespace interceptor { namespace log { template <class... Args> struct PrintArgs; template <class... Args> struct PrintTailArgs; template <> struct PrintArgs<> { static void exec() { } }; template <> struct PrintTailArgs<> { static void exec() { } }; template <class Arg, class... Args> struct PrintTailArgs<Arg, Args...> { static void exec(Arg const& arg, Args... args) { std::cout << ", " << arg; PrintTailArgs<Args...>::exec(args...); } }; template <class Arg, class... Args> struct PrintArgs<Arg, Args...> { static void exec(Arg const& arg, Args... args) { std::cout << arg; PrintTailArgs<Args...>::exec(args...); } }; template <class LibraryTag, class Ret, class... Args> struct SystemCall; template <class LibraryTag, class Ret, class... Args> struct SystemCall<LibraryTag, Ret (Args...)> : SystemCallHelper<LibraryTag, Ret(Args...)> { typedef SystemCallHelper<LibraryTag, Ret(Args...)> base_t; SystemCall(std::string const& name) : base_t(name) {} Ret operator()(Args... args) { std::cout << "calling " << base_t::name() << "("; PrintArgs<Args...>::exec(args...); std::cout << ")" << std::endl; return base_t::operator()(args...); } }; } } } #endif <|endoftext|>
<commit_before>/** * @file * * @brief * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #include "ccode.hpp" #include <kdbmodule.h> #include <kdbprivate.h> #include <tests.hpp> using std::string; using CppKeySet = kdb::KeySet; using CppKey = kdb::Key; using ckdb::elektraModulesClose; using ckdb::elektraModulesInit; using ckdb::elektraPluginClose; using ckdb::elektraPluginOpen; using ckdb::keyNew; using ckdb::ksDel; using ckdb::Plugin; void testRoundTrip (string const decodedString, string const encodedString = "") #ifdef __llvm__ __attribute__ ((annotate ("oclint:suppress[empty if statement]"), annotate ("oclint:suppress[high cyclomatic complexity]"), annotate ("oclint:suppress[high ncss method]"), annotate ("oclint:suppress[too few branches in switch statement]"))) #endif { CppKeySet modules{ 0, KS_END }; elektraModulesInit (modules.getKeySet (), NULL); CppKeySet config{ 20, keyNew ("user/chars", KEY_END), keyNew ("user/chars/0A", KEY_VALUE, "6E", KEY_END), // new line -> n keyNew ("user/chars/20", KEY_VALUE, "77", KEY_END), // space -> w keyNew ("user/chars/23", KEY_VALUE, "72", KEY_END), // # -> r keyNew ("user/chars/5C", KEY_VALUE, "62", KEY_END), // \\ (backslash) -> b keyNew ("user/chars/3D", KEY_VALUE, "65", KEY_END), // = -> e keyNew ("user/chars/3B", KEY_VALUE, "73", KEY_END), // ; -> s KS_END }; CppKey parent{ "system/elektra/modules/type", KEY_END }; Plugin * plugin = elektraPluginOpen ("ccode", modules.getKeySet (), config.getKeySet (), *parent); exit_if_fail (plugin != NULL, "Could not open ccode plugin"); CppKeySet keys{ 20, keyNew ("user/tests/ccode/key", KEY_VALUE, decodedString.c_str (), KEY_END), KS_END }; succeed_if_same (plugin->kdbSet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS, "Call of `kdbset` was not successful"); if (!encodedString.empty ()) { CppKey encoded = keys.lookup ("user/tests/ccode/key"); succeed_if_same (encoded.getString (), encodedString, "String not correctly encoded"); } succeed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS, "Call of `kdbGet` was not successful"); CppKey decoded = keys.lookup ("user/tests/ccode/key"); succeed_if_same (decoded.getString (), decodedString, "String not correctly decoded"); elektraPluginClose (plugin, 0); ksDel (modules.release ()); config.release (); elektraModulesClose (modules.getKeySet (), 0); } TEST (type, roundtrip) { testRoundTrip ("a value\nwith=;# and \\ itself", "a\\wvalue\\nwith\\e\\s\\r\\wand\\w\\b\\witself"); testRoundTrip ("hello world"); testRoundTrip ("hello world!\nnew line"); testRoundTrip ("\0"); testRoundTrip ("\n"); testRoundTrip ("\\"); testRoundTrip (" "); testRoundTrip ("="); testRoundTrip (";"); testRoundTrip ("#"); testRoundTrip (" =;#"); testRoundTrip ("\n\\"); testRoundTrip (""); } <commit_msg>CCode: Test plugin using `%` as escape character<commit_after>/** * @file * * @brief * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #include "ccode.hpp" #include <kdbmodule.h> #include <kdbprivate.h> #include <tests.hpp> using std::string; using CppKeySet = kdb::KeySet; using CppKey = kdb::Key; using ckdb::elektraModulesClose; using ckdb::elektraModulesInit; using ckdb::elektraPluginClose; using ckdb::elektraPluginOpen; using ckdb::keyNew; using ckdb::ksDel; using ckdb::Plugin; CppKeySet defaultConfig () { CppKeySet config{ 20, keyNew ("user/chars", KEY_END), keyNew ("user/chars/0A", KEY_VALUE, "6E", KEY_END), // new line -> n keyNew ("user/chars/20", KEY_VALUE, "77", KEY_END), // space -> w keyNew ("user/chars/23", KEY_VALUE, "72", KEY_END), // # -> r keyNew ("user/chars/5C", KEY_VALUE, "62", KEY_END), // \\ (backslash) -> b keyNew ("user/chars/3D", KEY_VALUE, "65", KEY_END), // = -> e keyNew ("user/chars/3B", KEY_VALUE, "73", KEY_END), // ; -> s KS_END }; return config; } CppKeySet percentConfig () { CppKeySet config{ 20, keyNew ("user/chars", KEY_END), keyNew ("user/chars/0A", KEY_VALUE, "6E", KEY_END), // new line -> n keyNew ("user/chars/20", KEY_VALUE, "77", KEY_END), // space -> w keyNew ("user/chars/23", KEY_VALUE, "72", KEY_END), // # -> r keyNew ("user/chars/5C", KEY_VALUE, "62", KEY_END), // \\ (backslash) -> b keyNew ("user/chars/3D", KEY_VALUE, "65", KEY_END), // = -> e keyNew ("user/chars/3B", KEY_VALUE, "73", KEY_END), // ; -> s keyNew ("user/escape", KEY_VALUE, "25", KEY_END), // use % as escape character KS_END }; return config; } void testRoundTrip (string const decodedString, string const encodedString = "", CppKeySet config = defaultConfig ()) #ifdef __llvm__ __attribute__ ((annotate ("oclint:suppress[empty if statement]"), annotate ("oclint:suppress[high cyclomatic complexity]"), annotate ("oclint:suppress[high ncss method]"), annotate ("oclint:suppress[too few branches in switch statement]"))) #endif { CppKeySet modules{ 0, KS_END }; elektraModulesInit (modules.getKeySet (), NULL); CppKey parent{ "system/elektra/modules/type", KEY_END }; Plugin * plugin = elektraPluginOpen ("ccode", modules.getKeySet (), config.getKeySet (), *parent); exit_if_fail (plugin != NULL, "Could not open ccode plugin"); CppKeySet keys{ 20, keyNew ("user/tests/ccode/key", KEY_VALUE, decodedString.c_str (), KEY_END), KS_END }; succeed_if_same (plugin->kdbSet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS, "Call of `kdbset` was not successful"); if (!encodedString.empty ()) { CppKey encoded = keys.lookup ("user/tests/ccode/key"); succeed_if_same (encoded.getString (), encodedString, "String not correctly encoded"); } succeed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS, "Call of `kdbGet` was not successful"); CppKey decoded = keys.lookup ("user/tests/ccode/key"); succeed_if_same (decoded.getString (), decodedString, "String not correctly decoded"); elektraPluginClose (plugin, 0); ksDel (modules.release ()); config.release (); elektraModulesClose (modules.getKeySet (), 0); } TEST (type, roundtrip) { testRoundTrip ("a value\nwith=;# and \\ itself", "a\\wvalue\\nwith\\e\\s\\r\\wand\\w\\b\\witself"); testRoundTrip ("hello world"); testRoundTrip ("hello world!\nnew line"); testRoundTrip ("\0"); testRoundTrip ("\n"); testRoundTrip ("\\"); testRoundTrip (" "); testRoundTrip ("="); testRoundTrip (";"); testRoundTrip ("#"); testRoundTrip (" =;#"); testRoundTrip ("\n\\"); testRoundTrip (""); testRoundTrip ("a value\nwith=;# and \\ itself", "a%wvalue%nwith%e%s%r%wand%w%b%witself", percentConfig ()); } <|endoftext|>
<commit_before>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2010-2011 Emmanuel Benazera <[email protected]> * * 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 "cf_configuration.h" #include "sweeper.h" #include "miscutil.h" #include "urlmatch.h" #include "errlog.h" #include <iostream> using sp::sweeper; using sp::miscutil; using sp::urlmatch; using sp::errlog; namespace seeks_plugins { #define hash_domain_name_weight 1333166351ul /* "domain-name-weight" */ #define hash_record_cache_timeout 1954675964ul /* "record-cache-timeout" */ #define hash_cf_peer 1520012134ul /* "cf-peer" */ #define hash_dead_peer_check 1043267473ul /* "dead-peer-check" */ #define hash_dead_peer_retries 681362871ul /* "dead-peer-retries" */ #define hash_post_url_check 3323226172ul /* "post-url-check" */ #define hash_post_radius 2436628877ul /* "post-radius" */ #define hash_post_ua 1442804836ul /* "post-ua" */ #define hash_stop_words_filtering 4002206625ul /* "stop-words-filtering" */ #define hash_remote_post 4059800377ul /* "remote-post" */ #define hash_use_http_url 1825269331ul /* "use-http-urls-only" */ #define hash_cf_estimator 1689657696ul /* "cf-estimator" */ cf_configuration* cf_configuration::_config = NULL; cf_configuration::cf_configuration(const std::string &filename) :configuration_spec(filename) { // external static variables. _pl = new peer_list(); _dpl = new peer_list(); dead_peer::_pl = _pl; dead_peer::_dpl = _dpl; load_config(); } cf_configuration::~cf_configuration() { // XXX: should mutex to avoid crash (this is only called when node is dying, for now). dead_peer::_pl = NULL; dead_peer::_dpl = NULL; delete _pl; // dead peers need to be unregistered from sweeper first. hash_map<const char*,peer*,hash<const char*>,eqstr>::iterator hit = _dpl->_peers.begin(); while(hit!=_dpl->_peers.end()) { dead_peer *dp = dynamic_cast<dead_peer*>((*hit).second); if (dp) sweeper::unregister_sweepable(dp); ++hit; } delete _dpl; } void cf_configuration::set_default_config() { _domain_name_weight = 0.7; _record_cache_timeout = 600; // 10 mins. _dead_peer_check = 300; // 5 mins. _dead_peer_retries = 3; _post_url_check = true; _post_radius = 5; _post_url_ua = "Mozilla/5.0 (X11; Linux x86_64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"; // default. _stop_words_filtering = false; _remote_post = true; _use_http_urls = true; _estimator = "sre"; } void cf_configuration::handle_config_cmd(char *cmd, const uint32_t &cmd_hash, char *arg, char *buf, const unsigned long &linenum) { char tmp[BUFFER_SIZE]; int vec_count; char *vec[4]; int port; std::vector<std::string> elts; std::string host, path, address, port_str; switch (cmd_hash) { case hash_domain_name_weight: _domain_name_weight = atof(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "Weight given to the domain names in the simple filter"); break; case hash_record_cache_timeout: _record_cache_timeout = atoi(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "Timeout on cached remote records, in seconds"); break; case hash_cf_peer: strlcpy(tmp,arg,sizeof(tmp)); vec_count = miscutil::ssplit(tmp," \t",vec,SZ(vec),1,1); div_t divresult; divresult = div(vec_count,2); if (divresult.rem != 0) { errlog::log_error(LOG_LEVEL_ERROR,"Wrong number of parameter when specifying static collaborative filtering peer"); break; } address = vec[0]; urlmatch::parse_url_host_and_path(address,host,path); miscutil::tokenize(host,elts,":"); port = -1; if (elts.size()>1) { host = elts.at(0); port = atoi(elts.at(1).c_str()); } port_str = (port != -1) ? ":" + miscutil::to_string(port) : ""; errlog::log_error(LOG_LEVEL_DEBUG,"adding peer %s%s%s with resource %s", host.c_str(),port_str.c_str(),path.c_str(),vec[1]); _pl->add(host,port,path,std::string(vec[1])); configuration_spec::html_table_row(_config_args,cmd,arg, "Remote peer address for collaborative filtering"); break; case hash_dead_peer_check: _dead_peer_check = atoi(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "Interval of time between two dead peer checks"); break; case hash_dead_peer_retries: _dead_peer_retries = atoi(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "Number of retries before marking a peer as dead"); break; case hash_post_url_check: _post_url_check = static_cast<bool>(atoi(arg)); configuration_spec::html_table_row(_config_args,cmd,arg, "Whether to ping and check on posted URLs"); break; case hash_post_radius: _post_radius = static_cast<bool>(atoi(arg)); configuration_spec::html_table_row(_config_args,cmd,arg, "Query similarity impact radius of posted URLs"); break; case hash_post_ua: _post_url_ua = std::string(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "default 'user-agent' header used to retrieve posted URLs"); break; case hash_stop_words_filtering: _stop_words_filtering = static_cast<bool>(atoi(arg)); configuration_spec::html_table_row(_config_args,cmd,arg, "Whether to filter similar queries with stop words"); break; case hash_remote_post: _remote_post = static_cast<bool>(atoi(arg)); configuration_spec::html_table_row(_config_args,cmd,arg, "Whether to allow remote posting of results"); break; case hash_use_http_url: _use_http_urls = static_cast<bool>(atoi(arg)); configuration_spec::html_table_row(_config_args,cmd,arg, "Whether to allow only HTTP URLs or to allow generic item UIDs"); break; case hash_cf_estimator: _estimator = arg; configuration_spec::html_table_row(_config_args,cmd,arg, "Estimator used by the collaborative filter"); break; default: break; } } void cf_configuration::finalize_configuration() { } } /* end of namespace. */ <commit_msg>Imported Upstream version 0.4.2~git201204121430<commit_after>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2010-2011 Emmanuel Benazera <[email protected]> * * 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 "cf_configuration.h" #include "sweeper.h" #include "miscutil.h" #include "urlmatch.h" #include "errlog.h" #include <iostream> using sp::sweeper; using sp::miscutil; using sp::urlmatch; using sp::errlog; namespace seeks_plugins { #define hash_domain_name_weight 1333166351ul /* "domain-name-weight" */ #define hash_record_cache_timeout 1954675964ul /* "record-cache-timeout" */ #define hash_cf_peer 1520012134ul /* "cf-peer" */ #define hash_dead_peer_check 1043267473ul /* "dead-peer-check" */ #define hash_dead_peer_retries 681362871ul /* "dead-peer-retries" */ #define hash_post_url_check 3323226172ul /* "post-url-check" */ #define hash_post_radius 2436628877ul /* "post-radius" */ #define hash_post_ua 1442804836ul /* "post-ua" */ #define hash_stop_words_filtering 4002206625ul /* "stop-words-filtering" */ #define hash_remote_post 4059800377ul /* "remote-post" */ #define hash_use_http_url 1825269331ul /* "use-http-urls-only" */ #define hash_cf_estimator 1689657696ul /* "cf-estimator" */ cf_configuration* cf_configuration::_config = NULL; cf_configuration::cf_configuration(const std::string &filename) :configuration_spec(filename) { // external static variables. _pl = new peer_list(); _dpl = new peer_list(); dead_peer::_pl = _pl; dead_peer::_dpl = _dpl; load_config(); } cf_configuration::~cf_configuration() { // XXX: should mutex to avoid crash (this is only called when node is dying, for now). dead_peer::_pl = NULL; dead_peer::_dpl = NULL; delete _pl; // dead peers need to be unregistered from sweeper first. hash_map<const char*,peer*,hash<const char*>,eqstr>::iterator hit = _dpl->_peers.begin(); while(hit!=_dpl->_peers.end()) { dead_peer *dp = dynamic_cast<dead_peer*>((*hit).second); if (dp) sweeper::unregister_sweepable(dp); ++hit; } delete _dpl; } void cf_configuration::set_default_config() { _domain_name_weight = 0.7; _record_cache_timeout = 600; // 10 mins. _dead_peer_check = 300; // 5 mins. _dead_peer_retries = 3; _post_url_check = true; _post_radius = 5; _post_url_ua = "Mozilla/5.0 (X11; Linux x86_64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"; // default. _stop_words_filtering = false; _remote_post = true; _use_http_urls = true; _estimator = "sre"; } void cf_configuration::handle_config_cmd(char *cmd, const uint32_t &cmd_hash, char *arg, char *buf, const unsigned long &linenum) { char tmp[BUFFER_SIZE]; int vec_count; char *vec[4]; int port; std::vector<std::string> elts; std::string host, path, address, port_str; switch (cmd_hash) { case hash_domain_name_weight: _domain_name_weight = atof(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "Weight given to the domain names in the simple filter"); break; case hash_record_cache_timeout: _record_cache_timeout = atoi(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "Timeout on cached remote records, in seconds"); break; case hash_cf_peer: strlcpy(tmp,arg,sizeof(tmp)); vec_count = miscutil::ssplit(tmp," \t",vec,SZ(vec),1,1); div_t divresult; divresult = div(vec_count,2); if (divresult.rem != 0) { errlog::log_error(LOG_LEVEL_ERROR,"Wrong number of parameter when specifying static collaborative filtering peer"); break; } address = vec[0]; urlmatch::parse_url_host_and_path(address,host,path); miscutil::tokenize(host,elts,":"); port = -1; if (elts.size()>1) { host = elts.at(0); port = atoi(elts.at(1).c_str()); } port_str = (port != -1) ? ":" + miscutil::to_string(port) : ""; errlog::log_error(LOG_LEVEL_DEBUG,"adding peer %s%s%s with resource %s", host.c_str(),port_str.c_str(),path.c_str(),vec[1]); _pl->add(host,port,path,std::string(vec[1])); configuration_spec::html_table_row(_config_args,cmd,arg, "Remote peer address for collaborative filtering"); break; case hash_dead_peer_check: _dead_peer_check = atoi(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "Interval of time between two dead peer checks"); break; case hash_dead_peer_retries: _dead_peer_retries = atoi(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "Number of retries before marking a peer as dead"); break; case hash_post_url_check: _post_url_check = static_cast<bool>(atoi(arg)); configuration_spec::html_table_row(_config_args,cmd,arg, "Whether to ping and check on posted URLs"); break; case hash_post_radius: _post_radius = atoi(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "Query similarity impact radius of posted URLs"); break; case hash_post_ua: _post_url_ua = std::string(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "default 'user-agent' header used to retrieve posted URLs"); break; case hash_stop_words_filtering: _stop_words_filtering = static_cast<bool>(atoi(arg)); configuration_spec::html_table_row(_config_args,cmd,arg, "Whether to filter similar queries with stop words"); break; case hash_remote_post: _remote_post = static_cast<bool>(atoi(arg)); configuration_spec::html_table_row(_config_args,cmd,arg, "Whether to allow remote posting of results"); break; case hash_use_http_url: _use_http_urls = static_cast<bool>(atoi(arg)); configuration_spec::html_table_row(_config_args,cmd,arg, "Whether to allow only HTTP URLs or to allow generic item UIDs"); break; case hash_cf_estimator: _estimator = arg; configuration_spec::html_table_row(_config_args,cmd,arg, "Estimator used by the collaborative filter"); break; default: break; } } void cf_configuration::finalize_configuration() { } } /* end of namespace. */ <|endoftext|>
<commit_before>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2009 Emmanuel Benazera, [email protected] * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **/ #include "websearch.h" #include "cgi.h" #include "cgisimple.h" #include "encode.h" #include "miscutil.h" #include "errlog.h" #include "query_interceptor.h" #include "proxy_configuration.h" #include "se_handler.h" #include "static_renderer.h" #include "sort_rank.h" #include <iostream> #include <algorithm> #include <bitset> #include <assert.h> using namespace sp; namespace seeks_plugins { websearch_configuration* websearch::_wconfig = NULL; hash_map<uint32_t,query_context*,hash<uint32_t> > websearch::_active_qcontexts = hash_map<uint32_t,query_context*,hash<uint32_t> >(); websearch::websearch() : plugin() { _name = "websearch"; _version_major = "0"; _version_minor = "1"; _config_filename = plugin_manager::_plugin_repository + "websearch/websearch-config"; if (websearch::_wconfig == NULL) websearch::_wconfig = new websearch_configuration(_config_filename); _configuration = websearch::_wconfig; // cgi dispatchers. cgi_dispatcher *cgid_wb_hp = new cgi_dispatcher("websearch-hp", &websearch::cgi_websearch_hp, NULL, TRUE); _cgi_dispatchers.push_back(cgid_wb_hp); cgi_dispatcher *cgid_wb_seeks_hp_search_css = new cgi_dispatcher("seeks_hp_search.css", &websearch::cgi_websearch_search_hp_css, NULL, TRUE); _cgi_dispatchers.push_back(cgid_wb_seeks_hp_search_css); cgi_dispatcher *cgid_wb_search = new cgi_dispatcher("search", &websearch::cgi_websearch_search, NULL, TRUE); _cgi_dispatchers.push_back(cgid_wb_search); // external cgi. static_renderer::register_cgi(this); // interceptor plugins. _interceptor_plugin = new query_interceptor(this); } websearch::~websearch() { } // CGI calls. sp_err websearch::cgi_websearch_hp(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters) { assert(csp); assert(rsp); assert(parameters); if (parameters->empty()) { // redirection to local file is forbidden by most browsers. Let's read the file instead. std::string seeks_ws_hp_str = plugin_manager::_plugin_repository + "websearch/html/seeks_ws_hp.html"; sp_err err = cgisimple::load_file(seeks_ws_hp_str.c_str(), &rsp->_body, &rsp->_content_length); return err; } else { //TODO. return SP_ERR_OK; } } sp_err websearch::cgi_websearch_search_hp_css(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters) { assert(csp); assert(rsp); assert(parameters); std::string seeks_search_css_str = plugin_manager::_plugin_repository + "websearch/css/seeks_hp_search.css"; sp_err err = cgisimple::load_file(seeks_search_css_str.c_str(),&rsp->_body,&rsp->_content_length); csp->_content_type = CT_CSS; if (err != SP_ERR_OK) { errlog::log_error(LOG_LEVEL_ERROR, "Could not load seeks_hp_search.css"); } rsp->_is_static = 1; return SP_ERR_OK; } sp_err websearch::cgi_websearch_search(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters) { // debug //std::cout << "parameters size: " << parameters->size() << std::endl; // debug if (!parameters->empty()) { // debug /* std::cerr << "parameters:\n"; hash_map<const char*, const char*, hash<const char*>, eqstr>::const_iterator hit = parameters->begin(); while(hit!=parameters->end()) { std::cerr << (*hit).first << " --> " << (*hit).second << std::endl; ++hit; } */ // debug const char *query = miscutil::lookup(parameters,"q"); // grab the query. if (strlen(query) == 0) { errlog::log_error(LOG_LEVEL_ERROR,"No query found."); return cgi::cgi_error_bad_param(csp,rsp); } else se_handler::preprocess_parameters(parameters); // preprocess the query... // perform websearch. sp_err err = websearch::perform_websearch(csp,rsp,parameters); // TODO: catch errors. return err; } else { // TODO. return SP_ERR_OK; } } sp_err websearch::perform_websearch(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters) { // lookup a cached context for the incoming query. query_context *qc = websearch::lookup_qc(parameters); // check whether search is expanding or the user is leafing through pages. const char *action = miscutil::lookup(parameters,"action"); // expansion: we fetch more pages from every search engine. if (qc) // we already had a context for this query. { if (strcmp(action,"expand") == 0) qc->generate(csp,rsp,parameters); } else { // new context, whether we're expanding or not doesn't matter, we need // to generate snippets first. qc = new query_context(parameters); qc->generate(csp,rsp,parameters); } // grab (updated) set of cached search result snippets. std::vector<search_snippet*> snippets = qc->_cached_snippets; //debug //std::cerr << "[Debug]:websearch: (cached) snippets size: " << snippets.size() << std::endl; //debug // sort and rank search snippets ! // TODO: strategies and configuration. std::vector<search_snippet*> unique_ranked_snippets; sort_rank::sort_merge_and_rank_snippets(snippets,unique_ranked_snippets); // render the page. // TODO: dynamic renderer. sp_err err = static_renderer::render_result_page_static(unique_ranked_snippets,csp,rsp,parameters); // clear snippets. unique_ranked_snippets.clear(); // TODO: catch errors. return err; } query_context* websearch::lookup_qc(const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters) { std::string query; uint32_t query_hash = query_context::hash_query_for_context(parameters,query); hash_map<uint32_t,query_context*,hash<uint32_t> >::iterator hit; if ((hit = websearch::_active_qcontexts.find(query_hash))!=websearch::_active_qcontexts.end()) { /** * Already have a context for this query, update its flags, and return it. */ (*hit).second->update_last_time(); return (*hit).second; } else return NULL; } /* error handling. */ sp_err websearch::failed_ses_connect(client_state *csp, http_response *rsp) { errlog::log_error(LOG_LEVEL_CONNECT, "connect to the search engines failed: %E"); rsp->_reason = RSP_REASON_CONNECT_FAILED; hash_map<const char*,const char*,hash<const char*>,eqstr> *exports = cgi::default_exports(csp,NULL); char *path = strdup(""); sp_err err = miscutil::string_append(&path, csp->_http._path); if (!err) err = miscutil::add_map_entry(exports, "host", 1, encode::html_encode(csp->_http._host), 0); if (!err) err = miscutil::add_map_entry(exports, "hostport", 1, encode::html_encode(csp->_http._hostport), 0); if (!err) err = miscutil::add_map_entry(exports, "path", 1, encode::html_encode_and_free_original(path), 0); if (!err) err = miscutil::add_map_entry(exports, "protocol", 1, csp->_http._ssl ? "https://" : "http://", 1); if (!err) { err = miscutil::add_map_entry(exports, "host-ip", 1, encode::html_encode(csp->_http._host_ip_addr_str), 0); if (err) { /* Some failures, like "404 no such domain", don't have an IP address. */ err = miscutil::add_map_entry(exports, "host-ip", 1, encode::html_encode(csp->_http._host), 0); } } // not catching error on template filling... err = cgi::template_fill_for_cgi(csp,"connect-failed",csp->_config->_templdir, exports,rsp); return err; } /* auto-registration */ extern "C" { plugin* maker() { return new websearch; } } class proxy_autor { public: proxy_autor() { plugin_manager::_factory["websearch-hp"] = maker; // beware: default plugin shell with no name. } }; proxy_autor _p; // one instance, instanciated when dl-opening. } /* end of namespace. */ <commit_msg>fix redirection on empty query<commit_after>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2009 Emmanuel Benazera, [email protected] * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **/ #include "websearch.h" #include "cgi.h" #include "cgisimple.h" #include "encode.h" #include "miscutil.h" #include "errlog.h" #include "query_interceptor.h" #include "proxy_configuration.h" #include "se_handler.h" #include "static_renderer.h" #include "sort_rank.h" #include <iostream> #include <algorithm> #include <bitset> #include <assert.h> using namespace sp; namespace seeks_plugins { websearch_configuration* websearch::_wconfig = NULL; hash_map<uint32_t,query_context*,hash<uint32_t> > websearch::_active_qcontexts = hash_map<uint32_t,query_context*,hash<uint32_t> >(); websearch::websearch() : plugin() { _name = "websearch"; _version_major = "0"; _version_minor = "1"; _config_filename = plugin_manager::_plugin_repository + "websearch/websearch-config"; if (websearch::_wconfig == NULL) websearch::_wconfig = new websearch_configuration(_config_filename); _configuration = websearch::_wconfig; // cgi dispatchers. cgi_dispatcher *cgid_wb_hp = new cgi_dispatcher("websearch-hp", &websearch::cgi_websearch_hp, NULL, TRUE); _cgi_dispatchers.push_back(cgid_wb_hp); cgi_dispatcher *cgid_wb_seeks_hp_search_css = new cgi_dispatcher("seeks_hp_search.css", &websearch::cgi_websearch_search_hp_css, NULL, TRUE); _cgi_dispatchers.push_back(cgid_wb_seeks_hp_search_css); cgi_dispatcher *cgid_wb_search = new cgi_dispatcher("search", &websearch::cgi_websearch_search, NULL, TRUE); _cgi_dispatchers.push_back(cgid_wb_search); // external cgi. static_renderer::register_cgi(this); // interceptor plugins. _interceptor_plugin = new query_interceptor(this); } websearch::~websearch() { } // CGI calls. sp_err websearch::cgi_websearch_hp(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters) { assert(csp); assert(rsp); assert(parameters); // redirection to local file is forbidden by most browsers. Let's read the file instead. std::string seeks_ws_hp_str = plugin_manager::_plugin_repository + "websearch/html/seeks_ws_hp.html"; sp_err err = cgisimple::load_file(seeks_ws_hp_str.c_str(), &rsp->_body, &rsp->_content_length); return err; } sp_err websearch::cgi_websearch_search_hp_css(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters) { assert(csp); assert(rsp); assert(parameters); std::string seeks_search_css_str = plugin_manager::_plugin_repository + "websearch/css/seeks_hp_search.css"; sp_err err = cgisimple::load_file(seeks_search_css_str.c_str(),&rsp->_body,&rsp->_content_length); csp->_content_type = CT_CSS; if (err != SP_ERR_OK) { errlog::log_error(LOG_LEVEL_ERROR, "Could not load seeks_hp_search.css"); } rsp->_is_static = 1; return SP_ERR_OK; } sp_err websearch::cgi_websearch_search(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters) { if (!parameters->empty()) { const char *query = miscutil::lookup(parameters,"q"); // grab the query. if (strlen(query) == 0) { // return websearch homepage instead. return websearch::cgi_websearch_hp(csp,rsp,parameters); } else se_handler::preprocess_parameters(parameters); // preprocess the query... // perform websearch. sp_err err = websearch::perform_websearch(csp,rsp,parameters); return err; } else { // TODO. return SP_ERR_OK; } } sp_err websearch::perform_websearch(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters) { // lookup a cached context for the incoming query. query_context *qc = websearch::lookup_qc(parameters); // check whether search is expanding or the user is leafing through pages. const char *action = miscutil::lookup(parameters,"action"); // expansion: we fetch more pages from every search engine. if (qc) // we already had a context for this query. { if (strcmp(action,"expand") == 0) qc->generate(csp,rsp,parameters); } else { // new context, whether we're expanding or not doesn't matter, we need // to generate snippets first. qc = new query_context(parameters); qc->generate(csp,rsp,parameters); } // grab (updated) set of cached search result snippets. std::vector<search_snippet*> snippets = qc->_cached_snippets; //debug //std::cerr << "[Debug]:websearch: (cached) snippets size: " << snippets.size() << std::endl; //debug // sort and rank search snippets ! // TODO: strategies and configuration. std::vector<search_snippet*> unique_ranked_snippets; sort_rank::sort_merge_and_rank_snippets(snippets,unique_ranked_snippets); // render the page. // TODO: dynamic renderer. sp_err err = static_renderer::render_result_page_static(unique_ranked_snippets,csp,rsp,parameters); // clear snippets. unique_ranked_snippets.clear(); // TODO: catch errors. return err; } query_context* websearch::lookup_qc(const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters) { std::string query; uint32_t query_hash = query_context::hash_query_for_context(parameters,query); hash_map<uint32_t,query_context*,hash<uint32_t> >::iterator hit; if ((hit = websearch::_active_qcontexts.find(query_hash))!=websearch::_active_qcontexts.end()) { /** * Already have a context for this query, update its flags, and return it. */ (*hit).second->update_last_time(); return (*hit).second; } else return NULL; } /* error handling. */ sp_err websearch::failed_ses_connect(client_state *csp, http_response *rsp) { errlog::log_error(LOG_LEVEL_CONNECT, "connect to the search engines failed: %E"); rsp->_reason = RSP_REASON_CONNECT_FAILED; hash_map<const char*,const char*,hash<const char*>,eqstr> *exports = cgi::default_exports(csp,NULL); char *path = strdup(""); sp_err err = miscutil::string_append(&path, csp->_http._path); if (!err) err = miscutil::add_map_entry(exports, "host", 1, encode::html_encode(csp->_http._host), 0); if (!err) err = miscutil::add_map_entry(exports, "hostport", 1, encode::html_encode(csp->_http._hostport), 0); if (!err) err = miscutil::add_map_entry(exports, "path", 1, encode::html_encode_and_free_original(path), 0); if (!err) err = miscutil::add_map_entry(exports, "protocol", 1, csp->_http._ssl ? "https://" : "http://", 1); if (!err) { err = miscutil::add_map_entry(exports, "host-ip", 1, encode::html_encode(csp->_http._host_ip_addr_str), 0); if (err) { /* Some failures, like "404 no such domain", don't have an IP address. */ err = miscutil::add_map_entry(exports, "host-ip", 1, encode::html_encode(csp->_http._host), 0); } } // not catching error on template filling... err = cgi::template_fill_for_cgi(csp,"connect-failed",csp->_config->_templdir, exports,rsp); return err; } /* auto-registration */ extern "C" { plugin* maker() { return new websearch; } } class proxy_autor { public: proxy_autor() { plugin_manager::_factory["websearch-hp"] = maker; // beware: default plugin shell with no name. } }; proxy_autor _p; // one instance, instanciated when dl-opening. } /* end of namespace. */ <|endoftext|>
<commit_before>/* This file is part of Ingen. e< "\n\tcycle_start: " << _cycle_time.start_ticks() * Copyright (C) 2007 Dave Robillard <http://drobilla.net> * * Ingen is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * Ingen is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "PatchWindow.h" #include <iostream> #include <cassert> #include <fstream> #include "App.h" #include "ModelEngineInterface.h" #include "PatchCanvas.h" #include "LoadPluginWindow.h" #include "PatchModel.h" #include "NewSubpatchWindow.h" #include "LoadPatchWindow.h" #include "LoadSubpatchWindow.h" #include "NodeControlWindow.h" #include "PatchPropertiesWindow.h" #include "ConfigWindow.h" #include "MessagesWindow.h" #include "PatchTreeWindow.h" #include "BreadCrumbBox.h" #include "Store.h" #include "ConnectWindow.h" #include "ThreadedLoader.h" #include "WindowFactory.h" #include "PatchView.h" namespace Ingenuity { PatchWindow::PatchWindow(BaseObjectType* cobject, const Glib::RefPtr<Gnome::Glade::Xml>& xml) : Gtk::Window(cobject), _enable_signal(true), _position_stored(false), _x(0), _y(0), _breadcrumb_box(NULL) { property_visible() = false; xml->get_widget("patch_win_vbox", _vbox); xml->get_widget("patch_win_viewport", _viewport); //xml->get_widget("patch_win_status_bar", _status_bar); //xml->get_widget("patch_open_menuitem", _menu_open); xml->get_widget("patch_import_menuitem", _menu_import); //xml->get_widget("patch_open_into_menuitem", _menu_open_into); xml->get_widget("patch_save_menuitem", _menu_save); xml->get_widget("patch_save_as_menuitem", _menu_save_as); xml->get_widget("patch_cut_menuitem", _menu_cut); xml->get_widget("patch_copy_menuitem", _menu_copy); xml->get_widget("patch_paste_menuitem", _menu_paste); xml->get_widget("patch_delete_menuitem", _menu_delete); xml->get_widget("patch_close_menuitem", _menu_close); xml->get_widget("patch_configuration_menuitem", _menu_configuration); xml->get_widget("patch_quit_menuitem", _menu_quit); xml->get_widget("patch_view_control_window_menuitem", _menu_view_control_window); xml->get_widget("patch_view_engine_window_menuitem", _menu_view_engine_window); xml->get_widget("patch_properties_menuitem", _menu_view_patch_properties); xml->get_widget("patch_fullscreen_menuitem", _menu_fullscreen); xml->get_widget("patch_clear_menuitem", _menu_clear); xml->get_widget("patch_destroy_menuitem", _menu_destroy_patch); xml->get_widget("patch_view_messages_window_menuitem", _menu_view_messages_window); xml->get_widget("patch_view_patch_tree_window_menuitem", _menu_view_patch_tree_window); xml->get_widget("patch_help_about_menuitem", _menu_help_about); _menu_view_control_window->property_sensitive() = false; //m_status_bar->push(App::instance().engine()->engine_url()); //m_status_bar->pack_start(*Gtk::manage(new Gtk::Image(Gtk::Stock::CONNECT, Gtk::ICON_SIZE_MENU)), false, false); /*_menu_open->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_open));*/ _menu_import->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_import)); _menu_save->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_save)); _menu_save_as->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_save_as)); _menu_copy->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_copy)); _menu_delete->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_delete)); _menu_quit->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_quit)); _menu_configuration->signal_activate().connect( sigc::mem_fun(App::instance().configuration_dialog(), &ConfigWindow::show)); _menu_fullscreen->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_fullscreen_toggled)); _menu_view_engine_window->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_show_engine)); _menu_view_control_window->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_show_controls)); _menu_view_patch_properties->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_show_properties)); _menu_destroy_patch->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_destroy)); _menu_clear->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_clear)); _menu_view_messages_window->signal_activate().connect( sigc::mem_fun<void>(App::instance().messages_dialog(), &MessagesWindow::present)); _menu_view_patch_tree_window->signal_activate().connect( sigc::mem_fun<void>(App::instance().patch_tree(), &PatchTreeWindow::present)); _menu_help_about->signal_activate().connect( sigc::mem_fun<void>(App::instance().about_dialog(), &Gtk::Dialog::present)); _breadcrumb_box = new BreadCrumbBox(); _breadcrumb_box->signal_patch_selected.connect(sigc::mem_fun(this, &PatchWindow::set_patch_from_path)); } PatchWindow::~PatchWindow() { // Prevents deletion //m_patch->claim_patch_view(); delete _breadcrumb_box; } /** Set the patch controller from a Path (for use by eg. BreadCrumbBox) */ void PatchWindow::set_patch_from_path(const Path& path, SharedPtr<PatchView> view) { if (view) { assert(view->patch()->path() == path); App::instance().window_factory()->present_patch(view->patch(), this, view); } else { SharedPtr<PatchModel> model = PtrCast<PatchModel>(App::instance().store()->object(path)); if (model) App::instance().window_factory()->present_patch(model, this); } } /** Sets the patch controller for this window and initializes everything. * * If @a view is NULL, a new view will be created. */ void PatchWindow::set_patch(SharedPtr<PatchModel> patch, SharedPtr<PatchView> view) { if (!patch || patch == _patch) return; _enable_signal = false; _patch = patch; _view = view; if (!_view) _view = _breadcrumb_box->view(patch->path()); if (!_view) _view = PatchView::create(patch); assert(_view); // Add view to our viewport if (_view->get_parent()) _view->get_parent()->remove(*_view.get()); _viewport->remove(); _viewport->add(*_view.get()); if (_breadcrumb_box->get_parent()) _breadcrumb_box->get_parent()->remove(*_breadcrumb_box); _view->breadcrumb_container()->remove(); _view->breadcrumb_container()->add(*_breadcrumb_box); _view->breadcrumb_container()->show(); _breadcrumb_box->build(patch->path(), _view); _breadcrumb_box->show(); //m_menu_view_control_window->property_sensitive() = patch->has_control_inputs(); int width, height; get_size(width, height); _view->canvas()->scroll_to( ((int)_view->canvas()->width() - width)/2, ((int)_view->canvas()->height() - height)/2); set_title(_patch->path() + " - Ingenuity"); //m_properties_window->patch_model(pc->patch_model()); if (patch->path() == "/") _menu_destroy_patch->set_sensitive(false); else _menu_destroy_patch->set_sensitive(true); show_all(); _enable_signal = true; } void PatchWindow::event_show_engine() { if (_patch) App::instance().connect_window()->show(); } void PatchWindow::event_show_controls() { App::instance().window_factory()->present_controls(_patch); } void PatchWindow::event_show_properties() { App::instance().window_factory()->present_properties(_patch); } void PatchWindow::event_import() { App::instance().window_factory()->present_load_patch(_patch); } void PatchWindow::event_save() { if (_patch->filename() == "") event_save_as(); else App::instance().loader()->save_patch(_patch, _patch->filename(), false); } void PatchWindow::event_save_as() { Gtk::FileChooserDialog dialog(*this, "Save Patch", Gtk::FILE_CHOOSER_ACTION_SAVE); Gtk::VBox* box = dialog.get_vbox(); Gtk::Label warning("Warning: Recursively saving will overwrite any subpatch files \ without confirmation."); box->pack_start(warning, false, false, 2); Gtk::CheckButton recursive_checkbutton("Recursively save all subpatches"); box->pack_start(recursive_checkbutton, false, false, 0); recursive_checkbutton.show(); dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL); dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK); // Set current folder to most sensible default const string& current_filename = _patch->filename(); if (current_filename.length() > 0) dialog.set_filename(current_filename); else if (App::instance().configuration()->patch_folder().length() > 0) dialog.set_current_folder(App::instance().configuration()->patch_folder()); int result = dialog.run(); bool recursive = recursive_checkbutton.get_active(); assert(result == Gtk::RESPONSE_OK || result == Gtk::RESPONSE_CANCEL || result == Gtk::RESPONSE_NONE); if (result == Gtk::RESPONSE_OK) { string filename = dialog.get_filename(); if (filename.length() < 11 || filename.substr(filename.length()-10) != ".ingen.ttl") filename += ".ingen.ttl"; bool confirm = false; std::fstream fin; fin.open(filename.c_str(), std::ios::in); if (fin.is_open()) { // File exists string msg = "File already exists! Are you sure you want to overwrite "; msg += filename + "?"; Gtk::MessageDialog confirm_dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_YES_NO, true); if (confirm_dialog.run() == Gtk::RESPONSE_YES) confirm = true; else confirm = false; } else { // File doesn't exist confirm = true; } fin.close(); if (confirm) { App::instance().loader()->save_patch(_patch, filename, recursive); //m_patch->set_metadata("filename", Atom(filename.c_str())); } } App::instance().configuration()->set_patch_folder(dialog.get_current_folder()); } void PatchWindow::event_copy() { if (_view) _view->canvas()->copy_selection(); } void PatchWindow::event_delete() { if (_view) _view->canvas()->destroy_selection(); } void PatchWindow::on_show() { if (_position_stored) move(_x, _y); Gtk::Window::on_show(); } void PatchWindow::on_hide() { _position_stored = true; get_position(_x, _y); Gtk::Window::on_hide(); } bool PatchWindow::on_key_press_event(GdkEventKey* event) { if (event->keyval == GDK_Delete) { cerr << "FIXME: delete key\n"; /* if (_patch && _patch->get_view()) { assert(_patch->get_view()->canvas()); _patch->get_view()->canvas()->destroy_selected(); }*/ return true; } else { return Gtk::Window::on_key_press_event(event); } } void PatchWindow::event_quit() { Gtk::MessageDialog d(*this, "Would you like to quit just Ingenuity\nor kill the engine as well?", true, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_NONE, true); d.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL); Gtk::Button* b = d.add_button(Gtk::Stock::REMOVE, 2); // kill b->set_label("_Kill Engine"); Gtk::Widget* kill_img = Gtk::manage(new Gtk::Image(Gtk::Stock::CLOSE, Gtk::ICON_SIZE_BUTTON)); b->set_image(*kill_img); b = d.add_button(Gtk::Stock::QUIT, 1); // just exit b->set_label("_Quit"); Gtk::Widget* close_img = Gtk::manage(new Gtk::Image(Gtk::Stock::QUIT, Gtk::ICON_SIZE_BUTTON)); b->set_image(*close_img); int ret = d.run(); if (ret == 1) { App::instance().quit(); } else if (ret == 2) { App::instance().engine()->quit(); App::instance().quit(); } // Otherwise cancelled, do nothing } void PatchWindow::event_destroy() { App::instance().engine()->destroy(_patch->path()); } void PatchWindow::event_clear() { App::instance().engine()->clear_patch(_patch->path()); } void PatchWindow::event_fullscreen_toggled() { // FIXME: ugh, use GTK signals to track state and know for sure static bool is_fullscreen = false; if (!is_fullscreen) { fullscreen(); is_fullscreen = true; } else { unfullscreen(); is_fullscreen = false; } } } // namespace Ingenuity <commit_msg>Fixed construction algorithm bugs.<commit_after>/* This file is part of Ingen. * Copyright (C) 2007 Dave Robillard <http://drobilla.net> * * Ingen is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * Ingen is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "PatchWindow.h" #include <iostream> #include <cassert> #include <fstream> #include "App.h" #include "ModelEngineInterface.h" #include "PatchCanvas.h" #include "LoadPluginWindow.h" #include "PatchModel.h" #include "NewSubpatchWindow.h" #include "LoadPatchWindow.h" #include "LoadSubpatchWindow.h" #include "NodeControlWindow.h" #include "PatchPropertiesWindow.h" #include "ConfigWindow.h" #include "MessagesWindow.h" #include "PatchTreeWindow.h" #include "BreadCrumbBox.h" #include "Store.h" #include "ConnectWindow.h" #include "ThreadedLoader.h" #include "WindowFactory.h" #include "PatchView.h" namespace Ingenuity { PatchWindow::PatchWindow(BaseObjectType* cobject, const Glib::RefPtr<Gnome::Glade::Xml>& xml) : Gtk::Window(cobject), _enable_signal(true), _position_stored(false), _x(0), _y(0), _breadcrumb_box(NULL) { property_visible() = false; xml->get_widget("patch_win_vbox", _vbox); xml->get_widget("patch_win_viewport", _viewport); //xml->get_widget("patch_win_status_bar", _status_bar); //xml->get_widget("patch_open_menuitem", _menu_open); xml->get_widget("patch_import_menuitem", _menu_import); //xml->get_widget("patch_open_into_menuitem", _menu_open_into); xml->get_widget("patch_save_menuitem", _menu_save); xml->get_widget("patch_save_as_menuitem", _menu_save_as); xml->get_widget("patch_cut_menuitem", _menu_cut); xml->get_widget("patch_copy_menuitem", _menu_copy); xml->get_widget("patch_paste_menuitem", _menu_paste); xml->get_widget("patch_delete_menuitem", _menu_delete); xml->get_widget("patch_close_menuitem", _menu_close); xml->get_widget("patch_configuration_menuitem", _menu_configuration); xml->get_widget("patch_quit_menuitem", _menu_quit); xml->get_widget("patch_view_control_window_menuitem", _menu_view_control_window); xml->get_widget("patch_view_engine_window_menuitem", _menu_view_engine_window); xml->get_widget("patch_properties_menuitem", _menu_view_patch_properties); xml->get_widget("patch_fullscreen_menuitem", _menu_fullscreen); xml->get_widget("patch_clear_menuitem", _menu_clear); xml->get_widget("patch_destroy_menuitem", _menu_destroy_patch); xml->get_widget("patch_view_messages_window_menuitem", _menu_view_messages_window); xml->get_widget("patch_view_patch_tree_window_menuitem", _menu_view_patch_tree_window); xml->get_widget("patch_help_about_menuitem", _menu_help_about); _menu_view_control_window->property_sensitive() = false; //m_status_bar->push(App::instance().engine()->engine_url()); //m_status_bar->pack_start(*Gtk::manage(new Gtk::Image(Gtk::Stock::CONNECT, Gtk::ICON_SIZE_MENU)), false, false); /*_menu_open->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_open));*/ _menu_import->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_import)); _menu_save->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_save)); _menu_save_as->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_save_as)); _menu_copy->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_copy)); _menu_delete->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_delete)); _menu_quit->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_quit)); _menu_configuration->signal_activate().connect( sigc::mem_fun(App::instance().configuration_dialog(), &ConfigWindow::show)); _menu_fullscreen->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_fullscreen_toggled)); _menu_view_engine_window->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_show_engine)); _menu_view_control_window->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_show_controls)); _menu_view_patch_properties->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_show_properties)); _menu_destroy_patch->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_destroy)); _menu_clear->signal_activate().connect( sigc::mem_fun(this, &PatchWindow::event_clear)); _menu_view_messages_window->signal_activate().connect( sigc::mem_fun<void>(App::instance().messages_dialog(), &MessagesWindow::present)); _menu_view_patch_tree_window->signal_activate().connect( sigc::mem_fun<void>(App::instance().patch_tree(), &PatchTreeWindow::present)); _menu_help_about->signal_activate().connect( sigc::mem_fun<void>(App::instance().about_dialog(), &Gtk::Dialog::present)); _breadcrumb_box = new BreadCrumbBox(); _breadcrumb_box->signal_patch_selected.connect(sigc::mem_fun(this, &PatchWindow::set_patch_from_path)); } PatchWindow::~PatchWindow() { // Prevents deletion //m_patch->claim_patch_view(); delete _breadcrumb_box; } /** Set the patch controller from a Path (for use by eg. BreadCrumbBox) */ void PatchWindow::set_patch_from_path(const Path& path, SharedPtr<PatchView> view) { if (view) { assert(view->patch()->path() == path); App::instance().window_factory()->present_patch(view->patch(), this, view); } else { SharedPtr<PatchModel> model = PtrCast<PatchModel>(App::instance().store()->object(path)); if (model) App::instance().window_factory()->present_patch(model, this); } } /** Sets the patch controller for this window and initializes everything. * * If @a view is NULL, a new view will be created. */ void PatchWindow::set_patch(SharedPtr<PatchModel> patch, SharedPtr<PatchView> view) { if (!patch || patch == _patch) return; _enable_signal = false; _patch = patch; _view = view; if (!_view) _view = _breadcrumb_box->view(patch->path()); if (!_view) _view = PatchView::create(patch); assert(_view); // Add view to our viewport if (_view->get_parent()) _view->get_parent()->remove(*_view.get()); _viewport->remove(); _viewport->add(*_view.get()); if (_breadcrumb_box->get_parent()) _breadcrumb_box->get_parent()->remove(*_breadcrumb_box); _view->breadcrumb_container()->remove(); _view->breadcrumb_container()->add(*_breadcrumb_box); _view->breadcrumb_container()->show(); _breadcrumb_box->build(patch->path(), _view); _breadcrumb_box->show(); //m_menu_view_control_window->property_sensitive() = patch->has_control_inputs(); int width, height; get_size(width, height); _view->canvas()->scroll_to( ((int)_view->canvas()->width() - width)/2, ((int)_view->canvas()->height() - height)/2); set_title(_patch->path() + " - Ingenuity"); //m_properties_window->patch_model(pc->patch_model()); if (patch->path() == "/") _menu_destroy_patch->set_sensitive(false); else _menu_destroy_patch->set_sensitive(true); show_all(); _enable_signal = true; } void PatchWindow::event_show_engine() { if (_patch) App::instance().connect_window()->show(); } void PatchWindow::event_show_controls() { App::instance().window_factory()->present_controls(_patch); } void PatchWindow::event_show_properties() { App::instance().window_factory()->present_properties(_patch); } void PatchWindow::event_import() { App::instance().window_factory()->present_load_patch(_patch); } void PatchWindow::event_save() { if (_patch->filename() == "") event_save_as(); else App::instance().loader()->save_patch(_patch, _patch->filename(), false); } void PatchWindow::event_save_as() { Gtk::FileChooserDialog dialog(*this, "Save Patch", Gtk::FILE_CHOOSER_ACTION_SAVE); Gtk::VBox* box = dialog.get_vbox(); Gtk::Label warning("Warning: Recursively saving will overwrite any subpatch files \ without confirmation."); box->pack_start(warning, false, false, 2); Gtk::CheckButton recursive_checkbutton("Recursively save all subpatches"); box->pack_start(recursive_checkbutton, false, false, 0); recursive_checkbutton.show(); dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL); dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK); // Set current folder to most sensible default const string& current_filename = _patch->filename(); if (current_filename.length() > 0) dialog.set_filename(current_filename); else if (App::instance().configuration()->patch_folder().length() > 0) dialog.set_current_folder(App::instance().configuration()->patch_folder()); int result = dialog.run(); bool recursive = recursive_checkbutton.get_active(); assert(result == Gtk::RESPONSE_OK || result == Gtk::RESPONSE_CANCEL || result == Gtk::RESPONSE_NONE); if (result == Gtk::RESPONSE_OK) { string filename = dialog.get_filename(); if (filename.length() < 11 || filename.substr(filename.length()-10) != ".ingen.ttl") filename += ".ingen.ttl"; bool confirm = false; std::fstream fin; fin.open(filename.c_str(), std::ios::in); if (fin.is_open()) { // File exists string msg = "File already exists! Are you sure you want to overwrite "; msg += filename + "?"; Gtk::MessageDialog confirm_dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_YES_NO, true); if (confirm_dialog.run() == Gtk::RESPONSE_YES) confirm = true; else confirm = false; } else { // File doesn't exist confirm = true; } fin.close(); if (confirm) { App::instance().loader()->save_patch(_patch, filename, recursive); //m_patch->set_metadata("filename", Atom(filename.c_str())); } } App::instance().configuration()->set_patch_folder(dialog.get_current_folder()); } void PatchWindow::event_copy() { if (_view) _view->canvas()->copy_selection(); } void PatchWindow::event_delete() { if (_view) _view->canvas()->destroy_selection(); } void PatchWindow::on_show() { if (_position_stored) move(_x, _y); Gtk::Window::on_show(); } void PatchWindow::on_hide() { _position_stored = true; get_position(_x, _y); Gtk::Window::on_hide(); } bool PatchWindow::on_key_press_event(GdkEventKey* event) { if (event->keyval == GDK_Delete) { cerr << "FIXME: delete key\n"; /* if (_patch && _patch->get_view()) { assert(_patch->get_view()->canvas()); _patch->get_view()->canvas()->destroy_selected(); }*/ return true; } else { return Gtk::Window::on_key_press_event(event); } } void PatchWindow::event_quit() { Gtk::MessageDialog d(*this, "Would you like to quit just Ingenuity\nor kill the engine as well?", true, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_NONE, true); d.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL); Gtk::Button* b = d.add_button(Gtk::Stock::REMOVE, 2); // kill b->set_label("_Kill Engine"); Gtk::Widget* kill_img = Gtk::manage(new Gtk::Image(Gtk::Stock::CLOSE, Gtk::ICON_SIZE_BUTTON)); b->set_image(*kill_img); b = d.add_button(Gtk::Stock::QUIT, 1); // just exit b->set_label("_Quit"); Gtk::Widget* close_img = Gtk::manage(new Gtk::Image(Gtk::Stock::QUIT, Gtk::ICON_SIZE_BUTTON)); b->set_image(*close_img); int ret = d.run(); if (ret == 1) { App::instance().quit(); } else if (ret == 2) { App::instance().engine()->quit(); App::instance().quit(); } // Otherwise cancelled, do nothing } void PatchWindow::event_destroy() { App::instance().engine()->destroy(_patch->path()); } void PatchWindow::event_clear() { App::instance().engine()->clear_patch(_patch->path()); } void PatchWindow::event_fullscreen_toggled() { // FIXME: ugh, use GTK signals to track state and know for sure static bool is_fullscreen = false; if (!is_fullscreen) { fullscreen(); is_fullscreen = true; } else { unfullscreen(); is_fullscreen = false; } } } // namespace Ingenuity <|endoftext|>
<commit_before>#include "ofdpa_bridge.hpp" #include "roflibs/netlink/clogging.hpp" #include <cassert> #include <map> #include <rofl/common/openflow/cofport.h> namespace basebox { ofdpa_bridge::ofdpa_bridge(rofl::rofl_ofdpa_fm_driver &fm_driver) : fm_driver(fm_driver) {} ofdpa_bridge::~ofdpa_bridge() {} void ofdpa_bridge::set_bridge_interface(const rofcore::crtlink &rtl) { if (AF_BRIDGE != rtl.get_family() || 0 != rtl.get_master()) { rofcore::logging::error << __PRETTY_FUNCTION__ << " not a bridge master: " << rtl << std::endl; return; } this->bridge = rtl; } static int find_next_bit(int i, uint32_t x) { int j; if (i >= 32) return -1; /* find first bit */ if (i < 0) return __builtin_ffs(x); /* mask off prior finds to get next */ j = __builtin_ffs(x >> i); return j ? j + i : 0; } void ofdpa_bridge::add_interface(const rofcore::crtlink &rtl) { using rofcore::logging; // sanity checks if (0 == bridge.get_ifindex()) { logging::error << __PRETTY_FUNCTION__ << " cannot attach interface without bridge: " << rtl << std::endl; return; } if (AF_BRIDGE != rtl.get_family()) { logging::error << __PRETTY_FUNCTION__ << rtl << " is not a bridge interface " << std::endl; return; } if (bridge.get_ifindex() != rtl.get_master()) { logging::error << __PRETTY_FUNCTION__ << rtl << " is not a slave of this bridge interface " << std::endl; return; } const struct rtnl_link_bridge_vlan *br_vlan = rtl.get_br_vlan(); for (int k = 0; k < RTNL_LINK_BRIDGE_VLAN_BITMAP_LEN; k++) { int base_bit; uint32_t a = br_vlan->vlan_bitmap[k]; base_bit = k * 32; int i = -1; int done = 0; while (!done) { int j = find_next_bit(i, a); if (j > 0) { int vid = j - 1 + base_bit; bool egress_untagged = false; // check if egress is untagged if (br_vlan->untagged_bitmap[k] & 1 << (j - 1)) { egress_untagged = true; } uint32_t group = fm_driver.enable_port_vid_egress(rtl.get_devname(), vid, egress_untagged); assert(group && "invalid group identifier"); if (rofl::openflow::OFPG_MAX == group) { logging::error << __PRETTY_FUNCTION__ << " failed to set vid on egress " << std::endl; i = j; continue; } l2_domain[vid].push_back(group); if (br_vlan->pvid == vid) { fm_driver.enable_port_pvid_ingress(rtl.get_devname(), vid); } else { fm_driver.enable_port_vid_ingress(rtl.get_devname(), vid); } // todo check if vid is okay as an id as well group = fm_driver.enable_group_l2_multicast(vid, vid, l2_domain[vid], 1 != l2_domain[vid].size()); if (1 == l2_domain[vid].size()) { // todo maybe unnecessary fm_driver.enable_policy_arp(vid, group); } i = j; } else { done = 1; } } } } void ofdpa_bridge::update_vlans(const std::string &devname, const rtnl_link_bridge_vlan *old_br_vlan, const rtnl_link_bridge_vlan *new_br_vlan) { for (int k = 0; k < RTNL_LINK_BRIDGE_VLAN_BITMAP_LEN; k++) { int base_bit; uint32_t a = old_br_vlan->vlan_bitmap[k]; uint32_t b = new_br_vlan->vlan_bitmap[k]; uint32_t c = old_br_vlan->untagged_bitmap[k]; uint32_t d = new_br_vlan->untagged_bitmap[k]; uint32_t vlan_diff = a ^ b; uint32_t untagged_diff = c ^ d; base_bit = k * 32; int i = -1; int done = 0; while (!done) { int j = find_next_bit(i, vlan_diff); if (j > 0) { // vlan added or removed int vid = j - 1 + base_bit; bool egress_untagged = false; // check if egress is untagged if (new_br_vlan->untagged_bitmap[k] & 1 << (j - 1)) { egress_untagged = true; // clear untagged_diff bit untagged_diff &= ~((uint32_t)1 << (j - 1)); } if (new_br_vlan->vlan_bitmap[k] & 1 << (j - 1)) { // vlan added uint32_t group = fm_driver.enable_port_vid_egress(devname, vid, egress_untagged); assert(group && "invalid group identifier"); if (rofl::openflow::OFPG_MAX == group) { logging::error << __PRETTY_FUNCTION__ << " failed to set vid on egress " << std::endl; i = j; continue; } l2_domain[vid].push_back(group); if (new_br_vlan->pvid == vid) { // todo check for existing pvid? fm_driver.enable_port_pvid_ingress(devname, vid); } else { fm_driver.enable_port_vid_ingress(devname, vid); } // todo check if vid is okay as an id as well group = fm_driver.enable_group_l2_multicast( vid, vid, l2_domain[vid], 1 != l2_domain[vid].size()); // enable arp flooding as well #if DISABLED_TO_TEST if (1 == l2_domain[vid].size()) { // todo maybe unnecessary fm_driver.enable_policy_arp(vid, group); } #endif } else { // vlan removed } i = j; } else { done = 1; } } #if 0 // not yet implemented the update done = 0; i = -1; while (!done) { // vlan is existing, but swapping egress tagged/untagged int j = find_next_bit(i, untagged_diff); if (j > 0) { // egress untagged changed int vid = j - 1 + base_bit; bool egress_untagged = false; // check if egress is untagged if (new_br_vlan->untagged_bitmap[k] & 1 << (j-1)) { egress_untagged = true; } // XXX implement update fm_driver.update_port_vid_egress(devname, vid, egress_untagged); i = j; } else { done = 1; } } #endif } } void ofdpa_bridge::update_interface(const rofcore::crtlink &oldlink, const rofcore::crtlink &newlink) { using rofcore::crtlink; using rofcore::logging; // sanity checks if (0 == bridge.get_ifindex()) { logging::error << __PRETTY_FUNCTION__ << " cannot update interface without bridge" << std::endl; return; } if (AF_BRIDGE != newlink.get_family()) { logging::error << __PRETTY_FUNCTION__ << newlink << " is not a bridge interface" << std::endl; return; } // if (AF_BRIDGE != oldlink.get_family()) { // logging::error << __PRETTY_FUNCTION__ << oldlink << " is // not a bridge interface" << std::endl; // return; // } if (bridge.get_ifindex() != newlink.get_master()) { logging::error << __PRETTY_FUNCTION__ << newlink << " is not a slave of this bridge interface" << std::endl; return; } if (bridge.get_ifindex() != oldlink.get_master()) { logging::error << __PRETTY_FUNCTION__ << newlink << " is not a slave of this bridge interface" << std::endl; return; } if (newlink.get_devname().compare(oldlink.get_devname())) { logging::info << __PRETTY_FUNCTION__ << " interface rename currently ignored " << std::endl; // FIXME this has to be handled differently return; } if (not crtlink::are_br_vlan_equal(newlink.get_br_vlan(), oldlink.get_br_vlan())) { // vlan updated update_vlans(oldlink.get_devname(), oldlink.get_br_vlan(), newlink.get_br_vlan()); } } void ofdpa_bridge::delete_interface(const rofcore::crtlink &rtl) { // XXX update L2 Multicast Group // get group id // remove id from l2_domain // update enable_group_l2_multicast } void ofdpa_bridge::add_mac_to_fdb(const uint32_t of_port_no, const uint16_t vlan, const rofl::cmacaddr &mac, bool permanent) { fm_driver.add_bridging_unicast_vlan(mac, vlan, of_port_no, permanent); } void ofdpa_bridge::remove_mac_from_fdb(const uint32_t of_port_no, uint16_t vid, const rofl::cmacaddr &mac) { fm_driver.remove_bridging_unicast_vlan(mac, vid, of_port_no); } } /* namespace basebox */ <commit_msg>missing namespace use<commit_after>#include "ofdpa_bridge.hpp" #include "roflibs/netlink/clogging.hpp" #include <cassert> #include <map> #include <rofl/common/openflow/cofport.h> namespace basebox { ofdpa_bridge::ofdpa_bridge(rofl::rofl_ofdpa_fm_driver &fm_driver) : fm_driver(fm_driver) {} ofdpa_bridge::~ofdpa_bridge() {} void ofdpa_bridge::set_bridge_interface(const rofcore::crtlink &rtl) { if (AF_BRIDGE != rtl.get_family() || 0 != rtl.get_master()) { rofcore::logging::error << __PRETTY_FUNCTION__ << " not a bridge master: " << rtl << std::endl; return; } this->bridge = rtl; } static int find_next_bit(int i, uint32_t x) { int j; if (i >= 32) return -1; /* find first bit */ if (i < 0) return __builtin_ffs(x); /* mask off prior finds to get next */ j = __builtin_ffs(x >> i); return j ? j + i : 0; } void ofdpa_bridge::add_interface(const rofcore::crtlink &rtl) { using rofcore::logging; // sanity checks if (0 == bridge.get_ifindex()) { logging::error << __PRETTY_FUNCTION__ << " cannot attach interface without bridge: " << rtl << std::endl; return; } if (AF_BRIDGE != rtl.get_family()) { logging::error << __PRETTY_FUNCTION__ << rtl << " is not a bridge interface " << std::endl; return; } if (bridge.get_ifindex() != rtl.get_master()) { logging::error << __PRETTY_FUNCTION__ << rtl << " is not a slave of this bridge interface " << std::endl; return; } const struct rtnl_link_bridge_vlan *br_vlan = rtl.get_br_vlan(); for (int k = 0; k < RTNL_LINK_BRIDGE_VLAN_BITMAP_LEN; k++) { int base_bit; uint32_t a = br_vlan->vlan_bitmap[k]; base_bit = k * 32; int i = -1; int done = 0; while (!done) { int j = find_next_bit(i, a); if (j > 0) { int vid = j - 1 + base_bit; bool egress_untagged = false; // check if egress is untagged if (br_vlan->untagged_bitmap[k] & 1 << (j - 1)) { egress_untagged = true; } uint32_t group = fm_driver.enable_port_vid_egress(rtl.get_devname(), vid, egress_untagged); assert(group && "invalid group identifier"); if (rofl::openflow::OFPG_MAX == group) { logging::error << __PRETTY_FUNCTION__ << " failed to set vid on egress " << std::endl; i = j; continue; } l2_domain[vid].push_back(group); if (br_vlan->pvid == vid) { fm_driver.enable_port_pvid_ingress(rtl.get_devname(), vid); } else { fm_driver.enable_port_vid_ingress(rtl.get_devname(), vid); } // todo check if vid is okay as an id as well group = fm_driver.enable_group_l2_multicast(vid, vid, l2_domain[vid], 1 != l2_domain[vid].size()); if (1 == l2_domain[vid].size()) { // todo maybe unnecessary fm_driver.enable_policy_arp(vid, group); } i = j; } else { done = 1; } } } } void ofdpa_bridge::update_vlans(const std::string &devname, const rtnl_link_bridge_vlan *old_br_vlan, const rtnl_link_bridge_vlan *new_br_vlan) { using rofcore::logging; for (int k = 0; k < RTNL_LINK_BRIDGE_VLAN_BITMAP_LEN; k++) { int base_bit; uint32_t a = old_br_vlan->vlan_bitmap[k]; uint32_t b = new_br_vlan->vlan_bitmap[k]; uint32_t c = old_br_vlan->untagged_bitmap[k]; uint32_t d = new_br_vlan->untagged_bitmap[k]; uint32_t vlan_diff = a ^ b; uint32_t untagged_diff = c ^ d; base_bit = k * 32; int i = -1; int done = 0; while (!done) { int j = find_next_bit(i, vlan_diff); if (j > 0) { // vlan added or removed int vid = j - 1 + base_bit; bool egress_untagged = false; // check if egress is untagged if (new_br_vlan->untagged_bitmap[k] & 1 << (j - 1)) { egress_untagged = true; // clear untagged_diff bit untagged_diff &= ~((uint32_t)1 << (j - 1)); } if (new_br_vlan->vlan_bitmap[k] & 1 << (j - 1)) { // vlan added uint32_t group = fm_driver.enable_port_vid_egress(devname, vid, egress_untagged); assert(group && "invalid group identifier"); if (rofl::openflow::OFPG_MAX == group) { logging::error << __PRETTY_FUNCTION__ << " failed to set vid on egress " << std::endl; i = j; continue; } l2_domain[vid].push_back(group); if (new_br_vlan->pvid == vid) { // todo check for existing pvid? fm_driver.enable_port_pvid_ingress(devname, vid); } else { fm_driver.enable_port_vid_ingress(devname, vid); } // todo check if vid is okay as an id as well group = fm_driver.enable_group_l2_multicast( vid, vid, l2_domain[vid], 1 != l2_domain[vid].size()); // enable arp flooding as well #if DISABLED_TO_TEST if (1 == l2_domain[vid].size()) { // todo maybe unnecessary fm_driver.enable_policy_arp(vid, group); } #endif } else { // vlan removed } i = j; } else { done = 1; } } #if 0 // not yet implemented the update done = 0; i = -1; while (!done) { // vlan is existing, but swapping egress tagged/untagged int j = find_next_bit(i, untagged_diff); if (j > 0) { // egress untagged changed int vid = j - 1 + base_bit; bool egress_untagged = false; // check if egress is untagged if (new_br_vlan->untagged_bitmap[k] & 1 << (j-1)) { egress_untagged = true; } // XXX implement update fm_driver.update_port_vid_egress(devname, vid, egress_untagged); i = j; } else { done = 1; } } #endif } } void ofdpa_bridge::update_interface(const rofcore::crtlink &oldlink, const rofcore::crtlink &newlink) { using rofcore::crtlink; using rofcore::logging; // sanity checks if (0 == bridge.get_ifindex()) { logging::error << __PRETTY_FUNCTION__ << " cannot update interface without bridge" << std::endl; return; } if (AF_BRIDGE != newlink.get_family()) { logging::error << __PRETTY_FUNCTION__ << newlink << " is not a bridge interface" << std::endl; return; } // if (AF_BRIDGE != oldlink.get_family()) { // logging::error << __PRETTY_FUNCTION__ << oldlink << " is // not a bridge interface" << std::endl; // return; // } if (bridge.get_ifindex() != newlink.get_master()) { logging::error << __PRETTY_FUNCTION__ << newlink << " is not a slave of this bridge interface" << std::endl; return; } if (bridge.get_ifindex() != oldlink.get_master()) { logging::error << __PRETTY_FUNCTION__ << newlink << " is not a slave of this bridge interface" << std::endl; return; } if (newlink.get_devname().compare(oldlink.get_devname())) { logging::info << __PRETTY_FUNCTION__ << " interface rename currently ignored " << std::endl; // FIXME this has to be handled differently return; } if (not crtlink::are_br_vlan_equal(newlink.get_br_vlan(), oldlink.get_br_vlan())) { // vlan updated update_vlans(oldlink.get_devname(), oldlink.get_br_vlan(), newlink.get_br_vlan()); } } void ofdpa_bridge::delete_interface(const rofcore::crtlink &rtl) { // XXX update L2 Multicast Group // get group id // remove id from l2_domain // update enable_group_l2_multicast } void ofdpa_bridge::add_mac_to_fdb(const uint32_t of_port_no, const uint16_t vlan, const rofl::cmacaddr &mac, bool permanent) { fm_driver.add_bridging_unicast_vlan(mac, vlan, of_port_no, permanent); } void ofdpa_bridge::remove_mac_from_fdb(const uint32_t of_port_no, uint16_t vid, const rofl::cmacaddr &mac) { fm_driver.remove_bridging_unicast_vlan(mac, vid, of_port_no); } } /* namespace basebox */ <|endoftext|>
<commit_before>#pragma once // `krbn::grabbable_state_queue` can be used safely in a multi-threaded environment. #include "boost_defs.hpp" #include "event_queue.hpp" #include "types.hpp" #include <boost/circular_buffer.hpp> #include <memory> #include <nod/nod.hpp> #include <optional> #include <pqrs/dispatcher.hpp> namespace krbn { class grabbable_state_queue final : public pqrs::dispatcher::extra::dispatcher_client { public: // Signals (invoked from the shared dispatcher thread) nod::signal<void(std::optional<grabbable_state>)> grabbable_state_changed; // Methods const int max_entries = 32; grabbable_state_queue(const grabbable_state_queue&) = delete; grabbable_state_queue(void) : dispatcher_client(), grabbable_states_(max_entries) { } virtual ~grabbable_state_queue(void) { detach_from_dispatcher(); } std::optional<absolute_time_point> get_first_grabbed_event_time_stamp(void) const { std::lock_guard<std::mutex> lock(mutex_); return first_grabbed_event_time_stamp_; } std::optional<grabbable_state> find_current_grabbable_state(void) const { std::lock_guard<std::mutex> lock(mutex_); return find_current_grabbable_state_(); } void clear(void) { std::lock_guard<std::mutex> lock(mutex_); auto old_state = find_current_grabbable_state_(); grabbable_states_.clear(); first_grabbed_event_time_stamp_ = std::nullopt; auto new_state = find_current_grabbable_state_(); call_grabbable_state_changed_if_needed(old_state, new_state); } bool push_back_grabbable_state(const grabbable_state& state) { std::lock_guard<std::mutex> lock(mutex_); // Ignore if the first grabbed event is already arrived. if (first_grabbed_event_time_stamp_ && *first_grabbed_event_time_stamp_ <= state.get_time_stamp()) { return false; } // push_back auto old_state = find_current_grabbable_state_(); grabbable_states_.push_back(state); auto new_state = find_current_grabbable_state_(); call_grabbable_state_changed_if_needed(old_state, new_state); return true; } bool update_first_grabbed_event_time_stamp(absolute_time_point time_stamp) { std::lock_guard<std::mutex> lock(mutex_); if (first_grabbed_event_time_stamp_) { return false; } // Pointing device sometimes send event with time_stamp(0) just after the device is connected. // We have to ignore the event, so compare the time_stamp with the first queued event. if (grabbable_states_.empty()) { return false; } if (grabbable_states_.front().get_time_stamp() > time_stamp) { return false; } // Set first_grabbed_event_time_stamp_ first_grabbed_event_time_stamp_ = time_stamp; auto old_state = find_current_grabbable_state_(); // Erase states after first_grabbed_event_time_stamp_. grabbable_states_.erase(std::remove_if(std::begin(grabbable_states_), std::end(grabbable_states_), [&](const auto& s) { return s.get_time_stamp() >= time_stamp; }), std::end(grabbable_states_)); auto new_state = find_current_grabbable_state_(); call_grabbable_state_changed_if_needed(old_state, new_state); return true; } void unset_first_grabbed_event_time_stamp(void) { std::lock_guard<std::mutex> lock(mutex_); first_grabbed_event_time_stamp_ = std::nullopt; } private: std::optional<grabbable_state> find_current_grabbable_state_(void) const { if (grabbable_states_.empty()) { return std::nullopt; } return grabbable_states_.back(); } void call_grabbable_state_changed_if_needed(std::optional<grabbable_state> old_state, std::optional<grabbable_state> new_state) { if (!old_state && !new_state) { return; } if (old_state && new_state && old_state->equals_except_time_stamp(*new_state)) { return; } enqueue_to_dispatcher([this, new_state] { grabbable_state_changed(new_state); }); } // Keep multiple entries for when `push_back_entry` is called multiple times before `set_first_grabbed_event_time_stamp`. // (We should remove entries after first_grabbed_event_time_stamp_.) boost::circular_buffer<grabbable_state> grabbable_states_; std::optional<absolute_time_point> first_grabbed_event_time_stamp_; mutable std::mutex mutex_; }; } // namespace krbn <commit_msg>remove boost/circular_buffer.hpp<commit_after>#pragma once // `krbn::grabbable_state_queue` can be used safely in a multi-threaded environment. #include "event_queue.hpp" #include "types.hpp" #include <deque> #include <memory> #include <nod/nod.hpp> #include <optional> #include <pqrs/dispatcher.hpp> namespace krbn { class grabbable_state_queue final : public pqrs::dispatcher::extra::dispatcher_client { public: // Signals (invoked from the shared dispatcher thread) nod::signal<void(std::optional<grabbable_state>)> grabbable_state_changed; // Methods grabbable_state_queue(const grabbable_state_queue&) = delete; grabbable_state_queue(void) : dispatcher_client() { } virtual ~grabbable_state_queue(void) { detach_from_dispatcher(); } std::optional<absolute_time_point> get_first_grabbed_event_time_stamp(void) const { std::lock_guard<std::mutex> lock(mutex_); return first_grabbed_event_time_stamp_; } std::optional<grabbable_state> find_current_grabbable_state(void) const { std::lock_guard<std::mutex> lock(mutex_); return find_current_grabbable_state_(); } void clear(void) { std::lock_guard<std::mutex> lock(mutex_); auto old_state = find_current_grabbable_state_(); grabbable_states_.clear(); first_grabbed_event_time_stamp_ = std::nullopt; auto new_state = find_current_grabbable_state_(); call_grabbable_state_changed_if_needed(old_state, new_state); } bool push_back_grabbable_state(const grabbable_state& state) { std::lock_guard<std::mutex> lock(mutex_); // Ignore if the first grabbed event is already arrived. if (first_grabbed_event_time_stamp_ && *first_grabbed_event_time_stamp_ <= state.get_time_stamp()) { return false; } // push_back auto old_state = find_current_grabbable_state_(); grabbable_states_.push_back(state); const int max_entries = 32; while (grabbable_states_.size() > max_entries) { grabbable_states_.pop_front(); } auto new_state = find_current_grabbable_state_(); call_grabbable_state_changed_if_needed(old_state, new_state); return true; } bool update_first_grabbed_event_time_stamp(absolute_time_point time_stamp) { std::lock_guard<std::mutex> lock(mutex_); if (first_grabbed_event_time_stamp_) { return false; } // Pointing device sometimes send event with time_stamp(0) just after the device is connected. // We have to ignore the event, so compare the time_stamp with the first queued event. if (grabbable_states_.empty()) { return false; } if (grabbable_states_.front().get_time_stamp() > time_stamp) { return false; } // Set first_grabbed_event_time_stamp_ first_grabbed_event_time_stamp_ = time_stamp; auto old_state = find_current_grabbable_state_(); // Erase states after first_grabbed_event_time_stamp_. grabbable_states_.erase(std::remove_if(std::begin(grabbable_states_), std::end(grabbable_states_), [&](const auto& s) { return s.get_time_stamp() >= time_stamp; }), std::end(grabbable_states_)); auto new_state = find_current_grabbable_state_(); call_grabbable_state_changed_if_needed(old_state, new_state); return true; } void unset_first_grabbed_event_time_stamp(void) { std::lock_guard<std::mutex> lock(mutex_); first_grabbed_event_time_stamp_ = std::nullopt; } private: std::optional<grabbable_state> find_current_grabbable_state_(void) const { if (grabbable_states_.empty()) { return std::nullopt; } return grabbable_states_.back(); } void call_grabbable_state_changed_if_needed(std::optional<grabbable_state> old_state, std::optional<grabbable_state> new_state) { if (!old_state && !new_state) { return; } if (old_state && new_state && old_state->equals_except_time_stamp(*new_state)) { return; } enqueue_to_dispatcher([this, new_state] { grabbable_state_changed(new_state); }); } // Keep multiple entries for when `push_back_entry` is called multiple times before `set_first_grabbed_event_time_stamp`. // (We should remove entries after first_grabbed_event_time_stamp_.) std::deque<grabbable_state> grabbable_states_; std::optional<absolute_time_point> first_grabbed_event_time_stamp_; mutable std::mutex mutex_; }; } // namespace krbn <|endoftext|>
<commit_before>/* * Copyright (c) The Shogun Machine Learning Toolbox * Written (w) 2014 Parijat Mazumdar * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the Shogun Development Team. */ #include <shogun/machine/RandomForest.h> #include <shogun/mathematics/linalg/LinalgNamespace.h> #include <shogun/multiclass/tree/RandomCARTree.h> #include <utility> using namespace shogun; RandomForest::RandomForest() : BaggingMachine() { init(); } RandomForest::RandomForest(int32_t rand_numfeats, int32_t num_bags) : BaggingMachine() { init(); set_num_bags(num_bags); if (rand_numfeats>0) m_machine->as<RandomCARTree>()->set_feature_subset_size(rand_numfeats); } RandomForest::RandomForest(std::shared_ptr<Features> features, std::shared_ptr<Labels> labels, int32_t num_bags, int32_t rand_numfeats) : BaggingMachine() { init(); m_features=std::move(features); set_labels(std::move(labels)); set_num_bags(num_bags); if (rand_numfeats>0) m_machine->as<RandomCARTree>()->set_feature_subset_size(rand_numfeats); } RandomForest::RandomForest(std::shared_ptr<Features> features, std::shared_ptr<Labels> labels, SGVector<float64_t> weights, int32_t num_bags, int32_t rand_numfeats) : BaggingMachine() { init(); m_features=std::move(features); set_labels(std::move(labels)); m_weights=weights; set_num_bags(num_bags); if (rand_numfeats>0) m_machine->as<RandomCARTree>()->set_feature_subset_size(rand_numfeats); } RandomForest::~RandomForest() { } void RandomForest::set_machine(std::shared_ptr<Machine> machine) { error("Machine is set as CRandomCART and cannot be changed"); } void RandomForest::set_weights(SGVector<float64_t> weights) { m_weights=weights; } SGVector<float64_t> RandomForest::get_weights() const { return m_weights; } void RandomForest::set_feature_types(SGVector<bool> ft) { require(m_machine,"m_machine is NULL. It is expected to be RandomCARTree"); m_machine->as<RandomCARTree>()->set_feature_types(ft); } SGVector<bool> RandomForest::get_feature_types() const { require(m_machine,"m_machine is NULL. It is expected to be RandomCARTree"); return m_machine->as<RandomCARTree>()->get_feature_types(); } EProblemType RandomForest::get_machine_problem_type() const { require(m_machine,"m_machine is NULL. It is expected to be RandomCARTree"); return m_machine->as<RandomCARTree>()->get_machine_problem_type(); } void RandomForest::set_machine_problem_type(EProblemType mode) { require(m_machine,"m_machine is NULL. It is expected to be RandomCARTree"); m_machine->as<RandomCARTree>()->set_machine_problem_type(mode); } void RandomForest::set_num_random_features(int32_t rand_featsize) { require(m_machine,"m_machine is NULL. It is expected to be RandomCARTree"); require(rand_featsize>0,"feature subset size should be greater than 0"); m_machine->as<RandomCARTree>()->set_feature_subset_size(rand_featsize); } int32_t RandomForest::get_num_random_features() const { require(m_machine,"m_machine is NULL. It is expected to be RandomCARTree"); return m_machine->as<RandomCARTree>()->get_feature_subset_size(); } void RandomForest::set_machine_parameters(std::shared_ptr<Machine> m, SGVector<index_t> idx) { require(m,"Machine supplied is NULL"); require(m_machine,"Reference Machine is NULL"); auto tree=m->as<RandomCARTree>(); SGVector<float64_t> weights(idx.vlen); if (m_weights.vlen==0) { weights.fill_vector(weights.vector,weights.vlen,1.0); } else { for (int32_t i=0;i<idx.vlen;i++) weights[i]=m_weights[idx[i]]; } tree->set_weights(weights); tree->set_sorted_features(m_sorted_transposed_feats, m_sorted_indices); // equate the machine problem types - cloning does not do this tree->set_machine_problem_type(m_machine->as<RandomCARTree>()->get_machine_problem_type()); } bool RandomForest::train_machine(std::shared_ptr<Features> data) { if (data) { m_features = data; } require(m_features, "Training features not set!"); m_machine->as<RandomCARTree>()->pre_sort_features(m_features, m_sorted_transposed_feats, m_sorted_indices); return BaggingMachine::train_machine(); } SGVector<float64_t> RandomForest::get_feature_importances() { auto num_feats = m_features->as<DenseFeatures<float64_t>>()->get_num_features(); SGVector<float64_t> feat_importances(num_feats); feat_importances.zero(); for (size_t i = 0; i < m_bags.size(); i++) { auto tree = m_bags[i]->as<RandomCARTree>(); linalg::add( tree->get_feature_importance(), feat_importances, feat_importances); } float64_t mean = 1.0 / m_num_bags; linalg::scale(feat_importances, feat_importances, mean); float64_t normalizer = linalg::sum(feat_importances); if (normalizer) { linalg::scale(feat_importances, feat_importances, 1 / normalizer); } return feat_importances; } void RandomForest::init() { m_machine=std::make_shared<RandomCARTree>(); m_weights=SGVector<float64_t>(); SG_ADD(&m_weights, kWeights, "weights"); } <commit_msg>add watch_method<commit_after>/* * Copyright (c) The Shogun Machine Learning Toolbox * Written (w) 2014 Parijat Mazumdar * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the Shogun Development Team. */ #include <shogun/machine/RandomForest.h> #include <shogun/mathematics/linalg/LinalgNamespace.h> #include <shogun/multiclass/tree/RandomCARTree.h> #include <utility> using namespace shogun; RandomForest::RandomForest() : BaggingMachine() { init(); } RandomForest::RandomForest(int32_t rand_numfeats, int32_t num_bags) : BaggingMachine() { init(); set_num_bags(num_bags); if (rand_numfeats>0) m_machine->as<RandomCARTree>()->set_feature_subset_size(rand_numfeats); } RandomForest::RandomForest(std::shared_ptr<Features> features, std::shared_ptr<Labels> labels, int32_t num_bags, int32_t rand_numfeats) : BaggingMachine() { init(); m_features=std::move(features); set_labels(std::move(labels)); set_num_bags(num_bags); if (rand_numfeats>0) m_machine->as<RandomCARTree>()->set_feature_subset_size(rand_numfeats); } RandomForest::RandomForest(std::shared_ptr<Features> features, std::shared_ptr<Labels> labels, SGVector<float64_t> weights, int32_t num_bags, int32_t rand_numfeats) : BaggingMachine() { init(); m_features=std::move(features); set_labels(std::move(labels)); m_weights=weights; set_num_bags(num_bags); if (rand_numfeats>0) m_machine->as<RandomCARTree>()->set_feature_subset_size(rand_numfeats); } RandomForest::~RandomForest() { } void RandomForest::set_machine(std::shared_ptr<Machine> machine) { error("Machine is set as CRandomCART and cannot be changed"); } void RandomForest::set_weights(SGVector<float64_t> weights) { m_weights=weights; } SGVector<float64_t> RandomForest::get_weights() const { return m_weights; } void RandomForest::set_feature_types(SGVector<bool> ft) { require(m_machine,"m_machine is NULL. It is expected to be RandomCARTree"); m_machine->as<RandomCARTree>()->set_feature_types(ft); } SGVector<bool> RandomForest::get_feature_types() const { require(m_machine,"m_machine is NULL. It is expected to be RandomCARTree"); return m_machine->as<RandomCARTree>()->get_feature_types(); } EProblemType RandomForest::get_machine_problem_type() const { require(m_machine,"m_machine is NULL. It is expected to be RandomCARTree"); return m_machine->as<RandomCARTree>()->get_machine_problem_type(); } void RandomForest::set_machine_problem_type(EProblemType mode) { require(m_machine,"m_machine is NULL. It is expected to be RandomCARTree"); m_machine->as<RandomCARTree>()->set_machine_problem_type(mode); } void RandomForest::set_num_random_features(int32_t rand_featsize) { require(m_machine,"m_machine is NULL. It is expected to be RandomCARTree"); require(rand_featsize>0,"feature subset size should be greater than 0"); m_machine->as<RandomCARTree>()->set_feature_subset_size(rand_featsize); } int32_t RandomForest::get_num_random_features() const { require(m_machine,"m_machine is NULL. It is expected to be RandomCARTree"); return m_machine->as<RandomCARTree>()->get_feature_subset_size(); } void RandomForest::set_machine_parameters(std::shared_ptr<Machine> m, SGVector<index_t> idx) { require(m,"Machine supplied is NULL"); require(m_machine,"Reference Machine is NULL"); auto tree=m->as<RandomCARTree>(); SGVector<float64_t> weights(idx.vlen); if (m_weights.vlen==0) { weights.fill_vector(weights.vector,weights.vlen,1.0); } else { for (int32_t i=0;i<idx.vlen;i++) weights[i]=m_weights[idx[i]]; } tree->set_weights(weights); tree->set_sorted_features(m_sorted_transposed_feats, m_sorted_indices); // equate the machine problem types - cloning does not do this tree->set_machine_problem_type(m_machine->as<RandomCARTree>()->get_machine_problem_type()); } bool RandomForest::train_machine(std::shared_ptr<Features> data) { if (data) { m_features = data; } require(m_features, "Training features not set!"); m_machine->as<RandomCARTree>()->pre_sort_features(m_features, m_sorted_transposed_feats, m_sorted_indices); return BaggingMachine::train_machine(); } SGVector<float64_t> RandomForest::get_feature_importances() { auto num_feats = m_features->as<DenseFeatures<float64_t>>()->get_num_features(); SGVector<float64_t> feat_importances(num_feats); feat_importances.zero(); for (size_t i = 0; i < m_bags.size(); i++) { auto tree = m_bags[i]->as<RandomCARTree>(); linalg::add( tree->get_feature_importance(), feat_importances, feat_importances); } float64_t mean = 1.0 / m_num_bags; linalg::scale(feat_importances, feat_importances, mean); float64_t normalizer = linalg::sum(feat_importances); if (normalizer) { linalg::scale(feat_importances, feat_importances, 1 / normalizer); } return feat_importances; } void RandomForest::init() { m_machine=std::make_shared<RandomCARTree>(); m_weights=SGVector<float64_t>(); watch_method("feature_importances", &RandomForest::get_feature_importances); SG_ADD(&m_weights, kWeights, "weights"); } <|endoftext|>
<commit_before>#ifndef __PML_FRACTION__ #define __PML_FRACTION__ #include <cmath> #include <cstdlib> #include <string> #include "factor.hpp" inline void parse_fraction(std::string frac, int64_t &num, int64_t &den) { unsigned pos = 0; for (unsigned i = 1; i < frac.size(); i++) { if (frac.at(i) == '/') { pos = i; break; } } if (pos == 0) { num = 0; den = 0; return; } num = std::stoll(frac.substr(0, pos)); den = std::stoll(frac.substr(pos + 1, frac.size() - 1)); } inline void reduce(int64_t &num, int64_t &den) { uint64_t numv = num >= 0 ? num : -1 * num; uint64_t denv = den >= 0 ? den : -1 * den; uint64_t div; while ((div = gdc(numv, denv)) != 1) { numv /= div; denv /= div; } num = numv * (num >= 0 ? 1 : -1); den = denv * (den >= 0 ? 1 : -1); } inline bool is_reduced(int64_t num, int64_t den) { num = abs(num); den = abs(den); return gdc(num, den) == 1; } inline void fractionize(double dec, int64_t &num, int64_t &den) { if (dec == 0) { num = 0; den = 1; return; } den = 1; double int_; while (modf(dec * den, &int_) != 0) { den *= 10; } num = dec * den; reduce(num, den); } inline void common_denominator(int64_t &numa, int64_t &dena, int64_t &numb, int64_t &denb) { if (dena == denb) return; int64_t tmp = dena; numa *= denb; numb *= dena; dena *= denb; denb *= tmp; } inline int frac_comp(int64_t numa, int64_t dena, int64_t numb, int64_t denb) { if (numa == numb && dena == denb) return 0; common_denominator(numa, dena, numb, denb); return numa > numb ? 1 : -1; } inline void frac_add(int64_t numa, int64_t dena, int64_t numb, int64_t denb, int64_t &numr, int64_t &denr) { common_denominator(numa, dena, numb, denb); numa += numb; numr = numa; denr = dena; reduce(numr, denr); } inline void frac_add(int64_t &numa, int64_t &dena, int64_t numb, int64_t denb) { return frac_add(numa, dena, numb, denb, numa, dena); } inline void frac_sub(int64_t numa, int64_t dena, int64_t numb, int64_t denb, int64_t &numr, int64_t &denr) { common_denominator(numa, dena, numb, denb); numa -= numb; numr = numa; denr = dena; reduce(numr, denr); } inline void frac_sub(int64_t &numa, int64_t &dena, int64_t numb, int64_t denb) { return frac_sub(numa, dena, numb, denb, numa, dena); } inline void frac_mul(int64_t numa, int64_t dena, int64_t numb, int64_t denb, int64_t &numr, int64_t &denr) { numa *= numb; dena *= denb; numr = numa; denr = dena; reduce(numr, denr); } inline void frac_mul(int64_t &numa, int64_t &dena, int64_t numb, int64_t denb) { return frac_mul(numa, dena, numb, denb, numa, dena); } inline void frac_div(int64_t numa, int64_t dena, int64_t numb, int64_t denb, int64_t &numr, int64_t &denr) { frac_mul(numa, dena, denb, numb, numr, denr); } inline void frac_div(int64_t &numa, int64_t &dena, int64_t numb, int64_t denb) { return frac_div(numa, dena, numb, denb, numa, dena); } #endif <commit_msg>fixed bug with frac_comp<commit_after>#ifndef __PML_FRACTION__ #define __PML_FRACTION__ #include <cmath> #include <cstdlib> #include <string> #include "factor.hpp" inline void parse_fraction(std::string frac, int64_t &num, int64_t &den) { unsigned pos = 0; for (unsigned i = 1; i < frac.size(); i++) { if (frac.at(i) == '/') { pos = i; break; } } if (pos == 0) { num = 0; den = 0; return; } num = std::stoll(frac.substr(0, pos)); den = std::stoll(frac.substr(pos + 1, frac.size() - 1)); } inline void reduce(int64_t &num, int64_t &den) { if (num == 0 || den == 0) return; uint64_t numv = num >= 0 ? num : -1 * num; uint64_t denv = den >= 0 ? den : -1 * den; uint64_t div; while ((div = gdc(numv, denv)) != 1) { numv /= div; denv /= div; } num = numv * (num >= 0 ? 1 : -1); den = denv * (den >= 0 ? 1 : -1); } inline bool is_reduced(int64_t num, int64_t den) { num = abs(num); den = abs(den); return gdc(num, den) == 1; } inline void fractionize(double dec, int64_t &num, int64_t &den) { if (dec == 0) { num = 0; den = 1; return; } den = 1; double int_; while (modf(dec * den, &int_) != 0) { den *= 10; } num = dec * den; reduce(num, den); } inline void common_denominator(int64_t &numa, int64_t &dena, int64_t &numb, int64_t &denb) { if (dena == denb) return; int64_t tmp = dena; numa *= denb; numb *= dena; dena *= denb; denb *= tmp; } inline int frac_comp(int64_t numa, int64_t dena, int64_t numb, int64_t denb) { if (numa == numb && dena == denb) return 0; common_denominator(numa, dena, numb, denb); if (numa == numb) return 0; return numa > numb ? 1 : -1; } inline void frac_add(int64_t numa, int64_t dena, int64_t numb, int64_t denb, int64_t &numr, int64_t &denr) { common_denominator(numa, dena, numb, denb); numa += numb; numr = numa; denr = dena; reduce(numr, denr); } inline void frac_add(int64_t &numa, int64_t &dena, int64_t numb, int64_t denb) { return frac_add(numa, dena, numb, denb, numa, dena); } inline void frac_sub(int64_t numa, int64_t dena, int64_t numb, int64_t denb, int64_t &numr, int64_t &denr) { common_denominator(numa, dena, numb, denb); numa -= numb; numr = numa; denr = dena; reduce(numr, denr); } inline void frac_sub(int64_t &numa, int64_t &dena, int64_t numb, int64_t denb) { return frac_sub(numa, dena, numb, denb, numa, dena); } inline void frac_mul(int64_t numa, int64_t dena, int64_t numb, int64_t denb, int64_t &numr, int64_t &denr) { numa *= numb; dena *= denb; numr = numa; denr = dena; reduce(numr, denr); } inline void frac_mul(int64_t &numa, int64_t &dena, int64_t numb, int64_t denb) { return frac_mul(numa, dena, numb, denb, numa, dena); } inline void frac_div(int64_t numa, int64_t dena, int64_t numb, int64_t denb, int64_t &numr, int64_t &denr) { frac_mul(numa, dena, denb, numb, numr, denr); } inline void frac_div(int64_t &numa, int64_t &dena, int64_t numb, int64_t denb) { return frac_div(numa, dena, numb, denb, numa, dena); } #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: uiks.hxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 17:01:03 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVX_UIKS_HXX #define _SVX_UIKS_HXX #ifndef _USR_UIKS_HXX #include <usr/uiks.hxx> #endif // DBENGINE #define UIK_XDATABASEENGINE UIK_DATABASE(00) #define UIK_XDATABASEFAVORITES UIK_DATABASE(01) #define UIK_XDATABASE UIK_DATABASE(02) #define UIK_XDATABASECONNECTION UIK_DATABASE(03) #define UIK_XTRANSACTIONSUPPORT UIK_DATABASE(04) #define UIK_XDATABASECURSOR UIK_DATABASE(05) #define UIK_XDATABASETABLE UIK_DATABASE(06) #define UIK_XDATABASETABLES UIK_DATABASE(07) #define UIK_XDATABASEQUERY UIK_DATABASE(08) #define UIK_XDATABASEQUERIES UIK_DATABASE(09) #define UIK_XDATABASERELATION UIK_DATABASE(0a) #define UIK_XDATABASERELATIONS UIK_DATABASE(0b) #define UIK_XDATABASEFIELD UIK_DATABASE(0c) #define UIK_XDATABASEFIELDS UIK_DATABASE(0d) #define UIK_XDATABASEINDEX UIK_DATABASE(0e) #define UIK_XDATABASEINDEXES UIK_DATABASE(0f) #define UIK_XDATABASEDOCUMENT UIK_DATABASE(10) #define UIK_XDATABASEDOCUMENTS UIK_DATABASE(11) #define UIK_XDATABASEWORKSPACE UIK_DATABASE(12) #define UIK_XDATABASEWORKSPACES UIK_DATABASE(13) #define UIK_XDATABASEITERATOR UIK_DATABASE(14) #define UIK_XPREPAREDDATABASECURSOR UIK_DATABASE(15) // DBENGINE // FORMS #define UIK_XFORM UIK_FORMS(01) #define UIK_XFORMS UIK_FORMS(02) #define UIK_XFORMCONTROL UIK_FORMS(03) #define UIK_XHTMLFORM UIK_FORMS(05) #define UIK_XHTMLFORMLISTENER UIK_FORMS(06) #define UIK_XDATABASEFORM UIK_FORMS(07) #define UIK_XBOUNDCONTROL UIK_FORMS(08) #define UIK_XINSERTRECORDLISTENER UIK_FORMS(09) #define UIK_XUPDATERECORDLISTENER UIK_FORMS(0a) #define UIK_XDESTROYRECORDLISTENER UIK_FORMS(0b) #define UIK_XCURRENTRECORDLISTENER UIK_FORMS(0c) #define UIK_XBOUNDCONTROLLISTENER UIK_FORMS(0d) #define UIK_XLOADLISTENER UIK_FORMS(0e) #define UIK_XERRORLISTENER UIK_FORMS(0f) #define UIK_XFORMCONTROLFACTORY UIK_FORMS(10) #define UIK_XFORMCONTROLLER UIK_FORMS(11) #define UIK_XFORMCONTROLLERLISTENER UIK_FORMS(12) // FORMS #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.1672); FILE MERGED 2005/09/05 14:16:56 rt 1.1.1.1.1672.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: uiks.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:22:36 $ * * 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 _SVX_UIKS_HXX #define _SVX_UIKS_HXX #ifndef _USR_UIKS_HXX #include <usr/uiks.hxx> #endif // DBENGINE #define UIK_XDATABASEENGINE UIK_DATABASE(00) #define UIK_XDATABASEFAVORITES UIK_DATABASE(01) #define UIK_XDATABASE UIK_DATABASE(02) #define UIK_XDATABASECONNECTION UIK_DATABASE(03) #define UIK_XTRANSACTIONSUPPORT UIK_DATABASE(04) #define UIK_XDATABASECURSOR UIK_DATABASE(05) #define UIK_XDATABASETABLE UIK_DATABASE(06) #define UIK_XDATABASETABLES UIK_DATABASE(07) #define UIK_XDATABASEQUERY UIK_DATABASE(08) #define UIK_XDATABASEQUERIES UIK_DATABASE(09) #define UIK_XDATABASERELATION UIK_DATABASE(0a) #define UIK_XDATABASERELATIONS UIK_DATABASE(0b) #define UIK_XDATABASEFIELD UIK_DATABASE(0c) #define UIK_XDATABASEFIELDS UIK_DATABASE(0d) #define UIK_XDATABASEINDEX UIK_DATABASE(0e) #define UIK_XDATABASEINDEXES UIK_DATABASE(0f) #define UIK_XDATABASEDOCUMENT UIK_DATABASE(10) #define UIK_XDATABASEDOCUMENTS UIK_DATABASE(11) #define UIK_XDATABASEWORKSPACE UIK_DATABASE(12) #define UIK_XDATABASEWORKSPACES UIK_DATABASE(13) #define UIK_XDATABASEITERATOR UIK_DATABASE(14) #define UIK_XPREPAREDDATABASECURSOR UIK_DATABASE(15) // DBENGINE // FORMS #define UIK_XFORM UIK_FORMS(01) #define UIK_XFORMS UIK_FORMS(02) #define UIK_XFORMCONTROL UIK_FORMS(03) #define UIK_XHTMLFORM UIK_FORMS(05) #define UIK_XHTMLFORMLISTENER UIK_FORMS(06) #define UIK_XDATABASEFORM UIK_FORMS(07) #define UIK_XBOUNDCONTROL UIK_FORMS(08) #define UIK_XINSERTRECORDLISTENER UIK_FORMS(09) #define UIK_XUPDATERECORDLISTENER UIK_FORMS(0a) #define UIK_XDESTROYRECORDLISTENER UIK_FORMS(0b) #define UIK_XCURRENTRECORDLISTENER UIK_FORMS(0c) #define UIK_XBOUNDCONTROLLISTENER UIK_FORMS(0d) #define UIK_XLOADLISTENER UIK_FORMS(0e) #define UIK_XERRORLISTENER UIK_FORMS(0f) #define UIK_XFORMCONTROLFACTORY UIK_FORMS(10) #define UIK_XFORMCONTROLLER UIK_FORMS(11) #define UIK_XFORMCONTROLLERLISTENER UIK_FORMS(12) // FORMS #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ndgrf.hxx,v $ * * $Revision: 1.13 $ * * last change: $Author: kz $ $Date: 2004-10-04 18:59:09 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _NDGRF_HXX #define _NDGRF_HXX #ifndef _LNKBASE_HXX //autogen #include <sfx2/lnkbase.hxx> #endif #ifndef _GRFMGR_HXX //autogen #include <goodies/grfmgr.hxx> #endif #ifndef _NDNOTXT_HXX #include <ndnotxt.hxx> #endif class SwGrfFmtColl; class SwDoc; class GraphicAttr; class SvStorage; // -------------------- // SwGrfNode // -------------------- class SwGrfNode: public SwNoTxtNode { friend class SwNodes; friend class SwGrfFrm; GraphicObject aGrfObj; ::sfx2::SvBaseLinkRef refLink; // falls Grafik nur als Link, dann Pointer gesetzt Size nGrfSize; // String aStrmName; // SW3: Name des Storage-Streams fuer Embedded String aNewStrmName; // SW3/XML: new stream name (either SW3 stream // name or package url) String aLowResGrf; // HTML: LowRes Grafik (Ersatzdarstellung bis // die normale (HighRes) geladen ist. BOOL bTransparentFlagValid :1; BOOL bInSwapIn :1; BOOL bGrafikArrived :1; BOOL bChgTwipSize :1; BOOL bChgTwipSizeFromPixel :1; BOOL bLoadLowResGrf :1; BOOL bFrameInPaint :1; //Um Start-/EndActions im Paint (ueber //SwapIn zu verhindern. BOOL bScaleImageMap :1; //Image-Map in SetTwipSize skalieren SwGrfNode( const SwNodeIndex& rWhere, const String& rGrfName, const String& rFltName, const Graphic* pGraphic, SwGrfFmtColl* pGrfColl, SwAttrSet* pAutoAttr = 0 ); // Ctor fuer Einlesen (SW/G) ohne Grafik SwGrfNode( const SwNodeIndex& rWhere, const String& rGrfName, const String& rFltName, SwGrfFmtColl* pGrfColl, SwAttrSet* pAutoAttr = 0 ); SwGrfNode( const SwNodeIndex& rWhere, const GraphicObject& rGrfObj, SwGrfFmtColl* pGrfColl, SwAttrSet* pAutoAttr = 0 ); void InsertLink( const String& rGrfName, const String& rFltName ); BOOL ImportGraphic( SvStream& rStrm ); BOOL HasStreamName() const { return aGrfObj.HasUserData(); } BOOL GetStreamStorageNames( String& rStrmName, String& rStgName ) const; void DelStreamName(); DECL_LINK( SwapGraphic, GraphicObject* ); public: virtual ~SwGrfNode(); const Graphic& GetGrf() const { return aGrfObj.GetGraphic(); } const GraphicObject& GetGrfObj() const { return aGrfObj; } GraphicObject& GetGrfObj() { return aGrfObj; } virtual SwCntntNode *SplitNode( const SwPosition & ); virtual Size GetTwipSize() const; #ifndef _FESHVIEW_ONLY_INLINE_NEEDED void SetTwipSize( const Size& rSz ); BOOL IsTransparent() const; inline BOOL IsAnimated() const { return aGrfObj.IsAnimated(); } inline BOOL IsChgTwipSize() const { return bChgTwipSize; } inline BOOL IsChgTwipSizeFromPixel() const { return bChgTwipSizeFromPixel; } inline void SetChgTwipSize( BOOL b, BOOL bFromPx=FALSE ) { bChgTwipSize = b; bChgTwipSizeFromPixel = bFromPx; } inline BOOL IsGrafikArrived() const { return bGrafikArrived; } inline void SetGrafikArrived( BOOL b ) { bGrafikArrived = b; } inline BOOL IsFrameInPaint() const { return bFrameInPaint; } inline void SetFrameInPaint( BOOL b ) { bFrameInPaint = b; } inline BOOL IsScaleImageMap() const { return bScaleImageMap; } inline void SetScaleImageMap( BOOL b ) { bScaleImageMap = b; } // alles fuers Laden der LowRes-Grafiken inline BOOL IsLoadLowResGrf() const { return bLoadLowResGrf; } inline void SetLoadLowResGrf( BOOL b ) { bLoadLowResGrf = b; } const String& GetLowResGrfName() const { return aLowResGrf; } void SetLowResGrfName( const String& r ) { aLowResGrf = r; } #endif // steht in ndcopy.cxx virtual SwCntntNode* MakeCopy( SwDoc*, const SwNodeIndex& ) const; #ifndef _FESHVIEW_ONLY_INLINE_NEEDED // erneutes Einlesen, falls Graphic nicht Ok ist. Die // aktuelle wird durch die neue ersetzt. BOOL ReRead( const String& rGrfName, const String& rFltName, const Graphic* pGraphic = 0, const GraphicObject* pGrfObj = 0, BOOL bModify = TRUE ); // Laden der Grafik unmittelbar vor der Anzeige short SwapIn( BOOL bWaitForData = FALSE ); // Entfernen der Grafik, um Speicher freizugeben short SwapOut(); // Schreiben der Grafik BOOL StoreGraphics( SvStorage* pDocStg = NULL ); // Zugriff auf den Storage-Streamnamen String GetStreamName() const; void SetStreamName( const String& r ) { aGrfObj.SetUserData( r ); } void SetNewStreamName( const String& r ) { aNewStrmName = r; } void SaveCompleted( BOOL bClear ); // is this node selected by any shell? BOOL IsSelected() const; #endif // Der Grafik sagen, dass sich der Node im Undobereich befindet virtual BOOL SavePersistentData(); virtual BOOL RestorePersistentData(); #ifndef _FESHVIEW_ONLY_INLINE_NEEDED // Abfrage der Link-Daten BOOL IsGrfLink() const { return refLink.Is(); } inline BOOL IsLinkedFile() const; inline BOOL IsLinkedDDE() const; ::sfx2::SvBaseLinkRef GetLink() const { return refLink; } BOOL GetFileFilterNms( String* pFileNm, String* pFilterNm ) const; void ReleaseLink(); // Prioritaet beim Laden der Grafik setzen. Geht nur, wenn der Link // ein FileObject gesetzt hat void SetTransferPriority( USHORT nPrio ); // Skalieren einer Image-Map: Die Image-Map wird um den Faktor // zwischen Grafik-Groesse und Rahmen-Groesse vergroessert/verkleinert void ScaleImageMap(); // returns the with our graphic attributes filled Graphic-Attr-Structure GraphicAttr& GetGraphicAttr( GraphicAttr&, const SwFrm* pFrm ) const; #endif }; // ---------------------------------------------------------------------- // Inline Metoden aus Node.hxx - erst hier ist der TxtNode bekannt !! inline SwGrfNode *SwNode::GetGrfNode() { return ND_GRFNODE == nNodeType ? (SwGrfNode*)this : 0; } inline const SwGrfNode *SwNode::GetGrfNode() const { return ND_GRFNODE == nNodeType ? (const SwGrfNode*)this : 0; } #ifndef _FESHVIEW_ONLY_INLINE_NEEDED inline BOOL SwGrfNode::IsLinkedFile() const { return refLink.Is() && OBJECT_CLIENT_GRF == refLink->GetObjType(); } inline BOOL SwGrfNode::IsLinkedDDE() const { return refLink.Is() && OBJECT_CLIENT_DDE == refLink->GetObjType(); } #endif #endif <commit_msg>INTEGRATION: CWS maybeb (1.13.112); FILE MERGED 2005/01/19 16:12:22 abi 1.13.112.2: #i9861# thread one level lower 2004/12/16 09:33:35 abi 1.13.112.1: #i33293# using thread for reread<commit_after>/************************************************************************* * * $RCSfile: ndgrf.hxx,v $ * * $Revision: 1.14 $ * * last change: $Author: obo $ $Date: 2005-03-15 10:06:27 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _NDGRF_HXX #define _NDGRF_HXX #ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_ #include <com/sun/star/io/XInputStream.hpp> #endif #ifndef _LNKBASE_HXX //autogen #include <sfx2/lnkbase.hxx> #endif #ifndef _GRFMGR_HXX //autogen #include <goodies/grfmgr.hxx> #endif #ifndef _NDNOTXT_HXX #include <ndnotxt.hxx> #endif class SwGrfFmtColl; class SwDoc; class GraphicAttr; class SvStorage; // -------------------- // SwGrfNode // -------------------- class SwGrfNode: public SwNoTxtNode { friend long GrfNodeChanged( void*, void* ); friend class SwNodes; friend class SwGrfFrm; GraphicObject aGrfObj; ::sfx2::SvBaseLinkRef refLink; // falls Grafik nur als Link, dann Pointer gesetzt Size nGrfSize; // String aStrmName; // SW3: Name des Storage-Streams fuer Embedded String aNewStrmName; // SW3/XML: new stream name (either SW3 stream // name or package url) String aLowResGrf; // HTML: LowRes Grafik (Ersatzdarstellung bis // die normale (HighRes) geladen ist. BOOL bTransparentFlagValid :1; BOOL bInSwapIn :1; BOOL bGrafikArrived :1; BOOL bChgTwipSize :1; BOOL bChgTwipSizeFromPixel :1; BOOL bLoadLowResGrf :1; BOOL bFrameInPaint :1; //Um Start-/EndActions im Paint (ueber //SwapIn zu verhindern. BOOL bScaleImageMap :1; //Image-Map in SetTwipSize skalieren SwGrfNode( const SwNodeIndex& rWhere, const String& rGrfName, const String& rFltName, const Graphic* pGraphic, SwGrfFmtColl* pGrfColl, SwAttrSet* pAutoAttr = 0 ); // Ctor fuer Einlesen (SW/G) ohne Grafik SwGrfNode( const SwNodeIndex& rWhere, const String& rGrfName, const String& rFltName, SwGrfFmtColl* pGrfColl, SwAttrSet* pAutoAttr = 0 ); SwGrfNode( const SwNodeIndex& rWhere, const GraphicObject& rGrfObj, SwGrfFmtColl* pGrfColl, SwAttrSet* pAutoAttr = 0 ); void InsertLink( const String& rGrfName, const String& rFltName ); BOOL ImportGraphic( SvStream& rStrm ); BOOL HasStreamName() const { return aGrfObj.HasUserData(); } BOOL GetStreamStorageNames( String& rStrmName, String& rStgName ) const; void DelStreamName(); DECL_LINK( SwapGraphic, GraphicObject* ); public: virtual ~SwGrfNode(); const Graphic& GetGrf() const { return aGrfObj.GetGraphic(); } const GraphicObject& GetGrfObj() const { return aGrfObj; } GraphicObject& GetGrfObj() { return aGrfObj; } virtual SwCntntNode *SplitNode( const SwPosition & ); virtual Size GetTwipSize() const; #ifndef _FESHVIEW_ONLY_INLINE_NEEDED void SetTwipSize( const Size& rSz ); BOOL IsTransparent() const; inline BOOL IsAnimated() const { return aGrfObj.IsAnimated(); } inline BOOL IsChgTwipSize() const { return bChgTwipSize; } inline BOOL IsChgTwipSizeFromPixel() const { return bChgTwipSizeFromPixel; } inline void SetChgTwipSize( BOOL b, BOOL bFromPx=FALSE ) { bChgTwipSize = b; bChgTwipSizeFromPixel = bFromPx; } inline BOOL IsGrafikArrived() const { return bGrafikArrived; } inline void SetGrafikArrived( BOOL b ) { bGrafikArrived = b; } inline BOOL IsFrameInPaint() const { return bFrameInPaint; } inline void SetFrameInPaint( BOOL b ) { bFrameInPaint = b; } inline BOOL IsScaleImageMap() const { return bScaleImageMap; } inline void SetScaleImageMap( BOOL b ) { bScaleImageMap = b; } // alles fuers Laden der LowRes-Grafiken inline BOOL IsLoadLowResGrf() const { return bLoadLowResGrf; } inline void SetLoadLowResGrf( BOOL b ) { bLoadLowResGrf = b; } const String& GetLowResGrfName() const { return aLowResGrf; } void SetLowResGrfName( const String& r ) { aLowResGrf = r; } #endif // steht in ndcopy.cxx virtual SwCntntNode* MakeCopy( SwDoc*, const SwNodeIndex& ) const; #ifndef _FESHVIEW_ONLY_INLINE_NEEDED // erneutes Einlesen, falls Graphic nicht Ok ist. Die // aktuelle wird durch die neue ersetzt. BOOL ReRead( const String& rGrfName, const String& rFltName, const Graphic* pGraphic = 0, const GraphicObject* pGrfObj = 0, BOOL bModify = TRUE ); // Laden der Grafik unmittelbar vor der Anzeige short SwapIn( BOOL bWaitForData = FALSE ); // Entfernen der Grafik, um Speicher freizugeben short SwapOut(); // Schreiben der Grafik BOOL StoreGraphics( SvStorage* pDocStg = NULL ); // Zugriff auf den Storage-Streamnamen String GetStreamName() const; void SetStreamName( const String& r ) { aGrfObj.SetUserData( r ); } void SetNewStreamName( const String& r ) { aNewStrmName = r; } void SaveCompleted( BOOL bClear ); // is this node selected by any shell? BOOL IsSelected() const; #endif // Der Grafik sagen, dass sich der Node im Undobereich befindet virtual BOOL SavePersistentData(); virtual BOOL RestorePersistentData(); #ifndef _FESHVIEW_ONLY_INLINE_NEEDED // Abfrage der Link-Daten BOOL IsGrfLink() const { return refLink.Is(); } inline BOOL IsLinkedFile() const; inline BOOL IsLinkedDDE() const; ::sfx2::SvBaseLinkRef GetLink() const { return refLink; } BOOL GetFileFilterNms( String* pFileNm, String* pFilterNm ) const; void ReleaseLink(); // Prioritaet beim Laden der Grafik setzen. Geht nur, wenn der Link // ein FileObject gesetzt hat void SetTransferPriority( USHORT nPrio ); // Skalieren einer Image-Map: Die Image-Map wird um den Faktor // zwischen Grafik-Groesse und Rahmen-Groesse vergroessert/verkleinert void ScaleImageMap(); // returns the with our graphic attributes filled Graphic-Attr-Structure GraphicAttr& GetGraphicAttr( GraphicAttr&, const SwFrm* pFrm ) const; #endif }; // ---------------------------------------------------------------------- // Inline Metoden aus Node.hxx - erst hier ist der TxtNode bekannt !! inline SwGrfNode *SwNode::GetGrfNode() { return ND_GRFNODE == nNodeType ? (SwGrfNode*)this : 0; } inline const SwGrfNode *SwNode::GetGrfNode() const { return ND_GRFNODE == nNodeType ? (const SwGrfNode*)this : 0; } #ifndef _FESHVIEW_ONLY_INLINE_NEEDED inline BOOL SwGrfNode::IsLinkedFile() const { return refLink.Is() && OBJECT_CLIENT_GRF == refLink->GetObjType(); } inline BOOL SwGrfNode::IsLinkedDDE() const { return refLink.Is() && OBJECT_CLIENT_DDE == refLink->GetObjType(); } #endif #endif <|endoftext|>
<commit_before>#include "dsa_common.h" #include "ws_connection.h" #include <boost/asio/write.hpp> #include "module/logger.h" #include "util/little_endian.h" namespace dsa { using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp> namespace websocket = boost::beast::websocket; // from <boost/beast/websocket.hpp> WsConnection::WsConnection(websocket_stream &ws, LinkStrandRef &strand, const string_ &dsid_prefix, const string_ &path) : Connection(strand, dsid_prefix, path), _ws(std::move(ws)), _read_buffer(DEFAULT_BUFFER_SIZE), _write_buffer(DEFAULT_BUFFER_SIZE) {} void WsConnection::on_deadline_timer_(const boost::system::error_code &error, shared_ptr_<Connection> sthis) { LOG_WARN(_strand->logger(), LOG << "Connection timeout"); destroy_in_strand(std::move(sthis)); } void WsConnection::destroy_impl() { LOG_DEBUG(_strand->logger(), LOG << "connection closed"); if (_ws_open.exchange(false)) { _ws.next_layer().shutdown(tcp::socket::shutdown_both); _ws.next_layer().close(); } Connection::destroy_impl(); } void WsConnection::start_read(shared_ptr_<WsConnection> &&connection, size_t cur, size_t next) { std::vector<uint8_t> &buffer = connection->_read_buffer; size_t partial_size = next - cur; if (cur > 0) { std::copy(buffer.data() + cur, buffer.data() + next, buffer.data()); } if (next * 2 > buffer.size() && buffer.size() < MAX_BUFFER_SIZE) { buffer.resize(buffer.size() * 4); } websocket_stream &ws = connection->_ws; ws.async_read_some( boost::asio::buffer(&buffer[partial_size], buffer.size() - partial_size), [ this, connection = std::move(connection), partial_size ]( const boost::system::error_code &err, size_t transferred) mutable { read_loop_(std::move(connection), partial_size, err, transferred); }); } void WsConnection::read_loop_(shared_ptr_<WsConnection> &&connection, size_t from_prev, const boost::system::error_code &error, size_t bytes_transferred) { // reset deadline timer for each new message // TODO: make this thread safe // connection->reset_standard_deadline_timer(); if (!error) { std::vector<uint8_t> &buffer = _read_buffer; size_t total_bytes = from_prev + bytes_transferred; size_t cur = 0; { std::lock_guard<std::mutex> read_loop_lock(mutex); if (is_destroyed()) { return; } while (cur < total_bytes) { if (total_bytes - cur < sizeof(uint32_t)) { // not enough data to check size start_read(std::move(connection), cur, total_bytes); return; } // TODO: check if message_size is valid; int32_t message_size = read_32_t(&buffer[cur]); if (message_size > Message::MAX_MESSAGE_SIZE) { LOG_DEBUG(_strand->logger(), LOG << "message is bigger than maxed buffer size"); destroy_in_strand(std::move(connection)); // TODO: send error, and close with std::move // WsConnection::destroy_in_strand(std::move(connection)); return; } if (message_size > total_bytes - cur) { // not enough data to parse message start_read(std::move(connection), cur, total_bytes); return; } // post job with message buffer if (on_read_message != nullptr) { try { on_read_message( Message::parse_message(&buffer[cur], message_size)); } catch (const MessageParsingError &err) { LOG_DEBUG(_strand->logger(), LOG << "invalid message received, close connection : " << err.what()); destroy_in_strand(std::move(connection)); // TODO: send error, and close with std::move // WsConnection::destroy_in_strand(std::move(connection)); return; } } else { LOG_FATAL(LOG << "on_read_message is null"); } cur += message_size; } if (!_batch_post.empty()) { do_batch_post(std::move(connection)); return; } } start_read(std::move(connection), 0, 0); } else { // TODO: send error destroy_in_strand(std::move(connection)); return; } } std::unique_ptr<ConnectionWriteBuffer> WsConnection::get_write_buffer() { return std::unique_ptr<ConnectionWriteBuffer>(new WriteBuffer(*this)); } size_t WsConnection::WriteBuffer::max_next_size() const { return MAX_BUFFER_SIZE - size; }; void WsConnection::WriteBuffer::add(const Message &message, int32_t rid, int32_t ack_id) { size_t total_size = size + message.size(); if (total_size > connection._write_buffer.size()) { if (total_size <= MAX_BUFFER_SIZE) { connection._write_buffer.resize(connection._write_buffer.size() * 4); } else { LOG_FATAL(LOG << "message is bigger than max buffer size: " << MAX_BUFFER_SIZE); } } message.write(&connection._write_buffer[size], rid, ack_id); size += message.size(); } void WsConnection::WriteBuffer::write(WriteHandler &&callback) { connection._ws.binary(true); connection._ws.async_write( boost::asio::buffer(connection._write_buffer.data(), size), [callback = std::move(callback)](const boost::system::error_code &error, size_t bytes_transferred) { callback(error); }); } websocket_stream &WsConnection::websocket() { return _ws; } } // namespace dsa <commit_msg>fix compilation errors due to changes in connection class<commit_after>#include "dsa_common.h" #include "ws_connection.h" #include <boost/asio/write.hpp> #include "module/logger.h" #include "util/little_endian.h" namespace dsa { using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp> namespace websocket = boost::beast::websocket; // from <boost/beast/websocket.hpp> WsConnection::WsConnection(websocket_stream &ws, LinkStrandRef &strand, const string_ &dsid_prefix, const string_ &path) : Connection(strand, dsid_prefix, path), _ws(std::move(ws)), _read_buffer(DEFAULT_BUFFER_SIZE), _write_buffer(DEFAULT_BUFFER_SIZE) {} void WsConnection::on_deadline_timer_(const boost::system::error_code &error, shared_ptr_<Connection> sthis) { LOG_WARN(_strand->logger(), LOG << "Connection timeout"); destroy_in_strand(std::move(sthis)); } void WsConnection::destroy_impl() { LOG_DEBUG(_strand->logger(), LOG << "connection closed"); if (_ws_open.exchange(false)) { _ws.next_layer().shutdown(tcp::socket::shutdown_both); _ws.next_layer().close(); } Connection::destroy_impl(); } void WsConnection::start_read(shared_ptr_<Connection> &&connection, size_t cur, size_t next) { std::vector<uint8_t> &buffer = _read_buffer; size_t partial_size = next - cur; if (cur > 0) { std::copy(buffer.data() + cur, buffer.data() + next, buffer.data()); } if (next * 2 > buffer.size() && buffer.size() < MAX_BUFFER_SIZE) { buffer.resize(buffer.size() * 4); } _ws.async_read_some( boost::asio::buffer(&buffer[partial_size], buffer.size() - partial_size), [ this, connection = std::move(connection), partial_size ]( const boost::system::error_code &err, size_t transferred) mutable { read_loop_(std::move(connection), partial_size, err, transferred); }); } void WsConnection::read_loop_(shared_ptr_<Connection> &&connection, size_t from_prev, const boost::system::error_code &error, size_t bytes_transferred) { // reset deadline timer for each new message // TODO: make this thread safe // connection->reset_standard_deadline_timer(); if (!error) { std::vector<uint8_t> &buffer = _read_buffer; size_t total_bytes = from_prev + bytes_transferred; size_t cur = 0; { std::lock_guard<std::mutex> read_loop_lock(mutex); if (is_destroyed()) { return; } while (cur < total_bytes) { if (total_bytes - cur < sizeof(uint32_t)) { // not enough data to check size start_read(std::move(connection), cur, total_bytes); return; } // TODO: check if message_size is valid; int32_t message_size = read_32_t(&buffer[cur]); if (message_size > Message::MAX_MESSAGE_SIZE) { LOG_DEBUG(_strand->logger(), LOG << "message is bigger than maxed buffer size"); destroy_in_strand(std::move(connection)); // TODO: send error, and close with std::move // WsConnection::destroy_in_strand(std::move(connection)); return; } if (message_size > total_bytes - cur) { // not enough data to parse message start_read(std::move(connection), cur, total_bytes); return; } // post job with message buffer if (on_read_message != nullptr) { try { on_read_message( Message::parse_message(&buffer[cur], message_size)); } catch (const MessageParsingError &err) { LOG_DEBUG(_strand->logger(), LOG << "invalid message received, close connection : " << err.what()); destroy_in_strand(std::move(connection)); // TODO: send error, and close with std::move // WsConnection::destroy_in_strand(std::move(connection)); return; } } else { LOG_FATAL(LOG << "on_read_message is null"); } cur += message_size; } if (!_batch_post.empty()) { do_batch_post(std::move(connection)); return; } } start_read(std::move(connection), 0, 0); } else { // TODO: send error destroy_in_strand(std::move(connection)); return; } } std::unique_ptr<ConnectionWriteBuffer> WsConnection::get_write_buffer() { return std::unique_ptr<ConnectionWriteBuffer>(new WriteBuffer(*this)); } size_t WsConnection::WriteBuffer::max_next_size() const { return MAX_BUFFER_SIZE - size; }; void WsConnection::WriteBuffer::add(const Message &message, int32_t rid, int32_t ack_id) { size_t total_size = size + message.size(); if (total_size > connection._write_buffer.size()) { if (total_size <= MAX_BUFFER_SIZE) { connection._write_buffer.resize(connection._write_buffer.size() * 4); } else { LOG_FATAL(LOG << "message is bigger than max buffer size: " << MAX_BUFFER_SIZE); } } message.write(&connection._write_buffer[size], rid, ack_id); size += message.size(); } void WsConnection::WriteBuffer::write(WriteHandler &&callback) { connection._ws.binary(true); connection._ws.async_write( boost::asio::buffer(connection._write_buffer.data(), size), [callback = std::move(callback)](const boost::system::error_code &error, size_t bytes_transferred) { callback(error); }); } websocket_stream &WsConnection::websocket() { return _ws; } } // namespace dsa <|endoftext|>
<commit_before>/** * \file position.cc * \author Jason Fernandez * \date 07/04/2020 */ #include "chess/position.h" #include <cctype> #include <cstddef> #include <string> #include "bitops/bitops.h" #include "superstring/superstring.h" #include "chess/util.h" namespace chess { /** * Constructor */ Position::Position() : black_(), white_(), en_passant_target_(Square::Overflow), full_move_number_(0), half_move_number_(0), pieces_(), to_move_(Player::kBoth) { } /** * Display the current position * * @param[in] stream Write to this output stream */ void Position::Display(std::ostream& stream) const { int prev_rank = 8; const std::uint64_t one = 1; for (int sq = 63; sq >= -1; sq--) { if (util::GetRank(sq) != prev_rank) { stream << "\n ---+---+---+---+---+---+---+--- \n"; if (sq == -1) break; prev_rank = util::GetRank(sq); } const bool black_occupies = OccupiedBy<Player::kBlack>(static_cast<Square>(sq)); stream << "| " << util::PieceToChar(pieces_[sq], black_occupies) << " "; if (sq % 8 == 0) stream << "|"; } stream << std::endl; } /** * Get the current position as a FEN string * * @return The current FEN-encoded position */ std::string Position::GetFen() const { std::string fen = ""; int empty_count = 0; for (Square square = Square::A8; square >= Square::H1; square--) { if (pieces_[square] != Piece::EMPTY) { const bool is_white = OccupiedBy<Player::kWhite>(square); if (empty_count != 0) { fen += std::to_string(empty_count); empty_count = 0; switch (pieces_[square]) { case Piece::PAWN: fen += is_white ? "P" : "p"; break; case Piece::KNIGHT: fen += is_white ? "K" : "k"; break; case Piece::BISHOP: fen += is_white ? "B" : "b"; break; case Piece::ROOK: fen += is_white ? "R" : "r"; break; case Piece::QUEEN: fen += is_white ? "Q" : "q"; break; default: fen += is_white ? "K" : "k"; break; } } } else { empty_count++; } // Time to start the next rank? if (square % 8 == 0) { if (empty_count != 0) { fen += std::to_string(empty_count); empty_count = 0; } if (square != Square::H1) { fen += "/"; } } } fen += to_move_ == Player::kWhite ? " w " : " b "; bool can_castle_any = false; if (white_.CanCastleShort()) { can_castle_any = true; fen += "K"; } if (white_.CanCastleLong()) { can_castle_any = true; fen += "Q"; } if (black_.CanCastleShort()) { can_castle_any = true; fen += "k"; } if (black_.CanCastleLong()) { can_castle_any = true; fen += "q"; } if (!can_castle_any) { fen += "-"; } fen += " "; fen += en_passant_target_ != Square::Overflow ? kSquareStr[en_passant_target_] : "-"; fen += " " + std::to_string(full_move_number_) + " " + std::to_string(half_move_number_); return fen; } /** * Make a move * * @param[in] move The move to make */ void Position::MakeMove(std::uint32_t move) noexcept { #ifdef DEBUG_MAKE_UNMAKE #endif } /** * Reset this position * * @param[in] fen_ Encodes the position to set up * * @return One of the \ref FenError codes */ auto Position::Reset(const std::string& fen_) -> FenError { Position pos; jfern::superstring fen(fen_); auto tokens = fen.split("/"); if (tokens.size() != 8) { return FenError::kNumberOfRanks; } auto square = 63; for (std::size_t i = 0; i < tokens.size(); i++) { for (std::size_t j = 0; j < tokens[i].size(); j++) { const char c = tokens[i][j]; const Piece piece = util::CharToPiece(c); if (piece != Piece::EMPTY) { pos.pieces_[square] = piece; const auto squareE = static_cast<Square>(square); if (std::tolower(c) == c) { pos.GetPlayerInfo<Player::kBlack>().Drop(piece, squareE); } else { pos.GetPlayerInfo<Player::kWhite>().Drop(piece, squareE); } square--; } else if (std::isdigit(c)) { square -= std::stol(std::string(&c,1)); } else { return FenError::kInvalidCharacter; } if ((square < -1) || (square == -1 && i != 7u)) { return FenError::kNumberOfSquares; } else if (square < 0) { break; // Move onto whose turn } } } tokens = jfern::superstring(tokens.back()).split(); pos.full_move_number_ = 1; pos.half_move_number_ = 0; switch (tokens.size()) { default: // Ignore anything beyond the 6th token instead of // returning an error case 6u: pos.full_move_number_ = std::stol(tokens[5]); case 5u: pos.half_move_number_ = std::stol(tokens[4]); case 4u: if (tokens[3] != "-") { if ((pos.en_passant_target_ = util::StrToSquare(tokens[3])) == Square::Overflow) { return FenError::kEnPassantSquare; } } case 3u: if (tokens[2] != "-") { for (std::size_t i = 0; i < tokens[2].size(); i++) { switch (tokens[2][i]) { case 'K': pos.white_.CanCastleShort() = true; break; case 'Q': pos.white_.CanCastleLong() = true; break; case 'k': pos.black_.CanCastleShort() = true; break; case 'q': pos.black_.CanCastleLong() = true; break; default: return FenError::kCastlingRights; } } } case 2u: if (tokens[1] != "w" && tokens[1] != "b") { return FenError::kInvalidColor; } else { pos.to_move_ = tokens[1] == "w" ? Player::kWhite : Player::kBlack; } break; case 1u: return FenError::kMissingColor; } const auto error_code = Validate(pos); if (error_code == FenError::kSuccess) { *this = std::move(pos); } return error_code; } /** * Make a move * * @param[in] move The move to make */ void Position::UnMakeMove(std::uint32_t move) noexcept { #ifdef DEBUG_MAKE_UNMAKE #endif } /** * * @param[in] error A \ref FenError code * * @return The */ std::string Position::ErrorToString(FenError error) { return ""; } /** * Validate a position. The following rules are checked against: * * 1. No pawns on the 1st or 8th ranks * 2. Only two kings on board * 3. Side to move cannot capture the opposing king * 4. Castling rights make sense (e.g. if the king is not on its home square, * then castling is not possible) * 5. En passant target makes sense (e.g. there must be a pawn that has * advanced by two squares) * 6. Maximum of 8 pawns per side * 7. At most 10 of any type of piece, per side * * @return One of the \ref FenError codes */ auto Position::Validate(const Position& pos) -> FenError { const auto& white = pos.GetPlayerInfo<Player::kWhite>(); const auto& black = pos.GetPlayerInfo<Player::kBlack>(); const auto white_pawns = white.Pawns(); const auto black_pawns = black.Pawns(); const auto white_kings = white.King(); const auto black_kings = black.King(); if ((white_pawns | black_pawns) & (kRank1 | kRank8)) { return FenError::kPawnsOnBackRank; } if ((jfern::bitops::count(white_kings) != 1u) || (jfern::bitops::count(black_kings) != 1u)) { return FenError::kNumberOfKings; } if ((pos.ToMove() == Player::kWhite && pos.InCheck<Player::kBlack>()) || (pos.ToMove() == Player::kBlack && pos.InCheck<Player::kWhite>())) { return FenError::kKingCanBeCaptured; } const auto white_king_square = white.KingSquare(); const auto black_king_square = black.KingSquare(); const bool may_castle_short_w = white.CanCastleShort(); const bool may_castle_long_w = white.CanCastleLong(); const bool may_castle_short_b = black.CanCastleShort(); const bool may_castle_long_b = black.CanCastleLong(); const bool white_may_castle = may_castle_short_w || may_castle_long_w; const bool black_may_castle = may_castle_short_b || may_castle_long_b; if (white_king_square != Square::E1 && white_may_castle) { return FenError::kWhiteMayNotCastle; } if (black_king_square != Square::E8 && black_may_castle) { return FenError::kBlackMayNotCastle; } const auto black_rook_on_h8 = black.Rooks() & data_tables::kSetMask[Square::H8]; const auto black_rook_on_a8 = black.Rooks() & data_tables::kSetMask[Square::A8]; if (may_castle_short_b && !black_rook_on_h8) { return FenError::kBlackMayNotCastleShort; } if (may_castle_long_b && !black_rook_on_a8) { return FenError::kBlackMayNotCastleLong; } const auto white_rook_on_h1 = white.Rooks() & data_tables::kSetMask[Square::H1]; const auto white_rook_on_a1 = white.Rooks() & data_tables::kSetMask[Square::A1]; if (may_castle_short_w && !white_rook_on_h1) { return FenError::kWhiteMayNotCastleShort; } if (may_castle_long_w && !white_rook_on_a1) { return FenError::kWhiteMayNotCastleLong; } const auto ep_target = pos.EnPassantTarget(); const auto ep_target64 = data_tables::kSetMask[ep_target]; if (ep_target != Square::Overflow && ep_target != Square::Underflow) { if (pos.ToMove() == Player::kWhite) { if (util::GetRank(ep_target) != 5 || !(black_pawns & (ep_target64 >> 8)) || (pos.Occupied() & ep_target64)) { return FenError::kEnPassantSquare; } } else { if (util::GetRank(ep_target) != 2 || !(black_pawns & (ep_target64 << 8)) || (pos.Occupied() & ep_target64)) { return FenError::kEnPassantSquare; } } } if ((jfern::bitops::count(white_pawns) > 8u) || (jfern::bitops::count(black_pawns) > 8u)) { return FenError::kTooManyPawns; } if ((jfern::bitops::count(white.Knights()) > 10u) || (jfern::bitops::count(black.Knights()) > 10u)) { return FenError::kTooManyKnights; } if ((jfern::bitops::count(white.Rooks()) > 10u) || (jfern::bitops::count(black.Rooks()) > 10u)) { return FenError::kTooManyRooks; } if ((jfern::bitops::count(white.Queens()) > 10u) || (jfern::bitops::count(black.Queens()) > 10u)) { return FenError::kTooManyQueens; } if ((jfern::bitops::count(white.Bishops()) > 10u) || (jfern::bitops::count(black.Bishops()) > 10u)) { return FenError::kTooManyBishops; } return FenError::kSuccess; } } // namespace chess <commit_msg>Additional checks on position validation<commit_after>/** * \file position.cc * \author Jason Fernandez * \date 07/04/2020 */ #include "chess/position.h" #include <cctype> #include <cstddef> #include <string> #include "bitops/bitops.h" #include "superstring/superstring.h" #include "chess/util.h" namespace chess { /** * Constructor */ Position::Position() : black_(), white_(), en_passant_target_(Square::Overflow), full_move_number_(0), half_move_number_(0), pieces_(), to_move_(Player::kBoth) { } /** * Display the current position * * @param[in] stream Write to this output stream */ void Position::Display(std::ostream& stream) const { int prev_rank = 8; const std::uint64_t one = 1; for (int sq = 63; sq >= -1; sq--) { if (util::GetRank(sq) != prev_rank) { stream << "\n ---+---+---+---+---+---+---+--- \n"; if (sq == -1) break; prev_rank = util::GetRank(sq); } const bool black_occupies = OccupiedBy<Player::kBlack>(static_cast<Square>(sq)); stream << "| " << util::PieceToChar(pieces_[sq], black_occupies) << " "; if (sq % 8 == 0) stream << "|"; } stream << std::endl; } /** * Get the current position as a FEN string * * @return The current FEN-encoded position */ std::string Position::GetFen() const { std::string fen = ""; int empty_count = 0; for (Square square = Square::A8; square >= Square::H1; square--) { if (pieces_[square] != Piece::EMPTY) { const bool is_white = OccupiedBy<Player::kWhite>(square); if (empty_count != 0) { fen += std::to_string(empty_count); empty_count = 0; switch (pieces_[square]) { case Piece::PAWN: fen += is_white ? "P" : "p"; break; case Piece::KNIGHT: fen += is_white ? "K" : "k"; break; case Piece::BISHOP: fen += is_white ? "B" : "b"; break; case Piece::ROOK: fen += is_white ? "R" : "r"; break; case Piece::QUEEN: fen += is_white ? "Q" : "q"; break; default: fen += is_white ? "K" : "k"; break; } } } else { empty_count++; } // Time to start the next rank? if (square % 8 == 0) { if (empty_count != 0) { fen += std::to_string(empty_count); empty_count = 0; } if (square != Square::H1) { fen += "/"; } } } fen += to_move_ == Player::kWhite ? " w " : " b "; bool can_castle_any = false; if (white_.CanCastleShort()) { can_castle_any = true; fen += "K"; } if (white_.CanCastleLong()) { can_castle_any = true; fen += "Q"; } if (black_.CanCastleShort()) { can_castle_any = true; fen += "k"; } if (black_.CanCastleLong()) { can_castle_any = true; fen += "q"; } if (!can_castle_any) { fen += "-"; } fen += " "; fen += en_passant_target_ != Square::Overflow ? kSquareStr[en_passant_target_] : "-"; fen += " " + std::to_string(full_move_number_) + " " + std::to_string(half_move_number_); return fen; } /** * Make a move * * @param[in] move The move to make */ void Position::MakeMove(std::uint32_t move) noexcept { #ifdef DEBUG_MAKE_UNMAKE #endif } /** * Reset this position * * @param[in] fen_ Encodes the position to set up * * @return One of the \ref FenError codes */ auto Position::Reset(const std::string& fen_) -> FenError { Position pos; jfern::superstring fen(fen_); auto tokens = fen.split("/"); if (tokens.size() != 8) { return FenError::kNumberOfRanks; } auto square = 63; for (std::size_t i = 0; i < tokens.size(); i++) { for (std::size_t j = 0; j < tokens[i].size(); j++) { const char c = tokens[i][j]; const Piece piece = util::CharToPiece(c); if (piece != Piece::EMPTY) { pos.pieces_[square] = piece; const auto squareE = static_cast<Square>(square); if (std::tolower(c) == c) { pos.GetPlayerInfo<Player::kBlack>().Drop(piece, squareE); } else { pos.GetPlayerInfo<Player::kWhite>().Drop(piece, squareE); } square--; } else if (std::isdigit(c)) { square -= std::stol(std::string(&c,1)); } else { return FenError::kInvalidCharacter; } if ((square < -1) || (square == -1 && i != 7u)) { return FenError::kNumberOfSquares; } else if (square < 0) { break; // Move onto whose turn } } } tokens = jfern::superstring(tokens.back()).split(); pos.full_move_number_ = 1; pos.half_move_number_ = 0; switch (tokens.size()) { default: // Ignore anything beyond the 6th token instead of // returning an error case 6u: pos.full_move_number_ = std::stol(tokens[5]); if (pos.full_move_number_ < 1) { return FenError::kFullMoveNumber; } case 5u: pos.half_move_number_ = std::stol(tokens[4]); if (pos.half_move_number_ < 0) { return FenError::kHalfMoveClock; } case 4u: if (tokens[3] != "-") { if ((pos.en_passant_target_ = util::StrToSquare(tokens[3])) == Square::Overflow) { return FenError::kEnPassantSquare; } } case 3u: if (tokens[2] != "-") { for (std::size_t i = 0; i < tokens[2].size(); i++) { switch (tokens[2][i]) { case 'K': pos.white_.CanCastleShort() = true; break; case 'Q': pos.white_.CanCastleLong() = true; break; case 'k': pos.black_.CanCastleShort() = true; break; case 'q': pos.black_.CanCastleLong() = true; break; default: return FenError::kCastlingRights; } } } case 2u: if (tokens[1] != "w" && tokens[1] != "b") { return FenError::kInvalidColor; } else { pos.to_move_ = tokens[1] == "w" ? Player::kWhite : Player::kBlack; } break; case 1u: return FenError::kMissingColor; } const auto error_code = Validate(pos); if (error_code == FenError::kSuccess) { *this = std::move(pos); } return error_code; } /** * Make a move * * @param[in] move The move to make */ void Position::UnMakeMove(std::uint32_t move) noexcept { #ifdef DEBUG_MAKE_UNMAKE #endif } /** * * @param[in] error A \ref FenError code * * @return The */ std::string Position::ErrorToString(FenError error) { return ""; } /** * Validate a position. The following rules are checked against: * * 1. No pawns on the 1st or 8th ranks * 2. Only two kings on board * 3. Side to move cannot capture the opposing king * 4. Castling rights make sense (e.g. if the king is not on its home square, * then castling is not possible) * 5. En passant target makes sense (e.g. there must be a pawn that has * advanced by two squares) * 6. Maximum of 8 pawns per side * 7. At most 10 of any type of piece, per side * * @return One of the \ref FenError codes */ auto Position::Validate(const Position& pos) -> FenError { const auto& white = pos.GetPlayerInfo<Player::kWhite>(); const auto& black = pos.GetPlayerInfo<Player::kBlack>(); const auto white_pawns = white.Pawns(); const auto black_pawns = black.Pawns(); const auto white_kings = white.King(); const auto black_kings = black.King(); if ((white_pawns | black_pawns) & (kRank1 | kRank8)) { return FenError::kPawnsOnBackRank; } if ((jfern::bitops::count(white_kings) != 1u) || (jfern::bitops::count(black_kings) != 1u)) { return FenError::kNumberOfKings; } if ((pos.ToMove() == Player::kWhite && pos.InCheck<Player::kBlack>()) || (pos.ToMove() == Player::kBlack && pos.InCheck<Player::kWhite>())) { return FenError::kKingCanBeCaptured; } const auto white_king_square = white.KingSquare(); const auto black_king_square = black.KingSquare(); const bool may_castle_short_w = white.CanCastleShort(); const bool may_castle_long_w = white.CanCastleLong(); const bool may_castle_short_b = black.CanCastleShort(); const bool may_castle_long_b = black.CanCastleLong(); const bool white_may_castle = may_castle_short_w || may_castle_long_w; const bool black_may_castle = may_castle_short_b || may_castle_long_b; if (white_king_square != Square::E1 && white_may_castle) { return FenError::kWhiteMayNotCastle; } if (black_king_square != Square::E8 && black_may_castle) { return FenError::kBlackMayNotCastle; } const auto black_rook_on_h8 = black.Rooks() & data_tables::kSetMask[Square::H8]; const auto black_rook_on_a8 = black.Rooks() & data_tables::kSetMask[Square::A8]; if (may_castle_short_b && !black_rook_on_h8) { return FenError::kBlackMayNotCastleShort; } if (may_castle_long_b && !black_rook_on_a8) { return FenError::kBlackMayNotCastleLong; } const auto white_rook_on_h1 = white.Rooks() & data_tables::kSetMask[Square::H1]; const auto white_rook_on_a1 = white.Rooks() & data_tables::kSetMask[Square::A1]; if (may_castle_short_w && !white_rook_on_h1) { return FenError::kWhiteMayNotCastleShort; } if (may_castle_long_w && !white_rook_on_a1) { return FenError::kWhiteMayNotCastleLong; } const auto ep_target = pos.EnPassantTarget(); const auto ep_target64 = data_tables::kSetMask[ep_target]; if (ep_target != Square::Overflow && ep_target != Square::Underflow) { if (pos.ToMove() == Player::kWhite) { if (util::GetRank(ep_target) != 5 || !(black_pawns & (ep_target64 >> 8)) || (pos.Occupied() & ep_target64)) { return FenError::kEnPassantSquare; } } else { if (util::GetRank(ep_target) != 2 || !(black_pawns & (ep_target64 << 8)) || (pos.Occupied() & ep_target64)) { return FenError::kEnPassantSquare; } } } if ((jfern::bitops::count(white_pawns) > 8u) || (jfern::bitops::count(black_pawns) > 8u)) { return FenError::kTooManyPawns; } if ((jfern::bitops::count(white.Knights()) > 10u) || (jfern::bitops::count(black.Knights()) > 10u)) { return FenError::kTooManyKnights; } if ((jfern::bitops::count(white.Rooks()) > 10u) || (jfern::bitops::count(black.Rooks()) > 10u)) { return FenError::kTooManyRooks; } if ((jfern::bitops::count(white.Queens()) > 10u) || (jfern::bitops::count(black.Queens()) > 10u)) { return FenError::kTooManyQueens; } if ((jfern::bitops::count(white.Bishops()) > 10u) || (jfern::bitops::count(black.Bishops()) > 10u)) { return FenError::kTooManyBishops; } return FenError::kSuccess; } } // namespace chess <|endoftext|>
<commit_before>#include "process.hpp" ////////////// // Includes // #include "image.hpp" ////////// // Code // // Verifying the validity of a set of images. bool validateImages(int count, Image** imgs) { for (int i = 1; i < count; i++) { if (imgs[i - 1]->width != imgs[i]->width || imgs[i - 1]->height != imgs[i]->height || imgs[i - 1]->maxValue != imgs[i]->maxValue) return false; } return true; } // Getting a single pixel at a given index of every image. Pixel* getPixelsAt(int count, Image** imgs, int index) { Pixel* pixels = new Pixel[count]; for (int i = 0; i < count; i++) pixels[i] = imgs[i]->pixels[i]; return pixels; } Pixel choosePixel(int count, Pixel* pixels) { // TODO: Develop a consensus. Pixel p; return p; } // Processing a set of images. Image* processImages(int count, Image** imgs) { if (!validateImages(count, imgs)) return nullptr; int length = imgs[0]->width * imgs[0]->height; Pixel* finalPixels = new Pixel[length]; Pixel* pixels; for (int i = 0; i < length; i++) { pixels = getPixelsAt(count, imgs, i); finalPixels[i] = choosePixel(count, pixels); delete[] pixels; } return new Image(finalPixels, imgs[0]->width, imgs[0]->height, imgs[0]->maxValue); } <commit_msg>Accidentally got the wrong index.<commit_after>#include "process.hpp" ////////////// // Includes // #include "image.hpp" ////////// // Code // // Verifying the validity of a set of images. bool validateImages(int count, Image** imgs) { for (int i = 1; i < count; i++) { if (imgs[i - 1]->width != imgs[i]->width || imgs[i - 1]->height != imgs[i]->height || imgs[i - 1]->maxValue != imgs[i]->maxValue) return false; } return true; } // Getting a single pixel at a given index of every image. Pixel* getPixelsAt(int count, Image** imgs, int index) { Pixel* pixels = new Pixel[count]; for (int i = 0; i < count; i++) pixels[i] = imgs[i]->pixels[index]; return pixels; } Pixel choosePixel(int count, Pixel* pixels) { // TODO: Develop a consensus. Pixel p; return p; } // Processing a set of images. Image* processImages(int count, Image** imgs) { if (!validateImages(count, imgs)) return nullptr; int length = imgs[0]->width * imgs[0]->height; Pixel* finalPixels = new Pixel[length]; Pixel* pixels; for (int i = 0; i < length; i++) { pixels = getPixelsAt(count, imgs, i); finalPixels[i] = choosePixel(count, pixels); delete[] pixels; } return new Image(finalPixels, imgs[0]->width, imgs[0]->height, imgs[0]->maxValue); } <|endoftext|>
<commit_before>#include "program.h" #include "filesystem.h" #include "common/settings.h" #include "common/log.h" #include "quickvertexbuffer.h" #include <hl1bspinstance.h> #include <SDL.h> #include <glm/gtc/matrix_transform.hpp> #include <iostream> #include <sstream> Application* gApp = new Program(); static FileLoggingStrategy fileLogging; glm::mat4 Object::LocalMatrix() const { return glm::translate(glm::toMat4(this->_rotation), this->_position); } glm::mat4 Object::WorldMatrix() const { glm::mat4 view = this->LocalMatrix(); if (this->_parent != nullptr) view = this->_parent->WorldMatrix() * this->LocalMatrix(); return view; } void Object::Render(const glm::mat4 &proj) { if (this->_instance != nullptr) { this->_instance->Render(proj, this->WorldMatrix()); } } Program::Program() : _pan(false), _lastX(0), _lastY(0), _asset(nullptr), _instance(nullptr) { Settings::Instance()->LoadFromDisk("king-of-the-bombspot.settings"); Setting("Viewer.PauseAnimation").Register(false); Setting("Viewer.Camera.Speed").Register(200.0f); Logging::Instance()->SetStrategy(&fileLogging); } Program::~Program() { } bool Program::InitializeApplication(System* sys) { this->_sys = sys; return true; } typedef struct { int index; std::set<int> neighbours; std::vector<int> cornerIndices; } element; QuickVertexBuffer* buf = nullptr; Array<element> edges; Array<element> faces; std::ostream& operator << (std::ostream& os, const glm::vec2& v) { os << "[" << v[0] << ", " << v[1] << "]"; return os; } std::ostream& operator << (std::ostream& os, const glm::vec3& v) { os << "[" << v[0] << ", " << v[1] << ", " << v[2] << "]"; return os; } std::ostream& operator << (std::ostream& os, const glm::vec4& v) { os << "[" << v[0] << ", " << v[1] << ", " << v[2] << ", " << v[3] << "]"; return os; } glm::vec3 ParseVec3(const std::string& str) { double x, y, z; std::stringstream ss(str); ss >> x >> y >> z; return glm::vec3(x, y, z); } bool Program::InitializeGraphics() { std::cout << "GL_VERSION : " << glGetString(GL_VERSION) << std::endl; std::cout << "GL_SHADING_LANGUAGE_VERSION : " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; std::cout << "GL_RENDERER : " << glGetString(GL_RENDERER) << std::endl; std::cout << "GL_VENDOR : " << glGetString(GL_VENDOR) << std::endl; glClearColor(0.0f, 0.0f, 0.0f, 1.0f); this->_cam.MoveForward(-120.0f); if (this->_sys->GetArgs().size() > 1) { std::string filename = this->_sys->GetArgs()[1]; this->_asset = new Hl1BspAsset(FileSystem::LocateDataFile, FileSystem::LoadFileData); if (this->_asset != nullptr && this->_asset->Load(filename)) { this->_instance = (Hl1BspInstance*)this->_asset->CreateInstance(); auto mdlAsset = new Hl1MdlAsset(FileSystem::LocateDataFile, FileSystem::LoadFileData); mdlAsset->Load("..\\king-of-the-bombspot\\data\\sas.mdl"); for (auto itr = this->_asset->_entities.begin(); itr != _asset->_entities.end(); ++itr) { HL1::tBSPEntity& entity = *itr; if (entity.classname == "info_player_start" && entity.keyvalues.find("origin") != entity.keyvalues.end()) { std::string origin = entity.keyvalues.at("origin"); auto obj = new Object(); obj->_instance = mdlAsset->CreateInstance(); obj->_position = ParseVec3(origin); this->_objects.push_back(obj); } } edges.Allocate(this->_asset->_edgeData.count); for (int f = 0; f < this->_asset->_faceData.count; f++) { HL1::tBSPFace& face = this->_asset->_faceData[f]; for (int e = 0; e < face.edgeCount; e++) { int ei = this->_asset->_surfedgeData[face.firstEdge + e]; edges[ei < 0 ? -ei : ei].index = ei < 0 ? -ei : ei; edges[ei < 0 ? -ei : ei].neighbours.insert(f); edges[ei < 0 ? -ei : ei].cornerIndices.push_back(_asset->_edgeData[ei < 0 ? -ei : ei].vertex[0]); edges[ei < 0 ? -ei : ei].cornerIndices.push_back(_asset->_edgeData[ei < 0 ? -ei : ei].vertex[1]); } } faces.Allocate(this->_asset->_faceData.count); for (int f = 0; f < this->_asset->_faceData.count; f++) { HL1::tBSPFace& face = this->_asset->_faceData[f]; for (int e = 0; e < face.edgeCount; e++) { int ei = this->_asset->_surfedgeData[face.firstEdge + e]; auto edge = edges[ei < 0 ? -ei : ei]; faces[f].index = f; faces[f].neighbours.insert(edge.neighbours.begin(), edge.neighbours.end()); faces[f].cornerIndices.push_back(_asset->_edgeData[ei < 0 ? -ei : ei].vertex[0]); faces[f].cornerIndices.push_back(_asset->_edgeData[ei < 0 ? -ei : ei].vertex[1]); } faces[f].neighbours.erase(f); } std::vector<glm::vec3> verts; for (int v = 0; v < _asset->_verticesData.count; v++) verts.push_back(_asset->_verticesData[v].point); buf = new QuickVertexBuffer(GL_LINES, verts); } } return true; } void Program::GameLoop() { static double lastTime = this->_sys->GetTime(); static double lastUpdateTime = this->_sys->GetTime(); double time = this->_sys->GetTime(); double diff = time - lastTime; double speed = double(Setting("Viewer.Camera.Speed").AsFloat()); if (this->_sys->IsKeyDown(KeyCodes::Character_A)) this->_cam.MoveLeft(diff * speed); else if (this->_sys->IsKeyDown(KeyCodes::Character_D)) this->_cam.MoveLeft(-diff * speed); if (this->_sys->IsKeyDown(KeyCodes::Character_W)) this->_cam.MoveForward(diff * speed); else if (this->_sys->IsKeyDown(KeyCodes::Character_S)) this->_cam.MoveForward(-diff * speed); lastTime = time; double updateDiff = time - lastUpdateTime; if (updateDiff > 1.0/60.0) { if (this->_instance != nullptr && Setting("Viewer.PauseAnimation").AsBool() == false) this->_instance->Update(updateDiff); lastUpdateTime = time; } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_ALPHA_TEST); // for (int i = 0; i < edges.count; i++) // { // buf->RenderSubSet(this->_proj * this->_cam.GetViewMatrix(), edges[i].cornerIndices); // } for (int i = 0; i < faces.count; i++) { if (glm::dot(_asset->_faces[i].plane.normal, glm::vec3(0.0f, 0.0f, 1.0f)) < 0.7f) continue; if (_asset->_faces[i].flags != 0) continue; if (_asset->_textures[_asset->_faces[i].texture].Name()[0] == '!') continue; buf->RenderSubSet(this->_proj * this->_cam.GetViewMatrix(), faces[i].cornerIndices); } glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GEQUAL, 0.8f); if (this->_instance != nullptr) { this->_instance->Render(this->_proj, this->_cam.GetViewMatrix()); } for (auto obj = this->_objects.begin(); obj != this->_objects.end(); ++obj) (*obj)->Render(this->_proj * this->_cam.GetViewMatrix()); } bool Program::IsRunning() { const Uint8 *state = SDL_GetKeyboardState(nullptr); return !state[SDL_SCANCODE_ESCAPE]; } void Program:: Resize(int w, int h) { if (h < 1) h = 1; glViewport(0, 0, w, h); this->_proj = glm::perspective(120.0f, float(w) / float(h), 0.1f, 4000.0f); } void Program::MouseButtonDown(int button, int x, int y) { this->_pan = (button == SDL_BUTTON_LEFT); this->_lastX = x; this->_lastY = y; } void Program::MouseMove(int x, int y) { if (this->_pan) { this->_cam.RotateZ(glm::radians(float(this->_lastX-x) * 0.1f)); this->_cam.RotateX(glm::radians(float(this->_lastY-y) * 0.1f)); } this->_lastX = x; this->_lastY = y; } void Program::MouseButtonUp(int button, int x, int y) { this->_pan = false; } void Program::MouseWheel(int x, int y) { } void Program::KeyAction(int key, int action) { if (key == SDLK_SPACE && action) Setting("Viewer.PauseAnimation") = !Setting("Viewer.PauseAnimation").AsBool(); else if (key == SDLK_KP_PLUS && action) Setting("Viewer.Camera.Speed") = Setting("Viewer.Camera.Speed").AsFloat() + 5.0f; else if (key == SDLK_KP_MINUS && action) Setting("Viewer.Camera.Speed") = Setting("Viewer.Camera.Speed").AsFloat() - 5.0f; } void Program::Close() { this->_running = false; } void Program::Destroy() { Settings::Instance()->SaveToDisk("king-of-the-bombspot.settings"); } int Program::GetWindowFlags() { return SDL_WINDOW_BORDERLESS; } <commit_msg>Make it work with updated game-assets library<commit_after>#include "program.h" #include "filesystem.h" #include "common/settings.h" #include "common/log.h" #include "quickvertexbuffer.h" #include <hl1bspinstance.h> #include <SDL.h> #include <glm/gtc/matrix_transform.hpp> #include <iostream> #include <sstream> Application* gApp = new Program(); static FileLoggingStrategy fileLogging; glm::mat4 Object::LocalMatrix() const { return glm::translate(glm::toMat4(this->_rotation), this->_position); } glm::mat4 Object::WorldMatrix() const { glm::mat4 view = this->LocalMatrix(); if (this->_parent != nullptr) view = this->_parent->WorldMatrix() * this->LocalMatrix(); return view; } void Object::Render(const glm::mat4 &proj) { if (this->_instance != nullptr) { this->_instance->Render(proj, this->WorldMatrix()); } } Program::Program() : _pan(false), _lastX(0), _lastY(0), _asset(nullptr), _instance(nullptr) { Settings::Instance()->LoadFromDisk("king-of-the-bombspot.settings"); Setting("Viewer.Camera.Speed").Register(200.0f); Logging::Instance()->SetStrategy(&fileLogging); } Program::~Program() { } bool Program::InitializeApplication(System* sys) { this->_sys = sys; return true; } typedef struct { int index; std::set<int> neighbours; std::vector<int> cornerIndices; } element; QuickVertexBuffer* buf = nullptr; Array<element> edges; Array<element> faces; std::ostream& operator << (std::ostream& os, const glm::vec2& v) { os << "[" << v[0] << ", " << v[1] << "]"; return os; } std::ostream& operator << (std::ostream& os, const glm::vec3& v) { os << "[" << v[0] << ", " << v[1] << ", " << v[2] << "]"; return os; } std::ostream& operator << (std::ostream& os, const glm::vec4& v) { os << "[" << v[0] << ", " << v[1] << ", " << v[2] << ", " << v[3] << "]"; return os; } glm::vec3 ParseVec3(const std::string& str) { double x, y, z; std::stringstream ss(str); ss >> x >> y >> z; return glm::vec3(x, y, z); } bool Program::InitializeGraphics() { std::cout << "GL_VERSION : " << glGetString(GL_VERSION) << std::endl; std::cout << "GL_SHADING_LANGUAGE_VERSION : " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; std::cout << "GL_RENDERER : " << glGetString(GL_RENDERER) << std::endl; std::cout << "GL_VENDOR : " << glGetString(GL_VENDOR) << std::endl; glClearColor(0.0f, 0.0f, 0.0f, 1.0f); this->_cam.MoveForward(-120.0f); if (this->_sys->GetArgs().size() > 1) { std::string filename = this->_sys->GetArgs()[1]; this->_asset = new Hl1BspAsset(FileSystem::LocateDataFile, FileSystem::LoadFileData); if (this->_asset != nullptr && this->_asset->Load(filename)) { this->_instance = (Hl1BspInstance*)this->_asset->CreateInstance(); auto mdlAsset = new Hl1MdlAsset(FileSystem::LocateDataFile, FileSystem::LoadFileData); mdlAsset->Load("..\\king-of-the-bombspot\\data\\sas.mdl"); for (auto itr = this->_asset->_entities.begin(); itr != _asset->_entities.end(); ++itr) { HL1::tBSPEntity& entity = *itr; if (entity.classname == "info_player_start" && entity.keyvalues.find("origin") != entity.keyvalues.end()) { std::string origin = entity.keyvalues.at("origin"); auto obj = new Object(); obj->_instance = mdlAsset->CreateInstance(); ((Hl1MdlInstance*)obj->_instance)->SetSequence(9, true); obj->_position = ParseVec3(origin); this->_objects.push_back(obj); } } edges.Allocate(this->_asset->_edgeData.count); for (int f = 0; f < this->_asset->_faceData.count; f++) { HL1::tBSPFace& face = this->_asset->_faceData[f]; for (int e = 0; e < face.edgeCount; e++) { int ei = this->_asset->_surfedgeData[face.firstEdge + e]; edges[ei < 0 ? -ei : ei].index = ei < 0 ? -ei : ei; edges[ei < 0 ? -ei : ei].neighbours.insert(f); edges[ei < 0 ? -ei : ei].cornerIndices.push_back(_asset->_edgeData[ei < 0 ? -ei : ei].vertex[0]); edges[ei < 0 ? -ei : ei].cornerIndices.push_back(_asset->_edgeData[ei < 0 ? -ei : ei].vertex[1]); } } faces.Allocate(this->_asset->_faceData.count); for (int f = 0; f < this->_asset->_faceData.count; f++) { HL1::tBSPFace& face = this->_asset->_faceData[f]; for (int e = 0; e < face.edgeCount; e++) { int ei = this->_asset->_surfedgeData[face.firstEdge + e]; auto edge = edges[ei < 0 ? -ei : ei]; faces[f].index = f; faces[f].neighbours.insert(edge.neighbours.begin(), edge.neighbours.end()); faces[f].cornerIndices.push_back(_asset->_edgeData[ei < 0 ? -ei : ei].vertex[0]); faces[f].cornerIndices.push_back(_asset->_edgeData[ei < 0 ? -ei : ei].vertex[1]); } faces[f].neighbours.erase(f); } std::vector<glm::vec3> verts; for (int v = 0; v < _asset->_verticesData.count; v++) verts.push_back(_asset->_verticesData[v].point); buf = new QuickVertexBuffer(GL_LINES, verts); } } return true; } void Program::GameLoop() { static double lastTime = this->_sys->GetTime(); static double lastUpdateTime = this->_sys->GetTime(); double time = this->_sys->GetTime(); double diff = time - lastTime; double speed = double(Setting("Viewer.Camera.Speed").AsFloat()); if (this->_sys->IsKeyDown(KeyCodes::Character_A)) this->_cam.MoveLeft(diff * speed); else if (this->_sys->IsKeyDown(KeyCodes::Character_D)) this->_cam.MoveLeft(-diff * speed); if (this->_sys->IsKeyDown(KeyCodes::Character_W)) this->_cam.MoveForward(diff * speed); else if (this->_sys->IsKeyDown(KeyCodes::Character_S)) this->_cam.MoveForward(-diff * speed); lastTime = time; double updateDiff = time - lastUpdateTime; if (updateDiff > 1.0/60.0) { if (this->_instance != nullptr) this->_instance->Update(updateDiff); for (auto obj = this->_objects.begin(); obj != this->_objects.end(); ++obj) (*obj)->_instance->Update(updateDiff); lastUpdateTime = time; } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_ALPHA_TEST); // for (int i = 0; i < edges.count; i++) // { // buf->RenderSubSet(this->_proj * this->_cam.GetViewMatrix(), edges[i].cornerIndices); // } // for (int i = 0; i < faces.count; i++) // { // if (glm::dot(_asset->_va.Faces()[i].plane.normal, glm::vec3(0.0f, 0.0f, 1.0f)) < 0.7f) // continue; // if (_asset->FaceFlags(i) != 0) // continue; // if (_asset->_textures[_asset->_faces[i].texture].Name()[0] == '!') // continue; // buf->RenderSubSet(this->_proj * this->_cam.GetViewMatrix(), faces[i].cornerIndices); // } glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GEQUAL, 0.8f); if (this->_instance != nullptr) { this->_instance->Render(this->_proj, this->_cam.GetViewMatrix()); } for (auto obj = this->_objects.begin(); obj != this->_objects.end(); ++obj) (*obj)->Render(this->_proj * this->_cam.GetViewMatrix()); } bool Program::IsRunning() { const Uint8 *state = SDL_GetKeyboardState(nullptr); return !state[SDL_SCANCODE_ESCAPE]; } void Program:: Resize(int w, int h) { if (h < 1) h = 1; glViewport(0, 0, w, h); this->_proj = glm::perspective(120.0f, float(w) / float(h), 0.1f, 4000.0f); } void Program::MouseButtonDown(int button, int x, int y) { this->_pan = (button == SDL_BUTTON_LEFT); this->_lastX = x; this->_lastY = y; } void Program::MouseMove(int x, int y) { if (this->_pan) { this->_cam.RotateZ(glm::radians(float(this->_lastX-x) * 0.1f)); this->_cam.RotateX(glm::radians(float(this->_lastY-y) * 0.1f)); } this->_lastX = x; this->_lastY = y; } void Program::MouseButtonUp(int button, int x, int y) { this->_pan = false; } void Program::MouseWheel(int x, int y) { } void Program::KeyAction(int key, int action) { if (key == SDLK_SPACE && action) Setting("Viewer.PauseAnimation") = !Setting("Viewer.PauseAnimation").AsBool(); else if (key == SDLK_KP_PLUS && action) Setting("Viewer.Camera.Speed") = Setting("Viewer.Camera.Speed").AsFloat() + 5.0f; else if (key == SDLK_KP_MINUS && action) Setting("Viewer.Camera.Speed") = Setting("Viewer.Camera.Speed").AsFloat() - 5.0f; } void Program::Close() { this->_running = false; } void Program::Destroy() { Settings::Instance()->SaveToDisk("king-of-the-bombspot.settings"); } int Program::GetWindowFlags() { return SDL_WINDOW_BORDERLESS; } <|endoftext|>
<commit_before>// The libMesh Finite Element Library. // Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "libmesh/libmesh_config.h" #ifdef LIBMESH_HAVE_DTK #include "libmesh/dtk_adapter.h" #include "libmesh/dtk_evaluator.h" #include "libmesh/mesh.h" #include "libmesh/numeric_vector.h" #include "libmesh/elem.h" #include <DTK_MeshTypes.hpp> #include <Teuchos_Comm.hpp> #include <vector> namespace libMesh { DTKAdapter::DTKAdapter(Teuchos::RCP<const Teuchos::Comm<int> > in_comm, EquationSystems & in_es): comm(in_comm), es(in_es), mesh(in_es.get_mesh()), dim(mesh.mesh_dimension()) { std::set<unsigned int> semi_local_nodes; get_semi_local_nodes(semi_local_nodes); num_local_nodes = semi_local_nodes.size(); vertices.resize(num_local_nodes); Teuchos::ArrayRCP<double> coordinates(num_local_nodes * dim); // Fill in the vertices and coordinates { unsigned int i = 0; for(std::set<unsigned int>::iterator it = semi_local_nodes.begin(); it != semi_local_nodes.end(); ++it) { const Node & node = mesh.node(*it); vertices[i] = node.id(); for(unsigned int j=0; j<dim; j++) coordinates[(j*num_local_nodes) + i] = node(j); i++; } } // Currently assuming all elements are the same! DataTransferKit::DTK_ElementTopology element_topology = get_element_topology(mesh.elem(0)); unsigned int n_nodes_per_elem = mesh.elem(0)->n_nodes(); Teuchos::ArrayRCP<int> elements(mesh.n_local_elem()); Teuchos::ArrayRCP<int> connectivity(n_nodes_per_elem*mesh.n_local_elem()); // Fill in the elements and connectivity { unsigned int i = 0; MeshBase::const_element_iterator end = mesh.local_elements_end(); for(MeshBase::const_element_iterator it = mesh.local_elements_begin(); it != end; ++it) { const Elem & elem = *(*it); elements[i] = elem.id(); for(unsigned int j=0; j<n_nodes_per_elem; j++) connectivity[(j*mesh.n_local_elem())+i] = elem.node(j); i++; } } Teuchos::ArrayRCP<int> permutation_list(n_nodes_per_elem); for ( int i = 0; i < n_nodes_per_elem; ++i ) permutation_list[i] = i; /* if(libMesh::processor_id() == 1) sleep(1); std::cout<<"n_nodes_per_elem: "<<n_nodes_per_elem<<std::endl; std::cout<<"Dim: "<<dim<<std::endl; std::cerr<<"Vertices size: "<<vertices.size()<<std::endl; { std::cerr<<libMesh::processor_id()<<" Vertices: "; for(unsigned int i=0; i<vertices.size(); i++) std::cerr<<vertices[i]<<" "; std::cerr<<std::endl; } std::cerr<<"Coordinates size: "<<coordinates.size()<<std::endl; { std::cerr<<libMesh::processor_id()<<" Coordinates: "; for(unsigned int i=0; i<coordinates.size(); i++) std::cerr<<coordinates[i]<<" "; std::cerr<<std::endl; } std::cerr<<"Connectivity size: "<<connectivity.size()<<std::endl; { std::cerr<<libMesh::processor_id()<<" Connectivity: "; for(unsigned int i=0; i<connectivity.size(); i++) std::cerr<<connectivity[i]<<" "; std::cerr<<std::endl; } std::cerr<<"Permutation_List size: "<<permutation_list.size()<<std::endl; { std::cerr<<libMesh::processor_id()<<" Permutation_List: "; for(unsigned int i=0; i<permutation_list.size(); i++) std::cerr<<permutation_list[i]<<" "; std::cerr<<std::endl; } */ Teuchos::RCP<MeshContainerType> mesh_container = Teuchos::rcp( new MeshContainerType(dim, vertices, coordinates, element_topology, n_nodes_per_elem, elements, connectivity, permutation_list) ); // We only have 1 element topology in this grid so we make just one mesh block Teuchos::ArrayRCP<Teuchos::RCP<MeshContainerType> > mesh_blocks(1); mesh_blocks[0] = mesh_container; // Create the MeshManager mesh_manager = Teuchos::rcp(new DataTransferKit::MeshManager<MeshContainerType>(mesh_blocks, comm, dim) ); // Pack the coordinates into a field, this will be the positions we'll ask for other systems fields at target_coords = Teuchos::rcp(new DataTransferKit::FieldManager<MeshContainerType>(mesh_container, comm)); } DTKAdapter::RCP_Evaluator DTKAdapter::get_variable_evaluator(std::string var_name) { if(evaluators.find(var_name) == evaluators.end()) // We haven't created an evaluator for the variable yet { System * sys = find_sys(var_name); // Create the FieldEvaluator evaluators[var_name] = Teuchos::rcp(new DTKEvaluator(*sys, var_name)); } return evaluators[var_name]; } Teuchos::RCP<DataTransferKit::FieldManager<DTKAdapter::FieldContainerType> > DTKAdapter::get_values_to_fill(std::string var_name) { if(values_to_fill.find(var_name) == values_to_fill.end()) { Teuchos::ArrayRCP<double> data_space(num_local_nodes); Teuchos::RCP<FieldContainerType> field_container = Teuchos::rcp(new FieldContainerType(data_space, 1)); values_to_fill[var_name] = Teuchos::rcp(new DataTransferKit::FieldManager<FieldContainerType>(field_container, comm)); } return values_to_fill[var_name]; } void DTKAdapter::update_variable_values(std::string var_name) { System * sys = find_sys(var_name); unsigned int var_num = sys->variable_number(var_name); Teuchos::RCP<FieldContainerType> values = values_to_fill[var_name]->field(); unsigned int i=0; // Loop over the values (one for each node) and assign the value of this variable at each node for(FieldContainerType::iterator it=values->begin(); it != values->end(); ++it) { unsigned int node_num = vertices[i]; const Node & node = mesh.node(node_num); if(node.processor_id() == libMesh::processor_id()) { // The 0 is for the component... this only works for LAGRANGE! dof_id_type dof = node.dof_number(sys->number(), var_num, 0); sys->solution->set(dof, *it); } i++; } sys->solution->close(); } /** * Small helper function for finding the system containing the variable. * * Note that this implies that variable names are unique across all systems! */ System * DTKAdapter::find_sys(std::string var_name) { System * sys = NULL; // Find the system this variable is from for(unsigned int i=0; i<es.n_systems(); i++) { if(es.get_system(i).has_variable(var_name)) { sys = &es.get_system(i); break; } } libmesh_assert(sys); return sys; } DataTransferKit::DTK_ElementTopology DTKAdapter::get_element_topology(const Elem * elem) { ElemType type = elem->type(); if(type == EDGE2) return DataTransferKit::DTK_LINE_SEGMENT; else if(type == TRI3) return DataTransferKit::DTK_TRIANGLE; else if(type == QUAD4) return DataTransferKit::DTK_QUADRILATERAL; else if(type == TET4) return DataTransferKit::DTK_TETRAHEDRON; else if(type == HEX8) return DataTransferKit::DTK_HEXAHEDRON; else if(type == PYRAMID5) return DataTransferKit::DTK_PYRAMID; std::cout<<"Element type not supported by DTK!"<<std::endl; libmesh_error(); } void DTKAdapter::get_semi_local_nodes(std::set<unsigned int> & semi_local_nodes) { MeshBase::const_element_iterator end = mesh.local_elements_end(); for(MeshBase::const_element_iterator it = mesh.local_elements_begin(); it != end; ++it) { const Elem & elem = *(*it); for(unsigned int j=0; j<elem.n_nodes(); j++) semi_local_nodes.insert(elem.node(j)); } } } // namespace libMesh #endif // #ifdef LIBMESH_HAVE_DTK <commit_msg>small optimization for dtk adapter<commit_after>// The libMesh Finite Element Library. // Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "libmesh/libmesh_config.h" #ifdef LIBMESH_HAVE_DTK #include "libmesh/dtk_adapter.h" #include "libmesh/dtk_evaluator.h" #include "libmesh/mesh.h" #include "libmesh/numeric_vector.h" #include "libmesh/elem.h" #include <DTK_MeshTypes.hpp> #include <Teuchos_Comm.hpp> #include <vector> namespace libMesh { DTKAdapter::DTKAdapter(Teuchos::RCP<const Teuchos::Comm<int> > in_comm, EquationSystems & in_es): comm(in_comm), es(in_es), mesh(in_es.get_mesh()), dim(mesh.mesh_dimension()) { std::set<unsigned int> semi_local_nodes; get_semi_local_nodes(semi_local_nodes); num_local_nodes = semi_local_nodes.size(); vertices.resize(num_local_nodes); Teuchos::ArrayRCP<double> coordinates(num_local_nodes * dim); // Fill in the vertices and coordinates { unsigned int i = 0; for(std::set<unsigned int>::iterator it = semi_local_nodes.begin(); it != semi_local_nodes.end(); ++it) { const Node & node = mesh.node(*it); vertices[i] = node.id(); for(unsigned int j=0; j<dim; j++) coordinates[(j*num_local_nodes) + i] = node(j); i++; } } // Currently assuming all elements are the same! DataTransferKit::DTK_ElementTopology element_topology = get_element_topology(mesh.elem(0)); unsigned int n_nodes_per_elem = mesh.elem(0)->n_nodes(); unsigned int n_local_elem = mesh.n_local_elem(); Teuchos::ArrayRCP<int> elements(n_local_elem); Teuchos::ArrayRCP<int> connectivity(n_nodes_per_elem*n_local_elem); // Fill in the elements and connectivity { unsigned int i = 0; MeshBase::const_element_iterator end = mesh.local_elements_end(); for(MeshBase::const_element_iterator it = mesh.local_elements_begin(); it != end; ++it) { const Elem & elem = *(*it); elements[i] = elem.id(); for(unsigned int j=0; j<n_nodes_per_elem; j++) connectivity[(j*n_local_elem)+i] = elem.node(j); i++; } } Teuchos::ArrayRCP<int> permutation_list(n_nodes_per_elem); for ( int i = 0; i < n_nodes_per_elem; ++i ) permutation_list[i] = i; /* if(libMesh::processor_id() == 1) sleep(1); std::cout<<"n_nodes_per_elem: "<<n_nodes_per_elem<<std::endl; std::cout<<"Dim: "<<dim<<std::endl; std::cerr<<"Vertices size: "<<vertices.size()<<std::endl; { std::cerr<<libMesh::processor_id()<<" Vertices: "; for(unsigned int i=0; i<vertices.size(); i++) std::cerr<<vertices[i]<<" "; std::cerr<<std::endl; } std::cerr<<"Coordinates size: "<<coordinates.size()<<std::endl; { std::cerr<<libMesh::processor_id()<<" Coordinates: "; for(unsigned int i=0; i<coordinates.size(); i++) std::cerr<<coordinates[i]<<" "; std::cerr<<std::endl; } std::cerr<<"Connectivity size: "<<connectivity.size()<<std::endl; { std::cerr<<libMesh::processor_id()<<" Connectivity: "; for(unsigned int i=0; i<connectivity.size(); i++) std::cerr<<connectivity[i]<<" "; std::cerr<<std::endl; } std::cerr<<"Permutation_List size: "<<permutation_list.size()<<std::endl; { std::cerr<<libMesh::processor_id()<<" Permutation_List: "; for(unsigned int i=0; i<permutation_list.size(); i++) std::cerr<<permutation_list[i]<<" "; std::cerr<<std::endl; } */ Teuchos::RCP<MeshContainerType> mesh_container = Teuchos::rcp( new MeshContainerType(dim, vertices, coordinates, element_topology, n_nodes_per_elem, elements, connectivity, permutation_list) ); // We only have 1 element topology in this grid so we make just one mesh block Teuchos::ArrayRCP<Teuchos::RCP<MeshContainerType> > mesh_blocks(1); mesh_blocks[0] = mesh_container; // Create the MeshManager mesh_manager = Teuchos::rcp(new DataTransferKit::MeshManager<MeshContainerType>(mesh_blocks, comm, dim) ); // Pack the coordinates into a field, this will be the positions we'll ask for other systems fields at target_coords = Teuchos::rcp(new DataTransferKit::FieldManager<MeshContainerType>(mesh_container, comm)); } DTKAdapter::RCP_Evaluator DTKAdapter::get_variable_evaluator(std::string var_name) { if(evaluators.find(var_name) == evaluators.end()) // We haven't created an evaluator for the variable yet { System * sys = find_sys(var_name); // Create the FieldEvaluator evaluators[var_name] = Teuchos::rcp(new DTKEvaluator(*sys, var_name)); } return evaluators[var_name]; } Teuchos::RCP<DataTransferKit::FieldManager<DTKAdapter::FieldContainerType> > DTKAdapter::get_values_to_fill(std::string var_name) { if(values_to_fill.find(var_name) == values_to_fill.end()) { Teuchos::ArrayRCP<double> data_space(num_local_nodes); Teuchos::RCP<FieldContainerType> field_container = Teuchos::rcp(new FieldContainerType(data_space, 1)); values_to_fill[var_name] = Teuchos::rcp(new DataTransferKit::FieldManager<FieldContainerType>(field_container, comm)); } return values_to_fill[var_name]; } void DTKAdapter::update_variable_values(std::string var_name) { System * sys = find_sys(var_name); unsigned int var_num = sys->variable_number(var_name); Teuchos::RCP<FieldContainerType> values = values_to_fill[var_name]->field(); unsigned int i=0; // Loop over the values (one for each node) and assign the value of this variable at each node for(FieldContainerType::iterator it=values->begin(); it != values->end(); ++it) { unsigned int node_num = vertices[i]; const Node & node = mesh.node(node_num); if(node.processor_id() == libMesh::processor_id()) { // The 0 is for the component... this only works for LAGRANGE! dof_id_type dof = node.dof_number(sys->number(), var_num, 0); sys->solution->set(dof, *it); } i++; } sys->solution->close(); } /** * Small helper function for finding the system containing the variable. * * Note that this implies that variable names are unique across all systems! */ System * DTKAdapter::find_sys(std::string var_name) { System * sys = NULL; // Find the system this variable is from for(unsigned int i=0; i<es.n_systems(); i++) { if(es.get_system(i).has_variable(var_name)) { sys = &es.get_system(i); break; } } libmesh_assert(sys); return sys; } DataTransferKit::DTK_ElementTopology DTKAdapter::get_element_topology(const Elem * elem) { ElemType type = elem->type(); if(type == EDGE2) return DataTransferKit::DTK_LINE_SEGMENT; else if(type == TRI3) return DataTransferKit::DTK_TRIANGLE; else if(type == QUAD4) return DataTransferKit::DTK_QUADRILATERAL; else if(type == TET4) return DataTransferKit::DTK_TETRAHEDRON; else if(type == HEX8) return DataTransferKit::DTK_HEXAHEDRON; else if(type == PYRAMID5) return DataTransferKit::DTK_PYRAMID; libMesh::err<<"Element type not supported by DTK!"<<std::endl; libmesh_error(); } void DTKAdapter::get_semi_local_nodes(std::set<unsigned int> & semi_local_nodes) { MeshBase::const_element_iterator end = mesh.local_elements_end(); for(MeshBase::const_element_iterator it = mesh.local_elements_begin(); it != end; ++it) { const Elem & elem = *(*it); for(unsigned int j=0; j<elem.n_nodes(); j++) semi_local_nodes.insert(elem.node(j)); } } } // namespace libMesh #endif // #ifdef LIBMESH_HAVE_DTK <|endoftext|>
<commit_before>// The libMesh Finite Element Library. // Copyright (C) 2002-2022 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "libmesh/petsc_auto_fieldsplit.h" #ifdef LIBMESH_HAVE_PETSC #include <petscksp.h> // Local includes #include "libmesh/dof_map.h" #include "libmesh/system.h" namespace { using namespace libMesh; void indices_to_fieldsplit (const Parallel::Communicator & comm, const std::vector<dof_id_type> & indices, PC my_pc, const std::string & field_name) { const PetscInt * idx = PETSC_NULL; if (!indices.empty()) idx = reinterpret_cast<const PetscInt *>(indices.data()); IS is; int ierr = ISCreateGeneral(comm.get(), cast_int<PetscInt>(indices.size()), idx, PETSC_COPY_VALUES, &is); CHKERRABORT(comm.get(), ierr); ierr = PCFieldSplitSetIS(my_pc, field_name.c_str(), is); CHKERRABORT(comm.get(), ierr); } } namespace libMesh { void petsc_auto_fieldsplit (PC my_pc, const System & sys) { std::string sys_prefix = "--solver_group_"; if (libMesh::on_command_line("--solver-system-names")) { sys_prefix = sys_prefix + sys.name() + "_"; } std::map<std::string, std::vector<dof_id_type>> group_indices; if (libMesh::on_command_line("--solver-variable-names")) { for (auto v : make_range(sys.n_vars())) { const std::string & var_name = sys.variable_name(v); std::vector<dof_id_type> var_idx; sys.get_dof_map().local_variable_indices (var_idx, sys.get_mesh(), v); std::string group_command = sys_prefix + var_name; const std::string empty_string; std::string group_name = libMesh::command_line_value (group_command, empty_string); if (group_name != empty_string) { std::vector<dof_id_type> & indices = group_indices[group_name]; const bool prior_indices = !indices.empty(); indices.insert(indices.end(), var_idx.begin(), var_idx.end()); if (prior_indices) std::sort(indices.begin(), indices.end()); } else { indices_to_fieldsplit (sys.comm(), var_idx, my_pc, var_name); } } } for (const auto & pr : group_indices) indices_to_fieldsplit(sys.comm(), pr.second, my_pc, pr.first); } } // namespace libMesh #endif // #ifdef LIBMESH_HAVE_PETSC <commit_msg>Structured bindings in petsc_auto_fieldsplit.C<commit_after>// The libMesh Finite Element Library. // Copyright (C) 2002-2022 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "libmesh/petsc_auto_fieldsplit.h" #ifdef LIBMESH_HAVE_PETSC #include <petscksp.h> // Local includes #include "libmesh/dof_map.h" #include "libmesh/system.h" namespace { using namespace libMesh; void indices_to_fieldsplit (const Parallel::Communicator & comm, const std::vector<dof_id_type> & indices, PC my_pc, const std::string & field_name) { const PetscInt * idx = PETSC_NULL; if (!indices.empty()) idx = reinterpret_cast<const PetscInt *>(indices.data()); IS is; int ierr = ISCreateGeneral(comm.get(), cast_int<PetscInt>(indices.size()), idx, PETSC_COPY_VALUES, &is); CHKERRABORT(comm.get(), ierr); ierr = PCFieldSplitSetIS(my_pc, field_name.c_str(), is); CHKERRABORT(comm.get(), ierr); } } namespace libMesh { void petsc_auto_fieldsplit (PC my_pc, const System & sys) { std::string sys_prefix = "--solver_group_"; if (libMesh::on_command_line("--solver-system-names")) { sys_prefix = sys_prefix + sys.name() + "_"; } std::map<std::string, std::vector<dof_id_type>> group_indices; if (libMesh::on_command_line("--solver-variable-names")) { for (auto v : make_range(sys.n_vars())) { const std::string & var_name = sys.variable_name(v); std::vector<dof_id_type> var_idx; sys.get_dof_map().local_variable_indices (var_idx, sys.get_mesh(), v); std::string group_command = sys_prefix + var_name; const std::string empty_string; std::string group_name = libMesh::command_line_value (group_command, empty_string); if (group_name != empty_string) { std::vector<dof_id_type> & indices = group_indices[group_name]; const bool prior_indices = !indices.empty(); indices.insert(indices.end(), var_idx.begin(), var_idx.end()); if (prior_indices) std::sort(indices.begin(), indices.end()); } else { indices_to_fieldsplit (sys.comm(), var_idx, my_pc, var_name); } } } for (const auto & [field_name, indices] : group_indices) indices_to_fieldsplit(sys.comm(), indices, my_pc, field_name); } } // namespace libMesh #endif // #ifdef LIBMESH_HAVE_PETSC <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QIcon> #include <QDebug> #include <QMessageBox> #include <QFileInfo> #include <QFileDialog> #include <QTextStream> #define MESSAGE_DISPLAY_LENGTH 4000 MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setWindowIcon(QIcon(":/imgs/money_management.gif")); setWindowTitle("Money Management"); setFixedSize(width(), height()); ui->dateEdit->setDate(QDate::currentDate()); ui->comboBoxMode->addItem("Deposit"); ui->comboBoxMode->addItem("Withdraw"); ui->comboBoxMode->setCurrentIndex(-1); ui->lineEditDepWithdr->setValidator(new QDoubleValidator(1, 10000000, 2, ui->lineEditDepWithdr)); db_path = QDir::currentPath() + "/transaction_db.db"; qDebug() << "DB Path: " << db_path; setup_database(); open_database(); QSqlQuery qry = transaction_db.exec("SELECT balance FROM transactions ORDER BY id DESC LIMIT 1;"); qDebug() << "Initial Setup Query Last Balance Status: " << qry.lastError(); if(qry.next()){ qDebug() << "Initially setting total label to: " << format.toCurrencyString(qry.value(0).toDouble()); ui->labelTotal->setText("Total: " + format.toCurrencyString(qry.value(0).toDouble())); }else{ qDebug() << "Initially setting total label to: " << format.toCurrencyString(0.00); ui->labelTotal->setText("Total: " + format.toCurrencyString(0.00)); } close_database(); } MainWindow::~MainWindow() { // QDir d; // d.remove(db_path); delete ui; } void MainWindow::setup_database(){ transaction_db = QSqlDatabase::addDatabase("QSQLITE"); transaction_db.setDatabaseName(db_path); QFileInfo db_info(db_path); bool exists = db_info.exists(); bool status = transaction_db.open(); qDebug() << "DB Exists: " << exists; qDebug() << "DB Opened Successfully: " << status; if(!status){ qDebug() << "Error connecting to database (setup_database)"; ui->statusBar->showMessage("Error connecting to database", MESSAGE_DISPLAY_LENGTH); QMessageBox::critical(this, "Error Connecting To Database", "Error opening database, please restart the program"); ui->lineEditDepWithdr->setEnabled(false); ui->lineEditDescription->setEnabled(false); ui->pushButtonSubmit->setEnabled(false); ui->comboBoxMode->setEnabled(false); ui->dateEdit->setEnabled(false); ui->menuBar->setEnabled(false); return; } ui->statusBar->showMessage("Connected...", MESSAGE_DISPLAY_LENGTH); if(!exists){ qDebug() << "Creating transaction table"; QSqlQuery create_transaction_table_qry = transaction_db.exec("CREATE TABLE transactions(id INTEGER PRIMARY KEY AUTOINCREMENT, description TEXT, mode TEXT, trans_amount DOUBLE, balance DOUBLE, date_added DATE);"); qDebug() << "Create Trans Table Status: " << create_transaction_table_qry.lastError(); } close_database(); } bool MainWindow::open_database(){ bool status = transaction_db.open(); if(status){ ui->statusBar->showMessage("Connected...", MESSAGE_DISPLAY_LENGTH); }else{ qDebug() << "Error opening database"; ui->statusBar->showMessage("Error connecting to database", MESSAGE_DISPLAY_LENGTH); QMessageBox::critical(this, "Error Connecting To Database", "Error opening database, please restart the program"); ui->lineEditDepWithdr->setEnabled(false); ui->lineEditDescription->setEnabled(false); ui->pushButtonSubmit->setEnabled(false); ui->comboBoxMode->setEnabled(false); ui->dateEdit->setEnabled(false); ui->menuBar->setEnabled(false); } return status; } void MainWindow::close_database(){ // bool status = transaction_db.commit(); // qDebug() << "Closing database: " << status; transaction_db.close(); } void MainWindow::on_actionAbout_triggered() { } void MainWindow::on_pushButtonSubmit_clicked() { if(!open_database()){ QMessageBox::critical(this, "Error Saving Transaction", "Error saving the transaction, please try again"); qDebug() << "Error connecting to database (submit button)\n Transaction not saved"; return; } QString description = ui->lineEditDescription->text(); QString mode = ui->comboBoxMode->currentText(); double amount = ui->lineEditDepWithdr->text().toDouble(); if(amount == 0 || description == "" || mode == ""){ QMessageBox::critical(this, "Invalid Input", "Please provide a description, amount and if this transaction is a deposit or withdrawal."); qDebug() << "Invalid Input\nAmount: " << amount << " Description: " << description << " Mode: " << mode; return; } QSqlQuery last_trans = transaction_db.exec("SELECT balance FROM transactions ORDER BY id DESC LIMIT 1;"); qDebug() << "Get last balance qry psh btn submit clicked status: " << last_trans.lastError(); double last_balance = 0; if(last_trans.next()){ qDebug() << "Checking last known balance (this should print once)"; last_balance = last_trans.value(0).toDouble(); } qDebug() << "last known balance (submit btn pressed): " << last_balance; if(mode == "Deposit"){ qDebug() << "Depositing " << amount << " to " << last_balance; last_balance += amount; ui->labelTotal->setText("Total: " + format.toCurrencyString(last_balance)); }else if(mode == "Withdraw"){ qDebug() << "Withdrawing " << amount << " from " << last_balance; if(last_balance - amount < 0){ qDebug() << "Can't withdraw " << amount << " from " << last_balance; QMessageBox::information(this, "Insufficient Funds", "There is not enough money to withdraw " + format.toCurrencyString(amount)); return; } last_balance -= amount; ui->labelTotal->setText("Total: " + format.toCurrencyString(last_balance)); } QSqlQuery add_transaction_qry; add_transaction_qry.prepare("INSERT INTO transactions (description, mode, trans_amount, balance, date_added) VALUES (:desc, :mode, :trans_amount, :balance, :date);"); add_transaction_qry.bindValue(":desc", description); add_transaction_qry.bindValue(":mode", mode); add_transaction_qry.bindValue(":trans_amount", amount); add_transaction_qry.bindValue(":balance", last_balance); add_transaction_qry.bindValue(":date", ui->dateEdit->date()); bool result = add_transaction_qry.exec(); qDebug() << "Add transaction status: " << add_transaction_qry.lastError(); if(result){ ui->statusBar->showMessage("Transaction saved", MESSAGE_DISPLAY_LENGTH); ui->lineEditDepWithdr->setText(""); ui->lineEditDescription->setText(""); ui->comboBoxMode->setCurrentIndex(-1); ui->pushButtonSubmit->setEnabled(false); QTimer::singleShot(1750, this, SLOT(reenable_submit_btn())); qDebug() << "Transaction saved"; }else{ ui->statusBar->showMessage("Error saving transaction", MESSAGE_DISPLAY_LENGTH); qDebug() << "Error saving transaction"; } close_database(); } void MainWindow::reenable_submit_btn(){ ui->pushButtonSubmit->setEnabled(true); } void MainWindow::on_actionQuit_triggered() { this->close(); } void MainWindow::closeEvent(QCloseEvent* event){ int result = QMessageBox::question(NULL, "Quit?", "Are you sure you want to quit?"); if(result == QMessageBox::Yes){ qDebug() << "Exiting, user selected yes"; event->accept(); }else{ qDebug() << "Not exiting, user selected no"; event->ignore(); } } void MainWindow::on_actionExport_triggered() { QString filename = QFileDialog::getSaveFileName(this, tr("Export Database"), QDir::currentPath(), tr("Sql File (*.sql)")); if(!filename.isEmpty()){ open_database(); QSqlQuery transactions_exist_qry = transaction_db.exec("SELECT count(id) FROM transactions;"); qDebug() << "Transactions exist qry status " << transactions_exist_qry.lastError(); if(transactions_exist_qry.next()){ if(transactions_exist_qry.value(0) <=0){ qDebug() << "there are no transactions to export"; QMessageBox::information(this, "No Transactions Exist", "There are no transactions to export, export cancelled"); return; } }else{ qDebug() << "there are no transactions to export"; QMessageBox::information(this, "No Transactions Exist", "There are no transactions to export, export cancelled"); return; } qDebug() << "transactions exist, go ahead and export"; QSqlQuery get_all_transactions_qry = transaction_db.exec("SELECT id, description, mode, trans_amount, balance, date_added FROM transactions;"); qDebug() << "Get all transactions for export status: " << get_all_transactions_qry.lastError(); int count = 0; QFile export_file(filename); if(!export_file.open(QFile::WriteOnly)){ QMessageBox::information(this, "Error Opening File", "Error opening " + filename + " for export, please try again"); return; } export_file.write("PRAGMA foreign_keys=OFF;\n"); export_file.write("BEGIN TRANSACTION;\n"); export_file.write("CREATE TABLE transactions(id INTEGER PRIMARY KEY AUTOINCREMENT, description TEXT, mode TEXT, trans_amount DOUBLE, balance DOUBLE, date_added DATE);\n"); //need to add error checking for 0 transactions. while(get_all_transactions_qry.next()){ QString write_str = "INSERT INTO transactions (id, description, mode, trans_amount, balance, date_added) VALUES (" + get_all_transactions_qry.value(0).toString() + ", '" + get_all_transactions_qry.value(1).toString() + "', '" + get_all_transactions_qry.value(2).toString() + "', " + get_all_transactions_qry.value(3).toString() + ", " + get_all_transactions_qry.value(4).toString() + ", '" + get_all_transactions_qry.value(5).toString() + "');\n"; qDebug() << "Writing " << write_str; export_file.write(write_str.toUtf8()); count++; } export_file.write("COMMIT;"); QMessageBox::information(this, "Success", QString::number(count) + " transactions exported to " + filename); qDebug() << count << " transactions written to " << filename; export_file.flush(); export_file.close(); close_database(); } } void MainWindow::on_actionImport_triggered() { QString filename = QFileDialog::getOpenFileName(this, tr("Import Database"), QDir::currentPath(), tr("Sql File (*.sql)")); if(!filename.isEmpty()){ //@TODO -- auto backup the datbase? -- create backups folder... int choice = QMessageBox::question(this, "Overwrite existing data?", "This action will overwrite any existing data, are you sure you want to continue?"); if(choice == QMessageBox::Yes){ open_database(); QSqlQuery drop_table_qry = transaction_db.exec("DROP TABLE transactions;"); qDebug() << "drop table qry result: " << drop_table_qry.lastError(); QFile import_file(filename); if(!import_file.open(QFile::ReadOnly)){ QMessageBox::information(this, "Error Opening File", "Error opening " + filename + " for import, please try again"); return; } QTextStream in(&import_file); QStringList errors; while(!in.atEnd()){ QString statement = in.readLine(); QSqlQuery qry = transaction_db.exec(statement); if(qry.lastError().text() != " "){ errors.push_back("Error: " + qry.lastError().text() + "\nStatement: " + statement); qDebug() << "Error: " << qry.lastError() << "\nStatement: " << statement; } } if(errors.empty()){ QMessageBox::information(this, "Success", "All data successfully imported"); }else{ QMessageBox::warning(this, QString::number(errors.size()) + " Error(s)", "Encountered " + QString::number(errors.size()) + " errors(s)"); } import_file.close(); close_database(); } } } void MainWindow::on_actionDelete_triggered() { int choice = QMessageBox::question(this, "Are you sure?", "Are you sure you want to delete the entire database? This cannot be undone"); if(choice == QMessageBox::Yes){ open_database(); QSqlQuery remove_all_records_qry = transaction_db.exec("DELETE FROM transactions;"); qDebug() << "drop table qry result: " << remove_all_records_qry.lastError(); close_database(); if(remove_all_records_qry.lastError().text() == " "){ ui->statusBar->showMessage("Database successfully deleted", MESSAGE_DISPLAY_LENGTH); }else{ ui->statusBar->showMessage("Error deleting database", MESSAGE_DISPLAY_LENGTH); } } } <commit_msg>when importing data, update the total label<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QIcon> #include <QDebug> #include <QMessageBox> #include <QFileInfo> #include <QFileDialog> #include <QTextStream> #define MESSAGE_DISPLAY_LENGTH 4000 MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setWindowIcon(QIcon(":/imgs/money_management.gif")); setWindowTitle("Money Management"); setFixedSize(width(), height()); ui->dateEdit->setDate(QDate::currentDate()); ui->comboBoxMode->addItem("Deposit"); ui->comboBoxMode->addItem("Withdraw"); ui->comboBoxMode->setCurrentIndex(-1); ui->lineEditDepWithdr->setValidator(new QDoubleValidator(1, 10000000, 2, ui->lineEditDepWithdr)); db_path = QDir::currentPath() + "/transaction_db.db"; qDebug() << "DB Path: " << db_path; setup_database(); open_database(); QSqlQuery qry = transaction_db.exec("SELECT balance FROM transactions ORDER BY id DESC LIMIT 1;"); qDebug() << "Initial Setup Query Last Balance Status: " << qry.lastError(); if(qry.next()){ qDebug() << "Initially setting total label to: " << format.toCurrencyString(qry.value(0).toDouble()); ui->labelTotal->setText("Total: " + format.toCurrencyString(qry.value(0).toDouble())); }else{ qDebug() << "Initially setting total label to: " << format.toCurrencyString(0.00); ui->labelTotal->setText("Total: " + format.toCurrencyString(0.00)); } close_database(); } MainWindow::~MainWindow() { // QDir d; // d.remove(db_path); delete ui; } void MainWindow::setup_database(){ transaction_db = QSqlDatabase::addDatabase("QSQLITE"); transaction_db.setDatabaseName(db_path); QFileInfo db_info(db_path); bool exists = db_info.exists(); bool status = transaction_db.open(); qDebug() << "DB Exists: " << exists; qDebug() << "DB Opened Successfully: " << status; if(!status){ qDebug() << "Error connecting to database (setup_database)"; ui->statusBar->showMessage("Error connecting to database", MESSAGE_DISPLAY_LENGTH); QMessageBox::critical(this, "Error Connecting To Database", "Error opening database, please restart the program"); ui->lineEditDepWithdr->setEnabled(false); ui->lineEditDescription->setEnabled(false); ui->pushButtonSubmit->setEnabled(false); ui->comboBoxMode->setEnabled(false); ui->dateEdit->setEnabled(false); ui->menuBar->setEnabled(false); return; } ui->statusBar->showMessage("Connected...", MESSAGE_DISPLAY_LENGTH); if(!exists){ qDebug() << "Creating transaction table"; QSqlQuery create_transaction_table_qry = transaction_db.exec("CREATE TABLE transactions(id INTEGER PRIMARY KEY AUTOINCREMENT, description TEXT, mode TEXT, trans_amount DOUBLE, balance DOUBLE, date_added DATE);"); qDebug() << "Create Trans Table Status: " << create_transaction_table_qry.lastError(); } close_database(); } bool MainWindow::open_database(){ bool status = transaction_db.open(); if(status){ ui->statusBar->showMessage("Connected...", MESSAGE_DISPLAY_LENGTH); }else{ qDebug() << "Error opening database"; ui->statusBar->showMessage("Error connecting to database", MESSAGE_DISPLAY_LENGTH); QMessageBox::critical(this, "Error Connecting To Database", "Error opening database, please restart the program"); ui->lineEditDepWithdr->setEnabled(false); ui->lineEditDescription->setEnabled(false); ui->pushButtonSubmit->setEnabled(false); ui->comboBoxMode->setEnabled(false); ui->dateEdit->setEnabled(false); ui->menuBar->setEnabled(false); } return status; } void MainWindow::close_database(){ // bool status = transaction_db.commit(); // qDebug() << "Closing database: " << status; transaction_db.close(); } void MainWindow::on_actionAbout_triggered() { } void MainWindow::on_pushButtonSubmit_clicked() { if(!open_database()){ QMessageBox::critical(this, "Error Saving Transaction", "Error saving the transaction, please try again"); qDebug() << "Error connecting to database (submit button)\n Transaction not saved"; return; } QString description = ui->lineEditDescription->text(); QString mode = ui->comboBoxMode->currentText(); double amount = ui->lineEditDepWithdr->text().toDouble(); if(amount == 0 || description == "" || mode == ""){ QMessageBox::critical(this, "Invalid Input", "Please provide a description, amount and if this transaction is a deposit or withdrawal."); qDebug() << "Invalid Input\nAmount: " << amount << " Description: " << description << " Mode: " << mode; return; } QSqlQuery last_trans = transaction_db.exec("SELECT balance FROM transactions ORDER BY id DESC LIMIT 1;"); qDebug() << "Get last balance qry psh btn submit clicked status: " << last_trans.lastError(); double last_balance = 0; if(last_trans.next()){ qDebug() << "Checking last known balance (this should print once)"; last_balance = last_trans.value(0).toDouble(); } qDebug() << "last known balance (submit btn pressed): " << last_balance; if(mode == "Deposit"){ qDebug() << "Depositing " << amount << " to " << last_balance; last_balance += amount; ui->labelTotal->setText("Total: " + format.toCurrencyString(last_balance)); }else if(mode == "Withdraw"){ qDebug() << "Withdrawing " << amount << " from " << last_balance; if(last_balance - amount < 0){ qDebug() << "Can't withdraw " << amount << " from " << last_balance; QMessageBox::information(this, "Insufficient Funds", "There is not enough money to withdraw " + format.toCurrencyString(amount)); return; } last_balance -= amount; ui->labelTotal->setText("Total: " + format.toCurrencyString(last_balance)); } QSqlQuery add_transaction_qry; add_transaction_qry.prepare("INSERT INTO transactions (description, mode, trans_amount, balance, date_added) VALUES (:desc, :mode, :trans_amount, :balance, :date);"); add_transaction_qry.bindValue(":desc", description); add_transaction_qry.bindValue(":mode", mode); add_transaction_qry.bindValue(":trans_amount", amount); add_transaction_qry.bindValue(":balance", last_balance); add_transaction_qry.bindValue(":date", ui->dateEdit->date()); bool result = add_transaction_qry.exec(); qDebug() << "Add transaction status: " << add_transaction_qry.lastError(); if(result){ ui->statusBar->showMessage("Transaction saved", MESSAGE_DISPLAY_LENGTH); ui->lineEditDepWithdr->setText(""); ui->lineEditDescription->setText(""); ui->comboBoxMode->setCurrentIndex(-1); ui->pushButtonSubmit->setEnabled(false); QTimer::singleShot(1750, this, SLOT(reenable_submit_btn())); qDebug() << "Transaction saved"; }else{ ui->statusBar->showMessage("Error saving transaction", MESSAGE_DISPLAY_LENGTH); qDebug() << "Error saving transaction"; } close_database(); } void MainWindow::reenable_submit_btn(){ ui->pushButtonSubmit->setEnabled(true); } void MainWindow::on_actionQuit_triggered() { this->close(); } void MainWindow::closeEvent(QCloseEvent* event){ int result = QMessageBox::question(NULL, "Quit?", "Are you sure you want to quit?"); if(result == QMessageBox::Yes){ qDebug() << "Exiting, user selected yes"; event->accept(); }else{ qDebug() << "Not exiting, user selected no"; event->ignore(); } } void MainWindow::on_actionExport_triggered() { QString filename = QFileDialog::getSaveFileName(this, tr("Export Database"), QDir::currentPath(), tr("Sql File (*.sql)")); if(!filename.isEmpty()){ open_database(); QSqlQuery transactions_exist_qry = transaction_db.exec("SELECT count(id) FROM transactions;"); qDebug() << "Transactions exist qry status " << transactions_exist_qry.lastError(); if(transactions_exist_qry.next()){ if(transactions_exist_qry.value(0) <=0){ qDebug() << "there are no transactions to export"; QMessageBox::information(this, "No Transactions Exist", "There are no transactions to export, export cancelled"); return; } }else{ qDebug() << "there are no transactions to export"; QMessageBox::information(this, "No Transactions Exist", "There are no transactions to export, export cancelled"); return; } qDebug() << "transactions exist, go ahead and export"; QSqlQuery get_all_transactions_qry = transaction_db.exec("SELECT id, description, mode, trans_amount, balance, date_added FROM transactions;"); qDebug() << "Get all transactions for export status: " << get_all_transactions_qry.lastError(); int count = 0; QFile export_file(filename); if(!export_file.open(QFile::WriteOnly)){ QMessageBox::information(this, "Error Opening File", "Error opening " + filename + " for export, please try again"); return; } export_file.write("PRAGMA foreign_keys=OFF;\n"); export_file.write("BEGIN TRANSACTION;\n"); export_file.write("CREATE TABLE transactions(id INTEGER PRIMARY KEY AUTOINCREMENT, description TEXT, mode TEXT, trans_amount DOUBLE, balance DOUBLE, date_added DATE);\n"); //need to add error checking for 0 transactions. while(get_all_transactions_qry.next()){ QString write_str = "INSERT INTO transactions (id, description, mode, trans_amount, balance, date_added) VALUES (" + get_all_transactions_qry.value(0).toString() + ", '" + get_all_transactions_qry.value(1).toString() + "', '" + get_all_transactions_qry.value(2).toString() + "', " + get_all_transactions_qry.value(3).toString() + ", " + get_all_transactions_qry.value(4).toString() + ", '" + get_all_transactions_qry.value(5).toString() + "');\n"; qDebug() << "Writing " << write_str; export_file.write(write_str.toUtf8()); count++; } export_file.write("COMMIT;"); QMessageBox::information(this, "Success", QString::number(count) + " transactions exported to " + filename); qDebug() << count << " transactions written to " << filename; export_file.flush(); export_file.close(); close_database(); } } void MainWindow::on_actionImport_triggered() { QString filename = QFileDialog::getOpenFileName(this, tr("Import Database"), QDir::currentPath(), tr("Sql File (*.sql)")); if(!filename.isEmpty()){ //@TODO -- auto backup the datbase? -- create backups folder... int choice = QMessageBox::question(this, "Overwrite existing data?", "This action will overwrite any existing data, are you sure you want to continue?"); if(choice == QMessageBox::Yes){ open_database(); QSqlQuery drop_table_qry = transaction_db.exec("DROP TABLE transactions;"); qDebug() << "drop table qry result: " << drop_table_qry.lastError(); QFile import_file(filename); if(!import_file.open(QFile::ReadOnly)){ QMessageBox::information(this, "Error Opening File", "Error opening " + filename + " for import, please try again"); return; } QTextStream in(&import_file); QStringList errors; while(!in.atEnd()){ QString statement = in.readLine(); QSqlQuery qry = transaction_db.exec(statement); if(qry.lastError().text() != " "){ errors.push_back("Error: " + qry.lastError().text() + "\nStatement: " + statement); qDebug() << "Error: " << qry.lastError() << "\nStatement: " << statement; } } if(errors.empty()){ QMessageBox::information(this, "Success", "All data successfully imported"); QSqlQuery qry = transaction_db.exec("SELECT balance FROM transactions ORDER BY id DESC LIMIT 1;"); if(qry.next()){ ui->labelTotal->setText("Total: " + format.toCurrencyString(qry.value(0).toDouble())); }else{ ui->labelTotal->setText("Total: " + format.toCurrencyString(0.00)); } }else{ QMessageBox::warning(this, QString::number(errors.size()) + " Error(s)", "Encountered " + QString::number(errors.size()) + " errors(s)"); } import_file.close(); close_database(); } } } void MainWindow::on_actionDelete_triggered() { int choice = QMessageBox::question(this, "Are you sure?", "Are you sure you want to delete the entire database? This cannot be undone"); if(choice == QMessageBox::Yes){ open_database(); QSqlQuery remove_all_records_qry = transaction_db.exec("DELETE FROM transactions;"); qDebug() << "drop table qry result: " << remove_all_records_qry.lastError(); close_database(); if(remove_all_records_qry.lastError().text() == " "){ ui->statusBar->showMessage("Database successfully deleted", MESSAGE_DISPLAY_LENGTH); }else{ ui->statusBar->showMessage("Error deleting database", MESSAGE_DISPLAY_LENGTH); } } } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include "model.h" #include <fstream> #include <QFileDialog> #include <QMessageBox> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), modelWidget(nullptr) { ui->setupUi(this); setModelWidget(new Ui::ModelWidget()); ui->actionUndo->setEnabled(modelWidget->canUndo()); connect(modelWidget, &Ui::ModelWidget::canUndoChanged, [this]() { ui->actionUndo->setEnabled(modelWidget->canUndo()); }); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_actionNew_triggered() { setModelWidget(new Ui::ModelWidget()); } void MainWindow::setModelWidget(Ui::ModelWidget *newWidget) { if (this->modelWidget) { ui->wrapperFrame->layout()->removeWidget(this->modelWidget); delete this->modelWidget; } this->modelWidget = newWidget; ui->wrapperFrame->layout()->addWidget(this->modelWidget); ui->actionSaveAs->setEnabled(true); } void MainWindow::on_actionOpen_triggered() { QString filename = QFileDialog::getOpenFileName( this, "Select file with a model", QDir::currentPath(), "Models (*.model)" ); if (filename == "") { return; } std::unique_ptr<Ui::ModelWidget> modelWidget(new Ui::ModelWidget()); std::ifstream file(filename.toStdString()); try { Model model; file >> model; modelWidget->setModel(std::move(model)); } catch (model_format_error &e) { QMessageBox::critical(this, "Error while opening model", e.what()); return; } setModelWidget(modelWidget.release()); } void MainWindow::on_actionSaveAs_triggered() { QString filename = QFileDialog::getSaveFileName( this, "Select file to save in", QDir::currentPath(), "Models (*.model);;SVG (*.svg)" ); if (filename == "") { return; } Model &model = this->modelWidget->getModel(); std::ofstream file(filename.toStdString()); if (filename.toLower().endsWith(".svg")) { exportModelToSvg(model, file); } else { file << model; } } void MainWindow::on_actionUndo_triggered() { modelWidget->undo(); } <commit_msg>mainwindow: undo listener is now added in setModelWidget, now in constructor only<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include "model.h" #include <fstream> #include <QFileDialog> #include <QMessageBox> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), modelWidget(nullptr) { ui->setupUi(this); setModelWidget(new Ui::ModelWidget()); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_actionNew_triggered() { setModelWidget(new Ui::ModelWidget()); } void MainWindow::setModelWidget(Ui::ModelWidget *newWidget) { if (this->modelWidget) { ui->wrapperFrame->layout()->removeWidget(this->modelWidget); delete this->modelWidget; } this->modelWidget = newWidget; ui->wrapperFrame->layout()->addWidget(this->modelWidget); ui->actionSaveAs->setEnabled(true); ui->actionUndo->setEnabled(modelWidget->canUndo()); connect(modelWidget, &Ui::ModelWidget::canUndoChanged, [this]() { ui->actionUndo->setEnabled(modelWidget->canUndo()); }); } void MainWindow::on_actionOpen_triggered() { QString filename = QFileDialog::getOpenFileName( this, "Select file with a model", QDir::currentPath(), "Models (*.model)" ); if (filename == "") { return; } std::unique_ptr<Ui::ModelWidget> modelWidget(new Ui::ModelWidget()); std::ifstream file(filename.toStdString()); try { Model model; file >> model; modelWidget->setModel(std::move(model)); } catch (model_format_error &e) { QMessageBox::critical(this, "Error while opening model", e.what()); return; } setModelWidget(modelWidget.release()); } void MainWindow::on_actionSaveAs_triggered() { QString filename = QFileDialog::getSaveFileName( this, "Select file to save in", QDir::currentPath(), "Models (*.model);;SVG (*.svg)" ); if (filename == "") { return; } Model &model = this->modelWidget->getModel(); std::ofstream file(filename.toStdString()); if (filename.toLower().endsWith(".svg")) { exportModelToSvg(model, file); } else { file << model; } } void MainWindow::on_actionUndo_triggered() { modelWidget->undo(); } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include <CoreService.h> #include <QStandardItemModel> CoreService *cs; QStringList extension_name_list; QString filePath; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { cs = new CoreService(this); ui->folderDir->setText(cs->GetFilePathBrowse()); } void MainWindow::on_btn_ListFiles_clicked() { cs = new CoreService(this); filePath = ui->folderDir->text(); cs->FilePath(filePath); QStringList fileList = cs->list_files(); QStandardItemModel* model = new QStandardItemModel(0, 1); QString header1 = "File Names"; QStandardItem* item = new QStandardItem(header1); model->setHorizontalHeaderItem(0, item); for (int i = 0; i < fileList.length(); i++) { QStandardItem* rowItem =new QStandardItem(fileList[i]); model->insertRow(i, rowItem); } ui->tbl_FileList->setModel(model); } void MainWindow::on_btn_SortFiles_clicked() { if (!ui->folderDir->text().isEmpty()) { filePath = ui->folderDir->text(); cs->FilePath(filePath); if (ui->rdBtn_MoveByExtension->isChecked()) { cs->MoveMode = cs->CoreService::MoveByExtension; } else if (ui->rdBtn_MoveByFirstLetter->isChecked()) { cs->MoveMode = cs->CoreService::MoveByFirstLetter; } cs->sortFiles(); qDebug()<<"sortFiles()"; } else cs->ShowMessageBox("No Directory selected"); } <commit_msg>Add sort by file size function in main window<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include <CoreService.h> #include <QStandardItemModel> CoreService *cs; QStringList extension_name_list; QString filePath; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { cs = new CoreService(this); ui->folderDir->setText(cs->GetFilePathBrowse()); } void MainWindow::on_btn_ListFiles_clicked() { cs = new CoreService(this); filePath = ui->folderDir->text(); cs->FilePath(filePath); QStringList fileList = cs->list_files(); QStandardItemModel* model = new QStandardItemModel(0, 1); QString header1 = "File Names"; QStandardItem* item = new QStandardItem(header1); model->setHorizontalHeaderItem(0, item); for (int i = 0; i < fileList.length(); i++) { QStandardItem* rowItem =new QStandardItem(fileList[i]); model->insertRow(i, rowItem); } ui->tbl_FileList->setModel(model); } void MainWindow::on_btn_SortFiles_clicked() { if (!ui->folderDir->text().isEmpty()) { filePath = ui->folderDir->text(); cs->FilePath(filePath); if (ui->rdBtn_MoveByExtension->isChecked()) { cs->MoveMode = cs->CoreService::MoveByExtension; } else if (ui->rdBtn_MoveByFirstLetter->isChecked()) { cs->MoveMode = cs->CoreService::MoveByFirstLetter; } else if (ui->rdBtn_MoveByModDate->isChecked()) { } else if (ui->rdBtn_MoveByFileSize->isChecked()) { cs->MoveMode = cs->CoreService::MoveByFileSize; // cs->ShowMessageBox("hello"); } cs->sortFiles(); qDebug()<<"sortFiles()"; } else cs->ShowMessageBox("No Directory selected"); } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QLabel> #include <QPushButton> #include <QComboBox> #include <QCloseEvent> #include <QTimer> #include <QSignalMapper> #include <QGridLayout> #include <SDL_haptic.h> const int kHapticLength = 500; const int kSafeTimeout = 50; static const char __CLASS__[] = "MainWindow"; MainWindow::MainWindow(QWidget *parent) : QMainWindow{parent} , ui{new Ui::MainWindow} , eventThread{new SdlEventThread{this}} , joystick{0} , haptic{0} , hapticId{-1} , numAxis{0} , numButtons{0} , numHats{0} { ui->setupUi(this); fillJoystickList(); connect(eventThread, &SdlEventThread::joyButtonEvent, this, &MainWindow::joystickButtonPressed); connect(eventThread, &SdlEventThread::joyDeviceRemoved, this, &MainWindow::joyDeviceRemoved); connect(ui->choosePadBox, QOverload<int>::of(&QComboBox::activated), this, [this](int index){ setJoystick(index - 1); }); eventThread->start(); } MainWindow::~MainWindow() { closeJoystick(); eventThread->stop(); delete ui; } void MainWindow::closeHaptic() { stopHaptic(); if (!haptic) return; SDL_HapticClose(haptic); haptic = 0; } void MainWindow::closeJoystick() { closeHaptic(); if (!joystick) return; qDebug("%s: close joystick %d %s", __CLASS__, SDL_JoystickInstanceID(joystick), SDL_JoystickName(joystick)); disconnect(eventThread, &SdlEventThread::hatEvent, this, &MainWindow::povPressed); disconnect(eventThread, &SdlEventThread::axisEvent, this, &MainWindow::axisMoved); while (auto child = ui->buttonsLayout->takeAt(0)) { delete child; } joystick = 0; numAxis = 0; numButtons = 0; numHats = 0; which = -1; ui->xyaxis->reset(); ui->zaxis->reset(); ui->axis4->reset(); ui->axis5->reset(); ui->pov->reset(); } void MainWindow::closeEvent(QCloseEvent *event) { eventThread->stop(); event->accept(); } void MainWindow::setButtons(int num) { for (int i = 0; i<num; i++) { QPushButton *b = new QPushButton(this); b->setText(QString::number(i+1)); b->setCheckable(true); ui->buttonsLayout->addWidget(b, i / 6, i % 6); } } void MainWindow::fillJoystickList() { while (ui->choosePadBox->count() > 1) ui->choosePadBox->removeItem(1); for (int i = 0; i < SDL_NumJoysticks(); ++i) ui->choosePadBox->addItem(SDL_JoystickNameForIndex(i)); } void MainWindow::setJoystick(int index) { closeJoystick(); joystick = SDL_JoystickOpen(index); if (!joystick) return; which = SDL_JoystickInstanceID(joystick); ui->choosePadBox->setCurrentIndex(index + 1); qDebug("%s: setup joystick %d %s", __CLASS__, SDL_JoystickInstanceID(joystick), SDL_JoystickName(joystick)); numAxis = SDL_JoystickNumAxes(joystick); numButtons = SDL_JoystickNumButtons(joystick); numHats = SDL_JoystickNumHats(joystick); hat = 0; ui->pov->setEnabled(numHats > 0); setButtons(numButtons); int axisOffset = numButtons; while (axisOffset % 6) ++axisOffset; for (int i = 0; i<numAxis; i++) { QLabel *l = new QLabel(this); l->setText(QString("[%1]").arg(i)); ui->buttonsLayout->addWidget(l, (axisOffset + i) / 6, (axisOffset + i) % 6); } connect(eventThread, &SdlEventThread::axisEvent, this, &MainWindow::axisMoved); connect(eventThread, &SdlEventThread::hatEvent, this, &MainWindow::povPressed); setHaptic(SDL_HapticOpenFromJoystick(joystick)); } void MainWindow::axisMoved(SDL_JoyAxisEvent event) { if (event.which != which) return; if (event.axis >= numAxis) return; switch (event.axis) { case 0: ui->xyaxis->xaxisMoved(event); break; case 1: ui->xyaxis->yaxisMoved(event); break; case 2: ui->zaxis->xaxisMoved(event); break; case 3: ui->zaxis->yaxisMoved(event); break; case 4: ui->axis4->axisMoved(event); break; case 5: ui->axis5->axisMoved(event); break; } QLabel *l = qobject_cast<QLabel*>( ui->buttonsLayout->itemAt(numButtons + event.axis)->widget()); if (!l) return; l->setText(QString("[%1]: %2").arg(event.axis).arg(event.value)); } void MainWindow::povPressed(SDL_JoyHatEvent event) { if (event.which != which) return; if (event.hat != hat) return; ui->pov->povPressed(event); } void MainWindow::setHaptic(struct _SDL_Haptic *haptic) { this->haptic = haptic; } void MainWindow::stopHaptic() { if (!haptic) { SDL_JoystickRumble(joystick, 0, 0, 0); return; } SDL_HapticStopEffect(haptic, hapticId); SDL_HapticDestroyEffect(haptic, hapticId); hapticId = -1; } void MainWindow::joystickButtonPressed(SDL_JoyButtonEvent event) { //qDebug("%s: button %d type %x", __FUNCTION__, event.button, event.type); if (event.button >= numButtons) return; QLayoutItem *item = ui->buttonsLayout->itemAt(event.button); if (!item) { qDebug("%s: no item at %d", __FUNCTION__, event.button); return; } QPushButton *b = qobject_cast<QPushButton*>(item->widget()); if (!b) { qDebug("%s: cast failed at %d", __FUNCTION__, event.button); return; } b->setChecked(event.type == SDL_JOYBUTTONDOWN); if (!ui->testHaptic->isChecked()) return; if (b->isChecked() || hapticId >= 0) return; SDL_HapticEffect lr = {0}; lr.type = SDL_HAPTIC_LEFTRIGHT; lr.leftright.length = kHapticLength; lr.leftright.large_magnitude = (event.button & 1) ? 0x7FFF : 0; lr.leftright.small_magnitude = (event.button & 1) ? 0 : 0x7FFF; if (!haptic) { if (SDL_JoystickRumble(joystick, lr.leftright.large_magnitude, lr.leftright.small_magnitude, lr.leftright.length) < 0) qWarning("Failed to start rumble: %s\n", SDL_GetError()); return; } hapticId = SDL_HapticNewEffect(haptic, &lr); if (hapticId < 0) { qWarning("Failed to create effect: %s\n", SDL_GetError()); return; } //qDebug("[%04x; %04x] : id", lr.leftright.large_magnitude, lr.leftright.small_magnitude, hapticId); SDL_HapticRunEffect(haptic, hapticId, 1); QTimer::singleShot(kHapticLength + kSafeTimeout, this, &MainWindow::stopHaptic); } void MainWindow::joyDeviceAdded(SDL_JoyDeviceEvent event) { if (!joystick) setJoystick(event.which); } void MainWindow::joyDeviceRemoved(SDL_JoyDeviceEvent event) { if (event.which == SDL_JoystickInstanceID(joystick)) closeJoystick(); if (SDL_NumJoysticks() > 0) setJoystick(0); } <commit_msg>Don't handle button pressed on other joysticks<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QLabel> #include <QPushButton> #include <QComboBox> #include <QCloseEvent> #include <QTimer> #include <QSignalMapper> #include <QGridLayout> #include <SDL_haptic.h> const int kHapticLength = 500; const int kSafeTimeout = 50; static const char __CLASS__[] = "MainWindow"; MainWindow::MainWindow(QWidget *parent) : QMainWindow{parent} , ui{new Ui::MainWindow} , eventThread{new SdlEventThread{this}} , joystick{0} , haptic{0} , hapticId{-1} , numAxis{0} , numButtons{0} , numHats{0} { ui->setupUi(this); fillJoystickList(); connect(eventThread, &SdlEventThread::joyDeviceRemoved, this, &MainWindow::joyDeviceRemoved); connect(ui->choosePadBox, QOverload<int>::of(&QComboBox::activated), this, [this](int index){ setJoystick(index - 1); }); eventThread->start(); } MainWindow::~MainWindow() { closeJoystick(); eventThread->stop(); delete ui; } void MainWindow::closeHaptic() { stopHaptic(); if (!haptic) return; SDL_HapticClose(haptic); haptic = 0; } void MainWindow::closeJoystick() { closeHaptic(); if (!joystick) return; qDebug("%s: close joystick %d %s", __CLASS__, SDL_JoystickInstanceID(joystick), SDL_JoystickName(joystick)); disconnect(eventThread, &SdlEventThread::joyButtonEvent, this, &MainWindow::joystickButtonPressed); disconnect(eventThread, &SdlEventThread::hatEvent, this, &MainWindow::povPressed); disconnect(eventThread, &SdlEventThread::axisEvent, this, &MainWindow::axisMoved); while (auto child = ui->buttonsLayout->takeAt(0)) { delete child; } joystick = 0; numAxis = 0; numButtons = 0; numHats = 0; which = -1; ui->xyaxis->reset(); ui->zaxis->reset(); ui->axis4->reset(); ui->axis5->reset(); ui->pov->reset(); } void MainWindow::closeEvent(QCloseEvent *event) { eventThread->stop(); event->accept(); } void MainWindow::setButtons(int num) { for (int i = 0; i<num; i++) { QPushButton *b = new QPushButton(this); b->setText(QString::number(i+1)); b->setCheckable(true); ui->buttonsLayout->addWidget(b, i / 6, i % 6); } } void MainWindow::fillJoystickList() { while (ui->choosePadBox->count() > 1) ui->choosePadBox->removeItem(1); for (int i = 0; i < SDL_NumJoysticks(); ++i) ui->choosePadBox->addItem(SDL_JoystickNameForIndex(i)); } void MainWindow::setJoystick(int index) { closeJoystick(); joystick = SDL_JoystickOpen(index); if (!joystick) return; which = SDL_JoystickInstanceID(joystick); ui->choosePadBox->setCurrentIndex(index + 1); qDebug("%s: setup joystick %d %s", __CLASS__, SDL_JoystickInstanceID(joystick), SDL_JoystickName(joystick)); numAxis = SDL_JoystickNumAxes(joystick); numButtons = SDL_JoystickNumButtons(joystick); numHats = SDL_JoystickNumHats(joystick); hat = 0; ui->pov->setEnabled(numHats > 0); setButtons(numButtons); int axisOffset = numButtons; while (axisOffset % 6) ++axisOffset; for (int i = 0; i<numAxis; i++) { QLabel *l = new QLabel(this); l->setText(QString("[%1]").arg(i)); ui->buttonsLayout->addWidget(l, (axisOffset + i) / 6, (axisOffset + i) % 6); } connect(eventThread, &SdlEventThread::axisEvent, this, &MainWindow::axisMoved); connect(eventThread, &SdlEventThread::hatEvent, this, &MainWindow::povPressed); connect(eventThread, &SdlEventThread::joyButtonEvent, this, &MainWindow::joystickButtonPressed); setHaptic(SDL_HapticOpenFromJoystick(joystick)); } void MainWindow::axisMoved(SDL_JoyAxisEvent event) { if (event.which != which) return; if (event.axis >= numAxis) return; switch (event.axis) { case 0: ui->xyaxis->xaxisMoved(event); break; case 1: ui->xyaxis->yaxisMoved(event); break; case 2: ui->zaxis->xaxisMoved(event); break; case 3: ui->zaxis->yaxisMoved(event); break; case 4: ui->axis4->axisMoved(event); break; case 5: ui->axis5->axisMoved(event); break; } QLabel *l = qobject_cast<QLabel*>( ui->buttonsLayout->itemAt(numButtons + event.axis)->widget()); if (!l) return; l->setText(QString("[%1]: %2").arg(event.axis).arg(event.value)); } void MainWindow::povPressed(SDL_JoyHatEvent event) { if (event.which != which) return; if (event.hat != hat) return; ui->pov->povPressed(event); } void MainWindow::setHaptic(struct _SDL_Haptic *haptic) { this->haptic = haptic; } void MainWindow::stopHaptic() { if (!haptic) { SDL_JoystickRumble(joystick, 0, 0, 0); return; } SDL_HapticStopEffect(haptic, hapticId); SDL_HapticDestroyEffect(haptic, hapticId); hapticId = -1; } void MainWindow::joystickButtonPressed(SDL_JoyButtonEvent event) { //qDebug("%s: button %d type %x", __FUNCTION__, event.button, event.type); if (event.which != which) return; if (event.button >= numButtons) return; QLayoutItem *item = ui->buttonsLayout->itemAt(event.button); if (!item) { qDebug("%s: no item at %d", __FUNCTION__, event.button); return; } QPushButton *b = qobject_cast<QPushButton*>(item->widget()); if (!b) { qDebug("%s: cast failed at %d", __FUNCTION__, event.button); return; } b->setChecked(event.type == SDL_JOYBUTTONDOWN); if (!ui->testHaptic->isChecked()) return; if (b->isChecked() || hapticId >= 0) return; SDL_HapticEffect lr = {0}; lr.type = SDL_HAPTIC_LEFTRIGHT; lr.leftright.length = kHapticLength; lr.leftright.large_magnitude = (event.button & 1) ? 0x7FFF : 0; lr.leftright.small_magnitude = (event.button & 1) ? 0 : 0x7FFF; if (!haptic) { if (SDL_JoystickRumble(joystick, lr.leftright.large_magnitude, lr.leftright.small_magnitude, lr.leftright.length) < 0) qWarning("Failed to start rumble: %s\n", SDL_GetError()); return; } hapticId = SDL_HapticNewEffect(haptic, &lr); if (hapticId < 0) { qWarning("Failed to create effect: %s\n", SDL_GetError()); return; } //qDebug("[%04x; %04x] : id", lr.leftright.large_magnitude, lr.leftright.small_magnitude, hapticId); SDL_HapticRunEffect(haptic, hapticId, 1); QTimer::singleShot(kHapticLength + kSafeTimeout, this, &MainWindow::stopHaptic); } void MainWindow::joyDeviceAdded(SDL_JoyDeviceEvent event) { if (!joystick) setJoystick(event.which); } void MainWindow::joyDeviceRemoved(SDL_JoyDeviceEvent event) { if (event.which == SDL_JoystickInstanceID(joystick)) closeJoystick(); if (SDL_NumJoysticks() > 0) setJoystick(0); } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include "QFileDialog" #include "QDebug" #include <QPicture> #include "imageprocessingstrategy.h" #include "QMessageBox" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QFile raw(Constants::IMG_RAW); QFile ref(Constants::IMG_REF); if ( raw.exists() && ref.exists() ){ on_bttnStep_clicked(); ui->lineParking->setText(Constants::IMG_RAW); ui->lineReference->setText(Constants::IMG_REF); } } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_fileBttnParking_clicked() { //Dialogo para abrir la ubicación de la foto del parqueo a probar QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),"~/",tr("Mp3 Files (*.jpg)")); qDebug() << fileName; ui->lineParking->setText(fileName); QFile raw_image(fileName); raw_image.copy(Constants::IMG_RAW); } void MainWindow::on_fileBttnReference_clicked() { //Dialogo para abrir la ubicación de la foto de referencia del parqueo QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),"~/",tr("Mp3 Files (*.jpg)")); qDebug() << fileName; ui->lineReference->setText(fileName); QFile ref_image(fileName); ref_image.copy(Constants::IMG_REF); } void MainWindow::on_bttnStep_clicked() { ImageProcessingStrategy* strategy = new ImageProcessingStrategy(); QImage imageRaw, imageRef; switch(Constants::STEP_STATE){ case Constants::RAW: //Constants::IMG_RAW = const_cast<char *>(ui->lineParking->text().toStdString().c_str()); imageRaw.load(Constants::IMG_RAW); imageRef.load(Constants::IMG_REF); qDebug() << imageRaw.bits(); qDebug() << Constants::IMG_RAW; //next state Constants::STEP_STATE = Constants::LAPLACE; break; case Constants::BLUR: if (strategy->processBlur()) showErrorMessage(); imageRaw.load(Constants::IMG_RAW_BLUR); imageRef.load(Constants::IMG_REF_BLUR); //next state Constants::STEP_STATE = Constants::SUBS; break; case Constants::LAPLACE: strategy->processLaplacian(); imageRaw.load(Constants::IMG_RAW_LAPLACE); imageRef.load(Constants::IMG_REF_LAPLACE); //next state Constants::STEP_STATE = Constants::BLUR; break; case Constants::EDGES: strategy->processEdge(); imageRaw.load(Constants::IMG_EDGES); imageRef.allGray(); //next state Constants::STEP_STATE = Constants::CONTOURNS; break; case Constants::SUBS: strategy->processSubs(); imageRaw.load( Constants::IMG_SUBS ); imageRef.allGray(); //next state Constants::STEP_STATE = Constants::EDGES; break; case Constants::CONTOURNS: strategy->processContourns(); imageRaw.load( Constants::IMG_CONTOURNS ); imageRef.load(Constants::IMG_FINAL); ui->bttnStep->setEnabled(false); break; } ui->imgRaw->setPixmap(QPixmap::fromImage(imageRaw)); ui->imgRef->setPixmap(QPixmap::fromImage(imageRef)); } void MainWindow::showErrorMessage(){ QMessageBox msgBox; msgBox.setText("Se detecto un problema al abrir la imagen, por favor intente de nuevo"); msgBox.exec(); } void MainWindow::on_bttnRestart_clicked() { ui->bttnStep->setEnabled(true); Constants::STEP_STATE = Constants::RAW; on_bttnStep_clicked(); } <commit_msg>Se escalan las imagenes para visualizar<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include "QFileDialog" #include "QDebug" #include <QPicture> #include "imageprocessingstrategy.h" #include "QMessageBox" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QFile raw(Constants::IMG_RAW); QFile ref(Constants::IMG_REF); if ( raw.exists() && ref.exists() ){ on_bttnStep_clicked(); ui->lineParking->setText(Constants::IMG_RAW); ui->lineReference->setText(Constants::IMG_REF); } } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_fileBttnParking_clicked() { //Dialogo para abrir la ubicación de la foto del parqueo a probar QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),"~/",tr("Mp3 Files (*.jpg)")); qDebug() << fileName; ui->lineParking->setText(fileName); QFile raw_image(fileName); QFile::remove(Constants::IMG_RAW); raw_image.copy(Constants::IMG_RAW); } void MainWindow::on_fileBttnReference_clicked() { //Dialogo para abrir la ubicación de la foto de referencia del parqueo QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),"~/",tr("Mp3 Files (*.jpg)")); qDebug() << fileName; ui->lineReference->setText(fileName); QFile ref_image(fileName); QFile::remove(Constants::IMG_REF); ref_image.copy(Constants::IMG_REF); } void MainWindow::on_bttnStep_clicked() { ImageProcessingStrategy* strategy = new ImageProcessingStrategy(); QImage imageRaw, imageRef; switch(Constants::STEP_STATE){ case Constants::RAW: //Constants::IMG_RAW = const_cast<char *>(ui->lineParking->text().toStdString().c_str()); imageRaw.load(Constants::IMG_RAW); imageRef.load(Constants::IMG_REF); qDebug() << imageRaw.bits(); qDebug() << Constants::IMG_RAW; //next state Constants::STEP_STATE = Constants::LAPLACE; break; case Constants::BLUR: if (strategy->processBlur()) showErrorMessage(); imageRaw.load(Constants::IMG_RAW_BLUR); imageRef.load(Constants::IMG_REF_BLUR); //next state Constants::STEP_STATE = Constants::SUBS; break; case Constants::LAPLACE: strategy->processLaplacian(); imageRaw.load(Constants::IMG_RAW_LAPLACE); imageRef.load(Constants::IMG_REF_LAPLACE); //next state Constants::STEP_STATE = Constants::BLUR; break; case Constants::EDGES: strategy->processEdge(); imageRaw.load(Constants::IMG_EDGES); imageRef.allGray(); //next state Constants::STEP_STATE = Constants::CONTOURNS; break; case Constants::SUBS: strategy->processSubs(); imageRaw.load( Constants::IMG_SUBS ); imageRef.allGray(); //next state Constants::STEP_STATE = Constants::EDGES; break; case Constants::CONTOURNS: strategy->processContourns(); imageRaw.load( Constants::IMG_CONTOURNS ); imageRef.load(Constants::IMG_FINAL); ui->bttnStep->setEnabled(false); break; } ui->imgRaw->setPixmap(QPixmap::fromImage(imageRaw.scaled(ui->imgRaw->width(),ui->imgRaw->height()))); ui->imgRef->setPixmap(QPixmap::fromImage( imageRef.scaled(ui->imgRef->width(),ui->imgRef->height()))); } void MainWindow::showErrorMessage(){ QMessageBox msgBox; msgBox.setText("Se detecto un problema al abrir la imagen, por favor intente de nuevo"); msgBox.exec(); } void MainWindow::on_bttnRestart_clicked() { ui->bttnStep->setEnabled(true); Constants::STEP_STATE = Constants::RAW; on_bttnStep_clicked(); } <|endoftext|>
<commit_before>/***************************************************************************** * Project: RooFit * * Package: RooFitCore * * File: $Id: RooAbsOptGoodnessOfFit.cc,v 1.4 2002/09/05 04:33:07 verkerke Exp $ * Authors: * * WV, Wouter Verkerke, UC Santa Barbara, [email protected] * * DK, David Kirkby, UC Irvine, [email protected] * * * * Copyright (c) 2000-2002, Regents of the University of California * * and Stanford University. All rights reserved. * * * * Redistribution and use in source and binary forms, * * with or without modification, are permitted according to the terms * * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ // -- CLASS DESCRIPTION [PDF] -- // RooAbsOptGoodnessOfFit is the abstract base class for goodness-of-fit // variables that evaluate the PDF at each point of a given dataset. // This class provides generic optimizations, such as caching and precalculation // of constant terms that can be made for all such quantities // // Implementations should define evaluatePartition(), which calculates the // value of a (sub)range of the dataset and optionally combinedValue(), // which combines the values calculated for each partition. If combinedValue() // is overloaded, the default implementation will add the partition results // to obtain the combined result // // Support for calculation in partitions is needed to allow parallel calculation // of goodness-of-fit values. #include "RooFitCore/RooAbsOptGoodnessOfFit.hh" #include "RooFitCore/RooAbsPdf.hh" #include "RooFitCore/RooAbsData.hh" #include "RooFitCore/RooArgSet.hh" #include "RooFitCore/RooRealVar.hh" #include "RooFitCore/RooErrorHandler.hh" ClassImp(RooAbsOptGoodnessOfFit) ; RooAbsOptGoodnessOfFit::RooAbsOptGoodnessOfFit(const char *name, const char *title, RooAbsPdf& pdf, RooAbsData& data, const RooArgSet& projDeps, Int_t nCPU) : RooAbsGoodnessOfFit(name,title,pdf,data,projDeps,nCPU), _projDeps(0) { // Don't do a thing in master mode if (operMode()!=Slave) { _normSet = 0 ; return ; } RooArgSet obs(*data.get()) ; obs.remove(projDeps,kTRUE,kTRUE) ; // Check that the PDF is valid for use with this dataset // Check if there are any unprotected multiple occurrences of dependents if (pdf.recursiveCheckDependents(&obs)) { cout << "RooAbsOptGoodnessOfFit: ERROR in PDF dependents, abort" << endl ; RooErrorHandler::softAbort() ; return ; } // Check if the fit ranges of the dependents in the data and in the PDF are consistent RooArgSet* pdfDepSet = pdf.getDependents(&data) ; const RooArgSet* dataDepSet = data.get() ; TIterator* iter = pdfDepSet->createIterator() ; RooAbsArg* arg ; while(arg=(RooAbsArg*)iter->Next()) { RooRealVar* pdfReal = dynamic_cast<RooRealVar*>(arg) ; if (!pdfReal) continue ; RooRealVar* datReal = dynamic_cast<RooRealVar*>(dataDepSet->find(pdfReal->GetName())) ; if (!datReal) continue ; if (pdfReal->getFitMin()<(datReal->getFitMin()-1e-6)) { cout << "RooAbsOptGoodnessOfFit: ERROR minimum of PDF variable " << arg->GetName() << "(" << pdfReal->getFitMin() << ") is smaller than that of " << arg->GetName() << " in the dataset (" << datReal->getFitMin() << ")" << endl ; RooErrorHandler::softAbort() ; return ; } if (pdfReal->getFitMax()>(datReal->getFitMax()+1e-6)) { cout << "RooAbsOptGoodnessOfFit: ERROR maximum of PDF variable " << arg->GetName() << " is smaller than that of " << arg->GetName() << " in the dataset" << endl ; RooErrorHandler::softAbort() ; return ; } } delete iter ; // Copy data and strip entries lost by adjusted fit range _dataClone = ((RooAbsData&)data).reduce(*pdfDepSet) ; delete pdfDepSet ; // Clone all PDF compents by copying all branch nodes RooArgSet tmp("PdfBranchNodeList") ; pdf.branchNodeServerList(&tmp) ; _pdfCloneSet = (RooArgSet*) tmp.snapshot(kFALSE) ; // Find the top level PDF in the snapshot list _pdfClone = (RooAbsPdf*) _pdfCloneSet->find(pdf.GetName()) ; // Attach PDF to data set _pdfClone->attachDataSet(*_dataClone) ; // Store normalization set _normSet = (RooArgSet*) data.get()->snapshot(kFALSE) ; // Remove projected dependents from normalization set if (projDeps.getSize()>0) { _projDeps = (RooArgSet*) projDeps.snapshot(kFALSE) ; _normSet->remove(*_projDeps,kTRUE,kTRUE) ; // Mark all projected dependents as such RooArgSet *projDataDeps = (RooArgSet*) _dataClone->get()->selectCommon(*_projDeps) ; projDataDeps->setAttribAll("projectedDependent") ; delete projDataDeps ; } // Add parameters as servers RooArgSet* params = _pdfClone->getParameters(_dataClone) ; _paramSet.add(*params) ; delete params ; // Mark all projected dependents as such if (_projDeps) { RooArgSet *projDataDeps = (RooArgSet*) _dataClone->get()->selectCommon(*_projDeps) ; projDataDeps->setAttribAll("projectedDependent") ; delete projDataDeps ; } optimizeDirty() ; } RooAbsOptGoodnessOfFit::RooAbsOptGoodnessOfFit(const RooAbsOptGoodnessOfFit& other, const char* name) : RooAbsGoodnessOfFit(other,name) { _pdfCloneSet = (RooArgSet*) other._pdfCloneSet->snapshot(kFALSE) ; _pdfClone = (RooAbsPdf*) _pdfCloneSet->find(other._pdfClone->GetName()) ; // Copy the operMode attribute of all branch nodes TIterator* iter = _pdfCloneSet->createIterator() ; RooAbsArg* branch ; while(branch=(RooAbsArg*)iter->Next()) { branch->setOperMode(other._pdfCloneSet->find(branch->GetName())->operMode()) ; } delete iter ; // WVE Must use clone with cache redirection here _dataClone = (RooAbsData*) other._dataClone->cacheClone(_pdfCloneSet) ; _pdfClone->attachDataSet(*_dataClone) ; _normSet = (RooArgSet*) other._normSet->snapshot() ; if (other._projDeps) { _projDeps = (RooArgSet*) other._projDeps->snapshot() ; } else { _projDeps = 0 ; } } RooAbsOptGoodnessOfFit::~RooAbsOptGoodnessOfFit() { if (operMode()==Slave) { delete _pdfCloneSet ; delete _dataClone ; delete _normSet ; delete _projDeps ; } } Double_t RooAbsOptGoodnessOfFit::combinedValue(RooAbsReal** array, Int_t n) const { // Default implementation returns sum of components Double_t sum(0) ; Int_t i ; for (i=0 ; i<n ; i++) { sum += array[i]->getVal() ; } return sum ; } Bool_t RooAbsOptGoodnessOfFit::redirectServersHook(const RooAbsCollection& newServerList, Bool_t mustReplaceAll, Bool_t nameChange) { RooAbsGoodnessOfFit::redirectServersHook(newServerList,mustReplaceAll,nameChange) ; if (operMode()!=Slave) return kFALSE ; return _pdfClone->redirectServers(newServerList,kFALSE,nameChange) ; } void RooAbsOptGoodnessOfFit::constOptimize(ConstOpCode opcode) { // Driver function to propagate const optimization RooAbsGoodnessOfFit::constOptimize(opcode); if (operMode()!=Slave) return ; cout << "RooAbsOptGoodnessOfFit::constOptimize(" << GetName() << ") Action=" ; switch(opcode) { case Activate: cout << "Activate" << endl ; doConstOpt() ; break ; case DeActivate: cout << "DeActivate" << endl ; undoConstOpt() ; break ; case ConfigChange: cout << "ConfigChange" << endl ; undoConstOpt() ; doConstOpt() ; break ; case ValueChange: cout << "ValueChange" << endl ; undoConstOpt() ; doConstOpt() ; break ; } } void RooAbsOptGoodnessOfFit::optimizeDirty() { _pdfClone->getVal(_normSet) ; RooArgSet branchList("branchList") ; _pdfClone->setOperMode(RooAbsArg::ADirty) ; _pdfClone->branchNodeServerList(&branchList) ; TIterator* bIter = branchList.createIterator() ; RooAbsArg* branch ; while(branch=(RooAbsArg*)bIter->Next()) { if (branch->dependsOn(*_dataClone->get())) { RooArgSet* bdep = branch->getDependents(_dataClone->get()) ; if (bdep->getSize()>0) { branch->setOperMode(RooAbsArg::ADirty) ; } else { //cout << "using lazy evaluation for node " << branch->GetName() << endl ; } delete bdep ; } } delete bIter ; // cout << " disabling data dirty state prop" << endl ; _dataClone->setDirtyProp(kFALSE) ; } void RooAbsOptGoodnessOfFit::doConstOpt() { // optimizeDirty must have been run first! // Find cachable branches and cache them with the data set RooArgSet cacheList ; findCacheableBranches(_pdfClone,_dataClone,cacheList) ; _dataClone->cacheArgs(cacheList,_normSet) ; // Find unused data variables after caching and disable them RooArgSet pruneList("pruneList") ; findUnusedDataVariables(_pdfClone,_dataClone,pruneList) ; findRedundantCacheServers(_pdfClone,_dataClone,cacheList,pruneList) ; if (pruneList.getSize()!=0) { // Deactivate tree branches here cout << "RooAbsOptGoodnessOfFit::optimize: The following unused tree branches are deactivated: " ; pruneList.Print("1") ; _dataClone->setArgStatus(pruneList,kFALSE) ; } TIterator* cIter = cacheList.createIterator() ; RooAbsArg *cacheArg ; while(cacheArg=(RooAbsArg*)cIter->Next()){ cacheArg->setOperMode(RooAbsArg::AClean) ; //cout << "setting cached branch " << cacheArg->GetName() << " to AClean" << endl ; } delete cIter ; } void RooAbsOptGoodnessOfFit::undoConstOpt() { // Delete the cache _dataClone->resetCache() ; // Reactivate all tree branches _dataClone->setArgStatus(*_dataClone->get(),kTRUE) ; // Reset all nodes to ADirty optimizeDirty() ; } Bool_t RooAbsOptGoodnessOfFit::findCacheableBranches(RooAbsArg* arg, RooAbsData* dset, RooArgSet& cacheList) { // Find branch PDFs with all-constant parameters, and add them // to the dataset cache list // Evaluate function with current normalization in case servers // are created on the fly RooAbsReal* realArg = dynamic_cast<RooAbsReal*>(arg) ; if (realArg) { realArg->getVal(_normSet) ; } TIterator* sIter = arg->serverIterator() ; RooAbsArg* server ; while(server=(RooAbsArg*)sIter->Next()) { if (server->isDerived()) { // Check if this branch node is eligible for precalculation Bool_t canOpt(kTRUE) ; RooArgSet* branchParamList = server->getParameters(dset) ; TIterator* pIter = branchParamList->createIterator() ; RooAbsArg* param ; while(param = (RooAbsArg*)pIter->Next()) { if (!param->isConstant()) canOpt=kFALSE ; } delete pIter ; delete branchParamList ; if (canOpt) { cout << "RooAbsOptGoodnessOfFit::optimize: component " << server->GetName() << " will be cached" << endl ; // Add to cache list cacheList.add(*server) ; } else { // Recurse if we cannot optimize at this level findCacheableBranches(server,dset,cacheList) ; } } } delete sIter ; return kFALSE ; } void RooAbsOptGoodnessOfFit::findUnusedDataVariables(RooAbsPdf* pdf,RooAbsData* dset,RooArgSet& pruneList) { TIterator* vIter = dset->get()->createIterator() ; RooAbsArg* arg ; while (arg=(RooAbsArg*) vIter->Next()) { if (!pdf->dependsOn(*arg)) pruneList.add(*arg) ; } delete vIter ; } void RooAbsOptGoodnessOfFit::findRedundantCacheServers(RooAbsPdf* pdf,RooAbsData* dset,RooArgSet& cacheList, RooArgSet& pruneList) { TIterator* vIter = dset->get()->createIterator() ; RooAbsArg *var ; while (var=(RooAbsArg*) vIter->Next()) { if (allClientsCached(var,cacheList)) { pruneList.add(*var) ; } } delete vIter ; } Bool_t RooAbsOptGoodnessOfFit::allClientsCached(RooAbsArg* var, RooArgSet& cacheList) { Bool_t ret(kTRUE), anyClient(kFALSE) ; TIterator* cIter = var->valueClientIterator() ; RooAbsArg* client ; while (client=(RooAbsArg*) cIter->Next()) { anyClient = kTRUE ; if (!cacheList.find(client->GetName())) { // If client is not cached recurse ret &= allClientsCached(client,cacheList) ; } } delete cIter ; return anyClient?ret:kFALSE ; } <commit_msg><commit_after>/***************************************************************************** * Project: RooFit * * Package: RooFitCore * * File: $Id: RooAbsOptGoodnessOfFit.cc,v 1.5 2002/09/06 22:41:29 verkerke Exp $ * Authors: * * WV, Wouter Verkerke, UC Santa Barbara, [email protected] * * DK, David Kirkby, UC Irvine, [email protected] * * * * Copyright (c) 2000-2002, Regents of the University of California * * and Stanford University. All rights reserved. * * * * Redistribution and use in source and binary forms, * * with or without modification, are permitted according to the terms * * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ // -- CLASS DESCRIPTION [PDF] -- // RooAbsOptGoodnessOfFit is the abstract base class for goodness-of-fit // variables that evaluate the PDF at each point of a given dataset. // This class provides generic optimizations, such as caching and precalculation // of constant terms that can be made for all such quantities // // Implementations should define evaluatePartition(), which calculates the // value of a (sub)range of the dataset and optionally combinedValue(), // which combines the values calculated for each partition. If combinedValue() // is overloaded, the default implementation will add the partition results // to obtain the combined result // // Support for calculation in partitions is needed to allow parallel calculation // of goodness-of-fit values. #include "RooFitCore/RooAbsOptGoodnessOfFit.hh" #include "RooFitCore/RooAbsPdf.hh" #include "RooFitCore/RooAbsData.hh" #include "RooFitCore/RooArgSet.hh" #include "RooFitCore/RooRealVar.hh" #include "RooFitCore/RooErrorHandler.hh" ClassImp(RooAbsOptGoodnessOfFit) ; RooAbsOptGoodnessOfFit::RooAbsOptGoodnessOfFit(const char *name, const char *title, RooAbsPdf& pdf, RooAbsData& data, const RooArgSet& projDeps, Int_t nCPU) : RooAbsGoodnessOfFit(name,title,pdf,data,projDeps,nCPU), _projDeps(0) { // Don't do a thing in master mode if (operMode()!=Slave) { _normSet = 0 ; return ; } RooArgSet obs(*data.get()) ; obs.remove(projDeps,kTRUE,kTRUE) ; // Check that the PDF is valid for use with this dataset // Check if there are any unprotected multiple occurrences of dependents if (pdf.recursiveCheckDependents(&obs)) { cout << "RooAbsOptGoodnessOfFit: ERROR in PDF dependents, abort" << endl ; RooErrorHandler::softAbort() ; return ; } // Check if the fit ranges of the dependents in the data and in the PDF are consistent RooArgSet* pdfDepSet = pdf.getDependents(&data) ; const RooArgSet* dataDepSet = data.get() ; TIterator* iter = pdfDepSet->createIterator() ; RooAbsArg* arg ; while(arg=(RooAbsArg*)iter->Next()) { RooRealVar* pdfReal = dynamic_cast<RooRealVar*>(arg) ; if (!pdfReal) continue ; RooRealVar* datReal = dynamic_cast<RooRealVar*>(dataDepSet->find(pdfReal->GetName())) ; if (!datReal) continue ; if (pdfReal->getFitMin()<(datReal->getFitMin()-1e-6)) { cout << "RooAbsOptGoodnessOfFit: ERROR minimum of PDF variable " << arg->GetName() << "(" << pdfReal->getFitMin() << ") is smaller than that of " << arg->GetName() << " in the dataset (" << datReal->getFitMin() << ")" << endl ; RooErrorHandler::softAbort() ; return ; } if (pdfReal->getFitMax()>(datReal->getFitMax()+1e-6)) { cout << "RooAbsOptGoodnessOfFit: ERROR maximum of PDF variable " << arg->GetName() << " is smaller than that of " << arg->GetName() << " in the dataset" << endl ; RooErrorHandler::softAbort() ; return ; } } delete iter ; // Copy data and strip entries lost by adjusted fit range _dataClone = ((RooAbsData&)data).reduce(*pdfDepSet) ; delete pdfDepSet ; // Clone all PDF compents by copying all branch nodes RooArgSet tmp("PdfBranchNodeList") ; pdf.branchNodeServerList(&tmp) ; _pdfCloneSet = (RooArgSet*) tmp.snapshot(kFALSE) ; // Find the top level PDF in the snapshot list _pdfClone = (RooAbsPdf*) _pdfCloneSet->find(pdf.GetName()) ; // Attach PDF to data set _pdfClone->attachDataSet(*_dataClone) ; // Store normalization set _normSet = (RooArgSet*) data.get()->snapshot(kFALSE) ; // Remove projected dependents from normalization set if (projDeps.getSize()>0) { _projDeps = (RooArgSet*) projDeps.snapshot(kFALSE) ; _normSet->remove(*_projDeps,kTRUE,kTRUE) ; // Mark all projected dependents as such RooArgSet *projDataDeps = (RooArgSet*) _dataClone->get()->selectCommon(*_projDeps) ; projDataDeps->setAttribAll("projectedDependent") ; delete projDataDeps ; } // Add parameters as servers RooArgSet* params = _pdfClone->getParameters(_dataClone) ; _paramSet.add(*params) ; delete params ; // Mark all projected dependents as such if (_projDeps) { RooArgSet *projDataDeps = (RooArgSet*) _dataClone->get()->selectCommon(*_projDeps) ; projDataDeps->setAttribAll("projectedDependent") ; delete projDataDeps ; } optimizeDirty() ; } RooAbsOptGoodnessOfFit::RooAbsOptGoodnessOfFit(const RooAbsOptGoodnessOfFit& other, const char* name) : RooAbsGoodnessOfFit(other,name) { // Don't do a thing in master mode if (operMode()!=Slave) { _normSet = (RooArgSet*) other._normSet->snapshot() ; return ; } _pdfCloneSet = (RooArgSet*) other._pdfCloneSet->snapshot(kFALSE) ; _pdfClone = (RooAbsPdf*) _pdfCloneSet->find(other._pdfClone->GetName()) ; // Copy the operMode attribute of all branch nodes TIterator* iter = _pdfCloneSet->createIterator() ; RooAbsArg* branch ; while(branch=(RooAbsArg*)iter->Next()) { branch->setOperMode(other._pdfCloneSet->find(branch->GetName())->operMode()) ; } delete iter ; // WVE Must use clone with cache redirection here _dataClone = (RooAbsData*) other._dataClone->cacheClone(_pdfCloneSet) ; _pdfClone->attachDataSet(*_dataClone) ; _normSet = (RooArgSet*) other._normSet->snapshot() ; if (other._projDeps) { _projDeps = (RooArgSet*) other._projDeps->snapshot() ; } else { _projDeps = 0 ; } } RooAbsOptGoodnessOfFit::~RooAbsOptGoodnessOfFit() { if (operMode()==Slave) { delete _pdfCloneSet ; delete _dataClone ; delete _normSet ; delete _projDeps ; } } Double_t RooAbsOptGoodnessOfFit::combinedValue(RooAbsReal** array, Int_t n) const { // Default implementation returns sum of components Double_t sum(0) ; Int_t i ; for (i=0 ; i<n ; i++) { sum += array[i]->getVal() ; } return sum ; } Bool_t RooAbsOptGoodnessOfFit::redirectServersHook(const RooAbsCollection& newServerList, Bool_t mustReplaceAll, Bool_t nameChange) { RooAbsGoodnessOfFit::redirectServersHook(newServerList,mustReplaceAll,nameChange) ; if (operMode()!=Slave) return kFALSE ; return _pdfClone->redirectServers(newServerList,kFALSE,nameChange) ; } void RooAbsOptGoodnessOfFit::constOptimize(ConstOpCode opcode) { // Driver function to propagate const optimization RooAbsGoodnessOfFit::constOptimize(opcode); if (operMode()!=Slave) return ; cout << "RooAbsOptGoodnessOfFit::constOptimize(" << GetName() << ") Action=" ; switch(opcode) { case Activate: cout << "Activate" << endl ; doConstOpt() ; break ; case DeActivate: cout << "DeActivate" << endl ; undoConstOpt() ; break ; case ConfigChange: cout << "ConfigChange" << endl ; undoConstOpt() ; doConstOpt() ; break ; case ValueChange: cout << "ValueChange" << endl ; undoConstOpt() ; doConstOpt() ; break ; } } void RooAbsOptGoodnessOfFit::optimizeDirty() { _pdfClone->getVal(_normSet) ; RooArgSet branchList("branchList") ; _pdfClone->setOperMode(RooAbsArg::ADirty) ; _pdfClone->branchNodeServerList(&branchList) ; TIterator* bIter = branchList.createIterator() ; RooAbsArg* branch ; while(branch=(RooAbsArg*)bIter->Next()) { if (branch->dependsOn(*_dataClone->get())) { RooArgSet* bdep = branch->getDependents(_dataClone->get()) ; if (bdep->getSize()>0) { branch->setOperMode(RooAbsArg::ADirty) ; } else { //cout << "using lazy evaluation for node " << branch->GetName() << endl ; } delete bdep ; } } delete bIter ; // cout << " disabling data dirty state prop" << endl ; _dataClone->setDirtyProp(kFALSE) ; } void RooAbsOptGoodnessOfFit::doConstOpt() { // optimizeDirty must have been run first! // Find cachable branches and cache them with the data set RooArgSet cacheList ; findCacheableBranches(_pdfClone,_dataClone,cacheList) ; _dataClone->cacheArgs(cacheList,_normSet) ; // Find unused data variables after caching and disable them RooArgSet pruneList("pruneList") ; findUnusedDataVariables(_pdfClone,_dataClone,pruneList) ; findRedundantCacheServers(_pdfClone,_dataClone,cacheList,pruneList) ; if (pruneList.getSize()!=0) { // Deactivate tree branches here cout << "RooAbsOptGoodnessOfFit::optimize: The following unused tree branches are deactivated: " ; pruneList.Print("1") ; _dataClone->setArgStatus(pruneList,kFALSE) ; } TIterator* cIter = cacheList.createIterator() ; RooAbsArg *cacheArg ; while(cacheArg=(RooAbsArg*)cIter->Next()){ cacheArg->setOperMode(RooAbsArg::AClean) ; //cout << "setting cached branch " << cacheArg->GetName() << " to AClean" << endl ; } delete cIter ; } void RooAbsOptGoodnessOfFit::undoConstOpt() { // Delete the cache _dataClone->resetCache() ; // Reactivate all tree branches _dataClone->setArgStatus(*_dataClone->get(),kTRUE) ; // Reset all nodes to ADirty optimizeDirty() ; } Bool_t RooAbsOptGoodnessOfFit::findCacheableBranches(RooAbsArg* arg, RooAbsData* dset, RooArgSet& cacheList) { // Find branch PDFs with all-constant parameters, and add them // to the dataset cache list // Evaluate function with current normalization in case servers // are created on the fly RooAbsReal* realArg = dynamic_cast<RooAbsReal*>(arg) ; if (realArg) { realArg->getVal(_normSet) ; } TIterator* sIter = arg->serverIterator() ; RooAbsArg* server ; while(server=(RooAbsArg*)sIter->Next()) { if (server->isDerived()) { // Check if this branch node is eligible for precalculation Bool_t canOpt(kTRUE) ; RooArgSet* branchParamList = server->getParameters(dset) ; TIterator* pIter = branchParamList->createIterator() ; RooAbsArg* param ; while(param = (RooAbsArg*)pIter->Next()) { if (!param->isConstant()) canOpt=kFALSE ; } delete pIter ; delete branchParamList ; if (canOpt) { cout << "RooAbsOptGoodnessOfFit::optimize: component " << server->GetName() << " will be cached" << endl ; // Add to cache list cacheList.add(*server) ; } else { // Recurse if we cannot optimize at this level findCacheableBranches(server,dset,cacheList) ; } } } delete sIter ; return kFALSE ; } void RooAbsOptGoodnessOfFit::findUnusedDataVariables(RooAbsPdf* pdf,RooAbsData* dset,RooArgSet& pruneList) { TIterator* vIter = dset->get()->createIterator() ; RooAbsArg* arg ; while (arg=(RooAbsArg*) vIter->Next()) { if (!pdf->dependsOn(*arg)) pruneList.add(*arg) ; } delete vIter ; } void RooAbsOptGoodnessOfFit::findRedundantCacheServers(RooAbsPdf* pdf,RooAbsData* dset,RooArgSet& cacheList, RooArgSet& pruneList) { TIterator* vIter = dset->get()->createIterator() ; RooAbsArg *var ; while (var=(RooAbsArg*) vIter->Next()) { if (allClientsCached(var,cacheList)) { pruneList.add(*var) ; } } delete vIter ; } Bool_t RooAbsOptGoodnessOfFit::allClientsCached(RooAbsArg* var, RooArgSet& cacheList) { Bool_t ret(kTRUE), anyClient(kFALSE) ; TIterator* cIter = var->valueClientIterator() ; RooAbsArg* client ; while (client=(RooAbsArg*) cIter->Next()) { anyClient = kTRUE ; if (!cacheList.find(client->GetName())) { // If client is not cached recurse ret &= allClientsCached(client,cacheList) ; } } delete cIter ; return anyClient?ret:kFALSE ; } <|endoftext|>
<commit_before> #include <test/agrad/fwd/matrix/to_fvar_test.cpp> //INTEGER-VALUED MATRIX SIZE FUNCTIONS -- DONE #include <test/agrad/fwd/matrix/rows_test.cpp> #include <test/agrad/fwd/matrix/cols_test.cpp> //MATRIX ARITHMETIC OPEPRATORS -- DONE //Negation Prefix Operators -- DONE #include <test/agrad/fwd/matrix/minus_test.cpp> //Infix Matrix Operators -- DONE #include <test/agrad/fwd/matrix/operator_addition_test.cpp> #include <test/agrad/fwd/matrix/operator_subtraction_test.cpp> #include <test/agrad/fwd/matrix/operator_multiplication_test.cpp> #include <test/agrad/fwd/matrix/operator_division_test.cpp> //Broadcast Infix Operators -- DONE //Operator+ is in <test/agrad/fwd/matrix/operator_addition_test.cpp> //Operator- is in <test/agrad/fwd/matrix/operator_subtraction_test.cpp> //Elementwise Products -- DONE #include <test/agrad/fwd/matrix/elt_multiply_test.cpp> #include <test/agrad/fwd/matrix/elt_divide_test.cpp> //Elementwise Logarithms -- DONE #include <test/agrad/fwd/matrix/log_test.cpp> #include <test/agrad/fwd/matrix/exp_test.cpp> //Cumulative Sums -- DONE #include <test/agrad/fwd/matrix/cumulative_sum_test.cpp> //Dot Products -- DONE #include <test/agrad/fwd/matrix/dot_product_test.cpp> #include <test/agrad/fwd/matrix/dot_self_test.cpp> //Specialized Products -- DONE #include <test/agrad/fwd/matrix/tcrossprod_test.cpp> #include <test/agrad/fwd/matrix/crossprod_test.cpp> #include <test/agrad/fwd/matrix/multiply_lower_tri_self_transpose_test.cpp> #include <test/agrad/fwd/matrix/diag_pre_multiply_test.cpp> #include <test/agrad/fwd/matrix/diag_post_multiply_test.cpp> //REDUCTIONS -- DONE //Minimum and Maximum -- DONE #include <test/agrad/fwd/matrix/min_test.cpp> #include <test/agrad/fwd/matrix/max_test.cpp> //Sums and Products -- DONE #include <test/agrad/fwd/matrix/sum_test.cpp> #include <test/agrad/fwd/matrix/prod_test.cpp> //Sample Moments -- DONE #include <test/agrad/fwd/matrix/mean_test.cpp> #include <test/agrad/fwd/matrix/variance_test.cpp> #include <test/agrad/fwd/matrix/sd_test.cpp> //BROADCAST FUNCTIONS -- DONE #include <test/agrad/fwd/matrix/rep_vector_test.cpp> #include <test/agrad/fwd/matrix/rep_row_vector_test.cpp> #include <test/agrad/fwd/matrix/rep_matrix_test.cpp> //SLICE AND PACKAGE FUNCTIONS -- DONE //Diagonal Matrices -- DONE #include <test/agrad/fwd/matrix/diagonal_test.cpp> #include <test/agrad/fwd/matrix/diag_matrix_test.cpp> #include <test/agrad/fwd/matrix/col_test.cpp> #include <test/agrad/fwd/matrix/row_test.cpp> //Block Operation -- DONE #include <test/agrad/fwd/matrix/block_test.cpp> //Transposition Postfix Operator -- DONE #include <test/agrad/fwd/matrix/transpose_test.cpp> //SPECIAL MATRIX FUNCTIONS -- DONE #include <test/agrad/fwd/matrix/softmax_test.cpp> //LINEAR ALGEBRA FUNCTIONS AND SOLVERS //Matrix Division Infix Operators //Lower-Triangular Matrix-Division Functions //Linear Algebra Functions #include <test/agrad/fwd/matrix/trace_test.cpp> #include <test/agrad/fwd/matrix/determinant_test.cpp> //#include <test/agrad/fwd/matrix/inverse_test.cpp> <commit_msg>added refactored tests to fvar_matrix<commit_after> #include <test/agrad/fwd/matrix/to_fvar_test.cpp> //INTEGER-VALUED MATRIX SIZE FUNCTIONS -- DONE #include <test/agrad/fwd/matrix/rows_test.cpp> #include <test/agrad/fwd/matrix/cols_test.cpp> //MATRIX ARITHMETIC OPEPRATORS -- DONE //Negation Prefix Operators -- DONE #include <test/agrad/fwd/matrix/minus_test.cpp> //Infix Matrix Operators -- DONE #include <test/agrad/fwd/matrix/operator_addition_test.cpp> #include <test/agrad/fwd/matrix/operator_subtraction_test.cpp> #include <test/agrad/fwd/matrix/operator_multiplication_test.cpp> #include <test/agrad/fwd/matrix/operator_division_test.cpp> //Broadcast Infix Operators -- DONE //Operator+ is in <test/agrad/fwd/matrix/operator_addition_test.cpp> //Operator- is in <test/agrad/fwd/matrix/operator_subtraction_test.cpp> //Elementwise Products -- DONE #include <test/agrad/fwd/matrix/elt_multiply_test.cpp> #include <test/agrad/fwd/matrix/elt_divide_test.cpp> //Elementwise Logarithms -- DONE #include <test/agrad/fwd/matrix/log_test.cpp> #include <test/agrad/fwd/matrix/exp_test.cpp> //Cumulative Sums -- DONE #include <test/agrad/fwd/matrix/cumulative_sum_test.cpp> //Dot Products -- DONE #include <test/agrad/fwd/matrix/dot_product_test.cpp> #include <test/agrad/fwd/matrix/columns_dot_product_test.cpp> #include <test/agrad/fwd/matrix/rows_dot_product_test.cpp> #include <test/agrad/fwd/matrix/dot_self_test.cpp> #include <test/agrad/fwd/matrix/rows_dot_self_test.cpp> #include <test/agrad/fwd/matrix/columns_dot_self_test.cpp> //Specialized Products -- DONE #include <test/agrad/fwd/matrix/tcrossprod_test.cpp> #include <test/agrad/fwd/matrix/crossprod_test.cpp> #include <test/agrad/fwd/matrix/multiply_lower_tri_self_transpose_test.cpp> #include <test/agrad/fwd/matrix/diag_pre_multiply_test.cpp> #include <test/agrad/fwd/matrix/diag_post_multiply_test.cpp> //REDUCTIONS -- DONE //Minimum and Maximum -- DONE #include <test/agrad/fwd/matrix/min_test.cpp> #include <test/agrad/fwd/matrix/max_test.cpp> //Sums and Products -- DONE #include <test/agrad/fwd/matrix/sum_test.cpp> #include <test/agrad/fwd/matrix/prod_test.cpp> //Sample Moments -- DONE #include <test/agrad/fwd/matrix/mean_test.cpp> #include <test/agrad/fwd/matrix/variance_test.cpp> #include <test/agrad/fwd/matrix/sd_test.cpp> //BROADCAST FUNCTIONS -- DONE #include <test/agrad/fwd/matrix/rep_vector_test.cpp> #include <test/agrad/fwd/matrix/rep_row_vector_test.cpp> #include <test/agrad/fwd/matrix/rep_matrix_test.cpp> //SLICE AND PACKAGE FUNCTIONS -- DONE //Diagonal Matrices -- DONE #include <test/agrad/fwd/matrix/diagonal_test.cpp> #include <test/agrad/fwd/matrix/diag_matrix_test.cpp> #include <test/agrad/fwd/matrix/col_test.cpp> #include <test/agrad/fwd/matrix/row_test.cpp> //Block Operation -- DONE #include <test/agrad/fwd/matrix/block_test.cpp> //Transposition Postfix Operator -- DONE #include <test/agrad/fwd/matrix/transpose_test.cpp> //SPECIAL MATRIX FUNCTIONS -- DONE #include <test/agrad/fwd/matrix/softmax_test.cpp> //LINEAR ALGEBRA FUNCTIONS AND SOLVERS //Matrix Division Infix Operators //Lower-Triangular Matrix-Division Functions //Linear Algebra Functions #include <test/agrad/fwd/matrix/trace_test.cpp> #include <test/agrad/fwd/matrix/determinant_test.cpp> //#include <test/agrad/fwd/matrix/inverse_test.cpp> <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <array> #include <bitset> struct sudoku_cell{ using numset = std::bitset<9>; sudoku_cell():cells{}{} std::array<unsigned,81> cells; std::array<numset,81> cands; std::array<numset,9> reduced_row; std::array<numset,9> reduced_col; constexpr inline unsigned rc_to_index(const unsigned row, const unsigned col){ return 9*row+col; } constexpr inline unsigned index_to_row(const unsigned index){ return index/9; } constexpr inline unsigned index_to_col(const unsigned index){ return index%9; } numset cand_in_row(const unsigned index){ numset ret; ret.set(); const unsigned row = index/9; for(unsigned i=row*9;i<row*9+9;++i) if(cells[i] != 0) ret.reset(cells[i]-1); return ret; } numset cand_in_col(const unsigned index){ numset ret; ret.set(); const unsigned col = index%9; for(unsigned i=col;i<81;i+=9) if(cells[i] != 0) ret.reset(cells[i]-1); return ret; } numset cand_in_3x3(const unsigned index){ numset ret; ret.set(); const unsigned row = index/9; const unsigned col = index%9; const unsigned row_begin = row/3*3; const unsigned col_begin = col/3*3; for(unsigned i=row_begin;i<row_begin+3;++i){ for(unsigned j=col_begin;j<col_begin+3;++j){ if(cells[9*i+j] != 0) ret.reset(cells[9*i+j]-1); } } return ret; } inline unsigned num_of_onbit(const numset& e){ // return least canding number indicated in e for(unsigned i=0;i<9;++i) if(e[i]) return i+1; return 0; // unreachable } void solve(){ gen_cands(); BEGIN: if(reduce_line()) goto BEGIN; if(solve_3x3()) goto BEGIN; if(solve_one_candidate()) goto BEGIN; } bool solve_one_candidate(){ // solve cells which has only one candidate bool changed = false; for(unsigned i=0;i<81;++i){ if(cells[i] == 0){ if(cands[i].count() == 1){ cells[i] = num_of_onbit(cands[i]); rebuild_cand(i); changed = true; } } } return changed; } bool solve_3x3(){ bool changed = false; for(unsigned i=0;i<3;++i){ for(unsigned j=0;j<3;++j){ if(solve_each_3x3(i,j)) changed = true; } } return changed; } bool solve_each_3x3(const unsigned row, const unsigned col){ bool changed = false; for(unsigned i=0;i<9;++i){ bool found = false; unsigned index = 0; for(unsigned j=3*row;j<3*row+3;++j){ for(unsigned k=3*col;k<3*col+3;++k){ auto index_ = 9*j+k; if(cands[index_][i]){ if(found) goto LEND; found = true; index = index_; } } } if(cells[index] == 0 && found){ cells[index] = i+1; rebuild_cand(index); changed = true; } LEND: ; } return changed; } bool reduce_line(){ bool changed = false; for(unsigned i=0;i<3;++i){ for(unsigned j=0;j<3;++j){ if(reduce_line_3x3(i,j)) changed = true; } } return changed; } bool reduce_line_3x3(const unsigned row, const unsigned col){ bool changed = false; for(unsigned i=0;i<9;++i){ for(unsigned j=3*row;j<3*row+3;++j){ auto index = 9*j+3*col; if( !reduced_row[j][i] && ( (cands[index][i] && (cands[index+1][i] || cands[index+2][i])) || (cands[index+1][i] && cands[index+2][i]) ) ){ for(unsigned k=3*row;k<3*row+3;++k){ if(j != k){ for(unsigned l=3*col;l<3*col+3;++l){ if(cands[9*k+l][i]) goto LEND; } } } for(unsigned k=9*j;k<9*j+9;++k){ if(k < 9*j+3*col || k >= 9*j+3*col+3) cands[k].reset(i); } reduced_row[j].set(i); changed = true; goto LEND; } } for(unsigned j=3*col;j<3*col+3;++j){ auto index = 27*row+j; if( !reduced_col[j][i] && ( (cands[index][i] && (cands[index+9][i] || cands[index+18][i])) || (cands[index+9][i] && cands[index+18][i]) ) ){ for(unsigned k=3*row;k<3*row+3;++k){ for(unsigned l=col*3;l<col*3+3;++l){ if(j == l) continue; if(cands[9*k+l][i]) goto LEND; } } for(unsigned k=j%9;k<81;k+=9){ if(k < j || k > j+18) cands[k].reset(i); } reduced_col[j].set(i); changed = true; goto LEND; } } LEND: ; } return changed; } numset gen_cand(unsigned index){ return (cells[index] != 0 ? numset().reset() : (cand_in_row(index) & cand_in_col(index) & cand_in_3x3(index))); } void gen_cands(){ for(unsigned i=0; i<81;++i) cands[i] = gen_cand(i); } void rebuild_cand(unsigned index){ const unsigned val = cells[index]; const unsigned row = index/9; const unsigned col = index%9; const unsigned row_begin = row/3*3; const unsigned col_begin = col/3*3; cands[index].reset(); for(unsigned i=row*9;i<row*9+9;++i) cands[i].reset(val-1); for(unsigned i=col;i<81;i+=9) cands[i].reset(val-1); for(unsigned i=row_begin;i<row_begin+3;++i){ for(unsigned j=col_begin;j<col_begin+3;++j){ cands[9*i+j].reset(val-1); } } } friend std::ostream& operator<<(std::ostream& os, sudoku_cell& s){ for (unsigned i=0;i<9;++i){ os << ' '; for(unsigned j=0;j<9;++j){ os << s.cells[9*i+j] << ((j+1)%3 == 0 && j != 8 ? " | " : " "); } std::cout << (((i+1)%3 == 0 && i != 8) ? "\n-------+-------+-------\n" : "\n"); } return os; } }; int main(){ sudoku_cell s; s.cells = {{ #include "problem.txt" }}; std::cout << s << std::endl; s.solve(); std::cout << s << std::endl; } <commit_msg>Some more change (index -> idx)<commit_after>#include <iostream> #include <iomanip> #include <array> #include <bitset> struct sudoku_cell{ using numset = std::bitset<9>; sudoku_cell():cells{}{} std::array<unsigned,81> cells; std::array<numset,81> cands; std::array<numset,9> reduced_row; std::array<numset,9> reduced_col; inline unsigned rc_to_idx(const unsigned row, const unsigned col){ return 9*row+col; } inline unsigned idx_to_row(const unsigned idx){ return idx/9; } inline unsigned idx_to_col(const unsigned idx){ return idx%9; } numset cand_in_row(const unsigned idx){ numset ret; ret.set(); const unsigned row = idx/9; for(unsigned i=row*9;i<row*9+9;++i) if(cells[i] != 0) ret.reset(cells[i]-1); return ret; } numset cand_in_col(const unsigned idx){ numset ret; ret.set(); const unsigned col = idx%9; for(unsigned i=col;i<81;i+=9) if(cells[i] != 0) ret.reset(cells[i]-1); return ret; } numset cand_in_3x3(const unsigned idx){ numset ret; ret.set(); const unsigned row = idx/9; const unsigned col = idx%9; const unsigned row_begin = row/3*3; const unsigned col_begin = col/3*3; for(unsigned i=row_begin;i<row_begin+3;++i){ for(unsigned j=col_begin;j<col_begin+3;++j){ if(cells[9*i+j] != 0) ret.reset(cells[9*i+j]-1); } } return ret; } inline unsigned num_of_onbit(const numset& e){ // return least canding number indicated in e for(unsigned i=0;i<9;++i) if(e[i]) return i+1; return 0; // unreachable } void solve(){ gen_cands(); BEGIN: if(reduce_line()) goto BEGIN; if(solve_3x3()) goto BEGIN; if(solve_one_candidate()) goto BEGIN; } bool solve_one_candidate(){ // solve cells which has only one candidate bool changed = false; for(unsigned i=0;i<81;++i){ if(cells[i] == 0){ if(cands[i].count() == 1){ cells[i] = num_of_onbit(cands[i]); rebuild_cand(i); changed = true; } } } return changed; } bool solve_3x3(){ bool changed = false; for(unsigned i=0;i<3;++i){ for(unsigned j=0;j<3;++j){ if(solve_each_3x3(i,j)) changed = true; } } return changed; } bool solve_each_3x3(const unsigned row, const unsigned col){ bool changed = false; for(unsigned i=0;i<9;++i){ bool found = false; unsigned idx = 0; for(unsigned j=3*row;j<3*row+3;++j){ for(unsigned k=3*col;k<3*col+3;++k){ auto idx_ = 9*j+k; if(cands[idx_][i]){ if(found) goto LEND; found = true; idx = idx_; } } } if(cells[idx] == 0 && found){ cells[idx] = i+1; rebuild_cand(idx); changed = true; } LEND: ; } return changed; } bool reduce_line(){ bool changed = false; for(unsigned i=0;i<3;++i){ for(unsigned j=0;j<3;++j){ if(reduce_line_3x3(i,j)) changed = true; } } return changed; } bool reduce_line_3x3(const unsigned row, const unsigned col){ bool changed = false; for(unsigned i=0;i<9;++i){ for(unsigned j=3*row;j<3*row+3;++j){ auto idx = 9*j+3*col; if( !reduced_row[j][i] && ( (cands[idx][i] && (cands[idx+1][i] || cands[idx+2][i])) || (cands[idx+1][i] && cands[idx+2][i]) ) ){ for(unsigned k=3*row;k<3*row+3;++k){ if(j != k){ for(unsigned l=3*col;l<3*col+3;++l){ if(cands[9*k+l][i]) goto LEND; } } } for(unsigned k=9*j;k<9*j+9;++k){ if(k < 9*j+3*col || k >= 9*j+3*col+3) cands[k].reset(i); } reduced_row[j].set(i); changed = true; goto LEND; } } for(unsigned j=3*col;j<3*col+3;++j){ auto idx = 27*row+j; if( !reduced_col[j][i] && ( (cands[idx][i] && (cands[idx+9][i] || cands[idx+18][i])) || (cands[idx+9][i] && cands[idx+18][i]) ) ){ for(unsigned k=3*row;k<3*row+3;++k){ for(unsigned l=col*3;l<col*3+3;++l){ if(j == l) continue; if(cands[9*k+l][i]) goto LEND; } } for(unsigned k=j%9;k<81;k+=9){ if(k < j || k > j+18) cands[k].reset(i); } reduced_col[j].set(i); changed = true; goto LEND; } } LEND: ; } return changed; } numset gen_cand(unsigned idx){ return (cells[idx] != 0 ? numset().reset() : (cand_in_row(idx) & cand_in_col(idx) & cand_in_3x3(idx))); } void gen_cands(){ for(unsigned i=0; i<81;++i) cands[i] = gen_cand(i); } void rebuild_cand(unsigned idx){ const unsigned val = cells[idx]; const unsigned row = idx/9; const unsigned col = idx%9; const unsigned row_begin = row/3*3; const unsigned col_begin = col/3*3; cands[idx].reset(); for(unsigned i=row*9;i<row*9+9;++i) cands[i].reset(val-1); for(unsigned i=col;i<81;i+=9) cands[i].reset(val-1); for(unsigned i=row_begin;i<row_begin+3;++i){ for(unsigned j=col_begin;j<col_begin+3;++j){ cands[9*i+j].reset(val-1); } } } friend std::ostream& operator<<(std::ostream& os, sudoku_cell& s){ for (unsigned i=0;i<9;++i){ os << ' '; for(unsigned j=0;j<9;++j){ os << s.cells[9*i+j] << ((j+1)%3 == 0 && j != 8 ? " | " : " "); } std::cout << (((i+1)%3 == 0 && i != 8) ? "\n-------+-------+-------\n" : "\n"); } return os; } }; int main(){ sudoku_cell s; s.cells = {{ #include "problem.txt" }}; std::cout << s << std::endl; s.solve(); std::cout << s << std::endl; } <|endoftext|>
<commit_before>#include <cstdio> #include <cstring> #include <stdexcept> const unsigned char HEX_TABLE[] = { 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 0,1,2,3,4,5,6,7,8,9, // 0-9 255,255,255,255,255,255,255, 10,11,12,13,14,15, // a-f 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 10,11,12,13,14,15, // A-F 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255 }; const auto HEX_ALPHABET = "0123456789abcdef"; int main (int argc, char** argv) { unsigned char hbuf[2] = {}; unsigned char bbuf[1] = {}; // decode? if (argc > 1) { if (!strncmp(argv[1], "-d", 2) && !strncmp(argv[1], "--decode", 8)) throw std::invalid_argument("Unknown argument"); while (true) { const auto read = fread(hbuf, sizeof(hbuf), 1, stdin); // EOF? if (read == 0) break; const auto a = HEX_TABLE[hbuf[0]]; const auto b = HEX_TABLE[hbuf[1]]; if (a != 255) throw std::domain_error("Invalid hex character"); if (b != 255) throw std::domain_error("Invalid hex character"); bbuf[0] = static_cast<unsigned char>(a * 16 + b); fwrite(bbuf, sizeof(bbuf), 1, stdout); } // encode } else { while (true) { const auto read = fread(bbuf, sizeof(bbuf), 1, stdin); // EOF? if (read == 0) break; const auto a = bbuf[0] / 16; const auto b = bbuf[0] % 16; hbuf[0] = HEX_ALPHABET[a]; hbuf[1] = HEX_ALPHABET[b]; fwrite(hbuf, sizeof(hbuf), 1, stdout); } } return 0; } <commit_msg>fix invalid argument detection<commit_after>#include <cstdio> #include <cstring> #include <stdexcept> const unsigned char HEX_TABLE[] = { 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 0,1,2,3,4,5,6,7,8,9, // 0-9 255,255,255,255,255,255,255, 10,11,12,13,14,15, // a-f 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 10,11,12,13,14,15, // A-F 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255 }; const auto HEX_ALPHABET = "0123456789abcdef"; int main (int argc, char** argv) { unsigned char hbuf[2] = {}; unsigned char bbuf[1] = {}; // decode? if (argc > 1) { if (strncmp(argv[1], "-d", 2) != 0 && strncmp(argv[1], "--decode", 8) != 0) { throw std::invalid_argument("Unknown argument"); } while (true) { const auto read = fread(hbuf, sizeof(hbuf), 1, stdin); // EOF? if (read == 0) break; const auto a = HEX_TABLE[hbuf[0]]; const auto b = HEX_TABLE[hbuf[1]]; if (a != 255) throw std::domain_error("Invalid hex character"); if (b != 255) throw std::domain_error("Invalid hex character"); bbuf[0] = static_cast<unsigned char>(a * 16 + b); fwrite(bbuf, sizeof(bbuf), 1, stdout); } // encode } else { while (true) { const auto read = fread(bbuf, sizeof(bbuf), 1, stdin); // EOF? if (read == 0) break; const auto a = bbuf[0] / 16; const auto b = bbuf[0] % 16; hbuf[0] = HEX_ALPHABET[a]; hbuf[1] = HEX_ALPHABET[b]; fwrite(hbuf, sizeof(hbuf), 1, stdout); } } return 0; } <|endoftext|>
<commit_before>#include "culebra.h" #include "linenoise.hpp" #include <fstream> #include <iomanip> #include <iostream> #include <vector> using namespace culebra; using namespace std; bool read_file(const char* path, vector<char>& buff) { ifstream ifs(path, ios::in|ios::binary); if (ifs.fail()) { return false; } auto size = static_cast<unsigned int>(ifs.seekg(0, ios::end).tellg()); if (size > 0) { buff.resize(size); ifs.seekg(0, ios::beg).read(&buff[0], static_cast<streamsize>(buff.size())); } return true; } struct CommandLineDebugger { void operator()(const peglib::Ast& ast, shared_ptr<Environment> env, bool force_to_break) { if (command == "n" && env->level <= level || command == "s" || command == "o" && env->level < level) { force_to_break = true; } if (force_to_break) { show_lines(ast); for (;;) { command = linenoise::Readline("debug> "); if (command == "bt") { cout << "level: " << env->level << endl; } else if (command == "c") { // continue break; } else if (command == "n") { // step over break; } else if (command == "s") { // step into break; } else if (command == "o") { // step out break; } } level = env->level;; } } void show_lines(const peglib::Ast& ast) { cout << "break in " << ast.path << ":" << ast.line << endl; auto count = get_line_count(ast.path); auto digits = to_string(count).length();; size_t start = max((int)ast.line - 1, 1); auto end = min(ast.line + 3, count); for (auto l = start; l < end; l++) { auto s = get_line(ast.path, l); if (l == ast.line) { cout << "> "; } else { cout << " "; } cout << setw(digits) << l << " " << s << endl; } } size_t get_line_count(const string& path) { prepare_cache(path); return sources[path].size(); } string get_line(const string& path, size_t line) { prepare_cache(path); const auto& positions = sources[path]; auto idx = line - 1; auto first = idx > 0 ? positions[idx - 1] : 0; auto last = positions[idx]; auto size = last - first; string s(size, 0); ifstream ifs(path, ios::in | ios::binary); ifs.seekg(first, ios::beg).read((char*)s.data(), static_cast<streamsize>(s.size())); size_t count = 0; auto rit = s.rbegin(); while (rit != s.rend()) { if (*rit == '\n') { count++; } ++rit; } s = s.substr(0, s.size() - count); return s; } void prepare_cache(const string& path) { auto it = sources.find(path); if (it == sources.end()) { vector<char> buff; read_file(path.c_str(), buff); auto& positions = sources[path]; auto i = 0u; for (; i < buff.size(); i++) { if (buff[i] == '\n') { positions.push_back(i + 1); } } positions.push_back(i); } } string command; size_t level = 0; map<string, vector<size_t>> sources; }; int repl(shared_ptr<Environment> env, bool print_ast) { for (;;) { auto line = linenoise::Readline("cul> "); if (line == "exit" || line == "quit") { break; } if (!line.empty()) { Value val; vector<string> msgs; shared_ptr<peglib::Ast> ast; auto ret = run("(repl)", env, line.c_str(), line.size(), val, msgs, ast); if (ret) { if (print_ast) { ast->print(); } cout << val << endl; linenoise::AddHistory(line.c_str()); } else if (!msgs.empty()) { for (const auto& msg: msgs) { cout << msg << endl;; } } } } return 0; } int main(int argc, const char** argv) { auto print_ast = false; auto shell = false; auto debug = false; vector<const char*> path_list; int argi = 1; while (argi < argc) { auto arg = argv[argi++]; if (string("--shell") == arg) { shell = true; } else if (string("--ast") == arg) { print_ast = true; } else if (string("--debug") == arg) { debug = true; } else { path_list.push_back(arg); } } if (!shell) { shell = path_list.empty(); } try { auto env = make_shared<Environment>(); setup_built_in_functions(*env); for (auto path: path_list) { vector<char> buff; if (!read_file(path, buff)) { cerr << "can't open '" << path << "'." << endl; return -1; } Value val; vector<string> msgs; shared_ptr<peglib::Ast> ast; Debugger dbg; CommandLineDebugger debugger; if (debug) { dbg = debugger; } auto ret = run(path, env, buff.data(), buff.size(), val, msgs, ast, dbg); if (!ret) { for (const auto& msg: msgs) { cerr << msg << endl; } return -1; } else if (print_ast) { ast->print(); } } if (shell) { repl(env, print_ast); } } catch (exception& e) { cerr << e.what() << endl; return -1; } return 0; } // vim: et ts=4 sw=4 cin cino={1s ff=unix <commit_msg>Fixed warning.<commit_after>#include "culebra.h" #include "linenoise.hpp" #include <fstream> #include <iomanip> #include <iostream> #include <vector> using namespace culebra; using namespace std; bool read_file(const char* path, vector<char>& buff) { ifstream ifs(path, ios::in|ios::binary); if (ifs.fail()) { return false; } auto size = static_cast<unsigned int>(ifs.seekg(0, ios::end).tellg()); if (size > 0) { buff.resize(size); ifs.seekg(0, ios::beg).read(&buff[0], static_cast<streamsize>(buff.size())); } return true; } struct CommandLineDebugger { void operator()(const peglib::Ast& ast, shared_ptr<Environment> env, bool force_to_break) { if ((command == "n" && env->level <= level) || (command == "s") || (command == "o" && env->level < level)) { force_to_break = true; } if (force_to_break) { show_lines(ast); for (;;) { command = linenoise::Readline("debug> "); if (command == "bt") { cout << "level: " << env->level << endl; } else if (command == "c") { // continue break; } else if (command == "n") { // step over break; } else if (command == "s") { // step into break; } else if (command == "o") { // step out break; } } level = env->level;; } } void show_lines(const peglib::Ast& ast) { cout << "break in " << ast.path << ":" << ast.line << endl; auto count = get_line_count(ast.path); auto digits = to_string(count).length();; size_t start = max((int)ast.line - 1, 1); auto end = min(ast.line + 3, count); for (auto l = start; l < end; l++) { auto s = get_line(ast.path, l); if (l == ast.line) { cout << "> "; } else { cout << " "; } cout << setw(digits) << l << " " << s << endl; } } size_t get_line_count(const string& path) { prepare_cache(path); return sources[path].size(); } string get_line(const string& path, size_t line) { prepare_cache(path); const auto& positions = sources[path]; auto idx = line - 1; auto first = idx > 0 ? positions[idx - 1] : 0; auto last = positions[idx]; auto size = last - first; string s(size, 0); ifstream ifs(path, ios::in | ios::binary); ifs.seekg(first, ios::beg).read((char*)s.data(), static_cast<streamsize>(s.size())); size_t count = 0; auto rit = s.rbegin(); while (rit != s.rend()) { if (*rit == '\n') { count++; } ++rit; } s = s.substr(0, s.size() - count); return s; } void prepare_cache(const string& path) { auto it = sources.find(path); if (it == sources.end()) { vector<char> buff; read_file(path.c_str(), buff); auto& positions = sources[path]; auto i = 0u; for (; i < buff.size(); i++) { if (buff[i] == '\n') { positions.push_back(i + 1); } } positions.push_back(i); } } string command; size_t level = 0; map<string, vector<size_t>> sources; }; int repl(shared_ptr<Environment> env, bool print_ast) { for (;;) { auto line = linenoise::Readline("cul> "); if (line == "exit" || line == "quit") { break; } if (!line.empty()) { Value val; vector<string> msgs; shared_ptr<peglib::Ast> ast; auto ret = run("(repl)", env, line.c_str(), line.size(), val, msgs, ast); if (ret) { if (print_ast) { ast->print(); } cout << val << endl; linenoise::AddHistory(line.c_str()); } else if (!msgs.empty()) { for (const auto& msg: msgs) { cout << msg << endl;; } } } } return 0; } int main(int argc, const char** argv) { auto print_ast = false; auto shell = false; auto debug = false; vector<const char*> path_list; int argi = 1; while (argi < argc) { auto arg = argv[argi++]; if (string("--shell") == arg) { shell = true; } else if (string("--ast") == arg) { print_ast = true; } else if (string("--debug") == arg) { debug = true; } else { path_list.push_back(arg); } } if (!shell) { shell = path_list.empty(); } try { auto env = make_shared<Environment>(); setup_built_in_functions(*env); for (auto path: path_list) { vector<char> buff; if (!read_file(path, buff)) { cerr << "can't open '" << path << "'." << endl; return -1; } Value val; vector<string> msgs; shared_ptr<peglib::Ast> ast; Debugger dbg; CommandLineDebugger debugger; if (debug) { dbg = debugger; } auto ret = run(path, env, buff.data(), buff.size(), val, msgs, ast, dbg); if (!ret) { for (const auto& msg: msgs) { cerr << msg << endl; } return -1; } else if (print_ast) { ast->print(); } } if (shell) { repl(env, print_ast); } } catch (exception& e) { cerr << e.what() << endl; return -1; } return 0; } // vim: et ts=4 sw=4 cin cino={1s ff=unix <|endoftext|>
<commit_before><commit_msg>loplugin:simplifybool<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <memory> #include <string> #include <unordered_map> #include <vector> #include "paddle/fluid/framework/op_registry.h" #ifdef PADDLE_WITH_MKLDNN #include "paddle/fluid/platform/mkldnn_helper.h" #endif namespace paddle { namespace operators { class AbsOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "abs"); OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "abs"); auto in_dims = ctx->GetInputDim("X"); ctx->SetOutputDim("Out", in_dims); ctx->ShareLoD("X", /*->*/ "Out"); } }; class AbsOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("X", "(Tensor), The input tensor of abs op."); AddOutput("Out", "(Tensor), The output tensor of abs op."); AddAttr<bool>("use_mkldnn", "(bool, default false) Only used in mkldnn kernel") .SetDefault(false) .AsExtra(); AddAttr<bool>("use_cudnn", "(bool, default false) Only used in cudnn kernel, need " "install cudnn") .SetDefault(false) .AsExtra(); AddComment(R"DOC( Abs Operator. This operator is used to perform elementwise abs for input $X$. $$out = |x|$$ )DOC"); } }; class AbsGradOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")), "Input", "Out@Grad", "AbsGrad"); OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("X")), "Output", "X@Grad", "AbsGrad"); auto dout_dims = ctx->GetInputDim(framework::GradVarName("Out")); ctx->SetOutputDim(framework::GradVarName("X"), dout_dims); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { auto dtype = OperatorWithKernel::IndicateVarDataType(ctx, "X"); return framework::OpKernelType(dtype, ctx.GetPlace()); } }; template <typename T> class AbsGradMaker : public framework::SingleGradOpMaker<T> { public: using framework::SingleGradOpMaker<T>::SingleGradOpMaker; void Apply(GradOpPtr<T> retv) const override { retv->SetType("abs_grad"); retv->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out")); retv->SetInput("X", this->Input("X")); retv->SetAttrMap(this->Attrs()); retv->SetOutput(framework::GradVarName("X"), this->InputGrad("X")); } }; // AbsGrad: dx=dy if x >=0 else -dy // AbsDoubleGrad: ddy = ddx if x >=0 else -ddx template <typename T> class AbsDoubleGradMaker : public framework::SingleGradOpMaker<T> { public: using ::paddle::framework::SingleGradOpMaker<T>::SingleGradOpMaker; protected: void Apply(GradOpPtr<T> op) const override { op->SetType("abs_double_grad"); // input1: x op->SetInput("X", this->Input("X")); // input2: ddx op->SetInput("DDX", this->OutputGrad(framework::GradVarName("X"))); op->SetAttrMap(this->Attrs()); // output: ddy op->SetOutput("DDOut", this->InputGrad(framework::GradVarName("Out"))); } }; class AbsDoubleGradOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { if (ctx->HasOutput("DDOut")) { ctx->ShareDim("X", "DDOut"); ctx->ShareLoD("X", "DDOut"); } } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { auto dtype = OperatorWithKernel::IndicateVarDataType(ctx, "DDX"); return framework::OpKernelType(dtype, ctx.GetPlace()); } framework::OpKernelType GetKernelTypeForVar( const std::string& var_name, const framework::Tensor& tensor, const framework::OpKernelType& expected_kernel_type) const { return framework::OpKernelType( framework::TransToProtoVarType(tensor.dtype()), tensor.place(), tensor.layout()); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(abs, ops::AbsOp, ops::AbsOpMaker, ops::AbsGradMaker<paddle::framework::OpDesc>, ops::AbsGradMaker<paddle::imperative::OpBase>); REGISTER_OPERATOR(abs_grad, ops::AbsGradOp, ops::AbsDoubleGradMaker<paddle::framework::OpDesc>, ops::AbsDoubleGradMaker<paddle::imperative::OpBase>); REGISTER_OPERATOR(abs_double_grad, ops::AbsDoubleGradOp); <commit_msg>Move Abs InferShape to phi (#39762)<commit_after>// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <memory> #include <string> #include <unordered_map> #include <vector> #include "paddle/fluid/framework/infershape_utils.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/phi/core/infermeta_utils.h" #include "paddle/phi/infermeta/unary.h" #ifdef PADDLE_WITH_MKLDNN #include "paddle/fluid/platform/mkldnn_helper.h" #endif namespace paddle { namespace operators { class AbsOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; }; class AbsOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("X", "(Tensor), The input tensor of abs op."); AddOutput("Out", "(Tensor), The output tensor of abs op."); AddAttr<bool>("use_mkldnn", "(bool, default false) Only used in mkldnn kernel") .SetDefault(false) .AsExtra(); AddAttr<bool>("use_cudnn", "(bool, default false) Only used in cudnn kernel, need " "install cudnn") .SetDefault(false) .AsExtra(); AddComment(R"DOC( Abs Operator. This operator is used to perform elementwise abs for input $X$. $$out = |x|$$ )DOC"); } }; class AbsGradOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")), "Input", "Out@Grad", "AbsGrad"); OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("X")), "Output", "X@Grad", "AbsGrad"); auto dout_dims = ctx->GetInputDim(framework::GradVarName("Out")); ctx->SetOutputDim(framework::GradVarName("X"), dout_dims); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { auto dtype = OperatorWithKernel::IndicateVarDataType(ctx, "X"); return framework::OpKernelType(dtype, ctx.GetPlace()); } }; template <typename T> class AbsGradMaker : public framework::SingleGradOpMaker<T> { public: using framework::SingleGradOpMaker<T>::SingleGradOpMaker; void Apply(GradOpPtr<T> retv) const override { retv->SetType("abs_grad"); retv->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out")); retv->SetInput("X", this->Input("X")); retv->SetAttrMap(this->Attrs()); retv->SetOutput(framework::GradVarName("X"), this->InputGrad("X")); } }; // AbsGrad: dx=dy if x >=0 else -dy // AbsDoubleGrad: ddy = ddx if x >=0 else -ddx template <typename T> class AbsDoubleGradMaker : public framework::SingleGradOpMaker<T> { public: using ::paddle::framework::SingleGradOpMaker<T>::SingleGradOpMaker; protected: void Apply(GradOpPtr<T> op) const override { op->SetType("abs_double_grad"); // input1: x op->SetInput("X", this->Input("X")); // input2: ddx op->SetInput("DDX", this->OutputGrad(framework::GradVarName("X"))); op->SetAttrMap(this->Attrs()); // output: ddy op->SetOutput("DDOut", this->InputGrad(framework::GradVarName("Out"))); } }; class AbsDoubleGradOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { if (ctx->HasOutput("DDOut")) { ctx->ShareDim("X", "DDOut"); ctx->ShareLoD("X", "DDOut"); } } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { auto dtype = OperatorWithKernel::IndicateVarDataType(ctx, "DDX"); return framework::OpKernelType(dtype, ctx.GetPlace()); } framework::OpKernelType GetKernelTypeForVar( const std::string& var_name, const framework::Tensor& tensor, const framework::OpKernelType& expected_kernel_type) const { return framework::OpKernelType( framework::TransToProtoVarType(tensor.dtype()), tensor.place(), tensor.layout()); } }; } // namespace operators } // namespace paddle DELCARE_INFER_SHAPE_FUNCTOR(abs, AbsInferShapeFunctor, PT_INFER_META(phi::UnchangedInferMeta)); namespace ops = paddle::operators; REGISTER_OPERATOR(abs, ops::AbsOp, ops::AbsOpMaker, ops::AbsGradMaker<paddle::framework::OpDesc>, ops::AbsGradMaker<paddle::imperative::OpBase>, AbsInferShapeFunctor); REGISTER_OPERATOR(abs_grad, ops::AbsGradOp, ops::AbsDoubleGradMaker<paddle::framework::OpDesc>, ops::AbsDoubleGradMaker<paddle::imperative::OpBase>); REGISTER_OPERATOR(abs_double_grad, ops::AbsDoubleGradOp); <|endoftext|>
<commit_before>/* This file is part of the Kate project. * * Copyright (C) 2010 Dominik Haumann <dhaumann kde org> * Copyright (C) 2010 Diana-Victoria Tiriplica <[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 "katerecoverbar.h" #include "ui_recoverwidget.h" #include "kateswapfile.h" #include "kateview.h" #include "katedocument.h" #include <kprocess.h> #include <kmessagebox.h> #include <ktemporaryfile.h> #include <krun.h> #include <QWhatsThis> //BEGIN KateRecoverBar KateRecoverBar::KateRecoverBar(KateView *view, QWidget *parent) : KateViewBarWidget( false, parent ) , m_view ( view ) , m_ui (new Ui::RecoverWidget()) , m_proc(0) { m_ui->setupUi( centralWidget() ); // clicking on the "Help" link pops up the content as what's this connect(m_ui->lblSwap, SIGNAL(linkActivated(const QString&)), this, SLOT(showWhatsThis(const QString&))); // set icons, but keep text from ui file m_ui->btnRecover->setGuiItem(KGuiItem(m_ui->btnRecover->text(), KIcon("edit-redo"))); m_ui->btnDiscard->setGuiItem(KStandardGuiItem::discard()); m_ui->lblIcon->setPixmap(KIcon("dialog-warning").pixmap(64, 64)); // use queued connections because this (all) KateRecoverBar widgets are deleted connect(m_ui->btnRecover, SIGNAL(clicked()), m_view->doc()->swapFile(), SLOT(recover()), Qt::QueuedConnection); connect(m_ui->btnDiscard, SIGNAL(clicked()), m_view->doc()->swapFile(), SLOT(discard()), Qt::QueuedConnection); connect(m_ui->btnDiff, SIGNAL(clicked()), this, SLOT(viewDiff())); } KateRecoverBar::~KateRecoverBar () { delete m_ui; } void KateRecoverBar::showWhatsThis(const QString& text) { QWhatsThis::showText(QCursor::pos(), text); } void KateRecoverBar::viewDiff() { // create a document with the recovered data KateDocument recoverDoc; recoverDoc.setText(m_view->doc()->text()); QString path = m_view->doc()->swapFile()->fileName(); if (path.isNull()) return; QFile swp(path); if (!swp.open(QIODevice::ReadOnly)) { kWarning( 13020 ) << "Can't open swap file"; return; } QDataStream stream(&swp); recoverDoc.swapFile()->recover(stream); // create a KProcess proc m_proc = new KProcess(this); m_proc->setOutputChannelMode(KProcess::MergedChannels); *m_proc << "diff" << "-u" << "-" << m_view->doc()->url().toLocalFile(); connect(m_proc, SIGNAL(readyRead()), this, SLOT(slotDataAvailable())); connect(m_proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(slotDiffFinished())); setCursor(Qt::WaitCursor); // disable the "View Changes" button, so the user won't click it twice m_ui->btnDiff->setEnabled(false); m_diffContent.clear(); m_proc->start(); QTextStream ts(m_proc); int lineCount = recoverDoc.lines(); for (int line = 0; line < lineCount; ++line) ts << recoverDoc.line(line) << '\n'; ts.flush(); m_proc->closeWriteChannel(); } void KateRecoverBar::slotDataAvailable() { // collect diff output m_diffContent += m_proc->readAll(); } void KateRecoverBar::slotDiffFinished() { m_ui->btnDiff->setEnabled(true); unsetCursor(); // get the exit status to check whether diff command run successfully const QProcess::ExitStatus es = m_proc->exitStatus(); delete m_proc; m_proc = 0; KTemporaryFile tempFile; tempFile.setSuffix(".diff"); if (!tempFile.open()) { kWarning( 13020 ) << "Can't open diff temporary file"; return; } // write the buffered data to the temporary file tempFile.write(m_diffContent); // check exit status if (es != QProcess::NormalExit) { KMessageBox::sorry(this, i18n("The diff command failed. Please make sure that " "diff(1) is installed and in your PATH."), i18n("Error Creating Diff")); return; } // sanity check: is there any diff content? if ( tempFile.size() == 0 ) { KMessageBox::information(this, i18n("The files are identical."), i18n("Diff Output")); return; } tempFile.setAutoRemove(false); KUrl url = KUrl::fromPath(tempFile.fileName()); // KRun::runUrl should delete the file, once the client exits KRun::runUrl(url, "text/x-patch", this, true ); } //END KateRecoverBar // kate: space-indent on; indent-width 2; replace-tabs on; <commit_msg>Hide the recover-bar as soon as the text is edited. There is 2 good reasons for this: 1. Other applications that integrate kate (like KDevelop) might have own recovery mechanisms, and this makes the non-configurable swap-file recovery not interfere with such mechanisms. 2. As soon as the user or the application has edited the text, the recovery will fail anyway.<commit_after>/* This file is part of the Kate project. * * Copyright (C) 2010 Dominik Haumann <dhaumann kde org> * Copyright (C) 2010 Diana-Victoria Tiriplica <[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 "katerecoverbar.h" #include "ui_recoverwidget.h" #include "kateswapfile.h" #include "kateview.h" #include "katedocument.h" #include <kprocess.h> #include <kmessagebox.h> #include <ktemporaryfile.h> #include <krun.h> #include <QWhatsThis> //BEGIN KateRecoverBar KateRecoverBar::KateRecoverBar(KateView *view, QWidget *parent) : KateViewBarWidget( false, parent ) , m_view ( view ) , m_ui (new Ui::RecoverWidget()) , m_proc(0) { m_ui->setupUi( centralWidget() ); // clicking on the "Help" link pops up the content as what's this connect(m_ui->lblSwap, SIGNAL(linkActivated(const QString&)), this, SLOT(showWhatsThis(const QString&))); // set icons, but keep text from ui file m_ui->btnRecover->setGuiItem(KGuiItem(m_ui->btnRecover->text(), KIcon("edit-redo"))); m_ui->btnDiscard->setGuiItem(KStandardGuiItem::discard()); m_ui->lblIcon->setPixmap(KIcon("dialog-warning").pixmap(64, 64)); // use queued connections because this (all) KateRecoverBar widgets are deleted connect(m_ui->btnRecover, SIGNAL(clicked()), m_view->doc()->swapFile(), SLOT(recover()), Qt::QueuedConnection); connect(m_ui->btnDiscard, SIGNAL(clicked()), m_view->doc()->swapFile(), SLOT(discard()), Qt::QueuedConnection); connect(&view->doc()->buffer(), SIGNAL(editingStarted()), this, SIGNAL(hideMe())); connect(m_ui->btnDiff, SIGNAL(clicked()), this, SLOT(viewDiff())); } KateRecoverBar::~KateRecoverBar () { delete m_ui; } void KateRecoverBar::showWhatsThis(const QString& text) { QWhatsThis::showText(QCursor::pos(), text); } void KateRecoverBar::viewDiff() { // create a document with the recovered data KateDocument recoverDoc; recoverDoc.setText(m_view->doc()->text()); QString path = m_view->doc()->swapFile()->fileName(); if (path.isNull()) return; QFile swp(path); if (!swp.open(QIODevice::ReadOnly)) { kWarning( 13020 ) << "Can't open swap file"; return; } QDataStream stream(&swp); recoverDoc.swapFile()->recover(stream); // create a KProcess proc m_proc = new KProcess(this); m_proc->setOutputChannelMode(KProcess::MergedChannels); *m_proc << "diff" << "-u" << "-" << m_view->doc()->url().toLocalFile(); connect(m_proc, SIGNAL(readyRead()), this, SLOT(slotDataAvailable())); connect(m_proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(slotDiffFinished())); setCursor(Qt::WaitCursor); // disable the "View Changes" button, so the user won't click it twice m_ui->btnDiff->setEnabled(false); m_diffContent.clear(); m_proc->start(); QTextStream ts(m_proc); int lineCount = recoverDoc.lines(); for (int line = 0; line < lineCount; ++line) ts << recoverDoc.line(line) << '\n'; ts.flush(); m_proc->closeWriteChannel(); } void KateRecoverBar::slotDataAvailable() { // collect diff output m_diffContent += m_proc->readAll(); } void KateRecoverBar::slotDiffFinished() { m_ui->btnDiff->setEnabled(true); unsetCursor(); // get the exit status to check whether diff command run successfully const QProcess::ExitStatus es = m_proc->exitStatus(); delete m_proc; m_proc = 0; KTemporaryFile tempFile; tempFile.setSuffix(".diff"); if (!tempFile.open()) { kWarning( 13020 ) << "Can't open diff temporary file"; return; } // write the buffered data to the temporary file tempFile.write(m_diffContent); // check exit status if (es != QProcess::NormalExit) { KMessageBox::sorry(this, i18n("The diff command failed. Please make sure that " "diff(1) is installed and in your PATH."), i18n("Error Creating Diff")); return; } // sanity check: is there any diff content? if ( tempFile.size() == 0 ) { KMessageBox::information(this, i18n("The files are identical."), i18n("Diff Output")); return; } tempFile.setAutoRemove(false); KUrl url = KUrl::fromPath(tempFile.fileName()); // KRun::runUrl should delete the file, once the client exits KRun::runUrl(url, "text/x-patch", this, true ); } //END KateRecoverBar // kate: space-indent on; indent-width 2; replace-tabs on; <|endoftext|>
<commit_before>/************************************************************************* * * * I|*j^3Cl|a "+!*% qt Nd gW * * l]{y+l?MM* !#Wla\NNP NW MM I| * * PW ?E| tWg Wg sC! AW ~@v~ * * NC ?M! yN| WW MK MW@K1Y%M@ RM #Q QP@tim * * CM| |WQCljAE| MD Mg RN cM~ NM WQ MQ * * #M aQ? MW M3 Mg Q( HQ YR IM| * * Dq {Ql MH iMX Mg MM QP QM Eg * * !EWNaPRag2$ +M" $WNaHaN% MQE$%EXW QQ CM %M%a$D * * * * Website: https://github.com/zpublic/zpublic * * * ************************************************************************/ /** * @file * @brief ע */ #pragma once #include "win_utils_header.h" #include <shlwapi.h> namespace zl { namespace WinUtils { /** * @brief ע, ,д,ɾ */ class ZLRegister { private: HKEY m_hKey; public: ZLRegister(); ZLRegister(ZLRegister& rhs); explicit ZLRegister(HKEY hKey); ~ZLRegister(); ZLRegister& operator=(ZLRegister& rhs); operator HKEY() const; public: /** * @brief ע * @see ˵μMSDNRegCreateKeyEx * @return ɹTRUE, ʧFALSE */ BOOL Create( HKEY hKey, LPCTSTR lpSubKey, REGSAM samDesired = KEY_READ | KEY_WRITE, LPTSTR lpClass = NULL, DWORD dwOptions = REG_OPTION_NON_VOLATILE, LPSECURITY_ATTRIBUTES lpSecAttr = NULL, LPDWORD lpdwDisposition = NULL); /** * @brief ע * @param[in] hKey * @param[in] lpSubKey ע· * @param[in] samDesired Ȩ * @param[in] bCreateIfNotExist עʱ, Ƿ񴴽 */ BOOL Open( HKEY hKey, LPCTSTR lpSubKey, REGSAM samDesired = KEY_READ | KEY_WRITE, BOOL bCreateIfNotExist = FALSE); public: // д BOOL SetBinaryValue(LPCTSTR lpValueName, const void* pValue, ULONG nBytes); BOOL SetDwordValue(LPCTSTR lpValueName, DWORD dwValue); BOOL SetQwordValue(LPCTSTR lpValueName, ULONGLONG qwValue); BOOL SetSzValue(LPCTSTR lpValueName, LPCTSTR lpValue); BOOL SetExpandSzValue(LPCTSTR lpValueName, LPCTSTR lpValue); BOOL SetMultiSzValue(LPCTSTR lpValueName, LPCTSTR lpValue); BOOL SetMultiSzValue(LPCTSTR lpValueName, const std::vector<CString> &vecValueLine); public: // BOOL GetBinaryValue(LPCTSTR pszValueName, void* pValue, ULONG* pnBytes); BOOL GetDwordValue(LPCTSTR lpValueName, DWORD& dwValue); BOOL GetQwordValue(LPCTSTR lpValueName, ULONGLONG& qwValue); BOOL GetStringValue(LPCTSTR lpValueName, CString& sValue); BOOL GetMultiSzValue(LPCTSTR lpValueName, LPTSTR lpValue, ULONG* pnChars); BOOL GetMultiSzValue(LPCTSTR lpValueName, std::vector<CString>& vecValues); public: // ɾ BOOL DelValue(LPCTSTR lpValueName); BOOL DelSubKey(LPCTSTR lpSubKey); static BOOL DelKey(HKEY hKey, LPCTSTR lpSubKey); public: void Attach(HKEY hKey); HKEY Detach(); void Close(); private: void ZLRegister::_ParseDNTString(LPCTSTR lpString, std::vector<CString>& vecResult) const; }; inline ZLRegister::ZLRegister() : m_hKey(NULL) {} inline ZLRegister::ZLRegister( ZLRegister& rhs ) { Attach(rhs.Detach()); } inline ZLRegister::ZLRegister( HKEY hKey ) : m_hKey(hKey) {} inline ZLRegister::~ZLRegister() { Close(); } inline void ZLRegister::Attach( HKEY hKey ) { m_hKey = hKey; } inline HKEY ZLRegister::Detach() { HKEY hKey = m_hKey; m_hKey = NULL; return hKey; } inline void ZLRegister::Close() { if (m_hKey != NULL) { ::RegCloseKey(m_hKey); m_hKey = NULL; } } inline ZLRegister& ZLRegister::operator=( ZLRegister& rhs ) { if(m_hKey!=rhs.m_hKey) { Close(); Attach( rhs.Detach() ); } return (*this); } inline ZLRegister::operator HKEY() const { return m_hKey; } inline BOOL ZLRegister::SetDwordValue( LPCTSTR lpValueName, DWORD dwValue ) { if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_DWORD, reinterpret_cast<const BYTE*>(&dwValue), sizeof(DWORD))) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetQwordValue( LPCTSTR lpValueName, ULONGLONG qwValue ) { if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_QWORD, reinterpret_cast<const BYTE*>(&qwValue), sizeof(ULONGLONG))) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetBinaryValue( LPCTSTR lpValueName, const void* pValue, ULONG nBytes ) { if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_BINARY, reinterpret_cast<const BYTE*>(pValue), nBytes)) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetSzValue( LPCTSTR lpValueName, LPCTSTR lpValue ) { if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_SZ, reinterpret_cast<const BYTE*>(lpValue), (lstrlen(lpValue)+1)*sizeof(TCHAR))) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetExpandSzValue( LPCTSTR lpValueName, LPCTSTR lpValue ) { if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_EXPAND_SZ, reinterpret_cast<const BYTE*>(lpValue), (lstrlen(lpValue)+1)*sizeof(TCHAR))) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetMultiSzValue( LPCTSTR lpValueName, LPCTSTR lpValue ) { LPCTSTR pszTemp; ULONG nBytes; ULONG nLength; // ַС(bytes) nBytes = 0; pszTemp = lpValue; do { nLength = lstrlen(pszTemp)+1; pszTemp += nLength; nBytes += nLength * sizeof(TCHAR); } while (nLength != 1); if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_MULTI_SZ, reinterpret_cast<const BYTE*>(lpValue), nBytes)) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetMultiSzValue( LPCTSTR lpValueName, const std::vector<CString> &vecValueLine ) { std::wstring sValue; for (size_t i=0; i<vecValueLine.size(); ++i) { sValue += vecValueLine[i]; sValue.push_back(0); } sValue.push_back(0); sValue.push_back(0); return SetMultiSzValue(lpValueName, sValue.c_str()); } inline BOOL ZLRegister::GetBinaryValue(LPCTSTR lpValueName, void* pValue, ULONG* pnBytes) { DWORD dwType = REG_NONE; LONG lRes = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(pValue), pnBytes); if (lRes != ERROR_SUCCESS) return FALSE; if (dwType != REG_BINARY) return FALSE; return TRUE; } inline BOOL ZLRegister::GetDwordValue( LPCTSTR lpValueName, DWORD& dwValue ) { DWORD dwType = REG_NONE; ULONG nBytes = sizeof(DWORD); LONG lRet = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(&dwValue), &nBytes); if ((ERROR_SUCCESS==lRet) && (REG_DWORD==dwType)) { return TRUE; } return FALSE; } inline BOOL ZLRegister::GetQwordValue( LPCTSTR lpValueName, ULONGLONG& qwValue ) { DWORD dwType; ULONG nBytes = sizeof(ULONGLONG); LONG lRet = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(&qwValue), &nBytes); if ((ERROR_SUCCESS==lRet) && (REG_QWORD==dwType)) { return TRUE; } return FALSE; } inline BOOL ZLRegister::GetStringValue( LPCTSTR lpValueName, CString& sValue ) { BOOL bReturn = FALSE; LPTSTR lpValueBuf = NULL; // ȡֵͺʹС DWORD dwType = REG_NONE; ULONG ulBytes = 0; ULONG lRet = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, NULL, &ulBytes); if (ERROR_SUCCESS != lRet) goto Exit0; if ((REG_SZ!=dwType) && (REG_EXPAND_SZ!=dwType)) goto Exit0; if (NULL == (lpValueBuf = (LPTSTR)malloc(ulBytes))) goto Exit0; // ȡֵ memset(lpValueBuf, 0, ulBytes); lRet = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(lpValueBuf), &ulBytes); if (ERROR_SUCCESS != lRet) goto Exit0; sValue = lpValueBuf; bReturn = TRUE; Exit0: if (lpValueBuf) free(lpValueBuf); return bReturn; } inline BOOL ZLRegister::GetMultiSzValue(LPCTSTR lpValueName, LPTSTR lpValue, ULONG* pnChars) { DWORD dwType; ULONG nBytes; if (lpValue != NULL && *pnChars < 2) return FALSE; nBytes = (*pnChars)*sizeof(TCHAR); *pnChars = 0; LONG lRes = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(lpValue), &nBytes); if (lRes != ERROR_SUCCESS) return FALSE; if (dwType != REG_MULTI_SZ) return FALSE; if (lpValue != NULL && (nBytes % sizeof(TCHAR) != 0 || nBytes / sizeof(TCHAR) < 1 || lpValue[nBytes / sizeof(TCHAR) -1] != 0 || ((nBytes/sizeof(TCHAR))>1 && lpValue[nBytes / sizeof(TCHAR) - 2] != 0))) return FALSE; *pnChars = nBytes/sizeof(TCHAR); return TRUE; } inline BOOL ZLRegister::GetMultiSzValue( LPCTSTR lpValueName, std::vector<CString>& vecValues ) { BOOL bReturn = FALSE; ULONG ulChars = 0; if (GetMultiSzValue(lpValueName, NULL, &ulChars)) // ȡС { TCHAR* pValue = new TCHAR[ulChars]; bReturn = GetMultiSzValue(lpValueName, pValue, &ulChars); _ParseDNTString(pValue, vecValues); delete pValue; } return bReturn; } inline BOOL ZLRegister::Create( HKEY hKey, LPCTSTR lpSubKey, REGSAM samDesired, LPTSTR lpClass, DWORD dwOptions, LPSECURITY_ATTRIBUTES lpSecAttr, LPDWORD lpdwDisposition) { HKEY hKeyResult = NULL; DWORD dwDisposition = 0; LONG lRet = RegCreateKeyEx(hKey, lpSubKey, 0, lpClass, dwOptions, samDesired, lpSecAttr, &hKeyResult, &dwDisposition); if (lpdwDisposition != NULL) *lpdwDisposition = dwDisposition; if (lRet == ERROR_SUCCESS) { Close(); m_hKey = hKeyResult; return TRUE; } return FALSE; } inline BOOL ZLRegister::Open( HKEY hKey, LPCTSTR lpSubKey, REGSAM samDesired, BOOL bCreateIfNotExist) { BOOL bReturn = FALSE; HKEY hKeyResult = NULL; LONG lRet = RegOpenKeyEx(hKey, lpSubKey, 0, samDesired, &hKeyResult); if (lRet == ERROR_SUCCESS) { Close(); m_hKey = hKeyResult; bReturn = TRUE; } else if (bCreateIfNotExist) { bReturn = Create(hKey, lpSubKey, samDesired); } return bReturn; } inline BOOL ZLRegister::DelSubKey( LPCTSTR lpSubKey ) { if (ERROR_SUCCESS == ::SHDeleteKey(m_hKey, lpSubKey)) return TRUE; return FALSE; } inline BOOL ZLRegister::DelValue( LPCTSTR lpValueName ) { if (ERROR_SUCCESS == ::RegDeleteValue(m_hKey, lpValueName)) return TRUE; return FALSE; } inline BOOL ZLRegister::DelKey( HKEY hKey, LPCTSTR lpSubKey ) { if (ERROR_SUCCESS == ::SHDeleteKey(hKey, lpSubKey)) return TRUE; return FALSE; } // Parse a "double null terminated string" to std::vector inline void ZLRegister::_ParseDNTString(LPCTSTR lpString, std::vector<CString>& vecResult) const { vecResult.clear(); if (NULL == lpString) return; LPCTSTR psTemp = lpString; DWORD dwLen = (DWORD)_tcslen(psTemp); while (dwLen > 0) { vecResult.push_back(psTemp); psTemp = &psTemp[dwLen + 1]; dwLen = (DWORD)_tcslen(psTemp); } } } }<commit_msg>* z_win_utils 修改一处内存泄漏BUG<commit_after>/************************************************************************* * * * I|*j^3Cl|a "+!*% qt Nd gW * * l]{y+l?MM* !#Wla\NNP NW MM I| * * PW ?E| tWg Wg sC! AW ~@v~ * * NC ?M! yN| WW MK MW@K1Y%M@ RM #Q QP@tim * * CM| |WQCljAE| MD Mg RN cM~ NM WQ MQ * * #M aQ? MW M3 Mg Q( HQ YR IM| * * Dq {Ql MH iMX Mg MM QP QM Eg * * !EWNaPRag2$ +M" $WNaHaN% MQE$%EXW QQ CM %M%a$D * * * * Website: https://github.com/zpublic/zpublic * * * ************************************************************************/ /** * @file * @brief ע */ #pragma once #include "win_utils_header.h" #include <shlwapi.h> namespace zl { namespace WinUtils { /** * @brief ע, ,д,ɾ */ class ZLRegister { private: HKEY m_hKey; public: ZLRegister(); ZLRegister(ZLRegister& rhs); explicit ZLRegister(HKEY hKey); ~ZLRegister(); ZLRegister& operator=(ZLRegister& rhs); operator HKEY() const; public: /** * @brief ע * @see ˵μMSDNRegCreateKeyEx * @return ɹTRUE, ʧFALSE */ BOOL Create( HKEY hKey, LPCTSTR lpSubKey, REGSAM samDesired = KEY_READ | KEY_WRITE, LPTSTR lpClass = NULL, DWORD dwOptions = REG_OPTION_NON_VOLATILE, LPSECURITY_ATTRIBUTES lpSecAttr = NULL, LPDWORD lpdwDisposition = NULL); /** * @brief ע * @param[in] hKey * @param[in] lpSubKey ע· * @param[in] samDesired Ȩ * @param[in] bCreateIfNotExist עʱ, Ƿ񴴽 */ BOOL Open( HKEY hKey, LPCTSTR lpSubKey, REGSAM samDesired = KEY_READ | KEY_WRITE, BOOL bCreateIfNotExist = FALSE); public: // д BOOL SetBinaryValue(LPCTSTR lpValueName, const void* pValue, ULONG nBytes); BOOL SetDwordValue(LPCTSTR lpValueName, DWORD dwValue); BOOL SetQwordValue(LPCTSTR lpValueName, ULONGLONG qwValue); BOOL SetSzValue(LPCTSTR lpValueName, LPCTSTR lpValue); BOOL SetExpandSzValue(LPCTSTR lpValueName, LPCTSTR lpValue); BOOL SetMultiSzValue(LPCTSTR lpValueName, LPCTSTR lpValue); BOOL SetMultiSzValue(LPCTSTR lpValueName, const std::vector<CString> &vecValueLine); public: // BOOL GetBinaryValue(LPCTSTR pszValueName, void* pValue, ULONG* pnBytes); BOOL GetDwordValue(LPCTSTR lpValueName, DWORD& dwValue); BOOL GetQwordValue(LPCTSTR lpValueName, ULONGLONG& qwValue); BOOL GetStringValue(LPCTSTR lpValueName, CString& sValue); BOOL GetMultiSzValue(LPCTSTR lpValueName, LPTSTR lpValue, ULONG* pnChars); BOOL GetMultiSzValue(LPCTSTR lpValueName, std::vector<CString>& vecValues); public: // ɾ BOOL DelValue(LPCTSTR lpValueName); BOOL DelSubKey(LPCTSTR lpSubKey); static BOOL DelKey(HKEY hKey, LPCTSTR lpSubKey); public: void Attach(HKEY hKey); HKEY Detach(); void Close(); private: void ZLRegister::_ParseDNTString(LPCTSTR lpString, std::vector<CString>& vecResult) const; }; inline ZLRegister::ZLRegister() : m_hKey(NULL) {} inline ZLRegister::ZLRegister( ZLRegister& rhs ) { Attach(rhs.Detach()); } inline ZLRegister::ZLRegister( HKEY hKey ) : m_hKey(hKey) {} inline ZLRegister::~ZLRegister() { Close(); } inline void ZLRegister::Attach( HKEY hKey ) { m_hKey = hKey; } inline HKEY ZLRegister::Detach() { HKEY hKey = m_hKey; m_hKey = NULL; return hKey; } inline void ZLRegister::Close() { if (m_hKey != NULL) { ::RegCloseKey(m_hKey); m_hKey = NULL; } } inline ZLRegister& ZLRegister::operator=( ZLRegister& rhs ) { if(m_hKey!=rhs.m_hKey) { Close(); Attach( rhs.Detach() ); } return (*this); } inline ZLRegister::operator HKEY() const { return m_hKey; } inline BOOL ZLRegister::SetDwordValue( LPCTSTR lpValueName, DWORD dwValue ) { if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_DWORD, reinterpret_cast<const BYTE*>(&dwValue), sizeof(DWORD))) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetQwordValue( LPCTSTR lpValueName, ULONGLONG qwValue ) { if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_QWORD, reinterpret_cast<const BYTE*>(&qwValue), sizeof(ULONGLONG))) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetBinaryValue( LPCTSTR lpValueName, const void* pValue, ULONG nBytes ) { if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_BINARY, reinterpret_cast<const BYTE*>(pValue), nBytes)) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetSzValue( LPCTSTR lpValueName, LPCTSTR lpValue ) { if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_SZ, reinterpret_cast<const BYTE*>(lpValue), (lstrlen(lpValue)+1)*sizeof(TCHAR))) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetExpandSzValue( LPCTSTR lpValueName, LPCTSTR lpValue ) { if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_EXPAND_SZ, reinterpret_cast<const BYTE*>(lpValue), (lstrlen(lpValue)+1)*sizeof(TCHAR))) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetMultiSzValue( LPCTSTR lpValueName, LPCTSTR lpValue ) { LPCTSTR pszTemp; ULONG nBytes; ULONG nLength; // ַС(bytes) nBytes = 0; pszTemp = lpValue; do { nLength = lstrlen(pszTemp)+1; pszTemp += nLength; nBytes += nLength * sizeof(TCHAR); } while (nLength != 1); if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_MULTI_SZ, reinterpret_cast<const BYTE*>(lpValue), nBytes)) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetMultiSzValue( LPCTSTR lpValueName, const std::vector<CString> &vecValueLine ) { std::wstring sValue; for (size_t i=0; i<vecValueLine.size(); ++i) { sValue += vecValueLine[i]; sValue.push_back(0); } sValue.push_back(0); sValue.push_back(0); return SetMultiSzValue(lpValueName, sValue.c_str()); } inline BOOL ZLRegister::GetBinaryValue(LPCTSTR lpValueName, void* pValue, ULONG* pnBytes) { DWORD dwType = REG_NONE; LONG lRes = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(pValue), pnBytes); if (lRes != ERROR_SUCCESS) return FALSE; if (dwType != REG_BINARY) return FALSE; return TRUE; } inline BOOL ZLRegister::GetDwordValue( LPCTSTR lpValueName, DWORD& dwValue ) { DWORD dwType = REG_NONE; ULONG nBytes = sizeof(DWORD); LONG lRet = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(&dwValue), &nBytes); if ((ERROR_SUCCESS==lRet) && (REG_DWORD==dwType)) { return TRUE; } return FALSE; } inline BOOL ZLRegister::GetQwordValue( LPCTSTR lpValueName, ULONGLONG& qwValue ) { DWORD dwType; ULONG nBytes = sizeof(ULONGLONG); LONG lRet = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(&qwValue), &nBytes); if ((ERROR_SUCCESS==lRet) && (REG_QWORD==dwType)) { return TRUE; } return FALSE; } inline BOOL ZLRegister::GetStringValue( LPCTSTR lpValueName, CString& sValue ) { BOOL bReturn = FALSE; LPTSTR lpValueBuf = NULL; // ȡֵͺʹС DWORD dwType = REG_NONE; ULONG ulBytes = 0; ULONG lRet = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, NULL, &ulBytes); if (ERROR_SUCCESS != lRet) goto Exit0; if ((REG_SZ!=dwType) && (REG_EXPAND_SZ!=dwType)) goto Exit0; if (NULL == (lpValueBuf = (LPTSTR)malloc(ulBytes))) goto Exit0; // ȡֵ memset(lpValueBuf, 0, ulBytes); lRet = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(lpValueBuf), &ulBytes); if (ERROR_SUCCESS != lRet) goto Exit0; sValue = lpValueBuf; bReturn = TRUE; Exit0: if (lpValueBuf) free(lpValueBuf); return bReturn; } inline BOOL ZLRegister::GetMultiSzValue(LPCTSTR lpValueName, LPTSTR lpValue, ULONG* pnChars) { DWORD dwType; ULONG nBytes; if (lpValue != NULL && *pnChars < 2) return FALSE; nBytes = (*pnChars)*sizeof(TCHAR); *pnChars = 0; LONG lRes = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(lpValue), &nBytes); if (lRes != ERROR_SUCCESS) return FALSE; if (dwType != REG_MULTI_SZ) return FALSE; if (lpValue != NULL && (nBytes % sizeof(TCHAR) != 0 || nBytes / sizeof(TCHAR) < 1 || lpValue[nBytes / sizeof(TCHAR) -1] != 0 || ((nBytes/sizeof(TCHAR))>1 && lpValue[nBytes / sizeof(TCHAR) - 2] != 0))) return FALSE; *pnChars = nBytes/sizeof(TCHAR); return TRUE; } inline BOOL ZLRegister::GetMultiSzValue( LPCTSTR lpValueName, std::vector<CString>& vecValues ) { BOOL bReturn = FALSE; ULONG ulChars = 0; if (GetMultiSzValue(lpValueName, NULL, &ulChars)) // ȡС { TCHAR* pValue = new TCHAR[ulChars]; bReturn = GetMultiSzValue(lpValueName, pValue, &ulChars); _ParseDNTString(pValue, vecValues); delete []pValue; } return bReturn; } inline BOOL ZLRegister::Create( HKEY hKey, LPCTSTR lpSubKey, REGSAM samDesired, LPTSTR lpClass, DWORD dwOptions, LPSECURITY_ATTRIBUTES lpSecAttr, LPDWORD lpdwDisposition) { HKEY hKeyResult = NULL; DWORD dwDisposition = 0; LONG lRet = RegCreateKeyEx(hKey, lpSubKey, 0, lpClass, dwOptions, samDesired, lpSecAttr, &hKeyResult, &dwDisposition); if (lpdwDisposition != NULL) *lpdwDisposition = dwDisposition; if (lRet == ERROR_SUCCESS) { Close(); m_hKey = hKeyResult; return TRUE; } return FALSE; } inline BOOL ZLRegister::Open( HKEY hKey, LPCTSTR lpSubKey, REGSAM samDesired, BOOL bCreateIfNotExist) { BOOL bReturn = FALSE; HKEY hKeyResult = NULL; LONG lRet = RegOpenKeyEx(hKey, lpSubKey, 0, samDesired, &hKeyResult); if (lRet == ERROR_SUCCESS) { Close(); m_hKey = hKeyResult; bReturn = TRUE; } else if (bCreateIfNotExist) { bReturn = Create(hKey, lpSubKey, samDesired); } return bReturn; } inline BOOL ZLRegister::DelSubKey( LPCTSTR lpSubKey ) { if (ERROR_SUCCESS == ::SHDeleteKey(m_hKey, lpSubKey)) return TRUE; return FALSE; } inline BOOL ZLRegister::DelValue( LPCTSTR lpValueName ) { if (ERROR_SUCCESS == ::RegDeleteValue(m_hKey, lpValueName)) return TRUE; return FALSE; } inline BOOL ZLRegister::DelKey( HKEY hKey, LPCTSTR lpSubKey ) { if (ERROR_SUCCESS == ::SHDeleteKey(hKey, lpSubKey)) return TRUE; return FALSE; } // Parse a "double null terminated string" to std::vector inline void ZLRegister::_ParseDNTString(LPCTSTR lpString, std::vector<CString>& vecResult) const { vecResult.clear(); if (NULL == lpString) return; LPCTSTR psTemp = lpString; DWORD dwLen = (DWORD)_tcslen(psTemp); while (dwLen > 0) { vecResult.push_back(psTemp); psTemp = &psTemp[dwLen + 1]; dwLen = (DWORD)_tcslen(psTemp); } } } }<|endoftext|>
<commit_before>#include "process.hpp" #include <cstdlib> #include <unistd.h> #include <signal.h> #include <stdexcept> Process::Data::Data(): id(-1) {} Process::id_type Process::open(const std::string &command, const std::string &path) { if(open_stdin) stdin_fd=std::unique_ptr<fd_type>(new fd_type); if(read_stdout) stdout_fd=std::unique_ptr<fd_type>(new fd_type); if(read_stderr) stderr_fd=std::unique_ptr<fd_type>(new fd_type); int stdin_p[2], stdout_p[2], stderr_p[2]; if(stdin_fd && pipe(stdin_p)!=0) { close(stdin_p[0]);close(stdin_p[1]); return -1; } if(stdout_fd && pipe(stdout_p)!=0) { if(stdin_fd) {close(stdin_p[0]);close(stdin_p[1]);} close(stdout_p[0]);close(stdout_p[1]); return -1; } if(stderr_fd && pipe(stderr_p)!=0) { if(stdin_fd) {close(stdin_p[0]);close(stdin_p[1]);} if(stdout_fd) {close(stdout_p[0]);close(stdout_p[1]);} close(stderr_p[0]);close(stderr_p[1]); return -1; } id_type pid = fork(); if (pid < 0) { if(stdin_fd) {close(stdin_p[0]);close(stdin_p[1]);} if(stdout_fd) {close(stdout_p[0]);close(stdout_p[1]);} if(stderr_fd) {close(stderr_p[0]);close(stderr_p[1]);} return pid; } else if (pid == 0) { if(stdin_fd) dup2(stdin_p[0], 0); if(stdout_fd) dup2(stdout_p[1], 1); if(stderr_fd) dup2(stderr_p[1], 2); if(stdin_fd) {close(stdin_p[0]);close(stdin_p[1]);} if(stdout_fd) {close(stdout_p[0]);close(stdout_p[1]);} if(stderr_fd) {close(stderr_p[0]);close(stderr_p[1]);} //Based on http://stackoverflow.com/a/899533/3808293 int fd_max=sysconf(_SC_OPEN_MAX); for(int fd=3;fd<fd_max;fd++) close(fd); setpgid(0, 0); //TODO: See here on how to emulate tty for colors: http://stackoverflow.com/questions/1401002/trick-an-application-into-thinking-its-stdin-is-interactive-not-a-pipe //TODO: One solution is: echo "command;exit"|script -q /dev/null if(!path.empty()) { auto path_escaped=path; size_t pos=0; //Based on https://www.reddit.com/r/cpp/comments/3vpjqg/a_new_platform_independent_process_library_for_c11/cxsxyb7 while((pos=path_escaped.find('\'', pos))!=std::string::npos) { path_escaped.replace(pos, 1, "'\\''"); pos+=4; } execl("/bin/sh", "sh", "-c", ("cd \'"+path_escaped+"\' && "+command).c_str(), NULL); } else execl("/bin/sh", "sh", "-c", command.c_str(), NULL); _exit(EXIT_FAILURE); } if(stdin_fd) close(stdin_p[0]); if(stdout_fd) close(stdout_p[1]); if(stderr_fd) close(stderr_p[1]); if(stdin_fd) *stdin_fd = stdin_p[1]; if(stdout_fd) *stdout_fd = stdout_p[0]; if(stderr_fd) *stderr_fd = stderr_p[0]; closed=false; data.id=pid; return pid; } void Process::async_read() { if(data.id<=0) return; if(stdout_fd) { stdout_thread=std::thread([this](){ char buffer[buffer_size]; ssize_t n; while ((n=read(*stdout_fd, buffer, buffer_size)) > 0) read_stdout(buffer, static_cast<size_t>(n)); }); } if(stderr_fd) { stderr_thread=std::thread([this](){ char buffer[buffer_size]; ssize_t n; while ((n=read(*stderr_fd, buffer, buffer_size)) > 0) read_stderr(buffer, static_cast<size_t>(n)); }); } } int Process::get_exit_status() { if(data.id<=0) return -1; int exit_status; waitpid(data.id, &exit_status, 0); close_mutex.lock(); closed=true; close_mutex.unlock(); close_fds(); return exit_status; } void Process::close_fds() { if(stdout_thread.joinable()) stdout_thread.join(); if(stderr_thread.joinable()) stderr_thread.join(); if(stdin_fd) close_stdin(); if(stdout_fd) { close(*stdout_fd); stdout_fd.reset(); } if(stderr_fd) { close(*stderr_fd); stderr_fd.reset(); } } bool Process::write(const char *bytes, size_t n) { if(!open_stdin) throw std::invalid_argument("Can't write to an unopened stdin pipe. Please set open_stdin=true when constructing the process."); stdin_mutex.lock(); if(stdin_fd) { if(::write(*stdin_fd, bytes, n)>=0) { stdin_mutex.unlock(); return true; } else { stdin_mutex.unlock(); return false; } } stdin_mutex.unlock(); return false; } void Process::close_stdin() { stdin_mutex.lock(); if(stdin_fd) { close(*stdin_fd); stdin_fd.reset(); } stdin_mutex.unlock(); } void Process::kill(bool force) { close_mutex.lock(); if(data.id>0 && !closed) { if(force) ::kill(-data.id, SIGTERM); else ::kill(-data.id, SIGINT); } close_mutex.unlock(); } void Process::kill(id_type id, bool force) { if(id<=0) return; if(force) ::kill(-id, SIGTERM); else ::kill(-id, SIGINT); } <commit_msg>Removed unnecessary backslashes<commit_after>#include "process.hpp" #include <cstdlib> #include <unistd.h> #include <signal.h> #include <stdexcept> Process::Data::Data(): id(-1) {} Process::id_type Process::open(const std::string &command, const std::string &path) { if(open_stdin) stdin_fd=std::unique_ptr<fd_type>(new fd_type); if(read_stdout) stdout_fd=std::unique_ptr<fd_type>(new fd_type); if(read_stderr) stderr_fd=std::unique_ptr<fd_type>(new fd_type); int stdin_p[2], stdout_p[2], stderr_p[2]; if(stdin_fd && pipe(stdin_p)!=0) { close(stdin_p[0]);close(stdin_p[1]); return -1; } if(stdout_fd && pipe(stdout_p)!=0) { if(stdin_fd) {close(stdin_p[0]);close(stdin_p[1]);} close(stdout_p[0]);close(stdout_p[1]); return -1; } if(stderr_fd && pipe(stderr_p)!=0) { if(stdin_fd) {close(stdin_p[0]);close(stdin_p[1]);} if(stdout_fd) {close(stdout_p[0]);close(stdout_p[1]);} close(stderr_p[0]);close(stderr_p[1]); return -1; } id_type pid = fork(); if (pid < 0) { if(stdin_fd) {close(stdin_p[0]);close(stdin_p[1]);} if(stdout_fd) {close(stdout_p[0]);close(stdout_p[1]);} if(stderr_fd) {close(stderr_p[0]);close(stderr_p[1]);} return pid; } else if (pid == 0) { if(stdin_fd) dup2(stdin_p[0], 0); if(stdout_fd) dup2(stdout_p[1], 1); if(stderr_fd) dup2(stderr_p[1], 2); if(stdin_fd) {close(stdin_p[0]);close(stdin_p[1]);} if(stdout_fd) {close(stdout_p[0]);close(stdout_p[1]);} if(stderr_fd) {close(stderr_p[0]);close(stderr_p[1]);} //Based on http://stackoverflow.com/a/899533/3808293 int fd_max=sysconf(_SC_OPEN_MAX); for(int fd=3;fd<fd_max;fd++) close(fd); setpgid(0, 0); //TODO: See here on how to emulate tty for colors: http://stackoverflow.com/questions/1401002/trick-an-application-into-thinking-its-stdin-is-interactive-not-a-pipe //TODO: One solution is: echo "command;exit"|script -q /dev/null if(!path.empty()) { auto path_escaped=path; size_t pos=0; //Based on https://www.reddit.com/r/cpp/comments/3vpjqg/a_new_platform_independent_process_library_for_c11/cxsxyb7 while((pos=path_escaped.find('\'', pos))!=std::string::npos) { path_escaped.replace(pos, 1, "'\\''"); pos+=4; } execl("/bin/sh", "sh", "-c", ("cd '"+path_escaped+"' && "+command).c_str(), NULL); } else execl("/bin/sh", "sh", "-c", command.c_str(), NULL); _exit(EXIT_FAILURE); } if(stdin_fd) close(stdin_p[0]); if(stdout_fd) close(stdout_p[1]); if(stderr_fd) close(stderr_p[1]); if(stdin_fd) *stdin_fd = stdin_p[1]; if(stdout_fd) *stdout_fd = stdout_p[0]; if(stderr_fd) *stderr_fd = stderr_p[0]; closed=false; data.id=pid; return pid; } void Process::async_read() { if(data.id<=0) return; if(stdout_fd) { stdout_thread=std::thread([this](){ char buffer[buffer_size]; ssize_t n; while ((n=read(*stdout_fd, buffer, buffer_size)) > 0) read_stdout(buffer, static_cast<size_t>(n)); }); } if(stderr_fd) { stderr_thread=std::thread([this](){ char buffer[buffer_size]; ssize_t n; while ((n=read(*stderr_fd, buffer, buffer_size)) > 0) read_stderr(buffer, static_cast<size_t>(n)); }); } } int Process::get_exit_status() { if(data.id<=0) return -1; int exit_status; waitpid(data.id, &exit_status, 0); close_mutex.lock(); closed=true; close_mutex.unlock(); close_fds(); return exit_status; } void Process::close_fds() { if(stdout_thread.joinable()) stdout_thread.join(); if(stderr_thread.joinable()) stderr_thread.join(); if(stdin_fd) close_stdin(); if(stdout_fd) { close(*stdout_fd); stdout_fd.reset(); } if(stderr_fd) { close(*stderr_fd); stderr_fd.reset(); } } bool Process::write(const char *bytes, size_t n) { if(!open_stdin) throw std::invalid_argument("Can't write to an unopened stdin pipe. Please set open_stdin=true when constructing the process."); stdin_mutex.lock(); if(stdin_fd) { if(::write(*stdin_fd, bytes, n)>=0) { stdin_mutex.unlock(); return true; } else { stdin_mutex.unlock(); return false; } } stdin_mutex.unlock(); return false; } void Process::close_stdin() { stdin_mutex.lock(); if(stdin_fd) { close(*stdin_fd); stdin_fd.reset(); } stdin_mutex.unlock(); } void Process::kill(bool force) { close_mutex.lock(); if(data.id>0 && !closed) { if(force) ::kill(-data.id, SIGTERM); else ::kill(-data.id, SIGINT); } close_mutex.unlock(); } void Process::kill(id_type id, bool force) { if(id<=0) return; if(force) ::kill(-id, SIGTERM); else ::kill(-id, SIGINT); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: usrfld.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2004-08-23 08:42:14 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _USRFLD_HXX #define _USRFLD_HXX #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif #ifndef _FLDBAS_HXX #include "fldbas.hxx" #endif class SfxPoolItem; class SwCalc; class SwDoc; /*-------------------------------------------------------------------- Beschreibung: Benutzerfelder --------------------------------------------------------------------*/ class SW_DLLPUBLIC SwUserFieldType : public SwValueFieldType { BOOL bValidValue : 1; BOOL bDeleted : 1; double nValue; String aName; String aContent; USHORT nType; public: SwUserFieldType( SwDoc* pDocPtr, const String& ); virtual const String& GetName() const; virtual SwFieldType* Copy() const; String Expand(ULONG nFmt, USHORT nSubType, USHORT nLng); String GetContent( ULONG nFmt = 0 ); void SetContent( const String& rStr, ULONG nFmt = 0 ); void CtrlSetContent( const String& rStr ); inline BOOL IsValid() const; inline void ChgValid( BOOL bNew ); virtual void Modify( SfxPoolItem* pOld, SfxPoolItem* pNew ); double GetValue(SwCalc& rCalc); // Member nValue neu berrechnen inline double GetValue() const; inline void SetValue(const double nVal); inline USHORT GetType() const; inline void SetType(USHORT); BOOL IsDeleted() const { return bDeleted; } void SetDeleted( BOOL b ) { bDeleted = b; } virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMId ) const; virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMId ); }; inline BOOL SwUserFieldType::IsValid() const { return bValidValue; } inline void SwUserFieldType::ChgValid( BOOL bNew ) { bValidValue = bNew; } inline double SwUserFieldType::GetValue() const { return nValue; } inline void SwUserFieldType::SetValue(const double nVal) { nValue = nVal; } inline USHORT SwUserFieldType::GetType() const { return nType; } inline void SwUserFieldType::SetType(USHORT nSub) { nType = nSub; EnableFormat(!(nSub & GSE_STRING)); } /*-------------------------------------------------------------------- Beschreibung: Benutzerfelder --------------------------------------------------------------------*/ class SwUserField : public SwValueField { USHORT nSubType; public: SwUserField(SwUserFieldType*, USHORT nSub = 0, ULONG nFmt = 0); virtual USHORT GetSubType() const; virtual void SetSubType(USHORT nSub); virtual double GetValue() const; virtual void SetValue( const double& rVal ); virtual String Expand() const; virtual SwField* Copy() const; virtual String GetCntnt(BOOL bName = FALSE) const; // Name kann nicht geaendert werden virtual const String& GetPar1() const; // Inhalt virtual String GetPar2() const; virtual void SetPar2(const String& rStr); virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMId ) const; virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMId ); }; #endif // _USRFLD_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.3.596); FILE MERGED 2005/09/05 13:37:01 rt 1.3.596.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: usrfld.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 02:30:03 $ * * 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 _USRFLD_HXX #define _USRFLD_HXX #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif #ifndef _FLDBAS_HXX #include "fldbas.hxx" #endif class SfxPoolItem; class SwCalc; class SwDoc; /*-------------------------------------------------------------------- Beschreibung: Benutzerfelder --------------------------------------------------------------------*/ class SW_DLLPUBLIC SwUserFieldType : public SwValueFieldType { BOOL bValidValue : 1; BOOL bDeleted : 1; double nValue; String aName; String aContent; USHORT nType; public: SwUserFieldType( SwDoc* pDocPtr, const String& ); virtual const String& GetName() const; virtual SwFieldType* Copy() const; String Expand(ULONG nFmt, USHORT nSubType, USHORT nLng); String GetContent( ULONG nFmt = 0 ); void SetContent( const String& rStr, ULONG nFmt = 0 ); void CtrlSetContent( const String& rStr ); inline BOOL IsValid() const; inline void ChgValid( BOOL bNew ); virtual void Modify( SfxPoolItem* pOld, SfxPoolItem* pNew ); double GetValue(SwCalc& rCalc); // Member nValue neu berrechnen inline double GetValue() const; inline void SetValue(const double nVal); inline USHORT GetType() const; inline void SetType(USHORT); BOOL IsDeleted() const { return bDeleted; } void SetDeleted( BOOL b ) { bDeleted = b; } virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMId ) const; virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMId ); }; inline BOOL SwUserFieldType::IsValid() const { return bValidValue; } inline void SwUserFieldType::ChgValid( BOOL bNew ) { bValidValue = bNew; } inline double SwUserFieldType::GetValue() const { return nValue; } inline void SwUserFieldType::SetValue(const double nVal) { nValue = nVal; } inline USHORT SwUserFieldType::GetType() const { return nType; } inline void SwUserFieldType::SetType(USHORT nSub) { nType = nSub; EnableFormat(!(nSub & GSE_STRING)); } /*-------------------------------------------------------------------- Beschreibung: Benutzerfelder --------------------------------------------------------------------*/ class SwUserField : public SwValueField { USHORT nSubType; public: SwUserField(SwUserFieldType*, USHORT nSub = 0, ULONG nFmt = 0); virtual USHORT GetSubType() const; virtual void SetSubType(USHORT nSub); virtual double GetValue() const; virtual void SetValue( const double& rVal ); virtual String Expand() const; virtual SwField* Copy() const; virtual String GetCntnt(BOOL bName = FALSE) const; // Name kann nicht geaendert werden virtual const String& GetPar1() const; // Inhalt virtual String GetPar2() const; virtual void SetPar2(const String& rStr); virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMId ) const; virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMId ); }; #endif // _USRFLD_HXX <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <iostream> #include <fstream> #include "init.h" // for pwalletMain #include "bitcoinrpc.h" #include "ui_interface.h" #include "base58.h" #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/variant/get.hpp> #include <boost/algorithm/string.hpp> #define printf OutputDebugStringF using namespace json_spirit; using namespace std; void EnsureWalletIsUnlocked(); namespace bt = boost::posix_time; // Extended DecodeDumpTime implementation, see this page for details: // http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost const std::locale formats[] = { std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d")) }; const size_t formats_n = sizeof(formats)/sizeof(formats[0]); std::time_t pt_to_time_t(const bt::ptime& pt) { bt::ptime timet_start(boost::gregorian::date(1970,1,1)); bt::time_duration diff = pt - timet_start; return diff.ticks()/bt::time_duration::rep_type::ticks_per_second; } int64_t DecodeDumpTime(const std::string& s) { bt::ptime pt; for(size_t i=0; i<formats_n; ++i) { std::istringstream is(s); is.imbue(formats[i]); is >> pt; if(pt != bt::ptime()) break; } return pt_to_time_t(pt); } std::string static EncodeDumpTime(int64_t nTime) { return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime); } std::string static EncodeDumpString(const std::string &str) { std::stringstream ret; BOOST_FOREACH(unsigned char c, str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr(&c, &c + 1); } else { ret << c; } } return ret.str(); } std::string DecodeDumpString(const std::string &str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos+2 < str.length()) { c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) | ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15)); pos += 2; } ret << c; } return ret.str(); } class CTxDump { public: CBlockIndex *pindex; int64_t nValue; bool fSpent; CWalletTx* ptx; int nOut; CTxDump(CWalletTx* ptx = NULL, int nOut = -1) { pindex = NULL; nValue = 0; fSpent = false; this->ptx = ptx; this->nOut = nOut; } }; Value importprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "importprivkey <blackcoinprivkey> [label]\n" "Adds a private key (as returned by dumpprivkey) to your wallet."); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); CKey key; bool fCompressed; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); CKeyID vchAddress = key.GetPubKey().GetID(); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); pwalletMain->SetAddressBookName(vchAddress, strLabel); pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKey(key)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); pwalletMain->ReacceptWalletTransactions(); } return Value::null; } Value importwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "importwallet <filename>\n" "Imports keys from a wallet dump file (see dumpwallet)."); EnsureWalletIsUnlocked(); ifstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); int64_t nTimeBegin = pindexBest->nTime; bool fGood = true; while (file.good()) { std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(" ")); if (vstr.size() < 2) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(vstr[0])) continue; bool fCompressed; CKey key; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); CKeyID keyid = key.GetPubKey().GetID(); if (pwalletMain->HaveKey(keyid)) { printf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString().c_str()); continue; } int64_t nTime = DecodeDumpTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (boost::algorithm::starts_with(vstr[nStr], "#")) break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (boost::algorithm::starts_with(vstr[nStr], "label=")) { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } printf("Importing %s...\n", CBitcoinAddress(keyid).ToString().c_str()); if (!pwalletMain->AddKey(key)) { fGood = false; continue; } pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime; if (fLabel) pwalletMain->SetAddressBookName(keyid, strLabel); nTimeBegin = std::min(nTimeBegin, nTime); } file.close(); CBlockIndex *pindex = pindexBest; while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200) pindex = pindex->pprev; if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey) pwalletMain->nTimeFirstKey = nTimeBegin; printf("Rescanning last %i blocks\n", pindexBest->nHeight - pindex->nHeight + 1); pwalletMain->ScanForWalletTransactions(pindex); pwalletMain->ReacceptWalletTransactions(); pwalletMain->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet"); return Value::null; } Value dumpprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey <blackcoinaddress>\n" "Reveals the private key corresponding to <blackcoinaddress>."); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid BlackCoin address"); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CSecret vchSecret; bool fCompressed; if (!pwalletMain->GetSecret(keyID, vchSecret, fCompressed)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret, fCompressed).ToString(); } Value dumpwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpwallet <filename>\n" "Dumps all wallet keys in a human-readable format."); EnsureWalletIsUnlocked(); ofstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CKeyID, int64_t> mapKeyBirth; std::set<CKeyID> setKeyPool; pwalletMain->GetKeyBirthTimes(mapKeyBirth); pwalletMain->GetAllReserveKeys(setKeyPool); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) { vKeyBirth.push_back(std::make_pair(it->second, it->first)); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by BlackCoin %s (%s)\n", CLIENT_BUILD.c_str(), CLIENT_DATE.c_str()); file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()).c_str()); file << strprintf("# * Best block at time of backup was %i (%s),\n", nBestHeight, hashBestChain.ToString().c_str()); file << strprintf("# mined on %s\n", EncodeDumpTime(pindexBest->nTime).c_str()); file << "\n"; for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID &keyid = it->second; std::string strTime = EncodeDumpTime(it->first); std::string strAddr = CBitcoinAddress(keyid).ToString(); bool IsCompressed; CKey key; if (pwalletMain->GetKey(keyid, key)) { if (pwalletMain->mapAddressBook.count(keyid)) { CSecret secret = key.GetSecret(IsCompressed); file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString().c_str(), strTime.c_str(), EncodeDumpString(pwalletMain->mapAddressBook[keyid]).c_str(), strAddr.c_str()); } else if (setKeyPool.count(keyid)) { CSecret secret = key.GetSecret(IsCompressed); file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString().c_str(), strTime.c_str(), strAddr.c_str()); } else { CSecret secret = key.GetSecret(IsCompressed); file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString().c_str(), strTime.c_str(), strAddr.c_str()); } } } file << "\n"; file << "# End of dump\n"; file.close(); return Value::null; } <commit_msg>importprivkey: Don't throw error in case a key is already there<commit_after>// Copyright (c) 2009-2012 Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <iostream> #include <fstream> #include "init.h" // for pwalletMain #include "bitcoinrpc.h" #include "ui_interface.h" #include "base58.h" #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/variant/get.hpp> #include <boost/algorithm/string.hpp> #define printf OutputDebugStringF using namespace json_spirit; using namespace std; void EnsureWalletIsUnlocked(); namespace bt = boost::posix_time; // Extended DecodeDumpTime implementation, see this page for details: // http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost const std::locale formats[] = { std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d")) }; const size_t formats_n = sizeof(formats)/sizeof(formats[0]); std::time_t pt_to_time_t(const bt::ptime& pt) { bt::ptime timet_start(boost::gregorian::date(1970,1,1)); bt::time_duration diff = pt - timet_start; return diff.ticks()/bt::time_duration::rep_type::ticks_per_second; } int64_t DecodeDumpTime(const std::string& s) { bt::ptime pt; for(size_t i=0; i<formats_n; ++i) { std::istringstream is(s); is.imbue(formats[i]); is >> pt; if(pt != bt::ptime()) break; } return pt_to_time_t(pt); } std::string static EncodeDumpTime(int64_t nTime) { return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime); } std::string static EncodeDumpString(const std::string &str) { std::stringstream ret; BOOST_FOREACH(unsigned char c, str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr(&c, &c + 1); } else { ret << c; } } return ret.str(); } std::string DecodeDumpString(const std::string &str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos+2 < str.length()) { c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) | ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15)); pos += 2; } ret << c; } return ret.str(); } class CTxDump { public: CBlockIndex *pindex; int64_t nValue; bool fSpent; CWalletTx* ptx; int nOut; CTxDump(CWalletTx* ptx = NULL, int nOut = -1) { pindex = NULL; nValue = 0; fSpent = false; this->ptx = ptx; this->nOut = nOut; } }; Value importprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "importprivkey <blackcoinprivkey> [label]\n" "Adds a private key (as returned by dumpprivkey) to your wallet."); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); CKey key; bool fCompressed; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); CKeyID vchAddress = key.GetPubKey().GetID(); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); pwalletMain->SetAddressBookName(vchAddress, strLabel); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) return Value::null; pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKey(key)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); pwalletMain->ReacceptWalletTransactions(); } return Value::null; } Value importwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "importwallet <filename>\n" "Imports keys from a wallet dump file (see dumpwallet)."); EnsureWalletIsUnlocked(); ifstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); int64_t nTimeBegin = pindexBest->nTime; bool fGood = true; while (file.good()) { std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(" ")); if (vstr.size() < 2) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(vstr[0])) continue; bool fCompressed; CKey key; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); CKeyID keyid = key.GetPubKey().GetID(); if (pwalletMain->HaveKey(keyid)) { printf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString().c_str()); continue; } int64_t nTime = DecodeDumpTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (boost::algorithm::starts_with(vstr[nStr], "#")) break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (boost::algorithm::starts_with(vstr[nStr], "label=")) { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } printf("Importing %s...\n", CBitcoinAddress(keyid).ToString().c_str()); if (!pwalletMain->AddKey(key)) { fGood = false; continue; } pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime; if (fLabel) pwalletMain->SetAddressBookName(keyid, strLabel); nTimeBegin = std::min(nTimeBegin, nTime); } file.close(); CBlockIndex *pindex = pindexBest; while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200) pindex = pindex->pprev; if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey) pwalletMain->nTimeFirstKey = nTimeBegin; printf("Rescanning last %i blocks\n", pindexBest->nHeight - pindex->nHeight + 1); pwalletMain->ScanForWalletTransactions(pindex); pwalletMain->ReacceptWalletTransactions(); pwalletMain->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet"); return Value::null; } Value dumpprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey <blackcoinaddress>\n" "Reveals the private key corresponding to <blackcoinaddress>."); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid BlackCoin address"); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CSecret vchSecret; bool fCompressed; if (!pwalletMain->GetSecret(keyID, vchSecret, fCompressed)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret, fCompressed).ToString(); } Value dumpwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpwallet <filename>\n" "Dumps all wallet keys in a human-readable format."); EnsureWalletIsUnlocked(); ofstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CKeyID, int64_t> mapKeyBirth; std::set<CKeyID> setKeyPool; pwalletMain->GetKeyBirthTimes(mapKeyBirth); pwalletMain->GetAllReserveKeys(setKeyPool); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) { vKeyBirth.push_back(std::make_pair(it->second, it->first)); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by BlackCoin %s (%s)\n", CLIENT_BUILD.c_str(), CLIENT_DATE.c_str()); file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()).c_str()); file << strprintf("# * Best block at time of backup was %i (%s),\n", nBestHeight, hashBestChain.ToString().c_str()); file << strprintf("# mined on %s\n", EncodeDumpTime(pindexBest->nTime).c_str()); file << "\n"; for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID &keyid = it->second; std::string strTime = EncodeDumpTime(it->first); std::string strAddr = CBitcoinAddress(keyid).ToString(); bool IsCompressed; CKey key; if (pwalletMain->GetKey(keyid, key)) { if (pwalletMain->mapAddressBook.count(keyid)) { CSecret secret = key.GetSecret(IsCompressed); file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString().c_str(), strTime.c_str(), EncodeDumpString(pwalletMain->mapAddressBook[keyid]).c_str(), strAddr.c_str()); } else if (setKeyPool.count(keyid)) { CSecret secret = key.GetSecret(IsCompressed); file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString().c_str(), strTime.c_str(), strAddr.c_str()); } else { CSecret secret = key.GetSecret(IsCompressed); file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString().c_str(), strTime.c_str(), strAddr.c_str()); } } } file << "\n"; file << "# End of dump\n"; file.close(); return Value::null; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 Bitcoin Developers // Copyright (c) 2012-2015 The Peercoin developers // Copyright (c) 2014-2015 The Paycoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" // for pwalletMain #include "bitcoinrpc.h" #include "ui_interface.h" #include "base58.h" #include <boost/lexical_cast.hpp> #include "json/json_spirit_reader_template.h" #include "json/json_spirit_writer_template.h" #include "json/json_spirit_utils.h" #define printf OutputDebugStringF // using namespace boost::asio; using namespace json_spirit; using namespace std; extern Object JSONRPCError(int code, const string& message); class CTxDump { public: CBlockIndex *pindex; int64 nValue; bool fSpent; CWalletTx* ptx; int nOut; CTxDump(CWalletTx* ptx = NULL, int nOut = -1) { pindex = NULL; nValue = 0; fSpent = false; this->ptx = ptx; this->nOut = nOut; } }; Value importprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "importprivkey <paycoinprivkey> [label]\n" "Adds a private key (as returned by dumpprivkey) to your wallet."); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(-5,"Invalid private key"); if (pwalletMain->IsLocked()) throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first."); if (fWalletUnlockMintOnly) // paycoin: no importprivkey in mint-only mode throw JSONRPCError(-102, "Wallet is unlocked for minting only."); CKey key; bool fCompressed; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); CKeyID vchAddress = key.GetPubKey().GetID(); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); pwalletMain->SetAddressBookName(vchAddress, strLabel); if (!pwalletMain->AddKey(key)) throw JSONRPCError(-4,"Error adding key to wallet"); pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); pwalletMain->ReacceptWalletTransactions(); } MainFrameRepaint(); return Value::null; } Value dumpprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey <paycoinaddress>\n" "Reveals the private key corresponding to <paycoinaddress>."); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(-5, "Invalid Paycoin address"); if (pwalletMain->IsLocked()) throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first."); if (fWalletUnlockMintOnly) // paycoin: no dumpprivkey in mint-only mode throw JSONRPCError(-102, "Wallet is unlocked for minting only."); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(-3, "Address does not refer to a key"); CSecret vchSecret; bool fCompressed; if (!pwalletMain->GetSecret(keyID, vchSecret, fCompressed)) throw JSONRPCError(-4,"Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret, fCompressed).ToString(); } <commit_msg>Make rpcdump commands more informative with wallets unlocked for minting<commit_after>// Copyright (c) 2009-2012 Bitcoin Developers // Copyright (c) 2012-2015 The Peercoin developers // Copyright (c) 2014-2015 The Paycoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" // for pwalletMain #include "bitcoinrpc.h" #include "ui_interface.h" #include "base58.h" #include <boost/lexical_cast.hpp> #include "json/json_spirit_reader_template.h" #include "json/json_spirit_writer_template.h" #include "json/json_spirit_utils.h" #define printf OutputDebugStringF // using namespace boost::asio; using namespace json_spirit; using namespace std; extern Object JSONRPCError(int code, const string& message); class CTxDump { public: CBlockIndex *pindex; int64 nValue; bool fSpent; CWalletTx* ptx; int nOut; CTxDump(CWalletTx* ptx = NULL, int nOut = -1) { pindex = NULL; nValue = 0; fSpent = false; this->ptx = ptx; this->nOut = nOut; } }; Value importprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "importprivkey <paycoinprivkey> [label]\n" "Adds a private key (as returned by dumpprivkey) to your wallet."); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(-5,"Invalid private key"); if (pwalletMain->IsLocked()) throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first."); if (fWalletUnlockMintOnly) // paycoin: no importprivkey in mint-only mode throw JSONRPCError(-102, "Wallet is unlocked for minting only (unlock with walletpassphrase)."); CKey key; bool fCompressed; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); CKeyID vchAddress = key.GetPubKey().GetID(); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); pwalletMain->SetAddressBookName(vchAddress, strLabel); if (!pwalletMain->AddKey(key)) throw JSONRPCError(-4,"Error adding key to wallet"); pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); pwalletMain->ReacceptWalletTransactions(); } MainFrameRepaint(); return Value::null; } Value dumpprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey <paycoinaddress>\n" "Reveals the private key corresponding to <paycoinaddress>."); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(-5, "Invalid Paycoin address"); if (pwalletMain->IsLocked()) throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first."); if (fWalletUnlockMintOnly) // paycoin: no dumpprivkey in mint-only mode throw JSONRPCError(-102, "Wallet is unlocked for minting only (unlock with walletpassphrase)."); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(-3, "Address does not refer to a key"); CSecret vchSecret; bool fCompressed; if (!pwalletMain->GetSecret(keyID, vchSecret, fCompressed)) throw JSONRPCError(-4,"Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret, fCompressed).ToString(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: formatclipboard.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: kz $ $Date: 2006-12-12 17:12:52 $ * * 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_sd.hxx" #include "formatclipboard.hxx" #ifndef _E3D_GLOBL3D_HXX #include <svx/globl3d.hxx> #endif // header for class SfxItemIter #ifndef _SFXITEMITER_HXX #include <svtools/itemiter.hxx> #endif // header for class SfxStyleSheet #ifndef _SFXSTYLE_HXX #include <svtools/style.hxx> #endif /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ SdFormatClipboard::SdFormatClipboard() : m_pItemSet(0) , m_bPersistentCopy(false) , m_nType_Inventor(0) , m_nType_Identifier(0) { } SdFormatClipboard::~SdFormatClipboard() { if(m_pItemSet) delete m_pItemSet; } bool SdFormatClipboard::HasContent() const { return m_pItemSet!=0; } bool SdFormatClipboard::CanCopyThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const { if( nObjectInventor != SdrInventor && nObjectInventor != E3dInventor ) return false; switch(nObjectIdentifier) { case OBJ_NONE: case OBJ_GRUP: return false; case OBJ_LINE: case OBJ_RECT: case OBJ_CIRC: case OBJ_SECT: case OBJ_CARC: case OBJ_CCUT: case OBJ_POLY: case OBJ_PLIN: case OBJ_PATHLINE: case OBJ_PATHFILL: case OBJ_FREELINE: case OBJ_FREEFILL: case OBJ_SPLNLINE: case OBJ_SPLNFILL: case OBJ_TEXT: case OBJ_TEXTEXT: case OBJ_TITLETEXT: return true; case OBJ_OUTLINETEXT: case OBJ_GRAF: case OBJ_OLE2: case OBJ_EDGE: case OBJ_CAPTION: return false; case OBJ_PATHPOLY: case OBJ_PATHPLIN: return true; case OBJ_PAGE: case OBJ_MEASURE: case OBJ_DUMMY: case OBJ_FRAME: case OBJ_UNO: return false; case OBJ_CUSTOMSHAPE: return true; default: return false; } } bool SdFormatClipboard::HasContentForThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const { if( !HasContent() ) return false; if( !CanCopyThisType( nObjectInventor, nObjectIdentifier ) ) return false; return true; } void SdFormatClipboard::Copy( ::sd::View& rDrawView, bool bPersistentCopy ) { this->Erase(); m_bPersistentCopy = bPersistentCopy; const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList(); if( rMarkList.GetMarkCount() >= 1 ) { BOOL bOnlyHardAttr = FALSE; m_pItemSet = new SfxItemSet( rDrawView.GetAttrFromMarked(bOnlyHardAttr) ); SdrObject* pObj = rMarkList.GetMark(0)->GetMarkedSdrObj(); m_nType_Inventor = pObj->GetObjInventor(); m_nType_Identifier = pObj->GetObjIdentifier(); } } void SdFormatClipboard::Paste( ::sd::View& rDrawView, bool, bool ) { if( !rDrawView.AreObjectsMarked() ) { if(!m_bPersistentCopy) this->Erase(); return; } SdrObject* pObj = 0; bool bWrongTargetType = false; { const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList(); if( rMarkList.GetMarkCount() != 1 ) bWrongTargetType = true; else { pObj = rMarkList.GetMark(0)->GetMarkedSdrObj(); if( pObj && pObj->GetStyleSheet() ) bWrongTargetType = !this->HasContentForThisType( pObj->GetObjInventor(), pObj->GetObjIdentifier() ); } } if( bWrongTargetType ) { if(!m_bPersistentCopy) this->Erase(); return; } if(m_pItemSet) { //modify source itemset { SfxItemSet aTargetSet( pObj->GetStyleSheet()->GetItemSet() ); USHORT nWhich=0; SfxItemState nSourceState; SfxItemState nTargetState; const SfxPoolItem* pSourceItem=0; const SfxPoolItem* pTargetItem=0; SfxItemIter aSourceIter(*m_pItemSet); pSourceItem = aSourceIter.FirstItem(); while( pSourceItem!=NULL ) { if (!IsInvalidItem(pSourceItem)) { nWhich = pSourceItem->Which(); if(nWhich) { nSourceState = m_pItemSet->GetItemState( nWhich ); nTargetState = aTargetSet.GetItemState( nWhich ); pTargetItem = aTargetSet.GetItem( nWhich ); ::com::sun::star::uno::Any aSourceValue, aTargetValue; if(!pTargetItem) m_pItemSet->ClearItem(nWhich); else if( (*pSourceItem) == (*pTargetItem) ) { //do not set items which have the same content in source and target m_pItemSet->ClearItem(nWhich); } } } pSourceItem = aSourceIter.NextItem(); }//end while } BOOL bReplaceAll = TRUE; rDrawView.SetAttrToMarked(*m_pItemSet, bReplaceAll); } if(!m_bPersistentCopy) this->Erase(); } void SdFormatClipboard::Erase() { if(m_pItemSet) { delete m_pItemSet; m_pItemSet = 0; } m_nType_Inventor=0; m_nType_Identifier=0; m_bPersistentCopy = false; } <commit_msg>INTEGRATION: CWS changefileheader (1.8.298); FILE MERGED 2008/04/01 15:34:25 thb 1.8.298.2: #i85898# Stripping all external header guards 2008/03/31 13:57:59 rt 1.8.298.1: #i87441# Change license header to LPGL v3.<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: formatclipboard.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_sd.hxx" #include "formatclipboard.hxx" #include <svx/globl3d.hxx> // header for class SfxItemIter #include <svtools/itemiter.hxx> // header for class SfxStyleSheet #include <svtools/style.hxx> /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ SdFormatClipboard::SdFormatClipboard() : m_pItemSet(0) , m_bPersistentCopy(false) , m_nType_Inventor(0) , m_nType_Identifier(0) { } SdFormatClipboard::~SdFormatClipboard() { if(m_pItemSet) delete m_pItemSet; } bool SdFormatClipboard::HasContent() const { return m_pItemSet!=0; } bool SdFormatClipboard::CanCopyThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const { if( nObjectInventor != SdrInventor && nObjectInventor != E3dInventor ) return false; switch(nObjectIdentifier) { case OBJ_NONE: case OBJ_GRUP: return false; case OBJ_LINE: case OBJ_RECT: case OBJ_CIRC: case OBJ_SECT: case OBJ_CARC: case OBJ_CCUT: case OBJ_POLY: case OBJ_PLIN: case OBJ_PATHLINE: case OBJ_PATHFILL: case OBJ_FREELINE: case OBJ_FREEFILL: case OBJ_SPLNLINE: case OBJ_SPLNFILL: case OBJ_TEXT: case OBJ_TEXTEXT: case OBJ_TITLETEXT: return true; case OBJ_OUTLINETEXT: case OBJ_GRAF: case OBJ_OLE2: case OBJ_EDGE: case OBJ_CAPTION: return false; case OBJ_PATHPOLY: case OBJ_PATHPLIN: return true; case OBJ_PAGE: case OBJ_MEASURE: case OBJ_DUMMY: case OBJ_FRAME: case OBJ_UNO: return false; case OBJ_CUSTOMSHAPE: return true; default: return false; } } bool SdFormatClipboard::HasContentForThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const { if( !HasContent() ) return false; if( !CanCopyThisType( nObjectInventor, nObjectIdentifier ) ) return false; return true; } void SdFormatClipboard::Copy( ::sd::View& rDrawView, bool bPersistentCopy ) { this->Erase(); m_bPersistentCopy = bPersistentCopy; const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList(); if( rMarkList.GetMarkCount() >= 1 ) { BOOL bOnlyHardAttr = FALSE; m_pItemSet = new SfxItemSet( rDrawView.GetAttrFromMarked(bOnlyHardAttr) ); SdrObject* pObj = rMarkList.GetMark(0)->GetMarkedSdrObj(); m_nType_Inventor = pObj->GetObjInventor(); m_nType_Identifier = pObj->GetObjIdentifier(); } } void SdFormatClipboard::Paste( ::sd::View& rDrawView, bool, bool ) { if( !rDrawView.AreObjectsMarked() ) { if(!m_bPersistentCopy) this->Erase(); return; } SdrObject* pObj = 0; bool bWrongTargetType = false; { const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList(); if( rMarkList.GetMarkCount() != 1 ) bWrongTargetType = true; else { pObj = rMarkList.GetMark(0)->GetMarkedSdrObj(); if( pObj && pObj->GetStyleSheet() ) bWrongTargetType = !this->HasContentForThisType( pObj->GetObjInventor(), pObj->GetObjIdentifier() ); } } if( bWrongTargetType ) { if(!m_bPersistentCopy) this->Erase(); return; } if(m_pItemSet) { //modify source itemset { SfxItemSet aTargetSet( pObj->GetStyleSheet()->GetItemSet() ); USHORT nWhich=0; SfxItemState nSourceState; SfxItemState nTargetState; const SfxPoolItem* pSourceItem=0; const SfxPoolItem* pTargetItem=0; SfxItemIter aSourceIter(*m_pItemSet); pSourceItem = aSourceIter.FirstItem(); while( pSourceItem!=NULL ) { if (!IsInvalidItem(pSourceItem)) { nWhich = pSourceItem->Which(); if(nWhich) { nSourceState = m_pItemSet->GetItemState( nWhich ); nTargetState = aTargetSet.GetItemState( nWhich ); pTargetItem = aTargetSet.GetItem( nWhich ); ::com::sun::star::uno::Any aSourceValue, aTargetValue; if(!pTargetItem) m_pItemSet->ClearItem(nWhich); else if( (*pSourceItem) == (*pTargetItem) ) { //do not set items which have the same content in source and target m_pItemSet->ClearItem(nWhich); } } } pSourceItem = aSourceIter.NextItem(); }//end while } BOOL bReplaceAll = TRUE; rDrawView.SetAttrToMarked(*m_pItemSet, bReplaceAll); } if(!m_bPersistentCopy) this->Erase(); } void SdFormatClipboard::Erase() { if(m_pItemSet) { delete m_pItemSet; m_pItemSet = 0; } m_nType_Inventor=0; m_nType_Identifier=0; m_bPersistentCopy = false; } <|endoftext|>
<commit_before>/* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post Copyright (C) 2014-2015 Pedro Côrte-Real Copyright (C) 2017 Roman Lebedev 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 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "decompressors/OlympusDecompressor.h" #include "common/Common.h" // for uint32, ushort16, uchar8 #include "common/Point.h" // for iPoint2D #include "common/RawImage.h" // for RawImage, RawImageData #include "decoders/RawDecoderException.h" // for ThrowRDE #include "io/BitPumpMSB.h" // for BitPumpMSB #include "io/ByteStream.h" // for ByteStream #include <algorithm> // for min #include <array> // for array, array<>::value_type #include <cassert> // for assert #include <cmath> // for abs #include <cstdlib> // for abs #include <memory> // for unique_ptr #include <type_traits> // for enable_if_t, is_integral namespace { // Normally, we'd just use std::signbit(int) here. But, some (non-conforming?) // compilers do not provide that overload, so the code simply fails to compile. // One could cast the int to the double, but at least right now that results // in a horrible code. So let's just provide our own signbit(). It compiles to // the exact same code as the std::signbit(int). template <typename T, typename = std::enable_if_t<std::is_integral<T>::value>> constexpr __attribute__((const)) bool SignBit(T x) { return x < 0; } } // namespace namespace rawspeed { OlympusDecompressor::OlympusDecompressor(const RawImage& img) : mRaw(img) { if (mRaw->getCpp() != 1 || mRaw->getDataType() != TYPE_USHORT16 || mRaw->getBpp() != 2) ThrowRDE("Unexpected component count / data type"); const uint32 w = mRaw->dim.x; const uint32 h = mRaw->dim.y; if (w == 0 || h == 0 || w % 2 != 0 || w > 10400 || h > 7792) ThrowRDE("Unexpected image dimensions found: (%u; %u)", w, h); } /* This is probably the slowest decoder of them all. * I cannot see any way to effectively speed up the prediction * phase, which is by far the slowest part of this algorithm. * Also there is no way to multithread this code, since prediction * is based on the output of all previous pixel (bar the first four) */ void OlympusDecompressor::decompress(ByteStream input) const { assert(mRaw->dim.y > 0); assert(mRaw->dim.x > 0); assert(mRaw->dim.x % 2 == 0); uchar8* data = mRaw->getData(); int pitch = mRaw->pitch; /* Build a table to quickly look up "high" value */ std::unique_ptr<char[]> bittable(new char[4096]); // NOLINT for (int i = 0; i < 4096; i++) { int b = i; int high; for (high = 0; high < 12; high++) if ((b >> (11 - high)) & 1) break; bittable[i] = std::min(12, high); } input.skipBytes(7); BitPumpMSB bits(input); for (uint32 y = 0; y < static_cast<uint32>(mRaw->dim.y); y++) { std::array<std::array<int, 3>, 2> acarry{{}}; std::array<int, 2> left{{}}; std::array<int, 2> nw{{}}; auto* dest = reinterpret_cast<ushort16*>(&data[y * pitch]); bool y_border = y < 2; bool border = true; for (uint32 x = 0; x < static_cast<uint32>(mRaw->dim.x); x++) { int c = x & 1; bits.fill(); int i = 2 * (acarry[c][2] < 3); int nbits; for (nbits = 2 + i; static_cast<ushort16>(acarry[c][0]) >> (nbits + i); nbits++) ; int b = bits.peekBitsNoFill(15); int sign = (b >> 14) * -1; int low = (b >> 12) & 3; int high = bittable[b & 4095]; // Skip bytes used above or read bits if (high == 12) { bits.skipBitsNoFill(15); high = bits.getBits(16 - nbits) >> 1; } else bits.skipBitsNoFill(high + 1 + 3); acarry[c][0] = (high << nbits) | bits.getBits(nbits); int diff = (acarry[c][0] ^ sign) + acarry[c][1]; acarry[c][1] = (diff * 3 + acarry[c][1]) >> 5; acarry[c][2] = acarry[c][0] > 16 ? 0 : acarry[c][2] + 1; int pred; if (border) { if (y_border && x < 2) pred = 0; else { if (y_border) pred = left[c]; else { pred = dest[-pitch + (static_cast<int>(x))]; nw[c] = pred; } } } else { // Have local variables for values used several tiles // (having a "ushort16 *dst_up" that caches dest[-pitch+((int)x)] is // actually slower, probably stack spill or aliasing) int up = dest[-pitch + (static_cast<int>(x))]; int leftMinusNw = left[c] - nw[c]; int upMinusNw = up - nw[c]; // Check if sign is different, and they are both not zero if ((SignBit(leftMinusNw) ^ SignBit(upMinusNw)) && (leftMinusNw != 0 && upMinusNw != 0)) { if (std::abs(leftMinusNw) > 32 || std::abs(upMinusNw) > 32) pred = left[c] + upMinusNw; else pred = (left[c] + up) >> 1; } else pred = std::abs(leftMinusNw) > std::abs(upMinusNw) ? left[c] : up; nw[c] = up; } // Set predictor left[c] = pred + ((diff * 4) | low); // Set the pixel dest[x] = left[c]; if (c) border = y_border; } } } } // namespace rawspeed <commit_msg>OlympusDecompressor: cache the acarry 'color' to be used<commit_after>/* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post Copyright (C) 2014-2015 Pedro Côrte-Real Copyright (C) 2017 Roman Lebedev 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 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "decompressors/OlympusDecompressor.h" #include "common/Common.h" // for uint32, ushort16, uchar8 #include "common/Point.h" // for iPoint2D #include "common/RawImage.h" // for RawImage, RawImageData #include "decoders/RawDecoderException.h" // for ThrowRDE #include "io/BitPumpMSB.h" // for BitPumpMSB #include "io/ByteStream.h" // for ByteStream #include <algorithm> // for min #include <array> // for array, array<>::value_type #include <cassert> // for assert #include <cmath> // for abs #include <cstdlib> // for abs #include <memory> // for unique_ptr #include <type_traits> // for enable_if_t, is_integral namespace { // Normally, we'd just use std::signbit(int) here. But, some (non-conforming?) // compilers do not provide that overload, so the code simply fails to compile. // One could cast the int to the double, but at least right now that results // in a horrible code. So let's just provide our own signbit(). It compiles to // the exact same code as the std::signbit(int). template <typename T, typename = std::enable_if_t<std::is_integral<T>::value>> constexpr __attribute__((const)) bool SignBit(T x) { return x < 0; } } // namespace namespace rawspeed { OlympusDecompressor::OlympusDecompressor(const RawImage& img) : mRaw(img) { if (mRaw->getCpp() != 1 || mRaw->getDataType() != TYPE_USHORT16 || mRaw->getBpp() != 2) ThrowRDE("Unexpected component count / data type"); const uint32 w = mRaw->dim.x; const uint32 h = mRaw->dim.y; if (w == 0 || h == 0 || w % 2 != 0 || w > 10400 || h > 7792) ThrowRDE("Unexpected image dimensions found: (%u; %u)", w, h); } /* This is probably the slowest decoder of them all. * I cannot see any way to effectively speed up the prediction * phase, which is by far the slowest part of this algorithm. * Also there is no way to multithread this code, since prediction * is based on the output of all previous pixel (bar the first four) */ void OlympusDecompressor::decompress(ByteStream input) const { assert(mRaw->dim.y > 0); assert(mRaw->dim.x > 0); assert(mRaw->dim.x % 2 == 0); uchar8* data = mRaw->getData(); int pitch = mRaw->pitch; /* Build a table to quickly look up "high" value */ std::unique_ptr<char[]> bittable(new char[4096]); // NOLINT for (int i = 0; i < 4096; i++) { int b = i; int high; for (high = 0; high < 12; high++) if ((b >> (11 - high)) & 1) break; bittable[i] = std::min(12, high); } input.skipBytes(7); BitPumpMSB bits(input); for (uint32 y = 0; y < static_cast<uint32>(mRaw->dim.y); y++) { std::array<std::array<int, 3>, 2> acarry{{}}; std::array<int, 2> left{{}}; std::array<int, 2> nw{{}}; auto* dest = reinterpret_cast<ushort16*>(&data[y * pitch]); bool y_border = y < 2; bool border = true; for (uint32 x = 0; x < static_cast<uint32>(mRaw->dim.x); x++) { int c = x & 1; std::array<int, 3>& carry = acarry[c]; bits.fill(); int i = 2 * (carry[2] < 3); int nbits; for (nbits = 2 + i; static_cast<ushort16>(carry[0]) >> (nbits + i); nbits++) ; int b = bits.peekBitsNoFill(15); int sign = (b >> 14) * -1; int low = (b >> 12) & 3; int high = bittable[b & 4095]; // Skip bytes used above or read bits if (high == 12) { bits.skipBitsNoFill(15); high = bits.getBits(16 - nbits) >> 1; } else bits.skipBitsNoFill(high + 1 + 3); carry[0] = (high << nbits) | bits.getBits(nbits); int diff = (carry[0] ^ sign) + carry[1]; carry[1] = (diff * 3 + carry[1]) >> 5; carry[2] = carry[0] > 16 ? 0 : carry[2] + 1; int pred; if (border) { if (y_border && x < 2) pred = 0; else { if (y_border) pred = left[c]; else { pred = dest[-pitch + (static_cast<int>(x))]; nw[c] = pred; } } } else { // Have local variables for values used several tiles // (having a "ushort16 *dst_up" that caches dest[-pitch+((int)x)] is // actually slower, probably stack spill or aliasing) int up = dest[-pitch + (static_cast<int>(x))]; int leftMinusNw = left[c] - nw[c]; int upMinusNw = up - nw[c]; // Check if sign is different, and they are both not zero if ((SignBit(leftMinusNw) ^ SignBit(upMinusNw)) && (leftMinusNw != 0 && upMinusNw != 0)) { if (std::abs(leftMinusNw) > 32 || std::abs(upMinusNw) > 32) pred = left[c] + upMinusNw; else pred = (left[c] + up) >> 1; } else pred = std::abs(leftMinusNw) > std::abs(upMinusNw) ? left[c] : up; nw[c] = up; } // Set predictor left[c] = pred + ((diff * 4) | low); // Set the pixel dest[x] = left[c]; if (c) border = y_border; } } } } // namespace rawspeed <|endoftext|>
<commit_before>/* * Copyright (C) 2013 midnightBITS * * 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 "pch.h" #include "settings.hpp" namespace FastCGI { namespace app { namespace reader { class ProfileSettingsPageHandler : public SettingsPageHandler { public: DEBUG_NAME("Settings: Profile"); protected: void prerender(const SessionPtr& session, Request& request, PageTranslation& tr) override { if (request.getVariable("close")) onPageDone(request); auto content = std::make_shared<settings::SectionForm>(settings::PAGE::PROFILE); request.setContent(content); std::string url = "/auth/change"; auto here_uri = request.getParam("DOCUMENT_URI"); if (here_uri) url += "?continue=" + url::encode(request.serverUri(here_uri, false)); auto& signin = content->section(tr(lng::LNG_SETTINGS_PROFILE_SEC_SIGNIN)); auto& name = content->section(tr(lng::LNG_SETTINGS_PROFILE_SEC_NAME)); content->buttons().submit("submit", tr(lng::LNG_CMD_UPDATE)); content->buttons().submit("close", tr(lng::LNG_CMD_CLOSE), ButtonType::Narrow); signin.text("login-text", tr(lng::LNG_LOGIN_USERNAME)); signin.text("pass-word", tr(lng::LNG_LOGIN_PASSWORD), true, tr(lng::LNG_SETTINGS_PROFILE_PASSWORD_MAIL_HINT)); signin.text("email", tr(lng::LNG_SETTINGS_PROFILE_EMAIL)); signin.link("pass", url, tr(lng::LNG_SETTINGS_PROFILE_CHANGE_PASSWORD)); Options opts; opts.add("0", tr(lng::LNG_SETTINGS_PROFILE_DISPLAY_NAME_CUSTOM)) .add("1", tr(lng::LNG_SETTINGS_PROFILE_DISPLAY_NAME_ORIGINAL)) .add("2", tr(lng::LNG_SETTINGS_PROFILE_DISPLAY_NAME_NAME)) .add("3", tr(lng::LNG_SETTINGS_PROFILE_DISPLAY_NAME_FAMILY_NAME)) .add("4", tr(lng::LNG_SETTINGS_PROFILE_DISPLAY_NAME_NFN)) .add("5", tr(lng::LNG_SETTINGS_PROFILE_DISPLAY_NAME_FNN)) .add("6", tr(lng::LNG_SETTINGS_PROFILE_DISPLAY_NAME_NCFN)) .add("7", tr(lng::LNG_SETTINGS_PROFILE_DISPLAY_NAME_FNCN)); name.text("name", tr(lng::LNG_SETTINGS_PROFILE_NAME)); name.text("family_name", tr(lng::LNG_SETTINGS_PROFILE_FAMILY_NAME)); name.selection("display_name", tr(lng::LNG_SETTINGS_PROFILE_DISPLAY_NAME), opts); name.text("custom", std::string()); if (true) { auto& avatar = content->section(tr(lng::LNG_SETTINGS_PROFILE_SEC_AVATAR)); auto engines = avatar.radio_group("avatar", tr(lng::LNG_SETTINGS_PROFILE_WHICH_AVATAR)); // TODO: actually enumerate available engines struct { const char* id; const char* name; const char* url; } avatar_engines[] = { { "gravatar", "Gravatar", "https://www.gravatar.com/" } }; engines->radio("", tr(lng::LNG_SETTINGS_PROFILE_AVATAR_NONE)); for (auto&& engine : avatar_engines) { engines->radio(engine.id, tr(lng::LNG_SETTINGS_PROFILE_USE_AVATAR_FROM, engine.name, engine.url)); } } } }; }}} // FastCGI::app::reader REGISTER_HANDLER("/settings/profile", FastCGI::app::reader::ProfileSettingsPageHandler); <commit_msg>Enumerating known avatar engines<commit_after>/* * Copyright (C) 2013 midnightBITS * * 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 "pch.h" #include "settings.hpp" #include "avatar.hpp" namespace FastCGI { namespace app { namespace reader { class ProfileSettingsPageHandler : public SettingsPageHandler { public: DEBUG_NAME("Settings: Profile"); protected: void prerender(const SessionPtr& session, Request& request, PageTranslation& tr) override { if (request.getVariable("close")) onPageDone(request); auto content = std::make_shared<settings::SectionForm>(settings::PAGE::PROFILE); request.setContent(content); std::string url = "/auth/change"; auto here_uri = request.getParam("DOCUMENT_URI"); if (here_uri) url += "?continue=" + url::encode(request.serverUri(here_uri, false)); auto& signin = content->section(tr(lng::LNG_SETTINGS_PROFILE_SEC_SIGNIN)); auto& name = content->section(tr(lng::LNG_SETTINGS_PROFILE_SEC_NAME)); content->buttons().submit("submit", tr(lng::LNG_CMD_UPDATE)); content->buttons().submit("close", tr(lng::LNG_CMD_CLOSE), ButtonType::Narrow); signin.text("login-text", tr(lng::LNG_LOGIN_USERNAME)); signin.text("pass-word", tr(lng::LNG_LOGIN_PASSWORD), true, tr(lng::LNG_SETTINGS_PROFILE_PASSWORD_MAIL_HINT)); signin.text("email", tr(lng::LNG_SETTINGS_PROFILE_EMAIL)); signin.link("pass", url, tr(lng::LNG_SETTINGS_PROFILE_CHANGE_PASSWORD)); Options opts; opts.add("0", tr(lng::LNG_SETTINGS_PROFILE_DISPLAY_NAME_CUSTOM)) .add("1", tr(lng::LNG_SETTINGS_PROFILE_DISPLAY_NAME_ORIGINAL)) .add("2", tr(lng::LNG_SETTINGS_PROFILE_DISPLAY_NAME_NAME)) .add("3", tr(lng::LNG_SETTINGS_PROFILE_DISPLAY_NAME_FAMILY_NAME)) .add("4", tr(lng::LNG_SETTINGS_PROFILE_DISPLAY_NAME_NFN)) .add("5", tr(lng::LNG_SETTINGS_PROFILE_DISPLAY_NAME_FNN)) .add("6", tr(lng::LNG_SETTINGS_PROFILE_DISPLAY_NAME_NCFN)) .add("7", tr(lng::LNG_SETTINGS_PROFILE_DISPLAY_NAME_FNCN)); name.text("name", tr(lng::LNG_SETTINGS_PROFILE_NAME)); name.text("family_name", tr(lng::LNG_SETTINGS_PROFILE_FAMILY_NAME)); name.selection("display_name", tr(lng::LNG_SETTINGS_PROFILE_DISPLAY_NAME), opts); name.text("custom", std::string()); const auto& avatars = avatar::Engines::engines(); if (avatars.size() > 1) // if there is anything more installed, than the default engine { auto& avatar = content->section(tr(lng::LNG_SETTINGS_PROFILE_SEC_AVATAR)); auto engines = avatar.radio_group("avatar", tr(lng::LNG_SETTINGS_PROFILE_WHICH_AVATAR)); engines->radio("", tr(lng::LNG_SETTINGS_PROFILE_AVATAR_NONE)); for (auto&& engine : avatars) { if (engine.first == "default") continue; auto e = avatar::Engines::engine(engine); if (!e->name()) continue; engines->radio(engine.first, tr(lng::LNG_SETTINGS_PROFILE_USE_AVATAR_FROM, e->name(), e->homePage())); } } } }; }}} // FastCGI::app::reader REGISTER_HANDLER("/settings/profile", FastCGI::app::reader::ProfileSettingsPageHandler); <|endoftext|>
<commit_before>// main.cc // // Copyright (c) 2016 Frank Lin ([email protected]) // // 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. // Expect command is : ./<this_cmd> --input <folder_name> --output <folder_name> --band <band> --maxzerror <max_z_error> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <string> #include "lerc_util.h" void create_directory(const char* directory) { struct stat st = {0}; if (stat(directory, &st) == -1) { mkdir(directory, 0700); } } const char *get_filename_ext(const char *filename) { const char *dot = strrchr(filename, '.'); if(!dot || dot == filename) return ""; return dot + 1; } void list_files_do_stuff(const char* name, int level, const std::string& input_path, const std::string& output_path, double max_z_error, int band, bool signed_type) { DIR *dir; struct dirent *entry; if (!(dir = opendir(name))) return; if (!(entry = readdir(dir))) return; do { bool isDir = false; #if SKR_PLATFORM==SKR_PLATFORM_MAC if (entry->d_type == DT_DIR) { isDir = true; } #else struct stat st; if (stat(name, &st) == 0) { isDir = S_ISDIR(st.st_mode); } #endif if (isDir) { gago::Logger::LogD("DEBUG - step2/ DIR - working %s", entry->d_name); char path[1024]; int len = snprintf(path, sizeof(path) - 1, "%s/%s", name, entry->d_name); path[len] = 0; if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue; // create directory in dest folder. std::string spec_output_folder = name; spec_output_folder += "/"; spec_output_folder += entry->d_name; spec_output_folder.replace(spec_output_folder.begin(), spec_output_folder.begin() + input_path.size(), output_path); create_directory(spec_output_folder.c_str()); // continue list_files_do_stuff(path, level + 1, input_path, output_path, max_z_error, band, signed_type); } else { gago::Logger::LogD("DEBUG - step2/ FILE - working %s", entry->d_name); if ((0 == strcmp("tif", get_filename_ext(entry->d_name))) || (0 == strcmp("tiff", get_filename_ext(entry->d_name)))) { // allow tif and tiff extension // destination path std::string spec_output_folder = name; spec_output_folder += "/"; spec_output_folder += entry->d_name; std::string file_path = spec_output_folder; gago::Logger::LogD("DEBUG - step3/ FILE - working %s", file_path.c_str()); size_t lastindex = spec_output_folder.find_last_of("."); std::string dest_file_name = spec_output_folder.substr(0, lastindex); dest_file_name += ".lerc"; dest_file_name.replace(dest_file_name.begin(), dest_file_name.begin() + input_path.size(), output_path); bool success = gago::LercUtil::EncodeTiffOrDie(file_path, dest_file_name, max_z_error, gago::LercUtil::LercVersion::V2_3, gago::LercUtil::DataType::UNKNOWN, band, signed_type); if (!success) { gago::Logger::LogD("%s encode failed", file_path.c_str()); } } } } while ((entry = readdir(dir))); closedir(dir); } int main(int argc, const char * argv[]) { std::string input_folder_path; std::string output_folder_path; uint32_t band = 0; double max_z_error = 0; // losses bool signed_type = false; // parse input arguments for (int i = 0; i < argc; ++i) { if (0 == strcmp("--input", argv[i])) { input_folder_path = argv[i + 1]; } else if (0 == strcmp("--output", argv[i])) { output_folder_path = argv[i + 1]; } else if (0 == strcmp("--band", argv[i])) { band = atoi(argv[i + 1]); } else if (0 == strcmp("--maxzerror", argv[i])) { max_z_error = atof(argv[i + 1]); } else if (0 == strcmp("--signed", argv[i])) { if (0 == strcmp("true", argv[i])) { signed_type = true; } } } // give a galance gago::Logger::LogD("The input folder path is %s, output lerc files will be inside %s, the TIFF band is %d, max Z error given is %f", input_folder_path.c_str(), output_folder_path.c_str(), band, max_z_error); // create output directory create_directory(output_folder_path.c_str()); // enumerate all files in directory list_files_do_stuff(input_folder_path.c_str(), 0, input_folder_path, output_folder_path, max_z_error, band, signed_type); gago::Logger::LogD("DONE"); return EXIT_SUCCESS; } <commit_msg>Fix stat issue.<commit_after>// main.cc // // Copyright (c) 2016 Frank Lin ([email protected]) // // 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. // Expect command is : ./<this_cmd> --input <folder_name> --output <folder_name> --band <band> --maxzerror <max_z_error> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <string> #include "lerc_util.h" void create_directory(const char* directory) { struct stat st = {0}; if (stat(directory, &st) == -1) { mkdir(directory, 0700); } } const char *get_filename_ext(const char *filename) { const char *dot = strrchr(filename, '.'); if(!dot || dot == filename) return ""; return dot + 1; } void list_files_do_stuff(const char* name, int level, const std::string& input_path, const std::string& output_path, double max_z_error, int band, bool signed_type) { DIR *dir; struct dirent *entry; if (!(dir = opendir(name))) return; if (!(entry = readdir(dir))) return; do { bool isDir = false; #if SKR_PLATFORM==SKR_PLATFORM_MAC // if (entry->d_type == DT_DIR) { // isDir = true; // } struct stat st; char filename[512]; snprintf(filename, sizeof(filename), "%s/%s", name, entry->d_name); lstat(filename, &st); isDir = S_ISDIR(st.st_mode); #else struct stat st; if (stat(name, &st) == 0) { isDir = S_ISDIR(st.st_mode); } #endif if (isDir) { gago::Logger::LogD("DEBUG - step2/ DIR - working %s", entry->d_name); char path[1024]; int len = snprintf(path, sizeof(path) - 1, "%s/%s", name, entry->d_name); path[len] = 0; if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue; // create directory in dest folder. std::string spec_output_folder = name; spec_output_folder += "/"; spec_output_folder += entry->d_name; spec_output_folder.replace(spec_output_folder.begin(), spec_output_folder.begin() + input_path.size(), output_path); create_directory(spec_output_folder.c_str()); // continue list_files_do_stuff(path, level + 1, input_path, output_path, max_z_error, band, signed_type); } else { gago::Logger::LogD("DEBUG - step2/ FILE - working %s", entry->d_name); if ((0 == strcmp("tif", get_filename_ext(entry->d_name))) || (0 == strcmp("tiff", get_filename_ext(entry->d_name)))) { // allow tif and tiff extension // destination path std::string spec_output_folder = name; spec_output_folder += "/"; spec_output_folder += entry->d_name; std::string file_path = spec_output_folder; gago::Logger::LogD("DEBUG - step3/ FILE - working %s", file_path.c_str()); size_t lastindex = spec_output_folder.find_last_of("."); std::string dest_file_name = spec_output_folder.substr(0, lastindex); dest_file_name += ".lerc"; dest_file_name.replace(dest_file_name.begin(), dest_file_name.begin() + input_path.size(), output_path); bool success = gago::LercUtil::EncodeTiffOrDie(file_path, dest_file_name, max_z_error, gago::LercUtil::LercVersion::V2_3, gago::LercUtil::DataType::UNKNOWN, band, signed_type); if (!success) { gago::Logger::LogD("%s encode failed", file_path.c_str()); } } } } while ((entry = readdir(dir))); closedir(dir); } int main(int argc, const char * argv[]) { std::string input_folder_path; std::string output_folder_path; uint32_t band = 0; double max_z_error = 0; // losses bool signed_type = false; // parse input arguments for (int i = 0; i < argc; ++i) { if (0 == strcmp("--input", argv[i])) { input_folder_path = argv[i + 1]; } else if (0 == strcmp("--output", argv[i])) { output_folder_path = argv[i + 1]; } else if (0 == strcmp("--band", argv[i])) { band = atoi(argv[i + 1]); } else if (0 == strcmp("--maxzerror", argv[i])) { max_z_error = atof(argv[i + 1]); } else if (0 == strcmp("--signed", argv[i])) { if (0 == strcmp("true", argv[i])) { signed_type = true; } } } // give a galance gago::Logger::LogD("The input folder path is %s, output lerc files will be inside %s, the TIFF band is %d, max Z error given is %f", input_folder_path.c_str(), output_folder_path.c_str(), band, max_z_error); // create output directory create_directory(output_folder_path.c_str()); // enumerate all files in directory list_files_do_stuff(input_folder_path.c_str(), 0, input_folder_path, output_folder_path, max_z_error, band, signed_type); gago::Logger::LogD("DONE"); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*********************************************************************** datetime.cpp - Implements date and time classes compatible with MySQL's various date and time column types. Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #define MYSQLPP_NOT_HEADER #include "common.h" #include "datetime.h" #include <iomanip> #include <time.h> using namespace std; namespace mysqlpp { std::ostream& operator <<(std::ostream& os, const Date& d) { char fill = os.fill('0'); ios::fmtflags flags = os.setf(ios::right); os << setw(4) << d.year << '-' << setw(2) << d.month << '-' << setw(2) << d.day; os.flags(flags); os.fill(fill); return os; } std::ostream& operator <<(std::ostream& os, const Time& t) { char fill = os.fill('0'); ios::fmtflags flags = os.setf(ios::right); os << setw(2) << t.hour << ':' << setw(2) << t.minute << ':' << setw(2) << t.second; os.flags(flags); os.fill(fill); return os; } std::ostream& operator <<(std::ostream& os, const DateTime& dt) { operator <<(os, Date(dt)); os << ' '; return operator <<(os, Time(dt)); } cchar* Date::convert(cchar* str) { char num[5]; num[0] = *str++; num[1] = *str++; num[2] = *str++; num[3] = *str++; num[4] = 0; year = short(strtol(num, 0, 10)); if (*str == '-') str++; num[0] = *str++; num[1] = *str++; num[2] = 0; month = short(strtol(num, 0, 10)); if (*str == '-') str++; num[0] = *str++; num[1] = *str++; num[2] = 0; day = short(strtol(num, 0, 10)); return str; } cchar* Time::convert(cchar* str) { char num[5]; num[0] = *str++; num[1] = *str++; num[2] = 0; hour = short(strtol(num,0,10)); if (*str == ':') str++; num[0] = *str++; num[1] = *str++; num[2] = 0; minute = short(strtol(num,0,10)); if (*str == ':') str++; num[0] = *str++; num[1] = *str++; num[2] = 0; second = short(strtol(num,0,10)); return str; } cchar* DateTime::convert(cchar* str) { Date d; str = d.convert(str); year = d.year; month = d.month; day = d.day; if (*str == ' ') ++str; Time t; str = t.convert(str); hour = t.hour; minute = t.minute; second = t.second; return str; } short int Date::compare(const Date& other) const { if (year != other.year) return year - other.year; if (month != other.month) return month - other.month; return day - other.day; } short int Time::compare(const Time& other) const { if (hour != other.hour) return hour - other.hour; if (minute != other.minute) return minute - other.minute; return second - other.second; } short int DateTime::compare(const DateTime& other) const { Date d(*this), od(other); Time t(*this), ot(other); if (int x = d.compare(od)) { return x; } else { return t.compare(ot); } } DateTime::operator time_t() const { struct tm tm; tm.tm_sec = second; tm.tm_min = minute; tm.tm_hour = hour; tm.tm_mday = day; tm.tm_mon = month - (tiny_int)1; tm.tm_year = year - 1900; tm.tm_isdst = -1; return mktime(&tm); }; DateTime::DateTime(time_t t) { struct tm tm; #if defined(_MSC_VER) && !defined(_STLP_VERSION) localtime_s(&tm, &t); #elif defined(__MINGW32_VERSION) memcpy(&tm, localtime(&t), sizeof(tm)); #else localtime_r(&t, &tm); #endif year = tm.tm_year + 1900; month = tm.tm_mon + 1; day = tm.tm_mday; hour = tm.tm_hour; minute = tm.tm_min; second = tm.tm_sec; } } // end namespace mysqlpp <commit_msg>More platform fixes for the localtime*() thing, for VC++2003 and MinGW.<commit_after>/*********************************************************************** datetime.cpp - Implements date and time classes compatible with MySQL's various date and time column types. Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #define MYSQLPP_NOT_HEADER #include "common.h" #include "datetime.h" #include <iomanip> #include <time.h> using namespace std; namespace mysqlpp { std::ostream& operator <<(std::ostream& os, const Date& d) { char fill = os.fill('0'); ios::fmtflags flags = os.setf(ios::right); os << setw(4) << d.year << '-' << setw(2) << d.month << '-' << setw(2) << d.day; os.flags(flags); os.fill(fill); return os; } std::ostream& operator <<(std::ostream& os, const Time& t) { char fill = os.fill('0'); ios::fmtflags flags = os.setf(ios::right); os << setw(2) << t.hour << ':' << setw(2) << t.minute << ':' << setw(2) << t.second; os.flags(flags); os.fill(fill); return os; } std::ostream& operator <<(std::ostream& os, const DateTime& dt) { operator <<(os, Date(dt)); os << ' '; return operator <<(os, Time(dt)); } cchar* Date::convert(cchar* str) { char num[5]; num[0] = *str++; num[1] = *str++; num[2] = *str++; num[3] = *str++; num[4] = 0; year = short(strtol(num, 0, 10)); if (*str == '-') str++; num[0] = *str++; num[1] = *str++; num[2] = 0; month = short(strtol(num, 0, 10)); if (*str == '-') str++; num[0] = *str++; num[1] = *str++; num[2] = 0; day = short(strtol(num, 0, 10)); return str; } cchar* Time::convert(cchar* str) { char num[5]; num[0] = *str++; num[1] = *str++; num[2] = 0; hour = short(strtol(num,0,10)); if (*str == ':') str++; num[0] = *str++; num[1] = *str++; num[2] = 0; minute = short(strtol(num,0,10)); if (*str == ':') str++; num[0] = *str++; num[1] = *str++; num[2] = 0; second = short(strtol(num,0,10)); return str; } cchar* DateTime::convert(cchar* str) { Date d; str = d.convert(str); year = d.year; month = d.month; day = d.day; if (*str == ' ') ++str; Time t; str = t.convert(str); hour = t.hour; minute = t.minute; second = t.second; return str; } short int Date::compare(const Date& other) const { if (year != other.year) return year - other.year; if (month != other.month) return month - other.month; return day - other.day; } short int Time::compare(const Time& other) const { if (hour != other.hour) return hour - other.hour; if (minute != other.minute) return minute - other.minute; return second - other.second; } short int DateTime::compare(const DateTime& other) const { Date d(*this), od(other); Time t(*this), ot(other); if (int x = d.compare(od)) { return x; } else { return t.compare(ot); } } DateTime::operator time_t() const { struct tm tm; tm.tm_sec = second; tm.tm_min = minute; tm.tm_hour = hour; tm.tm_mday = day; tm.tm_mon = month - (tiny_int)1; tm.tm_year = year - 1900; tm.tm_isdst = -1; return mktime(&tm); }; DateTime::DateTime(time_t t) { struct tm tm; #if defined(_MSC_VER) && _MSC_VER >= 1400 && !defined(_STLP_VERSION) localtime_s(&tm, &t); #elif !defined(__MINGW32_VERSION) && !defined(_STLP_VERSION) localtime_r(&t, &tm); #else memcpy(&tm, localtime(&t), sizeof(tm)); #endif year = tm.tm_year + 1900; month = tm.tm_mon + 1; day = tm.tm_mday; hour = tm.tm_hour; minute = tm.tm_min; second = tm.tm_sec; } } // end namespace mysqlpp <|endoftext|>
<commit_before>#include "global.h" #include "helper.h" #include "mem_alloc.h" #include "time.h" bool itemid_t::operator==(const itemid_t &other) const { return (type == other.type && location == other.location); } bool itemid_t::operator!=(const itemid_t &other) const { return !(*this == other); } void itemid_t::operator=(const itemid_t &other){ this->valid = other.valid; this->type = other.type; this->location = other.location; assert(*this == other); assert(this->valid); } void itemid_t::init() { valid = false; location = 0; next = NULL; } int get_thdid_from_txnid(uint64_t txnid) { return txnid % g_thread_cnt; } uint64_t get_part_id(void * addr) { return ((uint64_t)addr / PAGE_SIZE) % g_part_cnt; } uint64_t key_to_part(uint64_t key) { if (g_part_alloc) return key % g_part_cnt; else return 0; } uint64_t merge_idx_key(UInt64 key_cnt, UInt64 * keys) { UInt64 len = 64 / key_cnt; UInt64 key = 0; for (UInt32 i = 0; i < len; i++) { assert(keys[i] < (1UL << len)); key = (key << len) | keys[i]; } return key; } uint64_t merge_idx_key(uint64_t key1, uint64_t key2) { assert(key1 < (1UL << 32) && key2 < (1UL << 32)); return key1 << 32 | key2; } uint64_t merge_idx_key(uint64_t key1, uint64_t key2, uint64_t key3) { assert(key1 < (1 << 21) && key2 < (1 << 21) && key3 < (1 << 21)); return key1 << 42 | key2 << 21 | key3; } /****************************************************/ // Global Clock! /****************************************************/ uint64_t get_server_clock() { #if defined(__i386__) uint64_t ret; __asm__ __volatile__("rdtsc" : "=A" (ret)); #elif defined(__x86_64__) unsigned hi, lo; __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi)); uint64_t ret = ( (uint64_t)lo)|( ((uint64_t)hi)<<32 ); ret = (uint64_t) ((double)ret / CPU_FREQ); #else timespec * tp = new timespec; clock_gettime(CLOCK_REALTIME, tp); uint64_t ret = tp->tv_sec * 1000000000 + tp->tv_nsec; #endif return ret; } uint64_t get_sys_clock() { #ifndef NOGRAPHITE static volatile uint64_t fake_clock = 0; if (warmup_finish) return CarbonGetTime(); // in ns else { return ATOM_ADD_FETCH(fake_clock, 100); } #else if (TIME_ENABLE) return get_server_clock(); return 0; #endif } void myrand::init(uint64_t seed) { this->seed = seed; } uint64_t myrand::next() { seed = (seed * 1103515247UL + 12345UL) % (1UL<<63); return (seed / 65537) % RAND_MAX; } <commit_msg>get_server_clock() changed to get real clock time<commit_after>#include "global.h" #include "helper.h" #include "mem_alloc.h" #include "time.h" bool itemid_t::operator==(const itemid_t &other) const { return (type == other.type && location == other.location); } bool itemid_t::operator!=(const itemid_t &other) const { return !(*this == other); } void itemid_t::operator=(const itemid_t &other){ this->valid = other.valid; this->type = other.type; this->location = other.location; assert(*this == other); assert(this->valid); } void itemid_t::init() { valid = false; location = 0; next = NULL; } int get_thdid_from_txnid(uint64_t txnid) { return txnid % g_thread_cnt; } uint64_t get_part_id(void * addr) { return ((uint64_t)addr / PAGE_SIZE) % g_part_cnt; } uint64_t key_to_part(uint64_t key) { if (g_part_alloc) return key % g_part_cnt; else return 0; } uint64_t merge_idx_key(UInt64 key_cnt, UInt64 * keys) { UInt64 len = 64 / key_cnt; UInt64 key = 0; for (UInt32 i = 0; i < len; i++) { assert(keys[i] < (1UL << len)); key = (key << len) | keys[i]; } return key; } uint64_t merge_idx_key(uint64_t key1, uint64_t key2) { assert(key1 < (1UL << 32) && key2 < (1UL << 32)); return key1 << 32 | key2; } uint64_t merge_idx_key(uint64_t key1, uint64_t key2, uint64_t key3) { assert(key1 < (1 << 21) && key2 < (1 << 21) && key3 < (1 << 21)); return key1 << 42 | key2 << 21 | key3; } /****************************************************/ // Global Clock! /****************************************************/ uint64_t get_server_clock() { /* #if defined(__i386__) uint64_t ret; __asm__ __volatile__("rdtsc" : "=A" (ret)); #elif defined(__x86_64__) unsigned hi, lo; __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi)); uint64_t ret = ( (uint64_t)lo)|( ((uint64_t)hi)<<32 ); ret = (uint64_t) ((double)ret / CPU_FREQ); #else */ timespec * tp = new timespec; clock_gettime(CLOCK_REALTIME, tp); uint64_t ret = tp->tv_sec * 1000000000 + tp->tv_nsec; //#endif return ret; } uint64_t get_sys_clock() { #ifndef NOGRAPHITE static volatile uint64_t fake_clock = 0; if (warmup_finish) return CarbonGetTime(); // in ns else { return ATOM_ADD_FETCH(fake_clock, 100); } #else if (TIME_ENABLE) return get_server_clock(); return 0; #endif } void myrand::init(uint64_t seed) { this->seed = seed; } uint64_t myrand::next() { seed = (seed * 1103515247UL + 12345UL) % (1UL<<63); return (seed / 65537) % RAND_MAX; } <|endoftext|>
<commit_before>/* * Copyright (c) 2000-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert */ #include <Python.h> #include <signal.h> #include <iostream> #include <string> #include "base/cprintf.hh" #include "base/misc.hh" #include "config/pythonhome.hh" #include "python/swig/init.hh" #include "sim/async.hh" #include "sim/host.hh" #include "sim/core.hh" using namespace std; /// Stats signal handler. void dumpStatsHandler(int sigtype) { async_event = true; async_statdump = true; } void dumprstStatsHandler(int sigtype) { async_event = true; async_statdump = true; async_statreset = true; } /// Exit signal handler. void exitNowHandler(int sigtype) { async_event = true; async_exit = true; } /// Abort signal handler. void abortHandler(int sigtype) { ccprintf(cerr, "Program aborted at cycle %d\n", curTick); } int main(int argc, char **argv) { signal(SIGFPE, SIG_IGN); // may occur on misspeculated paths signal(SIGTRAP, SIG_IGN); signal(SIGUSR1, dumpStatsHandler); // dump intermediate stats signal(SIGUSR2, dumprstStatsHandler); // dump and reset stats signal(SIGINT, exitNowHandler); // dump final stats and exit signal(SIGABRT, abortHandler); Py_SetProgramName(argv[0]); // default path to m5 python code is the currently executing // file... Python ZipImporter will find embedded zip archive. // The M5_ARCHIVE environment variable can be used to override this. char *m5_archive = getenv("M5_ARCHIVE"); string pythonpath = m5_archive ? m5_archive : argv[0]; char *oldpath = getenv("PYTHONPATH"); if (oldpath != NULL) { pythonpath += ":"; pythonpath += oldpath; } if (setenv("PYTHONPATH", pythonpath.c_str(), true) == -1) fatal("setenv: %s\n", strerror(errno)); char *python_home = getenv("PYTHONHOME"); if (!python_home) python_home = PYTHONHOME; Py_SetPythonHome(python_home); // initialize embedded Python interpreter Py_Initialize(); PySys_SetArgv(argc, argv); // initialize SWIG modules init_swig(); PyRun_SimpleString("import m5.main"); PyRun_SimpleString("m5.main.main()"); // clean up Python intepreter. Py_Finalize(); } <commit_msg>main: return an an exit code of 1 when we exit due to a python exception. This requires us to not use PyRun_SimpleString, but PyRun_String since the latter actually returns a result<commit_after>/* * Copyright (c) 2000-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert */ #include <Python.h> #include <signal.h> #include <iostream> #include <string> #include "base/cprintf.hh" #include "base/misc.hh" #include "config/pythonhome.hh" #include "python/swig/init.hh" #include "sim/async.hh" #include "sim/host.hh" #include "sim/core.hh" using namespace std; /// Stats signal handler. void dumpStatsHandler(int sigtype) { async_event = true; async_statdump = true; } void dumprstStatsHandler(int sigtype) { async_event = true; async_statdump = true; async_statreset = true; } /// Exit signal handler. void exitNowHandler(int sigtype) { async_event = true; async_exit = true; } /// Abort signal handler. void abortHandler(int sigtype) { ccprintf(cerr, "Program aborted at cycle %d\n", curTick); } int python_main() { PyObject *module; PyObject *dict; PyObject *result; module = PyImport_AddModule("__main__"); if (module == NULL) fatal("Could not import __main__"); dict = PyModule_GetDict(module); result = PyRun_String("import m5.main", Py_file_input, dict, dict); if (!result) { PyErr_Print(); return 1; } Py_DECREF(result); result = PyRun_String("m5.main.main()", Py_file_input, dict, dict); if (!result) { PyErr_Print(); return 1; } Py_DECREF(result); if (Py_FlushLine()) PyErr_Clear(); return 0; } int main(int argc, char **argv) { signal(SIGFPE, SIG_IGN); // may occur on misspeculated paths signal(SIGTRAP, SIG_IGN); signal(SIGUSR1, dumpStatsHandler); // dump intermediate stats signal(SIGUSR2, dumprstStatsHandler); // dump and reset stats signal(SIGINT, exitNowHandler); // dump final stats and exit signal(SIGABRT, abortHandler); Py_SetProgramName(argv[0]); // default path to m5 python code is the currently executing // file... Python ZipImporter will find embedded zip archive. // The M5_ARCHIVE environment variable can be used to override this. char *m5_archive = getenv("M5_ARCHIVE"); string pythonpath = m5_archive ? m5_archive : argv[0]; char *oldpath = getenv("PYTHONPATH"); if (oldpath != NULL) { pythonpath += ":"; pythonpath += oldpath; } if (setenv("PYTHONPATH", pythonpath.c_str(), true) == -1) fatal("setenv: %s\n", strerror(errno)); char *python_home = getenv("PYTHONHOME"); if (!python_home) python_home = PYTHONHOME; Py_SetPythonHome(python_home); // initialize embedded Python interpreter Py_Initialize(); PySys_SetArgv(argc, argv); // initialize SWIG modules init_swig(); int ret = python_main(); // clean up Python intepreter. Py_Finalize(); return ret; } <|endoftext|>
<commit_before>// this node manage the number and index of present two wheel robot // publish topic on two wheel robot information // robot index, 2D position and speed of wheels // use gazebo service to spawn and delete model in gazebo // (compatible when a robot model is deleted directly from gazebo gui) // accept service request the command of adding or deleting robot model // (adding or deleting action will be reflected directly in the topic msg) // this node is not compatible with different robot models, for two wheel orbot only // because only two wheel robot has wheel speed, may write another node for other robot models // both low and high level robot control subscribe to same robot information topic // although it's better to divide the message into two, and publish at different frequency // this one topic method can be reused when it comes to other robot models // check collision when adding robots #include <ros/ros.h> #include <swarm_robot_msgs/two_wheel_robot.h> #include <swarm_robot_srv/swarm_robot_update.h> #include <gazebo_msgs/SpawnModel.h> #include <gazebo_msgs/DeleteModel.h> #include <gazebo_msgs/ModelStates.h> #include <gazebo_msgs/GetJointProperties.h> #include <string> #include <vector> // global variables // THE container maintained by this node swarm_robot_msgs::two_wheel_robot current_robots; bool robot_position_updated = false; // callback for getting robot positions // also check and update if there is any addition or deletion of robots void modelStatesCallback(const gazebo_msgs::ModelStates& current_model_states) { // parsing the two wheel robots from all the robot models // possible that there is models for obstacles or other environments int model_quantity = current_model_states.name.size(); // the index of robots in the container std::vector<int32_t> container_index = current_robots.index; // the index of robots found in gazebo std::vector<int32_t> gazebo_index; gazebo_index.clear(); for (int i=0; i<model_quantity; i++) { // check if it is a two wheel robot // there is a underscore between the name and the index std::size_t found = current_model_states.name[i].find("two_wheel_robot"); if (found != std::string::npos) { // a two_wheel_robot has been found // get the robot index // 16 = 15 + 1, 15 is the length of "two_wheel_robot" std::string index_str = current_model_states.name[i].substr(16); int index_found = std::atoi(index_str.c_str()); // search in the container int container_size = container_index.size(); for (int j=0; j<container_size; j++) { if (index_found == container_index[j]) } } } // reset robot_position_updated flag robot_position_updated = true; } // callback for service to change robot models in gazebo bool twoWheelRobotUpdateCallback(swarm_robot_srv::swarm_robot_updateRequest& request , swarm_robot_srv::swarm_robot_updateResponse& response , ros::ServiceClient add_model_client , ros::ServiceClient delete_model_client) { } int main(int argc, char **argv) { ros::init(argc, argv, "/swarm_sim/two_wheel_robot_manager"); ros::NodeHandle nh; // handshake with robot name in parameter server, and get model urdf std::string robot_name; std::string two_wheel_robot_urdf; bool get_name, get_urdf; get_name = nh.getParam("/swarm_sim/robot_name", robot_name); get_urdf = nh.getParam("/swarm_sim/two_wheel_robot_urdf", two_wheel_robot_urdf); if (!(get_name && get_urdf)) { ROS_ERROR("parameter server is not set"); return 0; // return when parameter server is not good } if (robot_name != "two_wheel_robot") { ROS_ERROR("wrong robot according to parameter server"); return 0; // return when wrong robot manager is called } // check if gazebo is up and running by check service "/gazebo/set_physics_properties" // this service seems like the last service hosted by gazebo ros::Duration half_sec(0.5); bool gazebo_ready = ros::service::exist("/gazebo/set_physics_properties", true); if (!gazebo_ready) { // gazebo not ready while (!gazebo_ready) { ROS_INFO("waiting for gazebo"); half_sec.sleep(); gazebo_ready = ros::service::exist("/gazebo/set_physics_properties", true); } } // initialize THE container current_robots.index.clear(); current_robots.x.clear(); current_robots.y.clear(); current_robots.orientation.clear(); current_robots.left_wheel_vel.clear(); current_robots.right_wheel_vel.clear(); // instantiate a publisher for the managed information of two wheel robot ros::Publisher two_wheel_robot_publisher = nh.advertise<swarm_robot_msgs::two_wheel_robot>("/swarm_sim/two_wheel_robot", 1); // instantiate a subscriber for "/gazebo/model_states" ros::Subscriber model_states_subscriber = nh.subscribe("/gazebo/model_states", 1, modelStatesCallback); // this topic publish at 1000hz rate // instantiate a service client to get wheel velocities ros::ServiceClient joint_properties_client = nh.serviceClient<gazebo_msgs::GetJointProperties>( "/gazebo/get_joint_properties"); gazebo_msgs::GetJointProperties joint_properties_srv_msg; // instantiate a service server to modify the robots in gazebo // add or delete robot models in gazebo ros::ServiceServer two_wheel_robot_service = nh.advertiseService("/swarm_sim/two_wheel_robot_update", twoWheelRobotUpdateCallback); // instantiate a service client for "/gazebo/spawn_urdf_model" ros::ServiceClient add_model_client = nh.serviceClient<gazebo_msgs::SpawnModel>("/gazebo/spawn_urdf_model"); gazebo_msgs::SpawnModel add_model_srv_msg; // service message geometry_msgs::Pose model_pose; // pose message for service message // instantiate a service client for "/gazebo/delete_model" ros::ServiceClient delete_model_client = nh.serviceClient<gazebo_msgs::DeleteModel>("/gazebo/delete_model"); gazebo_msgs::DeleteModel delete_model_srv_msg; // service message } <commit_msg>add robot updater in model states callback<commit_after>// this node manage the number and index of present two wheel robot // publish topic on two wheel robot information // robot index, 2D position and speed of wheels // use gazebo service to spawn and delete model in gazebo // (compatible when a robot model is deleted directly from gazebo gui) // accept service request the command of adding or deleting robot model // (adding or deleting action will be reflected directly in the topic msg) // this node is not compatible with different robot models, for two wheel orbot only // because only two wheel robot has wheel speed, may write another node for other robot models // both low and high level robot control subscribe to same robot information topic // although it's better to divide the message into two, and publish at different frequency // this one topic method can be reused when it comes to other robot models // check collision when adding robots #include <ros/ros.h> #include <swarm_robot_msgs/two_wheel_robot.h> #include <swarm_robot_srv/swarm_robot_update.h> #include <gazebo_msgs/SpawnModel.h> #include <gazebo_msgs/DeleteModel.h> #include <gazebo_msgs/ModelStates.h> #include <gazebo_msgs/GetJointProperties.h> #include <geometry_msgs/Quaternion.h> #include <gaometry_msgs/Pose.h> #include <string> #include <vector> #include <algorithm> // global variables // THE container maintained by this node swarm_robot_msgs::two_wheel_robot current_robots; bool robot_position_updated = false; // callback for getting robot positions // also check and update if there is any addition or deletion of robots void modelStatesCallback(const gazebo_msgs::ModelStates& current_model_states) { // parsing the two wheel robots from all the models in gazebo // possible that there are models for obstacles or other environments int model_quantity = current_model_states.name.size(); // the index of robots in the container std::vector<int32_t> container_index = current_robots.index; for (int i=0; i<model_quantity; i++) { // check if it is a two wheel robot // there is a underscore between the name and the index std::size_t found = current_model_states.name[i].find("two_wheel_robot"); if (found != std::string::npos) { // a two_wheel_robot has been found // get the robot index // 16 = 15 + 1, 15 is the length of "two_wheel_robot" std::string index_str = current_model_states.name[i].substr(16); int index_parsed = std::atoi(index_str.c_str()); // search in the container int container_size = container_index.size(); bool parsed_index_found = false; for (int j=0; j<container_size; j++) { // the size of container_index may change for each i if (index_parsed == container_index[j]) { // update the 2D position of two wheel robots current_robots.x[j] = current_model_states.pose[i].position.x; current_robots.y[j] = current_model_states.pose[i].position.y; current_robot.orientation[j] = quaternion_to_angle(current_model_states.pose[i].orientation); container_index.erase(j); parsed_index_found = true; break; } } if (!parsed_index_found) { // parsed index not found in the container, ADDITION found! // update a new robot in the container current_robots.index.push_back(index_parsed); current_robots.x.push_back(current_model_states.pose[i].position.x); current_robots.y.push_back(current_model_states.pose[i].position.y); current_robots.orientation.push_back(quaternion_to_angle(current_model_states.pose[i].orientation)); current_robots.left_wheel_vel.push_back(0); current_robots.right_wheel_vel.push_back(0); ROS_INFO_STREAM("robot addition detected: two_wheel_robot_" << index_str); } } } // update the container if there is deletion in gazebo if (container_index.size() != 0) { int container_index_size = container_index.size(); for (int i=0; i<container_index_size; i++) { int current_robots_index_size = current_robots.index.size(); for (int j=0; j<current_robots_index_size; j++) { // the index should be found before this loop ends if (container_index[i] == current_robots.index[j]) { // erase the node current_robots.index.erase(j); current_robots.x.erase(j); current_robots.y.erase(j); current_robots.orientation.erase(j); current_robots.left_wheel_vel.erase(j); current_robots.right_wheel_vel.erase(j); ROS_INFO_STREAM("robot deletion detected: two_wheel_robot_" << intToString(container_index[i])); break; } } } } // reset robot_position_updated flag robot_position_updated = true; } // callback for service to change robot models in gazebo bool twoWheelRobotUpdateCallback(swarm_robot_srv::swarm_robot_updateRequest& request , swarm_robot_srv::swarm_robot_updateResponse& response , ros::ServiceClient add_model_client , ros::ServiceClient delete_model_client) { } // quaternion => rotation angle double quaternion_to_angle(geometry_msgs::Quaternion input_quaternion) { // this assume the x and y element of the quaternion is close to zero return atan(input_quaternion.z/input_quaternion.w) * 2 } // int to string converter std::string intToString(int a) { std::stringstream ss; ss << a; return ss.str(); } int main(int argc, char **argv) { ros::init(argc, argv, "/swarm_sim/two_wheel_robot_manager"); ros::NodeHandle nh; // handshake with robot name in parameter server, and get model urdf std::string robot_name; std::string two_wheel_robot_urdf; bool get_name, get_urdf; get_name = nh.getParam("/swarm_sim/robot_name", robot_name); get_urdf = nh.getParam("/swarm_sim/two_wheel_robot_urdf", two_wheel_robot_urdf); if (!(get_name && get_urdf)) { ROS_ERROR("parameter server is not set"); return 0; // return when parameter server is not good } if (robot_name != "two_wheel_robot") { ROS_ERROR("wrong robot according to parameter server"); return 0; // return when wrong robot manager is called } // check if gazebo is up and running by check service "/gazebo/set_physics_properties" // this service seems like the last service hosted by gazebo ros::Duration half_sec(0.5); bool gazebo_ready = ros::service::exist("/gazebo/set_physics_properties", true); if (!gazebo_ready) { // gazebo not ready while (!gazebo_ready) { ROS_INFO("waiting for gazebo"); half_sec.sleep(); gazebo_ready = ros::service::exist("/gazebo/set_physics_properties", true); } } // initialize THE container current_robots.index.clear(); current_robots.x.clear(); current_robots.y.clear(); current_robots.orientation.clear(); current_robots.left_wheel_vel.clear(); current_robots.right_wheel_vel.clear(); // instantiate a publisher for the managed information of two wheel robot ros::Publisher two_wheel_robot_publisher = nh.advertise<swarm_robot_msgs::two_wheel_robot>("/swarm_sim/two_wheel_robot", 1); // instantiate a subscriber for "/gazebo/model_states" ros::Subscriber model_states_subscriber = nh.subscribe("/gazebo/model_states", 1, modelStatesCallback); // this topic publish at 1000hz rate // instantiate a service client to get wheel velocities ros::ServiceClient joint_properties_client = nh.serviceClient<gazebo_msgs::GetJointProperties>( "/gazebo/get_joint_properties"); gazebo_msgs::GetJointProperties joint_properties_srv_msg; // instantiate a service server to modify the robots in gazebo // add or delete robot models in gazebo ros::ServiceServer two_wheel_robot_service = nh.advertiseService("/swarm_sim/two_wheel_robot_update", twoWheelRobotUpdateCallback); // instantiate a service client for "/gazebo/spawn_urdf_model" ros::ServiceClient add_model_client = nh.serviceClient<gazebo_msgs::SpawnModel>("/gazebo/spawn_urdf_model"); gazebo_msgs::SpawnModel add_model_srv_msg; // service message geometry_msgs::Pose model_pose; // pose message for service message // instantiate a service client for "/gazebo/delete_model" ros::ServiceClient delete_model_client = nh.serviceClient<gazebo_msgs::DeleteModel>("/gazebo/delete_model"); gazebo_msgs::DeleteModel delete_model_srv_msg; // service message } <|endoftext|>
<commit_before><commit_msg>ant: optimizations<commit_after><|endoftext|>
<commit_before>#include "test/test_syscoin_services.h" #include "data/utxo.json.h" #include "utiltime.h" #include "rpcserver.h" #include <boost/test/unit_test.hpp> #include <univalue.h> int currentTx = 0; extern UniValue read_json(const std::string& jsondata); BOOST_FIXTURE_TEST_SUITE (syscoin_snapshot_tests, SyscoinMainNetSetup) struct PaymentAmount { std::string address; std::string amount; }; void SendSnapShotPayment(const std::string &strSend) { currentTx++; std::string strSendMany = "sendmany \"\" {" + strSend + "}"; UniValue r; BOOST_CHECK_THROW(r = CallRPC("mainnet1", strSendMany, false), runtime_error); } void GenerateSnapShot(const std::vector<PaymentAmount> &paymentAmounts) { // generate snapshot payments and let it mature printf("Generating 101 blocks to start the mainnet\n"); GenerateMainNetBlocks(101, "mainnet1"); int numberOfTxPerBlock = 1000; int totalTx = 0; double nTotal =0; std::string sendManyString = ""; for(int i =0;i<paymentAmounts.size();i++) { if(sendManyString != "") sendManyString += ","; sendManyString += "\\\"" + paymentAmounts[i].address + "\\\":" + paymentAmounts[i].amount; nTotal += atof(paymentAmounts[i].amount.c_str()); totalTx++; if(i != 0 && (i%numberOfTxPerBlock) == 0) { printf("strSendMany #%d, total %f, num txs %d\n", currentTx, nTotal, totalTx); SendSnapShotPayment(sendManyString); GenerateMainNetBlocks(1, "mainnet1"); sendManyString = ""; nTotal = 0; } } if(sendManyString != "") { printf("FINAL strSendMany #%d, total %f, num txs %d\n", currentTx, nTotal, totalTx); SendSnapShotPayment(sendManyString); GenerateMainNetBlocks(1, "mainnet1"); } } void GetUTXOs(std::vector<PaymentAmount> &paymentAmounts) { UniValue tests = read_json(std::string(json_tests::utxo, json_tests::utxo + sizeof(json_tests::utxo))); for (unsigned int idx = 0; idx < tests.size(); idx++) { UniValue test = tests[idx]; std::string strTest = test.write(); if (test.size() < 2) // Allow for extra stuff (useful for comments) { BOOST_ERROR("Bad test: " << strTest); continue; } PaymentAmount payment; payment.address = test[0].get_str(); CAmount amountInSys1 = test[1].get_int64(); // don't transfer less than 1 coin utxo's if(amountInSys1 <= COIN) continue; payment.amount = ValueFromAmount(amountInSys1).write(); paymentAmounts.push_back(payment); } } bool IsMainNetAlreadyCreated() { int height; UniValue r; BOOST_CHECK_NO_THROW(r = CallRPC("mainnet1", "getinfo", false)); height = find_value(r.get_obj(), "blocks").get_int(); return height > 1; } BOOST_AUTO_TEST_CASE (generate_and_verify_snapshot) { std::vector<PaymentAmount> paymentAmounts; GetUTXOs(paymentAmounts); if(!IsMainNetAlreadyCreated()) { GenerateSnapShot(paymentAmounts); } } BOOST_AUTO_TEST_SUITE_END ()<commit_msg>more output<commit_after>#include "test/test_syscoin_services.h" #include "data/utxo.json.h" #include "utiltime.h" #include "rpcserver.h" #include <boost/test/unit_test.hpp> #include <univalue.h> int currentTx = 0; extern UniValue read_json(const std::string& jsondata); BOOST_FIXTURE_TEST_SUITE (syscoin_snapshot_tests, SyscoinMainNetSetup) struct PaymentAmount { std::string address; std::string amount; }; void SendSnapShotPayment(const std::string &strSend) { currentTx++; std::string strSendMany = "sendmany \"\" {" + strSend + "}"; UniValue r; BOOST_CHECK_NO_THROW(r = CallRPC("mainnet1", strSendMany, false), runtime_error); } void GenerateSnapShot(const std::vector<PaymentAmount> &paymentAmounts) { // generate snapshot payments and let it mature printf("Generating 101 blocks to start the mainnet\n"); GenerateMainNetBlocks(101, "mainnet1"); int numberOfTxPerBlock = 1000; int totalTx = 0; double nTotal =0; std::string sendManyString = ""; for(int i =0;i<paymentAmounts.size();i++) { if(sendManyString != "") sendManyString += ","; sendManyString += "\\\"" + paymentAmounts[i].address + "\\\":" + paymentAmounts[i].amount; nTotal += atof(paymentAmounts[i].amount.c_str()); totalTx++; if(i != 0 && (i%numberOfTxPerBlock) == 0) { printf("strSendMany #%d, total %f, num txs %d\n", currentTx, nTotal, totalTx); SendSnapShotPayment(sendManyString); GenerateMainNetBlocks(1, "mainnet1"); sendManyString = ""; nTotal = 0; } } if(sendManyString != "") { printf("FINAL strSendMany #%d, total %f, num txs %d\n", currentTx, nTotal, totalTx); SendSnapShotPayment(sendManyString); GenerateMainNetBlocks(1, "mainnet1"); } } void GetUTXOs(std::vector<PaymentAmount> &paymentAmounts) { int countTx = 0; int rejectTx = 0; UniValue tests = read_json(std::string(json_tests::utxo, json_tests::utxo + sizeof(json_tests::utxo))); for (unsigned int idx = 0; idx < tests.size(); idx++) { UniValue test = tests[idx]; std::string strTest = test.write(); if (test.size() < 2) // Allow for extra stuff (useful for comments) { BOOST_ERROR("Bad test: " << strTest); continue; } PaymentAmount payment; payment.address = test[0].get_str(); CAmount amountInSys1 = test[1].get_int64(); // don't transfer less than 1 coin utxo's if(amountInSys1 <= COIN) { rejectTx++; continue; } countTx++; payment.amount = ValueFromAmount(amountInSys1).write(); paymentAmounts.push_back(payment); } printf("Read %d total utxo sets, rejected %d, valid %d\n", rejectTx+countTx, rejectTx, countTx); } bool IsMainNetAlreadyCreated() { int height; UniValue r; BOOST_CHECK_NO_THROW(r = CallRPC("mainnet1", "getinfo", false)); height = find_value(r.get_obj(), "blocks").get_int(); return height > 1; } BOOST_AUTO_TEST_CASE (generate_and_verify_snapshot) { std::vector<PaymentAmount> paymentAmounts; GetUTXOs(paymentAmounts); if(!IsMainNetAlreadyCreated()) { GenerateSnapShot(paymentAmounts); } } BOOST_AUTO_TEST_SUITE_END ()<|endoftext|>
<commit_before>/* * LoadHandler.cpp * * Created on: 29.05.2017 * Author: Alexander */ #include "persistence/base/LoadHandler.hpp" #include <sstream> // used for getLevel() #include "abstractDataTypes/Bag.hpp" #include "abstractDataTypes/Union.hpp" #include "boost/algorithm/string.hpp" // used for string splitting #include "ecore/EClass.hpp" #include "ecore/EClassifier.hpp" #include "ecore/EObject.hpp" #include "ecore/EPackage.hpp" #include "ecore/EStructuralFeature.hpp" #include "uml/Class.hpp" #include "uml/NamedElement.hpp" #include "uml/Package.hpp" #include "persistence/base/HandlerHelper.hpp" #include "pluginFramework/MDE4CPPPlugin.hpp" #include "pluginFramework/PluginFramework.hpp" #include "pluginFramework/EcoreModelPlugin.hpp" #include "pluginFramework/UMLModelPlugin.hpp" using namespace persistence::base; LoadHandler::LoadHandler() { m_rootObject = nullptr; m_level = -1; m_isXSIMode = true; } LoadHandler::~LoadHandler() { } std::shared_ptr<ecore::EObject> LoadHandler::getObjectByRef(std::string ref) { std::shared_ptr<ecore::EObject> tmp; if (!ref.empty()) { if (m_refToObject_map.find(ref) != m_refToObject_map.end()) { // found tmp = m_refToObject_map.at(ref); //return std::dynamic_pointer_cast<ecore::EObject>( tmp ); } else { size_t double_dot = ref.find("#//", 0); std::string _ref_prefix = ""; std::string _ref_name = ""; if (double_dot != std::string::npos) { std::string _ref_prefix = ref.substr(0, double_dot); // TODO '_ref_prefix' is not used in this case std::string _ref_name = ref.substr(double_dot); } if (m_refToObject_map.find(_ref_name) != m_refToObject_map.end()) { // found tmp = m_refToObject_map.at(_ref_name); //return std::dynamic_pointer_cast<ecore::EObject>( tmp ); } else { MSG_WARNING("Given Reference-Name '" << ref << "' or '" << _ref_name << "' are not in stored map."); return nullptr; } } } return tmp; } void LoadHandler::addToMap(std::shared_ptr<ecore::EObject> object) { addToMap(object, true); } void LoadHandler::addToMap(std::shared_ptr<ecore::EObject> object, bool useCurrentObjects) { std::string ref = ""; if (useCurrentObjects) { ref = getCurrentXMIID(); if (ref.empty()) { ref = persistence::base::HandlerHelper::extractReference(object, m_rootObject, m_rootPrefix, m_currentObjects); } } else { ref = persistence::base::HandlerHelper::extractReference(object, m_rootObject, m_rootPrefix); } if (!ref.empty()) { if (m_refToObject_map.find(ref) == m_refToObject_map.end()) { // ref not found in map, so insert m_refToObject_map.insert(std::pair<std::string, std::shared_ptr<ecore::EObject>>(ref, object)); MSG_DEBUG("Add to map: '" << ref << "' eClass: '" << object->eClass()->getName() << "'"); } } } /**/ std::string LoadHandler::getPrefix() { return m_rootPrefix; } std::string LoadHandler::getRootName() { return m_rootName; } std::string LoadHandler::getLevel() { std::stringstream ss; for (int ii = 0; ii < m_level; ii++) { ss << " "; } return ss.str(); } void LoadHandler::handleRoot(std::shared_ptr<ecore::EObject> object) { if (object == nullptr) { return; } m_level++; m_currentObjects.push_back(object); m_rootObject = object; getNextNodeName(); object->load(m_thisPtr); } void LoadHandler::handleChild(std::shared_ptr<ecore::EObject> object) { if (object == nullptr) { return; } m_level++; m_currentObjects.push_back(object); if (!m_isXSIMode) { addToMap(object); // add 'object' to loadHandler's internal Map, that is used for resolving references. } object->load(m_thisPtr); // call recursively 'object.load(). if (m_isXSIMode) { addToMap(object); // add 'object' to loadHandler's internal Map, that is used for resolving references. } release(); // report loadHandler to set 'this' as new current Object. } std::shared_ptr<ecore::EObject> LoadHandler::getCurrentObject() { std::shared_ptr<ecore::EObject> tmp_obj = m_currentObjects.back(); assert(tmp_obj); return tmp_obj; } /* * This API is adapted to API in Project emf4cpp. * * LINK to source: https://github.com/catedrasaes-umu/emf4cpp/tree/master/emf4cpp/ecorecpp/serializer/serializer-xerces.cpp * ::ecorecpp::mapping::type_traits::string_t serializer::get_type(EObject_ptr obj) const * */ std::string LoadHandler::extractType(std::shared_ptr<ecore::EObject> obj) const { return persistence::base::HandlerHelper::extractType(obj, m_rootPrefix); } void LoadHandler::release() { std::shared_ptr<ecore::EObject> tmp_obj = m_currentObjects.back(); if (tmp_obj == nullptr) { MSG_ERROR("You can't call " << __PRETTY_FUNCTION__ << " while current Object is nullptr."); } else { // set current (container) object as new current object (decrease depth) m_currentObjects.pop_back(); m_level--; } } void LoadHandler::addUnresolvedReference(const std::string &name, std::shared_ptr<ecore::EObject> object, std::shared_ptr<ecore::EStructuralFeature> esf) { if (object != nullptr) { if (esf != nullptr) { m_unresolvedReferences.push_back(persistence::base::UnresolvedReference(name, object, esf)); } else { MSG_ERROR(MSG_FLF << " esf is a nullptr"); } } else { MSG_ERROR(MSG_FLF << " object is a nullptr"); } } void LoadHandler::resolveReferences() { while (!m_unresolvedReferences.empty()) { persistence::base::UnresolvedReference uref = m_unresolvedReferences.back(); m_unresolvedReferences.pop_back(); std::string name = uref.refName; std::shared_ptr<ecore::EObject> object = uref.eObject; std::shared_ptr<ecore::EStructuralFeature> esf = uref.eStructuralFeature; std::list<std::shared_ptr<ecore::EObject>> references; try { if (esf->getUpperBound() == 1) { // EStructuralFeature is a single object solve(name, references, object, esf); } else { // EStructuralFeature is a list of objects std::list<std::string> _strs; std::string _tmpStr; boost::split(_strs, name, boost::is_any_of(" ")); while (_strs.size() > 0) { _tmpStr = _strs.front(); if (std::string::npos != _tmpStr.find("#//")) { solve(_tmpStr, references, object, esf); } _strs.pop_front(); } // Call resolveReferences() of corresponding 'object' object->resolveReferences(esf->getFeatureID(), references); } } catch (std::exception& e) { MSG_ERROR(MSG_FLF << " Exception: " << e.what()); } } } void LoadHandler::setThisPtr(std::shared_ptr<LoadHandler> thisPtr) { m_thisPtr = thisPtr; } void LoadHandler::solve(const std::string& name, std::list<std::shared_ptr<ecore::EObject>> references, std::shared_ptr<ecore::EObject> object, std::shared_ptr<ecore::EStructuralFeature> esf) { bool found = false; bool libraryLoaded = false; while (!found) { std::shared_ptr<ecore::EObject> resolved_object = this->getObjectByRef(name); if (resolved_object) { references.push_back(resolved_object); // Call resolveReferences() of corresponding 'object' object->resolveReferences(esf->getFeatureID(), references); found = true; } else { if (libraryLoaded) { return; } loadTypes(name); libraryLoaded = true; } } } void LoadHandler::loadTypes(const std::string& name) { unsigned int indexStartUri = name.find(" "); unsigned int indexEndUri = name.find("#"); if (indexStartUri != std::string::npos) { std::string nsURI = name.substr(indexStartUri+1, indexEndUri-indexStartUri-1); std::shared_ptr<PluginFramework> pluginFramework = PluginFramework::eInstance(); std::shared_ptr<MDE4CPPPlugin> plugin = pluginFramework->findPluginByUri(nsURI); if (plugin) { std::shared_ptr<EcoreModelPlugin> ecorePlugin = std::dynamic_pointer_cast<EcoreModelPlugin>(plugin); if (ecorePlugin) { loadTypes(ecorePlugin->getEPackage()); return; } std::shared_ptr<UMLModelPlugin> umlPlugin = std::dynamic_pointer_cast<UMLModelPlugin>(plugin); if (umlPlugin) { loadTypes(umlPlugin->getPackage(), umlPlugin->eNS_URI()); } } } } void LoadHandler::loadTypes(std::shared_ptr<ecore::EPackage> package) { std::shared_ptr<Bag<ecore::EClassifier>> eClassifiers = package->getEClassifiers(); for (std::shared_ptr<ecore::EClassifier> eClassifier : *eClassifiers) { // Filter only EDataType objects and add to handler's internal map std::shared_ptr<ecore::EClass> _metaClass = eClassifier->eClass(); addToMap(eClassifier, false); // TODO add default parameter force=true to addToMap() } } void LoadHandler::loadTypes(std::shared_ptr<uml::Package> package, std::string uri) { std::shared_ptr<Bag<uml::NamedElement>> memberList = package->getMember(); for (std::shared_ptr<uml::NamedElement> member : *memberList) { // Filter only EDataType objects and add to handler's internal map std::string metaClassName = ""; std::shared_ptr<ecore::EClass> ecoreMetaClass = member->eClass(); if (ecoreMetaClass) { auto x = ecoreMetaClass->getEPackage().lock(); if (x) { metaClassName = x->getName() + ":" + ecoreMetaClass->getName(); } else { metaClassName = ecoreMetaClass->getName(); } } else { std::shared_ptr<uml::Class> metaClass = member->getMetaClass(); if (metaClass == nullptr) { metaClassName = metaClass->getName(); } } std::string ref = metaClassName + " " + uri + "#" + member->getName(); m_refToObject_map.insert(std::pair<std::string, std::shared_ptr<ecore::EObject>>(ref, member)); MSG_DEBUG("Add to map: '" << ref << "'"); } } std::map<std::string, std::shared_ptr<ecore::EObject>> LoadHandler::getTypesMap() { return m_refToObject_map; } <commit_msg>[persistence] solve references without '#' in name in xmi mode<commit_after>/* * LoadHandler.cpp * * Created on: 29.05.2017 * Author: Alexander */ #include "persistence/base/LoadHandler.hpp" #include <sstream> // used for getLevel() #include "abstractDataTypes/Bag.hpp" #include "abstractDataTypes/Union.hpp" #include "boost/algorithm/string.hpp" // used for string splitting #include "ecore/EClass.hpp" #include "ecore/EClassifier.hpp" #include "ecore/EObject.hpp" #include "ecore/EPackage.hpp" #include "ecore/EStructuralFeature.hpp" #include "uml/Class.hpp" #include "uml/NamedElement.hpp" #include "uml/Package.hpp" #include "persistence/base/HandlerHelper.hpp" #include "pluginFramework/MDE4CPPPlugin.hpp" #include "pluginFramework/PluginFramework.hpp" #include "pluginFramework/EcoreModelPlugin.hpp" #include "pluginFramework/UMLModelPlugin.hpp" using namespace persistence::base; LoadHandler::LoadHandler() { m_rootObject = nullptr; m_level = -1; m_isXSIMode = true; } LoadHandler::~LoadHandler() { } std::shared_ptr<ecore::EObject> LoadHandler::getObjectByRef(std::string ref) { std::shared_ptr<ecore::EObject> tmp; if (!ref.empty()) { if (m_refToObject_map.find(ref) != m_refToObject_map.end()) { // found tmp = m_refToObject_map.at(ref); //return std::dynamic_pointer_cast<ecore::EObject>( tmp ); } else { size_t double_dot = ref.find("#//", 0); std::string _ref_prefix = ""; std::string _ref_name = ""; if (double_dot != std::string::npos) { std::string _ref_prefix = ref.substr(0, double_dot); // TODO '_ref_prefix' is not used in this case std::string _ref_name = ref.substr(double_dot); } if (m_refToObject_map.find(_ref_name) != m_refToObject_map.end()) { // found tmp = m_refToObject_map.at(_ref_name); //return std::dynamic_pointer_cast<ecore::EObject>( tmp ); } else { MSG_WARNING("Given Reference-Name '" << ref << "' or '" << _ref_name << "' are not in stored map."); return nullptr; } } } return tmp; } void LoadHandler::addToMap(std::shared_ptr<ecore::EObject> object) { addToMap(object, true); } void LoadHandler::addToMap(std::shared_ptr<ecore::EObject> object, bool useCurrentObjects) { std::string ref = ""; if (useCurrentObjects) { ref = getCurrentXMIID(); if (ref.empty()) { ref = persistence::base::HandlerHelper::extractReference(object, m_rootObject, m_rootPrefix, m_currentObjects); } } else { ref = persistence::base::HandlerHelper::extractReference(object, m_rootObject, m_rootPrefix); } if (!ref.empty()) { if (m_refToObject_map.find(ref) == m_refToObject_map.end()) { // ref not found in map, so insert m_refToObject_map.insert(std::pair<std::string, std::shared_ptr<ecore::EObject>>(ref, object)); MSG_DEBUG("Add to map: '" << ref << "' eClass: '" << object->eClass()->getName() << "'"); } } } /**/ std::string LoadHandler::getPrefix() { return m_rootPrefix; } std::string LoadHandler::getRootName() { return m_rootName; } std::string LoadHandler::getLevel() { std::stringstream ss; for (int ii = 0; ii < m_level; ii++) { ss << " "; } return ss.str(); } void LoadHandler::handleRoot(std::shared_ptr<ecore::EObject> object) { if (object == nullptr) { return; } m_level++; m_currentObjects.push_back(object); m_rootObject = object; getNextNodeName(); object->load(m_thisPtr); } void LoadHandler::handleChild(std::shared_ptr<ecore::EObject> object) { if (object == nullptr) { return; } m_level++; m_currentObjects.push_back(object); if (!m_isXSIMode) { addToMap(object); // add 'object' to loadHandler's internal Map, that is used for resolving references. } object->load(m_thisPtr); // call recursively 'object.load(). if (m_isXSIMode) { addToMap(object); // add 'object' to loadHandler's internal Map, that is used for resolving references. } release(); // report loadHandler to set 'this' as new current Object. } std::shared_ptr<ecore::EObject> LoadHandler::getCurrentObject() { std::shared_ptr<ecore::EObject> tmp_obj = m_currentObjects.back(); assert(tmp_obj); return tmp_obj; } /* * This API is adapted to API in Project emf4cpp. * * LINK to source: https://github.com/catedrasaes-umu/emf4cpp/tree/master/emf4cpp/ecorecpp/serializer/serializer-xerces.cpp * ::ecorecpp::mapping::type_traits::string_t serializer::get_type(EObject_ptr obj) const * */ std::string LoadHandler::extractType(std::shared_ptr<ecore::EObject> obj) const { return persistence::base::HandlerHelper::extractType(obj, m_rootPrefix); } void LoadHandler::release() { std::shared_ptr<ecore::EObject> tmp_obj = m_currentObjects.back(); if (tmp_obj == nullptr) { MSG_ERROR("You can't call " << __PRETTY_FUNCTION__ << " while current Object is nullptr."); } else { // set current (container) object as new current object (decrease depth) m_currentObjects.pop_back(); m_level--; } } void LoadHandler::addUnresolvedReference(const std::string &name, std::shared_ptr<ecore::EObject> object, std::shared_ptr<ecore::EStructuralFeature> esf) { if (object != nullptr) { if (esf != nullptr) { m_unresolvedReferences.push_back(persistence::base::UnresolvedReference(name, object, esf)); } else { MSG_ERROR(MSG_FLF << " esf is a nullptr"); } } else { MSG_ERROR(MSG_FLF << " object is a nullptr"); } } void LoadHandler::resolveReferences() { while (!m_unresolvedReferences.empty()) { persistence::base::UnresolvedReference uref = m_unresolvedReferences.back(); m_unresolvedReferences.pop_back(); std::string name = uref.refName; std::shared_ptr<ecore::EObject> object = uref.eObject; std::shared_ptr<ecore::EStructuralFeature> esf = uref.eStructuralFeature; std::list<std::shared_ptr<ecore::EObject>> references; try { if (esf->getUpperBound() == 1) { // EStructuralFeature is a single object solve(name, references, object, esf); } else { // EStructuralFeature is a list of objects std::list<std::string> _strs; std::string _tmpStr; boost::split(_strs, name, boost::is_any_of(" ")); while (_strs.size() > 0) { _tmpStr = _strs.front(); if (std::string::npos != _tmpStr.find("#//") || !m_isXSIMode) { solve(_tmpStr, references, object, esf); } _strs.pop_front(); } // Call resolveReferences() of corresponding 'object' object->resolveReferences(esf->getFeatureID(), references); } } catch (std::exception& e) { MSG_ERROR(MSG_FLF << " Exception: " << e.what()); } } } void LoadHandler::setThisPtr(std::shared_ptr<LoadHandler> thisPtr) { m_thisPtr = thisPtr; } void LoadHandler::solve(const std::string& name, std::list<std::shared_ptr<ecore::EObject>> references, std::shared_ptr<ecore::EObject> object, std::shared_ptr<ecore::EStructuralFeature> esf) { bool found = false; bool libraryLoaded = false; while (!found) { std::shared_ptr<ecore::EObject> resolved_object = this->getObjectByRef(name); if (resolved_object) { references.push_back(resolved_object); // Call resolveReferences() of corresponding 'object' object->resolveReferences(esf->getFeatureID(), references); found = true; } else { if (libraryLoaded) { return; } loadTypes(name); libraryLoaded = true; } } } void LoadHandler::loadTypes(const std::string& name) { unsigned int indexStartUri = name.find(" "); unsigned int indexEndUri = name.find("#"); if (indexStartUri != std::string::npos) { std::string nsURI = name.substr(indexStartUri+1, indexEndUri-indexStartUri-1); std::shared_ptr<PluginFramework> pluginFramework = PluginFramework::eInstance(); std::shared_ptr<MDE4CPPPlugin> plugin = pluginFramework->findPluginByUri(nsURI); if (plugin) { std::shared_ptr<EcoreModelPlugin> ecorePlugin = std::dynamic_pointer_cast<EcoreModelPlugin>(plugin); if (ecorePlugin) { loadTypes(ecorePlugin->getEPackage()); return; } std::shared_ptr<UMLModelPlugin> umlPlugin = std::dynamic_pointer_cast<UMLModelPlugin>(plugin); if (umlPlugin) { loadTypes(umlPlugin->getPackage(), umlPlugin->eNS_URI()); } } } } void LoadHandler::loadTypes(std::shared_ptr<ecore::EPackage> package) { std::shared_ptr<Bag<ecore::EClassifier>> eClassifiers = package->getEClassifiers(); for (std::shared_ptr<ecore::EClassifier> eClassifier : *eClassifiers) { // Filter only EDataType objects and add to handler's internal map std::shared_ptr<ecore::EClass> _metaClass = eClassifier->eClass(); addToMap(eClassifier, false); // TODO add default parameter force=true to addToMap() } } void LoadHandler::loadTypes(std::shared_ptr<uml::Package> package, std::string uri) { std::shared_ptr<Bag<uml::NamedElement>> memberList = package->getMember(); for (std::shared_ptr<uml::NamedElement> member : *memberList) { // Filter only EDataType objects and add to handler's internal map std::string metaClassName = ""; std::shared_ptr<ecore::EClass> ecoreMetaClass = member->eClass(); if (ecoreMetaClass) { auto x = ecoreMetaClass->getEPackage().lock(); if (x) { metaClassName = x->getName() + ":" + ecoreMetaClass->getName(); } else { metaClassName = ecoreMetaClass->getName(); } } else { std::shared_ptr<uml::Class> metaClass = member->getMetaClass(); if (metaClass == nullptr) { metaClassName = metaClass->getName(); } } std::string ref = metaClassName + " " + uri + "#" + member->getName(); m_refToObject_map.insert(std::pair<std::string, std::shared_ptr<ecore::EObject>>(ref, member)); MSG_DEBUG("Add to map: '" << ref << "'"); } } std::map<std::string, std::shared_ptr<ecore::EObject>> LoadHandler::getTypesMap() { return m_refToObject_map; } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _mitkExtendedLabelStatisticsImageFilter_hxx #define _mitkExtendedLabelStatisticsImageFilter_hxx #include "mitkExtendedLabelStatisticsImageFilter.h" #include "itkImageRegionConstIteratorWithIndex.h" namespace itk { template< class TInputImage , class TLabelImage> ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage > ::ExtendedLabelStatisticsImageFilter() : LabelStatisticsImageFilter< TInputImage, TLabelImage >() { } template< class TInputImage, class TLabelImage > typename ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >::RealType ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage > ::GetKurtosis(LabelPixelType label) const { CoefficientsMapConstIterator mapIt; mapIt = m_LabelStatisticsCoefficients.find(label); if ( mapIt == m_LabelStatisticsCoefficients.end() ) { // label does not exist, return a default value return NumericTraits< PixelType >::Zero; } else { return ( *mapIt ).second.m_Kurtosis; } } template< class TInputImage, class TLabelImage > typename ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >::RealType ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage > ::GetSkewness(LabelPixelType label) const { CoefficientsMapConstIterator mapIt; mapIt = m_LabelStatisticsCoefficients.find(label); if ( mapIt == m_LabelStatisticsCoefficients.end() ) { // label does not exist, return a default value return NumericTraits< PixelType >::Zero; } else { return ( *mapIt ).second.m_Skewness; } } template< class TInputImage, class TLabelImage > void ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >:: ComputeSkewnessAndKurtosis() { typename TLabelImage::RegionType Subregion; RealType baseOfSkewnessAndCurtosis( 0.0 ); RealType kurtosis( 0.0 ); RealType skewness( 0.0 ); std::list< LabelPixelType> relevantLabels; bool maskNonEmpty = false; LabelPixelType i; for ( i = 1; i < 4096; ++i ) { if ( this->HasLabel( i ) ) { relevantLabels.push_back( i ); maskNonEmpty = true; m_LabelStatisticsCoefficients.insert( std::make_pair(i, CoefficientsClass()) ); } } if ( maskNonEmpty ) { typename std::list< LabelPixelType >::const_iterator it; for ( it = relevantLabels.begin(); it != relevantLabels.end(); ++it ) { RealType sigma = GetSigma( *it ); RealType mean = GetMean( *it ); Subregion = Superclass::GetRegion(*it); int count( GetCount(*it) ); if ( count == 0 || sigma==0) { throw std::logic_error( "Empty segmentation" ); } ImageRegionConstIteratorWithIndex< TInputImage > it1 (this->GetInput(), Subregion); ImageRegionConstIterator< TLabelImage > labelIt (this->GetLabelInput(), Subregion); for (it1.GoToBegin(); !it1.IsAtEnd(); ++it1, ++labelIt) { if (labelIt.Get() == *it) { baseOfSkewnessAndCurtosis = (it1.Get() -mean) / sigma; kurtosis += std::pow( baseOfSkewnessAndCurtosis, 4.0 ); skewness += std::pow( baseOfSkewnessAndCurtosis, 3.0 ); } } m_LabelStatisticsCoefficients[*it].m_Skewness = RealType(skewness/count); m_LabelStatisticsCoefficients[*it].m_Kurtosis = RealType(kurtosis/count); } } } template< class TInputImage, class TLabelImage > void ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >:: AfterThreadedGenerateData() { Superclass::AfterThreadedGenerateData(); ComputeSkewnessAndKurtosis(); } } // end namespace itk #endif <commit_msg>improved exception handling to fix unittest<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _mitkExtendedLabelStatisticsImageFilter_hxx #define _mitkExtendedLabelStatisticsImageFilter_hxx #include "mitkExtendedLabelStatisticsImageFilter.h" #include "itkImageRegionConstIteratorWithIndex.h" #include "itkImageRegionConstIterator.h" #include "mitkNumericConstants.h" #include "mitkLogMacros.h" namespace itk { template< class TInputImage , class TLabelImage> ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage > ::ExtendedLabelStatisticsImageFilter() : LabelStatisticsImageFilter< TInputImage, TLabelImage >() { } template< class TInputImage, class TLabelImage > typename ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >::RealType ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage > ::GetKurtosis(LabelPixelType label) const { CoefficientsMapConstIterator mapIt; mapIt = m_LabelStatisticsCoefficients.find(label); if ( mapIt == m_LabelStatisticsCoefficients.end() ) { // label does not exist, return a default value return NumericTraits< PixelType >::Zero; } else { return ( *mapIt ).second.m_Kurtosis; } } template< class TInputImage, class TLabelImage > typename ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >::RealType ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage > ::GetSkewness(LabelPixelType label) const { CoefficientsMapConstIterator mapIt; mapIt = m_LabelStatisticsCoefficients.find(label); if ( mapIt == m_LabelStatisticsCoefficients.end() ) { // label does not exist, return a default value return NumericTraits< PixelType >::Zero; } else { return ( *mapIt ).second.m_Skewness; } } template< class TInputImage, class TLabelImage > void ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >:: ComputeSkewnessAndKurtosis() { typename TLabelImage::RegionType Subregion; RealType baseOfSkewnessAndCurtosis( 0.0 ); RealType kurtosis( 0.0 ); RealType skewness( 0.0 ); std::list< LabelPixelType> relevantLabels; bool maskNonEmpty = false; LabelPixelType i; for ( i = 1; i < 4096; ++i ) { if ( this->HasLabel( i ) ) { relevantLabels.push_back( i ); maskNonEmpty = true; m_LabelStatisticsCoefficients.insert( std::make_pair(i, CoefficientsClass()) ); } } if ( maskNonEmpty ) { typename std::list< LabelPixelType >::const_iterator it; for ( it = relevantLabels.cbegin(); it != relevantLabels.cend(); ++it ) { RealType sigma = GetSigma( *it ); RealType mean = GetMean( *it ); Subregion = Superclass::GetRegion(*it); int count( GetCount(*it) ); if ( count == 0 ) { throw std::logic_error( "Empty segmentation" ); } if ( fabs( sigma ) < typename mitk::sqrteps ) { throw std::logic_error( "Sigma == 0" ); } ImageRegionConstIteratorWithIndex< TInputImage > it1 (this->GetInput(), Subregion); ImageRegionConstIterator< TLabelImage > labelIt (this->GetLabelInput(), Subregion); for (it1.GoToBegin(); !it1.IsAtEnd(); ++it1, ++labelIt) { if (labelIt.Get() == *it) { baseOfSkewnessAndCurtosis = (it1.Get() -mean) / sigma; kurtosis += std::pow( baseOfSkewnessAndCurtosis, 4.0 ); skewness += std::pow( baseOfSkewnessAndCurtosis, 3.0 ); } } m_LabelStatisticsCoefficients[*it].m_Skewness = RealType(skewness/count); m_LabelStatisticsCoefficients[*it].m_Kurtosis = RealType(kurtosis/count); } } } template< class TInputImage, class TLabelImage > void ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >:: AfterThreadedGenerateData() { Superclass::AfterThreadedGenerateData(); try { ComputeSkewnessAndKurtosis(); } catch ( const std::exception& e ) { MITK_ERROR << "Caught an exception during calculation of skewness and kurtosis: " << e.what(); } } } // end namespace itk #endif <|endoftext|>
<commit_before>/* Copyright (c) 2013, Project OSRM, Dennis Luxen, others 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. 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 "OSRM.h" #include "OSRM_impl.h" #include "../Plugins/HelloWorldPlugin.h" #include "../Plugins/LocatePlugin.h" #include "../Plugins/NearestPlugin.h" #include "../Plugins/TimestampPlugin.h" #include "../Plugins/ViaRoutePlugin.h" #include "../Server/DataStructures/BaseDataFacade.h" #include "../Server/DataStructures/InternalDataFacade.h" #include "../Server/DataStructures/SharedBarriers.h" #include "../Server/DataStructures/SharedDataFacade.h" #include <boost/assert.hpp> OSRM_impl::OSRM_impl( const ServerPaths & server_paths, const bool use_shared_memory ) : use_shared_memory(use_shared_memory) { if( !use_shared_memory ) { query_data_facade = new InternalDataFacade<QueryEdge::EdgeData>( server_paths ); } else { barrier = new SharedBarriers(); query_data_facade = new SharedDataFacade<QueryEdge::EdgeData>( ); } //The following plugins handle all requests. RegisterPlugin( new HelloWorldPlugin() ); RegisterPlugin( new LocatePlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); RegisterPlugin( new NearestPlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); RegisterPlugin( new TimestampPlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); RegisterPlugin( new ViaRoutePlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); } OSRM_impl::~OSRM_impl() { BOOST_FOREACH(PluginMap::value_type & plugin_pointer, plugin_map) { delete plugin_pointer.second; } if( use_shared_memory ) { delete barrier; } } void OSRM_impl::RegisterPlugin(BasePlugin * plugin) { SimpleLogger().Write() << "loaded plugin: " << plugin->GetDescriptor(); if( plugin_map.find(plugin->GetDescriptor()) != plugin_map.end() ) { delete plugin_map.find(plugin->GetDescriptor())->second; } plugin_map.emplace(plugin->GetDescriptor(), plugin); } void OSRM_impl::RunQuery(RouteParameters & route_parameters, http::Reply & reply) { const PluginMap::const_iterator & iter = plugin_map.find( route_parameters.service ); if(plugin_map.end() != iter) { reply.status = http::Reply::ok; if( use_shared_memory ) { // lock update pending boost::interprocess::scoped_lock< boost::interprocess::named_mutex > pending_lock(barrier->pending_update_mutex); // lock query boost::interprocess::scoped_lock< boost::interprocess::named_mutex > query_lock(barrier->query_mutex); // unlock update pending pending_lock.unlock(); // increment query count ++(barrier->number_of_queries); (static_cast<SharedDataFacade<QueryEdge::EdgeData>* >(query_data_facade))->CheckAndReloadFacade(); } iter->second->HandleRequest(route_parameters, reply ); if( use_shared_memory ) { // lock query boost::interprocess::scoped_lock< boost::interprocess::named_mutex > query_lock(barrier->query_mutex); // decrement query count --(barrier->number_of_queries); BOOST_ASSERT_MSG( 0 <= barrier->number_of_queries, "invalid number of queries" ); // notify all processes that were waiting for this condition if (0 == barrier->number_of_queries) { barrier->no_running_queries_condition.notify_all(); } } } else { reply = http::Reply::StockReply(http::Reply::badRequest); } } // proxy code for compilation firewall OSRM::OSRM( const ServerPaths & paths, const bool use_shared_memory ) : OSRM_pimpl_(new OSRM_impl(paths, use_shared_memory)) { } OSRM::~OSRM() { delete OSRM_pimpl_; } void OSRM::RunQuery(RouteParameters & route_parameters, http::Reply & reply) { OSRM_pimpl_->RunQuery(route_parameters, reply); } <commit_msg>fix inverted logic<commit_after>/* Copyright (c) 2013, Project OSRM, Dennis Luxen, others 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. 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 "OSRM.h" #include "OSRM_impl.h" #include "../Plugins/HelloWorldPlugin.h" #include "../Plugins/LocatePlugin.h" #include "../Plugins/NearestPlugin.h" #include "../Plugins/TimestampPlugin.h" #include "../Plugins/ViaRoutePlugin.h" #include "../Server/DataStructures/BaseDataFacade.h" #include "../Server/DataStructures/InternalDataFacade.h" #include "../Server/DataStructures/SharedBarriers.h" #include "../Server/DataStructures/SharedDataFacade.h" #include <boost/assert.hpp> OSRM_impl::OSRM_impl( const ServerPaths & server_paths, const bool use_shared_memory ) : use_shared_memory(use_shared_memory) { if (use_shared_memory) { barrier = new SharedBarriers(); query_data_facade = new SharedDataFacade<QueryEdge::EdgeData>( ); } else { query_data_facade = new InternalDataFacade<QueryEdge::EdgeData>( server_paths ); } //The following plugins handle all requests. RegisterPlugin( new HelloWorldPlugin() ); RegisterPlugin( new LocatePlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); RegisterPlugin( new NearestPlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); RegisterPlugin( new TimestampPlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); RegisterPlugin( new ViaRoutePlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); } OSRM_impl::~OSRM_impl() { BOOST_FOREACH(PluginMap::value_type & plugin_pointer, plugin_map) { delete plugin_pointer.second; } if( use_shared_memory ) { delete barrier; } } void OSRM_impl::RegisterPlugin(BasePlugin * plugin) { SimpleLogger().Write() << "loaded plugin: " << plugin->GetDescriptor(); if( plugin_map.find(plugin->GetDescriptor()) != plugin_map.end() ) { delete plugin_map.find(plugin->GetDescriptor())->second; } plugin_map.emplace(plugin->GetDescriptor(), plugin); } void OSRM_impl::RunQuery(RouteParameters & route_parameters, http::Reply & reply) { const PluginMap::const_iterator & iter = plugin_map.find( route_parameters.service ); if(plugin_map.end() != iter) { reply.status = http::Reply::ok; if( use_shared_memory ) { // lock update pending boost::interprocess::scoped_lock< boost::interprocess::named_mutex > pending_lock(barrier->pending_update_mutex); // lock query boost::interprocess::scoped_lock< boost::interprocess::named_mutex > query_lock(barrier->query_mutex); // unlock update pending pending_lock.unlock(); // increment query count ++(barrier->number_of_queries); (static_cast<SharedDataFacade<QueryEdge::EdgeData>* >(query_data_facade))->CheckAndReloadFacade(); } iter->second->HandleRequest(route_parameters, reply ); if( use_shared_memory ) { // lock query boost::interprocess::scoped_lock< boost::interprocess::named_mutex > query_lock(barrier->query_mutex); // decrement query count --(barrier->number_of_queries); BOOST_ASSERT_MSG( 0 <= barrier->number_of_queries, "invalid number of queries" ); // notify all processes that were waiting for this condition if (0 == barrier->number_of_queries) { barrier->no_running_queries_condition.notify_all(); } } } else { reply = http::Reply::StockReply(http::Reply::badRequest); } } // proxy code for compilation firewall OSRM::OSRM( const ServerPaths & paths, const bool use_shared_memory ) : OSRM_pimpl_(new OSRM_impl(paths, use_shared_memory)) { } OSRM::~OSRM() { delete OSRM_pimpl_; } void OSRM::RunQuery(RouteParameters & route_parameters, http::Reply & reply) { OSRM_pimpl_->RunQuery(route_parameters, reply); } <|endoftext|>
<commit_before>// This is an independent project of an individual developer. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // MGenTest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "MGenTest.h" #include "../MGen/GLibrary/GLib.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // The one and only application object CWinApp theApp; using namespace std; CString current_dir; ofstream logfile; int continuous_integration = 0; int nRetCode = 0; vector<CString> errorMessages; CString pname; // Default time to start aborting generation int wait_sec = 60; // Default time to consider generation timeout int wait_sec2 = 120; void InitErrorMessages() { errorMessages.resize(1000); errorMessages[0] = "OK"; errorMessages[10] = "MGen detected critical errors during run"; errorMessages[11] = "MGen generator freeze on exit - possible error in generator"; errorMessages[100] = "GetExitCodeProcess error in MGenTest (for MGen.exe)"; errorMessages[101] = "MGen process did not exit correctly - possible crash"; errorMessages[102] = "GetExitCodeProcess error in MGenTest"; } CString GetErrorMessage(int e) { if (e < errorMessages.size()) return errorMessages[e]; else return ""; } void Run(CString fname, CString par, int delay) { DWORD ecode; SHELLEXECUTEINFO sei = { 0 }; sei.cbSize = sizeof(SHELLEXECUTEINFO); sei.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI; sei.hwnd = NULL; sei.lpVerb = NULL; sei.lpFile = fname; sei.lpParameters = par; sei.lpDirectory = NULL; sei.nShow = SW_SHOWNORMAL; sei.hInstApp = NULL; ShellExecuteEx(&sei); WaitForSingleObject(sei.hProcess, delay); if (!GetExitCodeProcess(sei.hProcess, &ecode)) ecode = 102; if (ecode != 0 && ecode != 259) { nRetCode = 3; cout << "Exit code " << ecode << ": " << fname << " " << par << "\n"; } } void Log(CString st, int level = 0) { cout << st; logfile << st; if (continuous_integration && level > 0) { CString cat; if (level == 1) cat = "Information"; if (level == 2) cat = "Warning"; if (level == 3) cat = "Error"; CString par = "AddMessage \"" + st + "\" -Category " + cat + " >> autotest\\run.log 2>&1"; Run("appveyor", par, 1000); } } CString file(CString fname) { CString st, st2; ifstream fs; // Check file exists if (!CGLib::fileExists(fname)) { cout << "Not found file " << fname << "\n"; } fs.open(fname); char pch[2550]; while (fs.good()) { // Get line fs.getline(pch, 2550); st2 = pch; if (!st2.IsEmpty()) { st += "- " + st2 + "\n"; } } fs.close(); return st; } void ClearBuffer() { fstream fs; fs.open("autotest\\buffer.log", ios::out); fs.close(); remove("autotest\\exit.log"); } void PublishTest(CString tname, int result, int tpassed) { CString emes = GetErrorMessage(result); CString st; CString st2; st2.Format("%s: code %d (%s) in %d ms\n", tname, result, emes, tpassed); if (result) { nRetCode = 2; Log(st2, 3); } else { Log(st2, 1); } // Show errors CString errors = file("autotest/buffer.log"); cout << errors; if (continuous_integration) { CString cat = "Passed"; if (result) cat = "Failed"; st.Format("UpdateTest \"%s\" -Framework MSTest -FileName MGen.exe -Duration %d -Outcome %s -ErrorMessage \"%d: %s\" >> autotest\\run.log 2>&1", tname, tpassed, cat, result, emes); Run("appveyor", st, 1000); // Send errors separately in case of command line overflow st.Format("UpdateTest \"%s\" -Framework MSTest -FileName MGen.exe -Duration %d -Outcome %s -ErrorMessage \"%d: %s\" -ErrorStackTrace \"%s\" >> autotest\\run.log 2>&1", tname, tpassed, cat, result, emes, errors); Run("appveyor", st, 1000); } } void LoadConfig() { long long time_start, time_stop; vector<CString> ast; CString fname = "autotest\\test.csv"; // Check file exists if (!CGLib::fileExists(fname)) { cout << "Not found file " << fname << "\n"; } // Clear expect.log remove("autotest\\expect.log"); // Clear run.log fstream fs; fs.open("autotest\\run.log", ios::out); fs.close(); // Open file fs.open(fname); DWORD ecode; CString st, st2; char pch[2550]; int pos = 0; int passed; while (fs.good()) { fs.getline(pch, 2550); st = pch; pos = st.Find("#"); if (pos != -1) st = st.Left(pos); st.Trim(); if (st.GetLength()) { CGLib::Tokenize(st, ast, ";"); pname = ast[0]; if (ast.size() > 1 && atoi(ast[1]) > 0) wait_sec = atoi(ast[1]); if (ast.size() > 2 && atoi(ast[2]) > 0) wait_sec2 = atoi(ast[2]); ClearBuffer(); if (continuous_integration) Run("appveyor", "AddTest \"" + pname + "\" -Framework MSTest -FileName MGen.exe -Outcome Running >> autotest\\run.log 2>&1", 1000); Log("Starting test config: " + pname + "\n"); // MGen.exe -test=5 configs\GenCA2\good-cp5.pl st2.Format("-test=%d %s", wait_sec, pname); SHELLEXECUTEINFO sei = { 0 }; sei.cbSize = sizeof(SHELLEXECUTEINFO); sei.fMask = SEE_MASK_NOCLOSEPROCESS; sei.hwnd = NULL; sei.lpVerb = NULL; sei.lpFile = "MGen.exe"; sei.lpParameters = st2; sei.lpDirectory = NULL; sei.nShow = SW_SHOW; sei.hInstApp = NULL; time_start = CGLib::time(); ShellExecuteEx(&sei); if (WaitForSingleObject(sei.hProcess, wait_sec2 * 1000) == WAIT_TIMEOUT) { Log(pname + ": Timeout waiting for process\n", 3); exit(1); } time_stop = CGLib::time(); passed = time_stop - time_start; if (!GetExitCodeProcess(sei.hProcess, &ecode)) ecode = 100; if (!CGLib::fileExists("autotest\\exit.log")) ecode = 101; PublishTest(pname, ecode, passed); } } Run("appveyor", "PushArtifact autotest\\expect.log -Verbosity Normal -Type Auto -FileName expect.log >> run.log 2>&1", 1000); // Show run output //Run("cmd.exe", "/c echo Test >> autotest\\run.log", 1000); CString outs = file("autotest\\run.log"); cout << "Run log:\n"; cout << outs; // Show expect output outs = file("autotest\\expect.log"); cout << "Expect log:\n"; cout << outs; fs.close(); } int test() { if (getenv("APPVEYOR_PROJECT_NAME") != NULL) { continuous_integration = 1; } logfile.open("autotest\\test.log", ios_base::app); TCHAR buffer[MAX_PATH]; GetCurrentDirectory(MAX_PATH, buffer); current_dir = string(buffer).c_str(); Log("Current dir: " + current_dir + "\n"); LoadConfig(); logfile.close(); // Do not pause if continuous integration if (!continuous_integration) { cout << "Press any key to continue... "; _getch(); } return 0; } int main() { InitErrorMessages(); HMODULE hModule = ::GetModuleHandle(nullptr); if (hModule != nullptr) { // initialize MFC and print and error on failure if (!AfxWinInit(hModule, nullptr, ::GetCommandLine(), 0)) { wprintf(L"Fatal Error: MFC initialization failed\n"); nRetCode = 4; } else { test(); } } else { wprintf(L"Fatal Error: GetModuleHandle failed\n"); nRetCode = 1; } return nRetCode; } <commit_msg>MGenTest: Report initial test command line to appveyor<commit_after>// This is an independent project of an individual developer. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // MGenTest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "MGenTest.h" #include "../MGen/GLibrary/GLib.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // The one and only application object CWinApp theApp; using namespace std; CString current_dir; ofstream logfile; int continuous_integration = 0; int nRetCode = 0; vector<CString> errorMessages; CString pname; // Default time to start aborting generation int wait_sec = 60; // Default time to consider generation timeout int wait_sec2 = 120; void InitErrorMessages() { errorMessages.resize(1000); errorMessages[0] = "OK"; errorMessages[10] = "MGen detected critical errors during run"; errorMessages[11] = "MGen generator freeze on exit - possible error in generator"; errorMessages[100] = "GetExitCodeProcess error in MGenTest (for MGen.exe)"; errorMessages[101] = "MGen process did not exit correctly - possible crash"; errorMessages[102] = "GetExitCodeProcess error in MGenTest"; } CString GetErrorMessage(int e) { if (e < errorMessages.size()) return errorMessages[e]; else return ""; } void Run(CString fname, CString par, int delay) { DWORD ecode; SHELLEXECUTEINFO sei = { 0 }; sei.cbSize = sizeof(SHELLEXECUTEINFO); sei.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI; sei.hwnd = NULL; sei.lpVerb = NULL; sei.lpFile = fname; sei.lpParameters = par; sei.lpDirectory = NULL; sei.nShow = SW_SHOWNORMAL; sei.hInstApp = NULL; ShellExecuteEx(&sei); WaitForSingleObject(sei.hProcess, delay); if (!GetExitCodeProcess(sei.hProcess, &ecode)) ecode = 102; if (ecode != 0 && ecode != 259) { nRetCode = 3; cout << "Exit code " << ecode << ": " << fname << " " << par << "\n"; } } void Log(CString st, int level = 0) { cout << st; logfile << st; if (continuous_integration && level > 0) { CString cat; if (level == 1) cat = "Information"; if (level == 2) cat = "Warning"; if (level == 3) cat = "Error"; CString par = "AddMessage \"" + st + "\" -Category " + cat + " >> autotest\\run.log 2>&1"; Run("appveyor", par, 1000); } } CString file(CString fname) { CString st, st2; ifstream fs; // Check file exists if (!CGLib::fileExists(fname)) { cout << "Not found file " << fname << "\n"; } fs.open(fname); char pch[2550]; while (fs.good()) { // Get line fs.getline(pch, 2550); st2 = pch; if (!st2.IsEmpty()) { st += "- " + st2 + "\n"; } } fs.close(); return st; } void ClearBuffer() { fstream fs; fs.open("autotest\\buffer.log", ios::out); fs.close(); remove("autotest\\exit.log"); } void PublishTest(CString tname, int result, int tpassed, CString params) { CString emes = GetErrorMessage(result); CString st; CString st2; st2.Format("%s: code %d (%s) in %d ms\n", tname, result, emes, tpassed); if (result) { nRetCode = 2; Log(st2, 3); } else { Log(st2, 1); } // Show errors CString errors = file("autotest/buffer.log"); cout << errors; if (continuous_integration) { CString cat = "Passed"; if (result) cat = "Failed"; st.Format("UpdateTest \"%s\" -Framework MSTest -FileName MGen.exe -Duration %d -Outcome %s -ErrorMessage \"%d: %s\" >> autotest\\run.log 2>&1", tname, tpassed, cat, result, emes); Run("appveyor", st, 1000); // Send errors separately in case of command line overflow st.Format("UpdateTest \"%s\" -Framework MSTest -FileName MGen.exe -Duration %d -Outcome %s -ErrorMessage \"%d: %s\" -StdOut \"MGen.exe %s\" -ErrorStackTrace \"%s\" >> autotest\\run.log 2>&1", tname, tpassed, cat, result, emes, params, errors); Run("appveyor", st, 1000); } } void LoadConfig() { long long time_start, time_stop; vector<CString> ast; CString fname = "autotest\\test.csv"; // Check file exists if (!CGLib::fileExists(fname)) { cout << "Not found file " << fname << "\n"; } // Clear expect.log remove("autotest\\expect.log"); // Clear run.log fstream fs; fs.open("autotest\\run.log", ios::out); fs.close(); // Open file fs.open(fname); DWORD ecode; CString st, st2; char pch[2550]; int pos = 0; int passed; while (fs.good()) { fs.getline(pch, 2550); st = pch; pos = st.Find("#"); if (pos != -1) st = st.Left(pos); st.Trim(); if (st.GetLength()) { CGLib::Tokenize(st, ast, ";"); pname = ast[0]; if (ast.size() > 1 && atoi(ast[1]) > 0) wait_sec = atoi(ast[1]); if (ast.size() > 2 && atoi(ast[2]) > 0) wait_sec2 = atoi(ast[2]); ClearBuffer(); if (continuous_integration) Run("appveyor", "AddTest \"" + pname + "\" -Framework MSTest -FileName MGen.exe -Outcome Running >> autotest\\run.log 2>&1", 1000); // MGen.exe -test=5 configs\GenCA2\good-cp5.pl st2.Format("-test=%d %s", wait_sec, pname); Log("Starting test config: " + st2 + "\n"); SHELLEXECUTEINFO sei = { 0 }; sei.cbSize = sizeof(SHELLEXECUTEINFO); sei.fMask = SEE_MASK_NOCLOSEPROCESS; sei.hwnd = NULL; sei.lpVerb = NULL; sei.lpFile = "MGen.exe"; sei.lpParameters = st2; sei.lpDirectory = NULL; sei.nShow = SW_SHOW; sei.hInstApp = NULL; time_start = CGLib::time(); ShellExecuteEx(&sei); if (WaitForSingleObject(sei.hProcess, wait_sec2 * 1000) == WAIT_TIMEOUT) { Log(pname + ": Timeout waiting for process\n", 3); exit(1); } time_stop = CGLib::time(); passed = time_stop - time_start; if (!GetExitCodeProcess(sei.hProcess, &ecode)) ecode = 100; if (!CGLib::fileExists("autotest\\exit.log")) ecode = 101; PublishTest(pname, ecode, passed, st2); } } Run("appveyor", "PushArtifact autotest\\expect.log -Verbosity Normal -Type Auto -FileName expect.log >> run.log 2>&1", 1000); // Show run output //Run("cmd.exe", "/c echo Test >> autotest\\run.log", 1000); CString outs = file("autotest\\run.log"); cout << "Run log:\n"; cout << outs; // Show expect output outs = file("autotest\\expect.log"); cout << "Expect log:\n"; cout << outs; fs.close(); } int test() { if (getenv("APPVEYOR_PROJECT_NAME") != NULL) { continuous_integration = 1; } logfile.open("autotest\\test.log", ios_base::app); TCHAR buffer[MAX_PATH]; GetCurrentDirectory(MAX_PATH, buffer); current_dir = string(buffer).c_str(); Log("Current dir: " + current_dir + "\n"); LoadConfig(); logfile.close(); // Do not pause if continuous integration if (!continuous_integration) { cout << "Press any key to continue... "; _getch(); } return 0; } int main() { InitErrorMessages(); HMODULE hModule = ::GetModuleHandle(nullptr); if (hModule != nullptr) { // initialize MFC and print and error on failure if (!AfxWinInit(hModule, nullptr, ::GetCommandLine(), 0)) { wprintf(L"Fatal Error: MFC initialization failed\n"); nRetCode = 4; } else { test(); } } else { wprintf(L"Fatal Error: GetModuleHandle failed\n"); nRetCode = 1; } return nRetCode; } <|endoftext|>
<commit_before>/* MCH DA for online occupancy Contact: Laurent Aphecetche <[email protected]>, Jean-Luc Charvet <[email protected]>, Alberto Baldisseri <[email protected]> Link: Run Type: PHYSICS STANDALONE DA Type: MON Number of events needed: all (or at least as much as possible...) Input Files: 09000094301009.10.raw Output Files: mch.occupancy, to be exported to the DAQ FXS Trigger types used: PHYSICS_EVENT */ /************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /// /// MUON TRACKER DA to compute the hit count at manu level. /// /// In the end, this DA produces an ASCII file containing /// the hit count of all the manus (that were seen in the data flow) /// of the MUON Tracker (and the number of seen events, so we can /// later on compute the occupancy) /// /// $Id$ #include "AliMUON2DMap.h" #include "AliMUONCalibParamNI.h" #include "AliMUONRawStreamTrackerHP.h" #include "AliMpConstants.h" #include "AliRawEventHeaderBase.h" #include "AliRawReaderDate.h" #include "Riostream.h" #include "TPluginManager.h" #include "TROOT.h" #include "TString.h" #include "TTimeStamp.h" #include "TStopwatch.h" #include "daqDA.h" #include "event.h" #include "monitor.h" #ifdef ALI_AMORE #include <AmoreDA.h> #include "TObjString.h" #include "TSystem.h" #include <sstream> #endif const char* OUTPUT_FILE = "mch.occupancy"; const char* DAVERSION = "MUONTRKOCCda v1.2 ($Id$)"; //______________________________________________________________________________ void Add(AliMUONVStore& destStore, const AliMUONVStore& srcStore) { /// Add all elements from srcStore to destStore /// Each element of srcStore is supposed to be an AliMUONCalibParamNI, /// with ID0=busPatchId and ID1=manuId TIter next(srcStore.CreateIterator()); AliMUONVCalibParam* source; while ( ( source = static_cast<AliMUONVCalibParam*>(next()) ) ) { AliMUONCalibParamNI* dest = static_cast<AliMUONCalibParamNI*>(destStore.FindObject(source->ID0(),source->ID1())); if (!dest) { dest = static_cast<AliMUONCalibParamNI*>(source->Clone()); destStore.Add(dest); } else { for ( Int_t i = 0; i < source->Size(); ++i ) { for ( Int_t j = 0; j < source->Dimension(); ++j ) { dest->SetValueAsIntFast(i,j,dest->ValueAsIntFast(i,j)+source->ValueAsIntFast(i,j)); } } } } } //______________________________________________________________________________ void GenerateOutputFile(const AliMUONVStore& store, ostream& out, Int_t runNumber, Int_t nevents) { /// Write the channel hit count (grouped by manu) in the output file. TIter next(store.CreateIterator()); AliMUONVCalibParam* manu; out << "//===========================================================================" << endl; out << "// Hit counter file calculated by " << __FILE__ << endl; out << "//===========================================================================" << endl; out << "//" << endl; out << "// * Run Number : " << runNumber << endl; out << "// * File Creation Date : " << TTimeStamp().AsString("l") << endl; out << "//---------------------------------------------------------------------------" << endl; out << "// BP MANU SUM_N NEVENTS" << endl; out << "//---------------------------------------------------------------------------" << endl; while ( ( manu = static_cast<AliMUONVCalibParam*>(next()) ) ) { Int_t sum(0); // Int_t nevents(0); for ( Int_t i = 0; i < manu->Size(); ++i ) { sum += manu->ValueAsInt(i); // nevents = TMath::Max(nevents,manu->ValueAsInt(i,1)); // nevents = TMath::Max(nevents,manu->ValueAsInt(i,1)); } out << Form("%5d %5d %10d %10d",manu->ID0(),manu->ID1(),sum,nevents) << endl; } } //______________________________________________________________________________ int main(int argc, char **argv) { /// Main method. /// /// We loop over all physics events. /// For each event we store the channels that were hit for that event. /// If the event is good, we then increment the list of channels hit for /// the whole run. /// We delete the store for a single event and move to next event. /// /// In the end we output an ASCII file with the necessary information /// to compute the occupancy later on, i.e. the number of times channels /// were seen per manu, and the number of events. /// TStopwatch timers; timers.Start(kTRUE); ios::sync_with_stdio(); cout << "Running " << DAVERSION << endl; if ( argc < 2 ) { cout << "Wrong number of arguments" << endl; cout << "Usage : " << argv[0] << " datasource1 [datasource2] ..." << endl; return -1; } // needed for streamer application gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo", "*", "TStreamerInfo", "RIO", "TStreamerInfo()"); Int_t numberOfEvents(0); Int_t numberOfPhysicsEvent(0); Int_t numberOfBadEvents(0); Int_t numberOfUsedEvents(0); AliMUON2DMap oneEventData(kTRUE); AliMUON2DMap accumulatedData(kTRUE); UInt_t runNumber(0); for ( Int_t i = 1; i < argc; ++i ) { int status; AliRawReaderDate* rawReader(0x0); // define data source : status=monitorSetDataSource(argv[i]); if (status!=0) { printf("MCH Occupancy DA ERROR: monitorSetDataSource() failed: %s\n", monitorDecodeError(status)); return -1; } // Declare monitoring program status=monitorDeclareMp("MUON_TRK_OCC"); if (status!=0) { printf("MCH Occupancy DA ERROR: monitorDeclareMp() failed: %s\n", monitorDecodeError(status)); return -1; } // Define wait event timeout - 1s max monitorSetNowait(); monitorSetNoWaitNetworkTimeout(1000); for(;;) { struct eventHeaderStruct *event(0x0); eventTypeType eventT; status=monitorGetEventDynamic((void **)&event); if (status!=0) { printf("MCH Occupancy DA ERROR: %s\n", monitorDecodeError(status)); delete event; break; } /* check shutdown condition */ if (daqDA_checkShutdown()) { delete event; break; } /* retry if got no event */ if (event==NULL) continue; ++numberOfEvents; eventT=event->eventType; if ((eventT == END_OF_RUN)||(eventT == END_OF_RUN_FILES)) { delete event; break; } if (eventT != PHYSICS_EVENT) { delete event; continue; } ++numberOfPhysicsEvent; rawReader = new AliRawReaderDate((void*)event); if ( rawReader->GetRunNumber() != runNumber ) { if ( runNumber != 0 ) { cout << "Uh oh. That's bad... Changing of run number ???" << endl; delete event; delete rawReader; return -9999; } runNumber = rawReader->GetRunNumber(); } AliMUONRawStreamTrackerHP stream(rawReader); stream.DisableWarnings(); oneEventData.Clear(); Int_t buspatchId; UShort_t manuId; UChar_t manuChannel; UShort_t adc; stream.First(); while ( stream.Next(buspatchId,manuId,manuChannel,adc,kTRUE) ) { AliMUONVCalibParam* one = static_cast<AliMUONVCalibParam*>(oneEventData.FindObject(buspatchId,manuId)); if (!one) { one = new AliMUONCalibParamNI(1,AliMpConstants::ManuNofChannels(),buspatchId,manuId); oneEventData.Add(one); } one->SetValueAsInt(manuChannel,0,one->ValueAsInt(manuChannel,0)+1); } Bool_t badEvent = stream.HasPaddingError() || stream.HasGlitchError(); if ( !badEvent ) { ++numberOfUsedEvents; Add(accumulatedData,oneEventData); } else { ++numberOfBadEvents; } delete event; delete rawReader; } } cout << Form("%12d events processed : %12d physics %d used ones %d bad ones", numberOfEvents,numberOfPhysicsEvent,numberOfUsedEvents,numberOfBadEvents) << endl; ofstream fout(OUTPUT_FILE); GenerateOutputFile(accumulatedData,fout,runNumber,numberOfUsedEvents); fout.close(); #ifdef ALI_AMORE // Send occupancy store (as a big string) to the AMORE DB amore::da::AmoreDA amoreDA(amore::da::AmoreDA::kSender); ostringstream str; GenerateOutputFile(accumulatedData,str,runNumber,numberOfUsedEvents); TObjString occupancyAsString(str.str().c_str()); Int_t status = amoreDA.Send("Occupancy",&occupancyAsString); if ( status ) { cerr << "ERROR : Failed to write occupancies in the AMORE database : " << status << endl; } #endif /* store the result file on FXS */ if (daqDA_FES_storeFile(OUTPUT_FILE,"OCCUPANCY")) return -9; timers.Stop(); printf("\nExecution time : R:%7.2fs C:%7.2fs\n", timers.RealTime(), timers.CpuTime()); return 0; } <commit_msg>Adding a line to be able to generate core dumps online<commit_after>/* MCH DA for online occupancy Contact: Laurent Aphecetche <[email protected]>, Jean-Luc Charvet <[email protected]>, Alberto Baldisseri <[email protected]> Link: Run Type: PHYSICS STANDALONE DA Type: MON Number of events needed: all (or at least as much as possible...) Input Files: 09000094301009.10.raw Output Files: mch.occupancy, to be exported to the DAQ FXS Trigger types used: PHYSICS_EVENT */ /************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /// /// MUON TRACKER DA to compute the hit count at manu level. /// /// In the end, this DA produces an ASCII file containing /// the hit count of all the manus (that were seen in the data flow) /// of the MUON Tracker (and the number of seen events, so we can /// later on compute the occupancy) /// /// $Id$ #include "AliMUON2DMap.h" #include "AliMUONCalibParamNI.h" #include "AliMUONRawStreamTrackerHP.h" #include "AliMpConstants.h" #include "AliRawEventHeaderBase.h" #include "AliRawReaderDate.h" #include "Riostream.h" #include "TPluginManager.h" #include "TROOT.h" #include "TString.h" #include "TTimeStamp.h" #include "TStopwatch.h" #include "daqDA.h" #include "event.h" #include "monitor.h" #ifdef ALI_AMORE #include <AmoreDA.h> #include "TObjString.h" #include "TSystem.h" #include <sstream> #endif const char* OUTPUT_FILE = "mch.occupancy"; const char* DAVERSION = "MUONTRKOCCda v1.2 ($Id$)"; //______________________________________________________________________________ void Add(AliMUONVStore& destStore, const AliMUONVStore& srcStore) { /// Add all elements from srcStore to destStore /// Each element of srcStore is supposed to be an AliMUONCalibParamNI, /// with ID0=busPatchId and ID1=manuId TIter next(srcStore.CreateIterator()); AliMUONVCalibParam* source; while ( ( source = static_cast<AliMUONVCalibParam*>(next()) ) ) { AliMUONCalibParamNI* dest = static_cast<AliMUONCalibParamNI*>(destStore.FindObject(source->ID0(),source->ID1())); if (!dest) { dest = static_cast<AliMUONCalibParamNI*>(source->Clone()); destStore.Add(dest); } else { for ( Int_t i = 0; i < source->Size(); ++i ) { for ( Int_t j = 0; j < source->Dimension(); ++j ) { dest->SetValueAsIntFast(i,j,dest->ValueAsIntFast(i,j)+source->ValueAsIntFast(i,j)); } } } } } //______________________________________________________________________________ void GenerateOutputFile(const AliMUONVStore& store, ostream& out, Int_t runNumber, Int_t nevents) { /// Write the channel hit count (grouped by manu) in the output file. TIter next(store.CreateIterator()); AliMUONVCalibParam* manu; out << "//===========================================================================" << endl; out << "// Hit counter file calculated by " << __FILE__ << endl; out << "//===========================================================================" << endl; out << "//" << endl; out << "// * Run Number : " << runNumber << endl; out << "// * File Creation Date : " << TTimeStamp().AsString("l") << endl; out << "//---------------------------------------------------------------------------" << endl; out << "// BP MANU SUM_N NEVENTS" << endl; out << "//---------------------------------------------------------------------------" << endl; while ( ( manu = static_cast<AliMUONVCalibParam*>(next()) ) ) { Int_t sum(0); // Int_t nevents(0); for ( Int_t i = 0; i < manu->Size(); ++i ) { sum += manu->ValueAsInt(i); // nevents = TMath::Max(nevents,manu->ValueAsInt(i,1)); // nevents = TMath::Max(nevents,manu->ValueAsInt(i,1)); } out << Form("%5d %5d %10d %10d",manu->ID0(),manu->ID1(),sum,nevents) << endl; } } //______________________________________________________________________________ int main(int argc, char **argv) { /// Main method. /// /// We loop over all physics events. /// For each event we store the channels that were hit for that event. /// If the event is good, we then increment the list of channels hit for /// the whole run. /// We delete the store for a single event and move to next event. /// /// In the end we output an ASCII file with the necessary information /// to compute the occupancy later on, i.e. the number of times channels /// were seen per manu, and the number of events. /// signal(SIGSEGV,SIG_DFL); // to be able to get core dumps... TStopwatch timers; timers.Start(kTRUE); ios::sync_with_stdio(); cout << "Running " << DAVERSION << endl; if ( argc < 2 ) { cout << "Wrong number of arguments" << endl; cout << "Usage : " << argv[0] << " datasource1 [datasource2] ..." << endl; return -1; } // needed for streamer application gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo", "*", "TStreamerInfo", "RIO", "TStreamerInfo()"); Int_t numberOfEvents(0); Int_t numberOfPhysicsEvent(0); Int_t numberOfBadEvents(0); Int_t numberOfUsedEvents(0); AliMUON2DMap oneEventData(kTRUE); AliMUON2DMap accumulatedData(kTRUE); UInt_t runNumber(0); for ( Int_t i = 1; i < argc; ++i ) { int status; AliRawReaderDate* rawReader(0x0); // define data source : status=monitorSetDataSource(argv[i]); if (status!=0) { printf("MCH Occupancy DA ERROR: monitorSetDataSource() failed: %s\n", monitorDecodeError(status)); return -1; } // Declare monitoring program status=monitorDeclareMp("MUON_TRK_OCC"); if (status!=0) { printf("MCH Occupancy DA ERROR: monitorDeclareMp() failed: %s\n", monitorDecodeError(status)); return -1; } // Define wait event timeout - 1s max monitorSetNowait(); monitorSetNoWaitNetworkTimeout(1000); for(;;) { struct eventHeaderStruct *event(0x0); eventTypeType eventT; status=monitorGetEventDynamic((void **)&event); if (status!=0) { printf("MCH Occupancy DA ERROR: %s\n", monitorDecodeError(status)); delete event; break; } /* check shutdown condition */ if (daqDA_checkShutdown()) { delete event; break; } /* retry if got no event */ if (event==NULL) continue; ++numberOfEvents; eventT=event->eventType; if ((eventT == END_OF_RUN)||(eventT == END_OF_RUN_FILES)) { delete event; break; } if (eventT != PHYSICS_EVENT) { delete event; continue; } ++numberOfPhysicsEvent; rawReader = new AliRawReaderDate((void*)event); if ( rawReader->GetRunNumber() != runNumber ) { if ( runNumber != 0 ) { cout << "Uh oh. That's bad... Changing of run number ???" << endl; delete event; delete rawReader; return -9999; } runNumber = rawReader->GetRunNumber(); } AliMUONRawStreamTrackerHP stream(rawReader); stream.DisableWarnings(); oneEventData.Clear(); Int_t buspatchId; UShort_t manuId; UChar_t manuChannel; UShort_t adc; stream.First(); while ( stream.Next(buspatchId,manuId,manuChannel,adc,kTRUE) ) { AliMUONVCalibParam* one = static_cast<AliMUONVCalibParam*>(oneEventData.FindObject(buspatchId,manuId)); if (!one) { one = new AliMUONCalibParamNI(1,AliMpConstants::ManuNofChannels(),buspatchId,manuId); oneEventData.Add(one); } one->SetValueAsInt(manuChannel,0,one->ValueAsInt(manuChannel,0)+1); } Bool_t badEvent = stream.HasPaddingError() || stream.HasGlitchError(); if ( !badEvent ) { ++numberOfUsedEvents; Add(accumulatedData,oneEventData); } else { ++numberOfBadEvents; } delete event; delete rawReader; } } cout << Form("%12d events processed : %12d physics %d used ones %d bad ones", numberOfEvents,numberOfPhysicsEvent,numberOfUsedEvents,numberOfBadEvents) << endl; ofstream fout(OUTPUT_FILE); GenerateOutputFile(accumulatedData,fout,runNumber,numberOfUsedEvents); fout.close(); #ifdef ALI_AMORE // Send occupancy store (as a big string) to the AMORE DB amore::da::AmoreDA amoreDA(amore::da::AmoreDA::kSender); ostringstream str; GenerateOutputFile(accumulatedData,str,runNumber,numberOfUsedEvents); TObjString occupancyAsString(str.str().c_str()); Int_t status = amoreDA.Send("Occupancy",&occupancyAsString); if ( status ) { cerr << "ERROR : Failed to write occupancies in the AMORE database : " << status << endl; } #endif /* store the result file on FXS */ if (daqDA_FES_storeFile(OUTPUT_FILE,"OCCUPANCY")) return -9; timers.Stop(); printf("\nExecution time : R:%7.2fs C:%7.2fs\n", timers.RealTime(), timers.CpuTime()); return 0; } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // // Copyright (C) Streamlet. All rights reserved. // // File Name: XmlRpc.cpp // Author: Streamlet // Create Time: 2010-10-28 // Description: // // Version history: // // // //------------------------------------------------------------------------------ #include "XmlRpc.h" #include "XmlRpcValue.h" #include "Encoding.h" #include <WinHttp.h> #pragma comment(lib, "WinHttp.lib") #define XML_RPC_METHOD_CALL L"methodCall" #define XML_RPC_METHOD_NAME L"methodCall" #define XML_RPC_PARAMS L"params" #define XML_RPC_PARAM L"param" #define XML_RPC_METHOD_RESPONSE L"methodResponse" #define XML_RPC_FAULT L"fault" XmlRpc::XmlRpc() : m_bConnected(false) { } XmlRpc::~XmlRpc() { Disconnect(); } bool XmlRpc::SetApiUrl(const xl::String &strUrl) { URL_COMPONENTS urlComp = { sizeof(URL_COMPONENTS) }; urlComp.dwHostNameLength = (DWORD)-1; urlComp.dwUrlPathLength = (DWORD)-1; urlComp.dwExtraInfoLength = (DWORD)-1; if (!WinHttpCrackUrl(strUrl.GetAddress(), 0, 0, &urlComp)) { return false; } m_strHostName += urlComp.lpszHostName; m_strPagePath += urlComp.lpszUrlPath; m_strPagePath += urlComp.lpszExtraInfo; return true; } bool XmlRpc::Connect() { Disconnect(); if (!m_http.Connect(m_strHostName.GetAddress())) { return false; } m_bConnected = true; return true; } void XmlRpc::Disconnect() { if (!m_bConnected) { return; } m_http.Disconnect(); m_bConnected = false; } bool XmlRpc::ExecuteMethod(const xl::String &strMethodName, const xl::Array<XmlRpcValue> &arrParameters, XmlRpcValue *pReturnValue, HANDLE hEventCancel) { XmlInstPtr pInst = MakeXmlInst(); XmlNodePtr pMethodCall = MakeMethodCall(strMethodName, arrParameters); xl::String strRequest = pInst->GetXmlString(L"") + pMethodCall->GetXmlString(L"", L""); xl::StringA strRequestUtf8 = Encoding::StringToUtf8(strRequest); xl::Array<BYTE> arrResponse; if (!m_http.SendRequest(L"POST", m_strPagePath.GetAddress(), NULL, (LPVOID)strRequestUtf8.GetAddress(), strRequestUtf8.Length(), hEventCancel, &arrResponse)) { return false; } arrResponse.PushBack('\0'); xl::StringA strResponseUtf8 = (LPCSTR)&arrResponse[0]; xl::String strResponse = Encoding::Utf8ToString(strRequestUtf8); XmlInstList xmlInst; XmlNodeList xmlNode; if (!XmlParser::ParseXml(strResponse, &xmlInst, &xmlNode)) { return false; } return ParseResponse(*xmlNode.Begin(), pReturnValue); } XmlInstPtr XmlRpc::MakeXmlInst() { XmlInstPtr pInst = new XmlInst; pInst->SetTagName(XML_INST_XML); pInst->Properties().Insert(XML_INST_VERSION, XML_INST_VERSION_1_0); pInst->Properties().Insert(XML_INST_ENCODING, XML_INST_ENCODING_UTF8); return pInst; } XmlNodePtr XmlRpc::MakeMethodCall(const xl::String &strMethodName, const xl::Array<XmlRpcValue> &arrParameters) { XmlNodePtr pMethodCall = new XmlNode; pMethodCall->SetTagName(XML_RPC_METHOD_CALL); XmlNodePtr pMethodName = new XmlNode; pMethodName->SetTagName(XML_RPC_METHOD_NAME); XmlNodePtr pMethodNameValue = new XmlNode; pMethodNameValue->SetType(XmlNode::XML_VALUE); pMethodNameValue->SetValue(strMethodName); pMethodName->SubNodes().PushBack(pMethodNameValue); XmlNodePtr pParams = new XmlNode; pParams->SetTagName(XML_RPC_PARAMS); for (xl::Array<XmlRpcValue>::Iterator it = arrParameters.Begin(); it != arrParameters.End(); ++it) { XmlNodePtr pParam = new XmlNode; pParam->SetTagName(XML_RPC_PARAM); XmlNodePtr pValue = it->ToXml(); pParam->SubNodes().PushBack(pValue); pParams->SubNodes().PushBack(pParam); } pMethodCall->SubNodes().PushBack(pMethodName); pMethodCall->SubNodes().PushBack(pParams); return pMethodCall; } bool XmlRpc::ParseResponse(XmlNodePtr pNode, XmlRpcValue *pReturnValue) { if (pNode->GetType() != XmlNode::XML_NODE || pNode->GetTagName() != XML_RPC_METHOD_RESPONSE || pNode->SubNodes().Size() != 1) { return false; } XmlNodePtr pResult = *pNode->SubNodes().Begin(); if (pResult->GetType() != XmlNode::XML_NODE || pResult->SubNodes().Size() != 1) { return false; } xl::String strRet = pResult->GetTagName(); if (strRet != XML_RPC_PARAMS && strRet != XML_RPC_FAULT) { return false; } bool bRet = (strRet == XML_RPC_PARAMS); XmlRpcValue value; if (bRet) { XmlNodePtr pParam = *pResult->SubNodes().Begin(); if (pParam->GetType() != XmlNode::XML_NODE || pParam->GetTagName() != XML_RPC_PARAM || pParam->SubNodes().Size() != 1) { return false; } XmlNodePtr pValue = *pParam->SubNodes().Begin(); if (!value.FromXml(pValue)) { return false; } } else { XmlNodePtr pValue = *pResult->SubNodes().Begin(); if (!value.FromXml(pValue)) { return false; } } if (pReturnValue != nullptr) { *pReturnValue = value; } return bRet; } <commit_msg>fix code<commit_after>//------------------------------------------------------------------------------ // // Copyright (C) Streamlet. All rights reserved. // // File Name: XmlRpc.cpp // Author: Streamlet // Create Time: 2010-10-28 // Description: // // Version history: // // // //------------------------------------------------------------------------------ #include "XmlRpc.h" #include "XmlRpcValue.h" #include "Encoding.h" #include <WinHttp.h> #pragma comment(lib, "WinHttp.lib") #define XML_RPC_METHOD_CALL L"methodCall" #define XML_RPC_METHOD_NAME L"methodName" #define XML_RPC_PARAMS L"params" #define XML_RPC_PARAM L"param" #define XML_RPC_METHOD_RESPONSE L"methodResponse" #define XML_RPC_FAULT L"fault" XmlRpc::XmlRpc() : m_bConnected(false) { } XmlRpc::~XmlRpc() { Disconnect(); } bool XmlRpc::SetApiUrl(const xl::String &strUrl) { URL_COMPONENTS urlComp = { sizeof(URL_COMPONENTS) }; urlComp.dwHostNameLength = (DWORD)-1; urlComp.dwUrlPathLength = (DWORD)-1; urlComp.dwExtraInfoLength = (DWORD)-1; if (!WinHttpCrackUrl(strUrl.GetAddress(), 0, 0, &urlComp)) { return false; } for (DWORD i = 0; i < urlComp.dwHostNameLength; ++i) { m_strHostName.AppendBack(urlComp.lpszHostName[i]); } for (DWORD i = 0; i < urlComp.dwUrlPathLength; ++i) { m_strPagePath.AppendBack(urlComp.lpszUrlPath[i]); } for (DWORD i = 0; i < urlComp.dwExtraInfoLength; ++i) { m_strPagePath.AppendBack(urlComp.lpszExtraInfo[i]); } return true; } bool XmlRpc::Connect() { Disconnect(); if (!m_http.Connect(m_strHostName.GetAddress())) { return false; } m_bConnected = true; return true; } void XmlRpc::Disconnect() { if (!m_bConnected) { return; } m_http.Disconnect(); m_bConnected = false; } bool XmlRpc::ExecuteMethod(const xl::String &strMethodName, const xl::Array<XmlRpcValue> &arrParameters, XmlRpcValue *pReturnValue, HANDLE hEventCancel) { XmlInstPtr pInst = MakeXmlInst(); XmlNodePtr pMethodCall = MakeMethodCall(strMethodName, arrParameters); xl::String strRequest = pInst->GetXmlString(L"") + pMethodCall->GetXmlString(L"", L""); xl::StringA strRequestUtf8 = Encoding::StringToUtf8(strRequest); xl::Array<BYTE> arrResponse; if (!m_http.SendRequest(L"POST", m_strPagePath.GetAddress(), NULL, (LPVOID)strRequestUtf8.GetAddress(), strRequestUtf8.Length(), hEventCancel, &arrResponse)) { return false; } arrResponse.PushBack('\0'); xl::StringA strResponseUtf8 = (LPCSTR)&arrResponse[0]; xl::String strResponse = Encoding::Utf8ToString(strResponseUtf8); XmlInstList xmlInst; XmlNodeList xmlNode; if (!XmlParser::ParseXml(strResponse, &xmlInst, &xmlNode)) { return false; } return ParseResponse(*xmlNode.Begin(), pReturnValue); } XmlInstPtr XmlRpc::MakeXmlInst() { XmlInstPtr pInst = new XmlInst; pInst->SetTagName(XML_INST_XML); pInst->Properties().Insert(XML_INST_VERSION, XML_INST_VERSION_1_0); // pInst->Properties().Insert(XML_INST_ENCODING, XML_INST_ENCODING_UTF8); return pInst; } XmlNodePtr XmlRpc::MakeMethodCall(const xl::String &strMethodName, const xl::Array<XmlRpcValue> &arrParameters) { XmlNodePtr pMethodCall = new XmlNode; pMethodCall->SetTagName(XML_RPC_METHOD_CALL); XmlNodePtr pMethodName = new XmlNode; pMethodName->SetTagName(XML_RPC_METHOD_NAME); XmlNodePtr pMethodNameValue = new XmlNode; pMethodNameValue->SetType(XmlNode::XML_VALUE); pMethodNameValue->SetValue(strMethodName); pMethodName->SubNodes().PushBack(pMethodNameValue); XmlNodePtr pParams = new XmlNode; pParams->SetTagName(XML_RPC_PARAMS); for (xl::Array<XmlRpcValue>::Iterator it = arrParameters.Begin(); it != arrParameters.End(); ++it) { XmlNodePtr pParam = new XmlNode; pParam->SetTagName(XML_RPC_PARAM); XmlNodePtr pValue = it->ToXml(); pParam->SubNodes().PushBack(pValue); pParams->SubNodes().PushBack(pParam); } pMethodCall->SubNodes().PushBack(pMethodName); pMethodCall->SubNodes().PushBack(pParams); return pMethodCall; } bool XmlRpc::ParseResponse(XmlNodePtr pNode, XmlRpcValue *pReturnValue) { if (pNode->GetType() != XmlNode::XML_NODE || pNode->GetTagName() != XML_RPC_METHOD_RESPONSE || pNode->SubNodes().Size() != 1) { return false; } XmlNodePtr pResult = *pNode->SubNodes().Begin(); if (pResult->GetType() != XmlNode::XML_NODE || pResult->SubNodes().Size() != 1) { return false; } xl::String strRet = pResult->GetTagName(); if (strRet != XML_RPC_PARAMS && strRet != XML_RPC_FAULT) { return false; } bool bRet = (strRet == XML_RPC_PARAMS); XmlRpcValue value; if (bRet) { XmlNodePtr pParam = *pResult->SubNodes().Begin(); if (pParam->GetType() != XmlNode::XML_NODE || pParam->GetTagName() != XML_RPC_PARAM || pParam->SubNodes().Size() != 1) { return false; } XmlNodePtr pValue = *pParam->SubNodes().Begin(); if (!value.FromXml(pValue)) { return false; } } else { XmlNodePtr pValue = *pResult->SubNodes().Begin(); if (!value.FromXml(pValue)) { return false; } } if (pReturnValue != nullptr) { *pReturnValue = value; } return bRet; } <|endoftext|>
<commit_before>// ---------------------------------------------------------------------------- // ModularDeviceBase.cpp // // // Authors: // Peter Polidoro [email protected] // ---------------------------------------------------------------------------- #include "ModularDeviceBase.h" using namespace modular_device_base; ModularDeviceBase::ModularDeviceBase() { } void ModularDeviceBase::setup() { // Server Setup modular_server_.setup(); // Pin Setup // Add Server Streams modular_server_.addServerStream(Serial); for (size_t i=0; i<constants::SERIAL_STREAM_COUNT; ++i) { modular_server_.addServerStream(*(constants::serial_stream_ptrs[i])); } // Add Client Streams for (size_t i=0; i<constants::SERIAL_STREAM_COUNT; ++i) { modular_clients_[i].setStream(*(constants::serial_stream_ptrs[i])); } // Set Device ID modular_server_.setDeviceName(constants::device_name); modular_server_.setFormFactor(constants::form_factor); // Add Hardware modular_server_.addHardware(constants::processor_hardware_info, processor_interrupts_); #if !defined(__AVR_ATmega2560__) modular_server_.addHardware(constants::hardware_info, interrupts_); #endif // Interrupts #if !defined(__AVR_ATmega2560__) modular_server::Interrupt & bnc_a_interrupt = modular_server_.createInterrupt(constants::bnc_a_interrupt_name, constants::bnc_a_pin); modular_server::Interrupt & bnc_b_interrupt = modular_server_.createInterrupt(constants::bnc_b_interrupt_name, constants::bnc_b_pin); #endif // Add Firmware modular_server_.addFirmware(constants::firmware_info, properties_, parameters_, functions_, callbacks_); // Properties // Parameters modular_server::Parameter & address_parameter = modular_server_.createParameter(constants::address_parameter_name); address_parameter.setRange(constants::address_min,constants::address_max); address_parameter.setArrayLengthRange(constants::address_array_length_min,constants::address_array_length_max); modular_server::Parameter & request_parameter = modular_server_.createParameter(constants::request_parameter_name); request_parameter.setArrayLengthRange(constants::request_array_length_min,constants::request_array_length_max); // Functions modular_server::Function & forward_function = modular_server_.createFunction(constants::forward_function_name); forward_function.attachFunctor(makeFunctor((Functor0 *)0,*this,&ModularDeviceBase::forwardHandler)); forward_function.addParameter(address_parameter); forward_function.addParameter(request_parameter); forward_function.setReturnTypeObject(); // Callbacks // Begin Streams Serial.begin(constants::baudrate); for (size_t i=0; i<constants::SERIAL_STREAM_COUNT; ++i) { constants::serial_stream_ptrs[i]->begin(constants::baudrate); pinMode(constants::serial_rx_pins[i],INPUT_PULLUP); } } void ModularDeviceBase::startServer() { // Start Modular Device Server modular_server_.startServer(); } void ModularDeviceBase::update() { modular_server_.handleServerRequests(); } bool ModularDeviceBase::forward(ArduinoJson::JsonArray & address_array, ArduinoJson::JsonArray & request_array) { bool succeeded = false; size_t address_array_size = address_array.size(); if (address_array_size >= 2) { size_t stream_id = address_array[0]; if (streamIdIsValid(stream_id)) { address_array.remove(0); } } else if (address_array_size == 1) { } else { } return succeeded; } bool ModularDeviceBase::streamIdIsValid(const size_t stream_id) { bool stream_id_is_valid = false; for (size_t i=0; i<constants::STREAM_COUNT; ++i) { if (stream_id == constants::stream_ids[i]) { stream_id_is_valid = true; break; } } return stream_id_is_valid; } // Handlers must be non-blocking (avoid 'delay') // // modular_server_.parameter(parameter_name).getValue(value) value type must be either: // fixed-point number (int, long, etc.) // floating-point number (float, double) // bool // const char * // ArduinoJson::JsonArray * // ArduinoJson::JsonObject * // // For more info read about ArduinoJson parsing https://github.com/janelia-arduino/ArduinoJson // // modular_server_.property(property_name).getValue(value) value type must match the property default type // modular_server_.property(property_name).setValue(value) value type must match the property default type // modular_server_.property(property_name).getElementValue(value) value type must match the property array element default type // modular_server_.property(property_name).setElementValue(value) value type must match the property array element default type void ModularDeviceBase::forwardHandler() { ArduinoJson::JsonArray * address_array_ptr; modular_server_.parameter(constants::address_parameter_name).getValue(address_array_ptr); ArduinoJson::JsonArray * request_array_ptr; modular_server_.parameter(constants::request_parameter_name).getValue(request_array_ptr); forward(*address_array_ptr,*request_array_ptr); modular_server_.response().writeResultKey(); modular_server_.response().beginObject(); modular_server_.response().endObject(); } <commit_msg>Do not set Serial RX lines as INPUT_PULLUP.<commit_after>// ---------------------------------------------------------------------------- // ModularDeviceBase.cpp // // // Authors: // Peter Polidoro [email protected] // ---------------------------------------------------------------------------- #include "ModularDeviceBase.h" using namespace modular_device_base; ModularDeviceBase::ModularDeviceBase() { } void ModularDeviceBase::setup() { // Server Setup modular_server_.setup(); // Pin Setup // Add Server Streams modular_server_.addServerStream(Serial); for (size_t i=0; i<constants::SERIAL_STREAM_COUNT; ++i) { modular_server_.addServerStream(*(constants::serial_stream_ptrs[i])); } // Add Client Streams for (size_t i=0; i<constants::SERIAL_STREAM_COUNT; ++i) { modular_clients_[i].setStream(*(constants::serial_stream_ptrs[i])); } // Set Device ID modular_server_.setDeviceName(constants::device_name); modular_server_.setFormFactor(constants::form_factor); // Add Hardware modular_server_.addHardware(constants::processor_hardware_info, processor_interrupts_); #if !defined(__AVR_ATmega2560__) modular_server_.addHardware(constants::hardware_info, interrupts_); #endif // Interrupts #if !defined(__AVR_ATmega2560__) modular_server::Interrupt & bnc_a_interrupt = modular_server_.createInterrupt(constants::bnc_a_interrupt_name, constants::bnc_a_pin); modular_server::Interrupt & bnc_b_interrupt = modular_server_.createInterrupt(constants::bnc_b_interrupt_name, constants::bnc_b_pin); #endif // Add Firmware modular_server_.addFirmware(constants::firmware_info, properties_, parameters_, functions_, callbacks_); // Properties // Parameters modular_server::Parameter & address_parameter = modular_server_.createParameter(constants::address_parameter_name); address_parameter.setRange(constants::address_min,constants::address_max); address_parameter.setArrayLengthRange(constants::address_array_length_min,constants::address_array_length_max); modular_server::Parameter & request_parameter = modular_server_.createParameter(constants::request_parameter_name); request_parameter.setArrayLengthRange(constants::request_array_length_min,constants::request_array_length_max); // Functions modular_server::Function & forward_function = modular_server_.createFunction(constants::forward_function_name); forward_function.attachFunctor(makeFunctor((Functor0 *)0,*this,&ModularDeviceBase::forwardHandler)); forward_function.addParameter(address_parameter); forward_function.addParameter(request_parameter); forward_function.setReturnTypeObject(); // Callbacks // Begin Streams Serial.begin(constants::baudrate); for (size_t i=0; i<constants::SERIAL_STREAM_COUNT; ++i) { constants::serial_stream_ptrs[i]->begin(constants::baudrate); } } void ModularDeviceBase::startServer() { // Start Modular Device Server modular_server_.startServer(); } void ModularDeviceBase::update() { modular_server_.handleServerRequests(); } bool ModularDeviceBase::forward(ArduinoJson::JsonArray & address_array, ArduinoJson::JsonArray & request_array) { bool succeeded = false; size_t address_array_size = address_array.size(); if (address_array_size >= 2) { size_t stream_id = address_array[0]; if (streamIdIsValid(stream_id)) { address_array.remove(0); } } else if (address_array_size == 1) { } else { } return succeeded; } bool ModularDeviceBase::streamIdIsValid(const size_t stream_id) { bool stream_id_is_valid = false; for (size_t i=0; i<constants::STREAM_COUNT; ++i) { if (stream_id == constants::stream_ids[i]) { stream_id_is_valid = true; break; } } return stream_id_is_valid; } // Handlers must be non-blocking (avoid 'delay') // // modular_server_.parameter(parameter_name).getValue(value) value type must be either: // fixed-point number (int, long, etc.) // floating-point number (float, double) // bool // const char * // ArduinoJson::JsonArray * // ArduinoJson::JsonObject * // // For more info read about ArduinoJson parsing https://github.com/janelia-arduino/ArduinoJson // // modular_server_.property(property_name).getValue(value) value type must match the property default type // modular_server_.property(property_name).setValue(value) value type must match the property default type // modular_server_.property(property_name).getElementValue(value) value type must match the property array element default type // modular_server_.property(property_name).setElementValue(value) value type must match the property array element default type void ModularDeviceBase::forwardHandler() { ArduinoJson::JsonArray * address_array_ptr; modular_server_.parameter(constants::address_parameter_name).getValue(address_array_ptr); ArduinoJson::JsonArray * request_array_ptr; modular_server_.parameter(constants::request_parameter_name).getValue(request_array_ptr); forward(*address_array_ptr,*request_array_ptr); modular_server_.response().writeResultKey(); modular_server_.response().beginObject(); modular_server_.response().endObject(); } <|endoftext|>
<commit_before>// Copyright 2015 The Statify 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. See the AUTHORS file for names of // contributors. #include <arpa/inet.h> #include <event2/event.h> #include <event2/listener.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #include "statify/log.h" #include "statify/program_options.h" using statify::Log; using statify::ProgramOptions; namespace { // Callback that is registered to handle new connection attempts. void accept_callback(struct evconnlistener* listener, evutil_socket_t sock, struct sockaddr* addr, int, void* arg) { // Reference arguments (void)listener; (void)sock; (void)addr; (void)arg; Log::Write(Log::INFO, "accepted connection"); close(sock); Log::Write(Log::INFO, "closed connection"); } // Callback that is registered to handle errors occurring during accept. void accept_error_callback(struct evconnlistener* listener, void* arg) { (void)listener; (void)arg; Log::Write(Log::ERROR, "failed to accept connection"); } } // namespace int main(int argc, char* argv[]) { // Extract program options from command line ProgramOptions options; options.ParseCommandLine(argc, argv); if (options.help()) { options.DisplayHelp(); return EXIT_SUCCESS; } // Log startup Log::Write(Log::INFO, "statifyd - Copyright (C) 2015 The Statify Authors"); Log::Write(Log::INFO, "starting up"); // Log important startup parameters Log::Write(Log::INFO, "listener port: %d", options.port()); Log::Write(Log::INFO, "listener size: %d", options.backlog()); // Create event base struct event_base* evbase = event_base_new(); if (evbase == NULL) { Log::Write(Log::ABORT, "failed to create event base"); return EXIT_FAILURE; } // Construct wildcard address for listening on the chosen port. struct sockaddr_in address; memset(&address, 0, sizeof(address)); address.sin_family = AF_INET; address.sin_addr.s_addr = htonl(0); address.sin_port = htons(options.port()); // Create a TCP listener struct evconnlistener* listener = NULL; listener = evconnlistener_new_bind( evbase, accept_callback, 0, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, options.backlog(), reinterpret_cast<struct sockaddr*>(&address), sizeof(address)); if (listener == NULL) { Log::Write(Log::ABORT, "failed to establish listener"); } // Configure a callback function to invoke on errors evconnlistener_set_error_cb(listener, accept_error_callback); Log::Write(Log::INFO, "startup complete"); // Dispatch events: This runs the event loop. event_base_dispatch(evbase); evconnlistener_free(listener); // Log that we're initiating shutdown Log::Write(Log::INFO, "shutting down"); // Free the event base event_base_free(evbase); // Finally, log that we're done and exiting. Log::Write(Log::INFO, "shutdown complete"); return EXIT_SUCCESS; } <commit_msg>got echo working<commit_after>// Copyright 2015 The Statify 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. See the AUTHORS file for names of // contributors. #include <arpa/inet.h> #include <assert.h> #include <event2/buffer.h> #include <event2/bufferevent.h> #include <event2/event.h> #include <event2/listener.h> #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #include "statify/log.h" #include "statify/program_options.h" using statify::Log; using statify::ProgramOptions; namespace { /* class Connection { public: private: Connection(const Connection& no_copy); Connection& operator=(const Connection& no_ }; */ void buffer_read_callback(struct bufferevent* bev, void* ctx) { Log::Write(Log::INFO, "buffer_read_callback()"); // TODO(tdial): Can bev or ctx be NULL? assert(bev != NULL); assert(ctx != NULL); // Access the input // TODO(tdial): Can this function return NULL? struct evbuffer* in = bufferevent_get_input(bev); assert(in != NULL); // Access the output // TODO(tdial): Can this function return NULL? struct evbuffer* out = bufferevent_get_output(bev); assert(out != NULL); // Write out whatever we read evbuffer_add_buffer(out, in); } void buffer_write_callback(struct bufferevent* bev, void* ctx) { // TODO(tdial): Implement Log::Write(Log::INFO, "buffer_write_callback()"); } void buffer_event_callback(struct bufferevent* bev, int16_t events, void* ctx) { Log::Write(Log::INFO, "buffer_event_callback()"); if (events & BEV_EVENT_ERROR) { Log::Write(Log::ERROR, "buffer_event_callback(): BEV_EVENT_ERROR"); } if (events & BEV_EVENT_EOF) { Log::Write(Log::INFO, "buffer_event_callback(): BEV_EVENT_EOF"); bufferevent_free(bev); } } // Callback that is registered to handle new connection attempts. void accept_callback(struct evconnlistener* listener, evutil_socket_t sock, struct sockaddr* addr, int, void* arg) { // TODO(tdial): Can listener ever be NULL? assert(listener != NULL); // TODO(tdial): Can socket ever be invalid? assert(sock >= 0); // TODO(tdial): Can a valid listener ever provide an invalid base? struct event_base* base = evconnlistener_get_base(listener); assert(base != NULL); // Construct buffer event object struct bufferevent* bev(NULL); bev = bufferevent_socket_new(base, sock, BEV_OPT_CLOSE_ON_FREE); // TODO(tdial): In what circumstances may bufferevent_socket_new() fail? assert(bev != NULL); // Configure event callbacks bufferevent_setcb(bev, buffer_read_callback, buffer_write_callback, buffer_event_callback, NULL); bufferevent_enable(bev, EV_READ | EV_WRITE); /* // Reference arguments (void)listener; (void)sock; (void)addr; (void)arg; Log::Write(Log::INFO, "accepted connection"); close(sock); Log::Write(Log::INFO, "closed connection"); */ } // Callback that is registered to handle errors occurring during accept. void accept_error_callback(struct evconnlistener* listener, void* arg) { (void)listener; (void)arg; Log::Write(Log::ERROR, "failed to accept connection"); } } // namespace int main(int argc, char* argv[]) { // Extract program options from command line ProgramOptions options; options.ParseCommandLine(argc, argv); if (options.help()) { options.DisplayHelp(); return EXIT_SUCCESS; } // Log startup Log::Write(Log::INFO, "statifyd - Copyright (C) 2015 The Statify Authors"); Log::Write(Log::INFO, "starting up"); // Log important startup parameters Log::Write(Log::INFO, "listener port: %d", options.port()); Log::Write(Log::INFO, "listener size: %d", options.backlog()); // Create event base struct event_base* evbase = event_base_new(); if (evbase == NULL) { Log::Write(Log::ABORT, "failed to create event base"); return EXIT_FAILURE; } // Construct wildcard address for listening on the chosen port. struct sockaddr_in address; memset(&address, 0, sizeof(address)); address.sin_family = AF_INET; address.sin_addr.s_addr = htonl(0); address.sin_port = htons(options.port()); // Create a TCP listener struct evconnlistener* listener = NULL; listener = evconnlistener_new_bind( evbase, accept_callback, 0, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, options.backlog(), reinterpret_cast<struct sockaddr*>(&address), sizeof(address)); if (listener == NULL) { Log::Write(Log::ABORT, "failed to establish listener"); } // Configure a callback function to invoke on errors evconnlistener_set_error_cb(listener, accept_error_callback); Log::Write(Log::INFO, "startup complete"); // Dispatch events: This runs the event loop. event_base_dispatch(evbase); evconnlistener_free(listener); // Log that we're initiating shutdown Log::Write(Log::INFO, "shutting down"); // Free the event base event_base_free(evbase); // Finally, log that we're done and exiting. Log::Write(Log::INFO, "shutdown complete"); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <dgtype/dgtype.hh> #include <memory> #include <vector> #include <iterator> #include <iostream> #include <cassert> namespace DG { namespace Sound { void WAV::open(const std::string& fname) { if (!is_file_accessible(fname)) { throw dgtype::Inaccessible_file("WAV"); } SNDFILE* temp = sf_open(fname.c_str(), SFM_READ, &wav_info); if (!is_format_supported()) { throw dgtype::Invalid_format("WAV"); } extract_samples(temp); sf_close(temp); } void WAV::write(const std::string& fname) const { SF_INFO temp_info = wav_info; SNDFILE* temp = sf_open(fname.c_str(), SFM_WRITE, &temp_info); sf_write_short(temp, &samples[0], samples.size()); //sf_write_sync(temp); sf_close(temp); } void WAV::sample_set_mask(int index, unsigned mask) { int sample = get_sample(index); sample |= mask; samples[index] = sample; } void WAV::sample_unset_mask(int index, unsigned mask) { unsigned sample = get_sample(index); sample &= ~mask; samples[index] = sample; } //// private member functions bool WAV::is_format_supported() const { int wav_mask = wav_info.format & SF_FORMAT_WAV; int pcm16_mask = wav_info.format & SF_FORMAT_PCM_16; bool is_wav = wav_mask == SF_FORMAT_WAV; bool is_pcm16 = pcm16_mask == SF_FORMAT_PCM_16; return is_wav && is_pcm16; } void WAV::extract_samples(SNDFILE* wav) { size_t num_samples = calc_num_samples(); std::unique_ptr<short> temp_array(new short[num_samples]); sf_read_short(wav, temp_array.get(), num_samples); samples = std::vector<short>(temp_array.get(), temp_array.get() + num_samples); } size_t WAV::calc_num_samples() const { return wav_info.frames * wav_info.channels; } } } <commit_msg>Removed confusing commented out line [ci skip]<commit_after>#include <dgtype/dgtype.hh> #include <memory> #include <vector> #include <iterator> #include <iostream> #include <cassert> namespace DG { namespace Sound { void WAV::open(const std::string& fname) { if (!is_file_accessible(fname)) { throw dgtype::Inaccessible_file("WAV"); } SNDFILE* temp = sf_open(fname.c_str(), SFM_READ, &wav_info); if (!is_format_supported()) { throw dgtype::Invalid_format("WAV"); } extract_samples(temp); sf_close(temp); } void WAV::write(const std::string& fname) const { SF_INFO temp_info = wav_info; SNDFILE* temp = sf_open(fname.c_str(), SFM_WRITE, &temp_info); sf_write_short(temp, &samples[0], samples.size()); sf_close(temp); } void WAV::sample_set_mask(int index, unsigned mask) { int sample = get_sample(index); sample |= mask; samples[index] = sample; } void WAV::sample_unset_mask(int index, unsigned mask) { unsigned sample = get_sample(index); sample &= ~mask; samples[index] = sample; } //// private member functions bool WAV::is_format_supported() const { int wav_mask = wav_info.format & SF_FORMAT_WAV; int pcm16_mask = wav_info.format & SF_FORMAT_PCM_16; bool is_wav = wav_mask == SF_FORMAT_WAV; bool is_pcm16 = pcm16_mask == SF_FORMAT_PCM_16; return is_wav && is_pcm16; } void WAV::extract_samples(SNDFILE* wav) { size_t num_samples = calc_num_samples(); std::unique_ptr<short> temp_array(new short[num_samples]); sf_read_short(wav, temp_array.get(), num_samples); samples = std::vector<short>(temp_array.get(), temp_array.get() + num_samples); } size_t WAV::calc_num_samples() const { return wav_info.frames * wav_info.channels; } } } <|endoftext|>
<commit_before>/* Copyright (C) 2008-2016 The Communi Project You may use this file under the terms of BSD license as follows: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "themewidget.h" #include "textbrowser.h" #include "treewidget.h" #include "bufferview.h" #include "splitview.h" #include "chatpage.h" #include <IrcBufferModel> #include <IrcConnection> #include <IrcChannel> #include <IrcMessage> #include <IrcBuffer> #include <QPainter> #include <QPixmap> #include <QTimer> class Channel : public IrcChannel { public: Channel(QObject* parent = 0) : IrcChannel(parent) { } bool isActive() const { return true; } }; class Server : public IrcBuffer { public: Server(QObject* parent = 0) : IrcBuffer(parent) { } bool isActive() const { return true; } }; static void receiveMessages(IrcBufferModel* model, IrcBuffer* buffer) { QString title = buffer->title(); IrcConnection* connection = buffer->connection(); model->receiveMessage(IrcMessage::fromParameters("Lorem", "JOIN", QStringList() << title, connection)); IrcNamesMessage* names = new IrcNamesMessage(connection); names->setParameters(QStringList() << title << "Lorem" << "Morbi" << "nulla" << "rhoncus" << "Etiam" << "nunc" << "gravida" << "Proin" << "Cras"); model->receiveMessage(names); model->receiveMessage(IrcMessage::fromParameters("Morbi", "PRIVMSG", QStringList() << title << "nullam eget commodo diam. sit amet ornare leo.", connection)); model->receiveMessage(IrcMessage::fromParameters("nulla", "PRIVMSG", QStringList() << title << "...", connection)); model->receiveMessage(IrcMessage::fromParameters("Ipsum", "JOIN", QStringList() << title, connection)); model->receiveMessage(IrcMessage::fromParameters("rhoncus", "PRIVMSG", QStringList() << title << "vivamus!", connection)); model->receiveMessage(IrcMessage::fromParameters("Etiam", "PRIVMSG", QStringList() << title << "Ut volutpat nibh nec enim elementum, sed placerat erat gravida.", connection)); model->receiveMessage(IrcMessage::fromParameters("Ipsum", "QUIT", QStringList() << "Nulla facilisi.", connection)); model->receiveMessage(IrcMessage::fromParameters("Ipsum", "JOIN", QStringList() << title, connection)); model->receiveMessage(IrcMessage::fromParameters("nunc", "PRIVMSG", QStringList() << title << ":)", connection)); model->receiveMessage(IrcMessage::fromParameters("gravida", "PRIVMSG", QStringList() << title << "etiam augue purus, pharetra vel neque a, fringilla hendrerit orci", connection)); model->receiveMessage(IrcMessage::fromParameters("Proin", "PRIVMSG", QStringList() << title << "enim ante?", connection)); model->receiveMessage(IrcMessage::fromParameters("Cras", "PRIVMSG", QStringList() << title << "quisque vel lacus eu odio pretium adipiscing...", connection)); } static IrcBuffer* createChannel(const QString& name, QObject* parent) { IrcChannel* channel = new Channel(parent); channel->setPrefix("#"); channel->setName(name); return channel; } static IrcBufferModel* createBufferModel(QObject* parent) { IrcConnection* connection = new IrcConnection(parent); connection->setNickName("communi"); IrcBufferModel* model = new IrcBufferModel(connection); IrcBuffer* server = new Server(model); server->setName("Lorem Ipsum"); server->setSticky(true); model->add(server); model->add(createChannel("donec", model)); model->add(createChannel("convallis", model)); model->add(createChannel("sagittis", model)); model->add(createChannel("magna", model)); model->add(createChannel("tincidunt", model)); model->add(createChannel("phasellus ", model)); model->add(createChannel("tellus", model)); model->add(createChannel("fermentum", model)); model->add(createChannel("pharetra", model)); model->add(createChannel("vehicula", model)); model->add(createChannel("aliquam", model)); model->add(createChannel("bibendum", model)); model->add(createChannel("semper", model)); model->add(createChannel("dictum", model)); model->add(createChannel("rhoncus", model)); return model; } static ChatPage* createChatPage(QWidget* parent = 0) { ChatPage* page = new ChatPage(parent); IrcBufferModel* model = createBufferModel(page); foreach (IrcBuffer* buffer, model->buffers()) page->treeWidget()->addBuffer(buffer); IrcBuffer* buffer = model->find("#magna"); page->addBuffer(buffer); page->splitView()->setCurrentBuffer(buffer); page->treeWidget()->setCurrentBuffer(buffer); page->treeWidget()->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); page->currentView()->textBrowser()->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); receiveMessages(model, buffer); return page; } ThemeWidget::ThemeWidget(QWidget* parent) : QLabel(parent) { d.page = createChatPage(); d.page->setVisible(false); d.page->resize(960, 600); QTimer::singleShot(0, this, SLOT(updatePreview())); } ThemeWidget::~ThemeWidget() { delete d.page; } QString ThemeWidget::theme() const { return d.page->theme(); } void ThemeWidget::setTheme(const QString& theme) { if (theme != d.page->theme()) { d.page->setTheme(theme); updatePreview(); } } void ThemeWidget::resizeEvent(QResizeEvent* event) { QLabel::resizeEvent(event); updatePreview(); } void ThemeWidget::updatePreview() { QPixmap pixmap(d.page->size()); QPainter painter(&pixmap); d.page->render(&painter); setPixmap(pixmap.scaled(contentsRect().size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); } <commit_msg>Fix theme previews on high-DPI<commit_after>/* Copyright (C) 2008-2016 The Communi Project You may use this file under the terms of BSD license as follows: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "themewidget.h" #include "textbrowser.h" #include "treewidget.h" #include "bufferview.h" #include "splitview.h" #include "chatpage.h" #include <IrcBufferModel> #include <IrcConnection> #include <IrcChannel> #include <IrcMessage> #include <IrcBuffer> #include <QPainter> #include <QPixmap> #include <QTimer> class Channel : public IrcChannel { public: Channel(QObject* parent = 0) : IrcChannel(parent) { } bool isActive() const { return true; } }; class Server : public IrcBuffer { public: Server(QObject* parent = 0) : IrcBuffer(parent) { } bool isActive() const { return true; } }; static void receiveMessages(IrcBufferModel* model, IrcBuffer* buffer) { QString title = buffer->title(); IrcConnection* connection = buffer->connection(); model->receiveMessage(IrcMessage::fromParameters("Lorem", "JOIN", QStringList() << title, connection)); IrcNamesMessage* names = new IrcNamesMessage(connection); names->setParameters(QStringList() << title << "Lorem" << "Morbi" << "nulla" << "rhoncus" << "Etiam" << "nunc" << "gravida" << "Proin" << "Cras"); model->receiveMessage(names); model->receiveMessage(IrcMessage::fromParameters("Morbi", "PRIVMSG", QStringList() << title << "nullam eget commodo diam. sit amet ornare leo.", connection)); model->receiveMessage(IrcMessage::fromParameters("nulla", "PRIVMSG", QStringList() << title << "...", connection)); model->receiveMessage(IrcMessage::fromParameters("Ipsum", "JOIN", QStringList() << title, connection)); model->receiveMessage(IrcMessage::fromParameters("rhoncus", "PRIVMSG", QStringList() << title << "vivamus!", connection)); model->receiveMessage(IrcMessage::fromParameters("Etiam", "PRIVMSG", QStringList() << title << "Ut volutpat nibh nec enim elementum, sed placerat erat gravida.", connection)); model->receiveMessage(IrcMessage::fromParameters("Ipsum", "QUIT", QStringList() << "Nulla facilisi.", connection)); model->receiveMessage(IrcMessage::fromParameters("Ipsum", "JOIN", QStringList() << title, connection)); model->receiveMessage(IrcMessage::fromParameters("nunc", "PRIVMSG", QStringList() << title << ":)", connection)); model->receiveMessage(IrcMessage::fromParameters("gravida", "PRIVMSG", QStringList() << title << "etiam augue purus, pharetra vel neque a, fringilla hendrerit orci", connection)); model->receiveMessage(IrcMessage::fromParameters("Proin", "PRIVMSG", QStringList() << title << "enim ante?", connection)); model->receiveMessage(IrcMessage::fromParameters("Cras", "PRIVMSG", QStringList() << title << "quisque vel lacus eu odio pretium adipiscing...", connection)); } static IrcBuffer* createChannel(const QString& name, QObject* parent) { IrcChannel* channel = new Channel(parent); channel->setPrefix("#"); channel->setName(name); return channel; } static IrcBufferModel* createBufferModel(QObject* parent) { IrcConnection* connection = new IrcConnection(parent); connection->setNickName("communi"); IrcBufferModel* model = new IrcBufferModel(connection); IrcBuffer* server = new Server(model); server->setName("Lorem Ipsum"); server->setSticky(true); model->add(server); model->add(createChannel("donec", model)); model->add(createChannel("convallis", model)); model->add(createChannel("sagittis", model)); model->add(createChannel("magna", model)); model->add(createChannel("tincidunt", model)); model->add(createChannel("phasellus ", model)); model->add(createChannel("tellus", model)); model->add(createChannel("fermentum", model)); model->add(createChannel("pharetra", model)); model->add(createChannel("vehicula", model)); model->add(createChannel("aliquam", model)); model->add(createChannel("bibendum", model)); model->add(createChannel("semper", model)); model->add(createChannel("dictum", model)); model->add(createChannel("rhoncus", model)); return model; } static ChatPage* createChatPage(QWidget* parent = 0) { ChatPage* page = new ChatPage(parent); IrcBufferModel* model = createBufferModel(page); foreach (IrcBuffer* buffer, model->buffers()) page->treeWidget()->addBuffer(buffer); IrcBuffer* buffer = model->find("#magna"); page->addBuffer(buffer); page->splitView()->setCurrentBuffer(buffer); page->treeWidget()->setCurrentBuffer(buffer); page->treeWidget()->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); page->currentView()->textBrowser()->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); receiveMessages(model, buffer); return page; } ThemeWidget::ThemeWidget(QWidget* parent) : QLabel(parent) { d.page = createChatPage(); d.page->setVisible(false); d.page->resize(960, 600); QTimer::singleShot(0, this, SLOT(updatePreview())); } ThemeWidget::~ThemeWidget() { delete d.page; } QString ThemeWidget::theme() const { return d.page->theme(); } void ThemeWidget::setTheme(const QString& theme) { if (theme != d.page->theme()) { d.page->setTheme(theme); updatePreview(); } } void ThemeWidget::resizeEvent(QResizeEvent* event) { QLabel::resizeEvent(event); updatePreview(); } void ThemeWidget::updatePreview() { qreal dpr = 1.0; #if QT_VERSION >= 0x050600 dpr = devicePixelRatioF(); #endif QPixmap pixmap(d.page->size() * dpr); #if QT_VERSION >= 0x050600 pixmap.setDevicePixelRatio(dpr); #endif QPainter painter(&pixmap); d.page->render(&painter); setPixmap(pixmap.scaled(contentsRect().size() * dpr, Qt::KeepAspectRatio, Qt::SmoothTransformation)); } <|endoftext|>
<commit_before>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2019 Ryo Suzuki // Copyright (c) 2016-2019 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <string> # define __STDC_CONSTANT_MACROS extern "C" { # include <libavformat/avformat.h> # include <libavcodec/avcodec.h> # include <libavutil/avutil.h> # include <libswresample/swresample.h> } # include <Siv3D/EngineLog.hpp> # include "AudioFormat_AAC.hpp" namespace s3d { namespace detail { class AACDecoder { private: AVFormatContext* m_format_context = nullptr; AVCodecContext* m_codec_context = nullptr; AVFrame* m_frame = nullptr; AVPacket* m_packet = nullptr; struct SwrContext* m_swr_context = nullptr; uint8_t* m_out_buf = nullptr; AVStream* m_audio_stream = nullptr; int m_audio_stream_idx = 0; AVCodec* m_codec = nullptr; int m_out_count = 0; int m_out_sample_rate = 0; int64_t m_duration = 0; size_t m_wave_idx = 0; FilePath m_path; void setSample(Wave& wave, float* buf, size_t idx, size_t count) { WaveSample sample; for (size_t i = 0; i < count; ++i) { sample.set(buf[0], buf[1]); if (idx < wave.size()) wave[idx] = sample; else wave.push_back(sample); buf += 2; idx++; } } bool decode_by_avcodec(Wave& wave, bool do_flush) { int ret; ret = avcodec_send_packet(m_codec_context, (do_flush ? nullptr : m_packet)); if (ret < 0) { LOG_FAIL(U"AACDecoder: load() failed (avcodec_send_packet()) ({})"_fmt(m_path)); return false; } while (avcodec_receive_frame(m_codec_context, m_frame) == 0) { ret = swr_convert(m_swr_context, &m_out_buf, m_out_count, (const uint8_t**)(m_frame->data), m_frame->nb_samples); if (ret < 0) { LOG_FAIL(U"AACDecoder: load() failed (avcodec_receive_frame()) ({})"_fmt(m_path)); return false; } setSample(wave, (float*)m_out_buf, m_wave_idx, ret); m_wave_idx += ret; } return true; } public: ~AACDecoder() { if (m_out_buf != nullptr) av_free(m_out_buf); if (m_swr_context != nullptr) swr_free(&m_swr_context); if (m_frame != nullptr) av_frame_free(&m_frame); if (m_packet != nullptr) av_packet_free(&m_packet); if (m_codec_context != nullptr) avcodec_free_context(&m_codec_context); if (m_format_context != nullptr) avformat_close_input(&m_format_context); } bool init(const FilePath& path) { const std::string pathUTF8 = path.toUTF8(); const char* path_char = pathUTF8.c_str(); // open file. if (avformat_open_input(&m_format_context, path_char, nullptr, nullptr) != 0) { LOG_DEBUG(U"AACDecoder: avformat_open_input() failed ({}})"_fmt(m_path)); return false; } if (avformat_find_stream_info(m_format_context, nullptr) < 0) { LOG_DEBUG(U"AACDecoder: avformat_find_stream_info() failed ({})"_fmt(m_path)); return false; } // search audio stream for (size_t i = 0; i < m_format_context->nb_streams; ++i) { if (m_format_context->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { m_audio_stream = m_format_context->streams[i]; m_audio_stream_idx = i; break; } } if (m_audio_stream == nullptr) { LOG_DEBUG(U"AACDecoder: There are no audio stream ({})"_fmt(m_path)); return false; } m_duration = m_audio_stream->duration; // setup codec. m_codec = avcodec_find_decoder(m_audio_stream->codecpar->codec_id); if (m_codec == nullptr) { LOG_DEBUG(U"AACDecoder: avcodec_find_decoder() failed ({})"_fmt(m_path)); return false; } m_codec_context = avcodec_alloc_context3(m_codec); if (m_codec_context == nullptr) { LOG_DEBUG(U"AACDecoder: avcodec_alloc_context3() failed ({})"_fmt(m_path)); return false; } if (avcodec_parameters_to_context(m_codec_context, m_audio_stream->codecpar) < 0) { LOG_DEBUG(U"AACDecoder: avcodec_parameters_to_context() failed ({})"_fmt(m_path)); return false; } if (avcodec_open2(m_codec_context, m_codec, nullptr) != 0) { LOG_DEBUG(U"AACDecoder: avcodec_open2() failed ({})"_fmt(m_path)); return false; } // allocate packet m_packet = (AVPacket*)av_malloc(sizeof(AVPacket)); if (m_packet == nullptr) { LOG_DEBUG(U"AACDecoder: av_malloc() failed (packet) ({})"_fmt(m_path)); return false; } av_init_packet(m_packet); // allocate frame m_frame = av_frame_alloc(); if (m_frame == nullptr) { LOG_DEBUG(U"AACDecoder: av_frame_alloc() failed ({})"_fmt(m_path)); return false; } // initialize swr context int64_t out_channel_layout = AV_CH_LAYOUT_STEREO; int out_nb_samples = m_codec_context->frame_size; AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_FLT; m_out_sample_rate = m_codec_context->sample_rate; m_swr_context = swr_alloc_set_opts(m_swr_context, out_channel_layout, out_sample_fmt, m_out_sample_rate, av_get_default_channel_layout(m_codec_context->channels), m_codec_context->sample_fmt, m_codec_context->sample_rate, 0, nullptr); if (m_swr_context == nullptr) { LOG_DEBUG(U"AACDecoder: swr_alloc() failed ({})"_fmt(m_path)); return false; } int averr = swr_init(m_swr_context); if (swr_is_initialized(m_swr_context) == 0) { LOG_DEBUG(U"AACDecoder: swr_init() failed (AVERROR: {}) ({})"_fmt(Unicode::Widen(av_err2str(averr)), m_path)); return false; } // allocate output buffer int out_nb_channels = av_get_channel_layout_nb_channels(out_channel_layout); int buf_size = av_samples_get_buffer_size(nullptr, out_nb_channels, out_nb_samples, out_sample_fmt, 0); m_out_buf = (uint8_t*)av_malloc(buf_size); if (m_out_buf == nullptr) { LOG_DEBUG(U"AACDecoder: av_malloc() failed (m_out_buf) ({})"_fmt(m_path)); return false; } m_out_count = buf_size / out_nb_channels; return true; } Wave load() { Wave wave(m_duration, Arg::samplingRate = static_cast<uint32>(m_out_sample_rate)); while (0 <= av_read_frame(m_format_context, m_packet)) { if (m_packet->stream_index == m_audio_stream_idx) { if(!decode_by_avcodec(wave, false)) return Wave(); } av_packet_unref(m_packet); } // flush decoder if(!decode_by_avcodec(wave, true)) return Wave(); wave.resize(m_wave_idx); return wave; } }; } AudioFormat_AAC::AudioFormat_AAC() { } AudioFormat_AAC::~AudioFormat_AAC() { } AudioFormat AudioFormat_AAC::format() const { return AudioFormat::AAC; } const Array<String>& AudioFormat_AAC::possibleExtexsions() const { static const Array<String> extensions = { U"m4a" }; return extensions; } bool AudioFormat_AAC::isHeader(const uint8(&bytes)[16], const IReader&) const { // M4V MPEG-4 video/QuickTime file static constexpr uint8 M4V_SIGNx[] = { 0x66, 0x74, 0x79, 0x70, 0x6D, 0x70, 0x34, 0x32 }; // M4A Apple Lossless Audio Codec file static constexpr uint8 M4A_SIGNx[] = { 0x66, 0x74, 0x79, 0x70, 0x4D, 0x34, 0x41, 0x20 }; // MP4 ftypisom static constexpr uint8 MP4ISOM_SIGNx[] = { 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6F, 0x6D }; return (::memcmp(bytes + 4, M4V_SIGNx, sizeof(M4V_SIGNx)) == 0 || ::memcmp(bytes + 4, M4A_SIGNx, sizeof(M4A_SIGNx)) == 0 || ::memcmp(bytes + 4, MP4ISOM_SIGNx, sizeof(MP4ISOM_SIGNx)) == 0); } Wave AudioFormat_AAC::decodeFromFile(const FilePath& path) const { detail::AACDecoder decoder; if (!decoder.init(path)) { LOG_FAIL(U"AACDecoder: init() failed.\n"); return Wave(); } return decoder.load(); } Wave AudioFormat_AAC::decode(IReader&) const { // not supported return Wave(); } } <commit_msg>変数設定忘れ<commit_after>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2019 Ryo Suzuki // Copyright (c) 2016-2019 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <string> # define __STDC_CONSTANT_MACROS extern "C" { # include <libavformat/avformat.h> # include <libavcodec/avcodec.h> # include <libavutil/avutil.h> # include <libswresample/swresample.h> } # include <Siv3D/EngineLog.hpp> # include "AudioFormat_AAC.hpp" namespace s3d { namespace detail { class AACDecoder { private: AVFormatContext* m_format_context = nullptr; AVCodecContext* m_codec_context = nullptr; AVFrame* m_frame = nullptr; AVPacket* m_packet = nullptr; struct SwrContext* m_swr_context = nullptr; uint8_t* m_out_buf = nullptr; AVStream* m_audio_stream = nullptr; int m_audio_stream_idx = 0; AVCodec* m_codec = nullptr; int m_out_count = 0; int m_out_sample_rate = 0; int64_t m_duration = 0; size_t m_wave_idx = 0; FilePath m_path; void setSample(Wave& wave, float* buf, size_t idx, size_t count) { WaveSample sample; for (size_t i = 0; i < count; ++i) { sample.set(buf[0], buf[1]); if (idx < wave.size()) wave[idx] = sample; else wave.push_back(sample); buf += 2; idx++; } } bool decode_by_avcodec(Wave& wave, bool do_flush) { int ret; ret = avcodec_send_packet(m_codec_context, (do_flush ? nullptr : m_packet)); if (ret < 0) { LOG_FAIL(U"AACDecoder: load() failed (avcodec_send_packet()) ({})"_fmt(m_path)); return false; } while (avcodec_receive_frame(m_codec_context, m_frame) == 0) { ret = swr_convert(m_swr_context, &m_out_buf, m_out_count, (const uint8_t**)(m_frame->data), m_frame->nb_samples); if (ret < 0) { LOG_FAIL(U"AACDecoder: load() failed (avcodec_receive_frame()) ({})"_fmt(m_path)); return false; } setSample(wave, (float*)m_out_buf, m_wave_idx, ret); m_wave_idx += ret; } return true; } public: ~AACDecoder() { if (m_out_buf != nullptr) av_free(m_out_buf); if (m_swr_context != nullptr) swr_free(&m_swr_context); if (m_frame != nullptr) av_frame_free(&m_frame); if (m_packet != nullptr) av_packet_free(&m_packet); if (m_codec_context != nullptr) avcodec_free_context(&m_codec_context); if (m_format_context != nullptr) avformat_close_input(&m_format_context); } bool init(const FilePath& path) { const std::string pathUTF8 = path.toUTF8(); const char* path_char = pathUTF8.c_str(); m_path = path; // open file. if (avformat_open_input(&m_format_context, path_char, nullptr, nullptr) != 0) { LOG_DEBUG(U"AACDecoder: avformat_open_input() failed ({}})"_fmt(m_path)); return false; } if (avformat_find_stream_info(m_format_context, nullptr) < 0) { LOG_DEBUG(U"AACDecoder: avformat_find_stream_info() failed ({})"_fmt(m_path)); return false; } // search audio stream for (size_t i = 0; i < m_format_context->nb_streams; ++i) { if (m_format_context->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { m_audio_stream = m_format_context->streams[i]; m_audio_stream_idx = i; break; } } if (m_audio_stream == nullptr) { LOG_DEBUG(U"AACDecoder: There are no audio stream ({})"_fmt(m_path)); return false; } m_duration = m_audio_stream->duration; // setup codec. m_codec = avcodec_find_decoder(m_audio_stream->codecpar->codec_id); if (m_codec == nullptr) { LOG_DEBUG(U"AACDecoder: avcodec_find_decoder() failed ({})"_fmt(m_path)); return false; } m_codec_context = avcodec_alloc_context3(m_codec); if (m_codec_context == nullptr) { LOG_DEBUG(U"AACDecoder: avcodec_alloc_context3() failed ({})"_fmt(m_path)); return false; } if (avcodec_parameters_to_context(m_codec_context, m_audio_stream->codecpar) < 0) { LOG_DEBUG(U"AACDecoder: avcodec_parameters_to_context() failed ({})"_fmt(m_path)); return false; } if (avcodec_open2(m_codec_context, m_codec, nullptr) != 0) { LOG_DEBUG(U"AACDecoder: avcodec_open2() failed ({})"_fmt(m_path)); return false; } // allocate packet m_packet = (AVPacket*)av_malloc(sizeof(AVPacket)); if (m_packet == nullptr) { LOG_DEBUG(U"AACDecoder: av_malloc() failed (packet) ({})"_fmt(m_path)); return false; } av_init_packet(m_packet); // allocate frame m_frame = av_frame_alloc(); if (m_frame == nullptr) { LOG_DEBUG(U"AACDecoder: av_frame_alloc() failed ({})"_fmt(m_path)); return false; } // initialize swr context int64_t out_channel_layout = AV_CH_LAYOUT_STEREO; int out_nb_samples = m_codec_context->frame_size; AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_FLT; m_out_sample_rate = m_codec_context->sample_rate; m_swr_context = swr_alloc_set_opts(m_swr_context, out_channel_layout, out_sample_fmt, m_out_sample_rate, av_get_default_channel_layout(m_codec_context->channels), m_codec_context->sample_fmt, m_codec_context->sample_rate, 0, nullptr); if (m_swr_context == nullptr) { LOG_DEBUG(U"AACDecoder: swr_alloc() failed ({})"_fmt(m_path)); return false; } int averr = swr_init(m_swr_context); if (swr_is_initialized(m_swr_context) == 0) { LOG_DEBUG(U"AACDecoder: swr_init() failed (AVERROR: {}) ({})"_fmt(Unicode::Widen(av_err2str(averr)), m_path)); return false; } // allocate output buffer int out_nb_channels = av_get_channel_layout_nb_channels(out_channel_layout); int buf_size = av_samples_get_buffer_size(nullptr, out_nb_channels, out_nb_samples, out_sample_fmt, 0); m_out_buf = (uint8_t*)av_malloc(buf_size); if (m_out_buf == nullptr) { LOG_DEBUG(U"AACDecoder: av_malloc() failed (m_out_buf) ({})"_fmt(m_path)); return false; } m_out_count = buf_size / out_nb_channels; return true; } Wave load() { Wave wave(m_duration, Arg::samplingRate = static_cast<uint32>(m_out_sample_rate)); while (0 <= av_read_frame(m_format_context, m_packet)) { if (m_packet->stream_index == m_audio_stream_idx) { if(!decode_by_avcodec(wave, false)) return Wave(); } av_packet_unref(m_packet); } // flush decoder if(!decode_by_avcodec(wave, true)) return Wave(); wave.resize(m_wave_idx); return wave; } }; } AudioFormat_AAC::AudioFormat_AAC() { } AudioFormat_AAC::~AudioFormat_AAC() { } AudioFormat AudioFormat_AAC::format() const { return AudioFormat::AAC; } const Array<String>& AudioFormat_AAC::possibleExtexsions() const { static const Array<String> extensions = { U"m4a" }; return extensions; } bool AudioFormat_AAC::isHeader(const uint8(&bytes)[16], const IReader&) const { // M4V MPEG-4 video/QuickTime file static constexpr uint8 M4V_SIGNx[] = { 0x66, 0x74, 0x79, 0x70, 0x6D, 0x70, 0x34, 0x32 }; // M4A Apple Lossless Audio Codec file static constexpr uint8 M4A_SIGNx[] = { 0x66, 0x74, 0x79, 0x70, 0x4D, 0x34, 0x41, 0x20 }; // MP4 ftypisom static constexpr uint8 MP4ISOM_SIGNx[] = { 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6F, 0x6D }; return (::memcmp(bytes + 4, M4V_SIGNx, sizeof(M4V_SIGNx)) == 0 || ::memcmp(bytes + 4, M4A_SIGNx, sizeof(M4A_SIGNx)) == 0 || ::memcmp(bytes + 4, MP4ISOM_SIGNx, sizeof(MP4ISOM_SIGNx)) == 0); } Wave AudioFormat_AAC::decodeFromFile(const FilePath& path) const { detail::AACDecoder decoder; if (!decoder.init(path)) { LOG_FAIL(U"AACDecoder: init() failed.\n"); return Wave(); } return decoder.load(); } Wave AudioFormat_AAC::decode(IReader&) const { // not supported return Wave(); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2006 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black */ #include "arch/sparc/isa_traits.hh" #include "arch/sparc/registers.hh" #include "arch/sparc/nativetrace.hh" #include "cpu/thread_context.hh" #include "params/SparcNativeTrace.hh" namespace Trace { static char *intRegNames[SparcISA::NumIntArchRegs] = { //Global registers "g0", "g1", "g2", "g3", "g4", "g5", "g6", "g7", //Output registers "o0", "o1", "o2", "o3", "o4", "o5", "o6", "o7", //Local registers "l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7", //Input registers "i0", "i1", "i2", "i3", "i4", "i5", "i6", "i7", }; void Trace::SparcNativeTrace::check(NativeTraceRecord *record) { ThreadContext *tc = record->getThread(); uint64_t regVal, realRegVal; // Integer registers // I doubt a real SPARC will describe more integer registers than this. assert(SparcISA::NumIntArchRegs == 32); char **regName = intRegNames; for (int i = 0; i < SparcISA::NumIntArchRegs; i++) { regVal = tc->readIntReg(i); read(&realRegVal, sizeof(realRegVal)); realRegVal = SparcISA::gtoh(realRegVal); checkReg(*(regName++), regVal, realRegVal); } // PC read(&realRegVal, sizeof(realRegVal)); realRegVal = SparcISA::gtoh(realRegVal); regVal = tc->readNextPC(); checkReg("pc", regVal, realRegVal); // NPC read(&realRegVal, sizeof(realRegVal)); realRegVal = SparcISA::gtoh(realRegVal); regVal = tc->readNextNPC(); checkReg("npc", regVal, realRegVal); // CCR read(&realRegVal, sizeof(realRegVal)); realRegVal = SparcISA::gtoh(realRegVal); regVal = tc->readIntReg(SparcISA::NumIntArchRegs + 2); checkReg("ccr", regVal, realRegVal); } } /* namespace Trace */ //////////////////////////////////////////////////////////////////////// // // ExeTracer Simulation Object // Trace::SparcNativeTrace * SparcNativeTraceParams::create() { return new Trace::SparcNativeTrace(this); }; <commit_msg>SPARC: Fix a minor compile bug in native trace on gcc > 4.1.<commit_after>/* * Copyright (c) 2006 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black */ #include "arch/sparc/isa_traits.hh" #include "arch/sparc/registers.hh" #include "arch/sparc/nativetrace.hh" #include "cpu/thread_context.hh" #include "params/SparcNativeTrace.hh" namespace Trace { static const char *intRegNames[SparcISA::NumIntArchRegs] = { //Global registers "g0", "g1", "g2", "g3", "g4", "g5", "g6", "g7", //Output registers "o0", "o1", "o2", "o3", "o4", "o5", "o6", "o7", //Local registers "l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7", //Input registers "i0", "i1", "i2", "i3", "i4", "i5", "i6", "i7", }; void Trace::SparcNativeTrace::check(NativeTraceRecord *record) { ThreadContext *tc = record->getThread(); uint64_t regVal, realRegVal; // Integer registers // I doubt a real SPARC will describe more integer registers than this. assert(SparcISA::NumIntArchRegs == 32); const char **regName = intRegNames; for (int i = 0; i < SparcISA::NumIntArchRegs; i++) { regVal = tc->readIntReg(i); read(&realRegVal, sizeof(realRegVal)); realRegVal = SparcISA::gtoh(realRegVal); checkReg(*(regName++), regVal, realRegVal); } // PC read(&realRegVal, sizeof(realRegVal)); realRegVal = SparcISA::gtoh(realRegVal); regVal = tc->readNextPC(); checkReg("pc", regVal, realRegVal); // NPC read(&realRegVal, sizeof(realRegVal)); realRegVal = SparcISA::gtoh(realRegVal); regVal = tc->readNextNPC(); checkReg("npc", regVal, realRegVal); // CCR read(&realRegVal, sizeof(realRegVal)); realRegVal = SparcISA::gtoh(realRegVal); regVal = tc->readIntReg(SparcISA::NumIntArchRegs + 2); checkReg("ccr", regVal, realRegVal); } } /* namespace Trace */ //////////////////////////////////////////////////////////////////////// // // ExeTracer Simulation Object // Trace::SparcNativeTrace * SparcNativeTraceParams::create() { return new Trace::SparcNativeTrace(this); }; <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iterator> #include "otbImage.h" #include "otbVectorData.h" #include "otbRadiometricMomentsImageFunction.h" #include "itkListSample.h" #include "itkFixedArray.h" #include "itkVariableLengthVector.h" #include "otbDescriptorsListSampleGenerator.h" #include "otbImageFileReader.h" #include "otbVectorDataFileReader.h" #include "otbImageFunctionAdaptor.h" #include "otbStatisticsXMLFileReader.h" #include "otbShiftScaleSampleListFilter.h" #include "otbSVMSampleListModelEstimator.h" const unsigned int Dimension = 2; typedef int LabelType; typedef double PixelType; typedef double FunctionPrecisionType; typedef double CoordRepType; typedef otb::Image<PixelType, Dimension> ImageType; typedef otb::VectorData<> VectorDataType; typedef otb::RadiometricMomentsImageFunction<ImageType, CoordRepType> FunctionType; typedef otb::ImageFunctionAdaptor<FunctionType, FunctionPrecisionType> AdapatedFunctionType; //typedef FunctionType::OutputType SampleType; typedef itk::VariableLengthVector<FunctionPrecisionType> SampleType; typedef itk::Statistics::ListSample<SampleType> ListSampleType; typedef itk::FixedArray<LabelType> LabelSampleType; typedef itk::Statistics::ListSample<LabelSampleType> LabelListSampleType; typedef otb::DescriptorsListSampleGenerator < ImageType, VectorDataType, ListSampleType, LabelListSampleType, FunctionPrecisionType, CoordRepType > DescriptorsListSampleGeneratorType; typedef otb::ImageFileReader<ImageType> ImageReaderType; typedef otb::VectorDataFileReader<VectorDataType> VectorDataReaderType; typedef otb::Functor::VariableLengthVectorToMeasurementVectorFunctor<SampleType> MeasurementVectorFunctorType; typedef otb::StatisticsXMLFileReader<SampleType> StatisticsReader; typedef otb::Statistics::ShiftScaleSampleListFilter<ListSampleType> ShiftScaleListSampleFilterType; typedef otb::SVMSampleListModelEstimator< ListSampleType, LabelListSampleType, MeasurementVectorFunctorType> SVMEstimatorType; typedef FunctionType::PointType PointType; typedef DescriptorsListSampleGeneratorType::SamplesPositionType SamplesPositionType; struct SampleEntry { PointType position; LabelType label; SampleType measurement; }; struct CompareSampleEntry { bool operator () (SampleEntry p, SampleEntry q) { // order with the y axis position if (p.position[1] < q.position[1]) return true; if (p.position[1] > q.position[1]) return false; // If one the same line, // order with the x axis position if (p.position[0] < q.position[0]) return true; return false; } }; std::ostream &operator<<(std::ostream &stream, SampleEntry entry) { stream << "---" << std::endl << "Label : " << entry.label << std::endl << "Position : " << entry.position << std::endl << "Measurements : " << entry.measurement; return stream; } int otbDescriptorsListSampleGeneratorNew(int itkNotUsed(argc), char* itkNotUsed(argv)[]) { // instantiation DescriptorsListSampleGeneratorType::Pointer generator = DescriptorsListSampleGeneratorType::New(); std::cout << generator << std::endl; return EXIT_SUCCESS; } int otbDescriptorsListSampleGenerator(int argc, char* argv[]) { if (argc != 6) { std::cerr << "Wrong number of arguments" << std::endl; return EXIT_FAILURE; } const char* inputImageFileName = argv[1]; const char* inputSamplesLocation = argv[2]; const char* outputFileName = argv[3]; int streaming = atoi(argv[4]); int neighborhood = atoi(argv[5]); ImageReaderType::Pointer imageReader = ImageReaderType::New(); imageReader->SetFileName(inputImageFileName); VectorDataReaderType::Pointer vectorDataReader = VectorDataReaderType::New(); vectorDataReader->SetFileName(inputSamplesLocation); //imageReader->Update(); //vectorDataReader->Update(); AdapatedFunctionType::Pointer descriptorsFunction = AdapatedFunctionType::New(); descriptorsFunction->SetInputImage(imageReader->GetOutput()); descriptorsFunction->GetInternalImageFunction()->SetNeighborhoodRadius(5); DescriptorsListSampleGeneratorType::Pointer descriptorsGenerator = DescriptorsListSampleGeneratorType::New(); descriptorsGenerator->SetInputImage(imageReader->GetOutput()); descriptorsGenerator->SetSamplesLocations(vectorDataReader->GetOutput()); descriptorsGenerator->SetDescriptorsFunction(descriptorsFunction.GetPointer()); descriptorsGenerator->SetNeighborhoodRadius(neighborhood); descriptorsGenerator->GetStreamer()->SetNumberOfLinesStrippedStreaming( streaming ); descriptorsGenerator->Update(); ListSampleType::Pointer samples = descriptorsGenerator->GetListSample(); LabelListSampleType::Pointer labels = descriptorsGenerator->GetLabelListSample(); SamplesPositionType& positions = descriptorsGenerator->GetSamplesPositions(); ListSampleType::Iterator sampleIt = samples->Begin(); LabelListSampleType::Iterator labelIt = labels->Begin(); SamplesPositionType::const_iterator posIt = positions.begin(); ListSampleType::Iterator sampleEnd = samples->End(); LabelListSampleType::Iterator labelEnd = labels->End(); SamplesPositionType::const_iterator posEnd = positions.end(); std::vector<SampleEntry> entries; while (sampleIt != sampleEnd && labelIt != labelEnd && posIt != posEnd) { SampleEntry entry; entry.position = *posIt; entry.label = labelIt.GetMeasurementVector()[0]; entry.measurement = sampleIt.GetMeasurementVector(); entries.push_back(entry); ++sampleIt; ++labelIt; ++posIt; } std::sort(entries.begin(), entries.end(), CompareSampleEntry()); std::ofstream file(outputFileName); std::copy(entries.begin(), entries.end(), std::ostream_iterator<SampleEntry>(file, "\n")); file.close(); return EXIT_SUCCESS; } int otbDescriptorsSVMModelCreation(int argc, char* argv[]) { if (argc != 7) { std::cerr << "Wrong number of arguments" << std::endl; return EXIT_FAILURE; } const char* inputImageFileName = argv[1]; const char* inputSamplesLocation = argv[2]; const char* featureStatisticsFileName = argv[3]; const char* outputFileName = argv[4]; int streaming = atoi(argv[5]); int neighborhood = atoi(argv[6]); ImageReaderType::Pointer imageReader = ImageReaderType::New(); imageReader->SetFileName(inputImageFileName); VectorDataReaderType::Pointer vectorDataReader = VectorDataReaderType::New(); vectorDataReader->SetFileName(inputSamplesLocation); //imageReader->Update(); //vectorDataReader->Update(); AdapatedFunctionType::Pointer descriptorsFunction = AdapatedFunctionType::New(); descriptorsFunction->SetInputImage(imageReader->GetOutput()); descriptorsFunction->GetInternalImageFunction()->SetNeighborhoodRadius(neighborhood); DescriptorsListSampleGeneratorType::Pointer descriptorsGenerator = DescriptorsListSampleGeneratorType::New(); descriptorsGenerator->SetInputImage(imageReader->GetOutput()); descriptorsGenerator->SetSamplesLocations(vectorDataReader->GetOutput()); descriptorsGenerator->SetDescriptorsFunction(descriptorsFunction.GetPointer()); descriptorsGenerator->SetNeighborhoodRadius(5); descriptorsGenerator->GetStreamer()->SetNumberOfLinesStrippedStreaming( streaming ); descriptorsGenerator->Update(); // Normalize the samples // Read the mean and variance form the XML file StatisticsReader::Pointer statisticsReader = StatisticsReader::New(); statisticsReader->SetFileName(featureStatisticsFileName); SampleType meanMeasurentVector = statisticsReader->GetStatisticVectorByName("mean"); SampleType varianceMeasurentVector = statisticsReader->GetStatisticVectorByName("stddev"); // Shift scale the samples ShiftScaleListSampleFilterType::Pointer shiftscaleFilter = ShiftScaleListSampleFilterType::New(); shiftscaleFilter->SetInput(descriptorsGenerator->GetListSample()); shiftscaleFilter->SetShifts(meanMeasurentVector); shiftscaleFilter->SetScales(varianceMeasurentVector); shiftscaleFilter->Update(); SVMEstimatorType::Pointer svmEstimator = SVMEstimatorType::New(); svmEstimator->SetInputSampleList(shiftscaleFilter->GetOutputSampleList()); svmEstimator->SetTrainingSampleList(descriptorsGenerator->GetLabelListSample()); svmEstimator->Update(); svmEstimator->GetModel()->SaveModel(outputFileName); return EXIT_SUCCESS; } <commit_msg>BUG: use a 1-dimension FixedArray since default is 3<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iterator> #include "otbImage.h" #include "otbVectorData.h" #include "otbRadiometricMomentsImageFunction.h" #include "itkListSample.h" #include "itkFixedArray.h" #include "itkVariableLengthVector.h" #include "otbDescriptorsListSampleGenerator.h" #include "otbImageFileReader.h" #include "otbVectorDataFileReader.h" #include "otbImageFunctionAdaptor.h" #include "otbStatisticsXMLFileReader.h" #include "otbShiftScaleSampleListFilter.h" #include "otbSVMSampleListModelEstimator.h" const unsigned int Dimension = 2; typedef int LabelType; typedef double PixelType; typedef double FunctionPrecisionType; typedef double CoordRepType; typedef otb::Image<PixelType, Dimension> ImageType; typedef otb::VectorData<> VectorDataType; typedef otb::RadiometricMomentsImageFunction<ImageType, CoordRepType> FunctionType; typedef otb::ImageFunctionAdaptor<FunctionType, FunctionPrecisionType> AdapatedFunctionType; typedef itk::VariableLengthVector<FunctionPrecisionType> SampleType; typedef itk::Statistics::ListSample<SampleType> ListSampleType; typedef itk::FixedArray<LabelType, 1> LabelSampleType; typedef itk::Statistics::ListSample<LabelSampleType> LabelListSampleType; typedef otb::DescriptorsListSampleGenerator < ImageType, VectorDataType, ListSampleType, LabelListSampleType, FunctionPrecisionType, CoordRepType > DescriptorsListSampleGeneratorType; typedef otb::ImageFileReader<ImageType> ImageReaderType; typedef otb::VectorDataFileReader<VectorDataType> VectorDataReaderType; typedef otb::Functor::VariableLengthVectorToMeasurementVectorFunctor<SampleType> MeasurementVectorFunctorType; typedef otb::StatisticsXMLFileReader<SampleType> StatisticsReader; typedef otb::Statistics::ShiftScaleSampleListFilter<ListSampleType> ShiftScaleListSampleFilterType; typedef otb::SVMSampleListModelEstimator< ListSampleType, LabelListSampleType, MeasurementVectorFunctorType> SVMEstimatorType; typedef FunctionType::PointType PointType; typedef DescriptorsListSampleGeneratorType::SamplesPositionType SamplesPositionType; struct SampleEntry { PointType position; LabelType label; SampleType measurement; }; struct CompareSampleEntry { bool operator () (SampleEntry p, SampleEntry q) { // order with the y axis position if (p.position[1] < q.position[1]) return true; if (p.position[1] > q.position[1]) return false; // If one the same line, // order with the x axis position if (p.position[0] < q.position[0]) return true; return false; } }; std::ostream &operator<<(std::ostream &stream, SampleEntry entry) { stream << "---" << std::endl << "Label : " << entry.label << std::endl << "Position : " << entry.position << std::endl << "Measurements : " << entry.measurement; return stream; } int otbDescriptorsListSampleGeneratorNew(int itkNotUsed(argc), char* itkNotUsed(argv)[]) { // instantiation DescriptorsListSampleGeneratorType::Pointer generator = DescriptorsListSampleGeneratorType::New(); std::cout << generator << std::endl; return EXIT_SUCCESS; } int otbDescriptorsListSampleGenerator(int argc, char* argv[]) { if (argc != 6) { std::cerr << "Wrong number of arguments" << std::endl; return EXIT_FAILURE; } const char* inputImageFileName = argv[1]; const char* inputSamplesLocation = argv[2]; const char* outputFileName = argv[3]; int streaming = atoi(argv[4]); int neighborhood = atoi(argv[5]); ImageReaderType::Pointer imageReader = ImageReaderType::New(); imageReader->SetFileName(inputImageFileName); VectorDataReaderType::Pointer vectorDataReader = VectorDataReaderType::New(); vectorDataReader->SetFileName(inputSamplesLocation); //imageReader->Update(); //vectorDataReader->Update(); AdapatedFunctionType::Pointer descriptorsFunction = AdapatedFunctionType::New(); descriptorsFunction->SetInputImage(imageReader->GetOutput()); descriptorsFunction->GetInternalImageFunction()->SetNeighborhoodRadius(5); DescriptorsListSampleGeneratorType::Pointer descriptorsGenerator = DescriptorsListSampleGeneratorType::New(); descriptorsGenerator->SetInputImage(imageReader->GetOutput()); descriptorsGenerator->SetSamplesLocations(vectorDataReader->GetOutput()); descriptorsGenerator->SetDescriptorsFunction(descriptorsFunction.GetPointer()); descriptorsGenerator->SetNeighborhoodRadius(neighborhood); descriptorsGenerator->GetStreamer()->SetNumberOfLinesStrippedStreaming( streaming ); descriptorsGenerator->Update(); ListSampleType::Pointer samples = descriptorsGenerator->GetListSample(); LabelListSampleType::Pointer labels = descriptorsGenerator->GetLabelListSample(); SamplesPositionType& positions = descriptorsGenerator->GetSamplesPositions(); ListSampleType::Iterator sampleIt = samples->Begin(); LabelListSampleType::Iterator labelIt = labels->Begin(); SamplesPositionType::const_iterator posIt = positions.begin(); ListSampleType::Iterator sampleEnd = samples->End(); LabelListSampleType::Iterator labelEnd = labels->End(); SamplesPositionType::const_iterator posEnd = positions.end(); std::vector<SampleEntry> entries; while (sampleIt != sampleEnd && labelIt != labelEnd && posIt != posEnd) { SampleEntry entry; entry.position = *posIt; entry.label = labelIt.GetMeasurementVector()[0]; entry.measurement = sampleIt.GetMeasurementVector(); entries.push_back(entry); ++sampleIt; ++labelIt; ++posIt; } std::sort(entries.begin(), entries.end(), CompareSampleEntry()); std::ofstream file(outputFileName); std::copy(entries.begin(), entries.end(), std::ostream_iterator<SampleEntry>(file, "\n")); file.close(); return EXIT_SUCCESS; } int otbDescriptorsSVMModelCreation(int argc, char* argv[]) { if (argc != 7) { std::cerr << "Wrong number of arguments" << std::endl; return EXIT_FAILURE; } const char* inputImageFileName = argv[1]; const char* inputSamplesLocation = argv[2]; const char* featureStatisticsFileName = argv[3]; const char* outputFileName = argv[4]; int streaming = atoi(argv[5]); int neighborhood = atoi(argv[6]); ImageReaderType::Pointer imageReader = ImageReaderType::New(); imageReader->SetFileName(inputImageFileName); VectorDataReaderType::Pointer vectorDataReader = VectorDataReaderType::New(); vectorDataReader->SetFileName(inputSamplesLocation); //imageReader->Update(); //vectorDataReader->Update(); AdapatedFunctionType::Pointer descriptorsFunction = AdapatedFunctionType::New(); descriptorsFunction->SetInputImage(imageReader->GetOutput()); descriptorsFunction->GetInternalImageFunction()->SetNeighborhoodRadius(neighborhood); DescriptorsListSampleGeneratorType::Pointer descriptorsGenerator = DescriptorsListSampleGeneratorType::New(); descriptorsGenerator->SetInputImage(imageReader->GetOutput()); descriptorsGenerator->SetSamplesLocations(vectorDataReader->GetOutput()); descriptorsGenerator->SetDescriptorsFunction(descriptorsFunction.GetPointer()); descriptorsGenerator->SetNeighborhoodRadius(5); descriptorsGenerator->GetStreamer()->SetNumberOfLinesStrippedStreaming( streaming ); descriptorsGenerator->Update(); // Normalize the samples // Read the mean and variance form the XML file StatisticsReader::Pointer statisticsReader = StatisticsReader::New(); statisticsReader->SetFileName(featureStatisticsFileName); SampleType meanMeasurentVector = statisticsReader->GetStatisticVectorByName("mean"); SampleType varianceMeasurentVector = statisticsReader->GetStatisticVectorByName("stddev"); // Shift scale the samples ShiftScaleListSampleFilterType::Pointer shiftscaleFilter = ShiftScaleListSampleFilterType::New(); shiftscaleFilter->SetInput(descriptorsGenerator->GetListSample()); shiftscaleFilter->SetShifts(meanMeasurentVector); shiftscaleFilter->SetScales(varianceMeasurentVector); shiftscaleFilter->Update(); SVMEstimatorType::Pointer svmEstimator = SVMEstimatorType::New(); svmEstimator->SetInputSampleList(shiftscaleFilter->GetOutputSampleList()); svmEstimator->SetTrainingSampleList(descriptorsGenerator->GetLabelListSample()); svmEstimator->Update(); svmEstimator->GetModel()->SaveModel(outputFileName); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <platform.hpp> #include <driver.h> #include <vector> #include <string> #include <algorithm> #include <sstream> #include <iostream> #include <stdexcept> #include <cstdio> //Macro for checking cuda errors following a cuda launch or api call #define CUDA(call) \ do { \ cudaError_t err = call; \ if (cudaSuccess != err) { \ fprintf (stderr, "CUDA Error in %s:%d : %s.", \ __FILE__, __LINE__, cudaGetErrorString(err)); \ exit(EXIT_FAILURE); \ } \ } while (0); \ using namespace std; namespace cuda { /////////////////////////////////////////////////////////////////////////// // HELPERS /////////////////////////////////////////////////////////////////////////// // pulled from CUTIL from CUDA SDK static inline int compute2cores(int major, int minor) { struct { int compute; // 0xMm (hex), M = major version, m = minor version int cores; } gpus[] = { { 0x10, 8 }, { 0x11, 8 }, { 0x12, 8 }, { 0x13, 8 }, { 0x20, 32 }, { 0x21, 48 }, { 0x30, 192 }, { 0x35, 192 }, { 0x50, 128 }, { -1, -1 }, }; for (int i = 0; gpus[i].compute != -1; ++i) { if (gpus[i].compute == (major << 4) + minor) return gpus[i].cores; } return 0; } // compare two cards based on (in order): // 1. flops (theoretical) // 2. total memory #define COMPARE(a,b,f) do { \ return ((a)->f >= (b)->f); \ } while (0); static inline bool card_compare_compute(const cudaDevice_t &l, const cudaDevice_t &r) { const cudaDevice_t *lc = &l; const cudaDevice_t *rc = &r; COMPARE(lc, rc, prop.major); COMPARE(lc, rc, prop.minor); COMPARE(lc, rc, flops); COMPARE(lc, rc, prop.totalGlobalMem); COMPARE(lc, rc, nativeId); return 0; } static inline bool card_compare_flops(const cudaDevice_t &l, const cudaDevice_t &r) { const cudaDevice_t *lc = &l; const cudaDevice_t *rc = &r; COMPARE(lc, rc, flops); COMPARE(lc, rc, prop.totalGlobalMem); COMPARE(lc, rc, prop.major); COMPARE(lc, rc, prop.minor); COMPARE(lc, rc, nativeId); return 0; } static inline bool card_compare_mem(const cudaDevice_t &l, const cudaDevice_t &r) { const cudaDevice_t *lc = &l; const cudaDevice_t *rc = &r; COMPARE(lc, rc, prop.totalGlobalMem); COMPARE(lc, rc, flops); COMPARE(lc, rc, prop.major); COMPARE(lc, rc, prop.minor); COMPARE(lc, rc, nativeId); return 0; } static inline bool card_compare_num(const cudaDevice_t &l, const cudaDevice_t &r) { const cudaDevice_t *lc = &l; const cudaDevice_t *rc = &r; COMPARE(lc, rc, nativeId); return 0; } template <typename T> static inline string toString(T val) { stringstream s; s << val; return s.str(); } /////////////////////////////////////////////////////////////////////////// // Wrapper Functions /////////////////////////////////////////////////////////////////////////// string getInfo() { string info = getPlatformInfo(); for (int i = 0; i < getDeviceCount(); ++i) { info += getDeviceInfo(i); } return info; } string getDeviceInfo(int device) { cudaDeviceProp dev = getDeviceProp(device); size_t mem_gpu_total = dev.totalGlobalMem; //double cc = double(dev.major) + double(dev.minor) / 10; bool show_braces = getActiveDeviceId() == device; string id = (show_braces ? string("[") : "-") + toString(device) + (show_braces ? string("]") : "-"); string name(dev.name); string memory = toString((mem_gpu_total / (1024 * 1024)) + !!(mem_gpu_total % (1024 * 1024))) + string(" MB"); string compute = string("CUDA Compute ") + toString(dev.major) + string(".") + toString(dev.minor); string info = id + string(" ") + name + string(", ") + memory + string(", ") + compute + string("\n"); return info; } string getPlatformInfo() { string driverVersion = getDriverVersion(); std::string cudaRuntime = getCUDARuntimeVersion(); string platform = "Platform: CUDA Toolkit " + cudaRuntime; if (!driverVersion.empty()) { platform.append(", Driver: "); platform.append(driverVersion); } platform.append("\n"); return platform; } string getDriverVersion() { char driverVersion[1024] = {" ",}; int x = nvDriverVersion(driverVersion, sizeof(driverVersion)); if (x != 1) { #ifndef OS_MAC // HACK Mac OSX 10.7 needs new method for fetching driver throw runtime_error("Invalid driver"); #endif return string(""); } else { return string(driverVersion); } } string getCUDARuntimeVersion() { int runtime = 0; CUDA(cudaRuntimeGetVersion(&runtime)); if(runtime / 100.f > 0) return toString((runtime / 1000) + (runtime % 1000)/ 100.); else return toString(runtime / 1000) + string(".0"); } int getDeviceCount() { return DeviceManager::getInstance().nDevices; } int getActiveDeviceId() { return DeviceManager::getInstance().activeDev; } int getDeviceNativeId(int device) { if(device < (int)DeviceManager::getInstance().cuDevices.size()) return DeviceManager::getInstance().cuDevices[device].nativeId; return -1; } int setDevice(int device) { return DeviceManager::getInstance().setActiveDevice(device); } cudaDeviceProp getDeviceProp(int device) { if(device < (int)DeviceManager::getInstance().cuDevices.size()) return DeviceManager::getInstance().cuDevices[device].prop; return DeviceManager::getInstance().cuDevices[0].prop; } /////////////////////////////////////////////////////////////////////////// // DeviceManager Class Functions /////////////////////////////////////////////////////////////////////////// DeviceManager& DeviceManager::getInstance() { static DeviceManager my_instance; return my_instance; } DeviceManager::DeviceManager() : cuDevices(0), activeDev(0), nDevices(0) { CUDA(cudaGetDeviceCount(&nDevices)); if (nDevices == 0) throw runtime_error("No CUDA-Capable devices found"); cuDevices.reserve(nDevices); for(int i = 0; i < nDevices; i++) { cudaDevice_t dev; cudaGetDeviceProperties(&dev.prop, i); dev.flops = dev.prop.multiProcessorCount * compute2cores(dev.prop.major, dev.prop.minor) * dev.prop.clockRate; dev.nativeId = i; cuDevices.push_back(dev); } sortDevices(); setActiveDevice(0); } void DeviceManager::sortDevices(sort_mode mode) { switch(mode) { case memory : sort(cuDevices.begin(), cuDevices.end(), card_compare_mem); break; case flops : sort(cuDevices.begin(), cuDevices.end(), card_compare_flops); break; case compute : sort(cuDevices.begin(), cuDevices.end(), card_compare_compute); break; case none : default : sort(cuDevices.begin(), cuDevices.end(), card_compare_num); break; } } int DeviceManager::setActiveDevice(int device) { if(device > (int)cuDevices.size()) { return -1; } else { int old = activeDev; CUDA(cudaSetDevice(device)); activeDev = device; return old; } } } <commit_msg>Fixed cudaGetDriverVersion for Mac and ARM<commit_after>#include <platform.hpp> #include <driver.h> #include <vector> #include <string> #include <algorithm> #include <sstream> #include <iostream> #include <stdexcept> #include <cstdio> //Macro for checking cuda errors following a cuda launch or api call #define CUDA(call) \ do { \ cudaError_t err = call; \ if (cudaSuccess != err) { \ fprintf (stderr, "CUDA Error in %s:%d : %s.", \ __FILE__, __LINE__, cudaGetErrorString(err)); \ exit(EXIT_FAILURE); \ } \ } while (0); \ using namespace std; namespace cuda { /////////////////////////////////////////////////////////////////////////// // HELPERS /////////////////////////////////////////////////////////////////////////// // pulled from CUTIL from CUDA SDK static inline int compute2cores(int major, int minor) { struct { int compute; // 0xMm (hex), M = major version, m = minor version int cores; } gpus[] = { { 0x10, 8 }, { 0x11, 8 }, { 0x12, 8 }, { 0x13, 8 }, { 0x20, 32 }, { 0x21, 48 }, { 0x30, 192 }, { 0x35, 192 }, { 0x50, 128 }, { -1, -1 }, }; for (int i = 0; gpus[i].compute != -1; ++i) { if (gpus[i].compute == (major << 4) + minor) return gpus[i].cores; } return 0; } // compare two cards based on (in order): // 1. flops (theoretical) // 2. total memory #define COMPARE(a,b,f) do { \ return ((a)->f >= (b)->f); \ } while (0); static inline bool card_compare_compute(const cudaDevice_t &l, const cudaDevice_t &r) { const cudaDevice_t *lc = &l; const cudaDevice_t *rc = &r; COMPARE(lc, rc, prop.major); COMPARE(lc, rc, prop.minor); COMPARE(lc, rc, flops); COMPARE(lc, rc, prop.totalGlobalMem); COMPARE(lc, rc, nativeId); return 0; } static inline bool card_compare_flops(const cudaDevice_t &l, const cudaDevice_t &r) { const cudaDevice_t *lc = &l; const cudaDevice_t *rc = &r; COMPARE(lc, rc, flops); COMPARE(lc, rc, prop.totalGlobalMem); COMPARE(lc, rc, prop.major); COMPARE(lc, rc, prop.minor); COMPARE(lc, rc, nativeId); return 0; } static inline bool card_compare_mem(const cudaDevice_t &l, const cudaDevice_t &r) { const cudaDevice_t *lc = &l; const cudaDevice_t *rc = &r; COMPARE(lc, rc, prop.totalGlobalMem); COMPARE(lc, rc, flops); COMPARE(lc, rc, prop.major); COMPARE(lc, rc, prop.minor); COMPARE(lc, rc, nativeId); return 0; } static inline bool card_compare_num(const cudaDevice_t &l, const cudaDevice_t &r) { const cudaDevice_t *lc = &l; const cudaDevice_t *rc = &r; COMPARE(lc, rc, nativeId); return 0; } template <typename T> static inline string toString(T val) { stringstream s; s << val; return s.str(); } /////////////////////////////////////////////////////////////////////////// // Wrapper Functions /////////////////////////////////////////////////////////////////////////// string getInfo() { string info = getPlatformInfo(); for (int i = 0; i < getDeviceCount(); ++i) { info += getDeviceInfo(i); } return info; } string getDeviceInfo(int device) { cudaDeviceProp dev = getDeviceProp(device); size_t mem_gpu_total = dev.totalGlobalMem; //double cc = double(dev.major) + double(dev.minor) / 10; bool show_braces = getActiveDeviceId() == device; string id = (show_braces ? string("[") : "-") + toString(device) + (show_braces ? string("]") : "-"); string name(dev.name); string memory = toString((mem_gpu_total / (1024 * 1024)) + !!(mem_gpu_total % (1024 * 1024))) + string(" MB"); string compute = string("CUDA Compute ") + toString(dev.major) + string(".") + toString(dev.minor); string info = id + string(" ") + name + string(", ") + memory + string(", ") + compute + string("\n"); return info; } string getPlatformInfo() { string driverVersion = getDriverVersion(); std::string cudaRuntime = getCUDARuntimeVersion(); string platform = "Platform: CUDA Toolkit " + cudaRuntime; if (!driverVersion.empty()) { platform.append(", Driver: "); platform.append(driverVersion); } platform.append("\n"); return platform; } string getDriverVersion() { char driverVersion[1024] = {" ",}; int x = nvDriverVersion(driverVersion, sizeof(driverVersion)); if (x != 1) { #if !defined(OS_MAC) && !defined(__arm__) // HACK Mac OSX 10.7 needs new method for fetching driver throw runtime_error("Invalid driver"); #endif int driver = 0; CUDA(cudaDriverGetVersion(&driver)); return string("CUDA Driver Version: ") + toString(driver); } else { return string(driverVersion); } } string getCUDARuntimeVersion() { int runtime = 0; CUDA(cudaRuntimeGetVersion(&runtime)); if(runtime / 100.f > 0) return toString((runtime / 1000) + (runtime % 1000)/ 100.); else return toString(runtime / 1000) + string(".0"); } int getDeviceCount() { return DeviceManager::getInstance().nDevices; } int getActiveDeviceId() { return DeviceManager::getInstance().activeDev; } int getDeviceNativeId(int device) { if(device < (int)DeviceManager::getInstance().cuDevices.size()) return DeviceManager::getInstance().cuDevices[device].nativeId; return -1; } int setDevice(int device) { return DeviceManager::getInstance().setActiveDevice(device); } cudaDeviceProp getDeviceProp(int device) { if(device < (int)DeviceManager::getInstance().cuDevices.size()) return DeviceManager::getInstance().cuDevices[device].prop; return DeviceManager::getInstance().cuDevices[0].prop; } /////////////////////////////////////////////////////////////////////////// // DeviceManager Class Functions /////////////////////////////////////////////////////////////////////////// DeviceManager& DeviceManager::getInstance() { static DeviceManager my_instance; return my_instance; } DeviceManager::DeviceManager() : cuDevices(0), activeDev(0), nDevices(0) { CUDA(cudaGetDeviceCount(&nDevices)); if (nDevices == 0) throw runtime_error("No CUDA-Capable devices found"); cuDevices.reserve(nDevices); for(int i = 0; i < nDevices; i++) { cudaDevice_t dev; cudaGetDeviceProperties(&dev.prop, i); dev.flops = dev.prop.multiProcessorCount * compute2cores(dev.prop.major, dev.prop.minor) * dev.prop.clockRate; dev.nativeId = i; cuDevices.push_back(dev); } sortDevices(); setActiveDevice(0); } void DeviceManager::sortDevices(sort_mode mode) { switch(mode) { case memory : sort(cuDevices.begin(), cuDevices.end(), card_compare_mem); break; case flops : sort(cuDevices.begin(), cuDevices.end(), card_compare_flops); break; case compute : sort(cuDevices.begin(), cuDevices.end(), card_compare_compute); break; case none : default : sort(cuDevices.begin(), cuDevices.end(), card_compare_num); break; } } int DeviceManager::setActiveDevice(int device) { if(device > (int)cuDevices.size()) { return -1; } else { int old = activeDev; CUDA(cudaSetDevice(device)); activeDev = device; return old; } } } <|endoftext|>
<commit_before>#include <unistd.h> #include <iostream> #include <vector> #include <utilities/realtime/dataman/ZmqMan.h> using namespace std; using namespace adios::realtime; using json = nlohmann::json; int main(){ adios::realtime::ZmqMan man; json msg; msg["local_ip"] = "127.0.0.1"; msg["remote_ip"] = "127.0.0.1"; msg["local_port"] = 12306; msg["remote_port"] = 12307; msg["num_channels"] = 1; msg["stream_mode"] = "sender"; msg["tolerance"] = {0}; msg["priority"] = {100}; man.init(msg); json msg2; msg2["putshape"] = {1,2,5}; msg2["varshape"] = {4,6,10}; msg2["doid"] = "aaa"; msg2["var"] = "data"; msg2["dtype"] = "float"; int datasize = 10; float data[datasize]; for(int loop=0; loop<100; loop++){ for (int i=0; i<4; i++){ for (int j=0; j<3; j++){ for (int k=0; k<2; k++){ for (int m=0; m<datasize; m++){ data[m] = i*10000 + j*100 + k*10 + m; } msg2["offset"] = {i,j*2,k*5}; man.put(data, msg2); for (int i=0; i<10; i++) cout << ((float*)data)[i] << " "; cout << endl; } } } man.flush(); } return 0; } <commit_msg>changed writeZmq.cc to accept cmd arguments for IP address<commit_after>#include <unistd.h> #include <iostream> #include <vector> #include <utilities/realtime/dataman/ZmqMan.h> using namespace std; using namespace adios::realtime; using json = nlohmann::json; int main(int argc, char** argv){ adios::realtime::ZmqMan man; json msg; msg["local_ip"] = "127.0.0.1"; msg["remote_ip"] = "127.0.0.1"; msg["local_port"] = 12306; msg["remote_port"] = 12307; msg["num_channels"] = 1; msg["stream_mode"] = "sender"; msg["tolerance"] = {0}; msg["priority"] = {100}; if(argc >= 2){ msg["remote_ip"] = argv[1]; if(argc >= 3){ msg["remote_port"] = stoi(argv[2]); } } man.init(msg); json msg2; msg2["putshape"] = {1,2,5}; msg2["varshape"] = {4,6,10}; msg2["doid"] = "aaa"; msg2["var"] = "data"; msg2["dtype"] = "float"; int datasize = 10; float data[datasize]; for(int loop=0; loop<100; loop++){ for (int i=0; i<4; i++){ for (int j=0; j<3; j++){ for (int k=0; k<2; k++){ for (int m=0; m<datasize; m++){ data[m] = i*10000 + j*100 + k*10 + m; } msg2["offset"] = {i,j*2,k*5}; man.put(data, msg2); for (int i=0; i<10; i++) cout << ((float*)data)[i] << " "; cout << endl; } } } man.flush(); } return 0; } <|endoftext|>
<commit_before>#ifndef BUFFER_CACHE_ALT_PAGE_HPP_ #define BUFFER_CACHE_ALT_PAGE_HPP_ #include "concurrency/cond_var.hpp" #include "containers/backindex_bag.hpp" #include "repli_timestamp.hpp" #include "serializer/buf_ptr.hpp" #include "serializer/types.hpp" class cache_account_t; namespace alt { class page_cache_t; class page_acq_t; class page_loader_t; class deferred_page_loader_t; class deferred_block_token_t; // A page_t represents a page (a byte buffer of a specific size), having a definite // value known at the construction of the page_t (and possibly later modified // in-place, but still a definite known value). class page_t { public: // Defers loading the block for the given block id (but does go and get its block // token ASAP, so that we can't lose access to the current version of the block). page_t(block_id_t block_id, page_cache_t *page_cache); // Loads the block for the given block id. page_t(block_id_t block_id, page_cache_t *page_cache, cache_account_t *account); page_t(block_id_t block_id, buf_ptr_t buf, page_cache_t *page_cache); page_t(block_id_t block_id, buf_ptr_t buf, const counted_t<standard_block_token_t> &token, page_cache_t *page_cache); page_t(page_t *copyee, page_cache_t *page_cache, cache_account_t *account); ~page_t(); page_t *make_copy(page_cache_t *page_cache, cache_account_t *account); void add_waiter(page_acq_t *acq, cache_account_t *account); void remove_waiter(page_acq_t *acq); // These may not be called until the page_acq_t's buf_ready_signal is pulsed. void *get_page_buf(page_cache_t *page_cache); void reset_block_token(page_cache_t *page_cache); void set_page_buf_size(block_size_t block_size, page_cache_t *page_cache); block_size_t get_page_buf_size(); // How much memory the block would use, if it were in memory. (If the block is // already in memory, this is how much memory the block is currently // using, of course.) uint32_t hypothetical_memory_usage(page_cache_t *page_cache) const; uint64_t access_time() const { return access_time_; } bool is_loading() const { return loader_ != NULL && page_t::loader_is_loading(loader_); } bool is_deferred_loading() const { return loader_ != NULL && !page_t::loader_is_loading(loader_); } bool has_waiters() const { return !waiters_.empty(); } bool is_loaded() const { return buf_.has(); } bool is_disk_backed() const { return block_token_.has(); } void evict_self(page_cache_t *page_cache); block_id_t block_id() const { return block_id_; } bool page_ptr_count() const { return snapshot_refcount_; } const counted_t<standard_block_token_t> &block_token() const { return block_token_; } ser_buffer_t *get_loaded_ser_buffer(); void init_block_token(counted_t<standard_block_token_t> token, page_cache_t *page_cache); private: friend class page_ptr_t; friend class deferred_page_loader_t; static bool loader_is_loading(page_loader_t *loader); void add_snapshotter(); void remove_snapshotter(page_cache_t *page_cache); size_t num_snapshot_references(); void pulse_waiters_or_make_evictable(page_cache_t *page_cache); static void finish_load_with_block_id(page_t *page, page_cache_t *page_cache, counted_t<standard_block_token_t> block_token, buf_ptr_t buf); static void catch_up_with_deferred_load( deferred_page_loader_t *deferred_loader, page_cache_t *page_cache, cache_account_t *account); static void deferred_load_with_block_id(page_t *page, block_id_t block_id, page_cache_t *page_cache); static void load_with_block_id(page_t *page, block_id_t block_id, page_cache_t *page_cache, cache_account_t *account); static void load_from_copyee(page_t *page, page_t *copyee, page_cache_t *page_cache, cache_account_t *account); static void load_using_block_token(page_t *page, page_cache_t *page_cache, cache_account_t *account); friend backindex_bag_index_t *access_backindex(page_t *page); // The block id. Used to (potentially) delete the page_t and current_page_t when // it gets evicted. const block_id_t block_id_; // KSI: Explain this more. // One of loader_, buf_, or block_token_ is non-null. page_loader_t *loader_; buf_ptr_t buf_; counted_t<standard_block_token_t> block_token_; uint64_t access_time_; // How many page_ptr_t's point at this page, expecting nothing to modify it, // other than themselves. size_t snapshot_refcount_; // A list of waiters that expect the value to be loaded, and (as long as there // are waiters) expect the value to never be evicted. // KSI: This could be a single pointer instead of two. intrusive_list_t<page_acq_t> waiters_; // This page_t's index into its eviction bag (managed by the page_cache_t -- one // of unevictable_pages_, etc). Which bag we should be in: // // if loader_ is non-null: unevictable_pages_ // else if waiters_ is non-empty: unevictable_pages_ // else if buf_ is null: evicted_pages_ (and block_token_ is non-null) // else if block_token_ is non-null: evictable_disk_backed_pages_ // else: evictable_unbacked_pages_ (buf_ is non-null, block_token_ is null) // // So, when loader_, waiters_, buf_, or block_token_ is touched, we might // need to change this page's eviction bag. // // The logic above is implemented in page_cache_t::correct_eviction_category. backindex_bag_index_t eviction_index_; DISABLE_COPYING(page_t); }; inline backindex_bag_index_t *access_backindex(page_t *page) { return &page->eviction_index_; } // A page_ptr_t holds a pointer to a page_t. class page_ptr_t { public: explicit page_ptr_t(page_t *page) : page_(NULL) { init(page); } page_ptr_t(); // The page_ptr_t MUST be reset before the destructor is called. ~page_ptr_t(); // You MUST manually call reset_page_ptr() to reset the page_ptr_t. Then, please // call consider_evicting_current_page if applicable. void reset_page_ptr(page_cache_t *page_cache); page_ptr_t(page_ptr_t &&movee); page_ptr_t &operator=(page_ptr_t &&movee); void init(page_t *page); page_t *get_page_for_read() const; page_t *get_page_for_write(page_cache_t *page_cache, cache_account_t *account); bool has() const { return page_ != NULL; } private: void swap_with(page_ptr_t *other); page_t *page_; DISABLE_COPYING(page_ptr_t); }; class timestamped_page_ptr_t { public: timestamped_page_ptr_t(); ~timestamped_page_ptr_t(); timestamped_page_ptr_t(timestamped_page_ptr_t &&movee); timestamped_page_ptr_t &operator=(timestamped_page_ptr_t &&movee); bool has() const; void init(repli_timestamp_t timestamp, page_t *page); page_t *get_page_for_read() const; repli_timestamp_t timestamp() const { return timestamp_; } void reset_page_ptr(page_cache_t *page_cache); private: repli_timestamp_t timestamp_; page_ptr_t page_ptr_; DISABLE_COPYING(timestamped_page_ptr_t); }; // This type's purpose is to wait for the page to be loaded, and to prevent it from // being unloaded. class page_acq_t : public intrusive_list_node_t<page_acq_t> { public: page_acq_t(); ~page_acq_t(); void init(page_t *page, page_cache_t *page_cache, cache_account_t *account); page_cache_t *page_cache() const { rassert(page_cache_ != NULL); return page_cache_; } signal_t *buf_ready_signal(); bool has() const; // These block, uninterruptibly waiting for buf_ready_signal() to be pulsed. block_size_t get_buf_size(); void *get_buf_write(block_size_t block_size); const void *get_buf_read(); private: friend class page_t; page_t *page_; page_cache_t *page_cache_; cond_t buf_ready_signal_; DISABLE_COPYING(page_acq_t); }; } // namespace alt #endif // BUFFER_CACHE_ALT_PAGE_HPP_ <commit_msg>Made comment about loader_, buf_, and block_token_ explain a bit more.<commit_after>#ifndef BUFFER_CACHE_ALT_PAGE_HPP_ #define BUFFER_CACHE_ALT_PAGE_HPP_ #include "concurrency/cond_var.hpp" #include "containers/backindex_bag.hpp" #include "repli_timestamp.hpp" #include "serializer/buf_ptr.hpp" #include "serializer/types.hpp" class cache_account_t; namespace alt { class page_cache_t; class page_acq_t; class page_loader_t; class deferred_page_loader_t; class deferred_block_token_t; // A page_t represents a page (a byte buffer of a specific size), having a definite // value known at the construction of the page_t (and possibly later modified // in-place, but still a definite known value). class page_t { public: // Defers loading the block for the given block id (but does go and get its block // token ASAP, so that we can't lose access to the current version of the block). page_t(block_id_t block_id, page_cache_t *page_cache); // Loads the block for the given block id. page_t(block_id_t block_id, page_cache_t *page_cache, cache_account_t *account); page_t(block_id_t block_id, buf_ptr_t buf, page_cache_t *page_cache); page_t(block_id_t block_id, buf_ptr_t buf, const counted_t<standard_block_token_t> &token, page_cache_t *page_cache); page_t(page_t *copyee, page_cache_t *page_cache, cache_account_t *account); ~page_t(); page_t *make_copy(page_cache_t *page_cache, cache_account_t *account); void add_waiter(page_acq_t *acq, cache_account_t *account); void remove_waiter(page_acq_t *acq); // These may not be called until the page_acq_t's buf_ready_signal is pulsed. void *get_page_buf(page_cache_t *page_cache); void reset_block_token(page_cache_t *page_cache); void set_page_buf_size(block_size_t block_size, page_cache_t *page_cache); block_size_t get_page_buf_size(); // How much memory the block would use, if it were in memory. (If the block is // already in memory, this is how much memory the block is currently // using, of course.) uint32_t hypothetical_memory_usage(page_cache_t *page_cache) const; uint64_t access_time() const { return access_time_; } bool is_loading() const { return loader_ != NULL && page_t::loader_is_loading(loader_); } bool is_deferred_loading() const { return loader_ != NULL && !page_t::loader_is_loading(loader_); } bool has_waiters() const { return !waiters_.empty(); } bool is_loaded() const { return buf_.has(); } bool is_disk_backed() const { return block_token_.has(); } void evict_self(page_cache_t *page_cache); block_id_t block_id() const { return block_id_; } bool page_ptr_count() const { return snapshot_refcount_; } const counted_t<standard_block_token_t> &block_token() const { return block_token_; } ser_buffer_t *get_loaded_ser_buffer(); void init_block_token(counted_t<standard_block_token_t> token, page_cache_t *page_cache); private: friend class page_ptr_t; friend class deferred_page_loader_t; static bool loader_is_loading(page_loader_t *loader); void add_snapshotter(); void remove_snapshotter(page_cache_t *page_cache); size_t num_snapshot_references(); void pulse_waiters_or_make_evictable(page_cache_t *page_cache); static void finish_load_with_block_id(page_t *page, page_cache_t *page_cache, counted_t<standard_block_token_t> block_token, buf_ptr_t buf); static void catch_up_with_deferred_load( deferred_page_loader_t *deferred_loader, page_cache_t *page_cache, cache_account_t *account); static void deferred_load_with_block_id(page_t *page, block_id_t block_id, page_cache_t *page_cache); static void load_with_block_id(page_t *page, block_id_t block_id, page_cache_t *page_cache, cache_account_t *account); static void load_from_copyee(page_t *page, page_t *copyee, page_cache_t *page_cache, cache_account_t *account); static void load_using_block_token(page_t *page, page_cache_t *page_cache, cache_account_t *account); friend backindex_bag_index_t *access_backindex(page_t *page); // The block id. Used to (potentially) delete the page_t and current_page_t when // it gets evicted. const block_id_t block_id_; // One of loader_, buf_, or block_token_ is non-null. (Either the page is in // memory, or there is always a way to get the page into memory.) page_loader_t *loader_; buf_ptr_t buf_; counted_t<standard_block_token_t> block_token_; uint64_t access_time_; // How many page_ptr_t's point at this page, expecting nothing to modify it, // other than themselves. size_t snapshot_refcount_; // A list of waiters that expect the value to be loaded, and (as long as there // are waiters) expect the value to never be evicted. // KSI: This could be a single pointer instead of two. intrusive_list_t<page_acq_t> waiters_; // This page_t's index into its eviction bag (managed by the page_cache_t -- one // of unevictable_pages_, etc). Which bag we should be in: // // if loader_ is non-null: unevictable_pages_ // else if waiters_ is non-empty: unevictable_pages_ // else if buf_ is null: evicted_pages_ (and block_token_ is non-null) // else if block_token_ is non-null: evictable_disk_backed_pages_ // else: evictable_unbacked_pages_ (buf_ is non-null, block_token_ is null) // // So, when loader_, waiters_, buf_, or block_token_ is touched, we might // need to change this page's eviction bag. // // The logic above is implemented in page_cache_t::correct_eviction_category. backindex_bag_index_t eviction_index_; DISABLE_COPYING(page_t); }; inline backindex_bag_index_t *access_backindex(page_t *page) { return &page->eviction_index_; } // A page_ptr_t holds a pointer to a page_t. class page_ptr_t { public: explicit page_ptr_t(page_t *page) : page_(NULL) { init(page); } page_ptr_t(); // The page_ptr_t MUST be reset before the destructor is called. ~page_ptr_t(); // You MUST manually call reset_page_ptr() to reset the page_ptr_t. Then, please // call consider_evicting_current_page if applicable. void reset_page_ptr(page_cache_t *page_cache); page_ptr_t(page_ptr_t &&movee); page_ptr_t &operator=(page_ptr_t &&movee); void init(page_t *page); page_t *get_page_for_read() const; page_t *get_page_for_write(page_cache_t *page_cache, cache_account_t *account); bool has() const { return page_ != NULL; } private: void swap_with(page_ptr_t *other); page_t *page_; DISABLE_COPYING(page_ptr_t); }; class timestamped_page_ptr_t { public: timestamped_page_ptr_t(); ~timestamped_page_ptr_t(); timestamped_page_ptr_t(timestamped_page_ptr_t &&movee); timestamped_page_ptr_t &operator=(timestamped_page_ptr_t &&movee); bool has() const; void init(repli_timestamp_t timestamp, page_t *page); page_t *get_page_for_read() const; repli_timestamp_t timestamp() const { return timestamp_; } void reset_page_ptr(page_cache_t *page_cache); private: repli_timestamp_t timestamp_; page_ptr_t page_ptr_; DISABLE_COPYING(timestamped_page_ptr_t); }; // This type's purpose is to wait for the page to be loaded, and to prevent it from // being unloaded. class page_acq_t : public intrusive_list_node_t<page_acq_t> { public: page_acq_t(); ~page_acq_t(); void init(page_t *page, page_cache_t *page_cache, cache_account_t *account); page_cache_t *page_cache() const { rassert(page_cache_ != NULL); return page_cache_; } signal_t *buf_ready_signal(); bool has() const; // These block, uninterruptibly waiting for buf_ready_signal() to be pulsed. block_size_t get_buf_size(); void *get_buf_write(block_size_t block_size); const void *get_buf_read(); private: friend class page_t; page_t *page_; page_cache_t *page_cache_; cond_t buf_ready_signal_; DISABLE_COPYING(page_acq_t); }; } // namespace alt #endif // BUFFER_CACHE_ALT_PAGE_HPP_ <|endoftext|>
<commit_before>#include "xchainer/native/im2col.h" #include <algorithm> #include <cassert> #include <cstdint> #include <vector> #include "xchainer/array.h" #include "xchainer/array_index.h" #include "xchainer/constant.h" #include "xchainer/device.h" #include "xchainer/indexable_array.h" #include "xchainer/indexer.h" #include "xchainer/macro.h" #include "xchainer/routines/connection.h" #include "xchainer/routines/creation.h" #include "xchainer/scalar.h" #include "xchainer/shape.h" #include "xchainer/slice.h" #include "xchainer/stack_vector.h" namespace xchainer { namespace native { namespace native_internal { namespace { template <typename T, int8_t kKernelNdim> void Im2ColImpl( const Array& x, const Array& out, const StackVector<int64_t, kMaxNdim>& kernel_size, const StackVector<int64_t, kMaxNdim>& stride, const StackVector<int64_t, kMaxNdim>& out_dims, const Indexer<2>& batch_channel_indexer) { static constexpr int8_t kInNdim = 2 + kKernelNdim; static constexpr int8_t kOutNdim = 2 + 2 * kKernelNdim; assert(kKernelNdim == static_cast<int8_t>(kernel_size.size())); assert(kKernelNdim == static_cast<int8_t>(stride.size())); assert(kKernelNdim == static_cast<int8_t>(out_dims.size())); assert(kInNdim == x.ndim()); assert(kOutNdim == out.ndim()); Indexer<kKernelNdim> kernel_indexer{Shape{kernel_size.begin(), kernel_size.end()}}; Indexer<kKernelNdim> out_dims_indexer{Shape{out_dims.begin(), out_dims.end()}}; Indexer<kInNdim> x_indexer{x.shape()}; Indexer<kOutNdim> out_indexer{out.shape()}; IndexableArray<const T, kInNdim> x_iarray{x}; IndexableArray<T, kOutNdim> out_iarray{out}; NdimIndex img_index{kKernelNdim}; for (auto it_batch_channel = batch_channel_indexer.It(0); it_batch_channel; ++it_batch_channel) { for (auto it_kernel = kernel_indexer.It(0); it_kernel; ++it_kernel) { for (auto it_out_dims = out_dims_indexer.It(0); it_out_dims; ++it_out_dims) { for (int i = 0; i < kKernelNdim; ++i) { img_index.index()[i] = it_out_dims.index()[i] * stride[i] + it_kernel.index()[i]; } auto it_x = x_indexer.At(it_batch_channel, img_index); auto it_out = out_indexer.At(it_batch_channel, it_kernel, it_out_dims); // Write the output column value. out_iarray[it_out] = x_iarray[it_x]; } } } } } // namespace Array Im2Col( const Array& x, const StackVector<int64_t, kMaxNdim>& kernel_size, const StackVector<int64_t, kMaxNdim>& stride, const StackVector<int64_t, kMaxNdim>& pad, bool cover_all, Scalar pad_value) { auto ndim = static_cast<int8_t>(kernel_size.size()); // Number of input image dimensions. assert(ndim == static_cast<int8_t>(stride.size())); assert(ndim == static_cast<int8_t>(pad.size())); assert(ndim + 2 == x.ndim()); // Batch and channel dimensions. Device& device = x.device(); // Create a padded copy of the input image. // TODO(hvy): Use the Pad function when implemented. Shape padded_shape = x.shape(); std::vector<ArrayIndex> unpadded_slice{ArrayIndex{Slice{}}, ArrayIndex{Slice{}}}; // All batch and channel dimensions. for (int64_t i = 0; i < ndim; ++i) { padded_shape[i + 2] += pad[i] * 2 + (cover_all ? stride[i] - 1 : 0); // Pad on both sides. unpadded_slice.emplace_back(Slice{pad[i], pad[i] + x.shape()[i + 2]}); } Array padded_x = static_cast<int64_t>(pad_value) == int64_t{0} ? Zeros(padded_shape, x.dtype(), device) : Full(padded_shape, pad_value, x.dtype(), device); device.Copy(x, padded_x.At(unpadded_slice)); assert(ndim + 2 == padded_x.ndim()); // Create the output array. StackVector<int64_t, kMaxNdim> out_dims; // Number of patches along each axis for (int8_t i = 0; i < ndim; ++i) { out_dims.emplace_back(internal::GetConvOutDim(x.shape()[i + 2], kernel_size[i], stride[i], pad[i], cover_all)); assert(out_dims.back() > 0); } assert(ndim == static_cast<int8_t>(out_dims.size())); int64_t batch_size = x.shape()[0]; int64_t channels = x.shape()[1]; Shape out_shape{batch_size, channels}; std::copy(kernel_size.begin(), kernel_size.end(), std::back_inserter(out_shape)); std::copy(out_dims.begin(), out_dims.end(), std::back_inserter(out_shape)); Array out = Empty(out_shape, x.dtype(), device); assert(ndim * 2 + 2 == out.ndim()); // Write to the output array. VisitDtype(x.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; Indexer<2> batch_channel_indexer{Shape{batch_size, channels}}; switch (ndim) { case 0: Im2ColImpl<T, 0>(padded_x, out, kernel_size, stride, out_dims, batch_channel_indexer); break; case 1: Im2ColImpl<T, 1>(padded_x, out, kernel_size, stride, out_dims, batch_channel_indexer); break; case 2: Im2ColImpl<T, 2>(padded_x, out, kernel_size, stride, out_dims, batch_channel_indexer); break; case 3: Im2ColImpl<T, 3>(padded_x, out, kernel_size, stride, out_dims, batch_channel_indexer); break; case 4: Im2ColImpl<T, 4>(padded_x, out, kernel_size, stride, out_dims, batch_channel_indexer); break; default: static_assert(kMaxNdim == 10, "kMaxNdim equals to 10"); XCHAINER_NEVER_REACH(); // Never out.ndim() > kMaxNdim break; } }); return out; } } // namespace native_internal } // namespace native } // namespace xchainer <commit_msg>elaborate static_assert message<commit_after>#include "xchainer/native/im2col.h" #include <algorithm> #include <cassert> #include <cstdint> #include <vector> #include "xchainer/array.h" #include "xchainer/array_index.h" #include "xchainer/constant.h" #include "xchainer/device.h" #include "xchainer/indexable_array.h" #include "xchainer/indexer.h" #include "xchainer/macro.h" #include "xchainer/routines/connection.h" #include "xchainer/routines/creation.h" #include "xchainer/scalar.h" #include "xchainer/shape.h" #include "xchainer/slice.h" #include "xchainer/stack_vector.h" namespace xchainer { namespace native { namespace native_internal { namespace { template <typename T, int8_t kKernelNdim> void Im2ColImpl( const Array& x, const Array& out, const StackVector<int64_t, kMaxNdim>& kernel_size, const StackVector<int64_t, kMaxNdim>& stride, const StackVector<int64_t, kMaxNdim>& out_dims, const Indexer<2>& batch_channel_indexer) { static constexpr int8_t kInNdim = 2 + kKernelNdim; static constexpr int8_t kOutNdim = 2 + 2 * kKernelNdim; assert(kKernelNdim == static_cast<int8_t>(kernel_size.size())); assert(kKernelNdim == static_cast<int8_t>(stride.size())); assert(kKernelNdim == static_cast<int8_t>(out_dims.size())); assert(kInNdim == x.ndim()); assert(kOutNdim == out.ndim()); Indexer<kKernelNdim> kernel_indexer{Shape{kernel_size.begin(), kernel_size.end()}}; Indexer<kKernelNdim> out_dims_indexer{Shape{out_dims.begin(), out_dims.end()}}; Indexer<kInNdim> x_indexer{x.shape()}; Indexer<kOutNdim> out_indexer{out.shape()}; IndexableArray<const T, kInNdim> x_iarray{x}; IndexableArray<T, kOutNdim> out_iarray{out}; NdimIndex img_index{kKernelNdim}; for (auto it_batch_channel = batch_channel_indexer.It(0); it_batch_channel; ++it_batch_channel) { for (auto it_kernel = kernel_indexer.It(0); it_kernel; ++it_kernel) { for (auto it_out_dims = out_dims_indexer.It(0); it_out_dims; ++it_out_dims) { for (int i = 0; i < kKernelNdim; ++i) { img_index.index()[i] = it_out_dims.index()[i] * stride[i] + it_kernel.index()[i]; } auto it_x = x_indexer.At(it_batch_channel, img_index); auto it_out = out_indexer.At(it_batch_channel, it_kernel, it_out_dims); // Write the output column value. out_iarray[it_out] = x_iarray[it_x]; } } } } } // namespace Array Im2Col( const Array& x, const StackVector<int64_t, kMaxNdim>& kernel_size, const StackVector<int64_t, kMaxNdim>& stride, const StackVector<int64_t, kMaxNdim>& pad, bool cover_all, Scalar pad_value) { auto ndim = static_cast<int8_t>(kernel_size.size()); // Number of input image dimensions. assert(ndim == static_cast<int8_t>(stride.size())); assert(ndim == static_cast<int8_t>(pad.size())); assert(ndim + 2 == x.ndim()); // Batch and channel dimensions. Device& device = x.device(); // Create a padded copy of the input image. // TODO(hvy): Use the Pad function when implemented. Shape padded_shape = x.shape(); std::vector<ArrayIndex> unpadded_slice{ArrayIndex{Slice{}}, ArrayIndex{Slice{}}}; // All batch and channel dimensions. for (int64_t i = 0; i < ndim; ++i) { padded_shape[i + 2] += pad[i] * 2 + (cover_all ? stride[i] - 1 : 0); // Pad on both sides. unpadded_slice.emplace_back(Slice{pad[i], pad[i] + x.shape()[i + 2]}); } Array padded_x = static_cast<int64_t>(pad_value) == int64_t{0} ? Zeros(padded_shape, x.dtype(), device) : Full(padded_shape, pad_value, x.dtype(), device); device.Copy(x, padded_x.At(unpadded_slice)); assert(ndim + 2 == padded_x.ndim()); // Create the output array. StackVector<int64_t, kMaxNdim> out_dims; // Number of patches along each axis for (int8_t i = 0; i < ndim; ++i) { out_dims.emplace_back(internal::GetConvOutDim(x.shape()[i + 2], kernel_size[i], stride[i], pad[i], cover_all)); assert(out_dims.back() > 0); } assert(ndim == static_cast<int8_t>(out_dims.size())); int64_t batch_size = x.shape()[0]; int64_t channels = x.shape()[1]; Shape out_shape{batch_size, channels}; std::copy(kernel_size.begin(), kernel_size.end(), std::back_inserter(out_shape)); std::copy(out_dims.begin(), out_dims.end(), std::back_inserter(out_shape)); Array out = Empty(out_shape, x.dtype(), device); assert(ndim * 2 + 2 == out.ndim()); // Write to the output array. VisitDtype(x.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; Indexer<2> batch_channel_indexer{Shape{batch_size, channels}}; static_assert(4 * 2 + 2 == kMaxNdim, "4 is the maximum kernel ndim whose output ndim does not exceed kMaxNdim"); switch (ndim) { case 0: Im2ColImpl<T, 0>(padded_x, out, kernel_size, stride, out_dims, batch_channel_indexer); break; case 1: Im2ColImpl<T, 1>(padded_x, out, kernel_size, stride, out_dims, batch_channel_indexer); break; case 2: Im2ColImpl<T, 2>(padded_x, out, kernel_size, stride, out_dims, batch_channel_indexer); break; case 3: Im2ColImpl<T, 3>(padded_x, out, kernel_size, stride, out_dims, batch_channel_indexer); break; case 4: Im2ColImpl<T, 4>(padded_x, out, kernel_size, stride, out_dims, batch_channel_indexer); break; default: XCHAINER_NEVER_REACH(); // Never out.ndim() > kMaxNdim break; } }); return out; } } // namespace native_internal } // namespace native } // namespace xchainer <|endoftext|>
<commit_before>/* * Copyright © 2012 Intel Corporation * * 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 (including the next * paragraph) 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 "brw_fs.h" #include "brw_cfg.h" namespace { /* avoid conflict with opt_copy_propagation_elements */ struct acp_entry : public exec_node { fs_reg dst; fs_reg src; }; } bool fs_visitor::try_copy_propagate(fs_inst *inst, int arg, acp_entry *entry) { if (entry->src.file == IMM) return false; if (inst->src[arg].file != entry->dst.file || inst->src[arg].reg != entry->dst.reg || inst->src[arg].reg_offset != entry->dst.reg_offset) { return false; } /* See resolve_ud_negate() and comment in brw_fs_emit.cpp. */ if (inst->conditional_mod && inst->src[arg].type == BRW_REGISTER_TYPE_UD && entry->src.negate) return false; bool has_source_modifiers = entry->src.abs || entry->src.negate; if (intel->gen == 6 && inst->is_math() && (has_source_modifiers || entry->src.file == UNIFORM || entry->src.smear != -1)) return false; inst->src[arg].file = entry->src.file; inst->src[arg].reg = entry->src.reg; inst->src[arg].reg_offset = entry->src.reg_offset; inst->src[arg].smear = entry->src.smear; if (!inst->src[arg].abs) { inst->src[arg].abs = entry->src.abs; inst->src[arg].negate ^= entry->src.negate; } return true; } bool fs_visitor::try_constant_propagate(fs_inst *inst, acp_entry *entry) { bool progress = false; if (entry->src.file != IMM) return false; for (int i = 2; i >= 0; i--) { if (inst->src[i].file != entry->dst.file || inst->src[i].reg != entry->dst.reg || inst->src[i].reg_offset != entry->dst.reg_offset) continue; /* Don't bother with cases that should have been taken care of by the * GLSL compiler's constant folding pass. */ if (inst->src[i].negate || inst->src[i].abs) continue; switch (inst->opcode) { case BRW_OPCODE_MOV: inst->src[i] = entry->src; progress = true; break; case BRW_OPCODE_MUL: case BRW_OPCODE_ADD: if (i == 1) { inst->src[i] = entry->src; progress = true; } else if (i == 0 && inst->src[1].file != IMM) { /* Fit this constant in by commuting the operands. * Exception: we can't do this for 32-bit integer MUL * because it's asymmetric. */ if (inst->opcode == BRW_OPCODE_MUL && (inst->src[1].type == BRW_REGISTER_TYPE_D || inst->src[1].type == BRW_REGISTER_TYPE_UD)) break; inst->src[0] = inst->src[1]; inst->src[1] = entry->src; progress = true; } break; case BRW_OPCODE_CMP: case BRW_OPCODE_IF: if (i == 1) { inst->src[i] = entry->src; progress = true; } else if (i == 0 && inst->src[1].file != IMM) { uint32_t new_cmod; new_cmod = brw_swap_cmod(inst->conditional_mod); if (new_cmod != ~0u) { /* Fit this constant in by swapping the operands and * flipping the test */ inst->src[0] = inst->src[1]; inst->src[1] = entry->src; inst->conditional_mod = new_cmod; progress = true; } } break; case BRW_OPCODE_SEL: if (i == 1) { inst->src[i] = entry->src; progress = true; } else if (i == 0 && inst->src[1].file != IMM) { inst->src[0] = inst->src[1]; inst->src[1] = entry->src; /* If this was predicated, flipping operands means * we also need to flip the predicate. */ if (inst->conditional_mod == BRW_CONDITIONAL_NONE) { inst->predicate_inverse = !inst->predicate_inverse; } progress = true; } break; case SHADER_OPCODE_RCP: /* The hardware doesn't do math on immediate values * (because why are you doing that, seriously?), but * the correct answer is to just constant fold it * anyway. */ assert(i == 0); if (inst->src[0].imm.f != 0.0f) { inst->opcode = BRW_OPCODE_MOV; inst->src[0] = entry->src; inst->src[0].imm.f = 1.0f / inst->src[0].imm.f; progress = true; } break; case FS_OPCODE_PULL_CONSTANT_LOAD: inst->src[i] = entry->src; progress = true; break; default: break; } } return progress; } /** @file brw_fs_copy_propagation.cpp * * Support for local copy propagation by walking the list of instructions * and maintaining the ACP table of available copies for propagation. * * See Muchnik's Advanced Compiler Design and Implementation, section * 12.5 (p356). */ /* Walks a basic block and does copy propagation on it using the acp * list. */ bool fs_visitor::opt_copy_propagate_local(void *mem_ctx, bblock_t *block) { bool progress = false; int acp_count = 16; exec_list acp[acp_count]; for (fs_inst *inst = (fs_inst *)block->start; inst != block->end->next; inst = (fs_inst *)inst->next) { /* Try propagating into this instruction. */ for (int i = 0; i < 3; i++) { if (inst->src[i].file != GRF) continue; foreach_list(entry_node, &acp[inst->src[i].reg % acp_count]) { acp_entry *entry = (acp_entry *)entry_node; if (try_constant_propagate(inst, entry)) progress = true; if (try_copy_propagate(inst, i, entry)) progress = true; } } /* kill the destination from the ACP */ if (inst->dst.file == GRF) { foreach_list_safe(entry_node, &acp[inst->dst.reg % acp_count]) { acp_entry *entry = (acp_entry *)entry_node; if (inst->overwrites_reg(entry->dst)) { entry->remove(); } } /* Oops, we only have the chaining hash based on the destination, not * the source, so walk across the entire table. */ for (int i = 0; i < acp_count; i++) { foreach_list_safe(entry_node, &acp[i]) { acp_entry *entry = (acp_entry *)entry_node; if (inst->overwrites_reg(entry->src)) entry->remove(); } } } /* If this instruction is a raw copy, add it to the ACP. */ if (inst->opcode == BRW_OPCODE_MOV && inst->dst.file == GRF && ((inst->src[0].file == GRF && (inst->src[0].reg != inst->dst.reg || inst->src[0].reg_offset != inst->dst.reg_offset)) || inst->src[0].file == UNIFORM || inst->src[0].file == IMM) && inst->src[0].type == inst->dst.type && !inst->saturate && !inst->predicate && !inst->force_uncompressed && !inst->force_sechalf) { acp_entry *entry = ralloc(mem_ctx, acp_entry); entry->dst = inst->dst; entry->src = inst->src[0]; acp[entry->dst.reg % acp_count].push_tail(entry); } } return progress; } bool fs_visitor::opt_copy_propagate() { bool progress = false; void *mem_ctx = ralloc_context(this->mem_ctx); cfg_t cfg(this); for (int b = 0; b < cfg.num_blocks; b++) { bblock_t *block = cfg.blocks[b]; progress = opt_copy_propagate_local(mem_ctx, block) || progress; } ralloc_free(mem_ctx); if (progress) live_intervals_valid = false; return progress; } <commit_msg>i965/fs: Fix a comment in copy propagation.<commit_after>/* * Copyright © 2012 Intel Corporation * * 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 (including the next * paragraph) 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 "brw_fs.h" #include "brw_cfg.h" namespace { /* avoid conflict with opt_copy_propagation_elements */ struct acp_entry : public exec_node { fs_reg dst; fs_reg src; }; } bool fs_visitor::try_copy_propagate(fs_inst *inst, int arg, acp_entry *entry) { if (entry->src.file == IMM) return false; if (inst->src[arg].file != entry->dst.file || inst->src[arg].reg != entry->dst.reg || inst->src[arg].reg_offset != entry->dst.reg_offset) { return false; } /* See resolve_ud_negate() and comment in brw_fs_emit.cpp. */ if (inst->conditional_mod && inst->src[arg].type == BRW_REGISTER_TYPE_UD && entry->src.negate) return false; bool has_source_modifiers = entry->src.abs || entry->src.negate; if (intel->gen == 6 && inst->is_math() && (has_source_modifiers || entry->src.file == UNIFORM || entry->src.smear != -1)) return false; inst->src[arg].file = entry->src.file; inst->src[arg].reg = entry->src.reg; inst->src[arg].reg_offset = entry->src.reg_offset; inst->src[arg].smear = entry->src.smear; if (!inst->src[arg].abs) { inst->src[arg].abs = entry->src.abs; inst->src[arg].negate ^= entry->src.negate; } return true; } bool fs_visitor::try_constant_propagate(fs_inst *inst, acp_entry *entry) { bool progress = false; if (entry->src.file != IMM) return false; for (int i = 2; i >= 0; i--) { if (inst->src[i].file != entry->dst.file || inst->src[i].reg != entry->dst.reg || inst->src[i].reg_offset != entry->dst.reg_offset) continue; /* Don't bother with cases that should have been taken care of by the * GLSL compiler's constant folding pass. */ if (inst->src[i].negate || inst->src[i].abs) continue; switch (inst->opcode) { case BRW_OPCODE_MOV: inst->src[i] = entry->src; progress = true; break; case BRW_OPCODE_MUL: case BRW_OPCODE_ADD: if (i == 1) { inst->src[i] = entry->src; progress = true; } else if (i == 0 && inst->src[1].file != IMM) { /* Fit this constant in by commuting the operands. * Exception: we can't do this for 32-bit integer MUL * because it's asymmetric. */ if (inst->opcode == BRW_OPCODE_MUL && (inst->src[1].type == BRW_REGISTER_TYPE_D || inst->src[1].type == BRW_REGISTER_TYPE_UD)) break; inst->src[0] = inst->src[1]; inst->src[1] = entry->src; progress = true; } break; case BRW_OPCODE_CMP: case BRW_OPCODE_IF: if (i == 1) { inst->src[i] = entry->src; progress = true; } else if (i == 0 && inst->src[1].file != IMM) { uint32_t new_cmod; new_cmod = brw_swap_cmod(inst->conditional_mod); if (new_cmod != ~0u) { /* Fit this constant in by swapping the operands and * flipping the test */ inst->src[0] = inst->src[1]; inst->src[1] = entry->src; inst->conditional_mod = new_cmod; progress = true; } } break; case BRW_OPCODE_SEL: if (i == 1) { inst->src[i] = entry->src; progress = true; } else if (i == 0 && inst->src[1].file != IMM) { inst->src[0] = inst->src[1]; inst->src[1] = entry->src; /* If this was predicated, flipping operands means * we also need to flip the predicate. */ if (inst->conditional_mod == BRW_CONDITIONAL_NONE) { inst->predicate_inverse = !inst->predicate_inverse; } progress = true; } break; case SHADER_OPCODE_RCP: /* The hardware doesn't do math on immediate values * (because why are you doing that, seriously?), but * the correct answer is to just constant fold it * anyway. */ assert(i == 0); if (inst->src[0].imm.f != 0.0f) { inst->opcode = BRW_OPCODE_MOV; inst->src[0] = entry->src; inst->src[0].imm.f = 1.0f / inst->src[0].imm.f; progress = true; } break; case FS_OPCODE_PULL_CONSTANT_LOAD: inst->src[i] = entry->src; progress = true; break; default: break; } } return progress; } /** @file brw_fs_copy_propagation.cpp * * Support for local copy propagation by walking the list of instructions * and maintaining the ACP table of available copies for propagation. * * See Muchnik's Advanced Compiler Design and Implementation, section * 12.5 (p356). */ /* Walks a basic block and does copy propagation on it using the acp * list. */ bool fs_visitor::opt_copy_propagate_local(void *mem_ctx, bblock_t *block) { bool progress = false; int acp_count = 16; exec_list acp[acp_count]; for (fs_inst *inst = (fs_inst *)block->start; inst != block->end->next; inst = (fs_inst *)inst->next) { /* Try propagating into this instruction. */ for (int i = 0; i < 3; i++) { if (inst->src[i].file != GRF) continue; foreach_list(entry_node, &acp[inst->src[i].reg % acp_count]) { acp_entry *entry = (acp_entry *)entry_node; if (try_constant_propagate(inst, entry)) progress = true; if (try_copy_propagate(inst, i, entry)) progress = true; } } /* kill the destination from the ACP */ if (inst->dst.file == GRF) { foreach_list_safe(entry_node, &acp[inst->dst.reg % acp_count]) { acp_entry *entry = (acp_entry *)entry_node; if (inst->overwrites_reg(entry->dst)) { entry->remove(); } } /* Oops, we only have the chaining hash based on the destination, not * the source, so walk across the entire table. */ for (int i = 0; i < acp_count; i++) { foreach_list_safe(entry_node, &acp[i]) { acp_entry *entry = (acp_entry *)entry_node; if (inst->overwrites_reg(entry->src)) entry->remove(); } } } /* If this instruction's source could potentially be folded into the * operand of another instruction, add it to the ACP. */ if (inst->opcode == BRW_OPCODE_MOV && inst->dst.file == GRF && ((inst->src[0].file == GRF && (inst->src[0].reg != inst->dst.reg || inst->src[0].reg_offset != inst->dst.reg_offset)) || inst->src[0].file == UNIFORM || inst->src[0].file == IMM) && inst->src[0].type == inst->dst.type && !inst->saturate && !inst->predicate && !inst->force_uncompressed && !inst->force_sechalf) { acp_entry *entry = ralloc(mem_ctx, acp_entry); entry->dst = inst->dst; entry->src = inst->src[0]; acp[entry->dst.reg % acp_count].push_tail(entry); } } return progress; } bool fs_visitor::opt_copy_propagate() { bool progress = false; void *mem_ctx = ralloc_context(this->mem_ctx); cfg_t cfg(this); for (int b = 0; b < cfg.num_blocks; b++) { bblock_t *block = cfg.blocks[b]; progress = opt_copy_propagate_local(mem_ctx, block) || progress; } ralloc_free(mem_ctx); if (progress) live_intervals_valid = false; return progress; } <|endoftext|>
<commit_before>#include "xchainer/python/device.h" #include <memory> #include <sstream> #include "xchainer/backend.h" #include "xchainer/device.h" #include "xchainer/python/common.h" namespace xchainer { namespace py = pybind11; // standard convention class PyDeviceScope { public: explicit PyDeviceScope(Device target) : target_(target) {} void Enter() { scope_ = std::make_unique<DeviceScope>(target_); } void Exit(py::args args) { (void)args; // unused scope_.reset(); } private: // TODO(beam2d): better to replace it by "optional"... std::unique_ptr<DeviceScope> scope_; Device target_; }; void InitXchainerDevice(pybind11::module& m) { py::class_<Device>(m, "Device") .def(py::init<const std::string&, Backend*>()) .def("__eq__", py::overload_cast<const Device&, const Device&>(&operator==)) .def("__ne__", py::overload_cast<const Device&, const Device&>(&operator!=)) .def("__repr__", &Device::ToString) .def_property_readonly("name", &Device::name) .def_property_readonly("backend", &Device::backend); m.def("get_current_device", []() { return GetCurrentDevice(); }); m.def("set_current_device", [](const Device& device) { SetCurrentDevice(device); }); py::class_<PyDeviceScope>(m, "DeviceScope").def("__enter__", &PyDeviceScope::Enter).def("__exit__", &PyDeviceScope::Exit); m.def("device_scope", [](Device device) { return PyDeviceScope(device); }); } } // namespace xchainer <commit_msg>Fix backend object lifetime<commit_after>#include "xchainer/python/device.h" #include <memory> #include <sstream> #include "xchainer/backend.h" #include "xchainer/device.h" #include "xchainer/python/common.h" namespace xchainer { namespace py = pybind11; // standard convention class PyDeviceScope { public: explicit PyDeviceScope(Device target) : target_(target) {} void Enter() { scope_ = std::make_unique<DeviceScope>(target_); } void Exit(py::args args) { (void)args; // unused scope_.reset(); } private: // TODO(beam2d): better to replace it by "optional"... std::unique_ptr<DeviceScope> scope_; Device target_; }; void InitXchainerDevice(pybind11::module& m) { py::class_<Device>(m, "Device") .def(py::init<const std::string&, Backend*>(), py::keep_alive<1, 3>()) .def("__eq__", py::overload_cast<const Device&, const Device&>(&operator==)) .def("__ne__", py::overload_cast<const Device&, const Device&>(&operator!=)) .def("__repr__", &Device::ToString) .def_property_readonly("name", &Device::name) .def_property_readonly("backend", &Device::backend); m.def("get_current_device", []() { return GetCurrentDevice(); }); m.def("set_current_device", [](const Device& device) { SetCurrentDevice(device); }); py::class_<PyDeviceScope>(m, "DeviceScope").def("__enter__", &PyDeviceScope::Enter).def("__exit__", &PyDeviceScope::Exit); m.def("device_scope", [](Device device) { return PyDeviceScope(device); }); } } // namespace xchainer <|endoftext|>
<commit_before>#include <doctest.h> #include <algorithm> #include <cctype> #include <iterator> #include <mirrage/utils/random_uuid_generator.hpp> #include <sstream> #include <vector> TEST_CASE("A large number of ids generated by a random_uuid_generator does contain no duplicates.") { mirrage::util::random_uuid_generator gen; std::vector<decltype(gen)::id_type> ids; std::generate_n(std::back_inserter(ids), 1 << 15, [&]() { return gen.generate_id(); }); std::sort(ids.begin(), ids.end()); CHECK(std::adjacent_find(ids.begin(), ids.end()) == ids.end()); } TEST_CASE( "A large number of ids generated by two different random_uuid_generators does contain no duplicates.") { mirrage::util::random_uuid_generator gen1; decltype(gen1) gen2; std::vector<decltype(gen1)::id_type> ids; std::generate_n(std::back_inserter(ids), 1 << 14, [&]() { return gen1.generate_id(); }); std::generate_n(std::back_inserter(ids), 1 << 14, [&]() { return gen2.generate_id(); }); std::sort(ids.begin(), ids.end()); CHECK(std::adjacent_find(ids.begin(), ids.end()) == ids.end()); } TEST_CASE("A copy of an random_uuid_generator produces the same ids.") { mirrage::util::random_uuid_generator gen1; auto gen2 = gen1; std::vector<decltype(gen1)::id_type> ids1; std::vector<decltype(gen1)::id_type> ids2; std::generate_n(std::back_inserter(ids1), 1 << 14, [&]() { return gen1.generate_id(); }); std::generate_n(std::back_inserter(ids2), 1 << 14, [&]() { return gen2.generate_id(); }); CHECK(std::equal(ids1.begin(), ids1.end(), ids2.begin(), ids2.end())); } TEST_CASE("An id generated by a random_uuid_generator has the expected format.") { mirrage::util::random_uuid_generator gen; auto id = gen.generate_id(); auto var = id.variant(); auto ver = id.version(); CHECK(var == 0b10); CHECK(ver == 4); std::stringstream outstr; outstr << id; auto str = outstr.str(); std::size_t index = 0; auto check_hex_block = [&str, &index](std::size_t bs) { for(std::size_t i = 0; i < bs; ++i, ++index) { CHECK(std::isxdigit(str.at(index))); } }; check_hex_block(8); CHECK(str.at(index++) == '-'); check_hex_block(4); CHECK(str.at(index++) == '-'); check_hex_block(4); CHECK(str.at(index++) == '-'); check_hex_block(4); CHECK(str.at(index++) == '-'); check_hex_block(12); } <commit_msg>workaround for weird clang-format edge-case<commit_after>#include <mirrage/utils/random_uuid_generator.hpp> #include <doctest.h> #include <algorithm> #include <cctype> #include <iterator> #include <sstream> #include <vector> TEST_CASE("A large number of ids generated by a random_uuid_generator does contain no duplicates.") { mirrage::util::random_uuid_generator gen; std::vector<decltype(gen)::id_type> ids; std::generate_n(std::back_inserter(ids), 1 << 15, [&]() { return gen.generate_id(); }); std::sort(ids.begin(), ids.end()); CHECK(std::adjacent_find(ids.begin(), ids.end()) == ids.end()); } TEST_CASE( "A large number of ids generated by two different random_uuid_generators does contain no duplicates.") { mirrage::util::random_uuid_generator gen1; decltype(gen1) gen2; std::vector<decltype(gen1)::id_type> ids; std::generate_n(std::back_inserter(ids), 1 << 14, [&]() { return gen1.generate_id(); }); std::generate_n(std::back_inserter(ids), 1 << 14, [&]() { return gen2.generate_id(); }); std::sort(ids.begin(), ids.end()); CHECK(std::adjacent_find(ids.begin(), ids.end()) == ids.end()); } TEST_CASE("A copy of an random_uuid_generator produces the same ids.") { mirrage::util::random_uuid_generator gen1; auto gen2 = gen1; std::vector<decltype(gen1)::id_type> ids1; std::vector<decltype(gen1)::id_type> ids2; std::generate_n(std::back_inserter(ids1), 1 << 14, [&]() { return gen1.generate_id(); }); std::generate_n(std::back_inserter(ids2), 1 << 14, [&]() { return gen2.generate_id(); }); CHECK(std::equal(ids1.begin(), ids1.end(), ids2.begin(), ids2.end())); } TEST_CASE("An id generated by a random_uuid_generator has the expected format.") { mirrage::util::random_uuid_generator gen; auto id = gen.generate_id(); auto var = id.variant(); auto ver = id.version(); CHECK(var == 0b10); CHECK(ver == 4); std::stringstream outstr; outstr << id; auto str = outstr.str(); std::size_t index = 0; auto check_hex_block = [&str, &index](std::size_t bs) { for(std::size_t i = 0; i < bs; ++i, ++index) { CHECK(std::isxdigit(str.at(index))); } }; check_hex_block(8); CHECK(str.at(index++) == '-'); check_hex_block(4); CHECK(str.at(index++) == '-'); check_hex_block(4); CHECK(str.at(index++) == '-'); check_hex_block(4); CHECK(str.at(index++) == '-'); check_hex_block(12); } <|endoftext|>
<commit_before>#include "miniz/miniz.h" #include "Zip/ZipArchive.hpp" namespace Slic3r { ZipArchive::ZipArchive (std::string zip_archive_name, char zip_mode) : archive(mz_zip_archive()), zip_name(zip_archive_name), mode(zip_mode), stats(0), finalized(false) { // Initialize the miniz zip archive struct. memset(&archive, 0, sizeof(archive)); if( mode == 'W'){ stats = mz_zip_writer_init_file(&archive, zip_name.c_str(), 0); } else if (mode == 'R') { stats = mz_zip_reader_init_file(&archive, zip_name.c_str(), 0); } else { std::cout << "Error:: Unknown zip mode" << std::endl; } } mz_bool ZipArchive::z_stats() { return stats; } mz_bool ZipArchive::add_entry (std::string entry_path, std::string file_path) { stats = 0; // Check if it's in the write mode. if(mode != 'W') return stats; stats = mz_zip_writer_add_file(&archive, entry_path.c_str(), file_path.c_str(), nullptr, 0, ZIP_DEFLATE_COMPRESSION); return stats; } mz_bool ZipArchive::extract_entry (std::string entry_path, std::string file_path) { stats = 0; // Check if it's in the read mode. if (mode != 'R') return stats; stats = mz_zip_reader_extract_file_to_file(&archive, entry_path.c_str(), file_path.c_str(), 0); return stats; } mz_bool ZipArchive::finalize() { stats = 0; // Finalize the archive and end writing if it's in the write mode. if(mode == 'W') { stats = mz_zip_writer_finalize_archive(&archive); stats |= mz_zip_writer_end(&archive); } else if (mode == 'R'){ stats = mz_zip_reader_end(&archive); } if(stats) finalized = true; return stats; } ZipArchive::~ZipArchive() { if(!finalized) this->finalize(); } } <commit_msg>Fix duplicate symbols caused by double invocation of miniz.h<commit_after>#include "Zip/ZipArchive.hpp" namespace Slic3r { ZipArchive::ZipArchive (std::string zip_archive_name, char zip_mode) : archive(mz_zip_archive()), zip_name(zip_archive_name), mode(zip_mode), stats(0), finalized(false) { // Initialize the miniz zip archive struct. memset(&archive, 0, sizeof(archive)); if( mode == 'W'){ stats = mz_zip_writer_init_file(&archive, zip_name.c_str(), 0); } else if (mode == 'R') { stats = mz_zip_reader_init_file(&archive, zip_name.c_str(), 0); } else { std::cout << "Error:: Unknown zip mode" << std::endl; } } mz_bool ZipArchive::z_stats() { return stats; } mz_bool ZipArchive::add_entry (std::string entry_path, std::string file_path) { stats = 0; // Check if it's in the write mode. if(mode != 'W') return stats; stats = mz_zip_writer_add_file(&archive, entry_path.c_str(), file_path.c_str(), nullptr, 0, ZIP_DEFLATE_COMPRESSION); return stats; } mz_bool ZipArchive::extract_entry (std::string entry_path, std::string file_path) { stats = 0; // Check if it's in the read mode. if (mode != 'R') return stats; stats = mz_zip_reader_extract_file_to_file(&archive, entry_path.c_str(), file_path.c_str(), 0); return stats; } mz_bool ZipArchive::finalize() { stats = 0; // Finalize the archive and end writing if it's in the write mode. if(mode == 'W') { stats = mz_zip_writer_finalize_archive(&archive); stats |= mz_zip_writer_end(&archive); } else if (mode == 'R'){ stats = mz_zip_reader_end(&archive); } if(stats) finalized = true; return stats; } ZipArchive::~ZipArchive() { if(!finalized) this->finalize(); } } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2013-2016 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file MulticopterLandDetector.cpp * * @author Johan Jansen <[email protected]> * @author Morten Lysgaard <[email protected]> * @author Julian Oes <[email protected]> */ #include <cmath> #include <drivers/drv_hrt.h> #include <mathlib/mathlib.h> #include "MulticopterLandDetector.h" namespace land_detector { MulticopterLandDetector::MulticopterLandDetector() : LandDetector(), _paramHandle(), _params(), _vehicleLocalPositionSub(-1), _actuatorsSub(-1), _armingSub(-1), _attitudeSub(-1), _manualSub(-1), _ctrl_state_sub(-1), _vehicle_control_mode_sub(-1), _battery_sub(-1), _vehicleLocalPosition{}, _actuators{}, _arming{}, _vehicleAttitude{}, _manual{}, _ctrl_state{}, _control_mode{}, _battery{}, _min_trust_start(0), _arming_time(0) { _paramHandle.maxRotation = param_find("LNDMC_ROT_MAX"); _paramHandle.maxVelocity = param_find("LNDMC_XY_VEL_MAX"); _paramHandle.maxClimbRate = param_find("LNDMC_Z_VEL_MAX"); _paramHandle.throttleRange = param_find("LNDMC_THR_RANGE"); _paramHandle.minThrottle = param_find("MPC_THR_MIN"); _paramHandle.hoverThrottle = param_find("MPC_THR_HOVER"); _paramHandle.minManThrottle = param_find("MPC_MANTHR_MIN"); _paramHandle.freefall_acc_threshold = param_find("LNDMC_FFALL_THR"); _paramHandle.freefall_trigger_time = param_find("LNDMC_FFALL_TTRI"); _paramHandle.manual_stick_down_threshold = param_find("LNDMC_MAN_DWNTHR"); _paramHandle.altitude_max = param_find("LNDMC_ALT_MAX"); _paramHandle.manual_stick_up_position_takeoff_threshold = param_find("LNDMC_POS_UPTHR"); } void MulticopterLandDetector::_initialize_topics() { // subscribe to position, attitude, arming and velocity changes _vehicleLocalPositionSub = orb_subscribe(ORB_ID(vehicle_local_position)); _attitudeSub = orb_subscribe(ORB_ID(vehicle_attitude)); _actuatorsSub = orb_subscribe(ORB_ID(actuator_controls_0)); _armingSub = orb_subscribe(ORB_ID(actuator_armed)); _parameterSub = orb_subscribe(ORB_ID(parameter_update)); _manualSub = orb_subscribe(ORB_ID(manual_control_setpoint)); _ctrl_state_sub = orb_subscribe(ORB_ID(control_state)); _vehicle_control_mode_sub = orb_subscribe(ORB_ID(vehicle_control_mode)); _battery_sub = orb_subscribe(ORB_ID(battery_status)); } void MulticopterLandDetector::_update_topics() { _orb_update(ORB_ID(vehicle_local_position), _vehicleLocalPositionSub, &_vehicleLocalPosition); _orb_update(ORB_ID(vehicle_attitude), _attitudeSub, &_vehicleAttitude); _orb_update(ORB_ID(actuator_controls_0), _actuatorsSub, &_actuators); _orb_update(ORB_ID(actuator_armed), _armingSub, &_arming); _orb_update(ORB_ID(manual_control_setpoint), _manualSub, &_manual); _orb_update(ORB_ID(control_state), _ctrl_state_sub, &_ctrl_state); _orb_update(ORB_ID(vehicle_control_mode), _vehicle_control_mode_sub, &_control_mode); _orb_update(ORB_ID(battery_status), _battery_sub, &_battery); } void MulticopterLandDetector::_update_params() { param_get(_paramHandle.maxClimbRate, &_params.maxClimbRate); param_get(_paramHandle.maxVelocity, &_params.maxVelocity); param_get(_paramHandle.maxRotation, &_params.maxRotation_rad_s); _params.maxRotation_rad_s = math::radians(_params.maxRotation_rad_s); param_get(_paramHandle.minThrottle, &_params.minThrottle); param_get(_paramHandle.hoverThrottle, &_params.hoverThrottle); param_get(_paramHandle.throttleRange, &_params.throttleRange); param_get(_paramHandle.minManThrottle, &_params.minManThrottle); param_get(_paramHandle.freefall_acc_threshold, &_params.freefall_acc_threshold); param_get(_paramHandle.freefall_trigger_time, &_params.freefall_trigger_time); _freefall_hysteresis.set_hysteresis_time_from(false, (hrt_abstime)(1e6f * _params.freefall_trigger_time)); param_get(_paramHandle.manual_stick_down_threshold, &_params.manual_stick_down_threshold); param_get(_paramHandle.altitude_max, &_params.altitude_max); param_get(_paramHandle.manual_stick_up_position_takeoff_threshold, &_params.manual_stick_up_position_takeoff_threshold); } bool MulticopterLandDetector::_get_freefall_state() { if (_params.freefall_acc_threshold < 0.1f || _params.freefall_acc_threshold > 10.0f) { //if parameter is set to zero or invalid, disable free-fall detection. return false; } if (_ctrl_state.timestamp == 0) { // _ctrl_state is not valid yet, we have to assume we're not falling. return false; } float acc_norm = _ctrl_state.x_acc * _ctrl_state.x_acc + _ctrl_state.y_acc * _ctrl_state.y_acc + _ctrl_state.z_acc * _ctrl_state.z_acc; acc_norm = sqrtf(acc_norm); //norm of specific force. Should be close to 9.8 m/s^2 when landed. return (acc_norm < _params.freefall_acc_threshold); //true if we are currently falling } bool MulticopterLandDetector::_get_ground_contact_state() { // Time base for this function const uint64_t now = hrt_absolute_time(); // only trigger flight conditions if we are armed if (!_arming.armed) { _arming_time = 0; return true; } else if (_arming_time == 0) { _arming_time = now; } // If in manual flight mode never report landed if the user has more than idle throttle // Check if user commands throttle and if so, report no ground contact based on // the user intent to take off (even if the system might physically still have // ground contact at this point). const bool manual_control_idle = (_has_manual_control_present() && _manual.z < _params.manual_stick_down_threshold); const bool manual_control_idle_or_auto = manual_control_idle || !_control_mode.flag_control_manual_enabled; // Widen acceptance thresholds for landed state right after arming // so that motor spool-up and other effects do not trigger false negatives. float armThresholdFactor = 1.0f; if (hrt_elapsed_time(&_arming_time) < LAND_DETECTOR_ARM_PHASE_TIME_US) { armThresholdFactor = 2.5f; } // Check if we are moving vertically - this might see a spike after arming due to // throttle-up vibration. If accelerating fast the throttle thresholds will still give // an accurate in-air indication. bool verticalMovement = fabsf(_vehicleLocalPosition.vz) > _params.maxClimbRate * armThresholdFactor; // If pilots commands down or in auto mode and we are already below minimal thrust and we do not move down we assume ground contact // TODO: we need an accelerometer based check for vertical movement for flying without GPS if (manual_control_idle_or_auto && _has_minimal_thrust() && (!verticalMovement || !_has_position_lock())) { return true; } return false; } bool MulticopterLandDetector::_get_landed_state() { // Time base for this function const uint64_t now = hrt_absolute_time(); // only trigger flight conditions if we are armed if (!_arming.armed) { return true; } // If we control manually and are still landed, we want to stay idle until the pilot rises the throttle for takeoff if (_state == LandDetectionState::LANDED && _has_manual_control_present()) { if (_manual.z < _get_takeoff_throttle()) { return true; } else { // Pilot wants to take off, assume no groundcontact anymore and therefore allow thrust _ground_contact_hysteresis.set_state_and_update(false); } } if (_has_minimal_thrust()) { if (_min_trust_start == 0) { _min_trust_start = now; } } else { _min_trust_start = 0; } // Return status based on armed state and throttle if no position lock is available. if (!_has_position_lock()) { // The system has minimum trust set (manual or in failsafe) // if this persists for 8 seconds AND the drone is not // falling consider it to be landed. This should even sustain // quite acrobatic flight. if ((_min_trust_start > 0) && (hrt_elapsed_time(&_min_trust_start) > 8000000)) { return true; } else { return false; } } float armThresholdFactor = 1.0f; // Widen acceptance thresholds for landed state right after arming // so that motor spool-up and other effects do not trigger false negatives. if (hrt_elapsed_time(&_arming_time) < LAND_DETECTOR_ARM_PHASE_TIME_US) { armThresholdFactor = 2.5f; } // Check if we are moving horizontally. bool horizontalMovement = sqrtf(_vehicleLocalPosition.vx * _vehicleLocalPosition.vx + _vehicleLocalPosition.vy * _vehicleLocalPosition.vy) > _params.maxVelocity; // Next look if all rotation angles are not moving. float maxRotationScaled = _params.maxRotation_rad_s * armThresholdFactor; bool rotating = (fabsf(_vehicleAttitude.rollspeed) > maxRotationScaled) || (fabsf(_vehicleAttitude.pitchspeed) > maxRotationScaled) || (fabsf(_vehicleAttitude.yawspeed) > maxRotationScaled); if (_ground_contact_hysteresis.get_state() && _has_minimal_thrust() && !rotating && !horizontalMovement) { // Ground contact, no thrust and no movement -> landed return true; } return false; } float MulticopterLandDetector::_get_takeoff_throttle() { /* Position mode */ if (_control_mode.flag_control_manual_enabled && _control_mode.flag_control_altitude_enabled) { /* Should be above 0.5 because below that we do not gain altitude and won't take off. * Also it should be quite high such that we don't accidentally take off when using * a spring loaded throttle and have a useful vertical speed to start with. */ return _params.manual_stick_up_position_takeoff_threshold; } /* Manual/attitude mode */ if (_control_mode.flag_control_manual_enabled && _control_mode.flag_control_attitude_enabled) { /* Should be quite low and certainly below hover throttle because pilot controls throttle manually. */ return 0.15f; } /* As default for example in acro mode we do not want to stay landed. */ return 0.0f; } float MulticopterLandDetector::_get_max_altitude() { /* ToDo: add a meaningful altitude */ float valid_altitude_max = _params.altitude_max; if (_battery.warning == battery_status_s::BATTERY_WARNING_LOW) { valid_altitude_max = _params.altitude_max * 0.75f; } if (_battery.warning == battery_status_s::BATTERY_WARNING_CRITICAL) { valid_altitude_max = _params.altitude_max * 0.5f; } if (_battery.warning == battery_status_s::BATTERY_WARNING_EMERGENCY) { valid_altitude_max = _params.altitude_max * 0.25f; } return valid_altitude_max; } bool MulticopterLandDetector::_has_position_lock() { return !(_vehicleLocalPosition.timestamp == 0 || hrt_elapsed_time(&_vehicleLocalPosition.timestamp) > 500000 || !_vehicleLocalPosition.xy_valid || !_vehicleLocalPosition.z_valid); } bool MulticopterLandDetector::_has_manual_control_present() { return _control_mode.flag_control_manual_enabled && _manual.timestamp > 0; } bool MulticopterLandDetector::_has_minimal_thrust() { // 10% of throttle range between min and hover float sys_min_throttle = _params.minThrottle + (_params.hoverThrottle - _params.minThrottle) * _params.throttleRange; // Determine the system min throttle based on flight mode if (!_control_mode.flag_control_altitude_enabled) { sys_min_throttle = (_params.minManThrottle + 0.01f); } // Check if thrust output is less than the minimum auto throttle param. return _actuators.control[3] <= sys_min_throttle; } } <commit_msg>landdetector: exit landing state if manual.z is larger than threshold<commit_after>/**************************************************************************** * * Copyright (c) 2013-2016 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file MulticopterLandDetector.cpp * * @author Johan Jansen <[email protected]> * @author Morten Lysgaard <[email protected]> * @author Julian Oes <[email protected]> */ #include <cmath> #include <drivers/drv_hrt.h> #include <mathlib/mathlib.h> #include "MulticopterLandDetector.h" namespace land_detector { MulticopterLandDetector::MulticopterLandDetector() : LandDetector(), _paramHandle(), _params(), _vehicleLocalPositionSub(-1), _actuatorsSub(-1), _armingSub(-1), _attitudeSub(-1), _manualSub(-1), _ctrl_state_sub(-1), _vehicle_control_mode_sub(-1), _battery_sub(-1), _vehicleLocalPosition{}, _actuators{}, _arming{}, _vehicleAttitude{}, _manual{}, _ctrl_state{}, _control_mode{}, _battery{}, _min_trust_start(0), _arming_time(0) { _paramHandle.maxRotation = param_find("LNDMC_ROT_MAX"); _paramHandle.maxVelocity = param_find("LNDMC_XY_VEL_MAX"); _paramHandle.maxClimbRate = param_find("LNDMC_Z_VEL_MAX"); _paramHandle.throttleRange = param_find("LNDMC_THR_RANGE"); _paramHandle.minThrottle = param_find("MPC_THR_MIN"); _paramHandle.hoverThrottle = param_find("MPC_THR_HOVER"); _paramHandle.minManThrottle = param_find("MPC_MANTHR_MIN"); _paramHandle.freefall_acc_threshold = param_find("LNDMC_FFALL_THR"); _paramHandle.freefall_trigger_time = param_find("LNDMC_FFALL_TTRI"); _paramHandle.manual_stick_down_threshold = param_find("LNDMC_MAN_DWNTHR"); _paramHandle.altitude_max = param_find("LNDMC_ALT_MAX"); _paramHandle.manual_stick_up_position_takeoff_threshold = param_find("LNDMC_POS_UPTHR"); } void MulticopterLandDetector::_initialize_topics() { // subscribe to position, attitude, arming and velocity changes _vehicleLocalPositionSub = orb_subscribe(ORB_ID(vehicle_local_position)); _attitudeSub = orb_subscribe(ORB_ID(vehicle_attitude)); _actuatorsSub = orb_subscribe(ORB_ID(actuator_controls_0)); _armingSub = orb_subscribe(ORB_ID(actuator_armed)); _parameterSub = orb_subscribe(ORB_ID(parameter_update)); _manualSub = orb_subscribe(ORB_ID(manual_control_setpoint)); _ctrl_state_sub = orb_subscribe(ORB_ID(control_state)); _vehicle_control_mode_sub = orb_subscribe(ORB_ID(vehicle_control_mode)); _battery_sub = orb_subscribe(ORB_ID(battery_status)); } void MulticopterLandDetector::_update_topics() { _orb_update(ORB_ID(vehicle_local_position), _vehicleLocalPositionSub, &_vehicleLocalPosition); _orb_update(ORB_ID(vehicle_attitude), _attitudeSub, &_vehicleAttitude); _orb_update(ORB_ID(actuator_controls_0), _actuatorsSub, &_actuators); _orb_update(ORB_ID(actuator_armed), _armingSub, &_arming); _orb_update(ORB_ID(manual_control_setpoint), _manualSub, &_manual); _orb_update(ORB_ID(control_state), _ctrl_state_sub, &_ctrl_state); _orb_update(ORB_ID(vehicle_control_mode), _vehicle_control_mode_sub, &_control_mode); _orb_update(ORB_ID(battery_status), _battery_sub, &_battery); } void MulticopterLandDetector::_update_params() { param_get(_paramHandle.maxClimbRate, &_params.maxClimbRate); param_get(_paramHandle.maxVelocity, &_params.maxVelocity); param_get(_paramHandle.maxRotation, &_params.maxRotation_rad_s); _params.maxRotation_rad_s = math::radians(_params.maxRotation_rad_s); param_get(_paramHandle.minThrottle, &_params.minThrottle); param_get(_paramHandle.hoverThrottle, &_params.hoverThrottle); param_get(_paramHandle.throttleRange, &_params.throttleRange); param_get(_paramHandle.minManThrottle, &_params.minManThrottle); param_get(_paramHandle.freefall_acc_threshold, &_params.freefall_acc_threshold); param_get(_paramHandle.freefall_trigger_time, &_params.freefall_trigger_time); _freefall_hysteresis.set_hysteresis_time_from(false, (hrt_abstime)(1e6f * _params.freefall_trigger_time)); param_get(_paramHandle.manual_stick_down_threshold, &_params.manual_stick_down_threshold); param_get(_paramHandle.altitude_max, &_params.altitude_max); param_get(_paramHandle.manual_stick_up_position_takeoff_threshold, &_params.manual_stick_up_position_takeoff_threshold); } bool MulticopterLandDetector::_get_freefall_state() { if (_params.freefall_acc_threshold < 0.1f || _params.freefall_acc_threshold > 10.0f) { //if parameter is set to zero or invalid, disable free-fall detection. return false; } if (_ctrl_state.timestamp == 0) { // _ctrl_state is not valid yet, we have to assume we're not falling. return false; } float acc_norm = _ctrl_state.x_acc * _ctrl_state.x_acc + _ctrl_state.y_acc * _ctrl_state.y_acc + _ctrl_state.z_acc * _ctrl_state.z_acc; acc_norm = sqrtf(acc_norm); //norm of specific force. Should be close to 9.8 m/s^2 when landed. return (acc_norm < _params.freefall_acc_threshold); //true if we are currently falling } bool MulticopterLandDetector::_get_ground_contact_state() { // Time base for this function const uint64_t now = hrt_absolute_time(); // only trigger flight conditions if we are armed if (!_arming.armed) { _arming_time = 0; return true; } else if (_arming_time == 0) { _arming_time = now; } // If in manual flight mode never report landed if the user has more than idle throttle // Check if user commands throttle and if so, report no ground contact based on // the user intent to take off (even if the system might physically still have // ground contact at this point). const bool manual_control_idle = (_has_manual_control_present() && _manual.z < _params.manual_stick_down_threshold); const bool manual_control_idle_or_auto = manual_control_idle || !_control_mode.flag_control_manual_enabled; // Widen acceptance thresholds for landed state right after arming // so that motor spool-up and other effects do not trigger false negatives. float armThresholdFactor = 1.0f; if (hrt_elapsed_time(&_arming_time) < LAND_DETECTOR_ARM_PHASE_TIME_US) { armThresholdFactor = 2.5f; } // Check if we are moving vertically - this might see a spike after arming due to // throttle-up vibration. If accelerating fast the throttle thresholds will still give // an accurate in-air indication. bool verticalMovement = fabsf(_vehicleLocalPosition.vz) > _params.maxClimbRate * armThresholdFactor; // If pilots commands down or in auto mode and we are already below minimal thrust and we do not move down we assume ground contact // TODO: we need an accelerometer based check for vertical movement for flying without GPS if (manual_control_idle_or_auto && _has_minimal_thrust() && (!verticalMovement || !_has_position_lock())) { return true; } return false; } bool MulticopterLandDetector::_get_landed_state() { // Time base for this function const uint64_t now = hrt_absolute_time(); // only trigger flight conditions if we are armed if (!_arming.armed) { return true; } // If we control manually and are still landed, we want to stay idle until the pilot rises the throttle for takeoff if (_state == LandDetectionState::LANDED && _has_manual_control_present()) { if (_manual.z < _get_takeoff_throttle()) { return true; } else { // Pilot wants to take off, assume no groundcontact anymore and therefore allow thrust _ground_contact_hysteresis.set_state_and_update(false); return false; } } if (_has_minimal_thrust()) { if (_min_trust_start == 0) { _min_trust_start = now; } } else { _min_trust_start = 0; } // Return status based on armed state and throttle if no position lock is available. if (!_has_position_lock()) { // The system has minimum trust set (manual or in failsafe) // if this persists for 8 seconds AND the drone is not // falling consider it to be landed. This should even sustain // quite acrobatic flight. if ((_min_trust_start > 0) && (hrt_elapsed_time(&_min_trust_start) > 8000000)) { return true; } else { return false; } } float armThresholdFactor = 1.0f; // Widen acceptance thresholds for landed state right after arming // so that motor spool-up and other effects do not trigger false negatives. if (hrt_elapsed_time(&_arming_time) < LAND_DETECTOR_ARM_PHASE_TIME_US) { armThresholdFactor = 2.5f; } // Check if we are moving horizontally. bool horizontalMovement = sqrtf(_vehicleLocalPosition.vx * _vehicleLocalPosition.vx + _vehicleLocalPosition.vy * _vehicleLocalPosition.vy) > _params.maxVelocity; // Next look if all rotation angles are not moving. float maxRotationScaled = _params.maxRotation_rad_s * armThresholdFactor; bool rotating = (fabsf(_vehicleAttitude.rollspeed) > maxRotationScaled) || (fabsf(_vehicleAttitude.pitchspeed) > maxRotationScaled) || (fabsf(_vehicleAttitude.yawspeed) > maxRotationScaled); if (_ground_contact_hysteresis.get_state() && _has_minimal_thrust() && !rotating && !horizontalMovement) { // Ground contact, no thrust and no movement -> landed return true; } return false; } float MulticopterLandDetector::_get_takeoff_throttle() { /* Position mode */ if (_control_mode.flag_control_manual_enabled && _control_mode.flag_control_altitude_enabled) { /* Should be above 0.5 because below that we do not gain altitude and won't take off. * Also it should be quite high such that we don't accidentally take off when using * a spring loaded throttle and have a useful vertical speed to start with. */ return _params.manual_stick_up_position_takeoff_threshold; } /* Manual/attitude mode */ if (_control_mode.flag_control_manual_enabled && _control_mode.flag_control_attitude_enabled) { /* Should be quite low and certainly below hover throttle because pilot controls throttle manually. */ return 0.15f; } /* As default for example in acro mode we do not want to stay landed. */ return 0.0f; } float MulticopterLandDetector::_get_max_altitude() { /* ToDo: add a meaningful altitude */ float valid_altitude_max = _params.altitude_max; if (_battery.warning == battery_status_s::BATTERY_WARNING_LOW) { valid_altitude_max = _params.altitude_max * 0.75f; } if (_battery.warning == battery_status_s::BATTERY_WARNING_CRITICAL) { valid_altitude_max = _params.altitude_max * 0.5f; } if (_battery.warning == battery_status_s::BATTERY_WARNING_EMERGENCY) { valid_altitude_max = _params.altitude_max * 0.25f; } return valid_altitude_max; } bool MulticopterLandDetector::_has_position_lock() { return !(_vehicleLocalPosition.timestamp == 0 || hrt_elapsed_time(&_vehicleLocalPosition.timestamp) > 500000 || !_vehicleLocalPosition.xy_valid || !_vehicleLocalPosition.z_valid); } bool MulticopterLandDetector::_has_manual_control_present() { return _control_mode.flag_control_manual_enabled && _manual.timestamp > 0; } bool MulticopterLandDetector::_has_minimal_thrust() { // 10% of throttle range between min and hover float sys_min_throttle = _params.minThrottle + (_params.hoverThrottle - _params.minThrottle) * _params.throttleRange; // Determine the system min throttle based on flight mode if (!_control_mode.flag_control_altitude_enabled) { sys_min_throttle = (_params.minManThrottle + 0.01f); } // Check if thrust output is less than the minimum auto throttle param. return _actuators.control[3] <= sys_min_throttle; } } <|endoftext|>
<commit_before>#include "common.th" // c <- multiplicand // d <- multiplier // b -> product .global imul imul: #if IMUL_EARLY_EXITS b <- c == 0 d <- d &~ b // d = (c == 0) ? 0 : d b <- d <> 0 jzrel(b, L_done) #endif pushall(h,i,j) b <- 0 h <- 1 j <- d >> 31 // save sign bit in j j <- -j // convert sign to flag d <- d ^ j // adjust multiplier d <- d - j L_top: // use constant 1 in h to combine instructions i <- d & h - 1 i <- c &~ i b <- b + i c <- c << 1 d <- d >> 1 i <- d <> 0 jnzrel(i, L_top) b <- b ^ j // adjust product for signed math b <- b - j popall(h,i,j) L_done: ret <commit_msg>Use arithmetic right-shift in imul<commit_after>#include "common.th" // c <- multiplicand // d <- multiplier // b -> product .global imul imul: #if IMUL_EARLY_EXITS b <- c == 0 d <- d &~ b // d = (c == 0) ? 0 : d b <- d <> 0 jzrel(b, L_done) #endif pushall(h,i,j) b <- 0 h <- 1 j <- d >>> 31 // save sign bit in j d <- d ^ j // adjust multiplier d <- d - j L_top: // use constant 1 in h to combine instructions i <- d & h - 1 i <- c &~ i b <- b + i c <- c << 1 d <- d >> 1 i <- d <> 0 jnzrel(i, L_top) b <- b ^ j // adjust product for signed math b <- b - j popall(h,i,j) L_done: ret <|endoftext|>
<commit_before>#include "networktables/NetworkTable.h" #include <algorithm> #include "llvm/SmallString.h" #include "tables/ITableListener.h" #include "ntcore.h" using llvm::StringRef; const char NetworkTable::PATH_SEPARATOR_CHAR = '/'; std::string NetworkTable::s_ip_address; bool NetworkTable::s_client = false; bool NetworkTable::s_running = false; void NetworkTable::Initialize() { if (s_client) nt::StartClient(s_ip_address.c_str(), NT_DEFAULT_PORT); else nt::StartServer("", "", NT_DEFAULT_PORT); s_running = true; } void NetworkTable::Shutdown() { if (s_client) nt::StopClient(); else nt::StopServer(); s_running = false; } void NetworkTable::SetClientMode() { s_client = true; } void NetworkTable::SetServerMode() { s_client = false; } void NetworkTable::SetTeam(int team) { char tmp[30]; sprintf(tmp, "%d.%d.%d.%d\n", 10, team / 100, team % 100, 2); SetIPAddress(tmp); } void NetworkTable::SetIPAddress(StringRef address) { s_ip_address = address; } std::shared_ptr<NetworkTable> NetworkTable::GetTable(StringRef key) { if (!s_running) Initialize(); llvm::SmallString<128> path; path += PATH_SEPARATOR_CHAR; path += key; return std::make_shared<NetworkTable>(path, private_init()); } NetworkTable::NetworkTable(StringRef path, const private_init&) : m_path(path) {} NetworkTable::~NetworkTable() { for (auto& i : m_listeners) nt::RemoveEntryListener(i.second); } void NetworkTable::AddTableListener(ITableListener* listener) { AddTableListener(listener, false); } void NetworkTable::AddTableListener(ITableListener* listener, bool immediateNotify) { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; unsigned int id = nt::AddEntryListener( path, [=](unsigned int uid, StringRef name, std::shared_ptr<nt::Value> value, bool is_new) { listener->ValueChanged(this, name, value, is_new); }, immediateNotify); m_listeners.emplace_back(listener, id); } void NetworkTable::AddTableListener(StringRef key, ITableListener* listener, bool immediateNotify) { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; unsigned int id = nt::AddEntryListener( path, [=](unsigned int uid, StringRef name, std::shared_ptr<nt::Value> value, bool is_new) { listener->ValueChanged(this, name, value, is_new); }, immediateNotify); m_listeners.emplace_back(listener, id); } void NetworkTable::RemoveTableListener(ITableListener* listener) { auto matches_begin = std::remove_if(m_listeners.begin(), m_listeners.end(), [=](const auto& x) { return x.first == listener; }); for (auto i = matches_begin; i != m_listeners.end(); ++i) nt::RemoveEntryListener(i->second); m_listeners.erase(matches_begin, m_listeners.end()); } std::shared_ptr<ITable> NetworkTable::GetSubTable(StringRef key) const { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; return std::make_shared<NetworkTable>(path, private_init()); } bool NetworkTable::ContainsKey(StringRef key) const { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; return !nt::GetEntryValue(path); } bool NetworkTable::ContainsSubTable(StringRef key) const { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; path += PATH_SEPARATOR_CHAR; return !nt::GetEntryInfo(path, 0).empty(); } void NetworkTable::PutNumber(StringRef key, double value) { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; nt::SetEntryValue(path, nt::Value::MakeDouble(value)); } double NetworkTable::GetNumber(StringRef key, double defaultValue) const { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; auto value = nt::GetEntryValue(path); if (!value || value->type() != NT_DOUBLE) return defaultValue; return value->GetDouble(); } void NetworkTable::PutString(StringRef key, StringRef value) { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; nt::SetEntryValue(path, nt::Value::MakeString(value)); } std::string NetworkTable::GetString(StringRef key, StringRef defaultValue) const { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; auto value = nt::GetEntryValue(path); if (!value || value->type() != NT_STRING) return defaultValue; return value->GetString(); } void NetworkTable::PutBoolean(StringRef key, bool value) { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; nt::SetEntryValue(path, nt::Value::MakeBoolean(value)); } bool NetworkTable::GetBoolean(StringRef key, bool defaultValue) const { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; auto value = nt::GetEntryValue(path); if (!value || value->type() != NT_BOOLEAN) return defaultValue; return value->GetBoolean(); } void NetworkTable::PutValue(StringRef key, std::shared_ptr<nt::Value> value) { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; nt::SetEntryValue(path, value); } std::shared_ptr<nt::Value> NetworkTable::GetValue(StringRef key) const { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; return nt::GetEntryValue(path); } <commit_msg>NetworkTable: Use networktables.ini as persistence filename.<commit_after>#include "networktables/NetworkTable.h" #include <algorithm> #include "llvm/SmallString.h" #include "tables/ITableListener.h" #include "ntcore.h" using llvm::StringRef; const char NetworkTable::PATH_SEPARATOR_CHAR = '/'; std::string NetworkTable::s_ip_address; bool NetworkTable::s_client = false; bool NetworkTable::s_running = false; void NetworkTable::Initialize() { if (s_client) nt::StartClient(s_ip_address.c_str(), NT_DEFAULT_PORT); else nt::StartServer("networktables.ini", "", NT_DEFAULT_PORT); s_running = true; } void NetworkTable::Shutdown() { if (s_client) nt::StopClient(); else nt::StopServer(); s_running = false; } void NetworkTable::SetClientMode() { s_client = true; } void NetworkTable::SetServerMode() { s_client = false; } void NetworkTable::SetTeam(int team) { char tmp[30]; sprintf(tmp, "%d.%d.%d.%d\n", 10, team / 100, team % 100, 2); SetIPAddress(tmp); } void NetworkTable::SetIPAddress(StringRef address) { s_ip_address = address; } std::shared_ptr<NetworkTable> NetworkTable::GetTable(StringRef key) { if (!s_running) Initialize(); llvm::SmallString<128> path; path += PATH_SEPARATOR_CHAR; path += key; return std::make_shared<NetworkTable>(path, private_init()); } NetworkTable::NetworkTable(StringRef path, const private_init&) : m_path(path) {} NetworkTable::~NetworkTable() { for (auto& i : m_listeners) nt::RemoveEntryListener(i.second); } void NetworkTable::AddTableListener(ITableListener* listener) { AddTableListener(listener, false); } void NetworkTable::AddTableListener(ITableListener* listener, bool immediateNotify) { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; unsigned int id = nt::AddEntryListener( path, [=](unsigned int uid, StringRef name, std::shared_ptr<nt::Value> value, bool is_new) { listener->ValueChanged(this, name, value, is_new); }, immediateNotify); m_listeners.emplace_back(listener, id); } void NetworkTable::AddTableListener(StringRef key, ITableListener* listener, bool immediateNotify) { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; unsigned int id = nt::AddEntryListener( path, [=](unsigned int uid, StringRef name, std::shared_ptr<nt::Value> value, bool is_new) { listener->ValueChanged(this, name, value, is_new); }, immediateNotify); m_listeners.emplace_back(listener, id); } void NetworkTable::RemoveTableListener(ITableListener* listener) { auto matches_begin = std::remove_if(m_listeners.begin(), m_listeners.end(), [=](const auto& x) { return x.first == listener; }); for (auto i = matches_begin; i != m_listeners.end(); ++i) nt::RemoveEntryListener(i->second); m_listeners.erase(matches_begin, m_listeners.end()); } std::shared_ptr<ITable> NetworkTable::GetSubTable(StringRef key) const { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; return std::make_shared<NetworkTable>(path, private_init()); } bool NetworkTable::ContainsKey(StringRef key) const { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; return !nt::GetEntryValue(path); } bool NetworkTable::ContainsSubTable(StringRef key) const { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; path += PATH_SEPARATOR_CHAR; return !nt::GetEntryInfo(path, 0).empty(); } void NetworkTable::PutNumber(StringRef key, double value) { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; nt::SetEntryValue(path, nt::Value::MakeDouble(value)); } double NetworkTable::GetNumber(StringRef key, double defaultValue) const { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; auto value = nt::GetEntryValue(path); if (!value || value->type() != NT_DOUBLE) return defaultValue; return value->GetDouble(); } void NetworkTable::PutString(StringRef key, StringRef value) { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; nt::SetEntryValue(path, nt::Value::MakeString(value)); } std::string NetworkTable::GetString(StringRef key, StringRef defaultValue) const { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; auto value = nt::GetEntryValue(path); if (!value || value->type() != NT_STRING) return defaultValue; return value->GetString(); } void NetworkTable::PutBoolean(StringRef key, bool value) { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; nt::SetEntryValue(path, nt::Value::MakeBoolean(value)); } bool NetworkTable::GetBoolean(StringRef key, bool defaultValue) const { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; auto value = nt::GetEntryValue(path); if (!value || value->type() != NT_BOOLEAN) return defaultValue; return value->GetBoolean(); } void NetworkTable::PutValue(StringRef key, std::shared_ptr<nt::Value> value) { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; nt::SetEntryValue(path, value); } std::shared_ptr<nt::Value> NetworkTable::GetValue(StringRef key) const { llvm::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; path += key; return nt::GetEntryValue(path); } <|endoftext|>
<commit_before>/* * param.cpp * */ #include "param.h" using namespace himan; using namespace std; param::~param() {} param::param() : itsId(kHPMissingInt), itsName("XX-X"), itsScale(1), itsBase(0), itsUnivId(kHPMissingInt), itsGribParameter(kHPMissingInt), itsGribCategory(kHPMissingInt), itsGribDiscipline(kHPMissingInt), itsGribTableVersion(kHPMissingInt), itsGribIndicatorOfParameter(kHPMissingInt), itsVersion(1), itsInterpolationMethod(kBiLinear), itsUnit(kUnknownUnit), itsAggregation(), itsPrecision(kHPMissingInt) { } param::param(const string& theName, unsigned long theUnivId) : itsId(kHPMissingInt), itsName(theName), itsScale(1), itsBase(0), itsUnivId(theUnivId), itsGribParameter(kHPMissingInt), itsGribCategory(kHPMissingInt), itsGribDiscipline(kHPMissingInt), itsGribTableVersion(kHPMissingInt), itsGribIndicatorOfParameter(kHPMissingInt), itsVersion(1), itsInterpolationMethod(kBiLinear), itsUnit(kUnknownUnit), itsAggregation(), itsPrecision(kHPMissingInt) { } param::param(const string& theName, unsigned long theUnivId, HPParameterUnit theUnit) : itsId(kHPMissingInt), itsName(theName), itsScale(1), itsBase(0), itsUnivId(theUnivId), itsGribParameter(kHPMissingInt), itsGribCategory(kHPMissingInt), itsGribDiscipline(kHPMissingInt), itsGribTableVersion(kHPMissingInt), itsGribIndicatorOfParameter(kHPMissingInt), itsVersion(1), itsInterpolationMethod(kBiLinear), itsUnit(theUnit), itsAggregation(), itsPrecision(kHPMissingInt) { } param::param(const string& theName) : itsId(kHPMissingInt), itsName(theName), itsScale(1), itsBase(0), itsUnivId(kHPMissingInt), itsGribParameter(kHPMissingInt), itsGribCategory(kHPMissingInt), itsGribDiscipline(kHPMissingInt), itsGribTableVersion(kHPMissingInt), itsGribIndicatorOfParameter(kHPMissingInt), itsVersion(1), itsInterpolationMethod(kBiLinear), itsUnit(kUnknownUnit), itsAggregation(), itsPrecision(kHPMissingInt) { } param::param(const string& theName, unsigned long theUnivId, double theScale, double theBase, HPInterpolationMethod theInterpolationMethod) : itsId(kHPMissingInt), itsName(theName), itsScale(theScale), itsBase(theBase), itsUnivId(theUnivId), itsGribParameter(kHPMissingInt), itsGribCategory(kHPMissingInt), itsGribDiscipline(kHPMissingInt), itsGribTableVersion(kHPMissingInt), itsGribIndicatorOfParameter(kHPMissingInt), itsVersion(1), itsInterpolationMethod(theInterpolationMethod), itsUnit(kUnknownUnit), itsAggregation(), itsPrecision(kHPMissingInt) { } param::param(const string& theName, unsigned long theUnivId, long theGribDiscipline, long theGribCategory, long theGribParameter) : itsId(kHPMissingInt), itsName(theName), itsScale(1), itsBase(0), itsUnivId(theUnivId), itsGribParameter(theGribParameter), itsGribCategory(theGribCategory), itsGribDiscipline(theGribDiscipline), itsGribTableVersion(kHPMissingInt), itsGribIndicatorOfParameter(kHPMissingInt), itsVersion(1), itsInterpolationMethod(kBiLinear), itsUnit(kUnknownUnit), itsAggregation(), itsPrecision(kHPMissingInt) { } param::param(const map<string, string>& databaseInfo) : param() { if (!databaseInfo.empty()) { itsId = stoi(databaseInfo.at("id")); itsName = databaseInfo.at("name"); itsVersion = stoi(databaseInfo.at("version")); try { itsGribIndicatorOfParameter = stoi(databaseInfo.at("grib1_number")); itsGribTableVersion = stoi(databaseInfo.at("grib1_table_version")); } catch (const out_of_range& e) { } catch (const invalid_argument& e) { } try { itsGribDiscipline = stoi(databaseInfo.at("grib2_discipline")); itsGribCategory = stoi(databaseInfo.at("grib2_category")); itsGribParameter = stoi(databaseInfo.at("grib2_number")); } catch (const out_of_range& e) { } catch (const invalid_argument& e) { } try { itsPrecision = stoi(databaseInfo.at("precision")); } catch (const out_of_range& e) { } catch (const invalid_argument& e) { } try { itsUnivId = stoi(databaseInfo.at("univ_id")); itsScale = stod(databaseInfo.at("scale")); itsBase = stod(databaseInfo.at("base")); } catch (const out_of_range& e) { } catch (const invalid_argument& e) { } } } param::param(const param& other) : itsId(other.itsId), itsName(other.itsName), itsScale(other.itsScale), itsBase(other.itsBase), itsUnivId(other.itsUnivId), itsGribParameter(other.itsGribParameter), itsGribCategory(other.itsGribCategory), itsGribDiscipline(other.itsGribDiscipline), itsGribTableVersion(other.itsGribTableVersion), itsGribIndicatorOfParameter(other.itsGribIndicatorOfParameter), itsVersion(other.itsVersion), itsInterpolationMethod(other.itsInterpolationMethod), itsUnit(other.itsUnit), itsAggregation(other.itsAggregation), itsPrecision(other.itsPrecision) { } param& param::operator=(const param& other) { itsId = other.itsId; itsName = other.itsName; itsScale = other.itsScale; itsBase = other.itsBase; itsUnivId = other.itsUnivId; itsGribParameter = other.itsGribParameter; itsGribCategory = other.itsGribCategory; itsGribDiscipline = other.itsGribDiscipline; itsGribTableVersion = other.itsGribTableVersion; itsGribIndicatorOfParameter = other.itsGribIndicatorOfParameter; itsVersion = other.itsVersion; itsInterpolationMethod = other.itsInterpolationMethod; itsUnit = other.itsUnit; itsAggregation = other.itsAggregation; itsPrecision = other.itsPrecision; return *this; } bool param::operator==(const param& other) const { if (this == &other) { return true; } if (itsId != other.itsId) { return false; } if (itsName != other.itsName) { return false; } if (UnivId() != static_cast<unsigned int>(kHPMissingInt) && other.UnivId() != static_cast<unsigned int>(kHPMissingInt) && UnivId() != other.UnivId()) { return false; } // Grib 1 if (itsGribTableVersion != kHPMissingInt && other.GribTableVersion() != kHPMissingInt && itsGribTableVersion != other.GribTableVersion()) { return false; } if (itsGribIndicatorOfParameter != kHPMissingInt && other.GribIndicatorOfParameter() != kHPMissingInt && itsGribIndicatorOfParameter != other.GribIndicatorOfParameter()) { return false; } // Grib 2 if (itsGribDiscipline != kHPMissingInt && other.GribDiscipline() != kHPMissingInt && itsGribDiscipline != other.GribDiscipline()) { return false; } if (itsGribCategory != kHPMissingInt && other.GribCategory() != kHPMissingInt && itsGribCategory != other.GribCategory()) { return false; } if (itsGribParameter != kHPMissingInt && other.GribParameter() != kHPMissingInt && itsGribParameter != other.GribParameter()) { return false; } if (itsAggregation.Type() != kUnknownAggregationType && other.itsAggregation.Type() != kUnknownAggregationType && itsAggregation != other.itsAggregation) { return false; } if (itsVersion != other.itsVersion) { return false; } return true; } bool param::operator!=(const param& other) const { return !(*this == other); } void param::GribParameter(long theGribParameter) { itsGribParameter = theGribParameter; } long param::GribParameter() const { return itsGribParameter; } void param::GribDiscipline(long theGribDiscipline) { itsGribDiscipline = theGribDiscipline; } long param::GribDiscipline() const { return itsGribDiscipline; } void param::GribCategory(long theGribCategory) { itsGribCategory = theGribCategory; } long param::GribCategory() const { return itsGribCategory; } void param::GribIndicatorOfParameter(long theGribIndicatorOfParameter) { itsGribIndicatorOfParameter = theGribIndicatorOfParameter; } long param::GribIndicatorOfParameter() const { return itsGribIndicatorOfParameter; } unsigned long param::UnivId() const { return itsUnivId; } void param::UnivId(unsigned long theUnivId) { itsUnivId = theUnivId; } string param::Name() const { return itsName; } void param::Name(const string& theName) { itsName = theName; } HPParameterUnit param::Unit() const { return itsUnit; } void param::Unit(HPParameterUnit theUnit) { itsUnit = theUnit; } void param::GribTableVersion(long theVersion) { itsGribTableVersion = theVersion; } long param::GribTableVersion() const { return itsGribTableVersion; } const aggregation& param::Aggregation() const { return itsAggregation; } void param::Aggregation(const aggregation& theAggregation) { itsAggregation = theAggregation; } double param::Base() const { return itsBase; } void param::Base(double theBase) { itsBase = theBase; } double param::Scale() const { return itsScale; } void param::Scale(double theScale) { itsScale = theScale; } long param::Id() const { return itsId; } void param::Id(long theId) { itsId = theId; } HPInterpolationMethod param::InterpolationMethod() const { return itsInterpolationMethod; } void param::InterpolationMethod(HPInterpolationMethod theInterpolationMethod) { itsInterpolationMethod = theInterpolationMethod; } int param::Precision() const { return itsPrecision; } void param::Precision(int thePrecision) { itsPrecision = thePrecision; } ostream& param::Write(ostream& file) const { file << "<" << ClassName() << ">" << endl; file << "__itsName__ " << itsName << endl; file << "__itsScale__ " << itsScale << endl; file << "__itsBase__ " << itsBase << endl; file << "__itsUnivId__ " << itsUnivId << endl; file << "__itsGribParameter__ " << itsGribParameter << endl; file << "__itsGribCategory__ " << itsGribCategory << endl; file << "__itsGribDiscipline__ " << itsGribDiscipline << endl; file << "__itsGribTableVersion__ " << itsGribTableVersion << endl; file << "__itsIndicatorOfParameter__ " << itsGribIndicatorOfParameter << endl; file << "__itsUnit__ " << static_cast<int>(itsUnit) << endl; file << "__itsVersion__ " << itsVersion << endl; file << "__itsInterpolationMethod__ " << HPInterpolationMethodToString.at(itsInterpolationMethod) << endl; file << "__itsPrecision__" << itsPrecision << endl; file << itsAggregation; return file; } <commit_msg>Remove comparison of output file numbers for param.<commit_after>/* * param.cpp * */ #include "param.h" using namespace himan; using namespace std; param::~param() {} param::param() : itsId(kHPMissingInt), itsName("XX-X"), itsScale(1), itsBase(0), itsUnivId(kHPMissingInt), itsGribParameter(kHPMissingInt), itsGribCategory(kHPMissingInt), itsGribDiscipline(kHPMissingInt), itsGribTableVersion(kHPMissingInt), itsGribIndicatorOfParameter(kHPMissingInt), itsVersion(1), itsInterpolationMethod(kBiLinear), itsUnit(kUnknownUnit), itsAggregation(), itsPrecision(kHPMissingInt) { } param::param(const string& theName, unsigned long theUnivId) : itsId(kHPMissingInt), itsName(theName), itsScale(1), itsBase(0), itsUnivId(theUnivId), itsGribParameter(kHPMissingInt), itsGribCategory(kHPMissingInt), itsGribDiscipline(kHPMissingInt), itsGribTableVersion(kHPMissingInt), itsGribIndicatorOfParameter(kHPMissingInt), itsVersion(1), itsInterpolationMethod(kBiLinear), itsUnit(kUnknownUnit), itsAggregation(), itsPrecision(kHPMissingInt) { } param::param(const string& theName, unsigned long theUnivId, HPParameterUnit theUnit) : itsId(kHPMissingInt), itsName(theName), itsScale(1), itsBase(0), itsUnivId(theUnivId), itsGribParameter(kHPMissingInt), itsGribCategory(kHPMissingInt), itsGribDiscipline(kHPMissingInt), itsGribTableVersion(kHPMissingInt), itsGribIndicatorOfParameter(kHPMissingInt), itsVersion(1), itsInterpolationMethod(kBiLinear), itsUnit(theUnit), itsAggregation(), itsPrecision(kHPMissingInt) { } param::param(const string& theName) : itsId(kHPMissingInt), itsName(theName), itsScale(1), itsBase(0), itsUnivId(kHPMissingInt), itsGribParameter(kHPMissingInt), itsGribCategory(kHPMissingInt), itsGribDiscipline(kHPMissingInt), itsGribTableVersion(kHPMissingInt), itsGribIndicatorOfParameter(kHPMissingInt), itsVersion(1), itsInterpolationMethod(kBiLinear), itsUnit(kUnknownUnit), itsAggregation(), itsPrecision(kHPMissingInt) { } param::param(const string& theName, unsigned long theUnivId, double theScale, double theBase, HPInterpolationMethod theInterpolationMethod) : itsId(kHPMissingInt), itsName(theName), itsScale(theScale), itsBase(theBase), itsUnivId(theUnivId), itsGribParameter(kHPMissingInt), itsGribCategory(kHPMissingInt), itsGribDiscipline(kHPMissingInt), itsGribTableVersion(kHPMissingInt), itsGribIndicatorOfParameter(kHPMissingInt), itsVersion(1), itsInterpolationMethod(theInterpolationMethod), itsUnit(kUnknownUnit), itsAggregation(), itsPrecision(kHPMissingInt) { } param::param(const string& theName, unsigned long theUnivId, long theGribDiscipline, long theGribCategory, long theGribParameter) : itsId(kHPMissingInt), itsName(theName), itsScale(1), itsBase(0), itsUnivId(theUnivId), itsGribParameter(theGribParameter), itsGribCategory(theGribCategory), itsGribDiscipline(theGribDiscipline), itsGribTableVersion(kHPMissingInt), itsGribIndicatorOfParameter(kHPMissingInt), itsVersion(1), itsInterpolationMethod(kBiLinear), itsUnit(kUnknownUnit), itsAggregation(), itsPrecision(kHPMissingInt) { } param::param(const map<string, string>& databaseInfo) : param() { if (!databaseInfo.empty()) { itsId = stoi(databaseInfo.at("id")); itsName = databaseInfo.at("name"); itsVersion = stoi(databaseInfo.at("version")); try { itsGribIndicatorOfParameter = stoi(databaseInfo.at("grib1_number")); itsGribTableVersion = stoi(databaseInfo.at("grib1_table_version")); } catch (const out_of_range& e) { } catch (const invalid_argument& e) { } try { itsGribDiscipline = stoi(databaseInfo.at("grib2_discipline")); itsGribCategory = stoi(databaseInfo.at("grib2_category")); itsGribParameter = stoi(databaseInfo.at("grib2_number")); } catch (const out_of_range& e) { } catch (const invalid_argument& e) { } try { itsPrecision = stoi(databaseInfo.at("precision")); } catch (const out_of_range& e) { } catch (const invalid_argument& e) { } try { itsUnivId = stoi(databaseInfo.at("univ_id")); itsScale = stod(databaseInfo.at("scale")); itsBase = stod(databaseInfo.at("base")); } catch (const out_of_range& e) { } catch (const invalid_argument& e) { } } } param::param(const param& other) : itsId(other.itsId), itsName(other.itsName), itsScale(other.itsScale), itsBase(other.itsBase), itsUnivId(other.itsUnivId), itsGribParameter(other.itsGribParameter), itsGribCategory(other.itsGribCategory), itsGribDiscipline(other.itsGribDiscipline), itsGribTableVersion(other.itsGribTableVersion), itsGribIndicatorOfParameter(other.itsGribIndicatorOfParameter), itsVersion(other.itsVersion), itsInterpolationMethod(other.itsInterpolationMethod), itsUnit(other.itsUnit), itsAggregation(other.itsAggregation), itsPrecision(other.itsPrecision) { } param& param::operator=(const param& other) { itsId = other.itsId; itsName = other.itsName; itsScale = other.itsScale; itsBase = other.itsBase; itsUnivId = other.itsUnivId; itsGribParameter = other.itsGribParameter; itsGribCategory = other.itsGribCategory; itsGribDiscipline = other.itsGribDiscipline; itsGribTableVersion = other.itsGribTableVersion; itsGribIndicatorOfParameter = other.itsGribIndicatorOfParameter; itsVersion = other.itsVersion; itsInterpolationMethod = other.itsInterpolationMethod; itsUnit = other.itsUnit; itsAggregation = other.itsAggregation; itsPrecision = other.itsPrecision; return *this; } bool param::operator==(const param& other) const { if (this == &other) { return true; } if (itsName != other.itsName) { return false; } if (itsAggregation.Type() != kUnknownAggregationType && other.itsAggregation.Type() != kUnknownAggregationType && itsAggregation != other.itsAggregation) { return false; } if (itsVersion != other.itsVersion) { return false; } return true; } bool param::operator!=(const param& other) const { return !(*this == other); } void param::GribParameter(long theGribParameter) { itsGribParameter = theGribParameter; } long param::GribParameter() const { return itsGribParameter; } void param::GribDiscipline(long theGribDiscipline) { itsGribDiscipline = theGribDiscipline; } long param::GribDiscipline() const { return itsGribDiscipline; } void param::GribCategory(long theGribCategory) { itsGribCategory = theGribCategory; } long param::GribCategory() const { return itsGribCategory; } void param::GribIndicatorOfParameter(long theGribIndicatorOfParameter) { itsGribIndicatorOfParameter = theGribIndicatorOfParameter; } long param::GribIndicatorOfParameter() const { return itsGribIndicatorOfParameter; } unsigned long param::UnivId() const { return itsUnivId; } void param::UnivId(unsigned long theUnivId) { itsUnivId = theUnivId; } string param::Name() const { return itsName; } void param::Name(const string& theName) { itsName = theName; } HPParameterUnit param::Unit() const { return itsUnit; } void param::Unit(HPParameterUnit theUnit) { itsUnit = theUnit; } void param::GribTableVersion(long theVersion) { itsGribTableVersion = theVersion; } long param::GribTableVersion() const { return itsGribTableVersion; } const aggregation& param::Aggregation() const { return itsAggregation; } void param::Aggregation(const aggregation& theAggregation) { itsAggregation = theAggregation; } double param::Base() const { return itsBase; } void param::Base(double theBase) { itsBase = theBase; } double param::Scale() const { return itsScale; } void param::Scale(double theScale) { itsScale = theScale; } long param::Id() const { return itsId; } void param::Id(long theId) { itsId = theId; } HPInterpolationMethod param::InterpolationMethod() const { return itsInterpolationMethod; } void param::InterpolationMethod(HPInterpolationMethod theInterpolationMethod) { itsInterpolationMethod = theInterpolationMethod; } int param::Precision() const { return itsPrecision; } void param::Precision(int thePrecision) { itsPrecision = thePrecision; } ostream& param::Write(ostream& file) const { file << "<" << ClassName() << ">" << endl; file << "__itsName__ " << itsName << endl; file << "__itsScale__ " << itsScale << endl; file << "__itsBase__ " << itsBase << endl; file << "__itsUnivId__ " << itsUnivId << endl; file << "__itsGribParameter__ " << itsGribParameter << endl; file << "__itsGribCategory__ " << itsGribCategory << endl; file << "__itsGribDiscipline__ " << itsGribDiscipline << endl; file << "__itsGribTableVersion__ " << itsGribTableVersion << endl; file << "__itsIndicatorOfParameter__ " << itsGribIndicatorOfParameter << endl; file << "__itsUnit__ " << static_cast<int>(itsUnit) << endl; file << "__itsVersion__ " << itsVersion << endl; file << "__itsInterpolationMethod__ " << HPInterpolationMethodToString.at(itsInterpolationMethod) << endl; file << "__itsPrecision__" << itsPrecision << endl; file << itsAggregation; return file; } <|endoftext|>
<commit_before>#include "core/numeric.h" #include "lsearch_morethuente.h" using namespace nano; /// /// see dcstep routine in MINPACK-2 (see http://ftp.mcs.anl.gov/pub/MINPACK-2/csrch/) /// static void dcstep( scalar_t& stx, scalar_t& fx, scalar_t& dx, scalar_t& sty, scalar_t& fy, scalar_t& dy, scalar_t& stp, scalar_t& fp, scalar_t& dp, bool& brackt, const scalar_t stpmin, const scalar_t stpmax) { scalar_t stpc, stpq, stpf; scalar_t theta, d1, d2, d3, s, gamma, p, q, r; const auto sgnd = dp * (dx / std::fabs(dx)); if (fp > fx) { theta = (fx - fp) * 3 / (stp - stx) + dx + dp; d1 = std::fabs(theta); d2 = std::fabs(dx); d1 = std::max(d1, d2); d2 = std::fabs(dp); s = std::max(d1, d2); d1 = theta / s; gamma = s * std::sqrt(d1 * d1 - dx / s * (dp / s)); if (stp < stx) { gamma = -gamma; } p = gamma - dx + theta; q = gamma - dx + gamma + dp; r = p / q; stpc = stx + r * (stp - stx); stpq = stx + dx / ((fx - fp) / (stp - stx) + dx) / 2 * (stp - stx); if (std::fabs(stpc - stx) < std::fabs(stpq - stx)) { stpf = stpc; } else { stpf = stpc + (stpq - stpc) / 2; } brackt = true; } else if (sgnd < 0) { theta = (fx - fp) * 3 / (stp - stx) + dx + dp; d1 = std::fabs(theta); d2 = std::abs(dx); d1 = std::max(d1, d2); d2 = std::fabs(dp); s = std::max(d1, d2); d1 = theta / s; gamma = s * std::sqrt(d1 * d1 - dx / s * (dp / s)); if (stp > stx) { gamma = -gamma; } p = gamma - dp + theta; q = gamma - dp + gamma + dx; r = p / q; stpc = stp + r * (stx - stp); stpq = stp + dp / (dp - dx) * (stx - stp); if (std::fabs(stpc - stp) > std::fabs(stpq - stp)) { stpf = stpc; } else { stpf = stpq; } brackt = true; } else if (std::fabs(dp) < std::fabs(dx)) { theta = (fx - fp) * 3 / (stp - stx) + dx + dp; d1 = std::fabs(theta); d2 = std::fabs(dx); d1 = std::max(d1, d2); d2 = std::fabs(dp); s = std::max(d1, d2); d3 = theta / s; d1 = 0; d2 = d3 * d3 - dx / s * (dp / s); gamma = s * std::sqrt(std::max(d1, d2)); if (stp > stx) { gamma = -gamma; } p = gamma - dp + theta; q = gamma + (dx - dp) + gamma; r = p / q; if (r < 0 && gamma != 0) { stpc = stp + r * (stx - stp); } else if (stp > stx) { stpc = stpmax; } else { stpc = stpmin; } stpq = stp + dp / (dp - dx) * (stx - stp); if (brackt) { if (std::fabs(stpc - stp) < std::fabs(stpq - stp)) { stpf = stpc; } else { stpf = stpq; } if (stp > stx) { d1 = stp + (sty - stp) * .66; stpf = std::min(d1, stpf); } else { d1 = stp + (sty - stp) * .66; stpf = std::max(d1, stpf); } } else { if (std::fabs(stpc - stp) > std::fabs(stpq - stp)) { stpf = stpc; } else { stpf = stpq; } stpf = std::min(stpmax, stpf); stpf = std::max(stpmin, stpf); } } else { if (brackt) { theta = (fp - fy) * 3 / (sty - stp) + dy + dp; d1 = std::fabs(theta); d2 = std::fabs(dy); d1 = std::max(d1, d2); d2 = std::fabs(dp); s = std::max(d1, d2); d1 = theta / s; gamma = s * sqrt(d1 * d1 - dy / s * (dp / s)); if (stp > sty) { gamma = -gamma; } p = gamma - dp + theta; q = gamma - dp + gamma + dy; r = p / q; stpc = stp + r * (sty - stp); stpf = stpc; } else if (stp > stx) { stpf = stpmax; } else { stpf = stpmin; } } if (fp > fx) { sty = stp; fy = fp; dy = dp; } else { if (sgnd < 0.) { sty = stx; fy = fx; dy = dx; } stx = stp; fx = fp; dx = dp; } stp = stpf; } lsearch_step_t lsearch_morethuente_t::get(const lsearch_step_t& step0, const scalar_t t0) { const auto ftol = m_c1; const auto gtol = m_c2; const auto xtol = epsilon0<scalar_t>(); const auto stpmin = lsearch_step_t::minimum(); const auto stpmax = lsearch_step_t::maximum(); lsearch_step_t step = step0; step.update(t0); int stage = 1; bool brackt = false; scalar_t stp = t0, f = step.phi(), g = step.gphi(); scalar_t stmin = 0, stmax = stp + stp * 4; scalar_t width = stpmax - stpmin; scalar_t width1 = 2 * width; scalar_t finit = step.phi0(), ginit = step.gphi0(), gtest = ftol * ginit; scalar_t stx = 0, fx = finit, gx = ginit; scalar_t sty = 0, fy = finit, gy = ginit; for (auto i = 0; i < m_max_iterations; ++ i) { const auto ftest = finit + stp * gtest; if (stage == 1 && f <= ftest && g >= scalar_t(0)) { stage = 2; } // Check if further progress can be made if (brackt && (stp <= stmin || stp >= stmax)) return step; if (brackt && stmax - stmin <= xtol * stmax) return step; if (stp == stpmax && f <= ftest && g <= gtest) return step; if (stp == stpmin && (f > ftest || g >= gtest)) return step; // Check convergence if (f <= ftest && std::abs(g) <= gtol * (-ginit)) { return step; } // Interpolate the next point to evaluate if (stage == 1 && f <= fx && f > ftest) { auto fm = f - stp * gtest; auto fxm = fx - stx * gtest; auto fym = fy - sty * gtest; auto gm = g - gtest; auto gxm = gx - gtest; auto gym = gy - gtest; dcstep(stx, fxm, gxm, sty, fym, gym, stp, fm, gm, brackt, stmin, stmax); fx = fxm + stx * gtest; fy = fym + sty * gtest; gx = gxm + gtest; gy = gym + gtest; } else { dcstep(stx, fx, gx, sty, fy, gy, stp, f, g, brackt, stmin, stmax); } // Decide if a bisection step is needed if (brackt) { if (std::fabs(sty - stx) >= width1 * scalar_t(.66)) { stp = stx + (sty - stx) * scalar_t(0.5); } width1 = width; width = std::fabs(sty - stx); } // Set the minimum and maximum steps allowed for stp if (brackt) { stmin = std::min(stx, sty); stmax = std::max(stx, sty); } else { stmin = stp + (stp - stx) * scalar_t(1.1); stmax = stp + (stp - stx) * scalar_t(4.0); } // Force the step to be within the bounds stpmax and stpmin stp = nano::clamp(stp, stpmin, stpmax); // If further progress is not possible, let stp be the best point obtained during the search if ( (brackt && (stp <= stmin || stp >= stmax)) || (brackt && stmax - stmin <= xtol * stmax)) { stp = stx; } // Obtain another function and derivative step.update(stp); f = step.phi(); g = step.gphi(); } // NOK, give up return step0; } <commit_msg>explicitly use std::fabs<commit_after>#include "core/numeric.h" #include "lsearch_morethuente.h" using namespace nano; /// /// see dcstep routine in MINPACK-2 (see http://ftp.mcs.anl.gov/pub/MINPACK-2/csrch/) /// static void dcstep( scalar_t& stx, scalar_t& fx, scalar_t& dx, scalar_t& sty, scalar_t& fy, scalar_t& dy, scalar_t& stp, scalar_t& fp, scalar_t& dp, bool& brackt, const scalar_t stpmin, const scalar_t stpmax) { scalar_t stpc, stpq, stpf; scalar_t theta, d1, d2, d3, s, gamma, p, q, r; const auto sgnd = dp * (dx / std::fabs(dx)); if (fp > fx) { theta = (fx - fp) * 3 / (stp - stx) + dx + dp; d1 = std::fabs(theta); d2 = std::fabs(dx); d1 = std::max(d1, d2); d2 = std::fabs(dp); s = std::max(d1, d2); d1 = theta / s; gamma = s * std::sqrt(d1 * d1 - dx / s * (dp / s)); if (stp < stx) { gamma = -gamma; } p = gamma - dx + theta; q = gamma - dx + gamma + dp; r = p / q; stpc = stx + r * (stp - stx); stpq = stx + dx / ((fx - fp) / (stp - stx) + dx) / 2 * (stp - stx); if (std::fabs(stpc - stx) < std::fabs(stpq - stx)) { stpf = stpc; } else { stpf = stpc + (stpq - stpc) / 2; } brackt = true; } else if (sgnd < 0) { theta = (fx - fp) * 3 / (stp - stx) + dx + dp; d1 = std::fabs(theta); d2 = std::fabs(dx); d1 = std::max(d1, d2); d2 = std::fabs(dp); s = std::max(d1, d2); d1 = theta / s; gamma = s * std::sqrt(d1 * d1 - dx / s * (dp / s)); if (stp > stx) { gamma = -gamma; } p = gamma - dp + theta; q = gamma - dp + gamma + dx; r = p / q; stpc = stp + r * (stx - stp); stpq = stp + dp / (dp - dx) * (stx - stp); if (std::fabs(stpc - stp) > std::fabs(stpq - stp)) { stpf = stpc; } else { stpf = stpq; } brackt = true; } else if (std::fabs(dp) < std::fabs(dx)) { theta = (fx - fp) * 3 / (stp - stx) + dx + dp; d1 = std::fabs(theta); d2 = std::fabs(dx); d1 = std::max(d1, d2); d2 = std::fabs(dp); s = std::max(d1, d2); d3 = theta / s; d1 = 0; d2 = d3 * d3 - dx / s * (dp / s); gamma = s * std::sqrt(std::max(d1, d2)); if (stp > stx) { gamma = -gamma; } p = gamma - dp + theta; q = gamma + (dx - dp) + gamma; r = p / q; if (r < 0 && gamma != 0) { stpc = stp + r * (stx - stp); } else if (stp > stx) { stpc = stpmax; } else { stpc = stpmin; } stpq = stp + dp / (dp - dx) * (stx - stp); if (brackt) { if (std::fabs(stpc - stp) < std::fabs(stpq - stp)) { stpf = stpc; } else { stpf = stpq; } if (stp > stx) { d1 = stp + (sty - stp) * .66; stpf = std::min(d1, stpf); } else { d1 = stp + (sty - stp) * .66; stpf = std::max(d1, stpf); } } else { if (std::fabs(stpc - stp) > std::fabs(stpq - stp)) { stpf = stpc; } else { stpf = stpq; } stpf = std::min(stpmax, stpf); stpf = std::max(stpmin, stpf); } } else { if (brackt) { theta = (fp - fy) * 3 / (sty - stp) + dy + dp; d1 = std::fabs(theta); d2 = std::fabs(dy); d1 = std::max(d1, d2); d2 = std::fabs(dp); s = std::max(d1, d2); d1 = theta / s; gamma = s * sqrt(d1 * d1 - dy / s * (dp / s)); if (stp > sty) { gamma = -gamma; } p = gamma - dp + theta; q = gamma - dp + gamma + dy; r = p / q; stpc = stp + r * (sty - stp); stpf = stpc; } else if (stp > stx) { stpf = stpmax; } else { stpf = stpmin; } } if (fp > fx) { sty = stp; fy = fp; dy = dp; } else { if (sgnd < 0.) { sty = stx; fy = fx; dy = dx; } stx = stp; fx = fp; dx = dp; } stp = stpf; } lsearch_step_t lsearch_morethuente_t::get(const lsearch_step_t& step0, const scalar_t t0) { const auto ftol = m_c1; const auto gtol = m_c2; const auto xtol = epsilon0<scalar_t>(); const auto stpmin = lsearch_step_t::minimum(); const auto stpmax = lsearch_step_t::maximum(); lsearch_step_t step = step0; step.update(t0); int stage = 1; bool brackt = false; scalar_t stp = t0, f = step.phi(), g = step.gphi(); scalar_t stmin = 0, stmax = stp + stp * 4; scalar_t width = stpmax - stpmin; scalar_t width1 = 2 * width; scalar_t finit = step.phi0(), ginit = step.gphi0(), gtest = ftol * ginit; scalar_t stx = 0, fx = finit, gx = ginit; scalar_t sty = 0, fy = finit, gy = ginit; for (auto i = 0; i < m_max_iterations; ++ i) { const auto ftest = finit + stp * gtest; if (stage == 1 && f <= ftest && g >= scalar_t(0)) { stage = 2; } // Check if further progress can be made if (brackt && (stp <= stmin || stp >= stmax)) return step; if (brackt && stmax - stmin <= xtol * stmax) return step; if (stp == stpmax && f <= ftest && g <= gtest) return step; if (stp == stpmin && (f > ftest || g >= gtest)) return step; // Check convergence if (f <= ftest && std::fabs(g) <= gtol * (-ginit)) { return step; } // Interpolate the next point to evaluate if (stage == 1 && f <= fx && f > ftest) { auto fm = f - stp * gtest; auto fxm = fx - stx * gtest; auto fym = fy - sty * gtest; auto gm = g - gtest; auto gxm = gx - gtest; auto gym = gy - gtest; dcstep(stx, fxm, gxm, sty, fym, gym, stp, fm, gm, brackt, stmin, stmax); fx = fxm + stx * gtest; fy = fym + sty * gtest; gx = gxm + gtest; gy = gym + gtest; } else { dcstep(stx, fx, gx, sty, fy, gy, stp, f, g, brackt, stmin, stmax); } // Decide if a bisection step is needed if (brackt) { if (std::fabs(sty - stx) >= width1 * scalar_t(.66)) { stp = stx + (sty - stx) * scalar_t(0.5); } width1 = width; width = std::fabs(sty - stx); } // Set the minimum and maximum steps allowed for stp if (brackt) { stmin = std::min(stx, sty); stmax = std::max(stx, sty); } else { stmin = stp + (stp - stx) * scalar_t(1.1); stmax = stp + (stp - stx) * scalar_t(4.0); } // Force the step to be within the bounds stpmax and stpmin stp = nano::clamp(stp, stpmin, stpmax); // If further progress is not possible, let stp be the best point obtained during the search if ( (brackt && (stp <= stmin || stp >= stmax)) || (brackt && stmax - stmin <= xtol * stmax)) { stp = stx; } // Obtain another function and derivative step.update(stp); f = step.phi(); g = step.gphi(); } // NOK, give up return step0; } <|endoftext|>
<commit_before>// The libMesh Finite Element Library. // Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "libmesh/petsc_auto_fieldsplit.h" #ifdef LIBMESH_HAVE_PETSC #if !PETSC_VERSION_LESS_THAN(3,2,0) // Local includes #include "libmesh/dof_map.h" #include "libmesh/system.h" EXTERN_C_FOR_PETSC_BEGIN # include <petscksp.h> EXTERN_C_FOR_PETSC_END // C++ includes namespace { void indices_to_fieldsplit (const libMesh::Parallel::Communicator& comm, const std::vector<dof_id_type>& indices, PC my_pc, const std::string& field_name) { const PetscInt *idx = PETSC_NULL; if (!indices.empty()) idx = reinterpret_cast<const PetscInt*>(&indices[0]); IS is; int ierr = ISCreateLibMesh(comm.get(), indices.size(), idx, PETSC_COPY_VALUES, &is); CHKERRABORT(comm.get(), ierr); ierr = PCFieldSplitSetIS(my_pc, field_name.c_str(), is); CHKERRABORT(comm.get(), ierr); } } namespace libMesh { void petsc_auto_fieldsplit (PC my_pc, const System &sys) { std::string sys_prefix = "--solver_group_"; if (libMesh::on_command_line("--solver_system_names")) { sys_prefix = sys_prefix + sys.name() + "_"; } std::map<std::string, std::vector<dof_id_type> > group_indices; if (libMesh::on_command_line("--solver_variable_names")) { for (unsigned int v = 0; v != sys.n_vars(); ++v) { const std::string& var_name = sys.variable_name(v); std::vector<dof_id_type> var_idx; sys.get_dof_map().local_variable_indices (var_idx, sys.get_mesh(), v); std::string group_command = sys_prefix + var_name; if (libMesh::on_command_line (group_command)) { std::string group_name = libMesh::command_line_value (group_command, std::string()); std::vector<dof_id_type> &indices = group_indices[group_name]; const bool prior_indices = !indices.empty(); indices.insert(indices.end(), var_idx.begin(), var_idx.end()); if (prior_indices) std::sort(indices.begin(), indices.end()); } else { indices_to_fieldsplit (sys.comm(), var_idx, my_pc, var_name); } } } for (std::map<std::string, std::vector<dof_id_type> >::const_iterator i = group_indices.begin(); i != group_indices.end(); ++i) { indices_to_fieldsplit(sys.comm(), i->second, my_pc, i->first); } } } // namespace libMesh #else // #PETSC_VERSION < 3.2.0 void assign_solver_fieldsplit_names (PC my_pc, const System &sys) { if (libMesh::on_command_line("--solver_variable_names")) { libmesh_do_once( libMesh::out << "WARNING: libMesh does not support setting field splits" << std::endl << "with PETSc " << LIBMESH_DETECTED_PETSC_VERSION_MAJOR << '.' LIBMESH_DETECTED_PETSC_VERSION_MINOR << '.' LIBMESH_DETECTED_PETSC_VERSION_SUBMINOR << std::endl;); } } #endif // #PETSC_VERSION > 3.2.0 #endif // #ifdef LIBMESH_HAVE_PETSC <commit_msg>Use consistent name for old PETSc case<commit_after>// The libMesh Finite Element Library. // Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "libmesh/petsc_auto_fieldsplit.h" #ifdef LIBMESH_HAVE_PETSC #if !PETSC_VERSION_LESS_THAN(3,2,0) // Local includes #include "libmesh/dof_map.h" #include "libmesh/system.h" EXTERN_C_FOR_PETSC_BEGIN # include <petscksp.h> EXTERN_C_FOR_PETSC_END // C++ includes namespace { void indices_to_fieldsplit (const libMesh::Parallel::Communicator& comm, const std::vector<dof_id_type>& indices, PC my_pc, const std::string& field_name) { const PetscInt *idx = PETSC_NULL; if (!indices.empty()) idx = reinterpret_cast<const PetscInt*>(&indices[0]); IS is; int ierr = ISCreateLibMesh(comm.get(), indices.size(), idx, PETSC_COPY_VALUES, &is); CHKERRABORT(comm.get(), ierr); ierr = PCFieldSplitSetIS(my_pc, field_name.c_str(), is); CHKERRABORT(comm.get(), ierr); } } namespace libMesh { void petsc_auto_fieldsplit (PC my_pc, const System &sys) { std::string sys_prefix = "--solver_group_"; if (libMesh::on_command_line("--solver_system_names")) { sys_prefix = sys_prefix + sys.name() + "_"; } std::map<std::string, std::vector<dof_id_type> > group_indices; if (libMesh::on_command_line("--solver_variable_names")) { for (unsigned int v = 0; v != sys.n_vars(); ++v) { const std::string& var_name = sys.variable_name(v); std::vector<dof_id_type> var_idx; sys.get_dof_map().local_variable_indices (var_idx, sys.get_mesh(), v); std::string group_command = sys_prefix + var_name; if (libMesh::on_command_line (group_command)) { std::string group_name = libMesh::command_line_value (group_command, std::string()); std::vector<dof_id_type> &indices = group_indices[group_name]; const bool prior_indices = !indices.empty(); indices.insert(indices.end(), var_idx.begin(), var_idx.end()); if (prior_indices) std::sort(indices.begin(), indices.end()); } else { indices_to_fieldsplit (sys.comm(), var_idx, my_pc, var_name); } } } for (std::map<std::string, std::vector<dof_id_type> >::const_iterator i = group_indices.begin(); i != group_indices.end(); ++i) { indices_to_fieldsplit(sys.comm(), i->second, my_pc, i->first); } } } // namespace libMesh #else // #PETSC_VERSION < 3.2.0 void petsc_auto_fieldsplit (PC my_pc, const System &sys) { if (libMesh::on_command_line("--solver_variable_names")) { libmesh_do_once( libMesh::out << "WARNING: libMesh does not support setting field splits" << std::endl << "with PETSc " << LIBMESH_DETECTED_PETSC_VERSION_MAJOR << '.' LIBMESH_DETECTED_PETSC_VERSION_MINOR << '.' LIBMESH_DETECTED_PETSC_VERSION_SUBMINOR << std::endl;); } } #endif // #PETSC_VERSION > 3.2.0 #endif // #ifdef LIBMESH_HAVE_PETSC <|endoftext|>
<commit_before>#include "Distributions.hh" #include "conf.hh" #include "LinearAlgebra.hh" #include "HmmSet.hh" #include "str.hh" std::string stat_file; conf::Config config; HmmSet model; int main(int argc, char *argv[]) { try { config("usage: optimize [OPTION...]\n") ('h', "help", "", "", "display help") ('b', "base=BASENAME", "arg", "", "Previous base filename for model files") ('g', "gk=FILE", "arg", "", "Previous mixture base distributions") ('m', "mc=FILE", "arg", "", "Previous mixture coefficients for the states") ('p', "ph=FILE", "arg", "", "Previous HMM definitions") ('o', "out=FILE", "arg must", "", "output file for the coefficients") ('L', "list=LISTNAME", "arg", "", "file with one statistics file per line") ('\0', "subspace=FILE", "arg", "", "use an already initialized subspace") ('\0', "to-pcgmm", "", "", "convert Gaussians to have a subspace constraint on precisions") ('\0', "to-scgmm", "", "", "convert Gaussians to have an exponential subspace constraint") ('\0', "ml", "", "", "maximum likelihood estimation") ('\0', "mmi", "", "", "maximum mutual information estimation") ('\0', "minvar=FLOAT", "arg", "0.1", "minimum variance (default 0.1)") ('\0', "covsmooth", "arg", "0", "covariance smoothing (default 0.0)") ('\0', "C1=FLOAT", "arg", "1.0", "constant \"C1\" for MMI updates (default 1.0)") ('\0', "C2=FLOAT", "arg", "2.0", "constant \"C2\" for MMI updates (default 2.0)") ('\0', "ismooth=FLOAT", "arg", "0.0", "I-smoothing constant for discriminative training (default 0.0)") ('\0', "hcl_bfgs_cfg=FILE", "arg", "", "configuration file for HCL biconjugate gradient algorithm") ('\0', "hcl_line_cfg=FILE", "arg", "", "configuration file for HCL line search algorithm") ('B', "batch=INT", "arg", "0", "number of batch processes with the same recipe") ('I', "bindex=INT", "arg", "0", "batch process index") ('i', "info=INT", "arg", "0", "info level") ; config.default_parse(argc, argv); // Load the previous models if (config["base"].specified) model.read_all(config["base"].get_str()); else { if (config["gk"].specified) model.read_gk(config["gk"].get_str()); else throw std::string("At least --gk should be defined"); if (config["mc"].specified) model.read_mc(config["mc"].get_str()); if (config["ph"].specified) model.read_ph(config["ph"].get_str()); } // Linesearch for subspace models HCL_LineSearch_MT_d ls; if (config["hcl_line_cfg"].specified) ls.Parameters().Merge(config["hcl_line_cfg"].get_str().c_str()); // lmBFGS for subspace models HCL_UMin_lbfgs_d bfgs(&ls); if (config["hcl_bfgs_cfg"].specified) bfgs.Parameters().Merge(config["hcl_bfgs_cfg"].get_str().c_str()); model.set_hcl_optimization(&ls, &bfgs, config["hcl_line_cfg"].get_str(), config["hcl_bfgs_cfg"].get_str()); // Open the file for writing out the subspace coefficients std::string outfilename = config["out"].get_str(); std::ofstream outfile(outfilename.c_str()); if (!outfile) { fprintf(stderr, "Could not open %s for writing\n", config["out"].get_str().c_str()); exit(1); } // Optimize coefficients for this batch int start_pos = int(floor( (config["bindex"].get_int()-1) * model.num_pool_pdfs() / config["batch"].get_int() )); int end_pos = int(ceil( config["bindex"].get_int() * model.num_pool_pdfs() / config["batch"].get_int() )); // Print out some information if (config["info"].get_int()>0) std::cout << "Processing Gaussians " << start_pos+1 << "-" << end_pos << " of " << model.num_pool_pdfs() << std::endl; // Convert based on the statistics if (config["list"].specified) { if (!config["base"].specified && !(config["gk"].specified && config["mc"].specified && config["ph"].specified)) throw std::string("Must give either --base or all --gk, --mc and --ph"); if (config["mmi"].specified && config["ml"].specified) throw std::string("Don't define both --ml and --mmi!"); if (!config["mmi"].specified && !config["ml"].specified) throw std::string("Define either --ml or --mmi!"); // ML or MMI? if (config["ml"].specified) model.set_estimation_mode(PDF::ML); else model.set_estimation_mode(PDF::MMI); // Open the list of statistics files std::ifstream filelist(config["list"].get_str().c_str()); if (!filelist) { fprintf(stderr, "Could not open %s\n", config["list"].get_str().c_str()); exit(1); } // Set parameters for Gaussian estimation model.set_gaussian_parameters(config["minvar"].get_double(), config["covsmooth"].get_double(), config["C1"].get_double(), config["C2"].get_double(), config["ismooth"].get_double()); // Accumulate .gk statistics model.start_accumulating(); while (filelist >> stat_file && stat_file != " ") model.accumulate_gk_from_dump(stat_file+".gks"); for (int g=start_pos; g<end_pos; g++) { PrecisionConstrainedGaussian *pc = dynamic_cast< PrecisionConstrainedGaussian* > (model.get_pool_pdf(g)); SubspaceConstrainedGaussian *sc = dynamic_cast< SubspaceConstrainedGaussian* > (model.get_pool_pdf(g)); if (pc != NULL || sc != NULL) std::cout << "Training Gaussian: " << g+1 << "/" << model.num_pool_pdfs() << std::endl; try { if (pc != NULL) pc->estimate_parameters(config["minvar"].get_double(), config["covsmooth"].get_double(), config["C1"].get_double(), config["C2"].get_double(), config["ismooth"].get_double()); else if (sc != NULL) sc->estimate_parameters(config["minvar"].get_double(), config["covsmooth"].get_double(), config["C1"].get_double(), config["C2"].get_double(), config["ismooth"].get_double()); } catch (std::string errstr) { std::cout << "Warning: Gaussian number " << g << ": " << errstr << std::endl; } outfile << g; if (pc != NULL) { pc->write(outfile); } else if (sc != NULL) { sc->write(outfile); } outfile << std::endl; } } // Convert the old model else { if (!config["to-pcgmm"].specified && !config["to-scgmm"].specified) throw std::string("Define either --to-pcgmm or --to-scgmm if you want to convert an old model!"); if (config["to-pcgmm"].specified && config["to-scgmm"].specified) throw std::string("Don't define both --to-pcgmm and --to-scgmm if you want to convert an old model!"); if (!config["subspace"].specified) throw std::string("Please specify --subspace if you want to convert an old model"); PrecisionSubspace *ps; ExponentialSubspace *es; if (config["to-pcgmm"].specified) { ps = new PrecisionSubspace(); std::ifstream in(config["subspace"].get_str().c_str()); ps->read_subspace(in); ps->set_hcl_optimization(&ls, &bfgs, config["hcl_line_cfg"].get_str(), config["hcl_bfgs_cfg"].get_str()); in.close(); } else if (config["to-scgmm"].specified) { es = new ExponentialSubspace(); std::ifstream in(config["subspace"].get_str().c_str()); es->read_subspace(in); es->set_hcl_optimization(&ls, &bfgs, config["hcl_line_cfg"].get_str(), config["hcl_bfgs_cfg"].get_str()); in.close(); } Matrix covariance; Vector mean; for (int g=start_pos; g<end_pos; g++) { // Print Gaussian index if (config["info"].get_int()>0) std::cout << "Converting Gaussian: " << g+1 << "/" << model.num_pool_pdfs(); // Fetch source Gaussian Gaussian *source_gaussian = dynamic_cast< Gaussian* > (model.get_pool_pdf(g)); if (source_gaussian == NULL) continue; Gaussian *target_gaussian; if (config["to-pcgmm"].specified) target_gaussian = new PrecisionConstrainedGaussian(ps); else if (config["to-scgmm"].specified) target_gaussian = new SubspaceConstrainedGaussian(es); // Get the old Gaussian parameters source_gaussian->get_covariance(covariance); source_gaussian->get_mean(mean); // Set parameters target_gaussian->set_parameters(mean, covariance); // Print kullback-leibler if (config["info"].get_int() > 0) { std::cout << "\tkl-divergence: " << source_gaussian->kullback_leibler(*target_gaussian); std::cout << std::endl; } outfile << g; target_gaussian->write(outfile); outfile << std::endl; } outfile.close(); } } catch (std::exception &e) { fprintf(stderr, "exception: %s\n", e.what()); abort(); } catch (std::string &str) { fprintf(stderr, "exception: %s\n", str.c_str()); abort(); } } <commit_msg>compatible with new mmi/mpe estimation things<commit_after>#include "Distributions.hh" #include "conf.hh" #include "LinearAlgebra.hh" #include "HmmSet.hh" #include "str.hh" std::string stat_file; conf::Config config; HmmSet model; int main(int argc, char *argv[]) { PDF::EstimationMode mode; try { config("usage: optimize [OPTION...]\n") ('h', "help", "", "", "display help") ('b', "base=BASENAME", "arg", "", "Previous base filename for model files") ('g', "gk=FILE", "arg", "", "Previous mixture base distributions") ('m', "mc=FILE", "arg", "", "Previous mixture coefficients for the states") ('p', "ph=FILE", "arg", "", "Previous HMM definitions") ('o', "out=FILE", "arg must", "", "output file for the coefficients") ('L', "list=LISTNAME", "arg", "", "file with one statistics file per line") ('\0', "subspace=FILE", "arg", "", "use an already initialized subspace") ('\0', "to-pcgmm", "", "", "convert Gaussians to have a subspace constraint on precisions") ('\0', "to-scgmm", "", "", "convert Gaussians to have an exponential subspace constraint") ('\0', "ml", "", "", "maximum likelihood estimation") ('\0', "mmi", "", "", "maximum mutual information estimation") ('\0', "mpe", "", "", "minimum phone error estimation") ('\0', "minvar=FLOAT", "arg", "0.1", "minimum variance (default 0.1)") ('\0', "covsmooth", "arg", "0", "covariance smoothing (default 0.0)") ('\0', "C1=FLOAT", "arg", "1.0", "constant \"C1\" for MMI updates (default 1.0)") ('\0', "C2=FLOAT", "arg", "2.0", "constant \"C2\" for MMI updates (default 2.0)") ('\0', "mmi-ismooth=FLOAT", "arg", "0.0", "I-smoothing constant for MMI") ('\0', "mpe-ismooth=FLOAT", "arg", "0.0", "I-smoothing constant for MPE") ('\0', "mmi-prior", "", "", "Use MMI prior when I-smoothing MPE model") ('\0', "hcl_bfgs_cfg=FILE", "arg", "", "configuration file for HCL biconjugate gradient algorithm") ('\0', "hcl_line_cfg=FILE", "arg", "", "configuration file for HCL line search algorithm") ('B', "batch=INT", "arg", "0", "number of batch processes with the same recipe") ('I', "bindex=INT", "arg", "0", "batch process index") ('i', "info=INT", "arg", "0", "info level") ; config.default_parse(argc, argv); // Load the previous models if (config["base"].specified) model.read_all(config["base"].get_str()); else { if (config["gk"].specified) model.read_gk(config["gk"].get_str()); else throw std::string("At least --gk should be defined"); if (config["mc"].specified) model.read_mc(config["mc"].get_str()); if (config["ph"].specified) model.read_ph(config["ph"].get_str()); } // Linesearch for subspace models HCL_LineSearch_MT_d ls; if (config["hcl_line_cfg"].specified) ls.Parameters().Merge(config["hcl_line_cfg"].get_str().c_str()); // lmBFGS for subspace models HCL_UMin_lbfgs_d bfgs(&ls); if (config["hcl_bfgs_cfg"].specified) bfgs.Parameters().Merge(config["hcl_bfgs_cfg"].get_str().c_str()); model.set_hcl_optimization(&ls, &bfgs, config["hcl_line_cfg"].get_str(), config["hcl_bfgs_cfg"].get_str()); // Open the file for writing out the subspace coefficients std::string outfilename = config["out"].get_str(); std::ofstream outfile(outfilename.c_str()); if (!outfile) { fprintf(stderr, "Could not open %s for writing\n", config["out"].get_str().c_str()); exit(1); } // Optimize coefficients for this batch int start_pos = int(floor( (config["bindex"].get_int()-1) * model.num_pool_pdfs() / config["batch"].get_int() )); int end_pos = int(ceil( config["bindex"].get_int() * model.num_pool_pdfs() / config["batch"].get_int() )); // Print out some information if (config["info"].get_int()>0) std::cout << "Processing Gaussians " << start_pos+1 << "-" << end_pos << " of " << model.num_pool_pdfs() << std::endl; // Convert based on the statistics if (config["list"].specified) { if (!config["base"].specified && !(config["gk"].specified && config["mc"].specified && config["ph"].specified)) throw std::string("Must give either --base or all --gk, --mc and --ph"); int count = 0; if (config["ml"].specified) { count++; mode = PDF::ML_EST; } if (config["mmi"].specified) { count++; mode = PDF::MMI_EST; } if (config["mpe"].specified) { count++; mode = PDF::MPE_EST; } if (count != 1) throw std::string("Define exactly one of --ml, --mmi and --mpe!"); if (config["mmi-ismooth"].specified && (!config["mmi"].specified && !config["mmi-prior"].specified)) fprintf(stderr, "Warning: --mmi-ismooth ignored without --mmi or --mmi-prior\n"); if (config["mpe-ismooth"].specified && mode != PDF::MPE_EST) fprintf(stderr, "Warning: --mpe-ismooth ignored without --mpe\n"); if (config["mmi-prior"].specified) { if (mode == PDF::MPE_EST) mode = PDF::MPE_MMI_PRIOR_EST; else fprintf(stderr, "Warning: --mmi-prior ignored without --mpe\n"); } // Open the list of statistics files std::ifstream filelist(config["list"].get_str().c_str()); if (!filelist) { fprintf(stderr, "Could not open %s\n", config["list"].get_str().c_str()); exit(1); } // Set parameters for Gaussian estimation model.set_gaussian_parameters(config["minvar"].get_double(), config["covsmooth"].get_double(), config["C1"].get_double(), config["C2"].get_double(), config["mmi-ismooth"].get_double(), config["mpe-ismooth"].get_double()); // Accumulate .gk statistics model.start_accumulating(mode); while (filelist >> stat_file && stat_file != " ") model.accumulate_gk_from_dump(stat_file+".gks"); for (int g=start_pos; g<end_pos; g++) { PrecisionConstrainedGaussian *pc = dynamic_cast< PrecisionConstrainedGaussian* > (model.get_pool_pdf(g)); SubspaceConstrainedGaussian *sc = dynamic_cast< SubspaceConstrainedGaussian* > (model.get_pool_pdf(g)); if (pc != NULL || sc != NULL) std::cout << "Training Gaussian: " << g+1 << "/" << model.num_pool_pdfs() << std::endl; try { if (pc != NULL) pc->estimate_parameters(mode, config["minvar"].get_double(), config["covsmooth"].get_double(), config["C1"].get_double(), config["C2"].get_double(), false); else if (sc != NULL) sc->estimate_parameters(mode, config["minvar"].get_double(), config["covsmooth"].get_double(), config["C1"].get_double(), config["C2"].get_double(), false); } catch (std::string errstr) { std::cout << "Warning: Gaussian number " << g << ": " << errstr << std::endl; } outfile << g; if (pc != NULL) { pc->write(outfile); } else if (sc != NULL) { sc->write(outfile); } outfile << std::endl; } } // Convert the old model else { if (!config["to-pcgmm"].specified && !config["to-scgmm"].specified) throw std::string("Define either --to-pcgmm or --to-scgmm if you want to convert an old model!"); if (config["to-pcgmm"].specified && config["to-scgmm"].specified) throw std::string("Don't define both --to-pcgmm and --to-scgmm if you want to convert an old model!"); if (!config["subspace"].specified) throw std::string("Please specify --subspace if you want to convert an old model"); PrecisionSubspace *ps; ExponentialSubspace *es; if (config["to-pcgmm"].specified) { ps = new PrecisionSubspace(); std::ifstream in(config["subspace"].get_str().c_str()); ps->read_subspace(in); ps->set_hcl_optimization(&ls, &bfgs, config["hcl_line_cfg"].get_str(), config["hcl_bfgs_cfg"].get_str()); in.close(); } else if (config["to-scgmm"].specified) { es = new ExponentialSubspace(); std::ifstream in(config["subspace"].get_str().c_str()); es->read_subspace(in); es->set_hcl_optimization(&ls, &bfgs, config["hcl_line_cfg"].get_str(), config["hcl_bfgs_cfg"].get_str()); in.close(); } Matrix covariance; Vector mean; for (int g=start_pos; g<end_pos; g++) { // Print Gaussian index if (config["info"].get_int()>0) std::cout << "Converting Gaussian: " << g+1 << "/" << model.num_pool_pdfs(); // Fetch source Gaussian Gaussian *source_gaussian = dynamic_cast< Gaussian* > (model.get_pool_pdf(g)); if (source_gaussian == NULL) continue; Gaussian *target_gaussian; if (config["to-pcgmm"].specified) target_gaussian = new PrecisionConstrainedGaussian(ps); else if (config["to-scgmm"].specified) target_gaussian = new SubspaceConstrainedGaussian(es); // Get the old Gaussian parameters source_gaussian->get_covariance(covariance); source_gaussian->get_mean(mean); // Set parameters target_gaussian->set_parameters(mean, covariance); // Print kullback-leibler if (config["info"].get_int() > 0) { std::cout << "\tkl-divergence: " << source_gaussian->kullback_leibler(*target_gaussian); std::cout << std::endl; } outfile << g; target_gaussian->write(outfile); outfile << std::endl; } outfile.close(); } } catch (std::exception &e) { fprintf(stderr, "exception: %s\n", e.what()); abort(); } catch (std::string &str) { fprintf(stderr, "exception: %s\n", str.c_str()); abort(); } } <|endoftext|>
<commit_before>// gampcompare_main.cpp: defines a GAMP to GAM annotation function #include <omp.h> #include <unistd.h> #include <getopt.h> #include <string> #include <vector> #include <set> #include <subcommand.hpp> #include "../algorithms/alignment_path_offsets.hpp" #include "../multipath_alignment.hpp" #include "../alignment.hpp" #include "../vg.hpp" #include <vg/io/stream.hpp> #include <vg/io/vpkg.hpp> #include <bdsg/overlays/overlay_helper.hpp> using namespace std; using namespace vg; using namespace vg::subcommand; void help_gampcompare(char** argv) { cerr << "usage: " << argv[0] << " gampcompare [options] alngraph.xg aln.gamp truth.gam > output.tsv" << endl << endl << "options:" << endl << " -G, --gam alignments are in GAM format rather than GAMP" << endl << " -r, --range N distance within which to consider reads correct [100]" << endl << " -a, --aligner STR aligner name for TSV output [\"vg\"]" << endl << " -d, --distance report minimum distance along a path rather than correctness" << endl << " -t, --threads N number of threads to use [1]" << endl; } int main_gampcompare(int argc, char** argv) { if (argc == 2) { help_gampcompare(argv); exit(1); } int threads = 1; int64_t range = 100; string aligner_name = "vg"; int buffer_size = 10000; bool gam_input = false; bool report_distance = false; int c; optind = 2; while (true) { static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"range", required_argument, 0, 'r'}, {"gam", no_argument, 0, 'G'}, {"aligner", required_argument, 0, 'a'}, {"distance", required_argument, 0, 'd'}, {"threads", required_argument, 0, 't'}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long (argc, argv, "hr:a:t:Gd", long_options, &option_index); // Detect the end of the options. if (c == -1) break; switch (c) { case 'r': range = parse<int>(optarg); break; case 'a': aligner_name = optarg; break; case 'd': report_distance = true; break; case 't': threads = parse<int>(optarg); omp_set_num_threads(threads); break; case 'G': gam_input = true; break; case 'h': case '?': help_gampcompare(argv); exit(1); break; default: abort (); } } // We need to read the second argument first, so we can't use get_input_file with its free error checking. string graph_file_name = get_input_file_name(optind, argc, argv); string test_file_name = get_input_file_name(optind, argc, argv); string truth_file_name = get_input_file_name(optind, argc, argv); if ((truth_file_name == "-") + (test_file_name == "-") + (graph_file_name == "-") > 1) { cerr << "error[vg gampcompare]: Standard input can only be used for one input file" << endl; exit(1); } // Load the graph we mapped to unique_ptr<PathHandleGraph> path_handle_graph; if (graph_file_name == "-") { path_handle_graph = vg::io::VPKG::load_one<PathHandleGraph>(std::cin); } else { ifstream graph_stream(graph_file_name); if (!graph_stream) { cerr << "error:[vg mpmap] Cannot open graph file " << graph_file_name << endl; exit(1); } path_handle_graph = vg::io::VPKG::load_one<PathHandleGraph>(graph_stream); } bdsg::PathPositionOverlayHelper overlay_helper; PathPositionHandleGraph* path_position_handle_graph = overlay_helper.apply(path_handle_graph.get()); // We will collect all the truth positions string_hash_map<string, map<string ,vector<pair<size_t, bool> > > > true_positions; function<void(Alignment&)> record_truth = [&true_positions](Alignment& aln) { auto val = alignment_refpos_to_path_offsets(aln); #pragma omp critical (truth_table) true_positions[move(*aln.mutable_name())] = move(val); }; if (truth_file_name == "-") { // Read truth fropm standard input, if it looks good. if (!std::cin) { cerr << "error[vg gampcompare]: Unable to read standard input when looking for true reads" << endl; exit(1); } vg::io::for_each_parallel(std::cin, record_truth); } else { // Read truth from this file, if it looks good. ifstream truth_file_in(truth_file_name); if (!truth_file_in) { cerr << "error[vg gampcompare]: Unable to read " << truth_file_name << " when looking for true reads" << endl; exit(1); } vg::io::for_each_parallel(truth_file_in, record_truth); } // A buffer we use for the TSV output vector<vector<tuple<int64_t, int64_t, string>>> buffers(get_thread_count()); // We have an output function to dump all the reads in the text buffer in TSV auto flush_buffer = [&](vector<tuple<int64_t, int64_t, string>>& buffer) { // We print exactly one header line. static bool header_printed = false; // Output TSV to standard out in the format plot-qq.R needs. if (!header_printed) { // It needs a header if (report_distance) { cout << "distance"; } else { cout << "correct"; } cout << "\tmq\taligner\tread" << endl; header_printed = true; } for (auto& result : buffer) { // Dump each alignment if (report_distance) { cout << get<0>(result); } else { cout << (get<0>(result) <= range); } cout << '\t' << get<1>(result) << '\t' << aligner_name << '\t' << get<2>(result) << endl; } buffer.clear(); }; // We want to count correct reads vector<size_t> correct_counts(get_thread_count(), 0); // This function annotates every read with distance and correctness, and batch-outputs them. function<void(MultipathAlignment&)> evaluate_correctness = [&](MultipathAlignment& proto_mp_aln) { // check the multipath mapping for correctness int64_t abs_dist = numeric_limits<int64_t>::max(); auto f = true_positions.find(proto_mp_aln.name()); if (f != true_positions.end()) { multipath_alignment_t mp_aln; from_proto_multipath_alignment(proto_mp_aln, mp_aln); auto& true_positions = f->second; auto mapped_positions = algorithms::multipath_alignment_path_offsets(*path_position_handle_graph, mp_aln); for (auto it = true_positions.begin(); it != true_positions.end(); ++it) { // TODO: it really should be possible to do this with only path handles instead of names auto path_handle = path_position_handle_graph->get_path_handle(it->first); if (mapped_positions.count(path_handle)) { // the true and mapped positions share this path auto& path_true_positions = it->second; auto& path_mapped_positions = mapped_positions[path_handle]; // check all pairs of positions for (size_t i = 0; i < path_true_positions.size(); ++i) { for (size_t j = 0; j < path_mapped_positions.size(); ++j) { if (path_true_positions[i].second == path_mapped_positions[j].second) { // there is a pair of positions on the same strand of the same path abs_dist = min<int64_t>(abs_dist, path_true_positions[i].first - path_mapped_positions[j].first); } } } } } } if (abs_dist <= range) { correct_counts[omp_get_thread_num()]++; } // put the result on the IO buffer auto& buffer = buffers[omp_get_thread_num()]; buffer.emplace_back(abs_dist, proto_mp_aln.mapping_quality(), move(*proto_mp_aln.mutable_name())); if (buffer.size() > buffer_size) { #pragma omp critical flush_buffer(buffer); } }; function<void(Alignment&)> evaluate_gam_correctness = [&](Alignment& aln) { // TODO: kinda ugly, but whatever multipath_alignment_t mp_aln; to_multipath_alignment(aln, mp_aln); MultipathAlignment proto_mp_aln; to_proto_multipath_alignment(mp_aln, proto_mp_aln); // we need the name to survive transit in multipath_alignment_t proto_mp_aln.set_name(aln.name()); // now use the same evaluation function evaluate_correctness(proto_mp_aln); }; if (test_file_name == "-") { if (!std::cin) { cerr << "error[vg gampcompare]: Unable to read standard input when looking for mapped reads" << endl; exit(1); } if (gam_input) { vg::io::for_each_parallel(std::cin, evaluate_gam_correctness); } else { vg::io::for_each_parallel(std::cin, evaluate_correctness); } } else { ifstream test_file_in(test_file_name); if (!test_file_in) { cerr << "error[vg gampcompare]: Unable to read " << test_file_name << " when looking for mapped reads" << endl; exit(1); } if (gam_input) { vg::io::for_each_parallel(test_file_in, evaluate_gam_correctness); } else { vg::io::for_each_parallel(test_file_in, evaluate_correctness); } } // Empty out whatever's in the buffers at the end. for (auto& buffer : buffers) { flush_buffer(buffer); } // We are flagging reads correct/incorrect. So report the total correct. size_t total_correct = 0; for (auto& count : correct_counts) { total_correct += count; } cerr << total_correct << " reads correct" << endl; return 0; } // Register subcommand static Subcommand vg_gampcompare("gampcompare", "compare multipath alignment positions", main_gampcompare); <commit_msg>fix absolute distance in gampcompare<commit_after>// gampcompare_main.cpp: defines a GAMP to GAM annotation function #include <omp.h> #include <unistd.h> #include <getopt.h> #include <string> #include <vector> #include <set> #include <subcommand.hpp> #include "../algorithms/alignment_path_offsets.hpp" #include "../multipath_alignment.hpp" #include "../alignment.hpp" #include "../vg.hpp" #include <vg/io/stream.hpp> #include <vg/io/vpkg.hpp> #include <bdsg/overlays/overlay_helper.hpp> using namespace std; using namespace vg; using namespace vg::subcommand; void help_gampcompare(char** argv) { cerr << "usage: " << argv[0] << " gampcompare [options] alngraph.xg aln.gamp truth.gam > output.tsv" << endl << endl << "options:" << endl << " -G, --gam alignments are in GAM format rather than GAMP" << endl << " -r, --range N distance within which to consider reads correct [100]" << endl << " -a, --aligner STR aligner name for TSV output [\"vg\"]" << endl << " -d, --distance report minimum distance along a path rather than correctness" << endl << " -t, --threads N number of threads to use [1]" << endl; } int main_gampcompare(int argc, char** argv) { if (argc == 2) { help_gampcompare(argv); exit(1); } int threads = 1; int64_t range = 100; string aligner_name = "vg"; int buffer_size = 10000; bool gam_input = false; bool report_distance = false; int c; optind = 2; while (true) { static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"range", required_argument, 0, 'r'}, {"gam", no_argument, 0, 'G'}, {"aligner", required_argument, 0, 'a'}, {"distance", required_argument, 0, 'd'}, {"threads", required_argument, 0, 't'}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long (argc, argv, "hr:a:t:Gd", long_options, &option_index); // Detect the end of the options. if (c == -1) break; switch (c) { case 'r': range = parse<int>(optarg); break; case 'a': aligner_name = optarg; break; case 'd': report_distance = true; break; case 't': threads = parse<int>(optarg); omp_set_num_threads(threads); break; case 'G': gam_input = true; break; case 'h': case '?': help_gampcompare(argv); exit(1); break; default: abort (); } } // We need to read the second argument first, so we can't use get_input_file with its free error checking. string graph_file_name = get_input_file_name(optind, argc, argv); string test_file_name = get_input_file_name(optind, argc, argv); string truth_file_name = get_input_file_name(optind, argc, argv); if ((truth_file_name == "-") + (test_file_name == "-") + (graph_file_name == "-") > 1) { cerr << "error[vg gampcompare]: Standard input can only be used for one input file" << endl; exit(1); } // Load the graph we mapped to unique_ptr<PathHandleGraph> path_handle_graph; if (graph_file_name == "-") { path_handle_graph = vg::io::VPKG::load_one<PathHandleGraph>(std::cin); } else { ifstream graph_stream(graph_file_name); if (!graph_stream) { cerr << "error:[vg mpmap] Cannot open graph file " << graph_file_name << endl; exit(1); } path_handle_graph = vg::io::VPKG::load_one<PathHandleGraph>(graph_stream); } bdsg::PathPositionOverlayHelper overlay_helper; PathPositionHandleGraph* path_position_handle_graph = overlay_helper.apply(path_handle_graph.get()); // We will collect all the truth positions string_hash_map<string, map<string ,vector<pair<size_t, bool> > > > true_positions; function<void(Alignment&)> record_truth = [&true_positions](Alignment& aln) { auto val = alignment_refpos_to_path_offsets(aln); #pragma omp critical (truth_table) true_positions[move(*aln.mutable_name())] = move(val); }; if (truth_file_name == "-") { // Read truth fropm standard input, if it looks good. if (!std::cin) { cerr << "error[vg gampcompare]: Unable to read standard input when looking for true reads" << endl; exit(1); } vg::io::for_each_parallel(std::cin, record_truth); } else { // Read truth from this file, if it looks good. ifstream truth_file_in(truth_file_name); if (!truth_file_in) { cerr << "error[vg gampcompare]: Unable to read " << truth_file_name << " when looking for true reads" << endl; exit(1); } vg::io::for_each_parallel(truth_file_in, record_truth); } // A buffer we use for the TSV output vector<vector<tuple<int64_t, int64_t, string>>> buffers(get_thread_count()); // We have an output function to dump all the reads in the text buffer in TSV auto flush_buffer = [&](vector<tuple<int64_t, int64_t, string>>& buffer) { // We print exactly one header line. static bool header_printed = false; // Output TSV to standard out in the format plot-qq.R needs. if (!header_printed) { // It needs a header if (report_distance) { cout << "distance"; } else { cout << "correct"; } cout << "\tmq\taligner\tread" << endl; header_printed = true; } for (auto& result : buffer) { // Dump each alignment if (report_distance) { cout << get<0>(result); } else { cout << (get<0>(result) <= range); } cout << '\t' << get<1>(result) << '\t' << aligner_name << '\t' << get<2>(result) << endl; } buffer.clear(); }; // We want to count correct reads vector<size_t> correct_counts(get_thread_count(), 0); // This function annotates every read with distance and correctness, and batch-outputs them. function<void(MultipathAlignment&)> evaluate_correctness = [&](MultipathAlignment& proto_mp_aln) { // check the multipath mapping for correctness int64_t abs_dist = numeric_limits<int64_t>::max(); auto f = true_positions.find(proto_mp_aln.name()); if (f != true_positions.end()) { multipath_alignment_t mp_aln; from_proto_multipath_alignment(proto_mp_aln, mp_aln); auto& true_positions = f->second; auto mapped_positions = algorithms::multipath_alignment_path_offsets(*path_position_handle_graph, mp_aln); for (auto it = true_positions.begin(); it != true_positions.end(); ++it) { // TODO: it really should be possible to do this with only path handles instead of names auto path_handle = path_position_handle_graph->get_path_handle(it->first); if (mapped_positions.count(path_handle)) { // the true and mapped positions share this path auto& path_true_positions = it->second; auto& path_mapped_positions = mapped_positions[path_handle]; // check all pairs of positions for (size_t i = 0; i < path_true_positions.size(); ++i) { for (size_t j = 0; j < path_mapped_positions.size(); ++j) { if (path_true_positions[i].second == path_mapped_positions[j].second) { // there is a pair of positions on the same strand of the same path abs_dist = min<int64_t>(abs_dist, abs<int64_t>(path_true_positions[i].first - path_mapped_positions[j].first)); } } } } } } if (abs_dist <= range) { correct_counts[omp_get_thread_num()]++; } // put the result on the IO buffer auto& buffer = buffers[omp_get_thread_num()]; buffer.emplace_back(abs_dist, proto_mp_aln.mapping_quality(), move(*proto_mp_aln.mutable_name())); if (buffer.size() > buffer_size) { #pragma omp critical flush_buffer(buffer); } }; function<void(Alignment&)> evaluate_gam_correctness = [&](Alignment& aln) { // TODO: kinda ugly, but whatever multipath_alignment_t mp_aln; to_multipath_alignment(aln, mp_aln); MultipathAlignment proto_mp_aln; to_proto_multipath_alignment(mp_aln, proto_mp_aln); // we need the name to survive transit in multipath_alignment_t proto_mp_aln.set_name(aln.name()); // now use the same evaluation function evaluate_correctness(proto_mp_aln); }; if (test_file_name == "-") { if (!std::cin) { cerr << "error[vg gampcompare]: Unable to read standard input when looking for mapped reads" << endl; exit(1); } if (gam_input) { vg::io::for_each_parallel(std::cin, evaluate_gam_correctness); } else { vg::io::for_each_parallel(std::cin, evaluate_correctness); } } else { ifstream test_file_in(test_file_name); if (!test_file_in) { cerr << "error[vg gampcompare]: Unable to read " << test_file_name << " when looking for mapped reads" << endl; exit(1); } if (gam_input) { vg::io::for_each_parallel(test_file_in, evaluate_gam_correctness); } else { vg::io::for_each_parallel(test_file_in, evaluate_correctness); } } // Empty out whatever's in the buffers at the end. for (auto& buffer : buffers) { flush_buffer(buffer); } // We are flagging reads correct/incorrect. So report the total correct. size_t total_correct = 0; for (auto& count : correct_counts) { total_correct += count; } cerr << total_correct << " reads correct" << endl; return 0; } // Register subcommand static Subcommand vg_gampcompare("gampcompare", "compare multipath alignment positions", main_gampcompare); <|endoftext|>
<commit_before>/* * Copyright 2017-2019 Baidu 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif extern "C" { #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" } #include <sstream> #include <fstream> #include "openrasp_v8.h" #include "openrasp_hook.h" #include "openrasp_ini.h" #include "agent/shared_config_manager.h" #ifdef HAVE_OPENRASP_REMOTE_MANAGER #include "agent/openrasp_agent_manager.h" #endif namespace openrasp { openrasp_v8_process_globals process_globals; } // namespace openrasp using namespace openrasp; ZEND_DECLARE_MODULE_GLOBALS(openrasp_v8) PHP_GINIT_FUNCTION(openrasp_v8) { #ifdef ZTS new (openrasp_v8_globals) _zend_openrasp_v8_globals; #endif } PHP_GSHUTDOWN_FUNCTION(openrasp_v8) { if (openrasp_v8_globals->isolate) { openrasp_v8_globals->isolate->Dispose(); openrasp_v8_globals->isolate = nullptr; } #ifdef ZTS openrasp_v8_globals->~_zend_openrasp_v8_globals(); #endif } PHP_MINIT_FUNCTION(openrasp_v8) { ZEND_INIT_MODULE_GLOBALS(openrasp_v8, PHP_GINIT(openrasp_v8), PHP_GSHUTDOWN(openrasp_v8)); // It can be called multiple times, // but intern code initializes v8 only once v8::V8::Initialize(); #ifdef HAVE_OPENRASP_REMOTE_MANAGER if (openrasp_ini.remote_management_enable && oam != nullptr) { return SUCCESS; } #endif load_plugins(); if (!process_globals.snapshot_blob) { Platform::Initialize(); Snapshot *snapshot = new Snapshot(process_globals.plugin_config, process_globals.plugin_src_list); if (!snapshot->IsOk()) { delete snapshot; openrasp_error(LEVEL_WARNING, PLUGIN_ERROR, _("Fail to initialize builtin js code.")); } else { process_globals.snapshot_blob = snapshot; std::map<OpenRASPCheckType, OpenRASPActionType> type_action_map; std::map<std::string, std::string> buildin_action_map = check_type_transfer->get_buildin_action_map(); Isolate *isolate = Isolate::New(snapshot); extract_buildin_action(isolate, buildin_action_map); isolate->Dispose(); for (auto iter = buildin_action_map.begin(); iter != buildin_action_map.end(); iter++) { type_action_map.insert({check_type_transfer->name_to_type(iter->first), string_to_action(iter->second)}); } openrasp::scm->set_buildin_check_action(type_action_map); } Platform::Shutdown(); } return SUCCESS; } PHP_MSHUTDOWN_FUNCTION(openrasp_v8) { ZEND_SHUTDOWN_MODULE_GLOBALS(openrasp_v8, PHP_GSHUTDOWN(openrasp_v8)); // Disposing v8 is permanent, it cannot be reinitialized, // it should generally not be necessary to dispose v8 before exiting a process, // so skip this step for module graceful reload // v8::V8::Dispose(); Platform::Shutdown(); delete process_globals.snapshot_blob; process_globals.snapshot_blob = nullptr; return SUCCESS; } PHP_RINIT_FUNCTION(openrasp_v8) { #ifdef HAVE_OPENRASP_REMOTE_MANAGER if (openrasp_ini.remote_management_enable && oam != nullptr) { uint64_t timestamp = oam->get_plugin_update_timestamp(); if (timestamp > 0 && (!process_globals.snapshot_blob || process_globals.snapshot_blob->IsExpired(timestamp))) { std::unique_lock<std::mutex> lock(process_globals.mtx, std::try_to_lock); if (lock && (!process_globals.snapshot_blob || process_globals.snapshot_blob->IsExpired(timestamp))) { std::string filename = std::string(openrasp_ini.root_dir) + DEFAULT_SLASH + std::string("snapshot.dat"); Snapshot *blob = new Snapshot(filename, timestamp); if (!blob->IsOk()) { delete blob; } else { delete process_globals.snapshot_blob; process_globals.snapshot_blob = blob; OPENRASP_HOOK_G(lru).clear(); } } } } #endif if (process_globals.snapshot_blob) { if (!OPENRASP_V8_G(isolate) || OPENRASP_V8_G(isolate)->IsExpired(process_globals.snapshot_blob->timestamp)) { std::unique_lock<std::mutex> lock(process_globals.mtx, std::try_to_lock); if (lock) { if (OPENRASP_V8_G(isolate)) { OPENRASP_V8_G(isolate)->Dispose(); } Platform::Initialize(); OPENRASP_V8_G(isolate) = Isolate::New(process_globals.snapshot_blob); OPENRASP_G(config).updateAlgorithmConfig(); } } } if (OPENRASP_V8_G(isolate)) { OPENRASP_V8_G(isolate)->GetData()->request_context.Reset(); } return SUCCESS; } <commit_msg>[PHP7]Isolate constructor timestamp<commit_after>/* * Copyright 2017-2019 Baidu 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif extern "C" { #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" } #include <sstream> #include <fstream> #include "openrasp_v8.h" #include "openrasp_hook.h" #include "openrasp_ini.h" #include "agent/shared_config_manager.h" #ifdef HAVE_OPENRASP_REMOTE_MANAGER #include "agent/openrasp_agent_manager.h" #endif namespace openrasp { openrasp_v8_process_globals process_globals; } // namespace openrasp using namespace openrasp; ZEND_DECLARE_MODULE_GLOBALS(openrasp_v8) PHP_GINIT_FUNCTION(openrasp_v8) { #ifdef ZTS new (openrasp_v8_globals) _zend_openrasp_v8_globals; #endif } PHP_GSHUTDOWN_FUNCTION(openrasp_v8) { if (openrasp_v8_globals->isolate) { openrasp_v8_globals->isolate->Dispose(); openrasp_v8_globals->isolate = nullptr; } #ifdef ZTS openrasp_v8_globals->~_zend_openrasp_v8_globals(); #endif } PHP_MINIT_FUNCTION(openrasp_v8) { ZEND_INIT_MODULE_GLOBALS(openrasp_v8, PHP_GINIT(openrasp_v8), PHP_GSHUTDOWN(openrasp_v8)); // It can be called multiple times, // but intern code initializes v8 only once v8::V8::Initialize(); #ifdef HAVE_OPENRASP_REMOTE_MANAGER if (openrasp_ini.remote_management_enable && oam != nullptr) { return SUCCESS; } #endif load_plugins(); if (!process_globals.snapshot_blob) { Platform::Initialize(); Snapshot *snapshot = new Snapshot(process_globals.plugin_config, process_globals.plugin_src_list); if (!snapshot->IsOk()) { delete snapshot; openrasp_error(LEVEL_WARNING, PLUGIN_ERROR, _("Fail to initialize builtin js code.")); } else { process_globals.snapshot_blob = snapshot; std::map<OpenRASPCheckType, OpenRASPActionType> type_action_map; std::map<std::string, std::string> buildin_action_map = check_type_transfer->get_buildin_action_map(); Isolate *isolate = Isolate::New(snapshot); extract_buildin_action(isolate, buildin_action_map); isolate->Dispose(); for (auto iter = buildin_action_map.begin(); iter != buildin_action_map.end(); iter++) { type_action_map.insert({check_type_transfer->name_to_type(iter->first), string_to_action(iter->second)}); } openrasp::scm->set_buildin_check_action(type_action_map); } Platform::Shutdown(); } return SUCCESS; } PHP_MSHUTDOWN_FUNCTION(openrasp_v8) { ZEND_SHUTDOWN_MODULE_GLOBALS(openrasp_v8, PHP_GSHUTDOWN(openrasp_v8)); // Disposing v8 is permanent, it cannot be reinitialized, // it should generally not be necessary to dispose v8 before exiting a process, // so skip this step for module graceful reload // v8::V8::Dispose(); Platform::Shutdown(); delete process_globals.snapshot_blob; process_globals.snapshot_blob = nullptr; return SUCCESS; } PHP_RINIT_FUNCTION(openrasp_v8) { #ifdef HAVE_OPENRASP_REMOTE_MANAGER if (openrasp_ini.remote_management_enable && oam != nullptr) { uint64_t timestamp = oam->get_plugin_update_timestamp(); if (timestamp > 0 && (!process_globals.snapshot_blob || process_globals.snapshot_blob->IsExpired(timestamp))) { std::unique_lock<std::mutex> lock(process_globals.mtx, std::try_to_lock); if (lock && (!process_globals.snapshot_blob || process_globals.snapshot_blob->IsExpired(timestamp))) { std::string filename = std::string(openrasp_ini.root_dir) + DEFAULT_SLASH + std::string("snapshot.dat"); Snapshot *blob = new Snapshot(filename, timestamp); if (!blob->IsOk()) { delete blob; } else { delete process_globals.snapshot_blob; process_globals.snapshot_blob = blob; OPENRASP_HOOK_G(lru).clear(); } } } } #endif if (process_globals.snapshot_blob) { if (!OPENRASP_V8_G(isolate) || OPENRASP_V8_G(isolate)->IsExpired(process_globals.snapshot_blob->timestamp)) { std::unique_lock<std::mutex> lock(process_globals.mtx, std::try_to_lock); if (lock) { if (OPENRASP_V8_G(isolate)) { OPENRASP_V8_G(isolate)->Dispose(); } Platform::Initialize(); OPENRASP_V8_G(isolate) = Isolate::New(process_globals.snapshot_blob, process_globals.snapshot_blob->timestamp); OPENRASP_G(config).updateAlgorithmConfig(); } } } if (OPENRASP_V8_G(isolate)) { OPENRASP_V8_G(isolate)->GetData()->request_context.Reset(); } return SUCCESS; } <|endoftext|>
<commit_before>#include "IndependentMultiRobotPathPlanner.hpp" #include "RobotConstraints.hpp" using namespace std; namespace Planning { std::map<int, std::unique_ptr<Path>> IndependentMultiRobotPathPlanner::run( std::map<int, PlanRequest> requests) { std::map<int, std::unique_ptr<Path>> paths; std::map<int, shared_ptr<Geometry2d::Circle>> staticRobotObstacles; std::vector<int> staticRequests; std::vector<int> dynamicRequests; for (auto& entry : requests) { int shell = entry.first; PlanRequest& request = entry.second; auto& prevPlanner = _planners[shell]; // Make sure we have the right planner. If it changes from last time, // delete the old path. if (!prevPlanner || prevPlanner->commandType() != request.motionCommand->getCommandType()) { _planners[shell] = PlannerForCommandType(request.motionCommand->getCommandType()); request.prevPath = nullptr; } if (_planners[shell]->canHandleDynamic()) { dynamicRequests.push_back(shell); } else { staticRequests.push_back(shell); } staticRobotObstacles[shell] = std::make_shared<Geometry2d::Circle>( request.start.pos, Robot_Radius); } // Sorts descending so that higher priorities are first auto comparator = [&](int& lhs, int& rhs) { return requests.at(lhs).priority > requests.at(rhs).priority; }; std::sort(std::begin(staticRequests), std::end(staticRequests), comparator); std::sort(std::begin(dynamicRequests), std::end(dynamicRequests), comparator); std::vector<int> inOrderRequests; inOrderRequests.insert(std::end(inOrderRequests), std::begin(staticRequests), std::end(staticRequests)); inOrderRequests.insert(std::end(inOrderRequests), std::begin(dynamicRequests), std::end(dynamicRequests)); vector<DynamicObstacle> ourRobotsObstacles; for (int shell : inOrderRequests) { PlanRequest& request = requests.at(shell); if (_planners[shell]->canHandleDynamic()) { std::copy(std::begin(ourRobotsObstacles), std::end(ourRobotsObstacles), std::back_inserter(request.dynamicObstacles)); } else { for (auto& entry : staticRobotObstacles) { if (entry.first != shell) { request.obstacles.add(entry.second); } } SingleRobotPathPlanner::allDynamicToStatic( request.obstacles, request.dynamicObstacles); request.dynamicObstacles = std::vector<DynamicObstacle>(); } paths[shell] = _planners[shell]->run(request); // Add our generated path to our list of our Robot Obstacles ourRobotsObstacles.push_back(DynamicObstacle( request.start.pos, Robot_Radius, paths[shell].get())); } return paths; } } // namespace Planning <commit_msg>Make sure theres no nullptrs<commit_after>#include "IndependentMultiRobotPathPlanner.hpp" #include "RobotConstraints.hpp" #include "InterpolatedPath.hpp" using namespace std; namespace Planning { std::map<int, std::unique_ptr<Path>> IndependentMultiRobotPathPlanner::run( std::map<int, PlanRequest> requests) { std::map<int, std::unique_ptr<Path>> paths; std::map<int, shared_ptr<Geometry2d::Circle>> staticRobotObstacles; std::vector<int> staticRequests; std::vector<int> dynamicRequests; for (auto& entry : requests) { int shell = entry.first; PlanRequest& request = entry.second; auto& prevPlanner = _planners[shell]; // Make sure we have the right planner. If it changes from last time, // delete the old path. if (!prevPlanner || prevPlanner->commandType() != request.motionCommand->getCommandType()) { _planners[shell] = PlannerForCommandType(request.motionCommand->getCommandType()); request.prevPath = nullptr; } if (_planners[shell]->canHandleDynamic()) { dynamicRequests.push_back(shell); } else { staticRequests.push_back(shell); } staticRobotObstacles[shell] = std::make_shared<Geometry2d::Circle>( request.start.pos, Robot_Radius); } // Sorts descending so that higher priorities are first auto comparator = [&](int& lhs, int& rhs) { return requests.at(lhs).priority > requests.at(rhs).priority; }; std::sort(std::begin(staticRequests), std::end(staticRequests), comparator); std::sort(std::begin(dynamicRequests), std::end(dynamicRequests), comparator); std::vector<int> inOrderRequests; inOrderRequests.insert(std::end(inOrderRequests), std::begin(staticRequests), std::end(staticRequests)); inOrderRequests.insert(std::end(inOrderRequests), std::begin(dynamicRequests), std::end(dynamicRequests)); vector<DynamicObstacle> ourRobotsObstacles; for (int shell : inOrderRequests) { PlanRequest& request = requests.at(shell); if (_planners[shell]->canHandleDynamic()) { std::copy(std::begin(ourRobotsObstacles), std::end(ourRobotsObstacles), std::back_inserter(request.dynamicObstacles)); } else { for (auto& entry : staticRobotObstacles) { if (entry.first != shell) { request.obstacles.add(entry.second); } } SingleRobotPathPlanner::allDynamicToStatic( request.obstacles, request.dynamicObstacles); request.dynamicObstacles = std::vector<DynamicObstacle>(); } std::unique_ptr<Path> path = _planners[shell]->run(request); if (!path) { path = Planning::InterpolatedPath::emptyPath(request.start.pos); debugLog("path was null!! " + to_string(shell) + ":" + to_string(request.motionCommand->getCommandType())); } paths[shell] = std::move(path); // Add our generated path to our list of our Robot Obstacles ourRobotsObstacles.push_back(DynamicObstacle( request.start.pos, Robot_Radius, paths[shell].get())); } return paths; } } // namespace Planning <|endoftext|>
<commit_before>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team 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. *******************************************************************************/ //============================================================================== // CellMLTools tests //============================================================================== #include "tests.h" //============================================================================== #include "../../../../tests/testsutils.h" //============================================================================== #include <QtTest/QtTest> //============================================================================== void Tests::cliHelpTests() { // Ask for the plugin's help QString help = OpenCOR::fileContents("src/plugins/miscellaneous/CellMLTools/tests/data/help.out"); QCOMPARE(OpenCOR::runCli(QStringList() << "-c" << "CellMLTools::help"), help); // Try an unknown command, resulting in the help being shown QCOMPARE(OpenCOR::runCli(QStringList() << "-c" << "CellMLTools::unknown"), help); } //============================================================================== void Tests::cliCellmlExportTests() { // Try to export a CellML 1.0 file to CellML 1.0 QString inFileName = "src/plugins/miscellaneous/CellMLTools/tests/data/noble_model_1962.cellml"; QString outFileName = "export.out"; QString predefined_format = "cellml_1_0"; QCOMPARE(OpenCOR::runCli(QStringList() << "-c" << "CellMLTools::export" << inFileName << outFileName << predefined_format), OpenCOR::fileContents("src/plugins/miscellaneous/CellMLTools/tests/data/input_file_already_cellml_1_0.out")); // Export a CellML 1.1 file to CellML 1.0 inFileName = "src/plugins/miscellaneous/CellMLTools/tests/data/experiments/periodic-stimulus.xml"; QCOMPARE(OpenCOR::runCli(QStringList() << "-c" << "CellMLTools::export" << inFileName << outFileName << predefined_format), QString()); QCOMPARE(OpenCOR::fileContents(outFileName), OpenCOR::fileContents("src/plugins/miscellaneous/CellMLTools/tests/data/cellml_1_0_export.out")); // Try to export a non-existing CellML file to CellML 1.0 QCOMPARE(OpenCOR::runCli(QStringList() << "-c" << "CellMLTools::export" << "non_existing_input_file" << outFileName << predefined_format), OpenCOR::fileContents("src/plugins/miscellaneous/CellMLTools/tests/data/input_file_not_found.out")); // Try to export to a user-defined format, which file description doesn't // exist QCOMPARE(OpenCOR::runCli(QStringList() << "-c" << "CellMLTools::export" << inFileName << outFileName << "non_existing_user_defined_format_file"), OpenCOR::fileContents("src/plugins/miscellaneous/CellMLTools/tests/data/user_defined_format_file_not_found.out")); // Try to export a local file to a user-defined format, which file // description exists QString userDefinedFormatFileName = "src/plugins/miscellaneous/CellMLTools/tests/data/user_defined_format.xml"; QCOMPARE(OpenCOR::runCli(QStringList() << "-c" << "CellMLTools::export" << inFileName << outFileName << userDefinedFormatFileName), QString()); #ifdef Q_OS_WIN QCOMPARE(OpenCOR::fileContents(outFileName), OpenCOR::fileContents("src/plugins/miscellaneous/CellMLTools/tests/data/user_defined_format_export_on_windows.out")); #else QCOMPARE(OpenCOR::fileContents(outFileName), OpenCOR::fileContents("src/plugins/miscellaneous/CellMLTools/tests/data/user_defined_format_export_on_non_windows.out")); #endif } //============================================================================== QTEST_GUILESS_MAIN(Tests) //============================================================================== // End of file //============================================================================== <commit_msg>Tests: properly clean up ourselves once we are done [ci skip].<commit_after>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team 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. *******************************************************************************/ //============================================================================== // CellMLTools tests //============================================================================== #include "tests.h" //============================================================================== #include "../../../../tests/testsutils.h" //============================================================================== #include <QtTest/QtTest> //============================================================================== void Tests::cliHelpTests() { // Ask for the plugin's help QString help = OpenCOR::fileContents("src/plugins/miscellaneous/CellMLTools/tests/data/help.out"); QCOMPARE(OpenCOR::runCli(QStringList() << "-c" << "CellMLTools::help"), help); // Try an unknown command, resulting in the help being shown QCOMPARE(OpenCOR::runCli(QStringList() << "-c" << "CellMLTools::unknown"), help); } //============================================================================== void Tests::cliCellmlExportTests() { // Try to export a CellML 1.0 file to CellML 1.0 QString inFileName = "src/plugins/miscellaneous/CellMLTools/tests/data/noble_model_1962.cellml"; QString outFileName = "export.out"; QString predefined_format = "cellml_1_0"; QCOMPARE(OpenCOR::runCli(QStringList() << "-c" << "CellMLTools::export" << inFileName << outFileName << predefined_format), OpenCOR::fileContents("src/plugins/miscellaneous/CellMLTools/tests/data/input_file_already_cellml_1_0.out")); // Export a CellML 1.1 file to CellML 1.0 inFileName = "src/plugins/miscellaneous/CellMLTools/tests/data/experiments/periodic-stimulus.xml"; QCOMPARE(OpenCOR::runCli(QStringList() << "-c" << "CellMLTools::export" << inFileName << outFileName << predefined_format), QString()); QCOMPARE(OpenCOR::fileContents(outFileName), OpenCOR::fileContents("src/plugins/miscellaneous/CellMLTools/tests/data/cellml_1_0_export.out")); // Try to export a non-existing CellML file to CellML 1.0 QCOMPARE(OpenCOR::runCli(QStringList() << "-c" << "CellMLTools::export" << "non_existing_input_file" << outFileName << predefined_format), OpenCOR::fileContents("src/plugins/miscellaneous/CellMLTools/tests/data/input_file_not_found.out")); // Try to export to a user-defined format, which file description doesn't // exist QCOMPARE(OpenCOR::runCli(QStringList() << "-c" << "CellMLTools::export" << inFileName << outFileName << "non_existing_user_defined_format_file"), OpenCOR::fileContents("src/plugins/miscellaneous/CellMLTools/tests/data/user_defined_format_file_not_found.out")); // Try to export a local file to a user-defined format, which file // description exists QString userDefinedFormatFileName = "src/plugins/miscellaneous/CellMLTools/tests/data/user_defined_format.xml"; QCOMPARE(OpenCOR::runCli(QStringList() << "-c" << "CellMLTools::export" << inFileName << outFileName << userDefinedFormatFileName), QString()); #ifdef Q_OS_WIN QCOMPARE(OpenCOR::fileContents(outFileName), OpenCOR::fileContents("src/plugins/miscellaneous/CellMLTools/tests/data/user_defined_format_export_on_windows.out")); #else QCOMPARE(OpenCOR::fileContents(outFileName), OpenCOR::fileContents("src/plugins/miscellaneous/CellMLTools/tests/data/user_defined_format_export_on_non_windows.out")); #endif // Delete the output file we generated QFile::remove(outFileName); } //============================================================================== QTEST_GUILESS_MAIN(Tests) //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before><commit_msg>fixed image stride alignment and added detection visualization for debugging<commit_after><|endoftext|>
<commit_before>#include <algorithm> #include <cmath> #include <iostream> #include <QPainter> #include <QPaintEvent> #include <QPoint> #include <QPointF> #include <QPolygonF> #include <QRect> #include <QStylePainter> #include <QVector> #include "tattoo_canvas.h" static double PI = 3.1415926535; static double deg2rad(double angle) { return angle / 180.0 * PI; } static double rad2deg(double angle) { return angle / PI * 180.0; } TattooCanvas::TattooCanvas(QWidget *parent) { revolution = 180.0; stroke = 1; curveRadius = 30; setMinimumSize(400, 400); } void TattooCanvas::setCurveRadius(int radius) { this->curveRadius = radius; update(); } void TattooCanvas::setStroke(int stroke) { this->stroke = stroke; std::cout << "New stroke is " << stroke << std::endl; update(); } double TattooCanvas::computeSpiralRadius(double angle) { double a = 0; double b = (getRadius() + getOriginOffset() - a) / deg2rad(revolution); return a + b * angle; } QPointF TattooCanvas::convertToCartesian(double angle, double radius) { return QPointF(std::cos(angle) * radius, std::sin(angle) * radius); } void TattooCanvas::paintEvent(QPaintEvent *event) { QStylePainter painter(this); QPen pen(Qt::black, stroke, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin); painter.setPen(pen); painter.setRenderHint(QPainter::Antialiasing); int radius = (std::min(width(), height()) - (2 * Margin)) / 2; QPoint center(width() / 2, height() / 2); painter.drawEllipse(center, radius, radius); drawCustomLayer(&painter); drawCircles(&painter); } void TattooCanvas::drawCircles(QPainter *painter) { painter->translate(width() / 2.0, height() / 2.0); double tHeight = std::sqrt(3.0 * std::pow((double) curveRadius, 2.0)); double y1 = 2.0 / 3.0 * tHeight; double y2 = y1 - tHeight; //painter->drawEllipse(QPoint(0, y1), radius, radius); painter->drawArc(0 - curveRadius, y1 - curveRadius, curveRadius * 2.0, curveRadius * 2.0, 60 * 16, 60 * 16); //painter->drawEllipse(QPointF(radius, y2), radius, radius); painter->drawArc(0, y2 - curveRadius, curveRadius * 2.0, curveRadius * 2.0, 180 * 16, 60 * 16); //painter->drawEllipse(QPointF(-radius, y2), radius, radius); painter->drawArc(0 - 2.0 * curveRadius, y2 - curveRadius, curveRadius * 2.0, curveRadius * 2.0, 0, -60 * 16); painter->translate(0, y2); int tatRadius = (std::min(width(), height()) - (2 * Margin)) / 2; drawSpiral(painter, tatRadius - y2, 270); double xOffset = (1.0 / 3.0 * tHeight) * std::cos(deg2rad(30.0)); double yOffset = (1.0 / 3.0 * tHeight) * std::sin(deg2rad(30.0)); painter->translate(xOffset, y1 - yOffset); drawSpiral(painter, tatRadius - y2, 30); painter->translate(-2.0 * xOffset, 0); drawSpiral(painter, tatRadius - y2, 150); painter->resetTransform(); } void TattooCanvas::drawCustomLayer(QPainter *painter) { painter->translate(width() / 2.0, height() / 2.0); QPen originalPen = painter->pen(); painter->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); double tHeight = std::sqrt(3.0 * std::pow((double) curveRadius, 2.0)); double y = 2.0 / 3.0 * tHeight; int radius = curveRadius - (stroke / 2); painter->translate(0, y); painter->drawEllipse(QPoint(0, 0), radius, radius); painter->drawPie(-radius, -radius, 2 * radius, 2 * radius, 60 * 16, 60 * 16); painter->setPen(QPen(Qt::black, 5, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); painter->drawPoint(0, 0); painter->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); // Draw curve angle painter->drawPie(-10, -10, 20, 20, 60 * 16, 60 * 16); QChar phi(0x03D5); int charWidth = painter->fontMetrics().width(phi); int charHeight = painter->fontMetrics().height(); painter->drawText(-charWidth / 2, -charHeight, QString(phi)); // Add visible theta & r guides painter->translate(0, -tHeight); painter->drawLine(0, 0, 0, -2 * curveRadius); painter->rotate(270); painter->setPen(QPen(Qt::gray, 1, Qt::DashLine, Qt::RoundCap, Qt::RoundJoin)); int maxAngle = 120; for (int angle = 30; angle <= maxAngle; angle += 10) { double r = computeSpiralRadius(deg2rad(angle)) - stroke / 2; QPointF pointOnSpiral = convertToCartesian(deg2rad(angle), r); if (angle == maxAngle) { painter->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); } painter->drawLine(QPointF(0, 0), pointOnSpiral); } painter->drawArc(-40, -40, 80, 80, 0, -maxAngle * 16); painter->rotate(-270); // recenter transform painter->translate(0, tHeight - y); for (int i = 0; i < 360; i += 90) { painter->rotate(i); int x = getRadius() + stroke / 2 + 2; painter->drawLine(x, 0, x + 5, 0); painter->rotate(-i); } painter->setPen(originalPen); painter->resetTransform(); } void TattooCanvas::drawSpiral(QPainter *painter, int radius, int rotate) { double a = 0; double b = (radius - a) / deg2rad(revolution); double angle = 0.0; double r = 0.0; QVector<QPointF> points; if (!(a > 0)) { //points.append(QPointF(width() / 2, height() / 2)); } while (r < radius) { r = a + b * angle; if (r > radius) { r = radius; angle = r / (a + b); } points.append(convertToCartesian(angle, r)); angle += 0.1; }; QPolygonF polyline(points); painter->rotate(rotate); painter->drawPolyline(polyline); painter->rotate(-rotate); } int TattooCanvas::getOriginOffset() const { return std::sqrt(3.0 * std::pow((double) curveRadius, 2.0)) / 3.0; } int TattooCanvas::getRadius() const { return (std::min(width(), height()) - (2 * Margin)) / 2; } QPointF TattooCanvas::rotatePoint(const QPointF &point, int angle) { double radians = deg2rad(angle); return QPointF( point.x() * std::cos(radians) - point.y() * std::sin(radians), point.x() * std::sin(radians) + point.y() * std::cos(radians) ); } void TattooCanvas::refreshCanvas() { } <commit_msg>repositioned circle guide to top left space<commit_after>#include <algorithm> #include <cmath> #include <iostream> #include <QPainter> #include <QPaintEvent> #include <QPoint> #include <QPointF> #include <QPolygonF> #include <QRect> #include <QStylePainter> #include <QVector> #include "tattoo_canvas.h" static double PI = 3.1415926535; static double deg2rad(double angle) { return angle / 180.0 * PI; } static double rad2deg(double angle) { return angle / PI * 180.0; } TattooCanvas::TattooCanvas(QWidget *parent) { revolution = 180.0; stroke = 1; curveRadius = 30; setMinimumSize(400, 400); } void TattooCanvas::setCurveRadius(int radius) { this->curveRadius = radius; update(); } void TattooCanvas::setStroke(int stroke) { this->stroke = stroke; std::cout << "New stroke is " << stroke << std::endl; update(); } double TattooCanvas::computeSpiralRadius(double angle) { double a = 0; double b = (getRadius() + getOriginOffset() - a) / deg2rad(revolution); return a + b * angle; } QPointF TattooCanvas::convertToCartesian(double angle, double radius) { return QPointF(std::cos(angle) * radius, std::sin(angle) * radius); } void TattooCanvas::paintEvent(QPaintEvent *event) { QStylePainter painter(this); QPen pen(Qt::black, stroke, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin); painter.setPen(pen); painter.setRenderHint(QPainter::Antialiasing); int radius = (std::min(width(), height()) - (2 * Margin)) / 2; QPoint center(width() / 2, height() / 2); painter.drawEllipse(center, radius, radius); drawCustomLayer(&painter); drawCircles(&painter); } void TattooCanvas::drawCircles(QPainter *painter) { painter->translate(width() / 2.0, height() / 2.0); double tHeight = std::sqrt(3.0 * std::pow((double) curveRadius, 2.0)); double y1 = 2.0 / 3.0 * tHeight; double y2 = y1 - tHeight; //painter->drawEllipse(QPoint(0, y1), radius, radius); painter->drawArc(0 - curveRadius, y1 - curveRadius, curveRadius * 2.0, curveRadius * 2.0, 60 * 16, 60 * 16); //painter->drawEllipse(QPointF(radius, y2), radius, radius); painter->drawArc(0, y2 - curveRadius, curveRadius * 2.0, curveRadius * 2.0, 180 * 16, 60 * 16); //painter->drawEllipse(QPointF(-radius, y2), radius, radius); painter->drawArc(0 - 2.0 * curveRadius, y2 - curveRadius, curveRadius * 2.0, curveRadius * 2.0, 0, -60 * 16); painter->translate(0, y2); int tatRadius = (std::min(width(), height()) - (2 * Margin)) / 2; drawSpiral(painter, tatRadius - y2, 270); double xOffset = (1.0 / 3.0 * tHeight) * std::cos(deg2rad(30.0)); double yOffset = (1.0 / 3.0 * tHeight) * std::sin(deg2rad(30.0)); painter->translate(xOffset, y1 - yOffset); drawSpiral(painter, tatRadius - y2, 30); painter->translate(-2.0 * xOffset, 0); drawSpiral(painter, tatRadius - y2, 150); painter->resetTransform(); } void TattooCanvas::drawCustomLayer(QPainter *painter) { painter->translate(width() / 2.0, height() / 2.0); QPen originalPen = painter->pen(); painter->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); double tHeight = std::sqrt(3.0 * std::pow((double) curveRadius, 2.0)); double y = 1.0 / 3.0 * tHeight; int radius = curveRadius - (stroke / 2); painter->translate(-curveRadius, -y); painter->drawEllipse(QPoint(0, 0), radius, radius); painter->drawPie(-radius, -radius, 2 * radius, 2 * radius, 0 * 16, -60 * 16); painter->setPen(QPen(Qt::black, 5, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); painter->drawPoint(0, 0); painter->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); // Draw curve angle painter->drawPie(-10, -10, 20, 20, 0 * 16, -60 * 16); QChar phi(0x03D5); int charWidth = painter->fontMetrics().width(phi); int charHeight = painter->fontMetrics().height(); painter->drawText(charWidth, charHeight - 3, QString(phi)); // Add visible theta & r guides painter->translate(curveRadius, y); painter->translate(0, 2 * y - tHeight); painter->drawLine(0, 0, 0, -2 * curveRadius); painter->rotate(270); painter->setPen(QPen(Qt::gray, 1, Qt::DashLine, Qt::RoundCap, Qt::RoundJoin)); int maxAngle = 120; for (int angle = 30; angle <= maxAngle; angle += 10) { double r = computeSpiralRadius(deg2rad(angle)) - stroke / 2; QPointF pointOnSpiral = convertToCartesian(deg2rad(angle), r); if (angle == maxAngle) { painter->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); } painter->drawLine(QPointF(0, 0), pointOnSpiral); } painter->drawArc(-40, -40, 80, 80, 0, -maxAngle * 16); painter->rotate(-270); // recenter transform painter->translate(0, -2 * y + tHeight); for (int i = 0; i < 360; i += 90) { painter->rotate(i); int x = getRadius() + stroke / 2 + 2; painter->drawLine(x, 0, x + 5, 0); painter->rotate(-i); } painter->setPen(originalPen); painter->resetTransform(); } void TattooCanvas::drawSpiral(QPainter *painter, int radius, int rotate) { double a = 0; double b = (radius - a) / deg2rad(revolution); double angle = 0.0; double r = 0.0; QVector<QPointF> points; if (!(a > 0)) { //points.append(QPointF(width() / 2, height() / 2)); } while (r < radius) { r = a + b * angle; if (r > radius) { r = radius; angle = r / (a + b); } points.append(convertToCartesian(angle, r)); angle += 0.1; }; QPolygonF polyline(points); painter->rotate(rotate); painter->drawPolyline(polyline); painter->rotate(-rotate); } int TattooCanvas::getOriginOffset() const { return std::sqrt(3.0 * std::pow((double) curveRadius, 2.0)) / 3.0; } int TattooCanvas::getRadius() const { return (std::min(width(), height()) - (2 * Margin)) / 2; } QPointF TattooCanvas::rotatePoint(const QPointF &point, int angle) { double radians = deg2rad(angle); return QPointF( point.x() * std::cos(radians) - point.y() * std::sin(radians), point.x() * std::sin(radians) + point.y() * std::cos(radians) ); } void TattooCanvas::refreshCanvas() { } <|endoftext|>
<commit_before>#include <jpl-tags/fiducial_stereo.h> #include <opencv2/opencv.hpp> #include <drc_utils/LcmWrapper.hpp> #include <drc_utils/BotWrapper.hpp> #include <lcm/lcm-cpp.hpp> #include <lcmtypes/multisense/images_t.hpp> #include <lcmtypes/bot_core/image_t.hpp> #include <lcmtypes/drc/tag_detection_t.hpp> #include <lcmtypes/drc/tag_detection_list_t.hpp> #include <bot_core/camtrans.h> #include <bot_param/param_util.h> #include <zlib.h> struct State { drc::BotWrapper::Ptr mBotWrapper; drc::LcmWrapper::Ptr mLcmWrapper; BotCamTrans* mCamTransLeft; BotCamTrans* mCamTransRight; fiducial_detector_t* mDetector; fiducial_stereo_t* mStereoDetector; double mStereoBaseline; Eigen::Matrix3d mCalibLeft; Eigen::Matrix3d mCalibLeftInv; std::string mCameraChannel; std::string mTagChannel; bool mRunStereoAlgorithm; State() { mDetector = NULL; mStereoDetector = NULL; mCamTransLeft = NULL; mCamTransRight = NULL; mCameraChannel = "CAMERA"; mTagChannel = "JPL_TAGS"; mRunStereoAlgorithm = true; } ~State() { if (mDetector != NULL) fiducial_detector_free(mDetector); if (mStereoDetector != NULL) fiducial_stereo_free(mStereoDetector); } void populate(BotCamTrans* iCam, fiducial_stereo_cam_model_t& oCam) { oCam.cols = bot_camtrans_get_width(iCam); oCam.rows = bot_camtrans_get_height(iCam); oCam.focal_length_x = bot_camtrans_get_focal_length_x(iCam); oCam.focal_length_y = bot_camtrans_get_focal_length_y(iCam); oCam.image_center_x = bot_camtrans_get_principal_x(iCam); oCam.image_center_y = bot_camtrans_get_principal_y(iCam); } void populate(BotCamTrans* iCam, Eigen::Matrix3d& oK) { oK(0,0) = bot_camtrans_get_focal_length_x(iCam); oK(1,1) = bot_camtrans_get_focal_length_y(iCam); oK(0,2) = bot_camtrans_get_principal_x(iCam); oK(1,2) = bot_camtrans_get_principal_y(iCam); oK(0,1) = bot_camtrans_get_skew(iCam); } void copyTransform(const Eigen::Isometry3d& iTransform, double oTransform[4][4]) { for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { oTransform[i][j] = iTransform(i,j); } } } void setup() { mBotWrapper.reset(new drc::BotWrapper()); mLcmWrapper.reset(new drc::LcmWrapper(mBotWrapper->getLcm())); mLcmWrapper->get()->subscribe(mCameraChannel, &State::onCamera, this); mDetector = fiducial_detector_alloc(); fiducial_detector_init(mDetector); fiducial_params_t params; fiducial_detector_get_params(mDetector, &params); // TODO: can set parameters here if desired //params.search_size = 40; // image search radius in pixels //params.min_viewing_angle = 20; // angle of view of fiducial in degrees //params.dist_thresh = 0.05; // max allowed distance in meters between initial and estimated fiducial positions fiducial_detector_set_params(mDetector, &params); mStereoDetector = fiducial_stereo_alloc(); fiducial_stereo_init(mStereoDetector); // populate camera data fiducial_stereo_cam_model_t leftModel, rightModel; mCamTransLeft = bot_param_get_new_camtrans(mBotWrapper->getBotParam(), (mCameraChannel + "_LEFT").c_str()); mCamTransRight = bot_param_get_new_camtrans(mBotWrapper->getBotParam(), (mCameraChannel + "_RIGHT").c_str()); populate(mCamTransLeft, leftModel); populate(mCamTransRight, rightModel); copyTransform(Eigen::Isometry3d::Identity(), leftModel.transform); copyTransform(Eigen::Isometry3d::Identity(), leftModel.inv_transform); Eigen::Isometry3d rightToLeft; mBotWrapper->getTransform(mCameraChannel + "_RIGHT", mCameraChannel + "_LEFT", rightToLeft); copyTransform(rightToLeft, rightModel.transform); copyTransform(rightToLeft.inverse(), rightModel.inv_transform); // set detector camera models fiducial_detector_set_camera_models(mDetector, &leftModel); fiducial_stereo_set_camera_models(mStereoDetector, &leftModel, &rightModel); // set internal values for stereo depth computation populate(mCamTransLeft, mCalibLeft); mCalibLeftInv = mCalibLeft.inverse(); mStereoBaseline = rightToLeft.translation().norm(); } void start() { mLcmWrapper->startHandleThread(true); } void onCamera(const lcm::ReceiveBuffer* iBuffer, const std::string& iChannel, const multisense::images_t* iMessage) { std::cout << "GOT IMAGE " << std::endl; // grab camera pose Eigen::Isometry3d cameraToLocal, localToCamera; mBotWrapper->getTransform(mCameraChannel + "_LEFT", "local", cameraToLocal, iMessage->utime); localToCamera = cameraToLocal.inverse(); bot_core::image_t* leftImage = NULL; bot_core::image_t* rightImage = NULL; bot_core::image_t* dispImage = NULL; // grab image pointers for (int i = 0; i < iMessage->n_images; ++i) { switch (iMessage->image_types[i]) { case multisense::images_t::LEFT: leftImage = (bot_core::image_t*)(&iMessage->images[i]); break; case multisense::images_t::RIGHT: rightImage = (bot_core::image_t*)(&iMessage->images[i]); break; case multisense::images_t::DISPARITY_ZIPPED: case multisense::images_t::DISPARITY: dispImage = (bot_core::image_t*)(&iMessage->images[i]); break; default: break; } } cv::Mat left, right, disp; // decode left image left = leftImage->pixelformat == leftImage->PIXEL_FORMAT_MJPEG ? cv::imdecode(cv::Mat(leftImage->data), -1) : cv::Mat(leftImage->height, leftImage->width, CV_8UC1, leftImage->data.data()); if (left.channels() < 3) cv::cvtColor(left, left, CV_GRAY2RGB); // decode right image if necessary for stereo algorithm if (mRunStereoAlgorithm) { if (rightImage != NULL) { right = rightImage->pixelformat == rightImage->PIXEL_FORMAT_MJPEG ? cv::imdecode(cv::Mat(rightImage->data), -1) : cv::Mat(rightImage->height, rightImage->width, CV_8UC1, rightImage->data.data()); if (right.channels() < 3) cv::cvtColor(right, right, CV_GRAY2RGB); } else { std::cout << "error: no right image available!" << std::endl; return; } } // otherwise decode disparity; we will compute depth from left image only else { int numPix = dispImage->width*dispImage->height; if ((int)dispImage->data.size() != numPix*2) { std::vector<uint8_t> buf(numPix*2); unsigned long len = buf.size(); uncompress(buf.data(), &len, dispImage->data.data(), dispImage->data.size()); disp = cv::Mat(dispImage->height, dispImage->width, CV_16UC1, buf.data()); } else { disp = cv::Mat(dispImage->height, dispImage->width, CV_16UC1, dispImage->data.data()); } } // set up tag detections message drc::tag_detection_list_t msg; msg.utime = iMessage->utime; msg.num_detections = 0; // TODO: initialize with number of tags from config int numTags = 1; for (int i = 0; i < numTags; ++i) { // TODO: populate from config id int tagId = i; fiducial_pose_t poseInit, poseFinal; // TODO: populate initial pose wrt left cam using fk and config location // can also initialize with previous pose (tracking) poseInit = fiducial_pose_ident(); poseInit.pos.z = 1; poseInit.rot = fiducial_rot_from_rpy(0,2*M_PI/2,0); fiducial_detector_error_t status; if (mRunStereoAlgorithm) { float leftScore(0), rightScore(0); status = fiducial_stereo_process(mStereoDetector, left.data, right.data, left.cols, left.rows, left.channels(), poseInit, &poseFinal, &leftScore, &rightScore, false); } else { float score = 0; status = fiducial_detector_match_subpixel(mDetector, left.data, left.cols, left.rows, left.channels(), poseInit, &score); if (status == FIDUCIAL_DETECTOR_OK) { float x = mDetector->fiducial_location.x; float y = mDetector->fiducial_location.y; int xInt(x), yInt(y); if ((xInt < 0) || (yInt < 0) || (xInt >= disp.cols-1) || (yInt >= disp.rows-1)) { status = FIDUCIAL_DETECTOR_ERR; } else { // interpolate disparity float xFrac(x-xInt), yFrac(y-yInt); int d00 = disp.at<uint16_t>(xInt, yInt); int d10 = disp.at<uint16_t>(xInt+1, yInt); int d01 = disp.at<uint16_t>(xInt, yInt+1); int d11 = disp.at<uint16_t>(xInt+1, yInt+1); float d = (1-xFrac)*(1-yFrac)*d00 + xFrac*(1-yFrac)*d10 + (1-xFrac)*yFrac*d01 + xFrac*yFrac*d11; // compute depth and 3d point float z = mStereoBaseline*mCalibLeft(0,0) / d; Eigen::Vector3d pos = z*mCalibLeftInv*Eigen::Vector3d(x,y,1); poseFinal.pos.x = pos[0]; poseFinal.pos.y = pos[1]; poseFinal.pos.z = pos[2]; // TODO: what about orientation? } } } if (status == FIDUCIAL_DETECTOR_OK) { // populate this tag detection message drc::tag_detection_t detection; detection.utime = msg.utime; detection.id = tagId; // put tag into local frame // TODO: keep in camera frame? Eigen::Vector3d pos(poseFinal.pos.x, poseFinal.pos.y, poseFinal.pos.z); pos = cameraToLocal*pos; for (int k = 0; k < 3; ++k) detection.pos[k] = pos[k]; Eigen::Quaterniond q(poseFinal.rot.u, poseFinal.rot.x, poseFinal.rot.y, poseFinal.rot.z); q = cameraToLocal.rotation()*q; detection.orientation[0] = q.w(); detection.orientation[1] = q.x(); detection.orientation[2] = q.y(); detection.orientation[3] = q.z(); // find pixel position of tag double p[] = {poseFinal.pos.x, poseFinal.pos.y, poseFinal.pos.z}; double pix[3]; bot_camtrans_project_point(mCamTransLeft, p, pix); detection.cxy[0] = pix[0]; detection.cxy[1] = pix[1]; // four corners are irrelevant, set them all to tag center for (int k = 0; k < 4; ++k) { for (int m = 0; m < 2; ++m) detection.p[k][m] = pix[m]; } // add this detection to list msg.detections.push_back(detection); msg.num_detections = msg.detections.size(); std::cout << "PROCESSED " << status << std::endl; std::cout << "POSE: " << poseFinal.pos.x << " " << poseFinal.pos.y << " " << poseFinal.pos.z << std::endl; } else { std::cout << "warning: could not detect tag " << tagId << std::endl; } } mLcmWrapper->get()->publish(mTagChannel, &msg); } }; int main(const int iArgc, const char** iArgv) { State state; state.setup(); state.start(); return -1; } <commit_msg>a bit of refactoring, and added left+disparity method<commit_after>#include <jpl-tags/fiducial_stereo.h> #include <opencv2/opencv.hpp> #include <drc_utils/LcmWrapper.hpp> #include <drc_utils/BotWrapper.hpp> #include <lcm/lcm-cpp.hpp> #include <lcmtypes/multisense/images_t.hpp> #include <lcmtypes/bot_core/image_t.hpp> #include <lcmtypes/drc/tag_detection_t.hpp> #include <lcmtypes/drc/tag_detection_list_t.hpp> #include <bot_core/camtrans.h> #include <bot_param/param_util.h> #include <zlib.h> struct State { drc::BotWrapper::Ptr mBotWrapper; drc::LcmWrapper::Ptr mLcmWrapper; BotCamTrans* mCamTransLeft; BotCamTrans* mCamTransRight; fiducial_detector_t* mDetector; fiducial_stereo_t* mStereoDetector; double mStereoBaseline; Eigen::Matrix3d mCalibLeft; Eigen::Matrix3d mCalibLeftInv; std::string mCameraChannel; std::string mTagChannel; bool mRunStereoAlgorithm; State() { mDetector = NULL; mStereoDetector = NULL; mCamTransLeft = NULL; mCamTransRight = NULL; mCameraChannel = "CAMERA"; mTagChannel = "JPL_TAGS"; mRunStereoAlgorithm = true; } ~State() { if (mDetector != NULL) fiducial_detector_free(mDetector); if (mStereoDetector != NULL) fiducial_stereo_free(mStereoDetector); } void populate(BotCamTrans* iCam, fiducial_stereo_cam_model_t& oCam) { oCam.cols = bot_camtrans_get_width(iCam); oCam.rows = bot_camtrans_get_height(iCam); oCam.focal_length_x = bot_camtrans_get_focal_length_x(iCam); oCam.focal_length_y = bot_camtrans_get_focal_length_y(iCam); oCam.image_center_x = bot_camtrans_get_principal_x(iCam); oCam.image_center_y = bot_camtrans_get_principal_y(iCam); } void populate(BotCamTrans* iCam, Eigen::Matrix3d& oK) { oK(0,0) = bot_camtrans_get_focal_length_x(iCam); oK(1,1) = bot_camtrans_get_focal_length_y(iCam); oK(0,2) = bot_camtrans_get_principal_x(iCam); oK(1,2) = bot_camtrans_get_principal_y(iCam); oK(0,1) = bot_camtrans_get_skew(iCam); } void copyTransform(const Eigen::Isometry3d& iTransform, double oTransform[4][4]) { for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { oTransform[i][j] = iTransform(i,j); } } } void setup() { mBotWrapper.reset(new drc::BotWrapper()); mLcmWrapper.reset(new drc::LcmWrapper(mBotWrapper->getLcm())); mLcmWrapper->get()->subscribe(mCameraChannel, &State::onCamera, this); mDetector = fiducial_detector_alloc(); fiducial_detector_init(mDetector); fiducial_params_t params; fiducial_detector_get_params(mDetector, &params); // TODO: can set parameters here if desired //params.search_size = 40; // image search radius in pixels //params.min_viewing_angle = 20; // angle of view of fiducial in degrees //params.dist_thresh = 0.05; // max allowed distance in meters between initial and estimated fiducial positions fiducial_detector_set_params(mDetector, &params); mStereoDetector = fiducial_stereo_alloc(); fiducial_stereo_init(mStereoDetector); // populate camera data fiducial_stereo_cam_model_t leftModel, rightModel; mCamTransLeft = bot_param_get_new_camtrans(mBotWrapper->getBotParam(), (mCameraChannel + "_LEFT").c_str()); mCamTransRight = bot_param_get_new_camtrans(mBotWrapper->getBotParam(), (mCameraChannel + "_RIGHT").c_str()); populate(mCamTransLeft, leftModel); populate(mCamTransRight, rightModel); copyTransform(Eigen::Isometry3d::Identity(), leftModel.transform); copyTransform(Eigen::Isometry3d::Identity(), leftModel.inv_transform); Eigen::Isometry3d rightToLeft; mBotWrapper->getTransform(mCameraChannel + "_RIGHT", mCameraChannel + "_LEFT", rightToLeft); copyTransform(rightToLeft, rightModel.transform); copyTransform(rightToLeft.inverse(), rightModel.inv_transform); // set detector camera models fiducial_detector_set_camera_models(mDetector, &leftModel); fiducial_stereo_set_camera_models(mStereoDetector, &leftModel, &rightModel); // set internal values for stereo depth computation populate(mCamTransLeft, mCalibLeft); mCalibLeftInv = mCalibLeft.inverse(); mStereoBaseline = rightToLeft.translation().norm(); } void start() { mLcmWrapper->startHandleThread(true); } bool decodeImages(const multisense::images_t* iMessage, cv::Mat& oLeft, cv::Mat& oRight, cv::Mat& oDisp) { bot_core::image_t* leftImage = NULL; bot_core::image_t* rightImage = NULL; bot_core::image_t* dispImage = NULL; // grab image pointers for (int i = 0; i < iMessage->n_images; ++i) { switch (iMessage->image_types[i]) { case multisense::images_t::LEFT: leftImage = (bot_core::image_t*)(&iMessage->images[i]); break; case multisense::images_t::RIGHT: rightImage = (bot_core::image_t*)(&iMessage->images[i]); break; case multisense::images_t::DISPARITY_ZIPPED: case multisense::images_t::DISPARITY: dispImage = (bot_core::image_t*)(&iMessage->images[i]); break; default: break; } } // decode left image if (leftImage == NULL) { std::cout << "error: no left image available!" << std::endl; return false; } oLeft = leftImage->pixelformat == leftImage->PIXEL_FORMAT_MJPEG ? cv::imdecode(cv::Mat(leftImage->data), -1) : cv::Mat(leftImage->height, leftImage->width, CV_8UC1, leftImage->data.data()); if (oLeft.channels() < 3) cv::cvtColor(oLeft, oLeft, CV_GRAY2RGB); // decode right image if necessary for stereo algorithm if (mRunStereoAlgorithm) { if (rightImage == NULL) { std::cout << "error: no right image available!" << std::endl; return false; } oRight = rightImage->pixelformat == rightImage->PIXEL_FORMAT_MJPEG ? cv::imdecode(cv::Mat(rightImage->data), -1) : cv::Mat(rightImage->height, rightImage->width, CV_8UC1, rightImage->data.data()); if (oRight.channels() < 3) cv::cvtColor(oRight, oRight, CV_GRAY2RGB); } // otherwise decode disparity; we will compute depth from left image only else { if (dispImage == NULL) { std::cout << "error: no disparity image available!" << std::endl; return false; } int numPix = dispImage->width*dispImage->height; if ((int)dispImage->data.size() != numPix*2) { std::vector<uint8_t> buf(numPix*2); unsigned long len = buf.size(); uncompress(buf.data(), &len, dispImage->data.data(), dispImage->data.size()); oDisp = cv::Mat(dispImage->height, dispImage->width, CV_16UC1, buf.data()); } else { oDisp = cv::Mat(dispImage->height, dispImage->width, CV_16UC1, dispImage->data.data()); } } return true; } void onCamera(const lcm::ReceiveBuffer* iBuffer, const std::string& iChannel, const multisense::images_t* iMessage) { std::cout << "GOT IMAGE " << std::endl; // grab camera pose Eigen::Isometry3d cameraToLocal, localToCamera; mBotWrapper->getTransform(mCameraChannel + "_LEFT", "local", cameraToLocal, iMessage->utime); localToCamera = cameraToLocal.inverse(); cv::Mat left, right, disp; if (!decodeImages(iMessage, left, right, disp)) return; // set up tag detections message drc::tag_detection_list_t msg; msg.utime = iMessage->utime; msg.num_detections = 0; // TODO: initialize with number of tags from config int numTags = 1; for (int i = 0; i < numTags; ++i) { // TODO: populate from config id int tagId = i; fiducial_pose_t poseInit, poseFinal; // TODO: populate initial pose wrt left cam using fk and config location // can also initialize with previous pose (tracking) poseInit = fiducial_pose_ident(); poseInit.pos.z = 1; poseInit.rot = fiducial_rot_from_rpy(0,2*M_PI/2,0); fiducial_detector_error_t status; if (mRunStereoAlgorithm) { float leftScore(0), rightScore(0); status = fiducial_stereo_process(mStereoDetector, left.data, right.data, left.cols, left.rows, left.channels(), poseInit, &poseFinal, &leftScore, &rightScore, false); } else { float score = 0; status = fiducial_detector_match_subpixel(mDetector, left.data, left.cols, left.rows, left.channels(), poseInit, &score); if (status == FIDUCIAL_DETECTOR_OK) { float x = mDetector->fiducial_location.x; float y = mDetector->fiducial_location.y; int xInt(x), yInt(y); if ((xInt < 0) || (yInt < 0) || (xInt >= disp.cols-1) || (yInt >= disp.rows-1)) { status = FIDUCIAL_DETECTOR_ERR; } else { // interpolate disparity float xFrac(x-xInt), yFrac(y-yInt); int d00 = disp.at<uint16_t>(xInt, yInt); int d10 = disp.at<uint16_t>(xInt+1, yInt); int d01 = disp.at<uint16_t>(xInt, yInt+1); int d11 = disp.at<uint16_t>(xInt+1, yInt+1); float d = (1-xFrac)*(1-yFrac)*d00 + xFrac*(1-yFrac)*d10 + (1-xFrac)*yFrac*d01 + xFrac*yFrac*d11; // compute depth and 3d point float z = mStereoBaseline*mCalibLeft(0,0) / d; Eigen::Vector3d pos = z*mCalibLeftInv*Eigen::Vector3d(x,y,1); poseFinal.pos.x = pos[0]; poseFinal.pos.y = pos[1]; poseFinal.pos.z = pos[2]; // TODO: what about orientation? } } } if (status == FIDUCIAL_DETECTOR_OK) { // populate this tag detection message drc::tag_detection_t detection; detection.utime = msg.utime; detection.id = tagId; // put tag into local frame Eigen::Vector3d pos(poseFinal.pos.x, poseFinal.pos.y, poseFinal.pos.z); pos = cameraToLocal*pos; for (int k = 0; k < 3; ++k) detection.pos[k] = pos[k]; Eigen::Quaterniond q(poseFinal.rot.u, poseFinal.rot.x, poseFinal.rot.y, poseFinal.rot.z); q = cameraToLocal.rotation()*q; detection.orientation[0] = q.w(); detection.orientation[1] = q.x(); detection.orientation[2] = q.y(); detection.orientation[3] = q.z(); // find pixel position of tag double p[] = {poseFinal.pos.x, poseFinal.pos.y, poseFinal.pos.z}; double pix[3]; bot_camtrans_project_point(mCamTransLeft, p, pix); detection.cxy[0] = pix[0]; detection.cxy[1] = pix[1]; // four corners are irrelevant; set them all to tag center for (int k = 0; k < 4; ++k) { for (int m = 0; m < 2; ++m) detection.p[k][m] = pix[m]; } // add this detection to list msg.detections.push_back(detection); msg.num_detections = msg.detections.size(); std::cout << "PROCESSED " << status << std::endl; std::cout << "POSE: " << poseFinal.pos.x << " " << poseFinal.pos.y << " " << poseFinal.pos.z << std::endl; } else { std::cout << "warning: could not detect tag " << tagId << std::endl; } } mLcmWrapper->get()->publish(mTagChannel, &msg); } }; int main(const int iArgc, const char** iArgv) { State state; state.setup(); state.start(); return -1; } <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/sync_driver/shared_change_processor.h" #include "base/message_loop/message_loop_proxy.h" #include "components/sync_driver/generic_change_processor.h" #include "components/sync_driver/generic_change_processor_factory.h" #include "components/sync_driver/sync_api_component_factory.h" #include "sync/api/sync_change.h" using base::AutoLock; namespace sync_driver { SharedChangeProcessor::SharedChangeProcessor() : disconnected_(false), type_(syncer::UNSPECIFIED), frontend_loop_(base::MessageLoopProxy::current()), generic_change_processor_(NULL), error_handler_(NULL) { } SharedChangeProcessor::~SharedChangeProcessor() { // We can either be deleted when the DTC is destroyed (on UI // thread), or when the syncer::SyncableService stop's syncing (datatype // thread). |generic_change_processor_|, if non-NULL, must be // deleted on |backend_loop_|. if (frontend_loop_->BelongsToCurrentThread()) { if (backend_loop_.get()) { if (!backend_loop_->DeleteSoon(FROM_HERE, generic_change_processor_)) { NOTREACHED(); } } else { DCHECK(!generic_change_processor_); } } else { DCHECK(backend_loop_.get()); DCHECK(backend_loop_->BelongsToCurrentThread()); delete generic_change_processor_; } } base::WeakPtr<syncer::SyncableService> SharedChangeProcessor::Connect( SyncApiComponentFactory* sync_factory, GenericChangeProcessorFactory* processor_factory, syncer::UserShare* user_share, DataTypeErrorHandler* error_handler, syncer::ModelType type, const base::WeakPtr<syncer::SyncMergeResult>& merge_result) { DCHECK(sync_factory); DCHECK(error_handler); DCHECK_NE(type, syncer::UNSPECIFIED); backend_loop_ = base::MessageLoopProxy::current(); AutoLock lock(monitor_lock_); if (disconnected_) return base::WeakPtr<syncer::SyncableService>(); type_ = type; error_handler_ = error_handler; base::WeakPtr<syncer::SyncableService> local_service = sync_factory->GetSyncableServiceForType(type); if (!local_service.get()) { LOG(WARNING) << "SyncableService destroyed before DTC was stopped."; disconnected_ = true; return base::WeakPtr<syncer::SyncableService>(); } generic_change_processor_ = processor_factory->CreateGenericChangeProcessor(type, user_share, error_handler, local_service, merge_result, sync_factory).release(); return local_service; } bool SharedChangeProcessor::Disconnect() { // May be called from any thread. DVLOG(1) << "Disconnecting change processor."; AutoLock lock(monitor_lock_); bool was_connected = !disconnected_; disconnected_ = true; error_handler_ = NULL; return was_connected; } ChangeProcessor* SharedChangeProcessor::generic_change_processor() { return generic_change_processor_; } int SharedChangeProcessor::GetSyncCount() { DCHECK(backend_loop_.get()); DCHECK(backend_loop_->BelongsToCurrentThread()); AutoLock lock(monitor_lock_); if (disconnected_) { LOG(ERROR) << "Change processor disconnected."; return 0; } return generic_change_processor_->GetSyncCount(); } syncer::SyncError SharedChangeProcessor::ProcessSyncChanges( const tracked_objects::Location& from_here, const syncer::SyncChangeList& list_of_changes) { DCHECK(backend_loop_.get()); DCHECK(backend_loop_->BelongsToCurrentThread()); AutoLock lock(monitor_lock_); if (disconnected_) { // The DTC that disconnects us must ensure it posts a StopSyncing task. // If we reach this, it means it just hasn't executed yet. syncer::SyncError error(FROM_HERE, syncer::SyncError::DATATYPE_ERROR, "Change processor disconnected.", type_); return error; } return generic_change_processor_->ProcessSyncChanges( from_here, list_of_changes); } syncer::SyncDataList SharedChangeProcessor::GetAllSyncData( syncer::ModelType type) const { syncer::SyncDataList data; GetAllSyncDataReturnError(type, &data); // Handles the disconnect case. return data; } syncer::SyncError SharedChangeProcessor::GetAllSyncDataReturnError( syncer::ModelType type, syncer::SyncDataList* data) const { DCHECK(backend_loop_.get()); DCHECK(backend_loop_->BelongsToCurrentThread()); AutoLock lock(monitor_lock_); if (disconnected_) { syncer::SyncError error(FROM_HERE, syncer::SyncError::DATATYPE_ERROR, "Change processor disconnected.", type_); return error; } return generic_change_processor_->GetAllSyncDataReturnError(data); } syncer::SyncError SharedChangeProcessor::UpdateDataTypeContext( syncer::ModelType type, syncer::SyncChangeProcessor::ContextRefreshStatus refresh_status, const std::string& context) { DCHECK(backend_loop_.get()); DCHECK(backend_loop_->BelongsToCurrentThread()); AutoLock lock(monitor_lock_); if (disconnected_) { syncer::SyncError error(FROM_HERE, syncer::SyncError::DATATYPE_ERROR, "Change processor disconnected.", type_); return error; } return generic_change_processor_->UpdateDataTypeContext( type, refresh_status, context); } bool SharedChangeProcessor::SyncModelHasUserCreatedNodes(bool* has_nodes) { DCHECK(backend_loop_.get()); DCHECK(backend_loop_->BelongsToCurrentThread()); AutoLock lock(monitor_lock_); if (disconnected_) { LOG(ERROR) << "Change processor disconnected."; return false; } return generic_change_processor_->SyncModelHasUserCreatedNodes(has_nodes); } bool SharedChangeProcessor::CryptoReadyIfNecessary() { DCHECK(backend_loop_.get()); DCHECK(backend_loop_->BelongsToCurrentThread()); AutoLock lock(monitor_lock_); if (disconnected_) { LOG(ERROR) << "Change processor disconnected."; return true; // Otherwise we get into infinite spin waiting. } return generic_change_processor_->CryptoReadyIfNecessary(); } bool SharedChangeProcessor::GetDataTypeContext(std::string* context) const { DCHECK(backend_loop_.get()); DCHECK(backend_loop_->BelongsToCurrentThread()); AutoLock lock(monitor_lock_); if (disconnected_) { LOG(ERROR) << "Change processor disconnected."; return false; } return generic_change_processor_->GetDataTypeContext(context); } syncer::SyncError SharedChangeProcessor::CreateAndUploadError( const tracked_objects::Location& location, const std::string& message) { AutoLock lock(monitor_lock_); if (!disconnected_) { return error_handler_->CreateAndUploadError(location, message, type_); } else { return syncer::SyncError(location, syncer::SyncError::DATATYPE_ERROR, message, type_); } } } // namespace sync_driver <commit_msg>Delete GenericChangeProcessor synchronously when possible.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/sync_driver/shared_change_processor.h" #include "base/message_loop/message_loop_proxy.h" #include "components/sync_driver/generic_change_processor.h" #include "components/sync_driver/generic_change_processor_factory.h" #include "components/sync_driver/sync_api_component_factory.h" #include "sync/api/sync_change.h" using base::AutoLock; namespace sync_driver { SharedChangeProcessor::SharedChangeProcessor() : disconnected_(false), type_(syncer::UNSPECIFIED), frontend_loop_(base::MessageLoopProxy::current()), generic_change_processor_(NULL), error_handler_(NULL) { } SharedChangeProcessor::~SharedChangeProcessor() { // We can either be deleted when the DTC is destroyed (on UI // thread), or when the syncer::SyncableService stops syncing (datatype // thread). |generic_change_processor_|, if non-NULL, must be // deleted on |backend_loop_|. if (backend_loop_.get()) { if (backend_loop_->BelongsToCurrentThread()) { delete generic_change_processor_; } else { DCHECK(frontend_loop_->BelongsToCurrentThread()); if (!backend_loop_->DeleteSoon(FROM_HERE, generic_change_processor_)) { NOTREACHED(); } } } else { DCHECK(!generic_change_processor_); } } base::WeakPtr<syncer::SyncableService> SharedChangeProcessor::Connect( SyncApiComponentFactory* sync_factory, GenericChangeProcessorFactory* processor_factory, syncer::UserShare* user_share, DataTypeErrorHandler* error_handler, syncer::ModelType type, const base::WeakPtr<syncer::SyncMergeResult>& merge_result) { DCHECK(sync_factory); DCHECK(error_handler); DCHECK_NE(type, syncer::UNSPECIFIED); backend_loop_ = base::MessageLoopProxy::current(); AutoLock lock(monitor_lock_); if (disconnected_) return base::WeakPtr<syncer::SyncableService>(); type_ = type; error_handler_ = error_handler; base::WeakPtr<syncer::SyncableService> local_service = sync_factory->GetSyncableServiceForType(type); if (!local_service.get()) { LOG(WARNING) << "SyncableService destroyed before DTC was stopped."; disconnected_ = true; return base::WeakPtr<syncer::SyncableService>(); } generic_change_processor_ = processor_factory->CreateGenericChangeProcessor(type, user_share, error_handler, local_service, merge_result, sync_factory).release(); return local_service; } bool SharedChangeProcessor::Disconnect() { // May be called from any thread. DVLOG(1) << "Disconnecting change processor."; AutoLock lock(monitor_lock_); bool was_connected = !disconnected_; disconnected_ = true; error_handler_ = NULL; return was_connected; } ChangeProcessor* SharedChangeProcessor::generic_change_processor() { return generic_change_processor_; } int SharedChangeProcessor::GetSyncCount() { DCHECK(backend_loop_.get()); DCHECK(backend_loop_->BelongsToCurrentThread()); AutoLock lock(monitor_lock_); if (disconnected_) { LOG(ERROR) << "Change processor disconnected."; return 0; } return generic_change_processor_->GetSyncCount(); } syncer::SyncError SharedChangeProcessor::ProcessSyncChanges( const tracked_objects::Location& from_here, const syncer::SyncChangeList& list_of_changes) { DCHECK(backend_loop_.get()); DCHECK(backend_loop_->BelongsToCurrentThread()); AutoLock lock(monitor_lock_); if (disconnected_) { // The DTC that disconnects us must ensure it posts a StopSyncing task. // If we reach this, it means it just hasn't executed yet. syncer::SyncError error(FROM_HERE, syncer::SyncError::DATATYPE_ERROR, "Change processor disconnected.", type_); return error; } return generic_change_processor_->ProcessSyncChanges( from_here, list_of_changes); } syncer::SyncDataList SharedChangeProcessor::GetAllSyncData( syncer::ModelType type) const { syncer::SyncDataList data; GetAllSyncDataReturnError(type, &data); // Handles the disconnect case. return data; } syncer::SyncError SharedChangeProcessor::GetAllSyncDataReturnError( syncer::ModelType type, syncer::SyncDataList* data) const { DCHECK(backend_loop_.get()); DCHECK(backend_loop_->BelongsToCurrentThread()); AutoLock lock(monitor_lock_); if (disconnected_) { syncer::SyncError error(FROM_HERE, syncer::SyncError::DATATYPE_ERROR, "Change processor disconnected.", type_); return error; } return generic_change_processor_->GetAllSyncDataReturnError(data); } syncer::SyncError SharedChangeProcessor::UpdateDataTypeContext( syncer::ModelType type, syncer::SyncChangeProcessor::ContextRefreshStatus refresh_status, const std::string& context) { DCHECK(backend_loop_.get()); DCHECK(backend_loop_->BelongsToCurrentThread()); AutoLock lock(monitor_lock_); if (disconnected_) { syncer::SyncError error(FROM_HERE, syncer::SyncError::DATATYPE_ERROR, "Change processor disconnected.", type_); return error; } return generic_change_processor_->UpdateDataTypeContext( type, refresh_status, context); } bool SharedChangeProcessor::SyncModelHasUserCreatedNodes(bool* has_nodes) { DCHECK(backend_loop_.get()); DCHECK(backend_loop_->BelongsToCurrentThread()); AutoLock lock(monitor_lock_); if (disconnected_) { LOG(ERROR) << "Change processor disconnected."; return false; } return generic_change_processor_->SyncModelHasUserCreatedNodes(has_nodes); } bool SharedChangeProcessor::CryptoReadyIfNecessary() { DCHECK(backend_loop_.get()); DCHECK(backend_loop_->BelongsToCurrentThread()); AutoLock lock(monitor_lock_); if (disconnected_) { LOG(ERROR) << "Change processor disconnected."; return true; // Otherwise we get into infinite spin waiting. } return generic_change_processor_->CryptoReadyIfNecessary(); } bool SharedChangeProcessor::GetDataTypeContext(std::string* context) const { DCHECK(backend_loop_.get()); DCHECK(backend_loop_->BelongsToCurrentThread()); AutoLock lock(monitor_lock_); if (disconnected_) { LOG(ERROR) << "Change processor disconnected."; return false; } return generic_change_processor_->GetDataTypeContext(context); } syncer::SyncError SharedChangeProcessor::CreateAndUploadError( const tracked_objects::Location& location, const std::string& message) { AutoLock lock(monitor_lock_); if (!disconnected_) { return error_handler_->CreateAndUploadError(location, message, type_); } else { return syncer::SyncError(location, syncer::SyncError::DATATYPE_ERROR, message, type_); } } } // namespace sync_driver <|endoftext|>
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved. #include "rdb_protocol/artificial_table/artificial_table.hpp" #include "rdb_protocol/artificial_table/backend.hpp" #include "rdb_protocol/env.hpp" #include "rdb_protocol/func.hpp" #include "rdb_protocol/table_common.hpp" /* Determines how many coroutines we spawn for a batched replace or insert. */ static const int max_parallel_ops = 10; artificial_table_t::artificial_table_t(artificial_table_backend_t *_backend) : backend(_backend), primary_key(backend->get_primary_key_name()) { } const std::string &artificial_table_t::get_pkey() { return primary_key; } counted_t<const ql::datum_t> artificial_table_t::read_row(ql::env_t *env, counted_t<const ql::datum_t> pval, UNUSED bool use_outdated) { counted_t<const ql::datum_t> row; std::string error; if (!checked_read_row(pval, env->interruptor, &row, &error)) { throw ql::datum_exc_t(ql::base_exc_t::GENERIC, error); } if (!row.has()) { row = ql::datum_t::null(); } return row; } counted_t<ql::datum_stream_t> artificial_table_t::read_all( ql::env_t *env, const std::string &get_all_sindex_id, const ql::protob_t<const Backtrace> &bt, const std::string &table_name, const datum_range_t &range, sorting_t sorting, UNUSED bool use_outdated) { if (get_all_sindex_id != primary_key) { rfail_datum(ql::base_exc_t::GENERIC, "%s", error_message_index_not_found(get_all_sindex_id, table_name).c_str()); } std::string error; /* Fetch the keys from the backend */ std::vector<counted_t<const ql::datum_t> > keys; if (!backend->read_all_primary_keys(env->interruptor, &keys, &error)) { throw ql::datum_exc_t(ql::base_exc_t::GENERIC, error); } /* Apply range filter */ if (!range.is_universe()) { std::vector<counted_t<const ql::datum_t> > temp; for (auto key : keys) { if (range.contains(reql_version_t::LATEST, key)) { temp.push_back(key); } } keys = std::move(temp); } /* Apply sorting */ switch (sorting) { case sorting_t::UNORDERED: break; case sorting_t::ASCENDING: std::sort(keys.begin(), keys.end(), [](counted_t<const ql::datum_t> a, counted_t<const ql::datum_t> b) { return a->compare_lt(reql_version_t::LATEST, *b); }); break; case sorting_t::DESCENDING: std::sort(keys.begin(), keys.end(), [](counted_t<const ql::datum_t> a, counted_t<const ql::datum_t> b) { return a->compare_gt(reql_version_t::LATEST, *b); }); break; default: unreachable(); } /* Fetch the actual rows from the backend */ ql::datum_array_builder_t array_builder((ql::configured_limits_t())); for (auto key : keys) { counted_t<const ql::datum_t> row; if (!checked_read_row(key, env->interruptor, &row, &error)) { throw ql::datum_exc_t(ql::base_exc_t::GENERIC, error); } if (!row.has()) { /* This can happen due to a race condition, if the row disappears between our call to `read_all_primary_keys()` and our call to `read_row()`. */ continue; } array_builder.add(row); } /* Build a `datum_stream_t` with the results */ return make_counted<ql::array_datum_stream_t>( std::move(array_builder).to_counted(), bt); } counted_t<ql::datum_stream_t> artificial_table_t::read_row_changes( UNUSED ql::env_t *env, UNUSED counted_t<const ql::datum_t> pval, UNUSED const ql::protob_t<const Backtrace> &bt, UNUSED const std::string &table_name) { /* RSI(reql_admin): Artificial tables will eventually support change feeds. */ rfail_datum(ql::base_exc_t::GENERIC, "Artificial tables don't support change-feeds."); } counted_t<ql::datum_stream_t> artificial_table_t::read_all_changes( UNUSED ql::env_t *env, UNUSED const ql::protob_t<const Backtrace> &bt, UNUSED const std::string &table_name) { /* RSI(reql_admin): Artificial tables will eventually support change feeds. */ rfail_datum(ql::base_exc_t::GENERIC, "Artificial tables don't support change-feeds."); } counted_t<ql::datum_stream_t> artificial_table_t::read_intersecting( UNUSED ql::env_t *env, const std::string &sindex, UNUSED const ql::protob_t<const Backtrace> &bt, const std::string &table_name, UNUSED bool use_outdated, UNUSED const counted_t<const ql::datum_t> &query_geometry) { guarantee(sindex != primary_key, "read_intersecting() should never be called with " "the primary index"); rfail_datum(ql::base_exc_t::GENERIC, "%s", error_message_index_not_found(sindex, table_name).c_str()); } counted_t<ql::datum_stream_t> artificial_table_t::read_nearest( UNUSED ql::env_t *env, const std::string &sindex, UNUSED const ql::protob_t<const Backtrace> &bt, const std::string &table_name, UNUSED bool use_outdated, UNUSED lat_lon_point_t center, UNUSED double max_dist, UNUSED uint64_t max_results, UNUSED const ellipsoid_spec_t &geo_system, UNUSED dist_unit_t dist_unit, UNUSED const ql::configured_limits_t &limits) { guarantee(sindex != primary_key, "read_nearest() should never be called with " "the primary index"); rfail_datum(ql::base_exc_t::GENERIC, "%s", error_message_index_not_found(sindex, table_name).c_str()); } counted_t<const ql::datum_t> artificial_table_t::write_batched_replace( ql::env_t *env, const std::vector<counted_t<const ql::datum_t> > &keys, const counted_t<const ql::func_t> &func, return_changes_t return_changes, UNUSED durability_requirement_t durability) { /* RSI(reql_admin): Should we require that durability is soft? */ counted_t<const ql::datum_t> stats = ql::datum_t::empty_object(); std::set<std::string> conditions; throttled_pmap(keys.size(), [&] (int i) { try { do_single_update(keys[i], [&] (counted_t<const ql::datum_t> old_row) { return func->call(env, old_row, ql::LITERAL_OK)->as_datum(); }, return_changes, env->interruptor, &stats, &conditions); } catch (interrupted_exc_t) { /* don't throw since we're in throttled_pmap() */ } }, max_parallel_ops); if (env->interruptor->is_pulsed()) { throw interrupted_exc_t(); } ql::datum_object_builder_t obj_builder(stats->as_object()); obj_builder.add_warnings(conditions, ql::configured_limits_t()); return std::move(obj_builder).to_counted(); } counted_t<const ql::datum_t> artificial_table_t::write_batched_insert( ql::env_t *env, std::vector<counted_t<const ql::datum_t> > &&inserts, conflict_behavior_t conflict_behavior, return_changes_t return_changes, UNUSED durability_requirement_t durability) { counted_t<const ql::datum_t> stats = ql::datum_t::empty_object(); std::set<std::string> conditions; throttled_pmap(inserts.size(), [&] (int i) { try { counted_t<const ql::datum_t> insert_row = inserts[i]; counted_t<const ql::datum_t> key = insert_row->get(primary_key, ql::NOTHROW); guarantee(key.has(), "write_batched_insert() shouldn't ever be called with " "documents that lack a primary key."); do_single_update(key, [&](counted_t<const ql::datum_t> old_row) { return resolve_insert_conflict( primary_key, old_row, insert_row, conflict_behavior); }, return_changes, env->interruptor, &stats, &conditions); } catch (interrupted_exc_t) { /* don't throw since we're in throttled_pmap() */ } }, max_parallel_ops); if (env->interruptor->is_pulsed()) { throw interrupted_exc_t(); } ql::datum_object_builder_t obj_builder(stats->as_object()); obj_builder.add_warnings(conditions, ql::configured_limits_t()); return std::move(obj_builder).to_counted(); } bool artificial_table_t::write_sync_depending_on_durability( UNUSED ql::env_t *env, UNUSED durability_requirement_t durability) { /* Calling `sync()` on an artificial table is a meaningful operation; it would mean to flush the metadata to disk. But it would be a lot of trouble to implement in practice, so we don't. */ rfail_datum(ql::base_exc_t::GENERIC, "Artificial tables don't support `sync()`."); } bool artificial_table_t::sindex_create( UNUSED ql::env_t *env, UNUSED const std::string &id, UNUSED counted_t<const ql::func_t> index_func, UNUSED sindex_multi_bool_t multi, UNUSED sindex_geo_bool_t geo) { rfail_datum(ql::base_exc_t::GENERIC, "Can't create a secondary index on an artificial table."); } bool artificial_table_t::sindex_drop(UNUSED ql::env_t *env, UNUSED const std::string &id) { rfail_datum(ql::base_exc_t::GENERIC, "Can't drop a secondary index on an artificial table."); } sindex_rename_result_t artificial_table_t::sindex_rename( UNUSED ql::env_t *env, UNUSED const std::string &old_name, UNUSED const std::string &new_name, UNUSED bool overwrite) { rfail_datum(ql::base_exc_t::GENERIC, "Can't rename a secondary index on an artificial table."); } std::vector<std::string> artificial_table_t::sindex_list(UNUSED ql::env_t *env) { return std::vector<std::string>(); } std::map<std::string, counted_t<const ql::datum_t> > artificial_table_t::sindex_status( UNUSED ql::env_t *env, UNUSED const std::set<std::string> &sindexes) { return std::map<std::string, counted_t<const ql::datum_t> >(); } bool artificial_table_t::checked_read_row( counted_t<const ql::datum_t> pval, signal_t *interruptor, counted_t<const ql::datum_t> *row_out, std::string *error_out) { if (!backend->read_row(pval, interruptor, row_out, error_out)) { return false; } #ifndef NDEBUG if (row_out->has()) { counted_t<const ql::datum_t> pval2 = (*row_out)->get(get_pkey(), ql::NOTHROW); rassert(pval2.has()); rassert(*pval2 == *pval); } #endif return true; } void artificial_table_t::do_single_update( counted_t<const ql::datum_t> pval, const std::function<counted_t<const ql::datum_t>(counted_t<const ql::datum_t>)> &function, return_changes_t return_changes, signal_t *interruptor, counted_t<const ql::datum_t> *stats_inout, std::set<std::string> *conditions_inout) { std::string error; counted_t<const ql::datum_t> old_row; if (!checked_read_row(pval, interruptor, &old_row, &error)) { ql::datum_object_builder_t builder; builder.add_error(error.c_str()); *stats_inout = (*stats_inout)->merge( std::move(builder).to_counted(), ql::stats_merge, ql::configured_limits_t(), conditions_inout); return; } if (!old_row.has()) { old_row = ql::datum_t::null(); } counted_t<const ql::datum_t> resp; try { counted_t<const ql::datum_t> new_row = function(old_row); bool was_changed; resp = make_row_replacement_stats( primary_key, store_key_t(pval->print_primary()), old_row, new_row, return_changes, &was_changed); if (was_changed) { if (new_row->get_type() == ql::datum_t::R_NULL) { new_row.reset(); } if (!backend->write_row(pval, new_row, interruptor, &error)) { rfail_datum(ql::base_exc_t::GENERIC, "%s", error.c_str()); } } } catch (const ql::base_exc_t &e) { resp = make_row_replacement_error_stats( old_row, return_changes, e.what()); } *stats_inout = (*stats_inout)->merge( resp, ql::stats_merge, ql::configured_limits_t(), conditions_inout); } <commit_msg>Pass counted_t<const ql::datum_t> by const reference for slightly better performance.<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved. #include "rdb_protocol/artificial_table/artificial_table.hpp" #include "rdb_protocol/artificial_table/backend.hpp" #include "rdb_protocol/env.hpp" #include "rdb_protocol/func.hpp" #include "rdb_protocol/table_common.hpp" /* Determines how many coroutines we spawn for a batched replace or insert. */ static const int max_parallel_ops = 10; artificial_table_t::artificial_table_t(artificial_table_backend_t *_backend) : backend(_backend), primary_key(backend->get_primary_key_name()) { } const std::string &artificial_table_t::get_pkey() { return primary_key; } counted_t<const ql::datum_t> artificial_table_t::read_row(ql::env_t *env, counted_t<const ql::datum_t> pval, UNUSED bool use_outdated) { counted_t<const ql::datum_t> row; std::string error; if (!checked_read_row(pval, env->interruptor, &row, &error)) { throw ql::datum_exc_t(ql::base_exc_t::GENERIC, error); } if (!row.has()) { row = ql::datum_t::null(); } return row; } counted_t<ql::datum_stream_t> artificial_table_t::read_all( ql::env_t *env, const std::string &get_all_sindex_id, const ql::protob_t<const Backtrace> &bt, const std::string &table_name, const datum_range_t &range, sorting_t sorting, UNUSED bool use_outdated) { if (get_all_sindex_id != primary_key) { rfail_datum(ql::base_exc_t::GENERIC, "%s", error_message_index_not_found(get_all_sindex_id, table_name).c_str()); } std::string error; /* Fetch the keys from the backend */ std::vector<counted_t<const ql::datum_t> > keys; if (!backend->read_all_primary_keys(env->interruptor, &keys, &error)) { throw ql::datum_exc_t(ql::base_exc_t::GENERIC, error); } /* Apply range filter */ if (!range.is_universe()) { std::vector<counted_t<const ql::datum_t> > temp; for (const counted_t<const ql::datum_t> &key : keys) { if (range.contains(reql_version_t::LATEST, key)) { temp.push_back(key); } } keys = std::move(temp); } /* Apply sorting */ switch (sorting) { case sorting_t::UNORDERED: break; case sorting_t::ASCENDING: std::sort(keys.begin(), keys.end(), [](const counted_t<const ql::datum_t> &a, const counted_t<const ql::datum_t> &b) { return a->compare_lt(reql_version_t::LATEST, *b); }); break; case sorting_t::DESCENDING: std::sort(keys.begin(), keys.end(), [](const counted_t<const ql::datum_t> &a, const counted_t<const ql::datum_t> &b) { return a->compare_gt(reql_version_t::LATEST, *b); }); break; default: unreachable(); } /* Fetch the actual rows from the backend */ ql::datum_array_builder_t array_builder((ql::configured_limits_t())); for (auto key : keys) { counted_t<const ql::datum_t> row; if (!checked_read_row(key, env->interruptor, &row, &error)) { throw ql::datum_exc_t(ql::base_exc_t::GENERIC, error); } if (!row.has()) { /* This can happen due to a race condition, if the row disappears between our call to `read_all_primary_keys()` and our call to `read_row()`. */ continue; } array_builder.add(row); } /* Build a `datum_stream_t` with the results */ return make_counted<ql::array_datum_stream_t>( std::move(array_builder).to_counted(), bt); } counted_t<ql::datum_stream_t> artificial_table_t::read_row_changes( UNUSED ql::env_t *env, UNUSED counted_t<const ql::datum_t> pval, UNUSED const ql::protob_t<const Backtrace> &bt, UNUSED const std::string &table_name) { /* RSI(reql_admin): Artificial tables will eventually support change feeds. */ rfail_datum(ql::base_exc_t::GENERIC, "Artificial tables don't support change-feeds."); } counted_t<ql::datum_stream_t> artificial_table_t::read_all_changes( UNUSED ql::env_t *env, UNUSED const ql::protob_t<const Backtrace> &bt, UNUSED const std::string &table_name) { /* RSI(reql_admin): Artificial tables will eventually support change feeds. */ rfail_datum(ql::base_exc_t::GENERIC, "Artificial tables don't support change-feeds."); } counted_t<ql::datum_stream_t> artificial_table_t::read_intersecting( UNUSED ql::env_t *env, const std::string &sindex, UNUSED const ql::protob_t<const Backtrace> &bt, const std::string &table_name, UNUSED bool use_outdated, UNUSED const counted_t<const ql::datum_t> &query_geometry) { guarantee(sindex != primary_key, "read_intersecting() should never be called with " "the primary index"); rfail_datum(ql::base_exc_t::GENERIC, "%s", error_message_index_not_found(sindex, table_name).c_str()); } counted_t<ql::datum_stream_t> artificial_table_t::read_nearest( UNUSED ql::env_t *env, const std::string &sindex, UNUSED const ql::protob_t<const Backtrace> &bt, const std::string &table_name, UNUSED bool use_outdated, UNUSED lat_lon_point_t center, UNUSED double max_dist, UNUSED uint64_t max_results, UNUSED const ellipsoid_spec_t &geo_system, UNUSED dist_unit_t dist_unit, UNUSED const ql::configured_limits_t &limits) { guarantee(sindex != primary_key, "read_nearest() should never be called with " "the primary index"); rfail_datum(ql::base_exc_t::GENERIC, "%s", error_message_index_not_found(sindex, table_name).c_str()); } counted_t<const ql::datum_t> artificial_table_t::write_batched_replace( ql::env_t *env, const std::vector<counted_t<const ql::datum_t> > &keys, const counted_t<const ql::func_t> &func, return_changes_t return_changes, UNUSED durability_requirement_t durability) { /* RSI(reql_admin): Should we require that durability is soft? */ counted_t<const ql::datum_t> stats = ql::datum_t::empty_object(); std::set<std::string> conditions; throttled_pmap(keys.size(), [&] (int i) { try { do_single_update(keys[i], [&] (counted_t<const ql::datum_t> old_row) { return func->call(env, old_row, ql::LITERAL_OK)->as_datum(); }, return_changes, env->interruptor, &stats, &conditions); } catch (interrupted_exc_t) { /* don't throw since we're in throttled_pmap() */ } }, max_parallel_ops); if (env->interruptor->is_pulsed()) { throw interrupted_exc_t(); } ql::datum_object_builder_t obj_builder(stats->as_object()); obj_builder.add_warnings(conditions, ql::configured_limits_t()); return std::move(obj_builder).to_counted(); } counted_t<const ql::datum_t> artificial_table_t::write_batched_insert( ql::env_t *env, std::vector<counted_t<const ql::datum_t> > &&inserts, conflict_behavior_t conflict_behavior, return_changes_t return_changes, UNUSED durability_requirement_t durability) { counted_t<const ql::datum_t> stats = ql::datum_t::empty_object(); std::set<std::string> conditions; throttled_pmap(inserts.size(), [&] (int i) { try { counted_t<const ql::datum_t> insert_row = inserts[i]; counted_t<const ql::datum_t> key = insert_row->get(primary_key, ql::NOTHROW); guarantee(key.has(), "write_batched_insert() shouldn't ever be called with " "documents that lack a primary key."); do_single_update(key, [&](counted_t<const ql::datum_t> old_row) { return resolve_insert_conflict( primary_key, old_row, insert_row, conflict_behavior); }, return_changes, env->interruptor, &stats, &conditions); } catch (interrupted_exc_t) { /* don't throw since we're in throttled_pmap() */ } }, max_parallel_ops); if (env->interruptor->is_pulsed()) { throw interrupted_exc_t(); } ql::datum_object_builder_t obj_builder(stats->as_object()); obj_builder.add_warnings(conditions, ql::configured_limits_t()); return std::move(obj_builder).to_counted(); } bool artificial_table_t::write_sync_depending_on_durability( UNUSED ql::env_t *env, UNUSED durability_requirement_t durability) { /* Calling `sync()` on an artificial table is a meaningful operation; it would mean to flush the metadata to disk. But it would be a lot of trouble to implement in practice, so we don't. */ rfail_datum(ql::base_exc_t::GENERIC, "Artificial tables don't support `sync()`."); } bool artificial_table_t::sindex_create( UNUSED ql::env_t *env, UNUSED const std::string &id, UNUSED counted_t<const ql::func_t> index_func, UNUSED sindex_multi_bool_t multi, UNUSED sindex_geo_bool_t geo) { rfail_datum(ql::base_exc_t::GENERIC, "Can't create a secondary index on an artificial table."); } bool artificial_table_t::sindex_drop(UNUSED ql::env_t *env, UNUSED const std::string &id) { rfail_datum(ql::base_exc_t::GENERIC, "Can't drop a secondary index on an artificial table."); } sindex_rename_result_t artificial_table_t::sindex_rename( UNUSED ql::env_t *env, UNUSED const std::string &old_name, UNUSED const std::string &new_name, UNUSED bool overwrite) { rfail_datum(ql::base_exc_t::GENERIC, "Can't rename a secondary index on an artificial table."); } std::vector<std::string> artificial_table_t::sindex_list(UNUSED ql::env_t *env) { return std::vector<std::string>(); } std::map<std::string, counted_t<const ql::datum_t> > artificial_table_t::sindex_status( UNUSED ql::env_t *env, UNUSED const std::set<std::string> &sindexes) { return std::map<std::string, counted_t<const ql::datum_t> >(); } bool artificial_table_t::checked_read_row( counted_t<const ql::datum_t> pval, signal_t *interruptor, counted_t<const ql::datum_t> *row_out, std::string *error_out) { if (!backend->read_row(pval, interruptor, row_out, error_out)) { return false; } #ifndef NDEBUG if (row_out->has()) { counted_t<const ql::datum_t> pval2 = (*row_out)->get(get_pkey(), ql::NOTHROW); rassert(pval2.has()); rassert(*pval2 == *pval); } #endif return true; } void artificial_table_t::do_single_update( counted_t<const ql::datum_t> pval, const std::function<counted_t<const ql::datum_t>(counted_t<const ql::datum_t>)> &function, return_changes_t return_changes, signal_t *interruptor, counted_t<const ql::datum_t> *stats_inout, std::set<std::string> *conditions_inout) { std::string error; counted_t<const ql::datum_t> old_row; if (!checked_read_row(pval, interruptor, &old_row, &error)) { ql::datum_object_builder_t builder; builder.add_error(error.c_str()); *stats_inout = (*stats_inout)->merge( std::move(builder).to_counted(), ql::stats_merge, ql::configured_limits_t(), conditions_inout); return; } if (!old_row.has()) { old_row = ql::datum_t::null(); } counted_t<const ql::datum_t> resp; try { counted_t<const ql::datum_t> new_row = function(old_row); bool was_changed; resp = make_row_replacement_stats( primary_key, store_key_t(pval->print_primary()), old_row, new_row, return_changes, &was_changed); if (was_changed) { if (new_row->get_type() == ql::datum_t::R_NULL) { new_row.reset(); } if (!backend->write_row(pval, new_row, interruptor, &error)) { rfail_datum(ql::base_exc_t::GENERIC, "%s", error.c_str()); } } } catch (const ql::base_exc_t &e) { resp = make_row_replacement_error_stats( old_row, return_changes, e.what()); } *stats_inout = (*stats_inout)->merge( resp, ql::stats_merge, ql::configured_limits_t(), conditions_inout); } <|endoftext|>