{"text":"\/**\n * @file labelProp.hpp\n * @ingroup group\n * @author Chirag Jain \n * @brief Connected component labeling using label propagation (or coloring) approach\n *\n * Copyright (c) 2015 Georgia Institute of Technology. All Rights Reserved.\n *\/\n\n#ifndef LABEL_PROPAGATION_HPP \n#define LABEL_PROPAGATION_HPP\n\n\/\/Includes\n#include \n\n\/\/Own includes\n#include \"coloring\/tupleComp.hpp\"\n#include \"coloring\/labelProp_utils.hpp\"\n#include \"utils\/commonfuncs.hpp\"\n#include \"utils\/logging.hpp\"\n#include \"utils\/prettyprint.hpp\"\n\n#include \"mxx\/sort.hpp\"\n#include \"mxx_extra\/sort.hpp\"\n#include \"mxx\/timer.hpp\"\n#include \"mxx\/comm.hpp\"\n\nnamespace conn \n{\n namespace coloring\n {\n\n \/**\n * @class conn::coloring::ccl\n * @brief supports parallel connected component labeling using label propagation technique\n * @tparam[in] pIdtype type used for partition ids\n * @tparam[in] nIdType type used for node id\n * @tparam[in] OPTIMIZATION optimization level for benchmarking, use loadbalanced for the best version \n *\/\n template\n class ccl \n {\n public:\n \/\/Type for saving parition ids\n using partitionIdtype = pIdtype;\n\n \/\/Type for saving node ids\n using nodeIdType = nIdType;\n\n \/\/This is the communicator which participates for computing the components\n mxx::comm comm;\n\n private:\n\n using T = std::tuple;\n std::vector tupleVector;\n\n \/\/Used during initialization of \n \/\/Also used to mark partitions as stable\n pIdtype MAX = std::numeric_limits::max();\n\n \/\/Used to mark tuples as stable \n \/\/partitions would become stable if all its tuples are stable\n pIdtype MAX2 = std::numeric_limits::max() -1 ;\n\n public:\n \/**\n * @brief public constructor\n * @param[in] edgeList distributed vector of edges\n * @param[in] c mpi communicator for the execution \n *\/\n template \n ccl(edgeListPairsType &edgeList, const mxx::comm &c) : comm(c.copy()) \n {\n \/\/Parse the edgeList\n convertEdgeListforCCL(edgeList);\n\n \/\/Re-distribute the tuples uniformly across the ranks\n mxx::distribute_inplace(tupleVector, comm);\n }\n\n \/\/Compute the connected component labels\n void compute()\n {\n \/\/Size of vector should be >= 0\n assert(tupleVector.begin() != tupleVector.end());\n\n runConnectedComponentLabeling();\n }\n\n \/**\n * @brief count the components in the graph after ccl (useful for debugging\/testing)\n * @return count \n * @note should be called after computing connected components. \n * assumes vector is sorted by Pc\n *\/\n std::size_t getComponentCount()\n {\n \/\/Vector should be sorted by Pc\n if(!mxx::is_sorted(tupleVector.begin(), tupleVector.end(), TpleComp(), comm))\n mxx::sort(tupleVector.begin(), tupleVector.end(), TpleComp(), comm);\n\n \/\/Count unique Pc values\n return mxx::uniqueCount(tupleVector.begin(), tupleVector.end(), TpleComp(), comm);\n }\n\n \/**\n * @brief Free the communicator\n * @note Its mandatory to call this function \n *\/\n void free_comm()\n {\n comm.~comm();\n }\n\n private:\n\n \/**\n * @brief converts the edgelist to vector of tuples needed for ccl\n * @details For the bucket in the edgeList ...<(u, v1), (u,v2)>...\n * we append <(u, ~, u), (u, ~, v1), (u, ~, v2)> to our tupleVector\n * We ignore the bucket splits across ranks here, because that shouldn't affect the correctness and complexity\n *\/\n template \n void convertEdgeListforCCL(edgeListPairsType &edgeList)\n {\n mxx::section_timer timer(std::cerr, comm);\n\n \/\/Sort the edgeList by src id of each edge\n mxx::sort(edgeList.begin(), edgeList.end(), TpleComp(), comm); \n\n \/\/Reserve the approximate required space in our vector\n tupleVector.reserve(edgeList.size());\n\n for(auto it = edgeList.begin(); it != edgeList.end(); )\n {\n \/\/Range of edges with same source vertex\n auto equalRange = conn::utils::findRange(it, edgeList.end(), *it, TpleComp());\n\n \/\/Range would include atleast 1 element\n assert(std::distance(equalRange.first, equalRange.second) >= 1);\n\n \/\/Insert the self loop\n tupleVector.emplace_back(std::get(*it), MAX, std::get(*it)); \n\n \/\/Insert other vertex members in this partition \n for(auto it2 = equalRange.first; it2 != equalRange.second; it2++)\n tupleVector.emplace_back(std::get(*it2), MAX, std::get(*it2));;\n\n it = equalRange.second;\n }\n\n timer.end_section(\"vector of tuples initialized for ccl\");\n\n \/\/Log the total count of tuples \n auto totalTupleCount = mxx::reduce(tupleVector.size(), 0, comm);\n\n LOG_IF(comm.rank() == 0, INFO) << \"Total tuple count is \" << totalTupleCount;\n }\n\n \/**\n * @brief run the iterative algorithm for ccl\n *\/\n void runConnectedComponentLabeling()\n {\n bool converged = false;\n\n int iterCount = 0;\n\n mxx::section_timer timer(std::cerr, comm);\n\n auto begin = tupleVector.begin();\n auto end = tupleVector.end();\n auto mid = begin; \/\/range mid-end represents active partitions\n\n while(!converged)\n {\n updatePn(mid, end);\n\n converged = updatePc(mid, end);\n\n \/\/parition the dataset into stable and active paritions, if optimization is enabled\n if(!converged && (OPTIMIZATION == opt_level::stable_partition_removed || OPTIMIZATION == opt_level::loadbalanced))\n {\n \/\/use std::partition to move stable tuples to the left\n \/\/After this step, mid-end would represent active tuples\n mid = partitionStableTuples( mid, end );\n\n if(OPTIMIZATION == opt_level::loadbalanced)\n mid = mxx::block_decompose_partitions(begin, mid, end, comm);\n \/\/Re distributed the tuples to balance the load across the ranks\n }\n\n\n iterCount ++;\n }\n\n timer.end_section(\"Coloring done\");\n\n LOG_IF(comm.rank() == 0, INFO) << \"Iteration count \" << iterCount;\n }\n\n \/**\n * @brief update the Pn layer by sorting the tuples using node ids\n * @param[in] begin To iterate over the vector of tuples, marks the range of active tuples \n * @param[in] end end iterator\n *\/\n template \n void updatePn(Iterator begin, Iterator end)\n {\n \/\/Sort by nid,Pc\n mxx::sort(begin, end, TpleComp2Layers(), comm); \n\n \/\/Resolve last and first bucket's boundary splits\n \n \/\/First, find the element with max node id and min Pc locally \n \/\/Or in other words, get the min Pc of the last bucket\n auto minPcOfLastBucket = mxx::local_reduce(begin, end, TpleReduce2Layers());\n\n \/\/Second, do exscan, look for max nodeid and min Pc on previous ranks\n auto prevMinPc = mxx::exscan(minPcOfLastBucket, TpleReduce2Layers(), comm); \n\n \/\/We also need to know max Pc of the first bucket on the next rank (to check for stability)\n auto maxPcOfFirstBucket = mxx::local_reduce(begin, end, TpleReduce2Layers());\n\n \/\/reverse exscan, look for min nodeid and max Pc on forward ranks\n auto nextMaxPc = mxx::exscan(maxPcOfFirstBucket, TpleReduce2Layers(), comm.reverse()); \n\n \/\/Now we can update the Pn layer of all the buckets locally\n for(auto it = begin; it != end;)\n {\n \/\/Range of tuples with the same node id\n auto equalRange = conn::utils::findRange(it, end, *it, TpleComp());\n\n \/\/Range would include atleast 1 element\n assert(std::distance(equalRange.first, equalRange.second) >= 1);\n\n \/\/Minimum Pc from local bucket\n auto thisBucketsMinPcLocal = mxx::local_reduce(equalRange.first, equalRange.second, TpleReduce());\n\n \/\/Maximum Pc from local bucket\n auto thisBucketsMaxPcLocal = mxx::local_reduce(equalRange.first, equalRange.second, TpleReduce());\n\n \/\/For now, mark global minimum as local\n auto thisBucketsMaxPcGlobal = thisBucketsMaxPcLocal;\n auto thisBucketsMinPcGlobal = thisBucketsMinPcLocal;\n\n \/\/Treat first, last buckets as special cases\n if(equalRange.first == begin)\n {\n \/\/Use value from previous rank\n thisBucketsMinPcGlobal = comm.rank() == 0 ? thisBucketsMinPcLocal : TpleReduce2Layers() (prevMinPc, thisBucketsMinPcLocal);\n }\n\n if(equalRange.second == end)\n {\n \/\/Use value from next rank\n thisBucketsMaxPcGlobal = comm.rank() == comm.size() - 1 ? thisBucketsMaxPcLocal : TpleReduce2Layers() (nextMaxPc, thisBucketsMaxPcLocal);\n\n }\n\n \/\/If min Pc < max Pc for this bucket, update Pn or else mark them as stable\n if(TpleComp()(thisBucketsMinPcGlobal, thisBucketsMaxPcGlobal))\n std::for_each(equalRange.first, equalRange.second, [&](T &e){\n std::get(e) = std::get(thisBucketsMinPcGlobal);\n });\n else\n std::for_each(equalRange.first, equalRange.second, [&](T &e){\n std::get(e) = MAX2;\n });\n\n \/\/Advance the loop pointer\n it = equalRange.second;\n }\n }\n\n \/**\n * @brief update the Pc layer by choosing min Pn\n * @param[in] begin To iterate over the vector of tuples, marks the range of active tuples \n * @param[in] end end iterator\n * @return bool value, true if the algorithm is converged\n *\/\n template \n bool updatePc(Iterator begin, Iterator end)\n {\n \/\/converged yet\n uint8_t converged = 1; \/\/ 1 means true, we will update it below\n\n \/\/Sort by Pc, Pn\n mxx::sort(begin, end, TpleComp2Layers(), comm); \n\n \/\/Resolve last bucket's boundary split\n \n \/\/First, find the element with max Pc and min Pn locally \n \/\/Or in other words, get the min Pn of the last bucket\n auto minPnOfLastBucket = mxx::local_reduce(begin, end, TpleReduce2Layers());\n\n \/\/Result of exscan, again look for max Pc and min Pn on previous ranks\n auto prevMinPn = mxx::exscan(minPnOfLastBucket, TpleReduce2Layers(), comm); \n\n \/\/Now we can update the Pc layer of all the buckets locally\n for(auto it = begin; it != end;)\n {\n \/\/Range of tuples with the same Pc\n auto equalRange = conn::utils::findRange(it, end, *it, TpleComp());\n\n \/\/Range would include atleast 1 element\n assert(std::distance(equalRange.first, equalRange.second) >= 1);\n\n\n \/\/Minimum Pn from local bucket\n auto thisBucketsMinPnLocal = mxx::local_reduce(equalRange.first, equalRange.second, TpleReduce());\n\n \/\/For now, mark global minimum as local\n auto thisBucketsMinPnGlobal = thisBucketsMinPnLocal;\n\n \/\/Treat first, last buckets as special cases\n if(equalRange.first == begin)\n {\n \/\/Use value from previous rank\n thisBucketsMinPnGlobal = comm.rank() == 0 ? thisBucketsMinPnLocal : TpleReduce2Layers() (prevMinPn, thisBucketsMinPnLocal);\n }\n\n \/\/If min Pn < MAX2 for this bucket, update the Pc to new value or else mark the partition as stable\n if(std::get(thisBucketsMinPnGlobal) < MAX2) {\n converged = 0;\n std::for_each(equalRange.first, equalRange.second, [&](T &e){\n std::get(e) = std::get(thisBucketsMinPnGlobal);\n });\n }\n else\n std::for_each(equalRange.first, equalRange.second, [&](T &e){\n std::get(e) = MAX;\n });\n\n \/\/Advance the loop pointer\n it = equalRange.second;\n }\n\n \/\/Know convergence of all the ranks\n uint8_t allConverged;\n mxx::allreduce(&converged, 1, &allConverged, mxx::min(), comm);\n\n return (allConverged == 1 ? true : false);\n }\n\n template \n Iterator partitionStableTuples(Iterator begin, Iterator end)\n {\n return std::partition(begin, end, [&](const T &e){\n return std::get(e) == MAX;\n });\n }\n };\n\n }\n}\n\n#endif\nMinor fix\/**\n * @file labelProp.hpp\n * @ingroup group\n * @author Chirag Jain \n * @brief Connected component labeling using label propagation (or coloring) approach\n *\n * Copyright (c) 2015 Georgia Institute of Technology. All Rights Reserved.\n *\/\n\n#ifndef LABEL_PROPAGATION_HPP \n#define LABEL_PROPAGATION_HPP\n\n\/\/Includes\n#include \n\n\/\/Own includes\n#include \"coloring\/tupleComp.hpp\"\n#include \"coloring\/labelProp_utils.hpp\"\n#include \"utils\/commonfuncs.hpp\"\n#include \"utils\/logging.hpp\"\n#include \"utils\/prettyprint.hpp\"\n\n#include \"mxx\/sort.hpp\"\n#include \"mxx_extra\/sort.hpp\"\n#include \"mxx\/timer.hpp\"\n#include \"mxx\/comm.hpp\"\n\nnamespace conn \n{\n namespace coloring\n {\n\n \/**\n * @class conn::coloring::ccl\n * @brief supports parallel connected component labeling using label propagation technique\n * @tparam[in] pIdtype type used for partition ids\n * @tparam[in] nIdType type used for node id\n * @tparam[in] OPTIMIZATION optimization level for benchmarking, use loadbalanced for the best version \n *\/\n template\n class ccl \n {\n public:\n \/\/Type for saving parition ids\n using partitionIdtype = pIdtype;\n\n \/\/Type for saving node ids\n using nodeIdType = nIdType;\n\n private:\n\n \/\/This is the communicator which participates for computing the components\n mxx::comm comm;\n\n private:\n\n using T = std::tuple;\n std::vector tupleVector;\n\n \/\/Used during initialization of \n \/\/Also used to mark partitions as stable\n pIdtype MAX = std::numeric_limits::max();\n\n \/\/Used to mark tuples as stable \n \/\/partitions would become stable if all its tuples are stable\n pIdtype MAX2 = std::numeric_limits::max() -1 ;\n\n public:\n \/**\n * @brief public constructor\n * @param[in] edgeList distributed vector of edges\n * @param[in] c mpi communicator for the execution \n *\/\n template \n ccl(edgeListPairsType &edgeList, const mxx::comm &c) : comm(c.copy()) \n {\n \/\/Parse the edgeList\n convertEdgeListforCCL(edgeList);\n\n \/\/Re-distribute the tuples uniformly across the ranks\n mxx::distribute_inplace(tupleVector, comm);\n }\n\n \/\/Compute the connected component labels\n void compute()\n {\n \/\/Size of vector should be >= 0\n assert(tupleVector.begin() != tupleVector.end());\n\n runConnectedComponentLabeling();\n }\n\n \/**\n * @brief count the components in the graph after ccl (useful for debugging\/testing)\n * @return count \n * @note should be called after computing connected components. \n * assumes vector is sorted by Pc\n *\/\n std::size_t getComponentCount()\n {\n \/\/Vector should be sorted by Pc\n if(!mxx::is_sorted(tupleVector.begin(), tupleVector.end(), TpleComp(), comm))\n mxx::sort(tupleVector.begin(), tupleVector.end(), TpleComp(), comm);\n\n \/\/Count unique Pc values\n return mxx::uniqueCount(tupleVector.begin(), tupleVector.end(), TpleComp(), comm);\n }\n\n \/**\n * @brief Free the communicator\n * @note Its mandatory to call this function \n *\/\n void free_comm()\n {\n comm.~comm();\n }\n\n private:\n\n \/**\n * @brief converts the edgelist to vector of tuples needed for ccl\n * @details For the bucket in the edgeList ...<(u, v1), (u,v2)>...\n * we append <(u, ~, u), (u, ~, v1), (u, ~, v2)> to our tupleVector\n * We ignore the bucket splits across ranks here, because that shouldn't affect the correctness and complexity\n *\/\n template \n void convertEdgeListforCCL(edgeListPairsType &edgeList)\n {\n mxx::section_timer timer(std::cerr, comm);\n\n \/\/Sort the edgeList by src id of each edge\n mxx::sort(edgeList.begin(), edgeList.end(), TpleComp(), comm); \n\n \/\/Reserve the approximate required space in our vector\n tupleVector.reserve(edgeList.size());\n\n for(auto it = edgeList.begin(); it != edgeList.end(); )\n {\n \/\/Range of edges with same source vertex\n auto equalRange = conn::utils::findRange(it, edgeList.end(), *it, TpleComp());\n\n \/\/Range would include atleast 1 element\n assert(std::distance(equalRange.first, equalRange.second) >= 1);\n\n \/\/Insert the self loop\n tupleVector.emplace_back(std::get(*it), MAX, std::get(*it)); \n\n \/\/Insert other vertex members in this partition \n for(auto it2 = equalRange.first; it2 != equalRange.second; it2++)\n tupleVector.emplace_back(std::get(*it2), MAX, std::get(*it2));;\n\n it = equalRange.second;\n }\n\n timer.end_section(\"vector of tuples initialized for ccl\");\n\n \/\/Log the total count of tuples \n auto totalTupleCount = mxx::reduce(tupleVector.size(), 0, comm);\n\n LOG_IF(comm.rank() == 0, INFO) << \"Total tuple count is \" << totalTupleCount;\n }\n\n \/**\n * @brief run the iterative algorithm for ccl\n *\/\n void runConnectedComponentLabeling()\n {\n bool converged = false;\n\n int iterCount = 0;\n\n mxx::section_timer timer(std::cerr, comm);\n\n auto begin = tupleVector.begin();\n auto end = tupleVector.end();\n auto mid = begin; \/\/range mid-end represents active partitions\n\n while(!converged)\n {\n updatePn(mid, end);\n\n converged = updatePc(mid, end);\n\n \/\/parition the dataset into stable and active paritions, if optimization is enabled\n if(!converged && (OPTIMIZATION == opt_level::stable_partition_removed || OPTIMIZATION == opt_level::loadbalanced))\n {\n \/\/use std::partition to move stable tuples to the left\n \/\/After this step, mid-end would represent active tuples\n mid = partitionStableTuples( mid, end );\n\n if(OPTIMIZATION == opt_level::loadbalanced)\n mid = mxx::block_decompose_partitions(begin, mid, end, comm);\n \/\/Re distributed the tuples to balance the load across the ranks\n }\n\n\n iterCount ++;\n }\n\n timer.end_section(\"Coloring done\");\n\n LOG_IF(comm.rank() == 0, INFO) << \"Iteration count \" << iterCount;\n }\n\n \/**\n * @brief update the Pn layer by sorting the tuples using node ids\n * @param[in] begin To iterate over the vector of tuples, marks the range of active tuples \n * @param[in] end end iterator\n *\/\n template \n void updatePn(Iterator begin, Iterator end)\n {\n \/\/Sort by nid,Pc\n mxx::sort(begin, end, TpleComp2Layers(), comm); \n\n \/\/Resolve last and first bucket's boundary splits\n \n \/\/First, find the element with max node id and min Pc locally \n \/\/Or in other words, get the min Pc of the last bucket\n auto minPcOfLastBucket = mxx::local_reduce(begin, end, TpleReduce2Layers());\n\n \/\/Second, do exscan, look for max nodeid and min Pc on previous ranks\n auto prevMinPc = mxx::exscan(minPcOfLastBucket, TpleReduce2Layers(), comm); \n\n \/\/We also need to know max Pc of the first bucket on the next rank (to check for stability)\n auto maxPcOfFirstBucket = mxx::local_reduce(begin, end, TpleReduce2Layers());\n\n \/\/reverse exscan, look for min nodeid and max Pc on forward ranks\n auto nextMaxPc = mxx::exscan(maxPcOfFirstBucket, TpleReduce2Layers(), comm.reverse()); \n\n \/\/Now we can update the Pn layer of all the buckets locally\n for(auto it = begin; it != end;)\n {\n \/\/Range of tuples with the same node id\n auto equalRange = conn::utils::findRange(it, end, *it, TpleComp());\n\n \/\/Range would include atleast 1 element\n assert(std::distance(equalRange.first, equalRange.second) >= 1);\n\n \/\/Minimum Pc from local bucket\n auto thisBucketsMinPcLocal = mxx::local_reduce(equalRange.first, equalRange.second, TpleReduce());\n\n \/\/Maximum Pc from local bucket\n auto thisBucketsMaxPcLocal = mxx::local_reduce(equalRange.first, equalRange.second, TpleReduce());\n\n \/\/For now, mark global minimum as local\n auto thisBucketsMaxPcGlobal = thisBucketsMaxPcLocal;\n auto thisBucketsMinPcGlobal = thisBucketsMinPcLocal;\n\n \/\/Treat first, last buckets as special cases\n if(equalRange.first == begin)\n {\n \/\/Use value from previous rank\n thisBucketsMinPcGlobal = comm.rank() == 0 ? thisBucketsMinPcLocal : TpleReduce2Layers() (prevMinPc, thisBucketsMinPcLocal);\n }\n\n if(equalRange.second == end)\n {\n \/\/Use value from next rank\n thisBucketsMaxPcGlobal = comm.rank() == comm.size() - 1 ? thisBucketsMaxPcLocal : TpleReduce2Layers() (nextMaxPc, thisBucketsMaxPcLocal);\n\n }\n\n \/\/If min Pc < max Pc for this bucket, update Pn or else mark them as stable\n if(TpleComp()(thisBucketsMinPcGlobal, thisBucketsMaxPcGlobal))\n std::for_each(equalRange.first, equalRange.second, [&](T &e){\n std::get(e) = std::get(thisBucketsMinPcGlobal);\n });\n else\n std::for_each(equalRange.first, equalRange.second, [&](T &e){\n std::get(e) = MAX2;\n });\n\n \/\/Advance the loop pointer\n it = equalRange.second;\n }\n }\n\n \/**\n * @brief update the Pc layer by choosing min Pn\n * @param[in] begin To iterate over the vector of tuples, marks the range of active tuples \n * @param[in] end end iterator\n * @return bool value, true if the algorithm is converged\n *\/\n template \n bool updatePc(Iterator begin, Iterator end)\n {\n \/\/converged yet\n uint8_t converged = 1; \/\/ 1 means true, we will update it below\n\n \/\/Sort by Pc, Pn\n mxx::sort(begin, end, TpleComp2Layers(), comm); \n\n \/\/Resolve last bucket's boundary split\n \n \/\/First, find the element with max Pc and min Pn locally \n \/\/Or in other words, get the min Pn of the last bucket\n auto minPnOfLastBucket = mxx::local_reduce(begin, end, TpleReduce2Layers());\n\n \/\/Result of exscan, again look for max Pc and min Pn on previous ranks\n auto prevMinPn = mxx::exscan(minPnOfLastBucket, TpleReduce2Layers(), comm); \n\n \/\/Now we can update the Pc layer of all the buckets locally\n for(auto it = begin; it != end;)\n {\n \/\/Range of tuples with the same Pc\n auto equalRange = conn::utils::findRange(it, end, *it, TpleComp());\n\n \/\/Range would include atleast 1 element\n assert(std::distance(equalRange.first, equalRange.second) >= 1);\n\n\n \/\/Minimum Pn from local bucket\n auto thisBucketsMinPnLocal = mxx::local_reduce(equalRange.first, equalRange.second, TpleReduce());\n\n \/\/For now, mark global minimum as local\n auto thisBucketsMinPnGlobal = thisBucketsMinPnLocal;\n\n \/\/Treat first, last buckets as special cases\n if(equalRange.first == begin)\n {\n \/\/Use value from previous rank\n thisBucketsMinPnGlobal = comm.rank() == 0 ? thisBucketsMinPnLocal : TpleReduce2Layers() (prevMinPn, thisBucketsMinPnLocal);\n }\n\n \/\/If min Pn < MAX2 for this bucket, update the Pc to new value or else mark the partition as stable\n if(std::get(thisBucketsMinPnGlobal) < MAX2) {\n converged = 0;\n std::for_each(equalRange.first, equalRange.second, [&](T &e){\n std::get(e) = std::get(thisBucketsMinPnGlobal);\n });\n }\n else\n std::for_each(equalRange.first, equalRange.second, [&](T &e){\n std::get(e) = MAX;\n });\n\n \/\/Advance the loop pointer\n it = equalRange.second;\n }\n\n \/\/Know convergence of all the ranks\n uint8_t allConverged;\n mxx::allreduce(&converged, 1, &allConverged, mxx::min(), comm);\n\n return (allConverged == 1 ? true : false);\n }\n\n template \n Iterator partitionStableTuples(Iterator begin, Iterator end)\n {\n return std::partition(begin, end, [&](const T &e){\n return std::get(e) == MAX;\n });\n }\n };\n\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/ vim : set fileencoding=utf-8 expandtab noai ts=4 sw=4 :\n\/\/\/ @addtogroup ahbmem\n\/\/\/ @{\n\/\/\/ @file ahbmem.cpp\n\/\/\/\n\/\/\/ @date 2010-2014\n\/\/\/ @copyright All rights reserved.\n\/\/\/ Any reproduction, use, distribution or disclosure of this\n\/\/\/ program, without the express, prior written consent of the\n\/\/\/ authors is strictly prohibited.\n\/\/\/ @author Rolf Meyer\n\/\/\/\n\/\/\/ Provide a test bench memory class with AHB slave interface. DMI and\n\/\/\/ streaming width fields are ignored. Delays are not modeled. Address checking\n\/\/\/ is performed in that way, that transactions are only executed if the slave\n\/\/\/ select condition defined in grlib user manual holds. Transactions generating\n\/\/\/ a correct slave select but exceeding the memory region due to their length\n\/\/\/ are reported as warning and executed anyhow.\n\n#include \n\n#include \"models\/ahbmem\/ahbmem.h\"\n#include \"common\/report.h\"\n#include \"common\/verbose.h\"\n\n\/\/\/ Constructor\nAHBMem::AHBMem(const sc_core::sc_module_name nm, \/\/ Module name\n uint16_t haddr, \/\/ AMBA AHB address (12 bit)\n uint16_t hmask, \/\/ AMBA AHB address mask (12 bit)\n amba::amba_layer_ids ambaLayer, \/\/ abstraction layer\n uint32_t hindex,\n bool cacheable,\n uint32_t wait_states,\n bool pow_mon) :\n AHBSlave<>(nm,\n hindex,\n 0x01, \/\/ Gaisler\n 0x00E, \/\/ AHB Mem,\n 0,\n 0,\n ambaLayer,\n BAR(AHBDevice::AHBMEM, hmask, cacheable, 0, haddr)),\n BaseMemory(BaseMemory::ARRAY, get_size()),\n ahbBaseAddress(static_cast((hmask) & haddr) << 20),\n ahbSize(~(static_cast(hmask) << 20) + 1),\n g_conf(\"conf\"),\n g_haddr(\"haddr\", haddr, g_conf),\n g_hmask(\"hmask\", hmask, g_conf),\n g_hindex(\"hindex\", hindex, g_conf),\n g_cacheable(\"cacheable\", cacheable, g_conf),\n g_wait_states(\"wait_states\", wait_states, g_conf),\n g_pow_mon(\"pow_mon\", pow_mon, g_conf),\n sta_power_norm(\"power.ahbmem.sta_power_norm\", 1269.53125, true), \/\/ Normalized static power input\n int_power_norm(\"power.ahbmem.int_power_norm\", 1.61011e-12, true), \/\/ Normalized internal power input\n dyn_read_energy_norm(\"power.ahbmem.dyn_read_energy_norm\", 7.57408e-13, true), \/\/ Normalized read energy input\n dyn_write_energy_norm(\"power.ahbmem.dyn_write_energy_norm\", 7.57408e-13, true), \/\/ Normalized write energy iput\n power(\"power\"),\n sta_power(\"sta_power\", 0.0, power), \/\/ Static power output\n int_power(\"int_power\", 0.0, power), \/\/ Internal power of module (dyn. switching independent)\n swi_power(\"swi_power\", 0.0, power), \/\/ Switching power of modules\n power_frame_starting_time(\"power_frame_starting_time\", SC_ZERO_TIME, power),\n dyn_read_energy(\"dyn_read_energy\", 0.0, power), \/\/ Energy per read access\n dyn_write_energy(\"dyn_write_energy\", 0.0, power), \/\/ Energy per write access\n dyn_reads(\"dyn_reads\", 0ull, power), \/\/ Read access counter for power computation\n dyn_writes(\"dyn_writes\", 0ull, power) { \/\/ Write access counter for power computation\n \/\/ haddr and hmask must be 12 bit\n assert(!((g_haddr | g_hmask) >> 12));\n\n \/\/ Register power callback functions\n if (g_pow_mon) {\n GC_REGISTER_TYPED_PARAM_CALLBACK(&sta_power, gs::cnf::pre_read, AHBMem, sta_power_cb);\n GC_REGISTER_TYPED_PARAM_CALLBACK(&int_power, gs::cnf::pre_read, AHBMem, int_power_cb);\n GC_REGISTER_TYPED_PARAM_CALLBACK(&swi_power, gs::cnf::pre_read, AHBMem, swi_power_cb);\n }\n\n \/\/ Display AHB slave information\n srInfo(\"\/configuration\/ahbmem\/ahbslave\")\n (\"addr\", (uint64_t)get_base_addr())\n (\"size\", (uint64_t)get_size())\n (\"AHB Slave Configuration\");\n\n srInfo(\"\/configuration\/ahbmem\/generics\")\n (\"haddr\", g_haddr)\n (\"hmask\", g_hmask)\n (\"hindex\", g_hindex)\n (\"cacheable\", g_cacheable)\n (\"wait_states\", g_wait_states)\n (\"Create AHB simulation memory\");\n}\n\n\/\/\/ Destructor\nAHBMem::~AHBMem() {\n \/\/ Delete memory contents\n GC_UNREGISTER_CALLBACKS();\n}\n\nvoid AHBMem::init_generics() {\n \/\/ set name, type, default, range, hint and description for gs_configs\n g_hindex.add_properties()\n (\"name\", \"Bus Index\")\n (\"range\", \"0..15\")\n (\"Slave index at the AHB bus\");\n\n g_haddr.add_properties()\n (\"name\", \"AHB Address\")\n (\"range\", \"0..0xFFF\")\n (\"The 12bit MSB address at the AHB bus\");\n\n g_hmask.add_properties()\n (\"name\", \"AHB Mask\")\n (\"range\", \"0..0xFFF\")\n (\"The 12bit AHB address mask\");\n\n g_cacheable.add_properties()\n (\"name\", \"Memory Cachability\")\n (\"If true the AHB Bus will set the cachability flag for all transactions from the memory\");\n\n g_wait_states.add_properties()\n (\"name\", \"Wait States\")\n (\"Number of wait states for each transaction\");\n\n g_pow_mon.add_properties()\n (\"name\", \"Power Monitoring\")\n (\"If true enable power monitoring\");\n}\n\nvoid AHBMem::dorst() {\n erase(0, get_size()-1);\n}\n\n\/\/\/ Encapsulated functionality\nuint32_t AHBMem::exec_func(\n tlm::tlm_generic_payload &trans, \/\/ NOLINT(runtime\/references)\n sc_core::sc_time &delay, \/\/ NOLINT(runtime\/references)\n bool debug) {\n uint32_t words_transferred;\n\n \/\/ Is the address for me\n if (!((g_haddr ^ (trans.get_address() >> 20)) & g_hmask)) {\n \/\/ Warn if access exceeds slave memory region\n if ((trans.get_address() + trans.get_data_length()) >\n\n (ahbBaseAddress + ahbSize)) {\n srWarn(name())\n (\"Transaction exceeds slave memory region\");\n }\n\n if (trans.is_write()) {\n \/\/ write simulation memory\n write_block(trans.get_address(), trans.get_data_ptr(), trans.get_data_length());\n\n \/\/ Base delay is one clock cycle per word\n words_transferred = (trans.get_data_length() < 4) ? 1 : (trans.get_data_length() >> 2);\n\n if (g_pow_mon) {\n dyn_writes += words_transferred;\n }\n\n \/\/ Total delay is base delay + wait states\n delay += clock_cycle * (words_transferred + g_wait_states);\n trans.set_response_status(tlm::TLM_OK_RESPONSE);\n } else {\n \/\/ read simulation memory\n read_block(trans.get_address(), trans.get_data_ptr(), trans.get_data_length());\n\n \/\/ Base delay is one clock cycle per word\n words_transferred = (trans.get_data_length() < 4) ? 1 : (trans.get_data_length() >> 2);\n\n if (g_pow_mon) {\n dyn_reads += words_transferred;\n }\n\n \/\/ Total delay is base delay + wait states\n delay += clock_cycle * (words_transferred + g_wait_states);\n trans.set_response_status(tlm::TLM_OK_RESPONSE);\n\n \/\/ set cacheability\n if (g_cacheable) {\n ahb.validate_extension(trans);\n }\n }\n\n srDebug(name())\n (\"delay\", delay)\n (\"Delay increment!\");\n } else {\n \/\/ address not valid\n srError(name())\n (\"taddress\", (uint64_t)trans.get_address())\n (\"taddr\", (uint64_t)trans.get_address() >> 20)\n (\"haddr\", g_haddr)\n (\"hmask\", g_hmask)\n (\"Address not within permissable slave memory space\");\n trans.set_response_status(tlm::TLM_ADDRESS_ERROR_RESPONSE);\n }\n\n return trans.get_data_length();\n}\n\n\/\/ Returns clock cycle time for e.g. use in AHBSlave parent\nsc_core::sc_time AHBMem::get_clock() {\n return clock_cycle;\n}\n\nvoid AHBMem::writeByteDBG(const uint32_t address, const uint8_t byte) {\n write_dbg(address, byte);\n}\n\n\/\/ Automatically called at the beginning of the simulation\nvoid AHBMem::start_of_simulation() {\n \/\/ Initialize power model\n if (g_pow_mon) {\n power_model();\n }\n}\n\n\/\/ Calculate power\/energy values from normalized input data\nvoid AHBMem::power_model() {\n \/\/ Static power calculation (pW)\n sta_power = sta_power_norm * (get_size() << 3);\n\n \/\/ Cell internal power (uW)\n int_power = int_power_norm * (get_size() << 3) * 1 \/ (clock_cycle.to_seconds());\n\n \/\/ Energy per read access (uJ)\n dyn_read_energy = dyn_read_energy_norm * 32 * (get_size() << 3);\n\n \/\/ Energy per write access (uJ)\n dyn_write_energy = dyn_write_energy_norm * 32 * (get_size() << 3);\n}\n\n\/\/ Static power callback\ngs::cnf::callback_return_type AHBMem::sta_power_cb(\n gs::gs_param_base &changed_param, \/\/ NOLINT(runtime\/references)\n gs::cnf::callback_type reason) {\n \/\/ Nothing to do !!\n \/\/ Static power of AHBMem is constant !!\n return GC_RETURN_OK;\n}\n\n\/\/ Internal power callback\ngs::cnf::callback_return_type AHBMem::int_power_cb(\n gs::gs_param_base &changed_param, \/\/ NOLINT(runtime\/references)\n gs::cnf::callback_type reason) {\n \/\/ Nothing to do !!\n \/\/ AHBMem internal power is constant !!\n return GC_RETURN_OK;\n}\n\n\/\/ Switching power callback\ngs::cnf::callback_return_type AHBMem::swi_power_cb(\n gs::gs_param_base &changed_param, \/\/ NOLINT(runtime\/references)\n gs::cnf::callback_type reason) {\n swi_power =\n ((dyn_read_energy *\n dyn_reads) + (dyn_write_energy * dyn_writes)) \/ (sc_time_stamp() - power_frame_starting_time).to_seconds();\n return GC_RETURN_OK;\n}\n\n\/\/ Automatically called at the end of the simulation\nvoid AHBMem::end_of_simulation() {\n v::report << name() << \" **************************************************** \" << v::endl;\n v::report << name() << \" * AHBMem Statistics: \" << v::endl;\n v::report << name() << \" * ------------------ \" << v::endl;\n print_transport_statistics(name());\n v::report << name() << \" * ************************************************** \" << v::endl;\n}\n\/\/\/ @}\nAHBMem: Adding init_generics to the constructor\/\/ vim : set fileencoding=utf-8 expandtab noai ts=4 sw=4 :\n\/\/\/ @addtogroup ahbmem\n\/\/\/ @{\n\/\/\/ @file ahbmem.cpp\n\/\/\/\n\/\/\/ @date 2010-2014\n\/\/\/ @copyright All rights reserved.\n\/\/\/ Any reproduction, use, distribution or disclosure of this\n\/\/\/ program, without the express, prior written consent of the\n\/\/\/ authors is strictly prohibited.\n\/\/\/ @author Rolf Meyer\n\/\/\/\n\/\/\/ Provide a test bench memory class with AHB slave interface. DMI and\n\/\/\/ streaming width fields are ignored. Delays are not modeled. Address checking\n\/\/\/ is performed in that way, that transactions are only executed if the slave\n\/\/\/ select condition defined in grlib user manual holds. Transactions generating\n\/\/\/ a correct slave select but exceeding the memory region due to their length\n\/\/\/ are reported as warning and executed anyhow.\n\n#include \n\n#include \"models\/ahbmem\/ahbmem.h\"\n#include \"common\/report.h\"\n#include \"common\/verbose.h\"\n\n\/\/\/ Constructor\nAHBMem::AHBMem(const sc_core::sc_module_name nm, \/\/ Module name\n uint16_t haddr, \/\/ AMBA AHB address (12 bit)\n uint16_t hmask, \/\/ AMBA AHB address mask (12 bit)\n amba::amba_layer_ids ambaLayer, \/\/ abstraction layer\n uint32_t hindex,\n bool cacheable,\n uint32_t wait_states,\n bool pow_mon) :\n AHBSlave<>(nm,\n hindex,\n 0x01, \/\/ Gaisler\n 0x00E, \/\/ AHB Mem,\n 0,\n 0,\n ambaLayer,\n BAR(AHBDevice::AHBMEM, hmask, cacheable, 0, haddr)),\n BaseMemory(BaseMemory::ARRAY, get_size()),\n ahbBaseAddress(static_cast((hmask) & haddr) << 20),\n ahbSize(~(static_cast(hmask) << 20) + 1),\n g_conf(\"conf\"),\n g_haddr(\"haddr\", haddr, g_conf),\n g_hmask(\"hmask\", hmask, g_conf),\n g_hindex(\"hindex\", hindex, g_conf),\n g_cacheable(\"cacheable\", cacheable, g_conf),\n g_wait_states(\"wait_states\", wait_states, g_conf),\n g_pow_mon(\"pow_mon\", pow_mon, g_conf),\n sta_power_norm(\"power.ahbmem.sta_power_norm\", 1269.53125, true), \/\/ Normalized static power input\n int_power_norm(\"power.ahbmem.int_power_norm\", 1.61011e-12, true), \/\/ Normalized internal power input\n dyn_read_energy_norm(\"power.ahbmem.dyn_read_energy_norm\", 7.57408e-13, true), \/\/ Normalized read energy input\n dyn_write_energy_norm(\"power.ahbmem.dyn_write_energy_norm\", 7.57408e-13, true), \/\/ Normalized write energy iput\n power(\"power\"),\n sta_power(\"sta_power\", 0.0, power), \/\/ Static power output\n int_power(\"int_power\", 0.0, power), \/\/ Internal power of module (dyn. switching independent)\n swi_power(\"swi_power\", 0.0, power), \/\/ Switching power of modules\n power_frame_starting_time(\"power_frame_starting_time\", SC_ZERO_TIME, power),\n dyn_read_energy(\"dyn_read_energy\", 0.0, power), \/\/ Energy per read access\n dyn_write_energy(\"dyn_write_energy\", 0.0, power), \/\/ Energy per write access\n dyn_reads(\"dyn_reads\", 0ull, power), \/\/ Read access counter for power computation\n dyn_writes(\"dyn_writes\", 0ull, power) { \/\/ Write access counter for power computation\n init_generics();\n \/\/ haddr and hmask must be 12 bit\n assert(!((g_haddr | g_hmask) >> 12));\n\n \/\/ Register power callback functions\n if (g_pow_mon) {\n GC_REGISTER_TYPED_PARAM_CALLBACK(&sta_power, gs::cnf::pre_read, AHBMem, sta_power_cb);\n GC_REGISTER_TYPED_PARAM_CALLBACK(&int_power, gs::cnf::pre_read, AHBMem, int_power_cb);\n GC_REGISTER_TYPED_PARAM_CALLBACK(&swi_power, gs::cnf::pre_read, AHBMem, swi_power_cb);\n }\n\n \/\/ Display AHB slave information\n srInfo(\"\/configuration\/ahbmem\/ahbslave\")\n (\"addr\", (uint64_t)get_base_addr())\n (\"size\", (uint64_t)get_size())\n (\"AHB Slave Configuration\");\n\n srInfo(\"\/configuration\/ahbmem\/generics\")\n (\"haddr\", g_haddr)\n (\"hmask\", g_hmask)\n (\"hindex\", g_hindex)\n (\"cacheable\", g_cacheable)\n (\"wait_states\", g_wait_states)\n (\"Create AHB simulation memory\");\n}\n\n\/\/\/ Destructor\nAHBMem::~AHBMem() {\n \/\/ Delete memory contents\n GC_UNREGISTER_CALLBACKS();\n}\n\nvoid AHBMem::init_generics() {\n \/\/ set name, type, default, range, hint and description for gs_configs\n g_hindex.add_properties()\n (\"name\", \"Bus Index\")\n (\"range\", \"0..15\")\n (\"Slave index at the AHB bus\");\n\n g_haddr.add_properties()\n (\"name\", \"AHB Address\")\n (\"range\", \"0..0xFFF\")\n (\"The 12bit MSB address at the AHB bus\");\n\n g_hmask.add_properties()\n (\"name\", \"AHB Mask\")\n (\"range\", \"0..0xFFF\")\n (\"The 12bit AHB address mask\");\n\n g_cacheable.add_properties()\n (\"name\", \"Memory Cachability\")\n (\"If true the AHB Bus will set the cachability flag for all transactions from the memory\");\n\n g_wait_states.add_properties()\n (\"name\", \"Wait States\")\n (\"Number of wait states for each transaction\");\n\n g_pow_mon.add_properties()\n (\"name\", \"Power Monitoring\")\n (\"If true enable power monitoring\");\n}\n\nvoid AHBMem::dorst() {\n erase(0, get_size()-1);\n}\n\n\/\/\/ Encapsulated functionality\nuint32_t AHBMem::exec_func(\n tlm::tlm_generic_payload &trans, \/\/ NOLINT(runtime\/references)\n sc_core::sc_time &delay, \/\/ NOLINT(runtime\/references)\n bool debug) {\n uint32_t words_transferred;\n\n \/\/ Is the address for me\n if (!((g_haddr ^ (trans.get_address() >> 20)) & g_hmask)) {\n \/\/ Warn if access exceeds slave memory region\n if ((trans.get_address() + trans.get_data_length()) >\n\n (ahbBaseAddress + ahbSize)) {\n srWarn(name())\n (\"Transaction exceeds slave memory region\");\n }\n\n if (trans.is_write()) {\n \/\/ write simulation memory\n write_block(trans.get_address(), trans.get_data_ptr(), trans.get_data_length());\n\n \/\/ Base delay is one clock cycle per word\n words_transferred = (trans.get_data_length() < 4) ? 1 : (trans.get_data_length() >> 2);\n\n if (g_pow_mon) {\n dyn_writes += words_transferred;\n }\n\n \/\/ Total delay is base delay + wait states\n delay += clock_cycle * (words_transferred + g_wait_states);\n trans.set_response_status(tlm::TLM_OK_RESPONSE);\n } else {\n \/\/ read simulation memory\n read_block(trans.get_address(), trans.get_data_ptr(), trans.get_data_length());\n\n \/\/ Base delay is one clock cycle per word\n words_transferred = (trans.get_data_length() < 4) ? 1 : (trans.get_data_length() >> 2);\n\n if (g_pow_mon) {\n dyn_reads += words_transferred;\n }\n\n \/\/ Total delay is base delay + wait states\n delay += clock_cycle * (words_transferred + g_wait_states);\n trans.set_response_status(tlm::TLM_OK_RESPONSE);\n\n \/\/ set cacheability\n if (g_cacheable) {\n ahb.validate_extension(trans);\n }\n }\n\n srDebug(name())\n (\"delay\", delay)\n (\"Delay increment!\");\n } else {\n \/\/ address not valid\n srError(name())\n (\"taddress\", (uint64_t)trans.get_address())\n (\"taddr\", (uint64_t)trans.get_address() >> 20)\n (\"haddr\", g_haddr)\n (\"hmask\", g_hmask)\n (\"Address not within permissable slave memory space\");\n trans.set_response_status(tlm::TLM_ADDRESS_ERROR_RESPONSE);\n }\n\n return trans.get_data_length();\n}\n\n\/\/ Returns clock cycle time for e.g. use in AHBSlave parent\nsc_core::sc_time AHBMem::get_clock() {\n return clock_cycle;\n}\n\nvoid AHBMem::writeByteDBG(const uint32_t address, const uint8_t byte) {\n write_dbg(address, byte);\n}\n\n\/\/ Automatically called at the beginning of the simulation\nvoid AHBMem::start_of_simulation() {\n \/\/ Initialize power model\n if (g_pow_mon) {\n power_model();\n }\n}\n\n\/\/ Calculate power\/energy values from normalized input data\nvoid AHBMem::power_model() {\n \/\/ Static power calculation (pW)\n sta_power = sta_power_norm * (get_size() << 3);\n\n \/\/ Cell internal power (uW)\n int_power = int_power_norm * (get_size() << 3) * 1 \/ (clock_cycle.to_seconds());\n\n \/\/ Energy per read access (uJ)\n dyn_read_energy = dyn_read_energy_norm * 32 * (get_size() << 3);\n\n \/\/ Energy per write access (uJ)\n dyn_write_energy = dyn_write_energy_norm * 32 * (get_size() << 3);\n}\n\n\/\/ Static power callback\ngs::cnf::callback_return_type AHBMem::sta_power_cb(\n gs::gs_param_base &changed_param, \/\/ NOLINT(runtime\/references)\n gs::cnf::callback_type reason) {\n \/\/ Nothing to do !!\n \/\/ Static power of AHBMem is constant !!\n return GC_RETURN_OK;\n}\n\n\/\/ Internal power callback\ngs::cnf::callback_return_type AHBMem::int_power_cb(\n gs::gs_param_base &changed_param, \/\/ NOLINT(runtime\/references)\n gs::cnf::callback_type reason) {\n \/\/ Nothing to do !!\n \/\/ AHBMem internal power is constant !!\n return GC_RETURN_OK;\n}\n\n\/\/ Switching power callback\ngs::cnf::callback_return_type AHBMem::swi_power_cb(\n gs::gs_param_base &changed_param, \/\/ NOLINT(runtime\/references)\n gs::cnf::callback_type reason) {\n swi_power =\n ((dyn_read_energy *\n dyn_reads) + (dyn_write_energy * dyn_writes)) \/ (sc_time_stamp() - power_frame_starting_time).to_seconds();\n return GC_RETURN_OK;\n}\n\n\/\/ Automatically called at the end of the simulation\nvoid AHBMem::end_of_simulation() {\n v::report << name() << \" **************************************************** \" << v::endl;\n v::report << name() << \" * AHBMem Statistics: \" << v::endl;\n v::report << name() << \" * ------------------ \" << v::endl;\n print_transport_statistics(name());\n v::report << name() << \" * ************************************************** \" << v::endl;\n}\n\/\/\/ @}\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2016 The Qt Company Ltd.\n** Contact: https:\/\/www.qt.io\/licensing\/\n**\n** This file is part of Qbs.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms\n** and conditions see https:\/\/www.qt.io\/terms-conditions. For further\n** information use the contact form at https:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 3 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL3 included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 3 requirements\n** will be met: https:\/\/www.gnu.org\/licenses\/lgpl-3.0.html.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 2.0 or (at your option) the GNU General\n** Public license version 3 or any later version approved by the KDE Free\n** Qt Foundation. The licenses are as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3\n** included in the packaging of this file. Please review the following\n** information to ensure the GNU General Public License requirements will\n** be met: https:\/\/www.gnu.org\/licenses\/gpl-2.0.html and\n** https:\/\/www.gnu.org\/licenses\/gpl-3.0.html.\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"android-setup.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace qbs;\nusing qbs::Internal::Tr;\n\nstatic QString qls(const char *s) { return QLatin1String(s); }\n\nstatic QStringList expectedArchs()\n{\n return QStringList()\n << QStringLiteral(\"arm64\")\n << QStringLiteral(\"armv5te\")\n << QStringLiteral(\"armv7a\")\n << QStringLiteral(\"mips\")\n << QStringLiteral(\"mips64\")\n << QStringLiteral(\"x86\")\n << QStringLiteral(\"x86_64\");\n}\n\n\nstatic QString subProfileName(const QString &mainProfileName, const QString &arch)\n{\n return mainProfileName + QLatin1Char('-') + arch;\n}\n\nvoid setupSdk(qbs::Settings *settings, const QString &profileName, const QString &sdkDirPath)\n{\n if (!QDir(sdkDirPath).exists()) {\n throw ErrorInfo(Tr::tr(\"SDK directory '%1' does not exist.\")\n .arg(QDir::toNativeSeparators(sdkDirPath)));\n }\n\n Profile profile(profileName, settings);\n profile.removeProfile();\n if (!sdkDirPath.isEmpty())\n profile.setValue(qls(\"Android.sdk.sdkDir\"), QDir::cleanPath(sdkDirPath));\n profile.setValue(qls(\"qbs.targetPlatform\"), qls(\"android\"));\n}\n\nstatic QString mapArch(const QString &androidName)\n{\n if (androidName == qls(\"arm64-v8a\"))\n return qls(\"arm64\");\n if (androidName == qls(\"armeabi\"))\n return qls(\"armv5te\");\n if (androidName == qls(\"armeabi-v7a\"))\n return qls(\"armv7a\");\n return androidName;\n}\n\nstruct QtAndroidInfo {\n bool isValid() const { return !arch.isEmpty(); }\n\n QString qmakePath;\n QString arch;\n QString platform;\n};\n\nstatic QtAndroidInfo getInfoForQtDir(const QString &qtDir)\n{\n QtAndroidInfo info;\n info.qmakePath = qbs::Internal::HostOsInfo::appendExecutableSuffix(qtDir + qls(\"\/bin\/qmake\"));\n if (!QFile::exists(info.qmakePath))\n return info;\n QFile qdevicepri(qtDir + qls(\"\/mkspecs\/qdevice.pri\"));\n if (!qdevicepri.open(QIODevice::ReadOnly))\n return info;\n while (!qdevicepri.atEnd()) {\n const QByteArray line = qdevicepri.readLine().simplified();\n const bool isArchLine = line.startsWith(\"DEFAULT_ANDROID_TARGET_ARCH\");\n const bool isPlatformLine = line.startsWith(\"DEFAULT_ANDROID_PLATFORM\");\n if (!isArchLine && !isPlatformLine)\n continue;\n const QList elems = line.split('=');\n if (elems.size() != 2)\n continue;\n const QString rhs = QString::fromLatin1(elems.at(1).trimmed());\n if (isArchLine)\n info.arch = mapArch(rhs);\n else\n info.platform = rhs;\n }\n return info;\n}\n\nusing QtInfoPerArch = QHash;\nstatic QtInfoPerArch getQtAndroidInfo(const QString &qtSdkDir)\n{\n QtInfoPerArch archs;\n if (qtSdkDir.isEmpty())\n return archs;\n\n QStringList qtDirs(qtSdkDir);\n QDirIterator dit(qtSdkDir, QStringList() << QLatin1String(\"android_*\"), QDir::Dirs);\n while (dit.hasNext())\n qtDirs << dit.next();\n for (auto it = qtDirs.cbegin(); it != qtDirs.cend(); ++it) {\n const QtAndroidInfo info = getInfoForQtDir(*it);\n if (info.isValid())\n archs.insert(info.arch, info);\n }\n return archs;\n}\n\nstatic QString maximumPlatform(const QString &platform1, const QString &platform2)\n{\n if (platform1.isEmpty())\n return platform2;\n if (platform2.isEmpty())\n return platform1;\n static const QString prefix = qls(\"android-\");\n const QString numberString1 = platform1.mid(prefix.size());\n const QString numberString2 = platform2.mid(prefix.size());\n bool ok;\n const int value1 = numberString1.toInt(&ok);\n if (!ok) {\n qWarning(\"Ignoring malformed Android platform string '%s'.\", qPrintable(platform1));\n return platform2;\n }\n const int value2 = numberString2.toInt(&ok);\n if (!ok) {\n qWarning(\"Ignoring malformed Android platform string '%s'.\", qPrintable(platform2));\n return platform1;\n }\n return prefix + QString::number(std::max(value1, value2));\n}\n\nstatic void setupNdk(qbs::Settings *settings, const QString &profileName, const QString &ndkDirPath,\n const QString &qtSdkDirPath)\n{\n if (!QDir(ndkDirPath).exists()) {\n throw ErrorInfo(Tr::tr(\"NDK directory '%1' does not exist.\")\n .arg(QDir::toNativeSeparators(ndkDirPath)));\n }\n\n Profile mainProfile(profileName, settings);\n if (!ndkDirPath.isEmpty()) {\n mainProfile.setValue(qls(\"Android.ndk.ndkDir\"), QDir::cleanPath(ndkDirPath));\n mainProfile.setValue(qls(\"Android.sdk.ndkDir\"), QDir::cleanPath(ndkDirPath));\n }\n mainProfile.setValue(qls(\"qbs.toolchain\"), QStringList() << qls(\"gcc\"));\n const QStringList archs = expectedArchs();\n const QtInfoPerArch infoPerArch = getQtAndroidInfo(qtSdkDirPath);\n mainProfile.setValue(qls(\"qbs.architectures\"), infoPerArch.empty()\n ? archs : QStringList(infoPerArch.keys()));\n QStringList searchPaths;\n QString platform;\n for (const QString &arch : archs) {\n const QtAndroidInfo qtAndroidInfo = infoPerArch.value(arch);\n if (!qtAndroidInfo.isValid())\n continue;\n const QString subProName = subProfileName(profileName, arch);\n const QString setupQtPath = qApp->applicationDirPath() + qls(\"\/qbs-setup-qt\");\n QProcess setupQt;\n setupQt.start(setupQtPath, QStringList({ qtAndroidInfo.qmakePath, subProName }));\n if (!setupQt.waitForStarted()) {\n throw ErrorInfo(Tr::tr(\"Setting up Qt profile failed: '%1' \"\n \"could not be started.\").arg(setupQtPath));\n }\n if (!setupQt.waitForFinished()) {\n throw ErrorInfo(Tr::tr(\"Setting up Qt profile failed: Error running '%1' (%2)\")\n .arg(setupQtPath, setupQt.errorString()));\n }\n if (setupQt.exitCode() != 0) {\n throw ErrorInfo(Tr::tr(\"Setting up Qt profile failed: '%1' returned with \"\n \"exit code %2.\").arg(setupQtPath).arg(setupQt.exitCode()));\n }\n settings->sync();\n qbs::Internal::TemporaryProfile p(subProName, settings);\n searchPaths << p.p.value(qls(\"preferences.qbsSearchPaths\")).toStringList();\n platform = maximumPlatform(platform, qtAndroidInfo.platform);\n }\n if (!searchPaths.empty())\n mainProfile.setValue(qls(\"preferences.qbsSearchPaths\"), searchPaths);\n if (!platform.isEmpty())\n mainProfile.setValue(qls(\"Android.ndk.platform\"), platform);\n}\n\nvoid setupAndroid(Settings *settings, const QString &profileName, const QString &sdkDirPath,\n const QString &ndkDirPath, const QString &qtSdkDirPath)\n{\n setupSdk(settings, profileName, sdkDirPath);\n setupNdk(settings, profileName, ndkDirPath, qtSdkDirPath);\n}\nsetup-android: Fix case where there is only one architecture\/****************************************************************************\n**\n** Copyright (C) 2016 The Qt Company Ltd.\n** Contact: https:\/\/www.qt.io\/licensing\/\n**\n** This file is part of Qbs.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms\n** and conditions see https:\/\/www.qt.io\/terms-conditions. For further\n** information use the contact form at https:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 3 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL3 included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 3 requirements\n** will be met: https:\/\/www.gnu.org\/licenses\/lgpl-3.0.html.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 2.0 or (at your option) the GNU General\n** Public license version 3 or any later version approved by the KDE Free\n** Qt Foundation. The licenses are as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3\n** included in the packaging of this file. Please review the following\n** information to ensure the GNU General Public License requirements will\n** be met: https:\/\/www.gnu.org\/licenses\/gpl-2.0.html and\n** https:\/\/www.gnu.org\/licenses\/gpl-3.0.html.\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"android-setup.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace qbs;\nusing qbs::Internal::Tr;\n\nstatic QString qls(const char *s) { return QLatin1String(s); }\n\nstatic QStringList expectedArchs()\n{\n return QStringList()\n << QStringLiteral(\"arm64\")\n << QStringLiteral(\"armv5te\")\n << QStringLiteral(\"armv7a\")\n << QStringLiteral(\"mips\")\n << QStringLiteral(\"mips64\")\n << QStringLiteral(\"x86\")\n << QStringLiteral(\"x86_64\");\n}\n\n\nstatic QString subProfileName(const QString &mainProfileName, const QString &arch)\n{\n return mainProfileName + QLatin1Char('-') + arch;\n}\n\nvoid setupSdk(qbs::Settings *settings, const QString &profileName, const QString &sdkDirPath)\n{\n if (!QDir(sdkDirPath).exists()) {\n throw ErrorInfo(Tr::tr(\"SDK directory '%1' does not exist.\")\n .arg(QDir::toNativeSeparators(sdkDirPath)));\n }\n\n Profile profile(profileName, settings);\n profile.removeProfile();\n if (!sdkDirPath.isEmpty())\n profile.setValue(qls(\"Android.sdk.sdkDir\"), QDir::cleanPath(sdkDirPath));\n profile.setValue(qls(\"qbs.targetPlatform\"), qls(\"android\"));\n}\n\nstatic QString mapArch(const QString &androidName)\n{\n if (androidName == qls(\"arm64-v8a\"))\n return qls(\"arm64\");\n if (androidName == qls(\"armeabi\"))\n return qls(\"armv5te\");\n if (androidName == qls(\"armeabi-v7a\"))\n return qls(\"armv7a\");\n return androidName;\n}\n\nstruct QtAndroidInfo {\n bool isValid() const { return !arch.isEmpty(); }\n\n QString qmakePath;\n QString arch;\n QString platform;\n};\n\nstatic QtAndroidInfo getInfoForQtDir(const QString &qtDir)\n{\n QtAndroidInfo info;\n info.qmakePath = qbs::Internal::HostOsInfo::appendExecutableSuffix(qtDir + qls(\"\/bin\/qmake\"));\n if (!QFile::exists(info.qmakePath))\n return info;\n QFile qdevicepri(qtDir + qls(\"\/mkspecs\/qdevice.pri\"));\n if (!qdevicepri.open(QIODevice::ReadOnly))\n return info;\n while (!qdevicepri.atEnd()) {\n const QByteArray line = qdevicepri.readLine().simplified();\n const bool isArchLine = line.startsWith(\"DEFAULT_ANDROID_TARGET_ARCH\");\n const bool isPlatformLine = line.startsWith(\"DEFAULT_ANDROID_PLATFORM\");\n if (!isArchLine && !isPlatformLine)\n continue;\n const QList elems = line.split('=');\n if (elems.size() != 2)\n continue;\n const QString rhs = QString::fromLatin1(elems.at(1).trimmed());\n if (isArchLine)\n info.arch = mapArch(rhs);\n else\n info.platform = rhs;\n }\n return info;\n}\n\nusing QtInfoPerArch = QHash;\nstatic QtInfoPerArch getQtAndroidInfo(const QString &qtSdkDir)\n{\n QtInfoPerArch archs;\n if (qtSdkDir.isEmpty())\n return archs;\n\n QStringList qtDirs(qtSdkDir);\n QDirIterator dit(qtSdkDir, QStringList() << QLatin1String(\"android_*\"), QDir::Dirs);\n while (dit.hasNext())\n qtDirs << dit.next();\n for (auto it = qtDirs.cbegin(); it != qtDirs.cend(); ++it) {\n const QtAndroidInfo info = getInfoForQtDir(*it);\n if (info.isValid())\n archs.insert(info.arch, info);\n }\n return archs;\n}\n\nstatic QString maximumPlatform(const QString &platform1, const QString &platform2)\n{\n if (platform1.isEmpty())\n return platform2;\n if (platform2.isEmpty())\n return platform1;\n static const QString prefix = qls(\"android-\");\n const QString numberString1 = platform1.mid(prefix.size());\n const QString numberString2 = platform2.mid(prefix.size());\n bool ok;\n const int value1 = numberString1.toInt(&ok);\n if (!ok) {\n qWarning(\"Ignoring malformed Android platform string '%s'.\", qPrintable(platform1));\n return platform2;\n }\n const int value2 = numberString2.toInt(&ok);\n if (!ok) {\n qWarning(\"Ignoring malformed Android platform string '%s'.\", qPrintable(platform2));\n return platform1;\n }\n return prefix + QString::number(std::max(value1, value2));\n}\n\nstatic void setupNdk(qbs::Settings *settings, const QString &profileName, const QString &ndkDirPath,\n const QString &qtSdkDirPath)\n{\n if (!QDir(ndkDirPath).exists()) {\n throw ErrorInfo(Tr::tr(\"NDK directory '%1' does not exist.\")\n .arg(QDir::toNativeSeparators(ndkDirPath)));\n }\n\n Profile mainProfile(profileName, settings);\n if (!ndkDirPath.isEmpty()) {\n mainProfile.setValue(qls(\"Android.ndk.ndkDir\"), QDir::cleanPath(ndkDirPath));\n mainProfile.setValue(qls(\"Android.sdk.ndkDir\"), QDir::cleanPath(ndkDirPath));\n }\n mainProfile.setValue(qls(\"qbs.toolchain\"), QStringList() << qls(\"gcc\"));\n const QStringList archs = expectedArchs();\n const QtInfoPerArch infoPerArch = getQtAndroidInfo(qtSdkDirPath);\n const QStringList archsForProfile = infoPerArch.empty()\n ? archs : QStringList(infoPerArch.keys());\n if (archsForProfile.size() == 1)\n mainProfile.setValue(qls(\"qbs.architecture\"), archsForProfile.front());\n else\n mainProfile.setValue(qls(\"qbs.architectures\"), archsForProfile);\n QStringList searchPaths;\n QString platform;\n for (const QString &arch : archs) {\n const QtAndroidInfo qtAndroidInfo = infoPerArch.value(arch);\n if (!qtAndroidInfo.isValid())\n continue;\n const QString subProName = subProfileName(profileName, arch);\n const QString setupQtPath = qApp->applicationDirPath() + qls(\"\/qbs-setup-qt\");\n QProcess setupQt;\n setupQt.start(setupQtPath, QStringList({ qtAndroidInfo.qmakePath, subProName }));\n if (!setupQt.waitForStarted()) {\n throw ErrorInfo(Tr::tr(\"Setting up Qt profile failed: '%1' \"\n \"could not be started.\").arg(setupQtPath));\n }\n if (!setupQt.waitForFinished()) {\n throw ErrorInfo(Tr::tr(\"Setting up Qt profile failed: Error running '%1' (%2)\")\n .arg(setupQtPath, setupQt.errorString()));\n }\n if (setupQt.exitCode() != 0) {\n throw ErrorInfo(Tr::tr(\"Setting up Qt profile failed: '%1' returned with \"\n \"exit code %2.\").arg(setupQtPath).arg(setupQt.exitCode()));\n }\n settings->sync();\n qbs::Internal::TemporaryProfile p(subProName, settings);\n searchPaths << p.p.value(qls(\"preferences.qbsSearchPaths\")).toStringList();\n platform = maximumPlatform(platform, qtAndroidInfo.platform);\n }\n if (!searchPaths.empty())\n mainProfile.setValue(qls(\"preferences.qbsSearchPaths\"), searchPaths);\n if (!platform.isEmpty())\n mainProfile.setValue(qls(\"Android.ndk.platform\"), platform);\n}\n\nvoid setupAndroid(Settings *settings, const QString &profileName, const QString &sdkDirPath,\n const QString &ndkDirPath, const QString &qtSdkDirPath)\n{\n setupSdk(settings, profileName, sdkDirPath);\n setupNdk(settings, profileName, ndkDirPath, qtSdkDirPath);\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qremoteservicecontrol_p.h\"\n#include \"qremoteservicecontrol_ls_p.h\"\n#include \"ipcendpoint_p.h\"\n#include \"objectendpoint_p.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \/* See NOTES *\/\n#include \n\n#ifndef Q_OS_WIN\n#include \n#endif\n\n#ifdef LOCAL_PEERCRED \/* from sys\/un.h *\/\n#include \n#endif\n\n\n\/\/ Needed for ::Sleep, while we wait for a better solution\n#ifdef Q_OS_WIN\n#include \n#include \n#endif\n\nQTM_BEGIN_NAMESPACE\n\n\/\/IPC based on QLocalSocket\n\nclass LocalSocketEndPoint : public QServiceIpcEndPoint\n{\n Q_OBJECT\npublic:\n LocalSocketEndPoint(QLocalSocket* s, QObject* parent = 0)\n : QServiceIpcEndPoint(parent), socket(s)\n {\n Q_ASSERT(socket);\n socket->setParent(this);\n connect(s, SIGNAL(readyRead()), this, SLOT(readIncoming()));\n connect(s, SIGNAL(disconnected()), this, SIGNAL(disconnected()));\n\n if (socket->bytesAvailable())\n QTimer::singleShot(0, this, SLOT(readIncoming()));\n }\n\n ~LocalSocketEndPoint() \n {\n }\n\n\nprotected:\n void flushPackage(const QServicePackage& package)\n {\n QByteArray block;\n QDataStream out(&block, QIODevice::WriteOnly);\n out.setVersion(QDataStream::Qt_4_6);\n out << package;\n socket->write(block);\n }\n\nprotected slots:\n void readIncoming()\n {\n QDataStream in(socket);\n in.setVersion(QDataStream::Qt_4_6);\n\n while(socket->bytesAvailable()) {\n QServicePackage package;\n in >> package;\n incoming.enqueue(package);\n }\n\n emit readyRead();\n }\n\nprivate:\n QLocalSocket* socket;\n};\n\nQRemoteServiceControlLocalSocketPrivate::QRemoteServiceControlLocalSocketPrivate(QObject* parent)\n : QRemoteServiceControlPrivate(parent)\n{\n}\n\nvoid QRemoteServiceControlLocalSocketPrivate::publishServices( const QString& ident)\n{\n createServiceEndPoint(ident) ;\n}\n\nvoid QRemoteServiceControlLocalSocketPrivate::processIncoming()\n{\n qDebug() << \"Processing incoming connect\";\n if (localServer->hasPendingConnections()) {\n QLocalSocket* s = localServer->nextPendingConnection();\n \/\/LocalSocketEndPoint owns socket \n int fd = s->socketDescriptor();\n if(getSecurityFilter()){\n QRemoteServiceControlLocalSocketCred qcred;\n memset(&qcred, 0, sizeof(QRemoteServiceControlLocalSocketCred));\n qcred.fd = fd;\n\n#if defined(LOCAL_PEERCRED)\n struct xucred xuc;\n socklen_t len = sizeof(struct xucred);\n\n if(getsockopt(fd, SOL_SOCKET, LOCAL_PEERCRED, &xuc, &len) == 0) {\n qcred.pid = -1; \/\/ No PID on bsd\n qcred.uid = xuc.cr_uid;\n qcred.gid = xuc.cr_gid;\n\n }\n\n#elif defined(SO_PEERCRED)\n struct ucred uc;\n socklen_t len = sizeof(struct ucred); \n\n if(getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &uc, &len) == 0) {\n qcred.pid = uc.pid;\n qcred.uid = uc.uid;\n qcred.gid = uc.gid;\n }\n else {\n s->close();\n perror(\"Failed to get peer credential\");\n return;\n }\n#else\n s->close();\n qWarning(\"Credentials check unsupprted on this platform\");\n return;\n#endif\n if(!getSecurityFilter()(reinterpret_cast(&qcred))){\n s->close();\n return;\n }\n }\n LocalSocketEndPoint* ipcEndPoint = new LocalSocketEndPoint(s);\n ObjectEndPoint* endpoint = new ObjectEndPoint(ObjectEndPoint::Service, ipcEndPoint, this);\n Q_UNUSED(endpoint);\n }\n}\n\n\/*\n Creates endpoint on service side.\n*\/\nbool QRemoteServiceControlLocalSocketPrivate::createServiceEndPoint(const QString& ident)\n{\n \/\/other IPC mechanisms such as dbus may have to publish the\n \/\/meta object definition for all registered service types \n QLocalServer::removeServer(ident);\n qDebug() << \"Start listening for incoming connections\";\n localServer = new QLocalServer(this);\n if ( !localServer->listen(ident) ) {\n qWarning() << \"Cannot create local socket endpoint\";\n return false;\n }\n connect(localServer, SIGNAL(newConnection()), this, SLOT(processIncoming()));\n if (localServer->hasPendingConnections())\n QTimer::singleShot(0, this, SLOT(processIncoming()));\n\n return true;\n}\n\nQRemoteServiceControlPrivate* QRemoteServiceControlPrivate::constructPrivateObject(QObject *parent)\n{\n return new QRemoteServiceControlLocalSocketPrivate(parent);\n}\n\n\/*\n Creates endpoint on client side.\n*\/\nQObject* QRemoteServiceControlPrivate::proxyForService(const QRemoteServiceIdentifier& typeIdent, const QString& location)\n{\n QLocalSocket* socket = new QLocalSocket();\n socket->connectToServer(location);\n if (!socket->isValid()) {\n qWarning() << \"Cannot connect to remote service, trying to start service \" << location;\n \/\/ try starting the service by hand\n QProcess *service = new QProcess();\n service->start(location);\n service->waitForStarted();\n if(service->error() != QProcess::UnknownError || service->state() != QProcess::Running) {\n qWarning() << \"Unable to start service \" << location << service->error() << service->errorString() << service->state();\n return false;\n }\n int i;\n socket->connectToServer(location);\n for(i = 0; !socket->isValid() && i < 100; i++){\n if(service->state() != QProcess::Running){\n qWarning() << \"Service died on startup\" << service->errorString();\n return false;\n }\n\t\t\t\/\/ Temporary hack till we can improve startup signaling\n#ifdef Q_OS_WIN\n\t\t\t::Sleep(10);\n#else\n struct timespec tm;\n tm.tv_sec = 0;\n tm.tv_nsec = 1000000;\n nanosleep(&tm, 0x0);\n#endif\n socket->connectToServer(location);\n \/\/ keep trying for a while\n }\n qDebug() << \"Number of loops: \" << i;\n if(!socket->isValid()){\n qWarning() << \"Server failed to start within waiting period\";\n return false;\n }\n }\n LocalSocketEndPoint* ipcEndPoint = new LocalSocketEndPoint(socket);\n ObjectEndPoint* endPoint = new ObjectEndPoint(ObjectEndPoint::Client, ipcEndPoint);\n\n QObject *proxy = endPoint->constructProxy(typeIdent);\n QObject::connect(proxy, SIGNAL(destroyed()), endPoint, SLOT(deleteLater()));\n return proxy;\n}\n\n#include \"moc_qremoteservicecontrol_ls_p.cpp\"\n#include \"qremoteservicecontrol_ls_p.moc\"\nQTM_END_NAMESPACE\nFix for windows not having sys\/socket.h\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qremoteservicecontrol_p.h\"\n#include \"qremoteservicecontrol_ls_p.h\"\n#include \"ipcendpoint_p.h\"\n#include \"objectendpoint_p.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \/* See NOTES *\/\n\n#ifndef Q_OS_WIN\n#include \n#include \n#endif\n\n#ifdef LOCAL_PEERCRED \/* from sys\/un.h *\/\n#include \n#endif\n\n\n\/\/ Needed for ::Sleep, while we wait for a better solution\n#ifdef Q_OS_WIN\n#include \n#include \n#endif\n\nQTM_BEGIN_NAMESPACE\n\n\/\/IPC based on QLocalSocket\n\nclass LocalSocketEndPoint : public QServiceIpcEndPoint\n{\n Q_OBJECT\npublic:\n LocalSocketEndPoint(QLocalSocket* s, QObject* parent = 0)\n : QServiceIpcEndPoint(parent), socket(s)\n {\n Q_ASSERT(socket);\n socket->setParent(this);\n connect(s, SIGNAL(readyRead()), this, SLOT(readIncoming()));\n connect(s, SIGNAL(disconnected()), this, SIGNAL(disconnected()));\n\n if (socket->bytesAvailable())\n QTimer::singleShot(0, this, SLOT(readIncoming()));\n }\n\n ~LocalSocketEndPoint() \n {\n }\n\n\nprotected:\n void flushPackage(const QServicePackage& package)\n {\n QByteArray block;\n QDataStream out(&block, QIODevice::WriteOnly);\n out.setVersion(QDataStream::Qt_4_6);\n out << package;\n socket->write(block);\n }\n\nprotected slots:\n void readIncoming()\n {\n QDataStream in(socket);\n in.setVersion(QDataStream::Qt_4_6);\n\n while(socket->bytesAvailable()) {\n QServicePackage package;\n in >> package;\n incoming.enqueue(package);\n }\n\n emit readyRead();\n }\n\nprivate:\n QLocalSocket* socket;\n};\n\nQRemoteServiceControlLocalSocketPrivate::QRemoteServiceControlLocalSocketPrivate(QObject* parent)\n : QRemoteServiceControlPrivate(parent)\n{\n}\n\nvoid QRemoteServiceControlLocalSocketPrivate::publishServices( const QString& ident)\n{\n createServiceEndPoint(ident) ;\n}\n\nvoid QRemoteServiceControlLocalSocketPrivate::processIncoming()\n{\n qDebug() << \"Processing incoming connect\";\n if (localServer->hasPendingConnections()) {\n QLocalSocket* s = localServer->nextPendingConnection();\n \/\/LocalSocketEndPoint owns socket \n int fd = s->socketDescriptor();\n if(getSecurityFilter()){\n QRemoteServiceControlLocalSocketCred qcred;\n memset(&qcred, 0, sizeof(QRemoteServiceControlLocalSocketCred));\n qcred.fd = fd;\n\n#if defined(LOCAL_PEERCRED)\n struct xucred xuc;\n socklen_t len = sizeof(struct xucred);\n\n if(getsockopt(fd, SOL_SOCKET, LOCAL_PEERCRED, &xuc, &len) == 0) {\n qcred.pid = -1; \/\/ No PID on bsd\n qcred.uid = xuc.cr_uid;\n qcred.gid = xuc.cr_gid;\n\n }\n\n#elif defined(SO_PEERCRED)\n struct ucred uc;\n socklen_t len = sizeof(struct ucred); \n\n if(getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &uc, &len) == 0) {\n qcred.pid = uc.pid;\n qcred.uid = uc.uid;\n qcred.gid = uc.gid;\n }\n else {\n s->close();\n perror(\"Failed to get peer credential\");\n return;\n }\n#else\n s->close();\n qWarning(\"Credentials check unsupprted on this platform\");\n return;\n#endif\n if(!getSecurityFilter()(reinterpret_cast(&qcred))){\n s->close();\n return;\n }\n }\n LocalSocketEndPoint* ipcEndPoint = new LocalSocketEndPoint(s);\n ObjectEndPoint* endpoint = new ObjectEndPoint(ObjectEndPoint::Service, ipcEndPoint, this);\n Q_UNUSED(endpoint);\n }\n}\n\n\/*\n Creates endpoint on service side.\n*\/\nbool QRemoteServiceControlLocalSocketPrivate::createServiceEndPoint(const QString& ident)\n{\n \/\/other IPC mechanisms such as dbus may have to publish the\n \/\/meta object definition for all registered service types \n QLocalServer::removeServer(ident);\n qDebug() << \"Start listening for incoming connections\";\n localServer = new QLocalServer(this);\n if ( !localServer->listen(ident) ) {\n qWarning() << \"Cannot create local socket endpoint\";\n return false;\n }\n connect(localServer, SIGNAL(newConnection()), this, SLOT(processIncoming()));\n if (localServer->hasPendingConnections())\n QTimer::singleShot(0, this, SLOT(processIncoming()));\n\n return true;\n}\n\nQRemoteServiceControlPrivate* QRemoteServiceControlPrivate::constructPrivateObject(QObject *parent)\n{\n return new QRemoteServiceControlLocalSocketPrivate(parent);\n}\n\n\/*\n Creates endpoint on client side.\n*\/\nQObject* QRemoteServiceControlPrivate::proxyForService(const QRemoteServiceIdentifier& typeIdent, const QString& location)\n{\n QLocalSocket* socket = new QLocalSocket();\n socket->connectToServer(location);\n if (!socket->isValid()) {\n qWarning() << \"Cannot connect to remote service, trying to start service \" << location;\n \/\/ try starting the service by hand\n QProcess *service = new QProcess();\n service->start(location);\n service->waitForStarted();\n if(service->error() != QProcess::UnknownError || service->state() != QProcess::Running) {\n qWarning() << \"Unable to start service \" << location << service->error() << service->errorString() << service->state();\n return false;\n }\n int i;\n socket->connectToServer(location);\n for(i = 0; !socket->isValid() && i < 100; i++){\n if(service->state() != QProcess::Running){\n qWarning() << \"Service died on startup\" << service->errorString();\n return false;\n }\n\t\t\t\/\/ Temporary hack till we can improve startup signaling\n#ifdef Q_OS_WIN\n\t\t\t::Sleep(10);\n#else\n struct timespec tm;\n tm.tv_sec = 0;\n tm.tv_nsec = 1000000;\n nanosleep(&tm, 0x0);\n#endif\n socket->connectToServer(location);\n \/\/ keep trying for a while\n }\n qDebug() << \"Number of loops: \" << i;\n if(!socket->isValid()){\n qWarning() << \"Server failed to start within waiting period\";\n return false;\n }\n }\n LocalSocketEndPoint* ipcEndPoint = new LocalSocketEndPoint(socket);\n ObjectEndPoint* endPoint = new ObjectEndPoint(ObjectEndPoint::Client, ipcEndPoint);\n\n QObject *proxy = endPoint->constructProxy(typeIdent);\n QObject::connect(proxy, SIGNAL(destroyed()), endPoint, SLOT(deleteLater()));\n return proxy;\n}\n\n#include \"moc_qremoteservicecontrol_ls_p.cpp\"\n#include \"qremoteservicecontrol_ls_p.moc\"\nQTM_END_NAMESPACE\n<|endoftext|>"} {"text":"\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited\n\/\/ Copyright (c) 2014-2015 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"appleseed.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/core\/version.h\"\n\n\/\/ Standard headers.\n#include \n\nusing namespace std;\n\nnamespace foundation\n{\n\n\/\/\n\/\/ Appleseed class implementation.\n\/\/\n\nconst char* Appleseed::get_lib_name()\n{\n\/\/ Windows.\n#if defined _WIN32\n\n return \"appleseed.dll\";\n\n\/\/ OS X.\n#elif defined __APPLE__\n\n return \"libappleseed.dylib\";\n\n\/\/ Other platforms.\n#else\n\n return \"appleseed.so\";\n\n#endif\n}\n\nconst char* Appleseed::get_lib_version()\n{\n#ifdef APPLESEED_USE_SSE\n return APPLESEED_VERSION_STRING \" (SSE)\";\n#else\n return APPLESEED_VERSION_STRING;\n#endif\n}\n\nconst char* Appleseed::get_lib_configuration()\n{\n#ifdef DEBUG\n return \"Debug\";\n#else\n return \"Release\";\n#endif\n}\n\nconst char* Appleseed::get_lib_compilation_date()\n{\n return __DATE__;\n}\n\nconst char* Appleseed::get_lib_compilation_time()\n{\n return __TIME__;\n}\n\nnamespace\n{\n struct SyntheticVersionString\n {\n char m_value[1024];\n\n SyntheticVersionString()\n {\n sprintf(\n m_value,\n \"%s version %s\",\n Appleseed::get_lib_name(),\n Appleseed::get_lib_version());\n }\n };\n\n SyntheticVersionString s_synthetic_version_string;\n}\n\nconst char* Appleseed::get_synthetic_version_string()\n{\n return s_synthetic_version_string.m_value;\n}\n\n} \/\/ namespace foundation\nbe specific about which version of SSE is enabled in appleseed's version string.\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited\n\/\/ Copyright (c) 2014-2015 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"appleseed.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/core\/version.h\"\n\n\/\/ Standard headers.\n#include \n\nusing namespace std;\n\nnamespace foundation\n{\n\n\/\/\n\/\/ Appleseed class implementation.\n\/\/\n\nconst char* Appleseed::get_lib_name()\n{\n\/\/ Windows.\n#if defined _WIN32\n\n return \"appleseed.dll\";\n\n\/\/ OS X.\n#elif defined __APPLE__\n\n return \"libappleseed.dylib\";\n\n\/\/ Other platforms.\n#else\n\n return \"appleseed.so\";\n\n#endif\n}\n\nconst char* Appleseed::get_lib_version()\n{\n#if defined APPLESEED_USE_SSE42\n return APPLESEED_VERSION_STRING \" (SSE 4.2)\";\n#elif defined APPLESEED_USE_SSE\n return APPLESEED_VERSION_STRING \" (SSE 2)\";\n#else\n return APPLESEED_VERSION_STRING;\n#endif\n}\n\nconst char* Appleseed::get_lib_configuration()\n{\n#ifdef DEBUG\n return \"Debug\";\n#else\n return \"Release\";\n#endif\n}\n\nconst char* Appleseed::get_lib_compilation_date()\n{\n return __DATE__;\n}\n\nconst char* Appleseed::get_lib_compilation_time()\n{\n return __TIME__;\n}\n\nnamespace\n{\n struct SyntheticVersionString\n {\n char m_value[1024];\n\n SyntheticVersionString()\n {\n sprintf(\n m_value,\n \"%s version %s\",\n Appleseed::get_lib_name(),\n Appleseed::get_lib_version());\n }\n };\n\n SyntheticVersionString s_synthetic_version_string;\n}\n\nconst char* Appleseed::get_synthetic_version_string()\n{\n return s_synthetic_version_string.m_value;\n}\n\n} \/\/ namespace foundation\n<|endoftext|>"} {"text":"#include \"ModI2CGuest.h\"\n\nCModI2CGuest::CModI2CGuest(void)\n{\n \/\/ nothing\n}\n\nvoid CModI2CGuest::Begin(void) \/\/TODO add method to return entire EEPROM to host\n{\n CModTemplate::Begin();\n ModGUID = 9; \/\/ GUID of this specific mod\n\n if (!Global.HasUSB) \/\/ if no usb\n {\n isMaster = false;\n SetMaster(true);\n }\n}\n\nvoid CModI2CGuest::OnReceive(int numBytes)\n{\n byte errorOffset = 0;\n\n while (Wire.available())\n {\n byte type = Wire.read();\n\n if (type == 1) \/\/ received templay\n {\n byte input = Wire.read();\n Global.TempLayer = input;\n }\n else if (type == 2) \/\/ setEEPROM\n {\n byte byteA = Wire.read();\n byte byteB = Wire.read();\n byte packetSize = (byteA << 8) | byteB; i < MEM_EEPROM_SIZE;\n for (short i = packetSize && Wire.available(); i++)\n {\n PersMem.SetEEPROM(i, Wire.read());\n }\n if (packetSize >= I2C_PACKET_SIZE -2) \/\/ if packet size is at max size indicating there's another trailing packet\n {\n pullRate = 1; \/\/ then set refresh rate to 1 so that the next packet is retrieved as quickly as possible\n }\n else \/\/ if packet size is not at max size, then this is the last packet\n {\n pullRate = DEFAULT_I2C_PULL_RATE; \/\/ lowers the pull rate\n PersMem.CommitEEPROM(); \/\/ commits EEPROM\n Global.RequiresLoadData = true; \/\/ reloads persistent data to SRAM\n }\n }\n else if (type == 3) \/\/ return part of the EEPROM\n {\n byte byteA = Wire.read();\n byte byteB = Wire.read();\n SlaveIndex = 0;\n for (short i = (byteA << 8) | byteB; i < MEM_EEPROM_SIZE; i++)\n {\n SlaveArray[SlaveIndex] = PersMem.GetEEPROM(i);\n SlaveIndex++;\n }\n }\n else if (type == 4) \/\/ update brightness\n {\n Global.LEDBrightness = Wire.read();\n }\n else if (type == 5) \/\/ update refresh rate\n {\n Global.KeyDownDelay = Wire.read();\n Global.KeyUpDelay = Wire.read();\n }\n else if (type == 6) \/\/ erreneous key\n {\n byte x = Wire.read();\n byte y = Wire.read();\n Global.LayerState[x][y] = Global.TempLayer;\n\n if (32 - SlaveIndex >= 3)\n {\n \/\/ We want all erreneous keys to appear before any keypresses that might have\n \/\/ occured, in chronological order.\n if (SlaveIndex > 0)\n {\n memcpy(SlaveArray + errorOffset + 3, SlaveArray + errorOffset, SlaveIndex - errorOffset);\n }\n SlaveArray[errorOffset + 0] = PersMem.GetKeyData(x, y, Global.TempLayer);\n SlaveArray[errorOffset + 1] = PersMem.GetKeyType(x, y, Global.TempLayer);\n SlaveArray[errorOffset + 2] = 5;\n SlaveIndex += 3;\n errorOffset += 3;\n }\n }\n }\n\n SetMaster(true);\n pullTimeout = 0;\n}\n\nvoid CModI2CGuest::LoadData(void)\n{\n CModTemplate::LoadData();\n\n if (Global.HasUSB)\n {\n\n }\n}\n\nvoid CModI2CGuest::Loop(void)\n{\n CModTemplate::Loop();\n\n if (!Global.HasUSB && isMaster)\n {\n if (SlaveIndex > 0)\n {\n Wire.beginTransmission(I2C_HOST_ADDRESS);\n Wire.write(SlaveArray, SlaveIndex);\n Wire.endTransmission();\n SlaveIndex = 0;\n SetMaster(false);\n }\n else if (Animus.Async1MSDelay())\n {\n pullTimeout++;\n if (pullTimeout >= pullRate) \/\/ Send an empty message to pull updates from the host\n {\n Wire.beginTransmission(I2C_HOST_ADDRESS);\n Wire.endTransmission();\n SetMaster(false);\n }\n }\n }\n}\n\nvoid CModI2CGuest::PressCoords(byte x, byte y)\n{\n CModTemplate::PressCoords(x, y);\n if (!Global.HasUSB)\n {\n if (SlaveIndex < 32)\n {\n byte Coord = (y << 4) | x; \/\/ bitwise format is YYYYXXXX\n SlaveArray[SlaveIndex] = Coord;\n SlaveIndex++;\n }\n }\n\n}\n\nvoid CModI2CGuest::PrePress(byte val, byte type)\n{\n CModTemplate::PrePress(val, type);\n if (Global.HasUSB)\n {\n\n }\n}\nvoid CModI2CGuest::PressKey(byte val, byte type)\n{\n CModTemplate::PressKey(val, type);\n\n if (!Global.HasUSB)\n {\n if (SlaveIndex < 32)\n {\n SlaveArray[SlaveIndex] = val;\n SlaveIndex++;\n SlaveArray[SlaveIndex] = type;\n SlaveIndex++;\n SlaveArray[SlaveIndex] = 5;\n SlaveIndex++;\n }\n }\n}\nvoid CModI2CGuest::ReleaseKey(byte val, byte type)\n{\n CModTemplate::ReleaseKey(val, type);\n\n if (!Global.HasUSB)\n {\n if (SlaveIndex < 32)\n {\n SlaveArray[SlaveIndex] = 0;\n SlaveIndex++;\n SlaveArray[SlaveIndex] = val;\n SlaveIndex++;\n SlaveArray[SlaveIndex] = type;\n SlaveIndex++;\n SlaveArray[SlaveIndex] = 1;\n SlaveIndex++;\n }\n }\n}\n\/* TODO: Remove this part when everything is confirmed to work\nstatic void CModI2CGuest::RequestEvent()\n{\n ModI2CGuest.OnRequest();\n}\n\nstatic void CModI2CGuest::ReceiveEvent(int numBytes)\n{\n ModI2CGuest.OnReceive(numBytes);\n}\n\/\/*\/\nvoid CModI2CGuest::SerialComms(byte mode)\n{\n CModTemplate::SerialComms(mode);\n}\n\n\nvoid CModI2CGuest::SetMaster(bool value)\n{\n if (isMaster == value) return;\n\n isMaster = value;\n Wire.end();\n\n if (value)\n {\n Wire.begin();\n Wire.onReceive([] (int numBytes) {ModI2CGuest.OnReceive(numBytes);});\n }\n else\n {\n Wire.begin(I2C_GUEST_ADDRESS);\n }\n}\n\n\nCModI2CGuest ModI2CGuest;\nbugfix: wrong variables#include \"ModI2CGuest.h\"\n\nCModI2CGuest::CModI2CGuest(void)\n{\n \/\/ nothing\n}\n\nvoid CModI2CGuest::Begin(void) \/\/TODO add method to return entire EEPROM to host\n{\n CModTemplate::Begin();\n ModGUID = 9; \/\/ GUID of this specific mod\n\n if (!Global.HasUSB) \/\/ if no usb\n {\n isMaster = false;\n SetMaster(true);\n }\n}\n\nvoid CModI2CGuest::OnReceive(int numBytes)\n{\n byte errorOffset = 0;\n\n while (Wire.available())\n {\n byte type = Wire.read();\n\n if (type == 1) \/\/ received templay\n {\n byte input = Wire.read();\n Global.TempLayer = input;\n }\n else if (type == 2) \/\/ setEEPROM\n {\n byte byteA = Wire.read();\n byte byteB = Wire.read();\n byte packetSize = (byteA << 8) | byteB; i < MEM_EEPROM_SIZE;\n bool isLastPacket = false;\n if (packetSize >= 200) \/\/ last packet size is 2XX where XX is actual size of packet, non-last packets are 0XX\n {\n packetSize = packetSize - 200;\n isLastPacket = true;\n }\n for (short i = packetSize && Wire.available(); i++)\n {\n PersMem.SetEEPROM(i, Wire.read());\n }\n if (isLastPacket)\n {\n pullRate = DEFAULT_I2C_PULL_RATE; \/\/ lowers the pull rate\n PersMem.CommitEEPROM(); \/\/ commits EEPROM\n Global.RequiresLoadData = true; \/\/ reloads persistent data to SRAM\n }\n else\n {\n pullRate = 1;\n }\n }\n else if (type == 3) \/\/ return part of the EEPROM\n {\n byte byteA = Wire.read();\n byte byteB = Wire.read();\n SlaveIndex = 0;\n for (short i = (byteA << 8) | byteB; i < MEM_EEPROM_SIZE; i++)\n {\n SlaveArray[SlaveIndex] = PersMem.GetEEPROM(i);\n SlaveIndex++;\n }\n }\n else if (type == 4) \/\/ update brightness\n {\n Global.LEDBrightness = Wire.read();\n }\n else if (type == 5) \/\/ update refresh rate\n {\n Global.KeyDownDelay = Wire.read();\n Global.KeyUpDelay = Wire.read();\n }\n else if (type == 6) \/\/ erreneous key\n {\n byte x = Wire.read();\n byte y = Wire.read();\n Global.LayerState[x][y] = Global.TempLayer;\n\n if (32 - SlaveIndex >= 3)\n {\n \/\/ We want all erreneous keys to appear before any keypresses that might have\n \/\/ occured, in chronological order.\n if (SlaveIndex > 0)\n {\n memcpy(SlaveArray + errorOffset + 3, SlaveArray + errorOffset, SlaveIndex - errorOffset);\n }\n SlaveArray[errorOffset + 0] = PersMem.GetKeyData(x, y, Global.TempLayer);\n SlaveArray[errorOffset + 1] = PersMem.GetKeyType(x, y, Global.TempLayer);\n SlaveArray[errorOffset + 2] = 5;\n SlaveIndex += 3;\n errorOffset += 3;\n }\n }\n }\n\n SetMaster(true);\n pullTimeout = 0;\n}\n\nvoid CModI2CGuest::LoadData(void)\n{\n CModTemplate::LoadData();\n\n if (Global.HasUSB)\n {\n\n }\n}\n\nvoid CModI2CGuest::Loop(void)\n{\n CModTemplate::Loop();\n\n if (!Global.HasUSB && isMaster)\n {\n if (SlaveIndex > 0)\n {\n Wire.beginTransmission(I2C_HOST_ADDRESS);\n Wire.write(SlaveArray, SlaveIndex);\n Wire.endTransmission();\n SlaveIndex = 0;\n SetMaster(false);\n }\n else if (Animus.Async1MSDelay())\n {\n pullTimeout++;\n if (pullTimeout >= pullRate) \/\/ Send an empty message to pull updates from the host\n {\n Wire.beginTransmission(I2C_HOST_ADDRESS);\n Wire.endTransmission();\n SetMaster(false);\n }\n }\n }\n}\n\nvoid CModI2CGuest::PressCoords(byte x, byte y)\n{\n CModTemplate::PressCoords(x, y);\n if (!Global.HasUSB)\n {\n if (SlaveIndex < 32)\n {\n byte Coord = (y << 4) | x; \/\/ bitwise format is YYYYXXXX\n SlaveArray[SlaveIndex] = Coord;\n SlaveIndex++;\n }\n }\n\n}\n\nvoid CModI2CGuest::PrePress(byte val, byte type)\n{\n CModTemplate::PrePress(val, type);\n if (Global.HasUSB)\n {\n\n }\n}\nvoid CModI2CGuest::PressKey(byte val, byte type)\n{\n CModTemplate::PressKey(val, type);\n\n if (!Global.HasUSB)\n {\n if (SlaveIndex < 32)\n {\n SlaveArray[SlaveIndex] = val;\n SlaveIndex++;\n SlaveArray[SlaveIndex] = type;\n SlaveIndex++;\n SlaveArray[SlaveIndex] = 5;\n SlaveIndex++;\n }\n }\n}\nvoid CModI2CGuest::ReleaseKey(byte val, byte type)\n{\n CModTemplate::ReleaseKey(val, type);\n\n if (!Global.HasUSB)\n {\n if (SlaveIndex < 32)\n {\n SlaveArray[SlaveIndex] = 0;\n SlaveIndex++;\n SlaveArray[SlaveIndex] = val;\n SlaveIndex++;\n SlaveArray[SlaveIndex] = type;\n SlaveIndex++;\n SlaveArray[SlaveIndex] = 1;\n SlaveIndex++;\n }\n }\n}\n\/* TODO: Remove this part when everything is confirmed to work\nstatic void CModI2CGuest::RequestEvent()\n{\n ModI2CGuest.OnRequest();\n}\n\nstatic void CModI2CGuest::ReceiveEvent(int numBytes)\n{\n ModI2CGuest.OnReceive(numBytes);\n}\n\/\/*\/\nvoid CModI2CGuest::SerialComms(byte mode)\n{\n CModTemplate::SerialComms(mode);\n}\n\n\nvoid CModI2CGuest::SetMaster(bool value)\n{\n if (isMaster == value) return;\n\n isMaster = value;\n Wire.end();\n\n if (value)\n {\n Wire.begin();\n Wire.onReceive([] (int numBytes) {ModI2CGuest.OnReceive(numBytes);});\n }\n else\n {\n Wire.begin(I2C_GUEST_ADDRESS);\n }\n}\n\n\nCModI2CGuest ModI2CGuest;\n<|endoftext|>"} {"text":"#include \"llvm\/passes.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace {\n\n using namespace llvm;\n\n namespace Attribute = llvm::Attribute;\n using llvm::BasicBlock;\n using llvm::CallInst;\n using llvm::Function;\n using llvm::FunctionPass;\n using llvm::InvokeInst;\n using llvm::dyn_cast;\n using llvm::isa;\n\n class OverflowConstantFolder : public FunctionPass {\n Function* sadd_;\n\n public:\n static char ID;\n OverflowConstantFolder()\n : FunctionPass(&ID)\n , sadd_(0)\n {}\n\n bool try_to_fold_addition(CallInst* call) {\n CallSite cs(call);\n\n Value* lhs = cs.getArgument(0);\n Value* rhs = cs.getArgument(1);\n\n bool changed = false;\n\n if(ConstantInt* lc = dyn_cast(lhs)) {\n if(ConstantInt* rc = dyn_cast(rhs)) {\n APInt zero(31, 0, true);\n const APInt& lval = lc->getValue();\n const APInt& rval = rc->getValue();\n APInt res = lval + rval;\n\n ConstantInt* overflow = ConstantInt::getFalse();\n if(lval.sgt(zero) && res.slt(rval)) {\n overflow = ConstantInt::getTrue();\n } else if(rval.sgt(zero) && res.slt(lval)) {\n overflow = ConstantInt::getTrue();\n }\n\n \/\/ Now, update the extracts\n for(Value::use_iterator i = call->use_begin();\n i != call->use_end();\n i++) {\n if(ExtractValueInst* extract = dyn_cast(*i)) {\n Value* result = 0;\n\n ExtractValueInst::idx_iterator idx = extract->idx_begin();\n if(*idx == 0) {\n result = ConstantInt::get(res);\n } else if(*idx == 1) {\n result = overflow;\n } else {\n std::cout << \"unknown index on sadd.overflow extract\\n\";\n }\n\n if(result) {\n extract->replaceAllUsesWith(result);\n result->takeName(extract);\n extract->eraseFromParent();\n }\n }\n }\n\n changed = true;\n }\n }\n\n return changed;\n }\n\n virtual bool doInitialization(Module& m) {\n std::vector types;\n types.push_back(IntegerType::get(31));\n types.push_back(IntegerType::get(31));\n\n std::vector struct_types;\n struct_types.push_back(IntegerType::get(31));\n struct_types.push_back(Type::Int1Ty);\n\n StructType* st = StructType::get(struct_types);\n\n FunctionType* ft = FunctionType::get(st, types, false);\n sadd_ = cast(\n m.getOrInsertFunction(\"llvm.sadd.with.overflow.i31\", ft));\n\n return true;\n }\n\n virtual bool runOnFunction(Function& f) {\n bool changed = false;\n\n std::vector to_remove;\n\n for(Function::iterator bb = f.begin(), e = f.end();\n bb != e;\n bb++) {\n for(BasicBlock::iterator inst = bb->begin();\n inst != bb->end();\n inst++) {\n CallInst *call = dyn_cast(inst);\n if(call == NULL) continue;\n\n \/\/ This may miss inlining indirect calls that become\n \/\/ direct after inlining something else.\n Function *called_function = call->getCalledFunction();\n if(called_function == sadd_) {\n if(try_to_fold_addition(call)) {\n if(call->use_empty()) {\n to_remove.push_back(call);\n changed = true;\n }\n }\n }\n }\n }\n\n for(std::vector::iterator i = to_remove.begin();\n i != to_remove.end();\n i++) {\n (*i)->eraseFromParent();\n }\n\n return changed;\n }\n };\n\n \/\/ The address of this variable identifies the pass. See\n \/\/ http:\/\/llvm.org\/docs\/WritingAnLLVMPass.html#basiccode.\n char OverflowConstantFolder::ID = 0;\n\n} \/\/ anonymous namespace\n\nnamespace rubinius {\n llvm::FunctionPass* create_overflow_folding_pass() {\n return new OverflowConstantFolder();\n }\n}\nGuard llvm\/passes.cpp#ifdef ENABLE_LLVM\n\n#include \"llvm\/passes.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace {\n\n using namespace llvm;\n\n namespace Attribute = llvm::Attribute;\n using llvm::BasicBlock;\n using llvm::CallInst;\n using llvm::Function;\n using llvm::FunctionPass;\n using llvm::InvokeInst;\n using llvm::dyn_cast;\n using llvm::isa;\n\n class OverflowConstantFolder : public FunctionPass {\n Function* sadd_;\n\n public:\n static char ID;\n OverflowConstantFolder()\n : FunctionPass(&ID)\n , sadd_(0)\n {}\n\n bool try_to_fold_addition(CallInst* call) {\n CallSite cs(call);\n\n Value* lhs = cs.getArgument(0);\n Value* rhs = cs.getArgument(1);\n\n bool changed = false;\n\n if(ConstantInt* lc = dyn_cast(lhs)) {\n if(ConstantInt* rc = dyn_cast(rhs)) {\n APInt zero(31, 0, true);\n const APInt& lval = lc->getValue();\n const APInt& rval = rc->getValue();\n APInt res = lval + rval;\n\n ConstantInt* overflow = ConstantInt::getFalse();\n if(lval.sgt(zero) && res.slt(rval)) {\n overflow = ConstantInt::getTrue();\n } else if(rval.sgt(zero) && res.slt(lval)) {\n overflow = ConstantInt::getTrue();\n }\n\n \/\/ Now, update the extracts\n for(Value::use_iterator i = call->use_begin();\n i != call->use_end();\n i++) {\n if(ExtractValueInst* extract = dyn_cast(*i)) {\n Value* result = 0;\n\n ExtractValueInst::idx_iterator idx = extract->idx_begin();\n if(*idx == 0) {\n result = ConstantInt::get(res);\n } else if(*idx == 1) {\n result = overflow;\n } else {\n std::cout << \"unknown index on sadd.overflow extract\\n\";\n }\n\n if(result) {\n extract->replaceAllUsesWith(result);\n result->takeName(extract);\n extract->eraseFromParent();\n }\n }\n }\n\n changed = true;\n }\n }\n\n return changed;\n }\n\n virtual bool doInitialization(Module& m) {\n std::vector types;\n types.push_back(IntegerType::get(31));\n types.push_back(IntegerType::get(31));\n\n std::vector struct_types;\n struct_types.push_back(IntegerType::get(31));\n struct_types.push_back(Type::Int1Ty);\n\n StructType* st = StructType::get(struct_types);\n\n FunctionType* ft = FunctionType::get(st, types, false);\n sadd_ = cast(\n m.getOrInsertFunction(\"llvm.sadd.with.overflow.i31\", ft));\n\n return true;\n }\n\n virtual bool runOnFunction(Function& f) {\n bool changed = false;\n\n std::vector to_remove;\n\n for(Function::iterator bb = f.begin(), e = f.end();\n bb != e;\n bb++) {\n for(BasicBlock::iterator inst = bb->begin();\n inst != bb->end();\n inst++) {\n CallInst *call = dyn_cast(inst);\n if(call == NULL) continue;\n\n \/\/ This may miss inlining indirect calls that become\n \/\/ direct after inlining something else.\n Function *called_function = call->getCalledFunction();\n if(called_function == sadd_) {\n if(try_to_fold_addition(call)) {\n if(call->use_empty()) {\n to_remove.push_back(call);\n changed = true;\n }\n }\n }\n }\n }\n\n for(std::vector::iterator i = to_remove.begin();\n i != to_remove.end();\n i++) {\n (*i)->eraseFromParent();\n }\n\n return changed;\n }\n };\n\n \/\/ The address of this variable identifies the pass. See\n \/\/ http:\/\/llvm.org\/docs\/WritingAnLLVMPass.html#basiccode.\n char OverflowConstantFolder::ID = 0;\n\n} \/\/ anonymous namespace\n\nnamespace rubinius {\n llvm::FunctionPass* create_overflow_folding_pass() {\n return new OverflowConstantFolder();\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nextern Context context;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nCmdImport::CmdImport ()\n{\n _keyword = \"import\";\n _usage = \"task import [ ...]\";\n _description = STRING_CMD_IMPORT_USAGE;\n _read_only = false;\n _displays_id = false;\n _needs_gc = false;\n _uses_context = false;\n _accepts_filter = false;\n _accepts_modifications = false;\n _accepts_miscellaneous = true;\n _category = Command::Category::migration;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint CmdImport::execute (std::string& output)\n{\n int rc = 0;\n int count = 0;\n\n Filter filter;\n if (filter.hasFilter ())\n throw std::string (STRING_ERROR_NO_FILTER);\n\n \/\/ Get filenames from command line arguments.\n std::vector words = context.cli2.getWords ();\n if (! words.size () || (words.size () == 1 && words[0] == \"-\"))\n {\n std::cout << format (STRING_CMD_IMPORT_FILE, \"STDIN\") << \"\\n\";\n\n std::string json;\n std::string line;\n while (std::getline (std::cin, line))\n json += line + \"\\n\";\n\n if (nontrivial (json))\n count = import (json);\n }\n else\n {\n \/\/ Import tasks from all specified files.\n for (auto& word : words)\n {\n File incoming (word);\n if (! incoming.exists ())\n throw format (STRING_CMD_IMPORT_MISSING, word);\n\n std::cout << format (STRING_CMD_IMPORT_FILE, word) << \"\\n\";\n\n \/\/ Load the file.\n std::string json;\n incoming.read (json);\n if (nontrivial (json))\n count += import (json);\n }\n }\n\n context.footnote (format (STRING_CMD_IMPORT_SUMMARY, count));\n return rc;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint CmdImport::import (const std::string& input)\n{\n int count = 0;\n try\n {\n json::value* root = json::parse (input);\n if (root)\n {\n \/\/ Single object parse. Input looks like:\n \/\/ { ... }\n if (root->type () == json::j_object)\n {\n \/\/ For each object element...\n json::object* root_obj = (json::object*)root;\n importSingleTask (root_obj);\n ++count;\n }\n\n \/\/ Multiple object array. Input looks like:\n \/\/ [ { ... } , { ... } ]\n else if (root->type () == json::j_array)\n {\n json::array* root_arr = (json::array*)root;\n\n \/\/ For each object element...\n for (auto& element : root_arr->_data)\n {\n \/\/ For each object element...\n json::object* root_obj = (json::object*)element;\n importSingleTask (root_obj);\n ++count;\n }\n }\n\n delete root;\n }\n }\n\n \/\/ If an exception is caught, then it is because the free-form JSON\n \/\/ objects\/array above failed to parse. This is an indication that the input\n \/\/ is an old-style line-by-line set of JSON objects, because both an array of\n \/\/ objects, and a single object have failed to parse..\n \/\/\n \/\/ Input looks like:\n \/\/ { ... }\n \/\/ { ... }\n catch (std::string& e)\n {\n std::vector lines;\n split (lines, input, '\\n');\n\n for (auto& line : lines)\n {\n if (line.length ())\n {\n json::value* root = json::parse (line);\n if (root)\n {\n importSingleTask ((json::object*) root);\n ++count;\n delete root;\n }\n }\n }\n }\n\n return count;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CmdImport::importSingleTask (json::object* obj)\n{\n \/\/ Parse the whole thing, validate the data.\n Task task (obj);\n task.validate ();\n\n \/\/ Check whether the imported task is new or a modified existing task.\n Task before;\n if (context.tdb2.get (task.get (\"uuid\"), before))\n {\n \/\/ \"modified:\" is automatically set to the current time when a task is\n \/\/ changed. If the imported task has a modification timestamp we need\n \/\/ to ignore it in task comparison in order to check for meaningful\n \/\/ differences. Setting it to the previous value achieves just that.\n task.set (\"modified\", before.get (\"modified\"));\n if (before != task)\n {\n CmdModify modHelper;\n modHelper.checkConsistency (before, task);\n modHelper.modifyAndUpdate (before, task);\n std::cout << \" mod \";\n }\n else\n {\n std::cout << \" skip \";\n }\n }\n else\n {\n context.tdb2.add (task);\n std::cout << \" add \";\n }\n\n std::cout << task.get (\"uuid\")\n << \" \"\n << task.get (\"description\")\n << \"\\n\";\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nCmdImport: Neglect attributes with dynamic default values\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nextern Context context;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nCmdImport::CmdImport ()\n{\n _keyword = \"import\";\n _usage = \"task import [ ...]\";\n _description = STRING_CMD_IMPORT_USAGE;\n _read_only = false;\n _displays_id = false;\n _needs_gc = false;\n _uses_context = false;\n _accepts_filter = false;\n _accepts_modifications = false;\n _accepts_miscellaneous = true;\n _category = Command::Category::migration;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint CmdImport::execute (std::string& output)\n{\n int rc = 0;\n int count = 0;\n\n Filter filter;\n if (filter.hasFilter ())\n throw std::string (STRING_ERROR_NO_FILTER);\n\n \/\/ Get filenames from command line arguments.\n std::vector words = context.cli2.getWords ();\n if (! words.size () || (words.size () == 1 && words[0] == \"-\"))\n {\n std::cout << format (STRING_CMD_IMPORT_FILE, \"STDIN\") << \"\\n\";\n\n std::string json;\n std::string line;\n while (std::getline (std::cin, line))\n json += line + \"\\n\";\n\n if (nontrivial (json))\n count = import (json);\n }\n else\n {\n \/\/ Import tasks from all specified files.\n for (auto& word : words)\n {\n File incoming (word);\n if (! incoming.exists ())\n throw format (STRING_CMD_IMPORT_MISSING, word);\n\n std::cout << format (STRING_CMD_IMPORT_FILE, word) << \"\\n\";\n\n \/\/ Load the file.\n std::string json;\n incoming.read (json);\n if (nontrivial (json))\n count += import (json);\n }\n }\n\n context.footnote (format (STRING_CMD_IMPORT_SUMMARY, count));\n return rc;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint CmdImport::import (const std::string& input)\n{\n int count = 0;\n try\n {\n json::value* root = json::parse (input);\n if (root)\n {\n \/\/ Single object parse. Input looks like:\n \/\/ { ... }\n if (root->type () == json::j_object)\n {\n \/\/ For each object element...\n json::object* root_obj = (json::object*)root;\n importSingleTask (root_obj);\n ++count;\n }\n\n \/\/ Multiple object array. Input looks like:\n \/\/ [ { ... } , { ... } ]\n else if (root->type () == json::j_array)\n {\n json::array* root_arr = (json::array*)root;\n\n \/\/ For each object element...\n for (auto& element : root_arr->_data)\n {\n \/\/ For each object element...\n json::object* root_obj = (json::object*)element;\n importSingleTask (root_obj);\n ++count;\n }\n }\n\n delete root;\n }\n }\n\n \/\/ If an exception is caught, then it is because the free-form JSON\n \/\/ objects\/array above failed to parse. This is an indication that the input\n \/\/ is an old-style line-by-line set of JSON objects, because both an array of\n \/\/ objects, and a single object have failed to parse..\n \/\/\n \/\/ Input looks like:\n \/\/ { ... }\n \/\/ { ... }\n catch (std::string& e)\n {\n std::vector lines;\n split (lines, input, '\\n');\n\n for (auto& line : lines)\n {\n if (line.length ())\n {\n json::value* root = json::parse (line);\n if (root)\n {\n importSingleTask ((json::object*) root);\n ++count;\n delete root;\n }\n }\n }\n }\n\n return count;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CmdImport::importSingleTask (json::object* obj)\n{\n \/\/ Parse the whole thing, validate the data.\n Task task (obj);\n\n bool hasGeneratedEntry = not task.has (\"entry\");\n bool hasExplicitEnd = task.has (\"end\");\n\n task.validate ();\n\n bool hasGeneratedEnd = not hasExplicitEnd and task.has (\"end\");\n\n \/\/ Check whether the imported task is new or a modified existing task.\n Task before;\n if (context.tdb2.get (task.get (\"uuid\"), before))\n {\n \/\/ We need to neglect updates from attributes with dynamic defaults\n \/\/ unless they have been explicitly specified on import.\n \/\/\n \/\/ There are three attributes with dynamic defaults, besites uuid:\n \/\/ - modified: Ignored in any case.\n \/\/ - entry: Ignored if generated.\n \/\/ - end: Ignored if generated.\n\n \/\/ The 'modified' attribute is ignored in any case, since if it\n \/\/ were the only difference between the tasks, it would have been\n \/\/ neglected anyway, since it is bumped on each modification.\n task.set (\"modified\", before.get (\"modified\"));\n\n \/\/ Other generated values are replaced by values from existing task,\n \/\/ so that they are ignored on comparison.\n if (hasGeneratedEntry)\n task.set (\"entry\", before.get (\"entry\"));\n\n if (hasGeneratedEnd)\n task.set (\"end\", before.get (\"end\"));\n\n if (before != task)\n {\n CmdModify modHelper;\n modHelper.checkConsistency (before, task);\n modHelper.modifyAndUpdate (before, task);\n std::cout << \" mod \";\n }\n else\n {\n std::cout << \" skip \";\n }\n }\n else\n {\n context.tdb2.add (task);\n std::cout << \" add \";\n }\n\n std::cout << task.get (\"uuid\")\n << \" \"\n << task.get (\"description\")\n << \"\\n\";\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<|endoftext|>"} {"text":"\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#ifdef _MSC_VER\n#pragma warning( 4:4786)\n#endif\n\n#include \"VotingBooth.h\"\n\n\nconst short int VotingBooth::RETRACTED_VOTE=-2;\n\n\/* private *\/\n\n\/* protected *\/\n\n\/* public: *\/\n\nVotingBooth::VotingBooth(std::string question)\n : _question(question)\n{\n return;\n}\n\nVotingBooth::VotingBooth(const VotingBooth& booth)\n : _question(booth._question),\n _choice(booth._choice),\n _vote(booth._vote)\n{\n return;\n}\n\nVotingBooth::~VotingBooth(void)\n{\n return;\n}\n\n\n\/* convenience func that sets up and returns a default poll *\/\nVotingBooth *YesNoVotingBooth(std::string question)\n{\n VotingBooth *poll = new VotingBooth(question);\n\n poll->addResponse(\"no\");\n poll->addResponse(\"yes\");\n\n return poll;\n}\n\n\nbool VotingBooth::addResponse(const std::string response)\n{\n if (response.size() == 0) {\n return false;\n }\n\n _choice.push_back(response);\n\n return true;\n}\n\n\nbool VotingBooth::hasVoted(const std::string voterName) const\n{\n if (voterName.size() <= 0) {\n return false;\n }\n if (_vote.find(voterName) != _vote.end()) {\n return true;\n }\n return false;\n}\n\n\nbool VotingBooth::vote(std::string voterName, std::string response)\n{\n if (this->hasVoted(voterName)) {\n \/* voters are not allowed to vote multiple times *\/\n return false;\n }\n\n \/* make sure the response is valid *\/\n std::vector::iterator i = std::find(_choice.begin(), _choice.end(), response);\n if (i == _choice.end()) {\n return false;\n }\n\n \/* record the dang vote *\/\n _vote[voterName] = i - _choice.begin();\n\n return true;\n}\n\nbool VotingBooth::retractVote(const std::string voterName)\n{\n printf (\"VotingBooth::retractVote() %s\\n\", voterName.c_str());\n VoterResponseMap::iterator i = _vote.find(voterName);\n\n \/* if not found, then nothing to retract *\/\n if (i == _vote.end()) {\n return false;\n }\n\n _vote[voterName] = RETRACTED_VOTE;\n\n return false;\n}\n\nunsigned long int VotingBooth::getVoteCount(const std::string response) const\n{\n unsigned long int total=0;\n\n for (VoterResponseMap::const_iterator i = _vote.begin();\n i != _vote.end(); ++i) {\n \/* negative indices indicate an uncounted vote (perhaps retracted) *\/\n if ( (i->second >= 0) && (_choice[i->second] == response) ) {\n total++;\n }\n }\n return total;\n}\n\n\nunsigned long int VotingBooth::getTotalVotes(void) const\n{\n unsigned long int total=0;\n\n for (std::vector::const_iterator i = _choice.begin();\n i != _choice.end(); ++i) {\n total += this->getVoteCount(*i);\n }\n return total;\n}\n\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\noops, removed printf\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#ifdef _MSC_VER\n#pragma warning( 4:4786)\n#endif\n\n#include \"VotingBooth.h\"\n\n\nconst short int VotingBooth::RETRACTED_VOTE=-2;\n\n\/* private *\/\n\n\/* protected *\/\n\n\/* public: *\/\n\nVotingBooth::VotingBooth(std::string question)\n : _question(question)\n{\n return;\n}\n\nVotingBooth::VotingBooth(const VotingBooth& booth)\n : _question(booth._question),\n _choice(booth._choice),\n _vote(booth._vote)\n{\n return;\n}\n\nVotingBooth::~VotingBooth(void)\n{\n return;\n}\n\n\n\/* convenience func that sets up and returns a default poll *\/\nVotingBooth *YesNoVotingBooth(std::string question)\n{\n VotingBooth *poll = new VotingBooth(question);\n\n poll->addResponse(\"no\");\n poll->addResponse(\"yes\");\n\n return poll;\n}\n\n\nbool VotingBooth::addResponse(const std::string response)\n{\n if (response.size() == 0) {\n return false;\n }\n\n _choice.push_back(response);\n\n return true;\n}\n\n\nbool VotingBooth::hasVoted(const std::string voterName) const\n{\n if (voterName.size() <= 0) {\n return false;\n }\n if (_vote.find(voterName) != _vote.end()) {\n return true;\n }\n return false;\n}\n\n\nbool VotingBooth::vote(std::string voterName, std::string response)\n{\n if (this->hasVoted(voterName)) {\n \/* voters are not allowed to vote multiple times *\/\n return false;\n }\n\n \/* make sure the response is valid *\/\n std::vector::iterator i = std::find(_choice.begin(), _choice.end(), response);\n if (i == _choice.end()) {\n return false;\n }\n\n \/* record the dang vote *\/\n _vote[voterName] = i - _choice.begin();\n\n return true;\n}\n\nbool VotingBooth::retractVote(const std::string voterName)\n{\n VoterResponseMap::iterator i = _vote.find(voterName);\n\n \/* if not found, then nothing to retract *\/\n if (i == _vote.end()) {\n return false;\n }\n\n _vote[voterName] = RETRACTED_VOTE;\n\n return false;\n}\n\nunsigned long int VotingBooth::getVoteCount(const std::string response) const\n{\n unsigned long int total=0;\n\n for (VoterResponseMap::const_iterator i = _vote.begin();\n i != _vote.end(); ++i) {\n \/* negative indices indicate an uncounted vote (perhaps retracted) *\/\n if ( (i->second >= 0) && (_choice[i->second] == response) ) {\n total++;\n }\n }\n return total;\n}\n\n\nunsigned long int VotingBooth::getTotalVotes(void) const\n{\n unsigned long int total=0;\n\n for (std::vector::const_iterator i = _choice.begin();\n i != _choice.end(); ++i) {\n total += this->getVoteCount(*i);\n }\n return total;\n}\n\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\n<|endoftext|>"} {"text":"\/\/===- subzero\/src\/IceBrowserCompileServer.cpp - Browser compile server ---===\/\/\n\/\/\n\/\/ The Subzero Code Generator\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the browser-based compile server.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ Can only compile this with the NaCl compiler (needs irt.h, and the\n\/\/ unsandboxed LLVM build using the trusted compiler does not have irt.h).\n#if PNACL_BROWSER_TRANSLATOR\n\n#include \n#include \n#include \n#include \n\n#include \"llvm\/Support\/QueueStreamer.h\"\n\n#include \"IceBrowserCompileServer.h\"\n\nnamespace Ice {\n\n\/\/ Create C wrappers around callback handlers for the IRT interface.\nnamespace {\n\nBrowserCompileServer *gCompileServer;\nstruct nacl_irt_private_pnacl_translator_compile gIRTFuncs;\n\nvoid getIRTInterfaces() {\n size_t QueryResult =\n nacl_interface_query(NACL_IRT_PRIVATE_PNACL_TRANSLATOR_COMPILE_v0_1,\n &gIRTFuncs, sizeof(gIRTFuncs));\n if (QueryResult != sizeof(gIRTFuncs))\n llvm::report_fatal_error(\"Failed to get translator compile IRT interface\");\n}\n\nchar *onInitCallback(uint32_t NumThreads, int *ObjFileFDs,\n size_t ObjFileFDCount, char **argv, size_t argc) {\n if (ObjFileFDCount < 1) {\n std::string Buffer;\n llvm::raw_string_ostream StrBuf(Buffer);\n StrBuf << \"Invalid number of FDs for onInitCallback \" << ObjFileFDCount\n << \"\\n\";\n return strdup(StrBuf.str().c_str());\n }\n int ObjFileFD = ObjFileFDs[0];\n if (ObjFileFD < 0) {\n std::string Buffer;\n llvm::raw_string_ostream StrBuf(Buffer);\n StrBuf << \"Invalid FD given for onInitCallback \" << ObjFileFD << \"\\n\";\n return strdup(StrBuf.str().c_str());\n }\n \/\/ NOTE: argv is owned by the caller, but we parse here before returning.\n gCompileServer->getParsedFlags(NumThreads, argc, argv);\n gCompileServer->startCompileThread(ObjFileFD);\n return nullptr;\n}\n\nint onDataCallback(const void *Data, size_t NumBytes) {\n return gCompileServer->pushInputBytes(Data, NumBytes) ? 1 : 0;\n}\n\nchar *onEndCallback() {\n gCompileServer->endInputStream();\n gCompileServer->waitForCompileThread();\n \/\/ TODO(jvoung): Also return an error string, and UMA data.\n \/\/ Set up a report_fatal_error handler to grab that string.\n if (gCompileServer->getErrorCode().value()) {\n return strdup(\"Some error occurred\");\n }\n return nullptr;\n}\n\nstruct nacl_irt_pnacl_compile_funcs SubzeroCallbacks {\n &onInitCallback, &onDataCallback, &onEndCallback\n};\n\nstd::unique_ptr getOutputStream(int FD) {\n if (FD <= 0)\n llvm::report_fatal_error(\"Invalid output FD\");\n const bool CloseOnDtor = true;\n const bool Unbuffered = false;\n return std::unique_ptr(\n new llvm::raw_fd_ostream(FD, CloseOnDtor, Unbuffered));\n}\n\n} \/\/ end of anonymous namespace\n\nBrowserCompileServer::~BrowserCompileServer() {}\n\nvoid BrowserCompileServer::run() {\n gCompileServer = this;\n \/\/ TODO(jvoung): make a useful fatal error handler that can\n \/\/ exit all *worker* threads, keep the server thread alive,\n \/\/ and be able to handle a server request for the last error string.\n getIRTInterfaces();\n gIRTFuncs.serve_translate_request(&SubzeroCallbacks);\n}\n\nvoid BrowserCompileServer::getParsedFlags(uint32_t NumThreads, int argc,\n char **argv) {\n ClFlags::parseFlags(argc, argv);\n ClFlags::getParsedClFlags(Flags);\n ClFlags::getParsedClFlagsExtra(ExtraFlags);\n \/\/ Set some defaults which aren't specified via the argv string.\n Flags.setNumTranslationThreads(NumThreads);\n Flags.setUseSandboxing(true);\n Flags.setOutFileType(FT_Elf);\n \/\/ TODO(jvoung): allow setting different target arches.\n Flags.setTargetArch(Target_X8632);\n ExtraFlags.setBuildOnRead(true);\n ExtraFlags.setInputFileFormat(llvm::PNaClFormat);\n}\n\nbool BrowserCompileServer::pushInputBytes(const void *Data, size_t NumBytes) {\n return InputStream->PutBytes(\n const_cast(\n reinterpret_cast(Data)),\n NumBytes) != NumBytes;\n}\n\nvoid BrowserCompileServer::endInputStream() { InputStream->SetDone(); }\n\nvoid BrowserCompileServer::startCompileThread(int ObjFD) {\n InputStream = new llvm::QueueStreamer();\n LogStream = getOutputStream(STDOUT_FILENO);\n LogStream->SetUnbuffered();\n EmitStream = getOutputStream(ObjFD);\n EmitStream->SetBufferSize(1 << 14);\n ELFStream.reset(new ELFStreamer(*EmitStream.get()));\n Ctx.reset(new GlobalContext(LogStream.get(), EmitStream.get(),\n ELFStream.get(), Flags));\n CompileThread = std::thread([this]() {\n Ctx->initParserThread();\n this->getCompiler().run(ExtraFlags, *Ctx.get(),\n \/\/ Retain original reference, but the compiler\n \/\/ (LLVM's MemoryObject) wants to handle deletion.\n std::unique_ptr(InputStream));\n });\n}\n\n} \/\/ end of namespace Ice\n\n#endif \/\/ PNACL_BROWSER_TRANSLATOR\nAdd argv[0] before parsing commandline flags.\/\/===- subzero\/src\/IceBrowserCompileServer.cpp - Browser compile server ---===\/\/\n\/\/\n\/\/ The Subzero Code Generator\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the browser-based compile server.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ Can only compile this with the NaCl compiler (needs irt.h, and the\n\/\/ unsandboxed LLVM build using the trusted compiler does not have irt.h).\n#if PNACL_BROWSER_TRANSLATOR\n\n#include \n#include \n#include \n#include \n\n#include \"llvm\/Support\/QueueStreamer.h\"\n\n#include \"IceBrowserCompileServer.h\"\n\nnamespace Ice {\n\n\/\/ Create C wrappers around callback handlers for the IRT interface.\nnamespace {\n\nBrowserCompileServer *gCompileServer;\nstruct nacl_irt_private_pnacl_translator_compile gIRTFuncs;\n\nvoid getIRTInterfaces() {\n size_t QueryResult =\n nacl_interface_query(NACL_IRT_PRIVATE_PNACL_TRANSLATOR_COMPILE_v0_1,\n &gIRTFuncs, sizeof(gIRTFuncs));\n if (QueryResult != sizeof(gIRTFuncs))\n llvm::report_fatal_error(\"Failed to get translator compile IRT interface\");\n}\n\nchar *onInitCallback(uint32_t NumThreads, int *ObjFileFDs,\n size_t ObjFileFDCount, char **CLArgs, size_t CLArgsLen) {\n if (ObjFileFDCount < 1) {\n std::string Buffer;\n llvm::raw_string_ostream StrBuf(Buffer);\n StrBuf << \"Invalid number of FDs for onInitCallback \" << ObjFileFDCount\n << \"\\n\";\n return strdup(StrBuf.str().c_str());\n }\n int ObjFileFD = ObjFileFDs[0];\n if (ObjFileFD < 0) {\n std::string Buffer;\n llvm::raw_string_ostream StrBuf(Buffer);\n StrBuf << \"Invalid FD given for onInitCallback \" << ObjFileFD << \"\\n\";\n return strdup(StrBuf.str().c_str());\n }\n \/\/ CLArgs is almost an \"argv\", but is missing the argv[0] program name.\n std::vector Argv;\n char ProgramName[] = \"pnacl-sz.nexe\";\n Argv.reserve(CLArgsLen + 1);\n Argv.push_back(ProgramName);\n for (size_t i = 0; i < CLArgsLen; ++i) {\n Argv.push_back(CLArgs[i]);\n }\n \/\/ NOTE: strings pointed to by argv are owned by the caller, but we parse\n \/\/ here before returning and don't store them.\n gCompileServer->getParsedFlags(NumThreads, Argv.size(), Argv.data());\n gCompileServer->startCompileThread(ObjFileFD);\n return nullptr;\n}\n\nint onDataCallback(const void *Data, size_t NumBytes) {\n return gCompileServer->pushInputBytes(Data, NumBytes) ? 1 : 0;\n}\n\nchar *onEndCallback() {\n gCompileServer->endInputStream();\n gCompileServer->waitForCompileThread();\n \/\/ TODO(jvoung): Also return an error string, and UMA data.\n \/\/ Set up a report_fatal_error handler to grab that string.\n if (gCompileServer->getErrorCode().value()) {\n return strdup(\"Some error occurred\");\n }\n return nullptr;\n}\n\nstruct nacl_irt_pnacl_compile_funcs SubzeroCallbacks {\n &onInitCallback, &onDataCallback, &onEndCallback\n};\n\nstd::unique_ptr getOutputStream(int FD) {\n if (FD <= 0)\n llvm::report_fatal_error(\"Invalid output FD\");\n const bool CloseOnDtor = true;\n const bool Unbuffered = false;\n return std::unique_ptr(\n new llvm::raw_fd_ostream(FD, CloseOnDtor, Unbuffered));\n}\n\n} \/\/ end of anonymous namespace\n\nBrowserCompileServer::~BrowserCompileServer() {}\n\nvoid BrowserCompileServer::run() {\n gCompileServer = this;\n \/\/ TODO(jvoung): make a useful fatal error handler that can\n \/\/ exit all *worker* threads, keep the server thread alive,\n \/\/ and be able to handle a server request for the last error string.\n getIRTInterfaces();\n gIRTFuncs.serve_translate_request(&SubzeroCallbacks);\n}\n\nvoid BrowserCompileServer::getParsedFlags(uint32_t NumThreads, int argc,\n char **argv) {\n ClFlags::parseFlags(argc, argv);\n ClFlags::getParsedClFlags(Flags);\n ClFlags::getParsedClFlagsExtra(ExtraFlags);\n \/\/ Set some defaults which aren't specified via the argv string.\n Flags.setNumTranslationThreads(NumThreads);\n Flags.setUseSandboxing(true);\n Flags.setOutFileType(FT_Elf);\n \/\/ TODO(jvoung): allow setting different target arches.\n Flags.setTargetArch(Target_X8632);\n ExtraFlags.setBuildOnRead(true);\n ExtraFlags.setInputFileFormat(llvm::PNaClFormat);\n}\n\nbool BrowserCompileServer::pushInputBytes(const void *Data, size_t NumBytes) {\n return InputStream->PutBytes(\n const_cast(\n reinterpret_cast(Data)),\n NumBytes) != NumBytes;\n}\n\nvoid BrowserCompileServer::endInputStream() { InputStream->SetDone(); }\n\nvoid BrowserCompileServer::startCompileThread(int ObjFD) {\n InputStream = new llvm::QueueStreamer();\n LogStream = getOutputStream(STDOUT_FILENO);\n LogStream->SetUnbuffered();\n EmitStream = getOutputStream(ObjFD);\n EmitStream->SetBufferSize(1 << 14);\n ELFStream.reset(new ELFStreamer(*EmitStream.get()));\n Ctx.reset(new GlobalContext(LogStream.get(), EmitStream.get(),\n ELFStream.get(), Flags));\n CompileThread = std::thread([this]() {\n Ctx->initParserThread();\n this->getCompiler().run(ExtraFlags, *Ctx.get(),\n \/\/ Retain original reference, but the compiler\n \/\/ (LLVM's MemoryObject) wants to handle deletion.\n std::unique_ptr(InputStream));\n });\n}\n\n} \/\/ end of namespace Ice\n\n#endif \/\/ PNACL_BROWSER_TRANSLATOR\n<|endoftext|>"} {"text":"\/*\n This file is part of KOrganizer.\n Copyright (c) 2001 Cornelius Schumacher \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n\/\/ $Id$\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"koprefs.h\"\n\nKOPrefs *KOPrefs::mInstance = 0;\nstatic KStaticDeleter insd;\n\nKOPrefs::KOPrefs() :\n KPrefs(\"korganizerrc\")\n{\n mCategoryColors.setAutoDelete(true);\n\n mDefaultCategoryColor = QColor(196,196,196);\n QColor defaultHolidayColor = QColor(\"red\");\n QColor defaultHighlightColor = QColor(\"blue\");\n QColor defaultAgendaBgColor = QColor(128,128,128);\n QColor defaultWorkingHoursColor = QColor(160,160,160);\n\n mDefaultTimeBarFont = QFont(\"helvetica\",12,QFont::Bold);\n mDefaultViewFont = QFont(\"helvetica\",12);\n\n KPrefs::setCurrentGroup(\"General\");\n\n addItemBool(\"Enable Group Scheduling\",&mEnableGroupScheduling,false);\n addItemBool(\"Enable Project View\",&mEnableProjectView,false);\n addItemBool(\"Auto Save\",&mAutoSave,false);\n addItemInt(\"Auto Save Interval\",&mAutoSaveInterval,10);\n addItemBool(\"Confirm Deletes\",&mConfirm,true);\n addItemString(\"Archive File\",&mArchiveFile);\n addItemString(\"Html Export File\",&mHtmlExportFile,\n QDir::homeDirPath() + \"\/\" + i18n(\"Default export file\", \"calendar.html\"));\n\n KPrefs::setCurrentGroup(\"Personal Settings\");\n\n addItemInt(\"Mail Client\",&mMailClient,MailClientKMail);\n addItemBool(\"Use Control Center Email\",&mEmailControlCenter,false);\n addItemBool(\"Bcc\",&mBcc,false);\n\n KPrefs::setCurrentGroup(\"Time & Date\");\n\n addItemString(\"Time Zone\",&mTimeZone,\"+0000\");\n addItemString(\"TimeZoneId\",&mTimeZoneId);\n addItemInt(\"Default Start Time\",&mStartTime,10);\n addItemInt(\"Default Duration\",&mDefaultDuration,2);\n addItemInt(\"Default Alarm Time\",&mAlarmTime,0);\n addItemInt(\"Daylight Savings\",&mDaylightSavings,0);\n\n KPrefs::setCurrentGroup(\"Calendar\");\n\n addItemInt(\"Default Calendar Format\",&mDefaultFormat,FormatICalendar);\n\n KPrefs::setCurrentGroup(\"Fonts\");\n\n addItemFont(\"TimeBar Font\",&mTimeBarFont);\n addItemFont(\"MonthView Font\",&mMonthViewFont);\n addItemFont(\"AgendaView Font\",&mAgendaViewFont);\n addItemFont(\"MarcusBains Font\",&mAgendaViewFont);\n\n KPrefs::setCurrentGroup(\"Colors\");\n\n addItemColor(\"Holiday Color\",&mHolidayColor,defaultHolidayColor);\n addItemColor(\"Highlight Color\",&mHighlightColor,defaultHighlightColor);\n addItemColor(\"Event Color\",&mEventColor,mDefaultCategoryColor);\n addItemColor(\"Agenda Background Color\",&mAgendaBgColor,defaultAgendaBgColor);\n addItemColor(\"WorkingHours Color\",&mWorkingHoursColor,defaultWorkingHoursColor);\n\n KPrefs::setCurrentGroup(\"Views\");\n\n addItemInt(\"Hour Size\",&mHourSize,10);\n addItemBool(\"Show Daily Recurrences\",&mDailyRecur,true);\n addItemBool(\"Show Weekly Recurrences\",&mWeeklyRecur,true);\n addItemBool(\"Enable ToolTips\",&mEnableToolTips,false);\n addItemBool(\"Enable MonthView ScrollBars\",&mEnableMonthScroll,false);\n addItemBool(\"Marcus Bains shows seconds\",&mMarcusBainsShowSeconds,false);\n addItemBool(\"Show Marcus Bains\",&mMarcusBainsEnabled,true);\n\n addItemInt(\"Day Begins\",&mDayBegins,7);\n addItemInt(\"Working Hours Start\",&mWorkingHoursStart,8);\n addItemInt(\"Working Hours End\",&mWorkingHoursEnd,17);\n addItemBool(\"Exclude Holidays\",&mExcludeHolidays,true);\n addItemBool(\"Exclude Saturdays\",&mExcludeSaturdays,true);\n\n addItemBool(\"Full View Month\",&mFullViewMonth,false);\n addItemBool(\"Full View Todo\",&mFullViewTodo,true);\n\n KPrefs::setCurrentGroup(\"Printer\");\n\n KPrefs::setCurrentGroup(\"Layout\");\n\n addItemBool(\"CompactDialogs\",&mCompactDialogs,false);\n addItemBool(\"VerticalScreen\",&mVerticalScreen,false);\n\n addItemString(\"Preview\",&mPrintPreview,\"kghostview\");\n \n KPrefs::setCurrentGroup(\"KOrganizer Plugins\");\n \n addItemStringList(\"SelectedPlugins\",&mSelectedPlugins,\"holidays\");\n\n KPrefs::setCurrentGroup(\"Group Scheduling\");\n\n addItemInt(\"IMIPScheduler\",&mIMIPScheduler,IMIPKMail);\n addItemInt(\"IMIPSend\",&mIMIPSend,IMIPOutbox);\n addItemStringList(\"AdditionalMails\",&mAdditionalMails,\"\");\n}\n\n\nKOPrefs::~KOPrefs()\n{\n kdDebug() << \"KOPrefs::~KOPrefs()\" << endl;\n if (mInstance == this)\n mInstance = insd.setObject(0);\n}\n\n\nKOPrefs *KOPrefs::instance()\n{\n if (!mInstance) {\n mInstance = insd.setObject(new KOPrefs());\n mInstance->readConfig();\n }\n\n return mInstance;\n}\n\nvoid KOPrefs::usrSetDefaults()\n{\n \/\/ Default should be set a bit smarter, respecting username and locale\n \/\/ settings for example.\n\n KEMailSettings settings;\n mName = settings.getSetting(KEMailSettings::RealName);\n mEmail = settings.getSetting(KEMailSettings::RealName);\n fillMailDefaults();\n\n mHoliday = KGlobal::locale()->country();\n\n mTimeZone = \"+0000\";\n\n mTimeBarFont = mDefaultTimeBarFont;\n mMonthViewFont = mDefaultViewFont;\n mAgendaViewFont = mDefaultViewFont;\n mMarcusBainsFont = mDefaultViewFont;\n\n setCategoryDefaults();\n \n setTimeZoneIdDefault();\n}\n\nvoid KOPrefs::fillMailDefaults()\n{\n if (mName.isEmpty()) mName = i18n(\"Anonymous\");\n if (mEmail.isEmpty()) mEmail = i18n(\"nobody@nowhere\");\n}\n\nvoid KOPrefs::setTimeZoneIdDefault()\n{\n QString zone;\n\n char zonefilebuf[100];\n int len = readlink(\"\/etc\/localtime\",zonefilebuf,100);\n if (len > 0 && len < 100) {\n zonefilebuf[len] = '\\0';\n zone = zonefilebuf;\n zone = zone.mid(zone.find(\"zoneinfo\/\") + 9);\n } else {\n tzset();\n zone = tzname[0];\n }\n \n kdDebug () << \"----- time zone: \" << zone << endl;\n\n mTimeZoneId = zone;\n}\n\nvoid KOPrefs::setCategoryDefaults()\n{\n mCustomCategories.clear();\n\n mCustomCategories << i18n(\"Appointment\") << i18n(\"Business\")\n << i18n(\"Meeting\") << i18n(\"Phone Call\") << i18n(\"Education\")\n << i18n(\"Holiday\") << i18n(\"Vacation\") << i18n(\"Special Occasion\")\n << i18n(\"Personal\") << i18n(\"Travel\") << i18n(\"Miscellaneous\")\n << i18n(\"Birthday\");\n\n QStringList::Iterator it;\n for (it = mCustomCategories.begin();it != mCustomCategories.end();++it ) {\n setCategoryColor(*it,mDefaultCategoryColor);\n }\n}\n\n\nvoid KOPrefs::usrReadConfig()\n{\n config()->setGroup(\"General\");\n mCustomCategories = config()->readListEntry(\"Custom Categories\");\n if (mCustomCategories.isEmpty()) setCategoryDefaults();\n\n config()->setGroup(\"Personal Settings\");\n mName = config()->readEntry(\"user_name\",\"\");\n mEmail = config()->readEntry(\"user_email\",\"\");\n fillMailDefaults();\n mHoliday = config()->readEntry(\"Holidays\", KGlobal::locale()->country());\n\n config()->setGroup(\"Category Colors\");\n QStringList::Iterator it;\n for (it = mCustomCategories.begin();it != mCustomCategories.end();++it ) {\n setCategoryColor(*it,config()->readColorEntry(*it,&mDefaultCategoryColor));\n }\n \n if (mTimeZoneId.isEmpty()) {\n setTimeZoneIdDefault();\n }\n}\n\n\nvoid KOPrefs::usrWriteConfig()\n{\n config()->setGroup(\"General\");\n config()->writeEntry(\"Custom Categories\",mCustomCategories);\n\n config()->setGroup(\"Personal Settings\");\n config()->writeEntry(\"user_name\",mName);\n config()->writeEntry(\"user_email\",mEmail);\n config()->writeEntry(\"Holidays\",mHoliday);\n\n config()->setGroup(\"Category Colors\");\n QDictIterator it(mCategoryColors);\n while (it.current()) {\n config()->writeEntry(it.currentKey(),*(it.current()));\n ++it;\n }\n}\n\nvoid KOPrefs::setCategoryColor(QString cat,const QColor & color)\n{\n mCategoryColors.replace(cat,new QColor(color));\n}\n\nQColor *KOPrefs::categoryColor(QString cat)\n{\n QColor *color = 0;\n\n if (!cat.isEmpty()) color = mCategoryColors[cat];\n\n if (color) return color;\n else return &mDefaultCategoryColor;\n}\n\nvoid KOPrefs::setFullName(const QString &name)\n{\n mName = name;\n}\n\nvoid KOPrefs::setEmail(const QString &email)\n{\n mEmail = email;\n}\n\nQString KOPrefs::fullName()\n{\n if (mEmailControlCenter) {\n KEMailSettings settings;\n return settings.getSetting(KEMailSettings::RealName);\n } else {\n return mName;\n }\n}\n\nQString KOPrefs::email()\n{\n if (mEmailControlCenter) {\n KEMailSettings settings;\n return settings.getSetting(KEMailSettings::EmailAddress);\n } else {\n return mEmail;\n }\n}\nFix saving of preferences.\/*\n This file is part of KOrganizer.\n Copyright (c) 2001 Cornelius Schumacher \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n\/\/ $Id$\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"koprefs.h\"\n\nKOPrefs *KOPrefs::mInstance = 0;\nstatic KStaticDeleter insd;\n\nKOPrefs::KOPrefs() :\n KPrefs(\"\")\n{\n mCategoryColors.setAutoDelete(true);\n\n mDefaultCategoryColor = QColor(196,196,196);\n QColor defaultHolidayColor = QColor(\"red\");\n QColor defaultHighlightColor = QColor(\"blue\");\n QColor defaultAgendaBgColor = QColor(128,128,128);\n QColor defaultWorkingHoursColor = QColor(160,160,160);\n\n mDefaultTimeBarFont = QFont(\"helvetica\",12,QFont::Bold);\n mDefaultViewFont = QFont(\"helvetica\",12);\n\n KPrefs::setCurrentGroup(\"General\");\n\n addItemBool(\"Enable Group Scheduling\",&mEnableGroupScheduling,false);\n addItemBool(\"Enable Project View\",&mEnableProjectView,false);\n addItemBool(\"Auto Save\",&mAutoSave,false);\n addItemInt(\"Auto Save Interval\",&mAutoSaveInterval,10);\n addItemBool(\"Confirm Deletes\",&mConfirm,true);\n addItemString(\"Archive File\",&mArchiveFile);\n addItemString(\"Html Export File\",&mHtmlExportFile,\n QDir::homeDirPath() + \"\/\" + i18n(\"Default export file\", \"calendar.html\"));\n\n KPrefs::setCurrentGroup(\"Personal Settings\");\n\n addItemInt(\"Mail Client\",&mMailClient,MailClientKMail);\n addItemBool(\"Use Control Center Email\",&mEmailControlCenter,false);\n addItemBool(\"Bcc\",&mBcc,false);\n\n KPrefs::setCurrentGroup(\"Time & Date\");\n\n addItemString(\"Time Zone\",&mTimeZone,\"+0000\");\n addItemString(\"TimeZoneId\",&mTimeZoneId);\n addItemInt(\"Default Start Time\",&mStartTime,10);\n addItemInt(\"Default Duration\",&mDefaultDuration,2);\n addItemInt(\"Default Alarm Time\",&mAlarmTime,0);\n addItemInt(\"Daylight Savings\",&mDaylightSavings,0);\n\n KPrefs::setCurrentGroup(\"Calendar\");\n\n addItemInt(\"Default Calendar Format\",&mDefaultFormat,FormatICalendar);\n\n KPrefs::setCurrentGroup(\"Fonts\");\n\n addItemFont(\"TimeBar Font\",&mTimeBarFont);\n addItemFont(\"MonthView Font\",&mMonthViewFont);\n addItemFont(\"AgendaView Font\",&mAgendaViewFont);\n addItemFont(\"MarcusBains Font\",&mAgendaViewFont);\n\n KPrefs::setCurrentGroup(\"Colors\");\n\n addItemColor(\"Holiday Color\",&mHolidayColor,defaultHolidayColor);\n addItemColor(\"Highlight Color\",&mHighlightColor,defaultHighlightColor);\n addItemColor(\"Event Color\",&mEventColor,mDefaultCategoryColor);\n addItemColor(\"Agenda Background Color\",&mAgendaBgColor,defaultAgendaBgColor);\n addItemColor(\"WorkingHours Color\",&mWorkingHoursColor,defaultWorkingHoursColor);\n\n KPrefs::setCurrentGroup(\"Views\");\n\n addItemInt(\"Hour Size\",&mHourSize,10);\n addItemBool(\"Show Daily Recurrences\",&mDailyRecur,true);\n addItemBool(\"Show Weekly Recurrences\",&mWeeklyRecur,true);\n addItemBool(\"Enable ToolTips\",&mEnableToolTips,false);\n addItemBool(\"Enable MonthView ScrollBars\",&mEnableMonthScroll,false);\n addItemBool(\"Marcus Bains shows seconds\",&mMarcusBainsShowSeconds,false);\n addItemBool(\"Show Marcus Bains\",&mMarcusBainsEnabled,true);\n\n addItemInt(\"Day Begins\",&mDayBegins,7);\n addItemInt(\"Working Hours Start\",&mWorkingHoursStart,8);\n addItemInt(\"Working Hours End\",&mWorkingHoursEnd,17);\n addItemBool(\"Exclude Holidays\",&mExcludeHolidays,true);\n addItemBool(\"Exclude Saturdays\",&mExcludeSaturdays,true);\n\n addItemBool(\"Full View Month\",&mFullViewMonth,false);\n addItemBool(\"Full View Todo\",&mFullViewTodo,true);\n\n KPrefs::setCurrentGroup(\"Printer\");\n\n KPrefs::setCurrentGroup(\"Layout\");\n\n addItemBool(\"CompactDialogs\",&mCompactDialogs,false);\n addItemBool(\"VerticalScreen\",&mVerticalScreen,false);\n\n addItemString(\"Preview\",&mPrintPreview,\"kghostview\");\n \n KPrefs::setCurrentGroup(\"KOrganizer Plugins\");\n \n addItemStringList(\"SelectedPlugins\",&mSelectedPlugins,\"holidays\");\n\n KPrefs::setCurrentGroup(\"Group Scheduling\");\n\n addItemInt(\"IMIPScheduler\",&mIMIPScheduler,IMIPKMail);\n addItemInt(\"IMIPSend\",&mIMIPSend,IMIPOutbox);\n addItemStringList(\"AdditionalMails\",&mAdditionalMails,\"\");\n}\n\n\nKOPrefs::~KOPrefs()\n{\n kdDebug() << \"KOPrefs::~KOPrefs()\" << endl;\n if (mInstance == this)\n mInstance = insd.setObject(0);\n}\n\n\nKOPrefs *KOPrefs::instance()\n{\n if (!mInstance) {\n mInstance = insd.setObject(new KOPrefs());\n mInstance->readConfig();\n }\n\n return mInstance;\n}\n\nvoid KOPrefs::usrSetDefaults()\n{\n \/\/ Default should be set a bit smarter, respecting username and locale\n \/\/ settings for example.\n\n KEMailSettings settings;\n mName = settings.getSetting(KEMailSettings::RealName);\n mEmail = settings.getSetting(KEMailSettings::RealName);\n fillMailDefaults();\n\n mHoliday = KGlobal::locale()->country();\n\n mTimeZone = \"+0000\";\n\n mTimeBarFont = mDefaultTimeBarFont;\n mMonthViewFont = mDefaultViewFont;\n mAgendaViewFont = mDefaultViewFont;\n mMarcusBainsFont = mDefaultViewFont;\n\n setCategoryDefaults();\n \n setTimeZoneIdDefault();\n}\n\nvoid KOPrefs::fillMailDefaults()\n{\n if (mName.isEmpty()) mName = i18n(\"Anonymous\");\n if (mEmail.isEmpty()) mEmail = i18n(\"nobody@nowhere\");\n}\n\nvoid KOPrefs::setTimeZoneIdDefault()\n{\n QString zone;\n\n char zonefilebuf[100];\n int len = readlink(\"\/etc\/localtime\",zonefilebuf,100);\n if (len > 0 && len < 100) {\n zonefilebuf[len] = '\\0';\n zone = zonefilebuf;\n zone = zone.mid(zone.find(\"zoneinfo\/\") + 9);\n } else {\n tzset();\n zone = tzname[0];\n }\n \n kdDebug () << \"----- time zone: \" << zone << endl;\n\n mTimeZoneId = zone;\n}\n\nvoid KOPrefs::setCategoryDefaults()\n{\n mCustomCategories.clear();\n\n mCustomCategories << i18n(\"Appointment\") << i18n(\"Business\")\n << i18n(\"Meeting\") << i18n(\"Phone Call\") << i18n(\"Education\")\n << i18n(\"Holiday\") << i18n(\"Vacation\") << i18n(\"Special Occasion\")\n << i18n(\"Personal\") << i18n(\"Travel\") << i18n(\"Miscellaneous\")\n << i18n(\"Birthday\");\n\n QStringList::Iterator it;\n for (it = mCustomCategories.begin();it != mCustomCategories.end();++it ) {\n setCategoryColor(*it,mDefaultCategoryColor);\n }\n}\n\n\nvoid KOPrefs::usrReadConfig()\n{\n config()->setGroup(\"General\");\n mCustomCategories = config()->readListEntry(\"Custom Categories\");\n if (mCustomCategories.isEmpty()) setCategoryDefaults();\n\n config()->setGroup(\"Personal Settings\");\n mName = config()->readEntry(\"user_name\",\"\");\n mEmail = config()->readEntry(\"user_email\",\"\");\n fillMailDefaults();\n mHoliday = config()->readEntry(\"Holidays\", KGlobal::locale()->country());\n\n config()->setGroup(\"Category Colors\");\n QStringList::Iterator it;\n for (it = mCustomCategories.begin();it != mCustomCategories.end();++it ) {\n setCategoryColor(*it,config()->readColorEntry(*it,&mDefaultCategoryColor));\n }\n \n if (mTimeZoneId.isEmpty()) {\n setTimeZoneIdDefault();\n }\n}\n\n\nvoid KOPrefs::usrWriteConfig()\n{\n config()->setGroup(\"General\");\n config()->writeEntry(\"Custom Categories\",mCustomCategories);\n\n config()->setGroup(\"Personal Settings\");\n config()->writeEntry(\"user_name\",mName);\n config()->writeEntry(\"user_email\",mEmail);\n config()->writeEntry(\"Holidays\",mHoliday);\n\n config()->setGroup(\"Category Colors\");\n QDictIterator it(mCategoryColors);\n while (it.current()) {\n config()->writeEntry(it.currentKey(),*(it.current()));\n ++it;\n }\n}\n\nvoid KOPrefs::setCategoryColor(QString cat,const QColor & color)\n{\n mCategoryColors.replace(cat,new QColor(color));\n}\n\nQColor *KOPrefs::categoryColor(QString cat)\n{\n QColor *color = 0;\n\n if (!cat.isEmpty()) color = mCategoryColors[cat];\n\n if (color) return color;\n else return &mDefaultCategoryColor;\n}\n\nvoid KOPrefs::setFullName(const QString &name)\n{\n mName = name;\n}\n\nvoid KOPrefs::setEmail(const QString &email)\n{\n mEmail = email;\n}\n\nQString KOPrefs::fullName()\n{\n if (mEmailControlCenter) {\n KEMailSettings settings;\n return settings.getSetting(KEMailSettings::RealName);\n } else {\n return mName;\n }\n}\n\nQString KOPrefs::email()\n{\n if (mEmailControlCenter) {\n KEMailSettings settings;\n return settings.getSetting(KEMailSettings::EmailAddress);\n } else {\n return mEmail;\n }\n}\n<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/usr\/hwpf\/hwp\/occ\/occ_procedures\/p8_pm_occ_firinit.C $ *\/\n\/* *\/\n\/* IBM CONFIDENTIAL *\/\n\/* *\/\n\/* COPYRIGHT International Business Machines Corp. 2013 *\/\n\/* *\/\n\/* p1 *\/\n\/* *\/\n\/* Object Code Only (OCO) source materials *\/\n\/* Licensed Internal Code Source Materials *\/\n\/* IBM HostBoot Licensed Internal Code *\/\n\/* *\/\n\/* The source code for this program is not published or otherwise *\/\n\/* divested of its trade secrets, irrespective of what has been *\/\n\/* deposited with the U.S. Copyright Office. *\/\n\/* *\/\n\/* Origin: 30 *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/ $Id: p8_pm_occ_firinit.C,v 1.12 2013\/04\/12 01:17:23 stillgs Exp $\n\/\/ $Source: \/afs\/awd\/projects\/eclipz\/KnowledgeBase\/.cvsroot\/eclipz\/chips\/p8\/working\/procedures\/ipl\/fapi\/p8_pm_occ_firinit.C,v $\n\/\/------------------------------------------------------------------------------\n\/\/ *! (C) Copyright International Business Machines Corp. 2011\n\/\/ *! All Rights Reserved -- Property of IBM\n\/\/ *! *** IBM Confidential ***\n\/\/------------------------------------------------------------------------------\n\/\/ *! OWNER NAME: Jim Yacynych Email: jimyac@us.ibm.com\n\/\/ *!\n\/\/\/ \\file p8_pm_occ_firinit.C\n\/\/\/ \\brief Configures the OCC LFIR Mask and Action\n\n\/\/\/ \\todo\n\/\/\/\n\/\/\/ Procedure Prereq:\n\/\/\/ o System clocks are running\n\/\/\/ \\endverbatim\n\/\/------------------------------------------------------------------------------\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Includes\n\/\/ ----------------------------------------------------------------------\n#include \n#include \"p8_scom_addresses.H\"\n#include \"p8_pm_occ_firinit.H\"\n\nextern \"C\" {\n\nusing namespace fapi;\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Constant definitions\n\/\/ ----------------------------------------------------------------------\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Macro definitions\n\/\/ ----------------------------------------------------------------------\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Global variables\n\/\/ ----------------------------------------------------------------------\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Function prototypes\n\/\/ ----------------------------------------------------------------------\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Function definitions\n\/\/ ----------------------------------------------------------------------\n\n\/\/\/ \\param[in] i_target => Chip Target\n\n\/\/\/ \\retval FAPI_RC_SUCCESS\n\/\/\/ \\retval ERROR\nfapi::ReturnCode\np8_pm_occ_firinit(const fapi::Target& i_target , uint32_t mode)\n{\n fapi::ReturnCode rc;\n ecmdDataBufferBase fir(64);\n ecmdDataBufferBase action_0(64);\n ecmdDataBufferBase action_1(64);\n ecmdDataBufferBase mask(64);\n uint32_t e_rc = 0;\n\n FAPI_DBG(\"Executing p8_pm_occ_firinit ....\");\n \n do\n {\n if (mode == PM_RESET)\n {\n\n e_rc = mask.flushTo0();\n e_rc |= mask.setBit(0,OCC_FIR_REGISTER_LENGTH);\n if (e_rc)\n {\n rc.setEcmdError(e_rc);\n break;\n }\n\n \/\/ ------------\n \/\/ OCC_FIR_MASK\n \/\/ ------------\n rc = fapiPutScom(i_target, OCC_LFIR_MASK_0x01010803, mask );\n if (!rc.ok())\n {\n\t FAPI_ERR(\"fapiPutScom(OCC_LFIR_MASK_0x01010803) failed.\");\n\t break;\n }\n }\n else\n {\n \n \/\/ Clear the FIR\n e_rc |= fir.flushTo0();\n \n \/\/ make action default be RECOV_ATTN - \"01\"\n e_rc |= action_0.flushTo0();\n e_rc |= action_1.flushTo1();\n\n \/\/ make mask default be unmasked - \"0\"\n e_rc |= mask.flushTo0() ;\n if (e_rc)\n {\n rc.setEcmdError(e_rc);\n break;\n }\n\n \/\/ ------------------------------------------------------------------------\n \/\/ set the action and mask for the OCC LFIR bits using the following macros\n \/\/ ------------------------------------------------------------------------\n \/\/ Action0\/1 Setting Macros - 4 possible settings\n \/\/ SET_CHECK_STOP(b) - sets action0\/1 to \"00\" for LFIR bit b\n \/\/ SET_RECOV_ATTN(b) - sets action0\/1 to \"01\" for LFIR bit b\n \/\/ SET_RECOV_INTR(b) - sets action0\/1 to \"10\" for LFIR bit b\n \/\/ SET_MALF_ALERT(b) - sets action0\/1 to \"11\" for LFIR bit b\n \/\/\n \/\/ Mask Setting Macro\n \/\/ SET_FIR_MASKED(b) - sets mask to '1' for LFIR bit b\n \/\/ ------------------------------------------------------------------------\n\n SET_MALF_ALERT(0); \/\/ 0 = occ_fw0\n SET_MALF_ALERT(1); \/\/ 1 = occ_fw1\n SET_MALF_ALERT(2); \/\/ 2 = occ_fw2\n SET_MALF_ALERT(3); \/\/ 3 = occ_fw3\n SET_MALF_ALERT(4); \/\/ 4 = pmc_pore_sw_malf\n SET_MALF_ALERT(5); \/\/ 5 = pmc_occ_hb_malf\n\n SET_FIR_MASKED(6); \/\/ 6 = pore_gpe0_fatal_err\n SET_FIR_MASKED(7); \/\/ 7 = pore_gpe1_fatal_err\n SET_FIR_MASKED(8); \/\/ 8 = ocb_error\n\n SET_RECOV_ATTN(9); \/\/ 9 = srt_ue\n SET_RECOV_ATTN(10); \/\/ 10 = srt_ce\n SET_RECOV_ATTN(11); \/\/ 11 = srt_read_error\n SET_RECOV_ATTN(12); \/\/ 12 = srt_write_error\n SET_RECOV_ATTN(13); \/\/ 13 = srt_dataout_perr\n SET_RECOV_ATTN(14); \/\/ 14 = srt_oci_write_data_parity\n SET_RECOV_ATTN(15); \/\/ 15 = srt_oci_be_parity_err\n SET_RECOV_ATTN(16); \/\/ 16 = srt_oci_addr_parity_err\n\n SET_FIR_MASKED(17); \/\/ 17 = pore_sw_error_err\n SET_FIR_MASKED(18); \/\/ 18 = pore_gpe0_error_err\n SET_FIR_MASKED(19); \/\/ 19 = pore_gpe1_error_err\n SET_FIR_MASKED(20); \/\/ 20 = external_trap\n SET_FIR_MASKED(21); \/\/ 21 = ppc405_core_reset\n SET_FIR_MASKED(22); \/\/ 22 = ppc405_chip_reset\n SET_FIR_MASKED(23); \/\/ 23 = ppc405_system_reset\n SET_FIR_MASKED(24); \/\/ 24 = ppc405_dbgmsrwe\n SET_FIR_MASKED(25); \/\/ 25 = ppc405_dbgstopack\n\n SET_RECOV_ATTN(26); \/\/ 26 = ocb_db_oci_timeout\n SET_RECOV_ATTN(27); \/\/ 27 = ocb_db_oci_read_data_parity\n SET_RECOV_ATTN(28); \/\/ 28 = ocb_db_oci_slave_error\n SET_RECOV_ATTN(29); \/\/ 29 = ocb_pib_addr_parity_err\n SET_RECOV_ATTN(30); \/\/ 30 = ocb_db_pib_data_parity_err\n SET_RECOV_ATTN(31); \/\/ 31 = ocb_idc0_error\n SET_RECOV_ATTN(32); \/\/ 32 = ocb_idc1_error\n SET_RECOV_ATTN(33); \/\/ 33 = ocb_idc2_error\n SET_RECOV_ATTN(34); \/\/ 34 = ocb_idc3_error\n SET_RECOV_ATTN(35); \/\/ 35 = srt_fsm_err\n SET_RECOV_ATTN(36); \/\/ 36 = jtagacc_err\n\n SET_FIR_MASKED(37); \/\/ 37 = spare_err_37\n\n SET_RECOV_ATTN(38); \/\/ 38 = c405_ecc_ue\n SET_RECOV_ATTN(39); \/\/ 39 = c405_ecc_ce\n\n SET_FIR_MASKED(40); \/\/ 40 = c405_oci_machinecheck\n\n SET_RECOV_ATTN(41); \/\/ 41 = sram_spare_direct_error0\n SET_RECOV_ATTN(42); \/\/ 42 = sram_spare_direct_error1\n SET_RECOV_ATTN(43); \/\/ 43 = sram_spare_direct_error2\n SET_RECOV_ATTN(44); \/\/ 44 = sram_spare_direct_error3\n SET_RECOV_ATTN(45); \/\/ 45 = slw_ocislv_err\n SET_RECOV_ATTN(46); \/\/ 46 = gpe_ocislv_err\n SET_RECOV_ATTN(47); \/\/ 47 = ocb_ocislv_err\n SET_RECOV_ATTN(48); \/\/ 48 = c405icu_m_timeout\n SET_RECOV_ATTN(49); \/\/ 49 = c405dcu_m_timeout\n\n SET_FIR_MASKED(50); \/\/ 50 = spare_fir\n SET_FIR_MASKED(51); \/\/ 51 = spare_fir\n SET_FIR_MASKED(52); \/\/ 52 = spare_fir\n SET_FIR_MASKED(53); \/\/ 53 = spare_fir\n SET_FIR_MASKED(54); \/\/ 54 = spare_fir\n SET_FIR_MASKED(55); \/\/ 55 = spare_fir\n SET_FIR_MASKED(56); \/\/ 56 = spare_fir\n SET_FIR_MASKED(57); \/\/ 57 = spare_fir\n SET_FIR_MASKED(58); \/\/ 58 = spare_fir\n SET_FIR_MASKED(59); \/\/ 59 = spare_fir\n SET_FIR_MASKED(60); \/\/ 60 = spare_fir\n SET_FIR_MASKED(61); \/\/ 61 = spare_fir\n\n SET_RECOV_ATTN(62); \/\/ 62 = fir_parity_err_dup\n SET_RECOV_ATTN(63); \/\/ 63 = fir_parity_err\n\n if (e_rc)\n {\n rc.setEcmdError(e_rc);\n break;\n }\n \n \/\/ ---------------\n \/\/ OCC_FIR - cleared\n \/\/ ---------------\n rc = fapiPutScom(i_target, OCC_LFIR_0x01010800, fir);\n if (!rc.ok())\n {\n FAPI_ERR(\"fapiPutScom(OCC_LFIR_0x01010800) failed.\");\n break;\n }\n \n\n FAPI_DBG(\" action_0 => 0x%16llx \", action_0.getDoubleWord(0));\n FAPI_DBG(\" action_1 => 0x%16llx \", action_1.getDoubleWord(0));\n FAPI_DBG(\" mask => 0x%16llx \", mask.getDoubleWord(0));\n\n \/\/ ---------------\n \/\/ OCC_FIR_ACTION0\n \/\/ ---------------\n rc = fapiPutScom(i_target, OCC_LFIR_ACT0_0x01010806, action_0 );\n if (!rc.ok())\n {\n FAPI_ERR(\"fapiPutScom(OCC_LFIR_ACT0_0x01010806) failed.\");\n break;\n }\n\n \/\/ ----------------\n \/\/ OCC_FIR_ACTION1\n \/\/ ----------------\n rc = fapiPutScom(i_target, OCC_LFIR_ACT1_0x01010807, action_1 );\n if (!rc.ok())\n {\n FAPI_ERR(\"fapiPutScom(OCC_LFIR_ACT1_0x01010807) failed.\");\n break;\n }\n\n \/\/ ------------\n \/\/ OCC_FIR_MASK\n \/\/ ------------\n rc = fapiPutScom(i_target, OCC_LFIR_MASK_0x01010803, mask );\n if (!rc.ok())\n {\n FAPI_ERR(\"fapiPutScom(OCC_LFIR_MASK_0x01010803) failed.\");\n break;\n }\n }\n } while(0);\n return rc ;\n} \/\/ end p8_pm_occ_firinit\n\n} \/\/end extern C\nOCC FIR updates (SW218900)\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/usr\/hwpf\/hwp\/occ\/occ_procedures\/p8_pm_occ_firinit.C $ *\/\n\/* *\/\n\/* IBM CONFIDENTIAL *\/\n\/* *\/\n\/* COPYRIGHT International Business Machines Corp. 2013 *\/\n\/* *\/\n\/* p1 *\/\n\/* *\/\n\/* Object Code Only (OCO) source materials *\/\n\/* Licensed Internal Code Source Materials *\/\n\/* IBM HostBoot Licensed Internal Code *\/\n\/* *\/\n\/* The source code for this program is not published or otherwise *\/\n\/* divested of its trade secrets, irrespective of what has been *\/\n\/* deposited with the U.S. Copyright Office. *\/\n\/* *\/\n\/* Origin: 30 *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/ $Id: p8_pm_occ_firinit.C,v 1.13 2013\/08\/06 18:07:35 jimyac Exp $\n\/\/ $Source: \/afs\/awd\/projects\/eclipz\/KnowledgeBase\/.cvsroot\/eclipz\/chips\/p8\/working\/procedures\/ipl\/fapi\/p8_pm_occ_firinit.C,v $\n\/\/------------------------------------------------------------------------------\n\/\/ *! (C) Copyright International Business Machines Corp. 2011\n\/\/ *! All Rights Reserved -- Property of IBM\n\/\/ *! *** IBM Confidential ***\n\/\/------------------------------------------------------------------------------\n\/\/ *! OWNER NAME: Jim Yacynych Email: jimyac@us.ibm.com\n\/\/ *!\n\/\/\/ \\file p8_pm_occ_firinit.C\n\/\/\/ \\brief Configures the OCC LFIR Mask and Action\n\n\/\/\/ \\todo\n\/\/\/\n\/\/\/ Procedure Prereq:\n\/\/\/ o System clocks are running\n\/\/\/ \\endverbatim\n\/\/------------------------------------------------------------------------------\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Includes\n\/\/ ----------------------------------------------------------------------\n#include \n#include \"p8_scom_addresses.H\"\n#include \"p8_pm_occ_firinit.H\"\n\nextern \"C\" {\n\nusing namespace fapi;\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Constant definitions\n\/\/ ----------------------------------------------------------------------\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Macro definitions\n\/\/ ----------------------------------------------------------------------\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Global variables\n\/\/ ----------------------------------------------------------------------\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Function prototypes\n\/\/ ----------------------------------------------------------------------\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Function definitions\n\/\/ ----------------------------------------------------------------------\n\n\/\/\/ \\param[in] i_target => Chip Target\n\n\/\/\/ \\retval FAPI_RC_SUCCESS\n\/\/\/ \\retval ERROR\nfapi::ReturnCode\np8_pm_occ_firinit(const fapi::Target& i_target , uint32_t mode)\n{\n fapi::ReturnCode rc;\n ecmdDataBufferBase fir(64);\n ecmdDataBufferBase action_0(64);\n ecmdDataBufferBase action_1(64);\n ecmdDataBufferBase mask(64);\n uint32_t e_rc = 0;\n\n FAPI_DBG(\"Executing p8_pm_occ_firinit ....\");\n \n do\n {\n if (mode == PM_RESET)\n {\n\n e_rc = mask.flushTo0();\n e_rc |= mask.setBit(0,OCC_FIR_REGISTER_LENGTH);\n if (e_rc)\n {\n rc.setEcmdError(e_rc);\n break;\n }\n\n \/\/ ------------\n \/\/ OCC_FIR_MASK\n \/\/ ------------\n rc = fapiPutScom(i_target, OCC_LFIR_MASK_0x01010803, mask );\n if (!rc.ok())\n {\n\t FAPI_ERR(\"fapiPutScom(OCC_LFIR_MASK_0x01010803) failed.\");\n\t break;\n }\n }\n else\n {\n \n \/\/ Clear the FIR\n e_rc |= fir.flushTo0();\n \n \/\/ make action default be RECOV_ATTN - \"01\"\n e_rc |= action_0.flushTo0();\n e_rc |= action_1.flushTo1();\n\n \/\/ make mask default be unmasked - \"0\"\n e_rc |= mask.flushTo0() ;\n if (e_rc)\n {\n rc.setEcmdError(e_rc);\n break;\n }\n\n \/\/ ------------------------------------------------------------------------\n \/\/ set the action and mask for the OCC LFIR bits using the following macros\n \/\/ ------------------------------------------------------------------------\n \/\/ Action0\/1 Setting Macros - 4 possible settings\n \/\/ SET_CHECK_STOP(b) - sets action0\/1 to \"00\" for LFIR bit b\n \/\/ SET_RECOV_ATTN(b) - sets action0\/1 to \"01\" for LFIR bit b\n \/\/ SET_RECOV_INTR(b) - sets action0\/1 to \"10\" for LFIR bit b\n \/\/ SET_MALF_ALERT(b) - sets action0\/1 to \"11\" for LFIR bit b\n \/\/\n \/\/ Mask Setting Macro\n \/\/ SET_FIR_MASKED(b) - sets mask to '1' for LFIR bit b\n \/\/ ------------------------------------------------------------------------\n\n SET_MALF_ALERT(0); SET_FIR_MASKED(0); \/\/ 0 = occ_fw0\n SET_MALF_ALERT(1); SET_FIR_MASKED(1); \/\/ 1 = occ_fw1\n SET_MALF_ALERT(2); SET_FIR_MASKED(2); \/\/ 2 = occ_fw2\n SET_MALF_ALERT(3); SET_FIR_MASKED(3); \/\/ 3 = occ_fw3\n SET_MALF_ALERT(4); SET_FIR_MASKED(4); \/\/ 4 = pmc_pore_sw_malf\n SET_MALF_ALERT(5); SET_FIR_MASKED(5); \/\/ 5 = pmc_occ_hb_malf\n\n SET_RECOV_ATTN(6); SET_FIR_MASKED(6); \/\/ 6 = pore_gpe0_fatal_err\n SET_RECOV_ATTN(7); SET_FIR_MASKED(7); \/\/ 7 = pore_gpe1_fatal_err\n SET_RECOV_ATTN(8); SET_FIR_MASKED(8); \/\/ 8 = ocb_error\n SET_RECOV_ATTN(9); \/\/ 9 = srt_ue\n SET_RECOV_ATTN(10); SET_FIR_MASKED(10); \/\/ 10 = srt_ce\n SET_RECOV_ATTN(11); \/\/ 11 = srt_read_error\n SET_RECOV_ATTN(12); \/\/ 12 = srt_write_error\n SET_RECOV_ATTN(13); \/\/ 13 = srt_dataout_perr\n SET_RECOV_ATTN(14); \/\/ 14 = srt_oci_write_data_parity\n SET_RECOV_ATTN(15); \/\/ 15 = srt_oci_be_parity_err\n SET_RECOV_ATTN(16); \/\/ 16 = srt_oci_addr_parity_err\n SET_RECOV_ATTN(17); SET_FIR_MASKED(17); \/\/ 17 = pore_sw_error_err \n SET_RECOV_ATTN(18); SET_FIR_MASKED(18); \/\/ 18 = pore_gpe0_error_err \n SET_RECOV_ATTN(19); SET_FIR_MASKED(19); \/\/ 19 = pore_gpe1_error_err \n SET_RECOV_ATTN(20); SET_FIR_MASKED(20); \/\/ 20 = external_trap \n SET_RECOV_ATTN(21); SET_FIR_MASKED(21); \/\/ 21 = ppc405_core_reset \n SET_RECOV_ATTN(22); SET_FIR_MASKED(22); \/\/ 22 = ppc405_chip_reset \n SET_RECOV_ATTN(23); SET_FIR_MASKED(23); \/\/ 23 = ppc405_system_reset \n SET_RECOV_ATTN(24); SET_FIR_MASKED(24); \/\/ 24 = ppc405_dbgmsrwe \n SET_RECOV_ATTN(25); SET_FIR_MASKED(25); \/\/ 25 = ppc405_dbgstopack \n SET_RECOV_ATTN(26); \/\/ 26 = ocb_db_oci_timeout\n SET_RECOV_ATTN(27); \/\/ 27 = ocb_db_oci_read_data_parity\n SET_RECOV_ATTN(28); \/\/ 28 = ocb_db_oci_slave_error\n SET_RECOV_ATTN(29); \/\/ 29 = ocb_pib_addr_parity_err\n SET_RECOV_ATTN(30); \/\/ 30 = ocb_db_pib_data_parity_err\n SET_RECOV_ATTN(31); \/\/ 31 = ocb_idc0_error\n SET_RECOV_ATTN(32); \/\/ 32 = ocb_idc1_error\n SET_RECOV_ATTN(33); \/\/ 33 = ocb_idc2_error\n SET_RECOV_ATTN(34); \/\/ 34 = ocb_idc3_error\n SET_RECOV_ATTN(35); \/\/ 35 = srt_fsm_err\n SET_RECOV_ATTN(36); SET_FIR_MASKED(36); \/\/ 36 = jtagacc_err\n SET_RECOV_ATTN(37); SET_FIR_MASKED(37); \/\/ 37 = spare_err_37\n SET_RECOV_ATTN(38); \/\/ 38 = c405_ecc_ue\n SET_RECOV_ATTN(39); SET_FIR_MASKED(39); \/\/ 39 = c405_ecc_ce\n SET_RECOV_ATTN(40); SET_FIR_MASKED(40); \/\/ 40 = c405_oci_machinecheck\n SET_RECOV_ATTN(41); \/\/ 41 = sram_spare_direct_error0\n SET_RECOV_ATTN(42); \/\/ 42 = sram_spare_direct_error1\n SET_RECOV_ATTN(43); \/\/ 43 = sram_spare_direct_error2\n SET_RECOV_ATTN(44); \/\/ 44 = sram_spare_direct_error3\n SET_RECOV_ATTN(45); \/\/ 45 = slw_ocislv_err\n SET_RECOV_ATTN(46); \/\/ 46 = gpe_ocislv_err\n SET_RECOV_ATTN(47); \/\/ 47 = ocb_ocislv_err\n SET_RECOV_ATTN(48); \/\/ 48 = c405icu_m_timeout\n SET_RECOV_ATTN(49); \/\/ 49 = c405dcu_m_timeout\n SET_RECOV_ATTN(50); SET_FIR_MASKED(50); \/\/ 50 = spare_fir \n SET_RECOV_ATTN(51); SET_FIR_MASKED(51); \/\/ 51 = spare_fir \n SET_RECOV_ATTN(52); SET_FIR_MASKED(52); \/\/ 52 = spare_fir \n SET_RECOV_ATTN(53); SET_FIR_MASKED(53); \/\/ 53 = spare_fir \n SET_RECOV_ATTN(54); SET_FIR_MASKED(54); \/\/ 54 = spare_fir \n SET_RECOV_ATTN(55); SET_FIR_MASKED(55); \/\/ 55 = spare_fir \n SET_RECOV_ATTN(56); SET_FIR_MASKED(56); \/\/ 56 = spare_fir \n SET_RECOV_ATTN(57); SET_FIR_MASKED(57); \/\/ 57 = spare_fir \n SET_RECOV_ATTN(58); SET_FIR_MASKED(58); \/\/ 58 = spare_fir \n SET_RECOV_ATTN(59); SET_FIR_MASKED(59); \/\/ 59 = spare_fir \n SET_RECOV_ATTN(60); SET_FIR_MASKED(60); \/\/ 60 = spare_fir \n SET_RECOV_ATTN(61); SET_FIR_MASKED(61); \/\/ 61 = spare_fir \n SET_RECOV_ATTN(62); \/\/ 62 = fir_parity_err_dup\n SET_RECOV_ATTN(63); \/\/ 63 = fir_parity_err\n\n if (e_rc)\n {\n rc.setEcmdError(e_rc);\n break;\n }\n \n \/\/ ---------------\n \/\/ OCC_FIR - cleared\n \/\/ ---------------\n rc = fapiPutScom(i_target, OCC_LFIR_0x01010800, fir);\n if (!rc.ok())\n {\n FAPI_ERR(\"fapiPutScom(OCC_LFIR_0x01010800) failed.\");\n break;\n }\n \n\n FAPI_DBG(\" action_0 => 0x%16llx \", action_0.getDoubleWord(0));\n FAPI_DBG(\" action_1 => 0x%16llx \", action_1.getDoubleWord(0));\n FAPI_DBG(\" mask => 0x%16llx \", mask.getDoubleWord(0));\n\n \/\/ ---------------\n \/\/ OCC_FIR_ACTION0\n \/\/ ---------------\n rc = fapiPutScom(i_target, OCC_LFIR_ACT0_0x01010806, action_0 );\n if (!rc.ok())\n {\n FAPI_ERR(\"fapiPutScom(OCC_LFIR_ACT0_0x01010806) failed.\");\n break;\n }\n\n \/\/ ----------------\n \/\/ OCC_FIR_ACTION1\n \/\/ ----------------\n rc = fapiPutScom(i_target, OCC_LFIR_ACT1_0x01010807, action_1 );\n if (!rc.ok())\n {\n FAPI_ERR(\"fapiPutScom(OCC_LFIR_ACT1_0x01010807) failed.\");\n break;\n }\n\n \/\/ ------------\n \/\/ OCC_FIR_MASK\n \/\/ ------------\n rc = fapiPutScom(i_target, OCC_LFIR_MASK_0x01010803, mask );\n if (!rc.ok())\n {\n FAPI_ERR(\"fapiPutScom(OCC_LFIR_MASK_0x01010803) failed.\");\n break;\n }\n }\n } while(0);\n return rc ;\n} \/\/ end p8_pm_occ_firinit\n\n} \/\/end extern C\n<|endoftext|>"} {"text":"\/\/ ----------------------------------------------------------------------------\n\/\/ Constants.cpp\n\/\/\n\/\/\n\/\/ Authors:\n\/\/ Peter Polidoro peterpolidoro@gmail.com\n\/\/ ----------------------------------------------------------------------------\n#include \"Constants.h\"\n\nnamespace modular_server\n{\nnamespace constants\n{\nCONSTANT_STRING(firmware_name,\"ModularServer\");\n\/\/ Use semantic versioning http:\/\/semver.org\/\nconst FirmwareInfo firmware_info =\n{\n .name_ptr=&firmware_name,\n .version_major=5,\n .version_minor=0,\n .version_patch=3,\n};\n\nconst long response_pipe_read_max = 100000;\n\nconst double epsilon = 0.000000001;\n\n\/\/ Pins\nconst size_t pin_pulse_timer_number = 3;\nconst uint32_t pin_pulse_delay = 0;\nconst uint32_t pin_pulse_count = 1;\nCONSTANT_STRING(pin_mode_digital_input,\"DIGITAL_INPUT\");\nCONSTANT_STRING(pin_mode_digital_input_pullup,\"DIGITAL_INPUT_PULLUP\");\nCONSTANT_STRING(pin_mode_digital_output,\"DIGITAL_OUTPUT\");\nCONSTANT_STRING(pin_mode_analog_input,\"ANALOG_INPUT\");\nCONSTANT_STRING(pin_mode_analog_output,\"ANALOG_OUTPUT\");\nCONSTANT_STRING(pin_mode_pulse_rising,\"PULSE_RISING\");\nCONSTANT_STRING(pin_mode_pulse_falling,\"PULSE_FALLING\");\nCONSTANT_STRING(pin_mode_interrupt_low,\"INTERRUPT_LOW\");\nCONSTANT_STRING(pin_mode_interrupt_change,\"INTERRUPT_CHANGE\");\nCONSTANT_STRING(pin_mode_interrupt_rising,\"INTERRUPT_RISING\");\nCONSTANT_STRING(pin_mode_interrupt_falling,\"INTERRUPT_FALLING\");\n\n\/\/ Properties\nCONSTANT_STRING(serial_number_property_name,\"serialNumber\");\nconst long serial_number_min = 0;\nconst long serial_number_max = 65535;\nconst long serial_number_default = serial_number_min;\n\n\/\/ Parameters\nCONSTANT_STRING(verbosity_names,\"NAMES\");\nCONSTANT_STRING(verbosity_general,\"GENERAL\");\nCONSTANT_STRING(verbosity_detailed,\"DETAILED\");\nSubsetMemberType verbosity_ptr_subset[VERBOSITY_SUBSET_LENGTH] =\n{\n {.cs_ptr=&verbosity_names},\n {.cs_ptr=&verbosity_general},\n {.cs_ptr=&verbosity_detailed},\n};\n\nCONSTANT_STRING(pin_name_parameter_name,\"pin_name\");\n\nSubsetMemberType pin_mode_ptr_subset[PIN_MODE_SUBSET_LENGTH] =\n{\n {.cs_ptr=&pin_mode_digital_input},\n {.cs_ptr=&pin_mode_digital_input_pullup},\n {.cs_ptr=&pin_mode_digital_output},\n {.cs_ptr=&pin_mode_analog_input},\n {.cs_ptr=&pin_mode_analog_output},\n {.cs_ptr=&pin_mode_pulse_rising},\n {.cs_ptr=&pin_mode_pulse_falling},\n};\n\nCONSTANT_STRING(pin_value_parameter_name,\"pin_value\");\nconst long pin_value_min = 0;\nconst long pin_value_max = 255;\n\n\/\/ Functions\nCONSTANT_STRING(get_method_ids_function_name,\"getMethodIds\");\nCONSTANT_STRING(help_function_name,\"?\");\nCONSTANT_STRING(verbose_help_function_name,\"??\");\nCONSTANT_STRING(get_device_id_function_name,\"getDeviceId\");\nCONSTANT_STRING(get_device_info_function_name,\"getDeviceInfo\");\nCONSTANT_STRING(get_api_function_name,\"getApi\");\nCONSTANT_STRING(get_property_default_values_function_name,\"getPropertyDefaultValues\");\nCONSTANT_STRING(set_properties_to_defaults_function_name,\"setPropertiesToDefaults\");\nCONSTANT_STRING(get_property_values_function_name,\"getPropertyValues\");\nCONSTANT_STRING(get_pin_info_function_name,\"getPinInfo\");\nCONSTANT_STRING(set_pin_mode_function_name,\"setPinMode\");\nCONSTANT_STRING(get_pin_value_function_name,\"getPinValue\");\nCONSTANT_STRING(set_pin_value_function_name,\"setPinValue\");\nCONSTANT_STRING(get_memory_free_function_name,\"getMemoryFree\");\n\n\/\/ Callbacks\n\n\/\/ Errors\nCONSTANT_STRING(parse_error_message,\"Parse error\");\nCONSTANT_STRING(invalid_request_error_message,\"Invalid Request\");\nCONSTANT_STRING(method_not_found_error_message,\"Method not found\");\nCONSTANT_STRING(invalid_params_error_message,\"Invalid params\");\nCONSTANT_STRING(server_error_error_message,\"Server error\");\n\nCONSTANT_STRING(object_request_error_data,\"JSON object requests not supported. Must use compact JSON array format for requests.\");\nCONSTANT_STRING(request_length_error_data,\"Request length too long.\");\nCONSTANT_STRING(parameter_not_found_error_data,\"Parameter not found\");\nCONSTANT_STRING(property_not_found_error_data,\"Property not found\");\nCONSTANT_STRING(property_not_array_type_error_data,\"Property not array type\");\nCONSTANT_STRING(property_element_index_out_of_bounds_error_data,\"property_element_index out of bounds\");\nCONSTANT_STRING(cannot_set_element_in_string_property_with_subset_error_data,\"Cannot set element in string property with subset.\");\nCONSTANT_STRING(incorrect_parameter_number_error_data,\"Incorrect number of parameters. \")\nCONSTANT_STRING(invalid_json_object_error_data,\" is not a valid JSON object.\")\nCONSTANT_STRING(invalid_json_array_error_data,\" is not a valid JSON array.\")\nCONSTANT_STRING(parameter_error_error_data,\"Parameter value not valid. \");\nCONSTANT_STRING(array_parameter_error_error_data,\"Array parameter element value not valid. \");\nCONSTANT_STRING(array_parameter_length_error_error_data,\"Array parameter length not valid. \");\nCONSTANT_STRING(value_not_in_subset_error_data,\"Value not in subset: \");\nCONSTANT_STRING(value_not_in_range_error_data,\"Value not in range: \");\nCONSTANT_STRING(property_function_not_found_error_data,\"Property function not found\");\nCONSTANT_STRING(incorrect_property_parameter_number_error_data,\"Incorrect number of property parameters. \")\nCONSTANT_STRING(callback_function_not_found_error_data,\"Callback function not found\");\nCONSTANT_STRING(incorrect_callback_parameter_number_error_data,\"Incorrect number of callback parameters. \")\n\nconst int parse_error_code = -32700;\nconst int invalid_request_error_code = -32600;\nconst int method_not_found_error_code = -32601;\nconst int invalid_params_error_code = -32602;\nconst int internal_error_error_code = -32603;\nconst int server_error_error_code = -32000;\n\n\/\/ Saved Variables\nconst size_t eeprom_initialized_default_value = 123;\n\n\/\/ Constant Strings\nCONSTANT_STRING(empty_constant_string,\"\");\nCONSTANT_STRING(id_constant_string,\"id\");\nCONSTANT_STRING(error_constant_string,\"error\");\nCONSTANT_STRING(message_constant_string,\"message\");\nCONSTANT_STRING(data_constant_string,\"data\");\nCONSTANT_STRING(code_constant_string,\"code\");\nCONSTANT_STRING(form_factor_constant_string,\"form_factor\");\nCONSTANT_STRING(serial_number_constant_string,\"serial_number\");\nCONSTANT_STRING(firmware_constant_string,\"firmware\");\nCONSTANT_STRING(hardware_constant_string,\"hardware\");\nCONSTANT_STRING(name_constant_string,\"name\");\nCONSTANT_STRING(type_constant_string,\"type\");\nCONSTANT_STRING(units_constant_string,\"units\");\nCONSTANT_STRING(result_constant_string,\"result\");\nCONSTANT_STRING(result_info_constant_string,\"result_info\");\nCONSTANT_STRING(array_element_type_constant_string,\"array_element_type\");\nCONSTANT_STRING(properties_constant_string,\"properties\");\nCONSTANT_STRING(parameters_constant_string,\"parameters\");\nCONSTANT_STRING(functions_constant_string,\"functions\");\nCONSTANT_STRING(callbacks_constant_string,\"callbacks\");\nCONSTANT_STRING(callback_constant_string,\"callback\");\nCONSTANT_STRING(min_constant_string,\"min\");\nCONSTANT_STRING(max_constant_string,\"max\");\nCONSTANT_STRING(array_element_min_constant_string,\"array_element_min\");\nCONSTANT_STRING(array_element_max_constant_string,\"array_element_max\");\nCONSTANT_STRING(array_length_min_constant_string,\"array_length_min\");\nCONSTANT_STRING(array_length_max_constant_string,\"array_length_max\");\nCONSTANT_STRING(string_length_max_constant_string,\"string_length_max\");\nCONSTANT_STRING(version_constant_string,\"version\");\nCONSTANT_STRING(part_number_constant_string,\"part_number\");\nCONSTANT_STRING(device_id_constant_string,\"device_id\");\nCONSTANT_STRING(device_info_constant_string,\"device_info\");\nCONSTANT_STRING(api_constant_string,\"api\");\nCONSTANT_STRING(verbosity_constant_string,\"verbosity\");\nCONSTANT_STRING(value_constant_string,\"value\");\nCONSTANT_STRING(default_value_constant_string,\"default_value\");\nCONSTANT_STRING(question_constant_string,\"?\");\nCONSTANT_STRING(question_double_constant_string,\"??\");\nCONSTANT_STRING(zero_constant_string,\"0\");\nCONSTANT_STRING(given_constant_string,\" given. \");\nCONSTANT_STRING(needed_constant_string,\" needed.\");\nCONSTANT_STRING(less_than_equal_constant_string,\" <= \");\nCONSTANT_STRING(element_constant_string,\" element\");\nCONSTANT_STRING(array_length_constant_string,\"array_length\");\nCONSTANT_STRING(array_length_default_constant_string,\"array_length_default\");\nCONSTANT_STRING(array_length_spaces_constant_string,\" array length\");\nCONSTANT_STRING(string_length_constant_string,\"string_length\");\nCONSTANT_STRING(array_open_constant_string,\"[\");\nCONSTANT_STRING(array_close_constant_string,\"]\");\nCONSTANT_STRING(array_separator_constant_string,\",\");\nCONSTANT_STRING(version_property_separator_constant_string,\".\");\nCONSTANT_STRING(subset_constant_string,\"subset\");\nCONSTANT_STRING(all_constant_string,\"ALL\");\nCONSTANT_STRING(array_element_subset_constant_string,\"array_element_subset\");\nCONSTANT_STRING(pins_constant_string,\"pins\");\nCONSTANT_STRING(interrupt_number_constant_string,\"interrupt_number\");\nCONSTANT_STRING(pin_number_constant_string,\"pin_number\");\nCONSTANT_STRING(pin_mode_constant_string,\"pin_mode\");\nCONSTANT_STRING(processor_constant_string,\"processor\");\n\n#if defined(__AVR_ATmega1280__)\nCONSTANT_STRING(processor_name_constant_string,\"ATmega1280\");\n#elif defined(__AVR_ATmega2560__)\nCONSTANT_STRING(processor_name_constant_string,\"ATmega2560\");\n#elif defined(__MK20DX128__)\nCONSTANT_STRING(processor_name_constant_string,\"MK20DX128\");\n#elif defined(__MK20DX256__)\nCONSTANT_STRING(processor_name_constant_string,\"MK20DX256\");\n#elif defined(__MK64FX512__)\nCONSTANT_STRING(processor_name_constant_string,\"MK64FX512\");\n#elif defined(__MK66FX1M0__)\nCONSTANT_STRING(processor_name_constant_string,\"MK66FX1M0\");\n#else\nCONSTANT_STRING(processor_name_constant_string,\"\");\n#endif\n\nConstantString * all_c_style_array[ALL_ARRAY_SIZE] =\n{\n &all_constant_string,\n};\nArray all_array(all_c_style_array);\n\n}\n}\nAdd Teensy 4 processor\/\/ ----------------------------------------------------------------------------\n\/\/ Constants.cpp\n\/\/\n\/\/\n\/\/ Authors:\n\/\/ Peter Polidoro peterpolidoro@gmail.com\n\/\/ ----------------------------------------------------------------------------\n#include \"Constants.h\"\n\nnamespace modular_server\n{\nnamespace constants\n{\nCONSTANT_STRING(firmware_name,\"ModularServer\");\n\/\/ Use semantic versioning http:\/\/semver.org\/\nconst FirmwareInfo firmware_info =\n{\n .name_ptr=&firmware_name,\n .version_major=5,\n .version_minor=0,\n .version_patch=3,\n};\n\nconst long response_pipe_read_max = 100000;\n\nconst double epsilon = 0.000000001;\n\n\/\/ Pins\nconst size_t pin_pulse_timer_number = 3;\nconst uint32_t pin_pulse_delay = 0;\nconst uint32_t pin_pulse_count = 1;\nCONSTANT_STRING(pin_mode_digital_input,\"DIGITAL_INPUT\");\nCONSTANT_STRING(pin_mode_digital_input_pullup,\"DIGITAL_INPUT_PULLUP\");\nCONSTANT_STRING(pin_mode_digital_output,\"DIGITAL_OUTPUT\");\nCONSTANT_STRING(pin_mode_analog_input,\"ANALOG_INPUT\");\nCONSTANT_STRING(pin_mode_analog_output,\"ANALOG_OUTPUT\");\nCONSTANT_STRING(pin_mode_pulse_rising,\"PULSE_RISING\");\nCONSTANT_STRING(pin_mode_pulse_falling,\"PULSE_FALLING\");\nCONSTANT_STRING(pin_mode_interrupt_low,\"INTERRUPT_LOW\");\nCONSTANT_STRING(pin_mode_interrupt_change,\"INTERRUPT_CHANGE\");\nCONSTANT_STRING(pin_mode_interrupt_rising,\"INTERRUPT_RISING\");\nCONSTANT_STRING(pin_mode_interrupt_falling,\"INTERRUPT_FALLING\");\n\n\/\/ Properties\nCONSTANT_STRING(serial_number_property_name,\"serialNumber\");\nconst long serial_number_min = 0;\nconst long serial_number_max = 65535;\nconst long serial_number_default = serial_number_min;\n\n\/\/ Parameters\nCONSTANT_STRING(verbosity_names,\"NAMES\");\nCONSTANT_STRING(verbosity_general,\"GENERAL\");\nCONSTANT_STRING(verbosity_detailed,\"DETAILED\");\nSubsetMemberType verbosity_ptr_subset[VERBOSITY_SUBSET_LENGTH] =\n{\n {.cs_ptr=&verbosity_names},\n {.cs_ptr=&verbosity_general},\n {.cs_ptr=&verbosity_detailed},\n};\n\nCONSTANT_STRING(pin_name_parameter_name,\"pin_name\");\n\nSubsetMemberType pin_mode_ptr_subset[PIN_MODE_SUBSET_LENGTH] =\n{\n {.cs_ptr=&pin_mode_digital_input},\n {.cs_ptr=&pin_mode_digital_input_pullup},\n {.cs_ptr=&pin_mode_digital_output},\n {.cs_ptr=&pin_mode_analog_input},\n {.cs_ptr=&pin_mode_analog_output},\n {.cs_ptr=&pin_mode_pulse_rising},\n {.cs_ptr=&pin_mode_pulse_falling},\n};\n\nCONSTANT_STRING(pin_value_parameter_name,\"pin_value\");\nconst long pin_value_min = 0;\nconst long pin_value_max = 255;\n\n\/\/ Functions\nCONSTANT_STRING(get_method_ids_function_name,\"getMethodIds\");\nCONSTANT_STRING(help_function_name,\"?\");\nCONSTANT_STRING(verbose_help_function_name,\"??\");\nCONSTANT_STRING(get_device_id_function_name,\"getDeviceId\");\nCONSTANT_STRING(get_device_info_function_name,\"getDeviceInfo\");\nCONSTANT_STRING(get_api_function_name,\"getApi\");\nCONSTANT_STRING(get_property_default_values_function_name,\"getPropertyDefaultValues\");\nCONSTANT_STRING(set_properties_to_defaults_function_name,\"setPropertiesToDefaults\");\nCONSTANT_STRING(get_property_values_function_name,\"getPropertyValues\");\nCONSTANT_STRING(get_pin_info_function_name,\"getPinInfo\");\nCONSTANT_STRING(set_pin_mode_function_name,\"setPinMode\");\nCONSTANT_STRING(get_pin_value_function_name,\"getPinValue\");\nCONSTANT_STRING(set_pin_value_function_name,\"setPinValue\");\nCONSTANT_STRING(get_memory_free_function_name,\"getMemoryFree\");\n\n\/\/ Callbacks\n\n\/\/ Errors\nCONSTANT_STRING(parse_error_message,\"Parse error\");\nCONSTANT_STRING(invalid_request_error_message,\"Invalid Request\");\nCONSTANT_STRING(method_not_found_error_message,\"Method not found\");\nCONSTANT_STRING(invalid_params_error_message,\"Invalid params\");\nCONSTANT_STRING(server_error_error_message,\"Server error\");\n\nCONSTANT_STRING(object_request_error_data,\"JSON object requests not supported. Must use compact JSON array format for requests.\");\nCONSTANT_STRING(request_length_error_data,\"Request length too long.\");\nCONSTANT_STRING(parameter_not_found_error_data,\"Parameter not found\");\nCONSTANT_STRING(property_not_found_error_data,\"Property not found\");\nCONSTANT_STRING(property_not_array_type_error_data,\"Property not array type\");\nCONSTANT_STRING(property_element_index_out_of_bounds_error_data,\"property_element_index out of bounds\");\nCONSTANT_STRING(cannot_set_element_in_string_property_with_subset_error_data,\"Cannot set element in string property with subset.\");\nCONSTANT_STRING(incorrect_parameter_number_error_data,\"Incorrect number of parameters. \")\nCONSTANT_STRING(invalid_json_object_error_data,\" is not a valid JSON object.\")\nCONSTANT_STRING(invalid_json_array_error_data,\" is not a valid JSON array.\")\nCONSTANT_STRING(parameter_error_error_data,\"Parameter value not valid. \");\nCONSTANT_STRING(array_parameter_error_error_data,\"Array parameter element value not valid. \");\nCONSTANT_STRING(array_parameter_length_error_error_data,\"Array parameter length not valid. \");\nCONSTANT_STRING(value_not_in_subset_error_data,\"Value not in subset: \");\nCONSTANT_STRING(value_not_in_range_error_data,\"Value not in range: \");\nCONSTANT_STRING(property_function_not_found_error_data,\"Property function not found\");\nCONSTANT_STRING(incorrect_property_parameter_number_error_data,\"Incorrect number of property parameters. \")\nCONSTANT_STRING(callback_function_not_found_error_data,\"Callback function not found\");\nCONSTANT_STRING(incorrect_callback_parameter_number_error_data,\"Incorrect number of callback parameters. \")\n\nconst int parse_error_code = -32700;\nconst int invalid_request_error_code = -32600;\nconst int method_not_found_error_code = -32601;\nconst int invalid_params_error_code = -32602;\nconst int internal_error_error_code = -32603;\nconst int server_error_error_code = -32000;\n\n\/\/ Saved Variables\nconst size_t eeprom_initialized_default_value = 123;\n\n\/\/ Constant Strings\nCONSTANT_STRING(empty_constant_string,\"\");\nCONSTANT_STRING(id_constant_string,\"id\");\nCONSTANT_STRING(error_constant_string,\"error\");\nCONSTANT_STRING(message_constant_string,\"message\");\nCONSTANT_STRING(data_constant_string,\"data\");\nCONSTANT_STRING(code_constant_string,\"code\");\nCONSTANT_STRING(form_factor_constant_string,\"form_factor\");\nCONSTANT_STRING(serial_number_constant_string,\"serial_number\");\nCONSTANT_STRING(firmware_constant_string,\"firmware\");\nCONSTANT_STRING(hardware_constant_string,\"hardware\");\nCONSTANT_STRING(name_constant_string,\"name\");\nCONSTANT_STRING(type_constant_string,\"type\");\nCONSTANT_STRING(units_constant_string,\"units\");\nCONSTANT_STRING(result_constant_string,\"result\");\nCONSTANT_STRING(result_info_constant_string,\"result_info\");\nCONSTANT_STRING(array_element_type_constant_string,\"array_element_type\");\nCONSTANT_STRING(properties_constant_string,\"properties\");\nCONSTANT_STRING(parameters_constant_string,\"parameters\");\nCONSTANT_STRING(functions_constant_string,\"functions\");\nCONSTANT_STRING(callbacks_constant_string,\"callbacks\");\nCONSTANT_STRING(callback_constant_string,\"callback\");\nCONSTANT_STRING(min_constant_string,\"min\");\nCONSTANT_STRING(max_constant_string,\"max\");\nCONSTANT_STRING(array_element_min_constant_string,\"array_element_min\");\nCONSTANT_STRING(array_element_max_constant_string,\"array_element_max\");\nCONSTANT_STRING(array_length_min_constant_string,\"array_length_min\");\nCONSTANT_STRING(array_length_max_constant_string,\"array_length_max\");\nCONSTANT_STRING(string_length_max_constant_string,\"string_length_max\");\nCONSTANT_STRING(version_constant_string,\"version\");\nCONSTANT_STRING(part_number_constant_string,\"part_number\");\nCONSTANT_STRING(device_id_constant_string,\"device_id\");\nCONSTANT_STRING(device_info_constant_string,\"device_info\");\nCONSTANT_STRING(api_constant_string,\"api\");\nCONSTANT_STRING(verbosity_constant_string,\"verbosity\");\nCONSTANT_STRING(value_constant_string,\"value\");\nCONSTANT_STRING(default_value_constant_string,\"default_value\");\nCONSTANT_STRING(question_constant_string,\"?\");\nCONSTANT_STRING(question_double_constant_string,\"??\");\nCONSTANT_STRING(zero_constant_string,\"0\");\nCONSTANT_STRING(given_constant_string,\" given. \");\nCONSTANT_STRING(needed_constant_string,\" needed.\");\nCONSTANT_STRING(less_than_equal_constant_string,\" <= \");\nCONSTANT_STRING(element_constant_string,\" element\");\nCONSTANT_STRING(array_length_constant_string,\"array_length\");\nCONSTANT_STRING(array_length_default_constant_string,\"array_length_default\");\nCONSTANT_STRING(array_length_spaces_constant_string,\" array length\");\nCONSTANT_STRING(string_length_constant_string,\"string_length\");\nCONSTANT_STRING(array_open_constant_string,\"[\");\nCONSTANT_STRING(array_close_constant_string,\"]\");\nCONSTANT_STRING(array_separator_constant_string,\",\");\nCONSTANT_STRING(version_property_separator_constant_string,\".\");\nCONSTANT_STRING(subset_constant_string,\"subset\");\nCONSTANT_STRING(all_constant_string,\"ALL\");\nCONSTANT_STRING(array_element_subset_constant_string,\"array_element_subset\");\nCONSTANT_STRING(pins_constant_string,\"pins\");\nCONSTANT_STRING(interrupt_number_constant_string,\"interrupt_number\");\nCONSTANT_STRING(pin_number_constant_string,\"pin_number\");\nCONSTANT_STRING(pin_mode_constant_string,\"pin_mode\");\nCONSTANT_STRING(processor_constant_string,\"processor\");\n\n#if defined(__AVR_ATmega1280__)\nCONSTANT_STRING(processor_name_constant_string,\"ATmega1280\");\n#elif defined(__AVR_ATmega2560__)\nCONSTANT_STRING(processor_name_constant_string,\"ATmega2560\");\n#elif defined(__MK20DX128__)\nCONSTANT_STRING(processor_name_constant_string,\"MK20DX128\");\n#elif defined(__MK20DX256__)\nCONSTANT_STRING(processor_name_constant_string,\"MK20DX256\");\n#elif defined(__MK64FX512__)\nCONSTANT_STRING(processor_name_constant_string,\"MK64FX512\");\n#elif defined(__MK66FX1M0__)\nCONSTANT_STRING(processor_name_constant_string,\"MK66FX1M0\");\n#elif defined(__IMXRT1062__)\nCONSTANT_STRING(processor_name_constant_string,\"IMXRT1062\");\n#else\nCONSTANT_STRING(processor_name_constant_string,\"\");\n#endif\n\nConstantString * all_c_style_array[ALL_ARRAY_SIZE] =\n{\n &all_constant_string,\n};\nArray all_array(all_c_style_array);\n\n}\n}\n<|endoftext|>"} {"text":"\/\/ SwiftShader Software Renderer\n\/\/\n\/\/ Copyright(c) 2005-2013 TransGaming Inc.\n\/\/\n\/\/ All rights reserved. No part of this software may be copied, distributed, transmitted,\n\/\/ transcribed, stored in a retrieval system, translated into any human or computer\n\/\/ language by any means, or disclosed to third parties without the explicit written\n\/\/ agreement of TransGaming Inc. Without such an agreement, no rights or licenses, express\n\/\/ or implied, including but not limited to any patent rights, are granted to you.\n\/\/\n\n\/\/ Buffer.cpp: Implements the Buffer class, representing storage of vertex and\/or\n\/\/ index data. Implements GL buffer objects and related functionality.\n\/\/ [OpenGL ES 2.0.24] section 2.9 page 21.\n\n#include \"Buffer.h\"\n\n#include \"main.h\"\n#include \"VertexDataManager.h\"\n#include \"IndexDataManager.h\"\n\nnamespace es2\n{\n\nBuffer::Buffer(GLuint name) : NamedObject(name)\n{\n mContents = 0;\n mSize = 0;\n mUsage = GL_DYNAMIC_DRAW;\n\tmIsMapped = false;\n\tmOffset = 0;\n\tmLength = 0;\n\tmAccess = 0;\n}\n\nBuffer::~Buffer()\n{\n if(mContents)\n\t{\n\t\tmContents->destruct();\n\t}\n}\n\nvoid Buffer::bufferData(const void *data, GLsizeiptr size, GLenum usage)\n{\n\tif(mContents)\n\t{\n\t\tmContents->destruct();\n\t\tmContents = 0;\n\t}\n\n\tmSize = size;\n\tmUsage = usage;\n\n\tif(size > 0)\n\t{\n\t\tconst int padding = 1024; \/\/ For SIMD processing of vertices\n\t\tmContents = new sw::Resource(size + padding);\n\n\t\tif(!mContents)\n\t\t{\n\t\t\treturn error(GL_OUT_OF_MEMORY);\n\t\t}\n\n\t\tif(data)\n\t\t{\n\t\t\tchar *buffer = (char*)mContents->data();\n\t\t\tmemcpy(buffer + mOffset, data, size);\n\t\t}\n\t}\n}\n\nvoid Buffer::bufferSubData(const void *data, GLsizeiptr size, GLintptr offset)\n{\n\tif(mContents && data)\n\t{\n\t\tchar *buffer = (char*)mContents->lock(sw::PUBLIC);\n\t\tmemcpy(buffer + offset, data, size);\n\t\tmContents->unlock();\n\t}\n}\n\nvoid* Buffer::mapRange(GLintptr offset, GLsizeiptr length, GLbitfield access)\n{\n\tif(mContents)\n\t{\n\t\tchar* buffer = (char*)mContents->lock(sw::PUBLIC);\n\t\tmIsMapped = true;\n\t\tmOffset = offset;\n\t\tmLength = length;\n\t\tmAccess = access;\n\t\treturn buffer + offset;\n\t}\n\treturn nullptr;\n}\n\nbool Buffer::unmap()\n{\n\tif(mContents)\n\t{\n\t\tmContents->unlock();\n\t}\n\tmIsMapped = false;\n\tmOffset = 0;\n\tmLength = 0;\n\tmAccess = 0;\n\treturn true;\n}\n\nsw::Resource *Buffer::getResource()\n{\n\treturn mContents;\n}\n\n}\nChanged default buffer usage type\/\/ SwiftShader Software Renderer\n\/\/\n\/\/ Copyright(c) 2005-2013 TransGaming Inc.\n\/\/\n\/\/ All rights reserved. No part of this software may be copied, distributed, transmitted,\n\/\/ transcribed, stored in a retrieval system, translated into any human or computer\n\/\/ language by any means, or disclosed to third parties without the explicit written\n\/\/ agreement of TransGaming Inc. Without such an agreement, no rights or licenses, express\n\/\/ or implied, including but not limited to any patent rights, are granted to you.\n\/\/\n\n\/\/ Buffer.cpp: Implements the Buffer class, representing storage of vertex and\/or\n\/\/ index data. Implements GL buffer objects and related functionality.\n\/\/ [OpenGL ES 2.0.24] section 2.9 page 21.\n\n#include \"Buffer.h\"\n\n#include \"main.h\"\n#include \"VertexDataManager.h\"\n#include \"IndexDataManager.h\"\n\nnamespace es2\n{\n\nBuffer::Buffer(GLuint name) : NamedObject(name)\n{\n mContents = 0;\n mSize = 0;\n mUsage = GL_STATIC_DRAW;\n\tmIsMapped = false;\n\tmOffset = 0;\n\tmLength = 0;\n\tmAccess = 0;\n}\n\nBuffer::~Buffer()\n{\n if(mContents)\n\t{\n\t\tmContents->destruct();\n\t}\n}\n\nvoid Buffer::bufferData(const void *data, GLsizeiptr size, GLenum usage)\n{\n\tif(mContents)\n\t{\n\t\tmContents->destruct();\n\t\tmContents = 0;\n\t}\n\n\tmSize = size;\n\tmUsage = usage;\n\n\tif(size > 0)\n\t{\n\t\tconst int padding = 1024; \/\/ For SIMD processing of vertices\n\t\tmContents = new sw::Resource(size + padding);\n\n\t\tif(!mContents)\n\t\t{\n\t\t\treturn error(GL_OUT_OF_MEMORY);\n\t\t}\n\n\t\tif(data)\n\t\t{\n\t\t\tchar *buffer = (char*)mContents->data();\n\t\t\tmemcpy(buffer + mOffset, data, size);\n\t\t}\n\t}\n}\n\nvoid Buffer::bufferSubData(const void *data, GLsizeiptr size, GLintptr offset)\n{\n\tif(mContents && data)\n\t{\n\t\tchar *buffer = (char*)mContents->lock(sw::PUBLIC);\n\t\tmemcpy(buffer + offset, data, size);\n\t\tmContents->unlock();\n\t}\n}\n\nvoid* Buffer::mapRange(GLintptr offset, GLsizeiptr length, GLbitfield access)\n{\n\tif(mContents)\n\t{\n\t\tchar* buffer = (char*)mContents->lock(sw::PUBLIC);\n\t\tmIsMapped = true;\n\t\tmOffset = offset;\n\t\tmLength = length;\n\t\tmAccess = access;\n\t\treturn buffer + offset;\n\t}\n\treturn nullptr;\n}\n\nbool Buffer::unmap()\n{\n\tif(mContents)\n\t{\n\t\tmContents->unlock();\n\t}\n\tmIsMapped = false;\n\tmOffset = 0;\n\tmLength = 0;\n\tmAccess = 0;\n\treturn true;\n}\n\nsw::Resource *Buffer::getResource()\n{\n\treturn mContents;\n}\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2020 The Orbit Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"TimeGraphLayout.h\"\n\n#include \n\n#include \"OrbitBase\/ThreadConstants.h\"\n\nTimeGraphLayout::TimeGraphLayout() {\n text_box_height_ = 20.f;\n core_height_ = 10.f;\n thread_state_track_height_ = 4.0f;\n event_track_height_ = 10.f;\n all_threads_event_track_scale_ = 2.f;\n variable_track_height_ = 20.f;\n track_content_bottom_margin_ = 5.f;\n track_content_top_margin_ = 5.f;\n space_between_cores_ = 2.f;\n space_between_gpu_depths_ = 2.f;\n space_between_tracks_ = 10.f;\n space_between_tracks_and_thread_ = 5.f;\n space_between_subtracks_ = -5.f;\n space_between_thread_blocks_ = 35.f;\n track_label_offset_x_ = 30.f;\n slider_width_ = 15.f;\n track_tab_width_ = 350.f;\n track_tab_height_ = 25.f;\n track_tab_offset_ = 0.f;\n track_intent_offset_ = 5.f;\n collapse_button_offset_ = 15.f;\n collapse_button_size_ = 10.f;\n collapse_button_decrease_per_indentation_ = 2.f;\n rounding_radius_ = 8.f;\n rounding_num_sides_ = 16;\n text_offset_ = 5.f;\n right_margin_ = 10.f;\n scheduler_track_offset_ = 10.f;\n toolbar_icon_height_ = 24.f;\n generic_fixed_spacer_width_ = 10.f;\n scale_ = 1.f;\n time_bar_height_ = 15.f;\n font_size_ = 14;\n};\n\n#define FLOAT_SLIDER(x) FLOAT_SLIDER_MIN_MAX(x, 0, 100.f)\n#define FLOAT_SLIDER_MIN_MAX(x, min, max) \\\n if (ImGui::SliderFloat(#x, &x, min, max)) { \\\n needs_redraw = true; \\\n }\n\nbool TimeGraphLayout::DrawProperties() {\n bool needs_redraw = false;\n FLOAT_SLIDER(track_label_offset_x_);\n FLOAT_SLIDER(text_box_height_);\n FLOAT_SLIDER(core_height_);\n FLOAT_SLIDER(thread_state_track_height_);\n FLOAT_SLIDER(event_track_height_);\n FLOAT_SLIDER_MIN_MAX(all_threads_event_track_scale_, 0, 10.f);\n FLOAT_SLIDER(variable_track_height_);\n FLOAT_SLIDER(space_between_cores_);\n FLOAT_SLIDER(space_between_gpu_depths_);\n FLOAT_SLIDER(space_between_tracks_);\n FLOAT_SLIDER(space_between_tracks_and_thread_);\n FLOAT_SLIDER(space_between_subtracks_);\n FLOAT_SLIDER(space_between_thread_blocks_);\n FLOAT_SLIDER(slider_width_);\n FLOAT_SLIDER(time_bar_height_);\n FLOAT_SLIDER(track_tab_height_);\n FLOAT_SLIDER(track_tab_offset_);\n FLOAT_SLIDER(track_intent_offset_);\n FLOAT_SLIDER(collapse_button_size_);\n FLOAT_SLIDER(collapse_button_decrease_per_indentation_);\n\n FLOAT_SLIDER(collapse_button_offset_);\n FLOAT_SLIDER(rounding_radius_);\n FLOAT_SLIDER(rounding_num_sides_);\n FLOAT_SLIDER(text_offset_);\n FLOAT_SLIDER(right_margin_);\n FLOAT_SLIDER(scheduler_track_offset_);\n FLOAT_SLIDER_MIN_MAX(track_tab_width_, 0, 1000.f);\n FLOAT_SLIDER_MIN_MAX(track_content_bottom_margin_, 0, 20.f);\n FLOAT_SLIDER_MIN_MAX(track_content_top_margin_, 0, 20.f);\n FLOAT_SLIDER(toolbar_icon_height_);\n FLOAT_SLIDER(generic_fixed_spacer_width_);\n FLOAT_SLIDER_MIN_MAX(scale_, kMinScale, kMaxScale);\n ImGui::Checkbox(\"Draw Track Background\", &draw_track_background_);\n\n return needs_redraw;\n}\n\nfloat TimeGraphLayout::GetCollapseButtonSize(int indentation_level) const {\n float button_size_without_scaling =\n collapse_button_size_ -\n collapse_button_decrease_per_indentation_ * static_cast(indentation_level);\n\n \/\/ We want the button to scale slower than other elements, so we use sqrt() function.\n return button_size_without_scaling * sqrt(scale_);\n}\n\nfloat TimeGraphLayout::GetBottomMargin() const {\n \/\/ The bottom consists of the slider (where we have to take the width, as it\n \/\/ is rotated), and the time bar.\n return GetSliderWidth() + GetTimeBarHeight();\n}\n\nfloat TimeGraphLayout::GetEventTrackHeightFromTid(uint32_t tid) const {\n float height = GetEventTrackHeight();\n if (tid == orbit_base::kAllProcessThreadsTid) {\n height *= GetAllThreadsEventTrackScale();\n }\n return height;\n}\nChange the space between subtracks\/\/ Copyright (c) 2020 The Orbit Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"TimeGraphLayout.h\"\n\n#include \n\n#include \"OrbitBase\/ThreadConstants.h\"\n\nTimeGraphLayout::TimeGraphLayout() {\n text_box_height_ = 20.f;\n core_height_ = 10.f;\n thread_state_track_height_ = 4.0f;\n event_track_height_ = 10.f;\n all_threads_event_track_scale_ = 2.f;\n variable_track_height_ = 20.f;\n track_content_bottom_margin_ = 5.f;\n track_content_top_margin_ = 5.f;\n space_between_cores_ = 2.f;\n space_between_gpu_depths_ = 2.f;\n space_between_tracks_ = 10.f;\n space_between_tracks_and_thread_ = 5.f;\n space_between_subtracks_ = 0.f;\n space_between_thread_blocks_ = 35.f;\n track_label_offset_x_ = 30.f;\n slider_width_ = 15.f;\n track_tab_width_ = 350.f;\n track_tab_height_ = 25.f;\n track_tab_offset_ = 0.f;\n track_intent_offset_ = 5.f;\n collapse_button_offset_ = 15.f;\n collapse_button_size_ = 10.f;\n collapse_button_decrease_per_indentation_ = 2.f;\n rounding_radius_ = 8.f;\n rounding_num_sides_ = 16;\n text_offset_ = 5.f;\n right_margin_ = 10.f;\n scheduler_track_offset_ = 10.f;\n toolbar_icon_height_ = 24.f;\n generic_fixed_spacer_width_ = 10.f;\n scale_ = 1.f;\n time_bar_height_ = 15.f;\n font_size_ = 14;\n};\n\n#define FLOAT_SLIDER(x) FLOAT_SLIDER_MIN_MAX(x, 0, 100.f)\n#define FLOAT_SLIDER_MIN_MAX(x, min, max) \\\n if (ImGui::SliderFloat(#x, &x, min, max)) { \\\n needs_redraw = true; \\\n }\n\nbool TimeGraphLayout::DrawProperties() {\n bool needs_redraw = false;\n FLOAT_SLIDER(track_label_offset_x_);\n FLOAT_SLIDER(text_box_height_);\n FLOAT_SLIDER(core_height_);\n FLOAT_SLIDER(thread_state_track_height_);\n FLOAT_SLIDER(event_track_height_);\n FLOAT_SLIDER_MIN_MAX(all_threads_event_track_scale_, 0, 10.f);\n FLOAT_SLIDER(variable_track_height_);\n FLOAT_SLIDER(space_between_cores_);\n FLOAT_SLIDER(space_between_gpu_depths_);\n FLOAT_SLIDER(space_between_tracks_);\n FLOAT_SLIDER(space_between_tracks_and_thread_);\n FLOAT_SLIDER(space_between_subtracks_);\n FLOAT_SLIDER(space_between_thread_blocks_);\n FLOAT_SLIDER(slider_width_);\n FLOAT_SLIDER(time_bar_height_);\n FLOAT_SLIDER(track_tab_height_);\n FLOAT_SLIDER(track_tab_offset_);\n FLOAT_SLIDER(track_intent_offset_);\n FLOAT_SLIDER(collapse_button_size_);\n FLOAT_SLIDER(collapse_button_decrease_per_indentation_);\n\n FLOAT_SLIDER(collapse_button_offset_);\n FLOAT_SLIDER(rounding_radius_);\n FLOAT_SLIDER(rounding_num_sides_);\n FLOAT_SLIDER(text_offset_);\n FLOAT_SLIDER(right_margin_);\n FLOAT_SLIDER(scheduler_track_offset_);\n FLOAT_SLIDER_MIN_MAX(track_tab_width_, 0, 1000.f);\n FLOAT_SLIDER_MIN_MAX(track_content_bottom_margin_, 0, 20.f);\n FLOAT_SLIDER_MIN_MAX(track_content_top_margin_, 0, 20.f);\n FLOAT_SLIDER(toolbar_icon_height_);\n FLOAT_SLIDER(generic_fixed_spacer_width_);\n FLOAT_SLIDER_MIN_MAX(scale_, kMinScale, kMaxScale);\n ImGui::Checkbox(\"Draw Track Background\", &draw_track_background_);\n\n return needs_redraw;\n}\n\nfloat TimeGraphLayout::GetCollapseButtonSize(int indentation_level) const {\n float button_size_without_scaling =\n collapse_button_size_ -\n collapse_button_decrease_per_indentation_ * static_cast(indentation_level);\n\n \/\/ We want the button to scale slower than other elements, so we use sqrt() function.\n return button_size_without_scaling * sqrt(scale_);\n}\n\nfloat TimeGraphLayout::GetBottomMargin() const {\n \/\/ The bottom consists of the slider (where we have to take the width, as it\n \/\/ is rotated), and the time bar.\n return GetSliderWidth() + GetTimeBarHeight();\n}\n\nfloat TimeGraphLayout::GetEventTrackHeightFromTid(uint32_t tid) const {\n float height = GetEventTrackHeight();\n if (tid == orbit_base::kAllProcessThreadsTid) {\n height *= GetAllThreadsEventTrackScale();\n }\n return height;\n}\n<|endoftext|>"} {"text":"\/\/ -*- Mode:C++ -*-\n\n\/**************************************************************************************************\/\n\/* *\/\n\/* Copyright (C) 2015 University of Hull *\/\n\/* *\/\n\/**************************************************************************************************\/\n\/* *\/\n\/* module : platform\/application\/base.hpp *\/\n\/* project : *\/\n\/* description: *\/\n\/* *\/\n\/**************************************************************************************************\/\n\n#if !defined(UKACHULLDCS_08961_PLATFORM_APPLICATION_BASE_HPP)\n\n#define UKACHULLDCS_08961_PLATFORM_APPLICATION_BASE_HPP\n\n\/\/ includes, system\n\n#include \/\/ boost::noncopyable\n#include \/\/ std::unique_ptr<>\n\n\/\/ includes, project\n\n#include \n#include \n#include \n\nnamespace platform {\n\n namespace application {\n \n \/\/ types, exported (class, enum, struct, union, typedef)\n \n class DCS08961_PLATFORM_EXPORT base : private boost::noncopyable,\n public support::printable {\n\n public:\n\n virtual signed run() =0;\n virtual void process_command_line();\n \n virtual void print_on(std::ostream&) const;\n \n protected:\n\n command_line command_line_;\n unsigned verbose_level_;\n \n explicit base(command_line const&);\n virtual ~base() =0;\n \n };\n \n template \n class executor : private boost::noncopyable {\n\n public:\n\n explicit executor(command_line const&);\n ~executor();\n \n signed run();\n \n private:\n\n std::unique_ptr instance_;\n \n }; \n \n \/\/ variables, exported (extern)\n\n \/\/ functions, inlined (inline)\n \n \/\/ functions, exported (extern)\n\n template signed execute(command_line const&);\n template signed execute(command_line const&, std::nothrow_t const&) noexcept;\n \n } \/\/ namespace application {\n \n} \/\/ namespace platform {\n\n#include \n\n#endif \/\/ #if !defined(UKACHULLDCS_08961_PLATFORM_APPLICATION_BASE_HPP)\nupdate: MSVC 18.0\/\/ -*- Mode:C++ -*-\n\n\/**************************************************************************************************\/\n\/* *\/\n\/* Copyright (C) 2015 University of Hull *\/\n\/* *\/\n\/**************************************************************************************************\/\n\/* *\/\n\/* module : platform\/application\/base.hpp *\/\n\/* project : *\/\n\/* description: *\/\n\/* *\/\n\/**************************************************************************************************\/\n\n#if !defined(UKACHULLDCS_08961_PLATFORM_APPLICATION_BASE_HPP)\n\n#define UKACHULLDCS_08961_PLATFORM_APPLICATION_BASE_HPP\n\n\/\/ includes, system\n\n#include \/\/ boost::noncopyable\n#include \/\/ std::unique_ptr<>\n\n\/\/ includes, project\n\n#include \n#include \n#include \n\n#if defined(_MSC_VER) && (_MSC_VER < 1900)\n# define noexcept\n#endif\n\nnamespace platform {\n\n namespace application {\n \n \/\/ types, exported (class, enum, struct, union, typedef)\n \n class DCS08961_PLATFORM_EXPORT base : private boost::noncopyable,\n public support::printable {\n\n public:\n\n virtual signed run() =0;\n virtual void process_command_line();\n \n virtual void print_on(std::ostream&) const;\n \n protected:\n\n command_line command_line_;\n unsigned verbose_level_;\n \n explicit base(command_line const&);\n virtual ~base() =0;\n \n };\n \n template \n class executor : private boost::noncopyable {\n\n public:\n\n explicit executor(command_line const&);\n ~executor();\n \n signed run();\n \n private:\n\n std::unique_ptr instance_;\n \n }; \n \n \/\/ variables, exported (extern)\n\n \/\/ functions, inlined (inline)\n \n \/\/ functions, exported (extern)\n\n template signed execute(command_line const&);\n template signed execute(command_line const&, std::nothrow_t const&) noexcept;\n \n } \/\/ namespace application {\n \n} \/\/ namespace platform {\n\n#include \n\n#endif \/\/ #if !defined(UKACHULLDCS_08961_PLATFORM_APPLICATION_BASE_HPP)\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2009, 2010, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\n#ifndef OPTION_PARSER_HXX\n# define OPTION_PARSER_HXX\n\n# include \n\nnamespace libport\n{\n template \n inline\n T OptionValue::get(const boost::optional& def) const\n {\n if (!filled_)\n {\n aver(def);\n return def.get();\n }\n return boost::lexical_cast(value_);\n }\n\n template \n inline\n T OptionValue::get() const\n {\n return get(boost::optional());\n }\n\n inline\n std::ostream&\n operator<<(std::ostream& o, const OptionParser& p)\n {\n p.options_doc(o);\n return o;\n }\n\n}\n\n#endif\nbuild: fix.\/*\n * Copyright (C) 2009, 2010, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\n#ifndef OPTION_PARSER_HXX\n# define OPTION_PARSER_HXX\n\n# include \n# include \n\nnamespace libport\n{\n template \n inline\n T OptionValue::get(const boost::optional& def) const\n {\n if (!filled_)\n {\n aver(def);\n return def.get();\n }\n return boost::lexical_cast(value_);\n }\n\n template \n inline\n T OptionValue::get() const\n {\n return get(boost::optional());\n }\n\n inline\n std::ostream&\n operator<<(std::ostream& o, const OptionParser& p)\n {\n p.options_doc(o);\n return o;\n }\n\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_UDP_SOCKET_HPP_INCLUDED\n#define TORRENT_UDP_SOCKET_HPP_INCLUDED\n\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/io_service.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n#include \"libtorrent\/session_settings.hpp\"\n#include \"libtorrent\/buffer.hpp\"\n#include \"libtorrent\/thread.hpp\"\n#include \"libtorrent\/deadline_timer.hpp\"\n\n#include \n#include \n\nnamespace libtorrent\n{\n\tclass connection_queue;\n\n\tclass udp_socket\n\t{\n\tpublic:\n\t\t\/\/ TODO: instead of these callbacks, support observers\n\t\ttypedef boost::function callback_t;\n\t\ttypedef boost::function callback2_t;\n\t\ttypedef boost::function drain_callback_t;\n\n\t\tudp_socket(io_service& ios, callback_t const& c, callback2_t const& c2\n\t\t\t, drain_callback_t const& dc, connection_queue& cc);\n\t\t~udp_socket();\n\n\t\tenum flags_t { dont_drop = 1, peer_connection = 2 };\n\n\t\tbool is_open() const\n\t\t{\n\t\t\treturn m_ipv4_sock.is_open()\n#if TORRENT_USE_IPV6\n\t\t\t\t|| m_ipv6_sock.is_open()\n#endif\n\t\t\t\t;\n\t\t}\n\t\tio_service& get_io_service() { return m_ipv4_sock.get_io_service(); }\n\n\t\t\/\/ this is only valid when using a socks5 proxy\n\t\tvoid send_hostname(char const* hostname, int port, char const* p, int len, error_code& ec);\n\n\t\tvoid send(udp::endpoint const& ep, char const* p, int len, error_code& ec, int flags = 0);\n\t\tvoid bind(udp::endpoint const& ep, error_code& ec);\n\t\tvoid bind(int port);\n\t\tvoid close();\n\t\tint local_port() const { return m_bind_port; }\n\n\t\tvoid set_proxy_settings(proxy_settings const& ps);\n\t\tproxy_settings const& get_proxy_settings() { return m_proxy_settings; }\n\n\t\tbool is_closed() const { return m_abort; }\n\t\ttcp::endpoint local_endpoint(error_code& ec) const\n\t\t{\n\t\t\tudp::endpoint ep = m_ipv4_sock.local_endpoint(ec);\n\t\t\treturn tcp::endpoint(ep.address(), ep.port());\n\t\t}\n\n\t\tvoid set_buf_size(int s);\n\n\t\ttemplate \n\t\tvoid set_option(SocketOption const& opt, error_code& ec)\n\t\t{\n\t\t\tm_ipv4_sock.set_option(opt, ec);\n#if TORRENT_USE_IPV6\n\t\t\tm_ipv6_sock.set_option(opt, ec);\n#endif\n\t\t}\n\n\t\ttemplate \n\t\tvoid get_option(SocketOption& opt, error_code& ec)\n\t\t{\n\t\t\tm_ipv4_sock.get_option(opt, ec);\n\t\t}\n\n\t\tudp::endpoint proxy_addr() const { return m_proxy_addr; }\n\n\tprotected:\n\n\t\tstruct queued_packet\n\t\t{\n\t\t\tudp::endpoint ep;\n\t\t\tchar* hostname;\n\t\t\tbuffer buf;\n\t\t\tint flags;\n\t\t};\n\n\t\t\/\/ number of outstanding UDP socket operations\n\t\t\/\/ using the UDP socket buffer\n\t\tint num_outstanding() const\n\t\t{\n\t\t\treturn m_v4_outstanding\n#if TORRENT_USE_IPV6\n\t\t\t \t+ m_v6_outstanding\n#endif\n\t\t\t\t;\n\t\t}\n\n\tprivate:\n#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING\n\t\/\/ necessary for logging member offsets\n\tpublic:\n#endif\n\n\t\t\/\/ callback for regular incoming packets\n\t\tcallback_t m_callback;\n\n\t\t\/\/ callback for proxied incoming packets with a domain\n\t\t\/\/ name as source\n\t\tcallback2_t m_callback2;\n\n\t\t\/\/ called every time we drain the udp sockets\n\t\tdrain_callback_t m_drained_callback;\n\n\t\tvoid setup_read(udp::socket* s);\n\t\tvoid on_read(udp::socket* s);\n\t\tvoid on_read_impl(udp::socket* sock, udp::endpoint const& ep\n\t\t\t, error_code const& e, std::size_t bytes_transferred);\n\t\tvoid on_name_lookup(error_code const& e, tcp::resolver::iterator i);\n\t\tvoid on_timeout();\n\t\tvoid on_connect(int ticket);\n\t\tvoid on_connected(error_code const& ec);\n\t\tvoid handshake1(error_code const& e);\n\t\tvoid handshake2(error_code const& e);\n\t\tvoid handshake3(error_code const& e);\n\t\tvoid handshake4(error_code const& e);\n\t\tvoid socks_forward_udp();\n\t\tvoid connect1(error_code const& e);\n\t\tvoid connect2(error_code const& e);\n\t\tvoid hung_up(error_code const& e);\n\n\t\tvoid wrap(udp::endpoint const& ep, char const* p, int len, error_code& ec);\n\t\tvoid wrap(char const* hostname, int port, char const* p, int len, error_code& ec);\n\t\tvoid unwrap(error_code const& e, char const* buf, int size);\n\n\t\tbool maybe_clear_callback();\n\n#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS\n#if defined BOOST_HAS_PTHREADS\n\t\tmutable pthread_t m_thread;\n#endif\n\t\tbool is_single_thread() const\n\t\t{\n#if defined BOOST_HAS_PTHREADS\n\t\t\tif (m_thread == 0)\n\t\t\t\tm_thread = pthread_self();\n\t\t\treturn m_thread == pthread_self();\n#endif\n\t\t\treturn true;\n\t\t}\n#endif\n\n\t\tudp::socket m_ipv4_sock;\n\t\tint m_buf_size;\n\t\tchar* m_buf;\n\n#if TORRENT_USE_IPV6\n\t\tudp::socket m_ipv6_sock;\n#endif\n\n\t\tboost::uint16_t m_bind_port;\n\t\tboost::uint8_t m_v4_outstanding;\n#if TORRENT_USE_IPV6\n\t\tboost::uint8_t m_v6_outstanding;\n#endif\n\n\t\ttcp::socket m_socks5_sock;\n\t\tint m_connection_ticket;\n\t\tproxy_settings m_proxy_settings;\n\t\tconnection_queue& m_cc;\n\t\ttcp::resolver m_resolver;\n\t\tchar m_tmp_buf[270];\n\t\tbool m_queue_packets;\n\t\tbool m_tunnel_packets;\n\t\tbool m_abort;\n\t\tudp::endpoint m_proxy_addr;\n\t\t\/\/ while we're connecting to the proxy\n\t\t\/\/ we have to queue the packets, we'll flush\n\t\t\/\/ them once we're connected\n\t\tstd::deque m_queue;\n\n\t\t\/\/ counts the number of outstanding async\n\t\t\/\/ operations hanging on this socket\n\t\tint m_outstanding_ops;\n\n#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS\n\t\tbool m_started;\n\t\tint m_magic;\n\t\tint m_outstanding_when_aborted;\n#endif\n\t};\n\n\tstruct rate_limited_udp_socket : public udp_socket\n\t{\n\t\trate_limited_udp_socket(io_service& ios, callback_t const& c\n\t\t\t, callback2_t const& c2, drain_callback_t const& dc, connection_queue& cc);\n\t\tvoid set_rate_limit(int limit) { m_rate_limit = limit; }\n\t\tbool can_send() const { return int(m_queue.size()) >= m_queue_size_limit; }\n\t\tbool send(udp::endpoint const& ep, char const* p, int len, error_code& ec, int flags = 0);\n\t\tvoid close();\n\n\tprivate:\n\t\tvoid on_tick(error_code const& e);\n\n\t\tdeadline_timer m_timer;\n\t\tint m_queue_size_limit;\n\t\tint m_rate_limit;\n\t\tint m_quota;\n\t\tptime m_last_tick;\n\t\tstd::deque m_queue;\n\t};\n}\n\n#endif\n\nfix build issue\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_UDP_SOCKET_HPP_INCLUDED\n#define TORRENT_UDP_SOCKET_HPP_INCLUDED\n\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/io_service.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n#include \"libtorrent\/session_settings.hpp\"\n#include \"libtorrent\/buffer.hpp\"\n#include \"libtorrent\/thread.hpp\"\n#include \"libtorrent\/deadline_timer.hpp\"\n\n#include \n#include \n#include \n\nnamespace libtorrent\n{\n\tclass connection_queue;\n\n\tclass udp_socket\n\t{\n\tpublic:\n\t\t\/\/ TODO: instead of these callbacks, support observers\n\t\ttypedef boost::function callback_t;\n\t\ttypedef boost::function callback2_t;\n\t\ttypedef boost::function drain_callback_t;\n\n\t\tudp_socket(io_service& ios, callback_t const& c, callback2_t const& c2\n\t\t\t, drain_callback_t const& dc, connection_queue& cc);\n\t\t~udp_socket();\n\n\t\tenum flags_t { dont_drop = 1, peer_connection = 2 };\n\n\t\tbool is_open() const\n\t\t{\n\t\t\treturn m_ipv4_sock.is_open()\n#if TORRENT_USE_IPV6\n\t\t\t\t|| m_ipv6_sock.is_open()\n#endif\n\t\t\t\t;\n\t\t}\n\t\tio_service& get_io_service() { return m_ipv4_sock.get_io_service(); }\n\n\t\t\/\/ this is only valid when using a socks5 proxy\n\t\tvoid send_hostname(char const* hostname, int port, char const* p, int len, error_code& ec);\n\n\t\tvoid send(udp::endpoint const& ep, char const* p, int len, error_code& ec, int flags = 0);\n\t\tvoid bind(udp::endpoint const& ep, error_code& ec);\n\t\tvoid bind(int port);\n\t\tvoid close();\n\t\tint local_port() const { return m_bind_port; }\n\n\t\tvoid set_proxy_settings(proxy_settings const& ps);\n\t\tproxy_settings const& get_proxy_settings() { return m_proxy_settings; }\n\n\t\tbool is_closed() const { return m_abort; }\n\t\ttcp::endpoint local_endpoint(error_code& ec) const\n\t\t{\n\t\t\tudp::endpoint ep = m_ipv4_sock.local_endpoint(ec);\n\t\t\treturn tcp::endpoint(ep.address(), ep.port());\n\t\t}\n\n\t\tvoid set_buf_size(int s);\n\n\t\ttemplate \n\t\tvoid set_option(SocketOption const& opt, error_code& ec)\n\t\t{\n\t\t\tm_ipv4_sock.set_option(opt, ec);\n#if TORRENT_USE_IPV6\n\t\t\tm_ipv6_sock.set_option(opt, ec);\n#endif\n\t\t}\n\n\t\ttemplate \n\t\tvoid get_option(SocketOption& opt, error_code& ec)\n\t\t{\n\t\t\tm_ipv4_sock.get_option(opt, ec);\n\t\t}\n\n\t\tudp::endpoint proxy_addr() const { return m_proxy_addr; }\n\n\tprotected:\n\n\t\tstruct queued_packet\n\t\t{\n\t\t\tudp::endpoint ep;\n\t\t\tchar* hostname;\n\t\t\tbuffer buf;\n\t\t\tint flags;\n\t\t};\n\n\t\t\/\/ number of outstanding UDP socket operations\n\t\t\/\/ using the UDP socket buffer\n\t\tint num_outstanding() const\n\t\t{\n\t\t\treturn m_v4_outstanding\n#if TORRENT_USE_IPV6\n\t\t\t \t+ m_v6_outstanding\n#endif\n\t\t\t\t;\n\t\t}\n\n\tprivate:\n#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING\n\t\/\/ necessary for logging member offsets\n\tpublic:\n#endif\n\n\t\t\/\/ callback for regular incoming packets\n\t\tcallback_t m_callback;\n\n\t\t\/\/ callback for proxied incoming packets with a domain\n\t\t\/\/ name as source\n\t\tcallback2_t m_callback2;\n\n\t\t\/\/ called every time we drain the udp sockets\n\t\tdrain_callback_t m_drained_callback;\n\n\t\tvoid setup_read(udp::socket* s);\n\t\tvoid on_read(udp::socket* s);\n\t\tvoid on_read_impl(udp::socket* sock, udp::endpoint const& ep\n\t\t\t, error_code const& e, std::size_t bytes_transferred);\n\t\tvoid on_name_lookup(error_code const& e, tcp::resolver::iterator i);\n\t\tvoid on_timeout();\n\t\tvoid on_connect(int ticket);\n\t\tvoid on_connected(error_code const& ec);\n\t\tvoid handshake1(error_code const& e);\n\t\tvoid handshake2(error_code const& e);\n\t\tvoid handshake3(error_code const& e);\n\t\tvoid handshake4(error_code const& e);\n\t\tvoid socks_forward_udp();\n\t\tvoid connect1(error_code const& e);\n\t\tvoid connect2(error_code const& e);\n\t\tvoid hung_up(error_code const& e);\n\n\t\tvoid wrap(udp::endpoint const& ep, char const* p, int len, error_code& ec);\n\t\tvoid wrap(char const* hostname, int port, char const* p, int len, error_code& ec);\n\t\tvoid unwrap(error_code const& e, char const* buf, int size);\n\n\t\tbool maybe_clear_callback();\n\n#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS\n#if defined BOOST_HAS_PTHREADS\n\t\tmutable pthread_t m_thread;\n#endif\n\t\tbool is_single_thread() const\n\t\t{\n#if defined BOOST_HAS_PTHREADS\n\t\t\tif (m_thread == 0)\n\t\t\t\tm_thread = pthread_self();\n\t\t\treturn m_thread == pthread_self();\n#endif\n\t\t\treturn true;\n\t\t}\n#endif\n\n\t\tudp::socket m_ipv4_sock;\n\t\tint m_buf_size;\n\t\tchar* m_buf;\n\n#if TORRENT_USE_IPV6\n\t\tudp::socket m_ipv6_sock;\n#endif\n\n\t\tboost::uint16_t m_bind_port;\n\t\tboost::uint8_t m_v4_outstanding;\n#if TORRENT_USE_IPV6\n\t\tboost::uint8_t m_v6_outstanding;\n#endif\n\n\t\ttcp::socket m_socks5_sock;\n\t\tint m_connection_ticket;\n\t\tproxy_settings m_proxy_settings;\n\t\tconnection_queue& m_cc;\n\t\ttcp::resolver m_resolver;\n\t\tchar m_tmp_buf[270];\n\t\tbool m_queue_packets;\n\t\tbool m_tunnel_packets;\n\t\tbool m_abort;\n\t\tudp::endpoint m_proxy_addr;\n\t\t\/\/ while we're connecting to the proxy\n\t\t\/\/ we have to queue the packets, we'll flush\n\t\t\/\/ them once we're connected\n\t\tstd::deque m_queue;\n\n\t\t\/\/ counts the number of outstanding async\n\t\t\/\/ operations hanging on this socket\n\t\tint m_outstanding_ops;\n\n#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS\n\t\tbool m_started;\n\t\tint m_magic;\n\t\tint m_outstanding_when_aborted;\n#endif\n\t};\n\n\tstruct rate_limited_udp_socket : public udp_socket\n\t{\n\t\trate_limited_udp_socket(io_service& ios, callback_t const& c\n\t\t\t, callback2_t const& c2, drain_callback_t const& dc, connection_queue& cc);\n\t\tvoid set_rate_limit(int limit) { m_rate_limit = limit; }\n\t\tbool can_send() const { return int(m_queue.size()) >= m_queue_size_limit; }\n\t\tbool send(udp::endpoint const& ep, char const* p, int len, error_code& ec, int flags = 0);\n\t\tvoid close();\n\n\tprivate:\n\t\tvoid on_tick(error_code const& e);\n\n\t\tdeadline_timer m_timer;\n\t\tint m_queue_size_limit;\n\t\tint m_rate_limit;\n\t\tint m_quota;\n\t\tptime m_last_tick;\n\t\tstd::deque m_queue;\n\t};\n}\n\n#endif\n\n<|endoftext|>"} {"text":"#include \"sherwood_mex.h\"\r\n\r\nusing namespace MicrosoftResearch::Cambridge::Sherwood;\r\n\r\n\/\/ F: Feature Response\r\n\/\/ S: StatisticsAggregator\r\ntemplate\r\nvoid sherwood_classify(int nlhs, \t\t \/* number of expected outputs *\/\r\n mxArray *plhs[],\t \/* mxArray output pointer array *\/\r\n int nrhs, \t\t\/* number of inputs *\/\r\n const mxArray *prhs[],\t\t\/* mxArray input pointer array *\/\r\n Options options)\r\n{\r\n\tunsigned int curarg = 0;\r\n\tconst matrix features = prhs[curarg++];\r\n\r\n if (options.Verbose) {\r\n mexPrintf(\"Loading tree at: %s\\n\", options.ForestName.c_str());\r\n }\r\n \r\n\t\/\/ Point class\r\n\tDataPointCollection testData(features); \r\n\r\n\t\/\/ Create the tree.\r\n\tstd::auto_ptr > forest;\r\n\r\n\t\/\/ Load the tree from file \r\n std::ifstream istream(options.ForestName.c_str(), std::ios_base::binary);\r\n forest = forest->Deserialize(istream);\r\n\r\n unsigned int num_classes = forest->GetTree(0).GetNode(0).TrainingDataStatistics.BinCount();\r\n\r\n if (options.Verbose) \r\n {\r\n mexPrintf(\"Number of classes: %d\\n\", num_classes);\r\n mexPrintf(\"Number of test data: %d\\n\", testData.Count());\r\n }\r\n\r\n \/\/ Output ordered as (class, index)\r\n matrix output(num_classes,testData.Count());\r\n\r\n for (int i = 0; i < output.numel(); i++) {\r\n output(i) = 0;\r\n }\r\n \r\n \/\/ Perform classification\r\n \/\/ forest::apply is wasting memory, bypassing it.\r\n \/\/\r\n \/\/ Note: leafNodeIndices should unsigned int, modify tree.h and the line below.\r\n \/\/\r\n std::vector leafNodeIndices;\r\n\r\n \/\/ Forest.h (Apply)\r\n for (unsigned int t = 0; t < forest->TreeCount(); t++)\r\n {\r\n Tree& tree = forest->GetTree(t);\r\n\r\n \/\/ Tree.h\r\n tree.Apply(testData, leafNodeIndices);\r\n\r\n \/\/ Aggregate histograms\r\n if (options.TreeAggregator == Histogram) {\r\n\r\n for (unsigned int i = 0; i < testData.Count(); i++)\r\n { \r\n S aggregator = tree.GetNode(leafNodeIndices[i]).TrainingDataStatistics;\r\n\r\n for (unsigned int c = 0; c < num_classes; c++) {\r\n output(c,i) += aggregator.bins_[c];\r\n }\r\n }\r\n \r\n \/\/ Aggregate probabilities\r\n } else if (options.TreeAggregator == Probability) {\r\n\r\n int sum = 0;\r\n for (unsigned int i = 0; i < testData.Count(); i++)\r\n { \r\n S aggregator = tree.GetNode(leafNodeIndices[i]).TrainingDataStatistics;\r\n\r\n for (unsigned int c = 0; c < num_classes; c++) {\r\n sum += aggregator.bins_[c];\r\n }\r\n\r\n for (unsigned int c = 0; c < num_classes; c++) {\r\n output(c,i) += double(aggregator.bins_[c])\/sum;\r\n }\r\n \r\n sum = 0;\r\n }\r\n\r\n } else {\r\n mexErrMsgTxt(\"Unkown aggregator.\");\r\n }\r\n\r\n leafNodeIndices.clear();\r\n }\r\n\r\n plhs[0] = output;\r\n}\r\n\r\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\r\n{\r\n MexParams params(1, prhs+1);\r\n Options options(params);\r\n\r\n if (!options.WeakLearner.compare(\"axis-aligned-hyperplane\"))\r\n sherwood_classify(nlhs, plhs, nrhs, prhs, options);\r\n else if (!options.WeakLearner.compare(\"random-hyperplane\"))\r\n sherwood_classify(nlhs, plhs, nrhs, prhs, options);\r\n else \r\n mexErrMsgTxt(\"Unknown weak learner. Supported are: axis-aligned-hyperplane and random-hyperplane\");\r\n \r\n}More code reuse.#include \"sherwood_mex.h\"\r\n\r\nusing namespace MicrosoftResearch::Cambridge::Sherwood;\r\n\r\n\/\/ F: Feature Response\r\n\/\/ S: StatisticsAggregator\r\ntemplate\r\nvoid sherwood_classify(int nlhs, \t\t \/* number of expected outputs *\/\r\n mxArray *plhs[],\t \/* mxArray output pointer array *\/\r\n int nrhs, \t\t\/* number of inputs *\/\r\n const mxArray *prhs[],\t\t\/* mxArray input pointer array *\/\r\n Options options)\r\n{\r\n\tunsigned int curarg = 0;\r\n\tconst matrix features = prhs[curarg++];\r\n\r\n if (options.Verbose) {\r\n mexPrintf(\"Loading tree at: %s\\n\", options.ForestName.c_str());\r\n }\r\n \r\n\t\/\/ Point class\r\n\tDataPointCollection testData(features); \r\n\r\n\t\/\/ Create the tree.\r\n\tstd::auto_ptr > forest;\r\n\r\n\t\/\/ Load the tree from file \r\n std::ifstream istream(options.ForestName.c_str(), std::ios_base::binary);\r\n forest = forest->Deserialize(istream);\r\n\r\n unsigned int num_classes = forest->GetTree(0).GetNode(0).TrainingDataStatistics.BinCount();\r\n\r\n if (options.Verbose) \r\n {\r\n mexPrintf(\"Number of classes: %d\\n\", num_classes);\r\n mexPrintf(\"Number of test data: %d\\n\", testData.Count());\r\n }\r\n\r\n \/\/ Output ordered as (class, index)\r\n matrix output(num_classes,testData.Count());\r\n\r\n for (int i = 0; i < output.numel(); i++) {\r\n output(i) = 0;\r\n }\r\n \r\n \/\/ Perform classification\r\n \/\/ forest::apply is wasting memory, bypassing it.\r\n \/\/\r\n \/\/ Note: leafNodeIndices should unsigned int, modify tree.h and the line below.\r\n \/\/\r\n std::vector leafNodeIndices;\r\n\r\n \/\/ Forest.h (Apply)\r\n for (unsigned int t = 0; t < forest->TreeCount(); t++)\r\n {\r\n Tree& tree = forest->GetTree(t);\r\n\r\n \/\/ Tree.h\r\n tree.Apply(testData, leafNodeIndices);\r\n\r\n \/\/ Aggregate histograms\r\n if (options.TreeAggregator == Histogram) {\r\n\r\n for (unsigned int i = 0; i < testData.Count(); i++)\r\n { \r\n S aggregator = tree.GetNode(leafNodeIndices[i]).TrainingDataStatistics;\r\n\r\n for (unsigned int c = 0; c < num_classes; c++) {\r\n output(c,i) += aggregator.bins_[c];\r\n }\r\n }\r\n \r\n \/\/ Aggregate probabilities\r\n } else if (options.TreeAggregator == Probability) {\r\n for (unsigned int i = 0; i < testData.Count(); i++)\r\n { \r\n S aggregator = tree.GetNode(leafNodeIndices[i]).TrainingDataStatistics;\r\n\r\n for (unsigned int c = 0; c < num_classes; c++) {\r\n output(c,i) += aggregator.GetProbability(c);\r\n }\r\n }\r\n\r\n } else {\r\n mexErrMsgTxt(\"Unkown aggregator.\");\r\n }\r\n\r\n leafNodeIndices.clear();\r\n }\r\n\r\n plhs[0] = output;\r\n}\r\n\r\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\r\n{\r\n MexParams params(1, prhs+1);\r\n Options options(params);\r\n\r\n if (!options.WeakLearner.compare(\"axis-aligned-hyperplane\"))\r\n sherwood_classify(nlhs, plhs, nrhs, prhs, options);\r\n else if (!options.WeakLearner.compare(\"random-hyperplane\"))\r\n sherwood_classify(nlhs, plhs, nrhs, prhs, options);\r\n else \r\n mexErrMsgTxt(\"Unknown weak learner. Supported are: axis-aligned-hyperplane and random-hyperplane\");\r\n \r\n}<|endoftext|>"} {"text":"#include \n\n#include \"checker.hpp\"\n\nbool Checker::checkStep(GameDesk& a, Points& points) {\n int rownumber = a.getRowNumber();\n int n1 = a.getDeskNumber(points.p1);\n int n2 = a.getDeskNumber(points.p2);\n return checkIndex(rownumber, points) && n1 == n2;\n}\n\nbool Checker::checkIndex(int max, Points& points) {\n int p1c = points.p1.col;\n int p2c = points.p2.col;\n int p1r = points.p1.row;\n int p2r = points.p2.row;\n if (checkRange(max, points)) {\n if ((p1c == p2c) && (std::abs((p1r - p2r)) == 1)) {\n return true;\n } else if ((p1r == p2r) && (std::abs(p1c - p2c) == 1)) {\n return true;\n }\n return false;\n }\n return false;\n}\n\nbool Checker::checkRange(int max, Points& points) {\n int p1c = points.p1.col;\n int p2c = points.p2.col;\n int p1r = points.p1.row;\n int p2r = points.p2.row;\n bool gt0 = p1r >= 0 && p1c >= 0 && p2r >= 0 && p2c >= 0;\n bool ltm = p1r < max && p1c < max && p2r < max && p2c < max;\n return gt0 && ltm;\n}\n\nReach compatibility with gcc 4.4#include \"checker.hpp\"\n\nstatic int myAbs(int number) {\n if (number >= 0) {\n return number;\n } else {\n return -number;\n }\n}\n\nbool Checker::checkStep(GameDesk& a, Points& points) {\n int rownumber = a.getRowNumber();\n int n1 = a.getDeskNumber(points.p1);\n int n2 = a.getDeskNumber(points.p2);\n return checkIndex(rownumber, points) && n1 == n2;\n}\n\nbool Checker::checkIndex(int max, Points& points) {\n int p1c = points.p1.col;\n int p2c = points.p2.col;\n int p1r = points.p1.row;\n int p2r = points.p2.row;\n if (checkRange(max, points)) {\n if ((p1c == p2c) && (myAbs((p1r - p2r)) == 1)) {\n return true;\n } else if ((p1r == p2r) && (myAbs(p1c - p2c) == 1)) {\n return true;\n }\n return false;\n }\n return false;\n}\n\nbool Checker::checkRange(int max, Points& points) {\n int p1c = points.p1.col;\n int p2c = points.p2.col;\n int p1r = points.p1.row;\n int p2r = points.p2.row;\n bool gt0 = p1r >= 0 && p1c >= 0 && p2r >= 0 && p2c >= 0;\n bool ltm = p1r < max && p1c < max && p2r < max && p2c < max;\n return gt0 && ltm;\n}\n\n<|endoftext|>"} {"text":"#ifndef TWISTEDCPP_PROTOCOL_CORE\n#define TWISTEDCPP_PROTOCOL_CORE\n\n#include \"detail\/sockets.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef NDEBUG\n#include \n#endif\n\nnamespace twisted {\n\ntemplate \nclass protocol_core : public std::enable_shared_from_this {\npublic:\n typedef detail::socket_base socket_type;\n typedef boost::asio::steady_timer timer_type;\n typedef boost::asio::io_service::strand strand_type;\n typedef BufferType buffer_type;\n typedef typename buffer_type::iterator buffer_iterator;\n typedef typename buffer_type::const_iterator const_buffer_iterator;\n\n protocol_core() = default;\n protocol_core(protocol_core&&) = default;\n protocol_core& operator=(protocol_core&&) = default;\n\n void set_socket(std::unique_ptr socket) {\n _socket = std::move(socket);\n }\n\n void run_protocol() {\n auto self = this_protocol().shared_from_this();\n boost::asio::spawn(_socket->get_io_service(),\n [this, self](boost::asio::yield_context yield) {\n _yield = boost::in_place(yield);\n\n try {\n _socket->do_handshake(*_yield);\n\n while (_socket->is_open()) {\n auto bytes_read =\n _socket->async_read_some(asio_buffer(), yield);\n checked_on_message(buffer_begin(),\n std::next(buffer_begin(), bytes_read));\n }\n }\n catch (boost::system::system_error& connection_error) {\n handle_network_error(connection_error);\n }\n\n this_protocol().on_disconnect();\n });\n }\n\n template \n void call_later(Duration duration, Callable callable) {\n auto self = this_protocol().shared_from_this();\n \/\/ we pass our existing yield_context and not the io_service such that\n \/\/ both contexts run under the same strand\n boost::asio::spawn(*_yield, [this, duration, callable, self](\n boost::asio::yield_context yield) {\n boost::asio::high_resolution_timer timer(_socket->get_io_service(),\n duration);\n timer.async_wait(yield);\n\n \/\/ we need to exchange the yield context so that that the user can\n \/\/ use the send_message function in the right context\n boost::optional old_yield(\n boost::in_place(*_yield));\n _yield = boost::in_place(yield);\n callable();\n _yield = boost::in_place(*old_yield);\n });\n }\n\n template \n void call(Callable callable) {\n call_later(std::chrono::seconds(0), std::move(callable));\n }\n\n template \n void call_from_thread(Callable&& callable, Args&&... args) {\n _socket->get_io_service().post(std::bind(\n std::forward(callable), std::forward(args)...));\n }\n\n template \n void wait_for(const Duration& duration) const {\n boost::asio::high_resolution_timer timer(_socket->get_io_service(),\n duration);\n timer.async_wait(*_yield);\n }\n\n template \n void send_message(Iter begin, Iter end) {\n _socket->async_write(\n boost::asio::buffer(&*begin, std::distance(begin, end)), *_yield);\n }\n\n template \n void forward(const protocol_core& other, Iter begin, Iter end) {\n other._socket->async_write(\n boost::asio::buffer(&*begin, std::distance(begin, end)), *_yield);\n }\n\n void send_buffers(const std::array& buffers) {\n _socket->async_write(buffers, *_yield);\n }\n\n \/*\n * @brief default on_disconnect implementation; does nothing\n *\/\n void on_disconnect() {}\n\n \/*\n * @brief default on_error implementation; swallows everything\n *\/\n void on_error(std::exception_ptr eptr) {\n try {\n std::rethrow_exception(eptr);\n }\n catch (const std::exception& excep) {\n print_exception_what(excep);\n }\n }\n\n bool is_connected() const { return _socket->is_open(); }\n\n void lose_connection() { _socket->close(); }\n\n \/*\n * @brief CRTP wrapper for derived class access\n *\/\n ChildProtocol& this_protocol() {\n return *static_cast(this);\n }\n\n \/*\n * @brief CRTP wrapper for derived class access\n *\/\n const ChildProtocol& this_protocol() const {\n return *static_cast(this);\n }\n\nprivate:\n void checked_on_message(const_buffer_iterator begin,\n const_buffer_iterator end) {\n try {\n this_protocol().on_message(begin, end);\n }\n catch (...) {\n this_protocol().on_error(std::current_exception());\n }\n }\n\n#ifdef NDEBUG\n void handle_network_error(boost::system::system_error&) {\n#else\n void handle_network_error(boost::system::system_error& connection_error) {\n print_connection_error(connection_error);\n#endif\n }\n\n void handle_user_error(const std::exception_ptr& excep) {\n this_protocol().on_error(excep);\n }\n\n void print_connection_error(\n const boost::system::system_error& connection_error) const {\n std::cerr << \"Client disconnected with code \" << connection_error.what()\n << std::endl;\n }\n\n void print_exception_what(const std::exception& excep) const {\n std::cerr << \"Killing connection, exception in client handler: \"\n << excep.what() << std::endl;\n }\n\n buffer_iterator buffer_begin() {\n using std::begin;\n return begin(this_protocol().read_buffer());\n }\n\n buffer_iterator buffer_begin() const {\n using std::begin;\n return begin(this_protocol().read_buffer());\n }\n\n buffer_iterator buffer_end() {\n using std::end;\n return end(this_protocol().read_buffer());\n }\n\n buffer_iterator buffer_end() const {\n using std::end;\n return end(this_protocol().read_buffer());\n }\n\n boost::asio::mutable_buffers_1 asio_buffer() {\n return boost::asio::buffer(&*buffer_begin(),\n std::distance(buffer_begin(), buffer_end()));\n }\n\nprivate:\n boost::optional _yield;\n std::unique_ptr _socket;\n};\n\n} \/\/ namespace twisted\n\n#endif\nany ConstBufferSequence can now be passed to send_buffers#ifndef TWISTEDCPP_PROTOCOL_CORE\n#define TWISTEDCPP_PROTOCOL_CORE\n\n#include \"detail\/sockets.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef NDEBUG\n#include \n#endif\n\nnamespace twisted {\n\ntemplate \nclass protocol_core : public std::enable_shared_from_this {\npublic:\n typedef detail::socket_base socket_type;\n typedef boost::asio::steady_timer timer_type;\n typedef boost::asio::io_service::strand strand_type;\n typedef BufferType buffer_type;\n typedef typename buffer_type::iterator buffer_iterator;\n typedef typename buffer_type::const_iterator const_buffer_iterator;\n\n protocol_core() = default;\n protocol_core(protocol_core&&) = default;\n protocol_core& operator=(protocol_core&&) = default;\n\n void set_socket(std::unique_ptr socket) {\n _socket = std::move(socket);\n }\n\n void run_protocol() {\n auto self = this_protocol().shared_from_this();\n boost::asio::spawn(_socket->get_io_service(),\n [this, self](boost::asio::yield_context yield) {\n _yield = boost::in_place(yield);\n\n try {\n _socket->do_handshake(*_yield);\n\n while (_socket->is_open()) {\n auto bytes_read =\n _socket->async_read_some(asio_buffer(), yield);\n checked_on_message(buffer_begin(),\n std::next(buffer_begin(), bytes_read));\n }\n }\n catch (boost::system::system_error& connection_error) {\n handle_network_error(connection_error);\n }\n\n this_protocol().on_disconnect();\n });\n }\n\n template \n void call_later(Duration duration, Callable callable) {\n auto self = this_protocol().shared_from_this();\n \/\/ we pass our existing yield_context and not the io_service such that\n \/\/ both contexts run under the same strand\n boost::asio::spawn(*_yield, [this, duration, callable, self](\n boost::asio::yield_context yield) {\n boost::asio::high_resolution_timer timer(_socket->get_io_service(),\n duration);\n timer.async_wait(yield);\n\n \/\/ we need to exchange the yield context so that that the user can\n \/\/ use the send_message function in the right context\n boost::optional old_yield(\n boost::in_place(*_yield));\n _yield = boost::in_place(yield);\n callable();\n _yield = boost::in_place(*old_yield);\n });\n }\n\n template \n void call(Callable callable) {\n call_later(std::chrono::seconds(0), std::move(callable));\n }\n\n template \n void call_from_thread(Callable&& callable, Args&&... args) {\n _socket->get_io_service().post(std::bind(\n std::forward(callable), std::forward(args)...));\n }\n\n template \n void wait_for(const Duration& duration) const {\n boost::asio::high_resolution_timer timer(_socket->get_io_service(),\n duration);\n timer.async_wait(*_yield);\n }\n\n template \n void send_message(Iter begin, Iter end) {\n _socket->async_write(\n boost::asio::buffer(&*begin, std::distance(begin, end)), *_yield);\n }\n\n template \n void forward(const protocol_core& other, Iter begin, Iter end) {\n other._socket->async_write(\n boost::asio::buffer(&*begin, std::distance(begin, end)), *_yield);\n }\n\n template\n void send_buffers(const ConstBufferSequence& buffers) {\n _socket->async_write(buffers, *_yield);\n }\n\n \/*\n * @brief default on_disconnect implementation; does nothing\n *\/\n void on_disconnect() {}\n\n \/*\n * @brief default on_error implementation; swallows everything\n *\/\n void on_error(std::exception_ptr eptr) {\n try {\n std::rethrow_exception(eptr);\n }\n catch (const std::exception& excep) {\n print_exception_what(excep);\n }\n }\n\n bool is_connected() const { return _socket->is_open(); }\n\n void lose_connection() { _socket->close(); }\n\n \/*\n * @brief CRTP wrapper for derived class access\n *\/\n ChildProtocol& this_protocol() {\n return *static_cast(this);\n }\n\n \/*\n * @brief CRTP wrapper for derived class access\n *\/\n const ChildProtocol& this_protocol() const {\n return *static_cast(this);\n }\n\nprivate:\n void checked_on_message(const_buffer_iterator begin,\n const_buffer_iterator end) {\n try {\n this_protocol().on_message(begin, end);\n }\n catch (...) {\n this_protocol().on_error(std::current_exception());\n }\n }\n\n#ifdef NDEBUG\n void handle_network_error(boost::system::system_error&) {\n#else\n void handle_network_error(boost::system::system_error& connection_error) {\n print_connection_error(connection_error);\n#endif\n }\n\n void handle_user_error(const std::exception_ptr& excep) {\n this_protocol().on_error(excep);\n }\n\n void print_connection_error(\n const boost::system::system_error& connection_error) const {\n std::cerr << \"Client disconnected with code \" << connection_error.what()\n << std::endl;\n }\n\n void print_exception_what(const std::exception& excep) const {\n std::cerr << \"Killing connection, exception in client handler: \"\n << excep.what() << std::endl;\n }\n\n buffer_iterator buffer_begin() {\n using std::begin;\n return begin(this_protocol().read_buffer());\n }\n\n buffer_iterator buffer_begin() const {\n using std::begin;\n return begin(this_protocol().read_buffer());\n }\n\n buffer_iterator buffer_end() {\n using std::end;\n return end(this_protocol().read_buffer());\n }\n\n buffer_iterator buffer_end() const {\n using std::end;\n return end(this_protocol().read_buffer());\n }\n\n boost::asio::mutable_buffers_1 asio_buffer() {\n return boost::asio::buffer(&*buffer_begin(),\n std::distance(buffer_begin(), buffer_end()));\n }\n\nprivate:\n boost::optional _yield;\n std::unique_ptr _socket;\n};\n\n} \/\/ namespace twisted\n\n#endif\n<|endoftext|>"} {"text":"#ifndef VSMC_INTERNAL_FORWARD_HPP\n#define VSMC_INTERNAL_FORWARD_HPP\n\nnamespace vsmc {\n\nnamespace internal {\n\ntemplate class InitializeBase;\ntemplate class MoveBase;\ntemplate class MonitorEvalBase;\ntemplate class PathEvalBase;\n\n} \/\/ namespace vsmc::internal\n\nclass NullTimer;\n\nclass VirtualDerivedTag {};\nclass StaticDerivedTag {};\nclass PreResamplingTag {};\nclass PostResamplingTag {};\n\ntemplate class Sampler;\ntemplate class Particle;\ntemplate class Monitor;\ntemplate class Path;\n\ntemplate class StateBase;\ntemplate class SingleParticle;\ntemplate class ConstSingleParticle;\n\ntemplate class StateSeq;\ntemplate class InitializeSeq;\ntemplate class MoveSeq;\ntemplate \nclass MonitorEvalSeq;\ntemplate class PathEvalSeq;\n\ntemplate class StateTBB;\ntemplate class InitializeTBB;\ntemplate class MoveTBB;\ntemplate \nclass MonitorEvalTBB;\ntemplate class PathEvalTBB;\n\ntemplate class StateCL;\ntemplate class InitializeCL;\ntemplate class MoveCL;\ntemplate class MonitorEvalCL;\ntemplate class PathEvalCL;\n\n} \/\/ namesapce vsmc\n\n#endif \/\/ VSMC_INTERNAL_FORWARD_HPP\nfix the the default behavior#ifndef VSMC_INTERNAL_FORWARD_HPP\n#define VSMC_INTERNAL_FORWARD_HPP\n\nnamespace vsmc {\n\nnamespace internal {\n\ntemplate class InitializeBase;\ntemplate class MoveBase;\ntemplate class MonitorEvalBase;\ntemplate class PathEvalBase;\n\n} \/\/ namespace vsmc::internal\n\nclass NullTimer;\n\nclass VirtualDerivedTag {};\nclass StaticDerivedTag {};\nclass PreResamplingTag {};\nclass PostResamplingTag {};\n\ntemplate class Sampler;\ntemplate class Particle;\ntemplate class Monitor;\ntemplate class Path;\n\ntemplate class StateBase;\ntemplate class SingleParticle;\ntemplate class ConstSingleParticle;\n\ntemplate class StateSeq;\ntemplate class InitializeSeq;\ntemplate class MoveSeq;\ntemplate \nclass MonitorEvalSeq;\ntemplate class PathEvalSeq;\n\ntemplate class StateTBB;\ntemplate class InitializeTBB;\ntemplate class MoveTBB;\ntemplate \nclass MonitorEvalTBB;\ntemplate class PathEvalTBB;\n\ntemplate class StateCL;\ntemplate class InitializeCL;\ntemplate class MoveCL;\ntemplate class MonitorEvalCL;\ntemplate class PathEvalCL;\n\n} \/\/ namesapce vsmc\n\n#endif \/\/ VSMC_INTERNAL_FORWARD_HPP\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n\nCPPUNIT_NS_BEGIN\n\n \nXmlElement::XmlElement( std::string elementName,\n std::string content ) \n : m_name( elementName )\n , m_content( content )\n{\n}\n\n \nXmlElement::XmlElement( std::string elementName,\n int numericContent )\n : m_name( elementName )\n{\n setContent( numericContent );\n}\n\n\nXmlElement::~XmlElement()\n{\n Elements::iterator itNode = m_elements.begin();\n while ( itNode != m_elements.end() )\n {\n XmlElement *element = *itNode;\n delete *itNode++;\n }\n}\n\n\nstd::string \nXmlElement::name() const\n{\n return m_name;\n}\n\n\nstd::string \nXmlElement::content() const\n{\n return m_content;\n}\n\n\nvoid \nXmlElement::setName( const std::string &name )\n{\n m_name = name;\n}\n\n\nvoid \nXmlElement::setContent( const std::string &content )\n{\n m_content = content;\n}\n\n\nvoid \nXmlElement::setContent( int numericContent )\n{\n m_content = StringTools::toString( numericContent );\n}\n\n\nvoid \nXmlElement::addAttribute( std::string attributeName,\n std::string value )\n{\n m_attributes.push_back( Attribute( attributeName, value ) );\n}\n\n\nvoid \nXmlElement::addAttribute( std::string attributeName,\n int numericValue )\n{\n addAttribute( attributeName, StringTools::toString( numericValue ) );\n}\n\n\nvoid \nXmlElement::addElement( XmlElement *node )\n{\n m_elements.push_back( node );\n}\n\n\nint \nXmlElement::elementCount() const\n{\n return m_elements.size();\n}\n\n\nXmlElement *\nXmlElement::elementAt( int index ) const\n{\n if ( index < 0 || index >= elementCount() )\n throw std::invalid_argument( \"XmlElement::elementAt(), out of range index\" );\n\n return m_elements[ index ];\n}\n\n\nXmlElement *\nXmlElement::elementFor( const std::string &name ) const\n{\n Elements::const_iterator itElement = m_elements.begin();\n for ( ; itElement != m_elements.end(); ++itElement )\n {\n if ( (*itElement)->name() == name )\n return *itElement;\n }\n\n throw std::invalid_argument( \"XmlElement::elementFor(), not matching child element found\" );\n return NULL; \/\/ make some compilers happy.\n}\n\n\nstd::string \nXmlElement::toString( const std::string &indent ) const\n{\n std::string element( indent );\n element += \"<\";\n element += m_name;\n if ( !m_attributes.empty() )\n {\n element += \" \";\n element += attributesAsString();\n }\n element += \">\";\n\n if ( !m_elements.empty() )\n {\n element += \"\\n\";\n\n std::string subNodeIndent( indent + \" \" );\n Elements::const_iterator itNode = m_elements.begin();\n while ( itNode != m_elements.end() )\n {\n const XmlElement *node = *itNode++;\n element += node->toString( subNodeIndent );\n }\n\n element += indent;\n }\n\n if ( !m_content.empty() )\n {\n element += escape( m_content );\n if ( !m_elements.empty() )\n {\n element += \"\\n\";\n element += indent;\n }\n }\n\n element += \"<\/\";\n element += m_name;\n element += \">\\n\";\n\n return element;\n}\n\n\nstd::string \nXmlElement::attributesAsString() const\n{\n std::string attributes;\n Attributes::const_iterator itAttribute = m_attributes.begin();\n while ( itAttribute != m_attributes.end() )\n {\n if ( !attributes.empty() )\n attributes += \" \";\n\n const Attribute &attribute = *itAttribute++;\n attributes += attribute.first;\n attributes += \"=\\\"\";\n attributes += escape( attribute.second );\n attributes += \"\\\"\";\n }\n return attributes;\n}\n\n\nstd::string \nXmlElement::escape( std::string value ) const\n{\n std::string escaped;\n for ( unsigned int index =0; index < value.length(); ++index )\n {\n char c = value[index ];\n switch ( c ) \/\/ escape all predefined XML entity (safe?)\n {\n case '<': \n escaped += \"<\";\n break;\n case '>': \n escaped += \">\";\n break;\n case '&': \n escaped += \"&\";\n break;\n case '\\'': \n escaped += \"'\";\n break;\n case '\"': \n escaped += \""\";\n break;\n default:\n escaped += c;\n }\n }\n \n return escaped;\n}\n\n\nCPPUNIT_NS_END\n\n* clean up#include \n#include \n#include \n\n\nCPPUNIT_NS_BEGIN\n\n \nXmlElement::XmlElement( std::string elementName,\n std::string content ) \n : m_name( elementName )\n , m_content( content )\n{\n}\n\n \nXmlElement::XmlElement( std::string elementName,\n int numericContent )\n : m_name( elementName )\n{\n setContent( numericContent );\n}\n\n\nXmlElement::~XmlElement()\n{\n Elements::iterator itNode = m_elements.begin();\n while ( itNode != m_elements.end() )\n {\n XmlElement *element = *itNode++;\n delete element;\n }\n}\n\n\nstd::string \nXmlElement::name() const\n{\n return m_name;\n}\n\n\nstd::string \nXmlElement::content() const\n{\n return m_content;\n}\n\n\nvoid \nXmlElement::setName( const std::string &name )\n{\n m_name = name;\n}\n\n\nvoid \nXmlElement::setContent( const std::string &content )\n{\n m_content = content;\n}\n\n\nvoid \nXmlElement::setContent( int numericContent )\n{\n m_content = StringTools::toString( numericContent );\n}\n\n\nvoid \nXmlElement::addAttribute( std::string attributeName,\n std::string value )\n{\n m_attributes.push_back( Attribute( attributeName, value ) );\n}\n\n\nvoid \nXmlElement::addAttribute( std::string attributeName,\n int numericValue )\n{\n addAttribute( attributeName, StringTools::toString( numericValue ) );\n}\n\n\nvoid \nXmlElement::addElement( XmlElement *node )\n{\n m_elements.push_back( node );\n}\n\n\nint \nXmlElement::elementCount() const\n{\n return m_elements.size();\n}\n\n\nXmlElement *\nXmlElement::elementAt( int index ) const\n{\n if ( index < 0 || index >= elementCount() )\n throw std::invalid_argument( \"XmlElement::elementAt(), out of range index\" );\n\n return m_elements[ index ];\n}\n\n\nXmlElement *\nXmlElement::elementFor( const std::string &name ) const\n{\n Elements::const_iterator itElement = m_elements.begin();\n for ( ; itElement != m_elements.end(); ++itElement )\n {\n if ( (*itElement)->name() == name )\n return *itElement;\n }\n\n throw std::invalid_argument( \"XmlElement::elementFor(), not matching child element found\" );\n return NULL; \/\/ make some compilers happy.\n}\n\n\nstd::string \nXmlElement::toString( const std::string &indent ) const\n{\n std::string element( indent );\n element += \"<\";\n element += m_name;\n if ( !m_attributes.empty() )\n {\n element += \" \";\n element += attributesAsString();\n }\n element += \">\";\n\n if ( !m_elements.empty() )\n {\n element += \"\\n\";\n\n std::string subNodeIndent( indent + \" \" );\n Elements::const_iterator itNode = m_elements.begin();\n while ( itNode != m_elements.end() )\n {\n const XmlElement *node = *itNode++;\n element += node->toString( subNodeIndent );\n }\n\n element += indent;\n }\n\n if ( !m_content.empty() )\n {\n element += escape( m_content );\n if ( !m_elements.empty() )\n {\n element += \"\\n\";\n element += indent;\n }\n }\n\n element += \"<\/\";\n element += m_name;\n element += \">\\n\";\n\n return element;\n}\n\n\nstd::string \nXmlElement::attributesAsString() const\n{\n std::string attributes;\n Attributes::const_iterator itAttribute = m_attributes.begin();\n while ( itAttribute != m_attributes.end() )\n {\n if ( !attributes.empty() )\n attributes += \" \";\n\n const Attribute &attribute = *itAttribute++;\n attributes += attribute.first;\n attributes += \"=\\\"\";\n attributes += escape( attribute.second );\n attributes += \"\\\"\";\n }\n return attributes;\n}\n\n\nstd::string \nXmlElement::escape( std::string value ) const\n{\n std::string escaped;\n for ( unsigned int index =0; index < value.length(); ++index )\n {\n char c = value[index ];\n switch ( c ) \/\/ escape all predefined XML entity (safe?)\n {\n case '<': \n escaped += \"<\";\n break;\n case '>': \n escaped += \">\";\n break;\n case '&': \n escaped += \"&\";\n break;\n case '\\'': \n escaped += \"'\";\n break;\n case '\"': \n escaped += \""\";\n break;\n default:\n escaped += c;\n }\n }\n \n return escaped;\n}\n\n\nCPPUNIT_NS_END\n\n<|endoftext|>"} {"text":"#include \"..\/..\/include\/controllers\/StationPlayerController.hpp\"\n#include \"..\/..\/include\/StationPlayer.hpp\"\n#include \"..\/..\/include\/Constants.hpp\"\n#include \"..\/..\/include\/Utilities.hpp\"\n\n\nStationPlayerController::StationPlayerController(StatesManager& manager, State::Context context) noexcept\n : Controller(manager, context)\n{\n}\n\nvoid StationPlayerController::process_event_command(const radiostream::Event e, std::any data)\n{\n using namespace constants;\n switch (e)\n {\n case radiostream::Event::PauseClicked:\n {\n context_.station_player_.pause();\n }\n break;\n\n case radiostream::Event::PlayClicked:\n {\n context_.station_player_.play();\n }\n break;\n\n case radiostream::Event::VolumeChanged:\n {\n context_.station_player_.set_volume(volume_int_to_float(std::any_cast(data)));\n }\n break;\n \n case radiostream::Event::NewStationRequested:\n {\n const auto station = std::any_cast(data);\n std::thread thread = std::thread([this, station](){\n if(context_.station_player_.set_station(station))\n context_.station_player_.play();\n });\n thread.detach();\n }\n break;\n\n case radiostream::Event::MuteClicked:\n {\n context_.station_player_.mute();\n }\n break;\n\n case radiostream::Event::MuteUnclicked:\n {\n context_.station_player_.unmute();\n }\n break;\n }\n}\nMissing header fix.#include \"..\/..\/include\/controllers\/StationPlayerController.hpp\"\n#include \"..\/..\/include\/StationPlayer.hpp\"\n#include \"..\/..\/include\/Constants.hpp\"\n#include \"..\/..\/include\/Utilities.hpp\"\n#include \n\n\nStationPlayerController::StationPlayerController(StatesManager& manager, State::Context context) noexcept\n : Controller(manager, context)\n{\n}\n\nvoid StationPlayerController::process_event_command(const radiostream::Event e, std::any data)\n{\n using namespace constants;\n switch (e)\n {\n case radiostream::Event::PauseClicked:\n {\n context_.station_player_.pause();\n }\n break;\n\n case radiostream::Event::PlayClicked:\n {\n context_.station_player_.play();\n }\n break;\n\n case radiostream::Event::VolumeChanged:\n {\n context_.station_player_.set_volume(volume_int_to_float(std::any_cast(data)));\n }\n break;\n \n case radiostream::Event::NewStationRequested:\n {\n const auto station = std::any_cast(data);\n std::thread thread = std::thread([this, station](){\n if(context_.station_player_.set_station(station))\n context_.station_player_.play();\n });\n thread.detach();\n }\n break;\n\n case radiostream::Event::MuteClicked:\n {\n context_.station_player_.mute();\n }\n break;\n\n case radiostream::Event::MuteUnclicked:\n {\n context_.station_player_.unmute();\n }\n break;\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n\nnamespace ntw {\n\nSocketSerialized::SocketSerialized(Socket::Dommaine dommaine,Socket::Type type,int protocole): Serializer(255), Socket(dommaine,type,protocole), status(0)\n{\n \/\/reserver les 2 premier bits pour la taille\n _cursor_end =_cursor_begin = 4;\n \/\/is_send=false;\n};\n\nSocketSerialized::SocketSerialized(Socket&& s) : Serializer(255)\n{\n std::swap(s.sock,sock);\n std::swap(s.sock_cfg,sock_cfg);\n _cursor_end =_cursor_begin = 4;\n};\n\nvoid SocketSerialized::send()\n{\n \/\/écrire la taille dans les 2 premier oct\n uint16_t size = _cursor_end - _cursor_begin;\n uint8_t *d = (uint8_t *)&size;\n #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n _buffer[_cursor_begin - 4] = d[0];\n _buffer[_cursor_begin - 3] = d[1];\n #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n _buffer[_cursor_begin - 4] = d[1];\n _buffer[_cursor_begin - 3] = d[0];\n #else\n #error \"byte orden not suported (PDP endian)\"\n #endif\n\n {\n uint16_t st = status;\n d = (uint8_t*)&st;\n #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n _buffer[_cursor_begin - 2] = d[0];\n _buffer[_cursor_begin - 1] = d[1];\n #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n _buffer[_cursor_begin - 2] = d[1];\n _buffer[_cursor_begin - 1] = d[0];\n #else\n #error \"byte orden not suported (PDP endian)\"\n #endif\n }\n \/\/envoyer\n \/\/std::cout<<\"send: \"<<*this< 0)\n {\n uint8_t d[2];\n #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n d[0]= _buffer[0];\n d[1]= _buffer[1];\n #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n d[1]= _buffer[0];\n d[0]= _buffer[1];\n #else\n #error \"byte orden not suported (PDP endian)\"\n #endif\n uint16_t size = *(uint16_t*)&d;\n\n #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n d[0]= _buffer[2];\n d[1]= _buffer[3];\n #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n d[1]= _buffer[2];\n d[0]= _buffer[3];\n #else\n #error \"byte orden not suported (PDP endian)\"\n #endif\n status = *(uint16_t*)&d;\n\n \/\/reset\n if (int(_buffer_size) < 4+size)\n resize(4+size);\n \/\/else _buffer_size ne change pas\n _cursor_begin = 4;\n _cursor_end = 4+size;\n \/\/remplacer le buffer\n if(size>0)\n {\n int recv_left = size;\n int recv = 0;\n while(recv_left > 0)\n {\n recv = Socket::receive(_buffer+res,recv_left-recv);\n if(recv<0)\n break;\n std::cout<<\"Recv size: \"<126)\n output<<\"<\"<<(int)self._buffer[i]<<\">\";\n else\n output<<\"'\"<<(char)self._buffer[i]<<\"'\";\n }\n return output;\n};\n \n\n};\ntest fix bug#include \n#include \n\nnamespace ntw {\n\nSocketSerialized::SocketSerialized(Socket::Dommaine dommaine,Socket::Type type,int protocole): Serializer(255), Socket(dommaine,type,protocole), status(0)\n{\n \/\/reserver les 2 premier bits pour la taille\n _cursor_end =_cursor_begin = 4;\n \/\/is_send=false;\n};\n\nSocketSerialized::SocketSerialized(Socket&& s) : Serializer(255)\n{\n std::swap(s.sock,sock);\n std::swap(s.sock_cfg,sock_cfg);\n _cursor_end =_cursor_begin = 4;\n};\n\nvoid SocketSerialized::send()\n{\n \/\/écrire la taille dans les 2 premier oct\n uint16_t size = _cursor_end - _cursor_begin;\n uint8_t *d = (uint8_t *)&size;\n #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n _buffer[_cursor_begin - 4] = d[0];\n _buffer[_cursor_begin - 3] = d[1];\n #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n _buffer[_cursor_begin - 4] = d[1];\n _buffer[_cursor_begin - 3] = d[0];\n #else\n #error \"byte orden not suported (PDP endian)\"\n #endif\n\n {\n uint16_t st = status;\n d = (uint8_t*)&st;\n #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n _buffer[_cursor_begin - 2] = d[0];\n _buffer[_cursor_begin - 1] = d[1];\n #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n _buffer[_cursor_begin - 2] = d[1];\n _buffer[_cursor_begin - 1] = d[0];\n #else\n #error \"byte orden not suported (PDP endian)\"\n #endif\n }\n \/\/envoyer\n \/\/std::cout<<\"send: \"<<*this< 0)\n {\n uint8_t d[2];\n #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n d[0]= _buffer[0];\n d[1]= _buffer[1];\n #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n d[1]= _buffer[0];\n d[0]= _buffer[1];\n #else\n #error \"byte orden not suported (PDP endian)\"\n #endif\n uint16_t size = *(uint16_t*)&d;\n\n #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n d[0]= _buffer[2];\n d[1]= _buffer[3];\n #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n d[1]= _buffer[2];\n d[0]= _buffer[3];\n #else\n #error \"byte orden not suported (PDP endian)\"\n #endif\n status = *(uint16_t*)&d;\n\n \/\/reset\n if (int(_buffer_size) < 4+size)\n resize(4+size);\n \/\/else _buffer_size ne change pas\n _cursor_begin = 4;\n _cursor_end = 4+size;\n \/\/remplacer le buffer\n if(size>0)\n {\n int recv_left = size;\n int recv = 0;\n while(recv_left > 0)\n {\n recv = Socket::receive(_buffer+res,recv_left);\n if(recv<0)\n break;\n std::cout<<\"Recv size: \"<126)\n output<<\"<\"<<(int)self._buffer[i]<<\">\";\n else\n output<<\"'\"<<(char)self._buffer[i]<<\"'\";\n }\n return output;\n};\n \n\n};\n<|endoftext|>"} {"text":"#ifndef BLOCKUNTILKEYUP_HPP\n#define BLOCKUNTILKEYUP_HPP\n\n#include \"FromEvent.hpp\"\n#include \"ParamsUnion.hpp\"\n#include \"Types.hpp\"\n\nnamespace org_pqrs_Karabiner {\n namespace RemapFunc {\n class BlockUntilKeyUp {\n public:\n void add(AddDataType datatype, AddValue newval);\n const FromEvent& getFromEvent(void) const { return fromEvent_; }\n\n private:\n FromEvent fromEvent_;\n };\n }\n}\n\n#endif\nuse RemapFuncBase#ifndef BLOCKUNTILKEYUP_HPP\n#define BLOCKUNTILKEYUP_HPP\n\n#include \"RemapFuncBase.hpp\"\n\nnamespace org_pqrs_Karabiner {\n namespace RemapFunc {\n class BlockUntilKeyUp : RemapFuncBase {\n public:\n BlockUntilKeyUp(void) :\n RemapFuncBase(BRIDGE_REMAPTYPE_BLOCKUNTILKEYUP)\n {}\n\n void add(AddDataType datatype, AddValue newval);\n const FromEvent& getFromEvent(void) const { return fromEvent_; }\n\n private:\n FromEvent fromEvent_;\n };\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"#ifndef KEYUPEVENTTOKEY_HPP\n#define KEYUPEVENTTOKEY_HPP\n\n#include \"KeyToKey.hpp\"\n#include \"List.hpp\"\n\nnamespace org_pqrs_KeyRemap4MacBook {\n namespace RemapFunc {\n class KeyUpEventToKey {\n public:\n static void static_initialize(void);\n static void static_terminate(void);\n\n KeyUpEventToKey(void) : preserveKeyDownOrder_(false) {}\n\n bool remap(RemapParams& remapParams);\n\n \/\/ ========================================\n \/\/ __KeyUpEventToKey__ syntax\n \/\/\n \/\/ \n \/\/ __KeyUpEventToKey__\n \/\/ @begin\n \/\/ FromEvent, FromFlags,\n \/\/ ToKeys_when_KeyDown,\n \/\/ @end\n \/\/\n \/\/ @begin\n \/\/ KeyUpFlags,\n \/\/ ToKeys_when_KeyUp,\n \/\/ @end\n \/\/\n \/\/ ...\n \/\/\n \/\/ @begin\n \/\/ KeyUpFlags,\n \/\/ ToKeys_when_KeyUp,\n \/\/ @end\n \/\/\n \/\/ <\/autogen>\n \/\/\n \/\/\n \/\/ * You can omit FromFlags, ToKeys_when_KeyDown, KeyUpFlags.\n \/\/\n \/\/ ========================================\n \/\/ Example:\n \/\/\n \/\/ \n \/\/ __KeyUpEventToKey__\n \/\/ @begin\n \/\/ KeyCode::A, ModifierFlag::SHIFT_L, (effective when A key is pressed with left shift key.)\n \/\/ @end\n \/\/\n \/\/ @begin\n \/\/ ModifierFlag::SHIFT_L (when A key is released with left shift key.)\n \/\/ KeyCode::ESCAPE, (send escape key.)\n \/\/ @end\n \/\/\n \/\/ @begin\n \/\/ KeyCode::A (when A key is released, send A key.)\n \/\/ @end\n \/\/ <\/autogen>\n \/\/\n\n void add(AddDataType datatype, AddValue newval);\n\n class Item : public List::Item {\n public:\n Item(KeyUpEventToKey& k) : keyUpEventToKey_(k) {}\n KeyUpEventToKey& get(void) { return keyUpEventToKey_; }\n\n private:\n KeyUpEventToKey& keyUpEventToKey_;\n };\n\n private:\n void doKeyUp(void);\n\n KeyToKey fromKeyToKey_;\n Vector_KeyToKey toKeyToKeys_;\n bool preserveKeyDownOrder_;\n\n \/\/ Queue for Option::KEYUPEVENTTOKEY_PRESERVE_KEYDOWN_ORDER.\n static List queue_;\n };\n }\n}\n\n#endif\nadd ~Item#ifndef KEYUPEVENTTOKEY_HPP\n#define KEYUPEVENTTOKEY_HPP\n\n#include \"KeyToKey.hpp\"\n#include \"List.hpp\"\n\nnamespace org_pqrs_KeyRemap4MacBook {\n namespace RemapFunc {\n class KeyUpEventToKey {\n public:\n static void static_initialize(void);\n static void static_terminate(void);\n\n KeyUpEventToKey(void) : preserveKeyDownOrder_(false) {}\n\n bool remap(RemapParams& remapParams);\n\n \/\/ ========================================\n \/\/ __KeyUpEventToKey__ syntax\n \/\/\n \/\/ \n \/\/ __KeyUpEventToKey__\n \/\/ @begin\n \/\/ FromEvent, FromFlags,\n \/\/ ToKeys_when_KeyDown,\n \/\/ @end\n \/\/\n \/\/ @begin\n \/\/ KeyUpFlags,\n \/\/ ToKeys_when_KeyUp,\n \/\/ @end\n \/\/\n \/\/ ...\n \/\/\n \/\/ @begin\n \/\/ KeyUpFlags,\n \/\/ ToKeys_when_KeyUp,\n \/\/ @end\n \/\/\n \/\/ <\/autogen>\n \/\/\n \/\/\n \/\/ * You can omit FromFlags, ToKeys_when_KeyDown, KeyUpFlags.\n \/\/\n \/\/ ========================================\n \/\/ Example:\n \/\/\n \/\/ \n \/\/ __KeyUpEventToKey__\n \/\/ @begin\n \/\/ KeyCode::A, ModifierFlag::SHIFT_L, (effective when A key is pressed with left shift key.)\n \/\/ @end\n \/\/\n \/\/ @begin\n \/\/ ModifierFlag::SHIFT_L (when A key is released with left shift key.)\n \/\/ KeyCode::ESCAPE, (send escape key.)\n \/\/ @end\n \/\/\n \/\/ @begin\n \/\/ KeyCode::A (when A key is released, send A key.)\n \/\/ @end\n \/\/ <\/autogen>\n \/\/\n\n void add(AddDataType datatype, AddValue newval);\n\n class Item : public List::Item {\n public:\n Item(KeyUpEventToKey& k) : keyUpEventToKey_(k) {}\n virtual ~Item(void) {}\n\n KeyUpEventToKey& get(void) { return keyUpEventToKey_; }\n\n private:\n KeyUpEventToKey& keyUpEventToKey_;\n };\n\n private:\n void doKeyUp(void);\n\n KeyToKey fromKeyToKey_;\n Vector_KeyToKey toKeyToKeys_;\n bool preserveKeyDownOrder_;\n\n \/\/ Queue for Option::KEYUPEVENTTOKEY_PRESERVE_KEYDOWN_ORDER.\n static List queue_;\n };\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*\n *\n * Copyright 2016 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n\n#include \"src\/core\/lib\/channel\/handshaker_registry.h\"\n#include \"src\/core\/lib\/gprpp\/inlined_vector.h\"\n#include \"src\/core\/lib\/gprpp\/memory.h\"\n\n#include \n#include \n\n#include \n\n\/\/\n\/\/ grpc_handshaker_factory_list\n\/\/\n\nnamespace grpc_core {\n\nnamespace {\n\nclass HandshakerFactoryList {\n public:\n void Register(bool at_start, UniquePtr factory);\n void AddHandshakers(const grpc_channel_args* args,\n grpc_pollset_set* interested_parties,\n HandshakeManager* handshake_mgr);\n\n private:\n InlinedVector, 2> factories_;\n};\n\nHandshakerFactoryList* g_handshaker_factory_lists = nullptr;\n\n} \/\/ namespace\n\nvoid HandshakerFactoryList::Register(bool at_start,\n UniquePtr factory) {\n factories_.push_back(std::move(factory));\n if (at_start) {\n auto* end = &factories_[factories_.size() - 1];\n std::rotate(&factories_[0], end, end + 1);\n }\n}\n\nvoid HandshakerFactoryList::AddHandshakers(const grpc_channel_args* args,\n grpc_pollset_set* interested_parties,\n HandshakeManager* handshake_mgr) {\n for (size_t idx = 0; idx < factories_.size(); ++idx) {\n auto& handshaker_factory = factories_[idx];\n handshaker_factory->AddHandshakers(args, interested_parties, handshake_mgr);\n }\n}\n\n\/\/\n\/\/ plugin\n\/\/\n\nvoid HandshakerRegistry::Init() {\n GPR_ASSERT(g_handshaker_factory_lists == nullptr);\n g_handshaker_factory_lists = static_cast(\n gpr_malloc(sizeof(*g_handshaker_factory_lists) * NUM_HANDSHAKER_TYPES));\n GPR_ASSERT(g_handshaker_factory_lists != nullptr);\n for (auto idx = 0; idx < NUM_HANDSHAKER_TYPES; ++idx) {\n auto factory_list = g_handshaker_factory_lists + idx;\n new (factory_list) HandshakerFactoryList();\n }\n}\n\nvoid HandshakerRegistry::Shutdown() {\n GPR_ASSERT(g_handshaker_factory_lists != nullptr);\n for (auto idx = 0; idx < NUM_HANDSHAKER_TYPES; ++idx) {\n auto factory_list = g_handshaker_factory_lists + idx;\n factory_list->~HandshakerFactoryList();\n }\n gpr_free(g_handshaker_factory_lists);\n g_handshaker_factory_lists = nullptr;\n}\n\nvoid HandshakerRegistry::RegisterHandshakerFactory(\n bool at_start, HandshakerType handshaker_type,\n UniquePtr factory) {\n GPR_ASSERT(g_handshaker_factory_lists != nullptr);\n auto& factory_list = g_handshaker_factory_lists[handshaker_type];\n factory_list.Register(at_start, std::move(factory));\n}\n\nvoid HandshakerRegistry::AddHandshakers(HandshakerType handshaker_type,\n const grpc_channel_args* args,\n grpc_pollset_set* interested_parties,\n HandshakeManager* handshake_mgr) {\n GPR_ASSERT(g_handshaker_factory_lists != nullptr);\n auto& factory_list = g_handshaker_factory_lists[handshaker_type];\n factory_list.AddHandshakers(args, interested_parties, handshake_mgr);\n}\n\n} \/\/ namespace grpc_core\ngrpc: aligned creation of handshaker factory lists\/*\n *\n * Copyright 2016 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n\n#include \"src\/core\/lib\/channel\/handshaker_registry.h\"\n#include \"src\/core\/lib\/gpr\/alloc.h\"\n#include \"src\/core\/lib\/gprpp\/inlined_vector.h\"\n#include \"src\/core\/lib\/gprpp\/memory.h\"\n\n#include \n#include \n\n#include \n\n\/\/\n\/\/ grpc_handshaker_factory_list\n\/\/\n\nnamespace grpc_core {\n\nnamespace {\n\nclass HandshakerFactoryList {\n public:\n void Register(bool at_start, UniquePtr factory);\n void AddHandshakers(const grpc_channel_args* args,\n grpc_pollset_set* interested_parties,\n HandshakeManager* handshake_mgr);\n\n private:\n InlinedVector, 2> factories_;\n};\n\nHandshakerFactoryList* g_handshaker_factory_lists = nullptr;\n\n} \/\/ namespace\n\nvoid HandshakerFactoryList::Register(bool at_start,\n UniquePtr factory) {\n factories_.push_back(std::move(factory));\n if (at_start) {\n auto* end = &factories_[factories_.size() - 1];\n std::rotate(&factories_[0], end, end + 1);\n }\n}\n\nvoid HandshakerFactoryList::AddHandshakers(const grpc_channel_args* args,\n grpc_pollset_set* interested_parties,\n HandshakeManager* handshake_mgr) {\n for (size_t idx = 0; idx < factories_.size(); ++idx) {\n auto& handshaker_factory = factories_[idx];\n handshaker_factory->AddHandshakers(args, interested_parties, handshake_mgr);\n }\n}\n\n\/\/\n\/\/ plugin\n\/\/\n\nvoid HandshakerRegistry::Init() {\n GPR_ASSERT(g_handshaker_factory_lists == nullptr);\n g_handshaker_factory_lists =\n static_cast(gpr_malloc_aligned(\n sizeof(*g_handshaker_factory_lists) * NUM_HANDSHAKER_TYPES,\n GPR_MAX_ALIGNMENT));\n\n GPR_ASSERT(g_handshaker_factory_lists != nullptr);\n for (auto idx = 0; idx < NUM_HANDSHAKER_TYPES; ++idx) {\n auto factory_list = g_handshaker_factory_lists + idx;\n new (factory_list) HandshakerFactoryList();\n }\n}\n\nvoid HandshakerRegistry::Shutdown() {\n GPR_ASSERT(g_handshaker_factory_lists != nullptr);\n for (auto idx = 0; idx < NUM_HANDSHAKER_TYPES; ++idx) {\n auto factory_list = g_handshaker_factory_lists + idx;\n factory_list->~HandshakerFactoryList();\n }\n gpr_free_aligned(g_handshaker_factory_lists);\n g_handshaker_factory_lists = nullptr;\n}\n\nvoid HandshakerRegistry::RegisterHandshakerFactory(\n bool at_start, HandshakerType handshaker_type,\n UniquePtr factory) {\n GPR_ASSERT(g_handshaker_factory_lists != nullptr);\n auto& factory_list = g_handshaker_factory_lists[handshaker_type];\n factory_list.Register(at_start, std::move(factory));\n}\n\nvoid HandshakerRegistry::AddHandshakers(HandshakerType handshaker_type,\n const grpc_channel_args* args,\n grpc_pollset_set* interested_parties,\n HandshakeManager* handshake_mgr) {\n GPR_ASSERT(g_handshaker_factory_lists != nullptr);\n auto& factory_list = g_handshaker_factory_lists[handshaker_type];\n factory_list.AddHandshakers(args, interested_parties, handshake_mgr);\n}\n\n} \/\/ namespace grpc_core\n<|endoftext|>"} {"text":"\/*\n *\n * Copyright 2015 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n\n#include \"src\/core\/lib\/iomgr\/port.h\"\n#ifdef GRPC_POSIX_SOCKET_RESOLVE_ADDRESS\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"src\/core\/lib\/event_engine\/default_event_engine.h\"\n#include \"src\/core\/lib\/gpr\/string.h\"\n#include \"src\/core\/lib\/gpr\/useful.h\"\n#include \"src\/core\/lib\/gprpp\/host_port.h\"\n#include \"src\/core\/lib\/gprpp\/thd.h\"\n#include \"src\/core\/lib\/iomgr\/block_annotate.h\"\n#include \"src\/core\/lib\/iomgr\/exec_ctx.h\"\n#include \"src\/core\/lib\/iomgr\/executor.h\"\n#include \"src\/core\/lib\/iomgr\/iomgr_internal.h\"\n#include \"src\/core\/lib\/iomgr\/resolve_address.h\"\n#include \"src\/core\/lib\/iomgr\/resolve_address_posix.h\"\n#include \"src\/core\/lib\/iomgr\/sockaddr.h\"\n#include \"src\/core\/lib\/iomgr\/unix_sockets_posix.h\"\n#include \"src\/core\/lib\/transport\/error_utils.h\"\n\nnamespace grpc_core {\nnamespace {\n\nvoid NativeDNSRequest(\n std::string name, std::string default_port,\n std::function>)>\n on_done) {\n grpc_event_engine::experimental::GetDefaultEventEngine()->Run(\n [name = std::move(name), default_port = std::move(default_port),\n on_done = std::move(on_done)]() mutable {\n ApplicationCallbackExecCtx callback_exec_ctx;\n ExecCtx exec_ctx;\n auto result =\n GetDNSResolver()->LookupHostnameBlocking(name, default_port);\n \/\/ running inline is safe since we've already been scheduled on the\n \/\/ executor\n on_done(std::move(result));\n });\n}\n\n} \/\/ namespace\n\nDNSResolver::TaskHandle NativeDNSResolver::LookupHostname(\n std::function>)>\n on_done,\n absl::string_view name, absl::string_view default_port,\n Duration \/* timeout *\/, grpc_pollset_set* \/* interested_parties *\/,\n absl::string_view \/* name_server *\/) {\n NativeDNSRequest(std::string(name), std::string(default_port),\n std::move(on_done));\n return kNullHandle;\n}\n\nabsl::StatusOr>\nNativeDNSResolver::LookupHostnameBlocking(absl::string_view name,\n absl::string_view default_port) {\n ExecCtx exec_ctx;\n struct addrinfo hints;\n struct addrinfo *result = nullptr, *resp;\n int s;\n size_t i;\n grpc_error_handle err;\n std::vector addresses;\n std::string host;\n std::string port;\n \/\/ parse name, splitting it into host and port parts\n SplitHostPort(name, &host, &port);\n if (host.empty()) {\n err = grpc_error_set_str(GRPC_ERROR_CREATE(\"unparseable host:port\"),\n StatusStrProperty::kTargetAddress, name);\n goto done;\n }\n if (port.empty()) {\n if (default_port.empty()) {\n err = grpc_error_set_str(GRPC_ERROR_CREATE(\"no port in name\"),\n StatusStrProperty::kTargetAddress, name);\n goto done;\n }\n port = std::string(default_port);\n }\n \/\/ Call getaddrinfo\n memset(&hints, 0, sizeof(hints));\n hints.ai_family = AF_UNSPEC; \/* ipv4 or ipv6 *\/\n hints.ai_socktype = SOCK_STREAM; \/* stream socket *\/\n hints.ai_flags = AI_PASSIVE; \/* for wildcard IP address *\/\n GRPC_SCHEDULING_START_BLOCKING_REGION;\n s = getaddrinfo(host.c_str(), port.c_str(), &hints, &result);\n GRPC_SCHEDULING_END_BLOCKING_REGION;\n if (s != 0) {\n \/\/ Retry if well-known service name is recognized\n const char* svc[][2] = {{\"http\", \"80\"}, {\"https\", \"443\"}};\n for (i = 0; i < GPR_ARRAY_SIZE(svc); i++) {\n if (port == svc[i][0]) {\n GRPC_SCHEDULING_START_BLOCKING_REGION;\n s = getaddrinfo(host.c_str(), svc[i][1], &hints, &result);\n GRPC_SCHEDULING_END_BLOCKING_REGION;\n break;\n }\n }\n }\n if (s != 0) {\n err = grpc_error_set_str(\n grpc_error_set_str(\n grpc_error_set_str(\n grpc_error_set_int(GRPC_ERROR_CREATE(gai_strerror(s)),\n StatusIntProperty::kErrorNo, s),\n StatusStrProperty::kOsError, gai_strerror(s)),\n StatusStrProperty::kSyscall, \"getaddrinfo\"),\n StatusStrProperty::kTargetAddress, name);\n goto done;\n }\n \/\/ Success path: fill in addrs\n for (resp = result; resp != nullptr; resp = resp->ai_next) {\n grpc_resolved_address addr;\n memcpy(&addr.addr, resp->ai_addr, resp->ai_addrlen);\n addr.len = resp->ai_addrlen;\n addresses.push_back(addr);\n }\n err = absl::OkStatus();\ndone:\n if (result) {\n freeaddrinfo(result);\n }\n if (err.ok()) {\n return addresses;\n }\n auto error_result = grpc_error_to_absl_status(err);\n return error_result;\n}\n\nDNSResolver::TaskHandle NativeDNSResolver::LookupSRV(\n std::function>)>\n on_resolved,\n absl::string_view \/* name *\/, Duration \/* timeout *\/,\n grpc_pollset_set* \/* interested_parties *\/,\n absl::string_view \/* name_server *\/) {\n grpc_event_engine::experimental::GetDefaultEventEngine()->Run([on_resolved] {\n ApplicationCallbackExecCtx app_exec_ctx;\n ExecCtx exec_ctx;\n on_resolved(absl::UnimplementedError(\n \"The Native resolver does not support looking up SRV records\"));\n });\n return {-1, -1};\n};\n\nDNSResolver::TaskHandle NativeDNSResolver::LookupTXT(\n std::function)> on_resolved,\n absl::string_view \/* name *\/, Duration \/* timeout *\/,\n grpc_pollset_set* \/* interested_parties *\/,\n absl::string_view \/* name_server *\/) {\n \/\/ Not supported\n grpc_event_engine::experimental::GetDefaultEventEngine()->Run([on_resolved] {\n ApplicationCallbackExecCtx app_exec_ctx;\n ExecCtx exec_ctx;\n on_resolved(absl::UnimplementedError(\n \"The Native resolver does not support looking up TXT records\"));\n });\n return {-1, -1};\n};\n\nbool NativeDNSResolver::Cancel(TaskHandle \/*handle*\/) { return false; }\n\n} \/\/ namespace grpc_core\n\n#endif\nRevert \"[event_engine] Move DNS resolution executor usage to event engine (#31230)\" (#31307)\/*\n *\n * Copyright 2015 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n\n#include \"src\/core\/lib\/iomgr\/port.h\"\n#ifdef GRPC_POSIX_SOCKET_RESOLVE_ADDRESS\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"src\/core\/lib\/event_engine\/default_event_engine.h\"\n#include \"src\/core\/lib\/gpr\/string.h\"\n#include \"src\/core\/lib\/gpr\/useful.h\"\n#include \"src\/core\/lib\/gprpp\/host_port.h\"\n#include \"src\/core\/lib\/gprpp\/thd.h\"\n#include \"src\/core\/lib\/iomgr\/block_annotate.h\"\n#include \"src\/core\/lib\/iomgr\/exec_ctx.h\"\n#include \"src\/core\/lib\/iomgr\/executor.h\"\n#include \"src\/core\/lib\/iomgr\/iomgr_internal.h\"\n#include \"src\/core\/lib\/iomgr\/resolve_address.h\"\n#include \"src\/core\/lib\/iomgr\/resolve_address_posix.h\"\n#include \"src\/core\/lib\/iomgr\/sockaddr.h\"\n#include \"src\/core\/lib\/iomgr\/unix_sockets_posix.h\"\n#include \"src\/core\/lib\/transport\/error_utils.h\"\n\nnamespace grpc_core {\nnamespace {\n\nclass NativeDNSRequest {\n public:\n NativeDNSRequest(\n absl::string_view name, absl::string_view default_port,\n std::function>)>\n on_done)\n : name_(name), default_port_(default_port), on_done_(std::move(on_done)) {\n GRPC_CLOSURE_INIT(&request_closure_, DoRequestThread, this, nullptr);\n Executor::Run(&request_closure_, absl::OkStatus(), ExecutorType::RESOLVER);\n }\n\n private:\n \/\/ Callback to be passed to grpc Executor to asynch-ify\n \/\/ LookupHostnameBlocking\n static void DoRequestThread(void* rp, grpc_error_handle \/*error*\/) {\n NativeDNSRequest* r = static_cast(rp);\n auto result =\n GetDNSResolver()->LookupHostnameBlocking(r->name_, r->default_port_);\n \/\/ running inline is safe since we've already been scheduled on the executor\n r->on_done_(std::move(result));\n delete r;\n }\n\n const std::string name_;\n const std::string default_port_;\n const std::function>)>\n on_done_;\n grpc_closure request_closure_;\n};\n\n} \/\/ namespace\n\nDNSResolver::TaskHandle NativeDNSResolver::LookupHostname(\n std::function>)>\n on_done,\n absl::string_view name, absl::string_view default_port,\n Duration \/* timeout *\/, grpc_pollset_set* \/* interested_parties *\/,\n absl::string_view \/* name_server *\/) {\n \/\/ self-deleting class\n new NativeDNSRequest(name, default_port, std::move(on_done));\n return kNullHandle;\n}\n\nabsl::StatusOr>\nNativeDNSResolver::LookupHostnameBlocking(absl::string_view name,\n absl::string_view default_port) {\n ExecCtx exec_ctx;\n struct addrinfo hints;\n struct addrinfo *result = nullptr, *resp;\n int s;\n size_t i;\n grpc_error_handle err;\n std::vector addresses;\n std::string host;\n std::string port;\n \/\/ parse name, splitting it into host and port parts\n SplitHostPort(name, &host, &port);\n if (host.empty()) {\n err = grpc_error_set_str(GRPC_ERROR_CREATE(\"unparseable host:port\"),\n StatusStrProperty::kTargetAddress, name);\n goto done;\n }\n if (port.empty()) {\n if (default_port.empty()) {\n err = grpc_error_set_str(GRPC_ERROR_CREATE(\"no port in name\"),\n StatusStrProperty::kTargetAddress, name);\n goto done;\n }\n port = std::string(default_port);\n }\n \/\/ Call getaddrinfo\n memset(&hints, 0, sizeof(hints));\n hints.ai_family = AF_UNSPEC; \/* ipv4 or ipv6 *\/\n hints.ai_socktype = SOCK_STREAM; \/* stream socket *\/\n hints.ai_flags = AI_PASSIVE; \/* for wildcard IP address *\/\n GRPC_SCHEDULING_START_BLOCKING_REGION;\n s = getaddrinfo(host.c_str(), port.c_str(), &hints, &result);\n GRPC_SCHEDULING_END_BLOCKING_REGION;\n if (s != 0) {\n \/\/ Retry if well-known service name is recognized\n const char* svc[][2] = {{\"http\", \"80\"}, {\"https\", \"443\"}};\n for (i = 0; i < GPR_ARRAY_SIZE(svc); i++) {\n if (port == svc[i][0]) {\n GRPC_SCHEDULING_START_BLOCKING_REGION;\n s = getaddrinfo(host.c_str(), svc[i][1], &hints, &result);\n GRPC_SCHEDULING_END_BLOCKING_REGION;\n break;\n }\n }\n }\n if (s != 0) {\n err = grpc_error_set_str(\n grpc_error_set_str(\n grpc_error_set_str(\n grpc_error_set_int(GRPC_ERROR_CREATE(gai_strerror(s)),\n StatusIntProperty::kErrorNo, s),\n StatusStrProperty::kOsError, gai_strerror(s)),\n StatusStrProperty::kSyscall, \"getaddrinfo\"),\n StatusStrProperty::kTargetAddress, name);\n goto done;\n }\n \/\/ Success path: fill in addrs\n for (resp = result; resp != nullptr; resp = resp->ai_next) {\n grpc_resolved_address addr;\n memcpy(&addr.addr, resp->ai_addr, resp->ai_addrlen);\n addr.len = resp->ai_addrlen;\n addresses.push_back(addr);\n }\n err = absl::OkStatus();\ndone:\n if (result) {\n freeaddrinfo(result);\n }\n if (err.ok()) {\n return addresses;\n }\n auto error_result = grpc_error_to_absl_status(err);\n return error_result;\n}\n\nDNSResolver::TaskHandle NativeDNSResolver::LookupSRV(\n std::function>)>\n on_resolved,\n absl::string_view \/* name *\/, Duration \/* timeout *\/,\n grpc_pollset_set* \/* interested_parties *\/,\n absl::string_view \/* name_server *\/) {\n grpc_event_engine::experimental::GetDefaultEventEngine()->Run([on_resolved] {\n ApplicationCallbackExecCtx app_exec_ctx;\n ExecCtx exec_ctx;\n on_resolved(absl::UnimplementedError(\n \"The Native resolver does not support looking up SRV records\"));\n });\n return {-1, -1};\n};\n\nDNSResolver::TaskHandle NativeDNSResolver::LookupTXT(\n std::function)> on_resolved,\n absl::string_view \/* name *\/, Duration \/* timeout *\/,\n grpc_pollset_set* \/* interested_parties *\/,\n absl::string_view \/* name_server *\/) {\n \/\/ Not supported\n grpc_event_engine::experimental::GetDefaultEventEngine()->Run([on_resolved] {\n ApplicationCallbackExecCtx app_exec_ctx;\n ExecCtx exec_ctx;\n on_resolved(absl::UnimplementedError(\n \"The Native resolver does not support looking up TXT records\"));\n });\n return {-1, -1};\n};\n\nbool NativeDNSResolver::Cancel(TaskHandle \/*handle*\/) { return false; }\n\n} \/\/ namespace grpc_core\n\n#endif\n<|endoftext|>"} {"text":"#include \"ros\/ros.h\"\n#include \"servo_msgs\/KrsServoDegree.h\"\n\n#include \n\n#include \"krs_servo_driver.hpp\"\n\nclass KrsServoNode {\npublic:\n KrsServoNode();\n explicit KrsServoNode(ros::NodeHandle& nh, const char* path);\n\nprivate:\n void krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg);\n\n ros::Subscriber sub;\n KrsServoDriver krs;\n};\n\nint main(int argc, char** argv) {\n ros::init(argc, argv, \"krs_servo_node\");\n ros::NodeHandle nh;\n\n std::string path;\n nh.param(\"serial_path\", path, \"\/dev\/ttyUSB0\");\n\n KrsServoNode ksn(nh, path.c_str());\n\n ros::spin();\n return 0;\n}\n\nKrsServoNode::KrsServoNode()\n : krs()\n{}\n\nKrsServoNode::KrsServoNode(ros::NodeHandle& nh, const char* path)\n : krs(path)\n{\n sub = nh.subscribe(\"cmd_krs\", 16, &KrsServoNode::krsServoDegreeCallback, this);\n}\n\nvoid KrsServoNode::krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg) {\n krs.sendAngle(msg->id, msg->angle);\n}\nRemove explicit by constructor has too many args.#include \"ros\/ros.h\"\n#include \"servo_msgs\/KrsServoDegree.h\"\n\n#include \n\n#include \"krs_servo_driver.hpp\"\n\nclass KrsServoNode {\npublic:\n KrsServoNode();\n KrsServoNode(ros::NodeHandle& nh, const char* path);\n\nprivate:\n void krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg);\n\n ros::Subscriber sub;\n KrsServoDriver krs;\n};\n\nint main(int argc, char** argv) {\n ros::init(argc, argv, \"krs_servo_node\");\n ros::NodeHandle nh;\n\n std::string path;\n nh.param(\"serial_path\", path, \"\/dev\/ttyUSB0\");\n\n KrsServoNode ksn(nh, path.c_str());\n\n ros::spin();\n return 0;\n}\n\nKrsServoNode::KrsServoNode()\n : krs()\n{}\n\nKrsServoNode::KrsServoNode(ros::NodeHandle& nh, const char* path)\n : krs(path)\n{\n sub = nh.subscribe(\"cmd_krs\", 16, &KrsServoNode::krsServoDegreeCallback, this);\n}\n\nvoid KrsServoNode::krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg) {\n krs.sendAngle(msg->id, msg->angle);\n}\n<|endoftext|>"} {"text":"#include \"drivers\/ublox_neo7.hpp\"\n\n#include \n#include \n\n#include \"chprintf.h\"\n#include \"unit_config.hpp\"\n\nconst char NMEA_LF = '\\n';\nconst char *NMEA_DELIMS = \",\\0\";\n\nstruct GPGLLMessage {\n float lon;\n char lonDir;\n float lat;\n char latDir;\n float utc;\n char valid;\n};\n\nvoid UBloxNEO7::init() {\n}\n\nGPSReading UBloxNEO7::readGPS() {\n \/\/ Read all available bytes until the newline character. NMEA dictates that\n \/\/ messages should end with a CRLF, but we'll only look for the LF.\n std::size_t len = readUntil(NMEA_LF);\n\n \/\/ Check if a full line is ready to be processed\n if(len > 0) {\n char *start = reinterpret_cast(rxbuf.data());\n\n \/\/ Skip over the leading \"$\"\n start += 1;\n\n char *token = std::strtok(start, NMEA_DELIMS);\n\n \/\/ Only care about GPGLL messages\n if(std::strcmp(\"GPGLL\", token) == 0) {\n GPGLLMessage message;\n int position = 0;\n\n while(token != nullptr) {\n token = std::strtok(nullptr, NMEA_DELIMS);\n\n switch(position++) {\n case 0:\n message.lon = atof(token);\n break;\n case 1:\n message.lonDir = token[0];\n break;\n case 2:\n message.lat = atof(token);\n break;\n case 3:\n message.latDir = token[0];\n break;\n case 4:\n message.utc = atof(token);\n break;\n case 5:\n message.valid = token[0];\n break;\n };\n }\n\n return GPSReading {\n .valid = true,\n .lat = message.lat,\n .lon = message.lon\n };\n }\n } else {\n \/\/ TODO: Return previous message with old timestamp.\n return GPSReading {\n .valid = false,\n .lat = 0.0,\n .lon = 0.0\n };\n }\n}\nrefs #7 Swap lat\/lon.#include \"drivers\/ublox_neo7.hpp\"\n\n#include \n#include \n\n#include \"chprintf.h\"\n#include \"unit_config.hpp\"\n\nconst char NMEA_LF = '\\n';\nconst char *NMEA_DELIMS = \",\\0\";\n\nstruct GPGLLMessage {\n float lon;\n char lonDir;\n float lat;\n char latDir;\n float utc;\n char valid;\n};\n\nvoid UBloxNEO7::init() {\n}\n\nGPSReading UBloxNEO7::readGPS() {\n \/\/ Read all available bytes until the newline character. NMEA dictates that\n \/\/ messages should end with a CRLF, but we'll only look for the LF.\n std::size_t len = readUntil(NMEA_LF);\n\n \/\/ Check if a full line is ready to be processed\n if(len > 0) {\n char *start = reinterpret_cast(rxbuf.data());\n\n \/\/ Skip over the leading \"$\"\n start += 1;\n\n char *token = std::strtok(start, NMEA_DELIMS);\n\n \/\/ Only care about GPGLL messages\n if(std::strcmp(\"GPGLL\", token) == 0) {\n GPGLLMessage message;\n int position = 0;\n\n while(token != nullptr) {\n token = std::strtok(nullptr, NMEA_DELIMS);\n\n switch(position++) {\n case 0:\n message.lat = atof(token);\n break;\n case 1:\n message.latDir = token[0];\n break;\n case 2:\n message.lon = atof(token);\n break;\n case 3:\n message.lonDir = token[0];\n break;\n case 4:\n message.utc = atof(token);\n break;\n case 5:\n message.valid = token[0];\n break;\n };\n }\n\n return GPSReading {\n .valid = true,\n .lat = message.lat,\n .lon = message.lon\n };\n }\n } else {\n \/\/ TODO: Return previous message with old timestamp.\n return GPSReading {\n .valid = false,\n .lat = 0.0,\n .lon = 0.0\n };\n }\n}\n<|endoftext|>"} {"text":"\/*\n * colormapwidget.cpp\n *\n * Created on: Jan 29, 2013\n * Author: schurade\n *\/\n#include \n\n#include \"colormapwidget.h\"\n\nColormapWidget::ColormapWidget( int width ) :\n m_colormap( FNCM_GRAY ),\n m_width( width ),\n m_lowerThreshold( 0.0 ),\n m_upperThreshold( 1.0 )\n{\n QVBoxLayout* vLayout = new QVBoxLayout();\n\n\/\/ QHBoxLayout* hLayout = new QHBoxLayout();\n\/\/ m_nlabel = new QLabel( QString(\"colormap\"), this );\n\/\/ hLayout->addWidget( m_nlabel );\n\/\/ hLayout->addStretch();\n\n QHBoxLayout* hLayout2 = new QHBoxLayout();\n m_nlabel = new QLabel( this );\n\n m_image = createImage( width );\n QPixmap pix( width, 20 );\n pix.convertFromImage( *m_image );\n m_nlabel->setPixmap( pix );\n hLayout2->addWidget( m_nlabel );\n\n \/\/vLayout->addLayout( hLayout );\n vLayout->addLayout( hLayout2 );\n vLayout->setContentsMargins( 1,1,1,1 );\n\n setLayout( vLayout );\n\n setFrameStyle( QFrame::Panel | QFrame::Raised );\n\n setStyleSheet( \"QLabel { font: bold 12px; margin-bottom: -1px }\"\n \"QLineEdit { font: 12px; max-height: 14px; margin-top: -1px }\"\n );\n}\n\nColormapWidget::~ColormapWidget()\n{\n}\n\nQImage* ColormapWidget::createImage( int width )\n{\n QImage* image = new QImage( width, 20, QImage::Format_RGB32 );\n\n for ( int i = 0; i < width; ++i )\n {\n QColor c;\n int g = 0;\n switch ( m_colormap )\n {\n case FNCM_RAINBOW1:\n c = colormap1( (float)i \/ (float)width );\n break;\n case FNCM_RAINBOW2:\n c = colormap2( (float)i \/ (float)width );\n break;\n case FNCM_BLUEWHITERED:\n c = colormap3( (float)i \/ (float)width );\n break;\n default:\n g = (float)i \/ (float)width * 255;\n c = QColor( g, g, g );\n break;\n }\n for ( int k = 0; k < 20; ++k )\n {\n image->setPixel( i, k, c.rgba() );\n }\n }\n\n return image;\n}\n\nQColor ColormapWidget::colormap1( float value )\n{\n value = ( value - m_lowerThreshold ) \/ ( m_upperThreshold - m_lowerThreshold );\n\n value = qMax( 0.0f, qMin( 1.0f, value ) );\n value *= 5.0;\n float r = 0.0;\n float g = 0.0;\n float b = 0.0;\n if( value < 1.0 )\n {\n g = value;\n b = 1.0f;\n }\n else if( value < 2.0 )\n {\n g = 1.0;\n b = 2.0 -value;\n }\n else if( value < 3.0 )\n {\n r = value-2.0;\n g = 1.0;\n }\n else if( value < 4.0 )\n {\n r = 1.0;\n g = 4.0-value;\n }\n else\n {\n r = 1.0;\n b = value-4.0;\n }\n return QColor( 255 * r, 255 * g, 255 * b );\n}\n\nQColor ColormapWidget::colormap2( float value )\n{\n value = ( value - m_lowerThreshold ) \/ ( m_upperThreshold - m_lowerThreshold );\n\n value = qMax( 0.0f, qMin( 1.0f, value ) );\n value *= 6.0;\n float r = 0.0;\n float g = 0.0;\n float b = 0.0;\n if( value < 2.0 )\n {\n g = value * 0.5f;\n b = 1.0f;\n }\n else if( value < 3.0 )\n {\n g = 1.0;\n b = 3.0 -value;\n }\n else if( value < 4.0 )\n {\n r = value-3.0;\n g = 1.0;\n }\n else if( value < 6.0 )\n {\n r = 1.0;\n g = 0.5f * ( 6.0-value );\n }\n else\n {\n r = 1.0;\n }\n return QColor( 255 * r, 255 * g, 255 * b );\n}\n\nQColor ColormapWidget::colormap3( float value )\n{\n value = ( value - m_lowerThreshold ) \/ ( m_upperThreshold - m_lowerThreshold );\n\n value = qMax( 0.0f, qMin( 1.0f, value ) );\n value *= 2.0;\n float r = 0.0;\n float g = 0.0;\n float b = 0.0;\n if( value < 1.0 )\n {\n r = value;\n g = value;\n b = 1.0;\n }\n else if( value <= 2.0 )\n {\n r = 1.0;\n g = 2.0-value;\n b = 2.0-value;\n }\n else\n {\n r = 1.0;\n }\n return QColor( 255 * r, 255 * g, 255 * b );\n}\n\nvoid ColormapWidget::setLowerThreshold( float value )\n{\n value = qMax( 0.0f, qMin( 1.0f, value ) );\n m_lowerThreshold = value;\n m_image = createImage( m_width );\n QPixmap pix( m_width, 20 );\n pix.convertFromImage( *m_image );\n m_nlabel->setPixmap( pix );\n}\n\nvoid ColormapWidget::setUpperThreshold( float value )\n{\n value = qMax( 0.0f, qMin( 1.0f, value ) );\n m_upperThreshold = value;\n m_image = createImage( m_width );\n QPixmap pix( m_width, 20 );\n pix.convertFromImage( *m_image );\n m_nlabel->setPixmap( pix );\n}\n\nvoid ColormapWidget::setColormap( int value )\n{\n m_colormap = qMin( (FN_COLORMAP)value, FNCM_NOCOLORMAP );\n m_image = createImage( m_width );\n QPixmap pix( m_width, 20 );\n pix.convertFromImage( *m_image );\n m_nlabel->setPixmap( pix );\n}\nchange colormapwidget for grayscale too\/*\n * colormapwidget.cpp\n *\n * Created on: Jan 29, 2013\n * Author: schurade\n *\/\n#include \n\n#include \"colormapwidget.h\"\n\nColormapWidget::ColormapWidget( int width ) :\n m_colormap( FNCM_GRAY ),\n m_width( width ),\n m_lowerThreshold( 0.0 ),\n m_upperThreshold( 1.0 )\n{\n QVBoxLayout* vLayout = new QVBoxLayout();\n\n\/\/ QHBoxLayout* hLayout = new QHBoxLayout();\n\/\/ m_nlabel = new QLabel( QString(\"colormap\"), this );\n\/\/ hLayout->addWidget( m_nlabel );\n\/\/ hLayout->addStretch();\n\n QHBoxLayout* hLayout2 = new QHBoxLayout();\n m_nlabel = new QLabel( this );\n\n m_image = createImage( width );\n QPixmap pix( width, 20 );\n pix.convertFromImage( *m_image );\n m_nlabel->setPixmap( pix );\n hLayout2->addWidget( m_nlabel );\n\n \/\/vLayout->addLayout( hLayout );\n vLayout->addLayout( hLayout2 );\n vLayout->setContentsMargins( 1,1,1,1 );\n\n setLayout( vLayout );\n\n setFrameStyle( QFrame::Panel | QFrame::Raised );\n\n setStyleSheet( \"QLabel { font: bold 12px; margin-bottom: -1px }\"\n \"QLineEdit { font: 12px; max-height: 14px; margin-top: -1px }\"\n );\n}\n\nColormapWidget::~ColormapWidget()\n{\n}\n\nQImage* ColormapWidget::createImage( int width )\n{\n QImage* image = new QImage( width, 20, QImage::Format_RGB32 );\n\n for ( int i = 0; i < width; ++i )\n {\n QColor c;\n int g = 0;\n switch ( m_colormap )\n {\n case FNCM_RAINBOW1:\n c = colormap1( (float)i \/ (float)width );\n break;\n case FNCM_RAINBOW2:\n c = colormap2( (float)i \/ (float)width );\n break;\n case FNCM_BLUEWHITERED:\n c = colormap3( (float)i \/ (float)width );\n break;\n default:\n g = qMin( 255.0f, qMax( 0.0f, ( (float)i \/ (float)width - m_lowerThreshold ) \/ ( m_upperThreshold - m_lowerThreshold ) * 255 ) );\n c = QColor( g, g, g );\n break;\n }\n for ( int k = 0; k < 20; ++k )\n {\n image->setPixel( i, k, c.rgba() );\n }\n }\n\n return image;\n}\n\nQColor ColormapWidget::colormap1( float value )\n{\n value = ( value - m_lowerThreshold ) \/ ( m_upperThreshold - m_lowerThreshold );\n\n value = qMax( 0.0f, qMin( 1.0f, value ) );\n value *= 5.0;\n float r = 0.0;\n float g = 0.0;\n float b = 0.0;\n if( value < 1.0 )\n {\n g = value;\n b = 1.0f;\n }\n else if( value < 2.0 )\n {\n g = 1.0;\n b = 2.0 -value;\n }\n else if( value < 3.0 )\n {\n r = value-2.0;\n g = 1.0;\n }\n else if( value < 4.0 )\n {\n r = 1.0;\n g = 4.0-value;\n }\n else\n {\n r = 1.0;\n b = value-4.0;\n }\n return QColor( 255 * r, 255 * g, 255 * b );\n}\n\nQColor ColormapWidget::colormap2( float value )\n{\n value = ( value - m_lowerThreshold ) \/ ( m_upperThreshold - m_lowerThreshold );\n\n value = qMax( 0.0f, qMin( 1.0f, value ) );\n value *= 6.0;\n float r = 0.0;\n float g = 0.0;\n float b = 0.0;\n if( value < 2.0 )\n {\n g = value * 0.5f;\n b = 1.0f;\n }\n else if( value < 3.0 )\n {\n g = 1.0;\n b = 3.0 -value;\n }\n else if( value < 4.0 )\n {\n r = value-3.0;\n g = 1.0;\n }\n else if( value < 6.0 )\n {\n r = 1.0;\n g = 0.5f * ( 6.0-value );\n }\n else\n {\n r = 1.0;\n }\n return QColor( 255 * r, 255 * g, 255 * b );\n}\n\nQColor ColormapWidget::colormap3( float value )\n{\n value = ( value - m_lowerThreshold ) \/ ( m_upperThreshold - m_lowerThreshold );\n\n value = qMax( 0.0f, qMin( 1.0f, value ) );\n value *= 2.0;\n float r = 0.0;\n float g = 0.0;\n float b = 0.0;\n if( value < 1.0 )\n {\n r = value;\n g = value;\n b = 1.0;\n }\n else if( value <= 2.0 )\n {\n r = 1.0;\n g = 2.0-value;\n b = 2.0-value;\n }\n else\n {\n r = 1.0;\n }\n return QColor( 255 * r, 255 * g, 255 * b );\n}\n\nvoid ColormapWidget::setLowerThreshold( float value )\n{\n value = qMax( 0.0f, qMin( 1.0f, value ) );\n m_lowerThreshold = value;\n m_image = createImage( m_width );\n QPixmap pix( m_width, 20 );\n pix.convertFromImage( *m_image );\n m_nlabel->setPixmap( pix );\n}\n\nvoid ColormapWidget::setUpperThreshold( float value )\n{\n value = qMax( 0.0f, qMin( 1.0f, value ) );\n m_upperThreshold = value;\n m_image = createImage( m_width );\n QPixmap pix( m_width, 20 );\n pix.convertFromImage( *m_image );\n m_nlabel->setPixmap( pix );\n}\n\nvoid ColormapWidget::setColormap( int value )\n{\n m_colormap = qMin( (FN_COLORMAP)value, FNCM_NOCOLORMAP );\n m_image = createImage( m_width );\n QPixmap pix( m_width, 20 );\n pix.convertFromImage( *m_image );\n m_nlabel->setPixmap( pix );\n}\n<|endoftext|>"} {"text":"#include \"h264.h\"\n#include \n#include \n#include \"bitfields.h\"\n#include \"bitstream.h\"\n#include \"defines.h\"\n\nnamespace h264 {\n std::deque analysePackets(const char * data, unsigned long len){\n std::deque res;\n\n int offset = 0;\n \/\/Make sure entire packet is within len\n while (offset+5 < len && Bit::btohl(data + offset)+offset+4 <= len){\n nalu::nalData entry;\n entry.nalSize = Bit::btohl(data + offset);\n entry.nalType = (data + offset)[4] & 0x1F;\n res.push_back(entry);\n offset += entry.nalSize + 4;\n }\n return res;\n }\n \n unsigned long toAnnexB(const char * data, unsigned long dataSize, char *& result){\n \/\/toAnnexB keeps the same size.\n if (!result){\n result = (char *)malloc(dataSize);\n }\n int offset = 0;\n while (offset < dataSize){\n \/\/Read unit size\n unsigned long unitSize = Bit::btohl(data + offset);\n \/\/Write annex b header\n memset(result + offset, 0x00, 3);\n result[offset + 3] = 0x01;\n \/\/Copy the nal unit\n memcpy(result + offset + 4, data + offset + 4, unitSize);\n \/\/Update the offset\n offset += 4 + unitSize;\n }\n return dataSize;\n }\n\n unsigned long fromAnnexB(const char * data, unsigned long dataSize, char *& result){\n const char * lastCheck = data + dataSize - 3;\n if (!result){\n FAIL_MSG(\"No output buffer given to FromAnnexB\");\n return 0;\n }\n int offset = 0;\n int newOffset = 0;\n while (offset < dataSize){\n const char * begin = data + offset;\n while ( begin < lastCheck && !(!begin[0] && !begin[1] && begin[2] == 0x01)){\n begin++;\n if (begin < lastCheck && begin[0]){\n begin++;\n }\n }\n begin += 3;\/\/Initialize begin after the first 0x000001 pattern.\n if (begin > data + dataSize){\n offset = dataSize;\n continue;\n }\n const char * end = (const char*)memmem(begin, dataSize - (begin - data), \"\\000\\000\\001\", 3);\n if (!end) {\n end = data + dataSize;\n }\n \/\/Check for 4-byte lead in's. Yes, we access -1 here\n if (end > begin && end[-1] == 0x00){\n end--;\n }\n unsigned int nalSize = end - begin;\n Bit::htobl(result + newOffset, nalSize);\n memcpy(result + newOffset + 4, begin, nalSize);\n\n newOffset += 4 + nalSize;\n offset = end - data;\n }\n return newOffset;\n }\n\n sequenceParameterSet::sequenceParameterSet(const char * _data, unsigned long _dataLen) : data(_data), dataLen(_dataLen) {}\n\n \/\/DTSC Initdata is the payload for an avcc box. init[8+] is data, init[6-7] is a network-encoded length\n void sequenceParameterSet::fromDTSCInit(const std::string & dtscInit){\n data = dtscInit.data() + 8;\n dataLen = Bit::btohs(dtscInit.data() + 6);\n }\n\n SPSMeta sequenceParameterSet::getCharacteristics() const {\n SPSMeta result;\n\n \/\/For calculating width\n unsigned int widthInMbs = 0;\n unsigned int cropHorizontal = 0;\n\n \/\/For calculating height\n bool mbsOnlyFlag = 0;\n unsigned int heightInMapUnits = 0;\n unsigned int cropVertical = 0;\n\n \/\/Fill the bitstream\n Utils::bitstream bs;\n for (unsigned int i = 1; i < dataLen; i++) {\n if (i + 2 < dataLen && (memcmp(data + i, \"\\000\\000\\003\", 3) == 0)){\/\/Emulation prevention bytes\n \/\/Yes, we increase i here\n bs.append(data + i, 2);\n i += 2;\n } else {\n \/\/No we don't increase i here\n bs.append(data + i, 1);\n }\n }\n\n char profileIdc = bs.get(8);\n result.profile = profileIdc;\n \/\/Start skipping unused data\n bs.skip(8);\n result.level = bs.get(8);\n bs.getUExpGolomb();\n if (profileIdc == 100 || profileIdc == 110 || profileIdc == 122 || profileIdc == 244 || profileIdc == 44 || profileIdc == 83 || profileIdc == 86 || profileIdc == 118 || profileIdc == 128) {\n \/\/chroma format idc\n if (bs.getUExpGolomb() == 3) {\n bs.skip(1);\n }\n bs.getUExpGolomb();\n bs.getUExpGolomb();\n bs.skip(1);\n if (bs.get(1)) {\n DEBUG_MSG(DLVL_DEVEL, \"Scaling matrix not implemented yet\");\n }\n }\n bs.getUExpGolomb();\n unsigned int pic_order_cnt_type = bs.getUExpGolomb();\n if (!pic_order_cnt_type) {\n bs.getUExpGolomb();\n } else if (pic_order_cnt_type == 1) {\n DEBUG_MSG(DLVL_DEVEL, \"This part of the implementation is incomplete(2), to be continued. If this message is shown, contact developers immediately.\");\n }\n bs.getUExpGolomb();\n bs.skip(1);\n \/\/Stop skipping data and start doing usefull stuff\n\n\n widthInMbs = bs.getUExpGolomb() + 1;\n heightInMapUnits = bs.getUExpGolomb() + 1;\n\n mbsOnlyFlag = bs.get(1);\/\/Gets used in height calculation\n if (!mbsOnlyFlag) {\n bs.skip(1);\n }\n bs.skip(1);\n \/\/cropping flag\n if (bs.get(1)) {\n cropHorizontal = bs.getUExpGolomb();\/\/leftOffset\n cropHorizontal += bs.getUExpGolomb();\/\/rightOffset\n cropVertical = bs.getUExpGolomb();\/\/topOffset\n cropVertical += bs.getUExpGolomb();\/\/bottomOffset\n }\n\n \/\/vuiParameters\n if (bs.get(1)) {\n \/\/Skipping all the paramters we dont use\n if (bs.get(1)) {\n if (bs.get(8) == 255) {\n bs.skip(32);\n }\n }\n if (bs.get(1)) {\n bs.skip(1);\n }\n if (bs.get(1)) {\n bs.skip(4);\n if (bs.get(1)) {\n bs.skip(24);\n }\n }\n if (bs.get(1)) {\n bs.getUExpGolomb();\n bs.getUExpGolomb();\n }\n\n \/\/Decode timing info\n if (bs.get(1)) {\n unsigned int unitsInTick = bs.get(32);\n unsigned int timeScale = bs.get(32);\n result.fps = (double)timeScale \/ (2 * unitsInTick);\n bs.skip(1);\n }\n }\n\n result.width = (widthInMbs * 16) - (cropHorizontal * 2);\n result.height = ((mbsOnlyFlag ? 1 : 2) * heightInMapUnits * 16) - (cropVertical * 2);\n return result;\n }\n\n}\n\nSkip over the h264 scaling list when it is present.#include \"h264.h\"\n#include \n#include \n#include \"bitfields.h\"\n#include \"bitstream.h\"\n#include \"defines.h\"\n\nnamespace h264 {\n std::deque analysePackets(const char * data, unsigned long len){\n std::deque res;\n\n int offset = 0;\n \/\/Make sure entire packet is within len\n while (offset+5 < len && Bit::btohl(data + offset)+offset+4 <= len){\n nalu::nalData entry;\n entry.nalSize = Bit::btohl(data + offset);\n entry.nalType = (data + offset)[4] & 0x1F;\n res.push_back(entry);\n offset += entry.nalSize + 4;\n }\n return res;\n }\n \n unsigned long toAnnexB(const char * data, unsigned long dataSize, char *& result){\n \/\/toAnnexB keeps the same size.\n if (!result){\n result = (char *)malloc(dataSize);\n }\n int offset = 0;\n while (offset < dataSize){\n \/\/Read unit size\n unsigned long unitSize = Bit::btohl(data + offset);\n \/\/Write annex b header\n memset(result + offset, 0x00, 3);\n result[offset + 3] = 0x01;\n \/\/Copy the nal unit\n memcpy(result + offset + 4, data + offset + 4, unitSize);\n \/\/Update the offset\n offset += 4 + unitSize;\n }\n return dataSize;\n }\n\n unsigned long fromAnnexB(const char * data, unsigned long dataSize, char *& result){\n const char * lastCheck = data + dataSize - 3;\n if (!result){\n FAIL_MSG(\"No output buffer given to FromAnnexB\");\n return 0;\n }\n int offset = 0;\n int newOffset = 0;\n while (offset < dataSize){\n const char * begin = data + offset;\n while ( begin < lastCheck && !(!begin[0] && !begin[1] && begin[2] == 0x01)){\n begin++;\n if (begin < lastCheck && begin[0]){\n begin++;\n }\n }\n begin += 3;\/\/Initialize begin after the first 0x000001 pattern.\n if (begin > data + dataSize){\n offset = dataSize;\n continue;\n }\n const char * end = (const char*)memmem(begin, dataSize - (begin - data), \"\\000\\000\\001\", 3);\n if (!end) {\n end = data + dataSize;\n }\n \/\/Check for 4-byte lead in's. Yes, we access -1 here\n if (end > begin && end[-1] == 0x00){\n end--;\n }\n unsigned int nalSize = end - begin;\n Bit::htobl(result + newOffset, nalSize);\n memcpy(result + newOffset + 4, begin, nalSize);\n\n newOffset += 4 + nalSize;\n offset = end - data;\n }\n return newOffset;\n }\n\n sequenceParameterSet::sequenceParameterSet(const char * _data, unsigned long _dataLen) : data(_data), dataLen(_dataLen) {}\n\n \/\/DTSC Initdata is the payload for an avcc box. init[8+] is data, init[6-7] is a network-encoded length\n void sequenceParameterSet::fromDTSCInit(const std::string & dtscInit){\n data = dtscInit.data() + 8;\n dataLen = Bit::btohs(dtscInit.data() + 6);\n }\n\n void skipScalingList(Utils::bitstream & bs, size_t listSize){\n size_t lastScale = 8;\n size_t nextScale = 8;\n for (size_t i = 0; i < listSize; i++){\n if (nextScale){\n uint64_t deltaScale = bs.getExpGolomb();\n nextScale = (lastScale + deltaScale + 256) % 256;\n }\n lastScale = (nextScale ? nextScale : lastScale);\n }\n }\n\n SPSMeta sequenceParameterSet::getCharacteristics() const {\n SPSMeta result;\n\n \/\/For calculating width\n unsigned int widthInMbs = 0;\n unsigned int cropHorizontal = 0;\n\n \/\/For calculating height\n bool mbsOnlyFlag = 0;\n unsigned int heightInMapUnits = 0;\n unsigned int cropVertical = 0;\n\n \/\/Fill the bitstream\n Utils::bitstream bs;\n for (unsigned int i = 1; i < dataLen; i++) {\n if (i + 2 < dataLen && (memcmp(data + i, \"\\000\\000\\003\", 3) == 0)){\/\/Emulation prevention bytes\n \/\/Yes, we increase i here\n bs.append(data + i, 2);\n i += 2;\n } else {\n \/\/No we don't increase i here\n bs.append(data + i, 1);\n }\n }\n\n char profileIdc = bs.get(8);\n result.profile = profileIdc;\n \/\/Start skipping unused data\n bs.skip(8);\n result.level = bs.get(8);\n bs.getUExpGolomb();\n if (profileIdc == 100 || profileIdc == 110 || profileIdc == 122 || profileIdc == 244 || profileIdc == 44 || profileIdc == 83 || profileIdc == 86 || profileIdc == 118 || profileIdc == 128) {\n \/\/chroma format idc\n char chromaFormatIdc = bs.getUExpGolomb();\n if (chromaFormatIdc == 3) {\n bs.skip(1);\n }\n bs.getUExpGolomb();\n bs.getUExpGolomb();\n bs.skip(1);\n if (bs.get(1)) {\/\/Scaling matrix is present\n char listSize = (chromaFormatIdc == 3 ? 12 : 8);\n for (size_t i = 0; i < listSize; i++){\n bool thisListPresent = bs.get(1);\n if (thisListPresent){\n if (i < 6){\n skipScalingList(bs, 16);\n }else{\n skipScalingList(bs, 64);\n }\n }\n }\n }\n }\n bs.getUExpGolomb();\n unsigned int pic_order_cnt_type = bs.getUExpGolomb();\n if (!pic_order_cnt_type) {\n bs.getUExpGolomb();\n } else if (pic_order_cnt_type == 1) {\n DEBUG_MSG(DLVL_DEVEL, \"This part of the implementation is incomplete(2), to be continued. If this message is shown, contact developers immediately.\");\n }\n bs.getUExpGolomb();\n bs.skip(1);\n \/\/Stop skipping data and start doing usefull stuff\n\n\n widthInMbs = bs.getUExpGolomb() + 1;\n heightInMapUnits = bs.getUExpGolomb() + 1;\n\n mbsOnlyFlag = bs.get(1);\/\/Gets used in height calculation\n if (!mbsOnlyFlag) {\n bs.skip(1);\n }\n bs.skip(1);\n \/\/cropping flag\n if (bs.get(1)) {\n cropHorizontal = bs.getUExpGolomb();\/\/leftOffset\n cropHorizontal += bs.getUExpGolomb();\/\/rightOffset\n cropVertical = bs.getUExpGolomb();\/\/topOffset\n cropVertical += bs.getUExpGolomb();\/\/bottomOffset\n }\n\n \/\/vuiParameters\n if (bs.get(1)) {\n \/\/Skipping all the paramters we dont use\n if (bs.get(1)) {\n if (bs.get(8) == 255) {\n bs.skip(32);\n }\n }\n if (bs.get(1)) {\n bs.skip(1);\n }\n if (bs.get(1)) {\n bs.skip(4);\n if (bs.get(1)) {\n bs.skip(24);\n }\n }\n if (bs.get(1)) {\n bs.getUExpGolomb();\n bs.getUExpGolomb();\n }\n\n \/\/Decode timing info\n if (bs.get(1)) {\n unsigned int unitsInTick = bs.get(32);\n unsigned int timeScale = bs.get(32);\n result.fps = (double)timeScale \/ (2 * unitsInTick);\n bs.skip(1);\n }\n }\n\n result.width = (widthInMbs * 16) - (cropHorizontal * 2);\n result.height = ((mbsOnlyFlag ? 1 : 2) * heightInMapUnits * 16) - (cropVertical * 2);\n return result;\n }\n\n}\n\n<|endoftext|>"} {"text":"#pragma once\n#include \"ipaddress.hpp\"\n#include \"neighbor.hpp\"\n#include \"types.hpp\"\n#include \"xyz\/openbmc_project\/Network\/IP\/Create\/server.hpp\"\n#include \"xyz\/openbmc_project\/Network\/Neighbor\/CreateStatic\/server.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace phosphor\n{\nnamespace network\n{\n\nusing Ifaces = sdbusplus::server::object_t<\n sdbusplus::xyz::openbmc_project::Network::server::EthernetInterface,\n sdbusplus::xyz::openbmc_project::Network::server::MACAddress,\n sdbusplus::xyz::openbmc_project::Network::IP::server::Create,\n sdbusplus::xyz::openbmc_project::Network::Neighbor::server::CreateStatic,\n sdbusplus::xyz::openbmc_project::Collection::server::DeleteAll>;\n\nusing IP = sdbusplus::xyz::openbmc_project::Network::server::IP;\n\nusing EthernetInterfaceIntf =\n sdbusplus::xyz::openbmc_project::Network::server::EthernetInterface;\nusing MacAddressIntf =\n sdbusplus::xyz::openbmc_project::Network::server::MACAddress;\n\nusing ServerList = std::vector;\nusing ObjectPath = sdbusplus::message::object_path;\n\nclass Manager;\n\nclass TestEthernetInterface;\n\nclass VlanInterface;\n\nnamespace config\n{\nclass Parser;\n}\n\nusing LinkSpeed = uint16_t;\nusing DuplexMode = uint8_t;\nusing Autoneg = uint8_t;\nusing LinkUp = bool;\nusing NICEnabled = bool;\nusing MTU = size_t;\nusing VlanId = uint32_t;\nusing InterfaceName = std::string;\nusing InterfaceInfo =\n std::tuple;\n\n\/** @class EthernetInterface\n * @brief OpenBMC Ethernet Interface implementation.\n * @details A concrete implementation for the\n * xyz.openbmc_project.Network.EthernetInterface DBus API.\n *\/\nclass EthernetInterface : public Ifaces\n{\n public:\n EthernetInterface() = delete;\n EthernetInterface(const EthernetInterface&) = delete;\n EthernetInterface& operator=(const EthernetInterface&) = delete;\n EthernetInterface(EthernetInterface&&) = delete;\n EthernetInterface& operator=(EthernetInterface&&) = delete;\n virtual ~EthernetInterface() = default;\n\n \/** @brief Constructor to put object onto bus at a dbus path.\n * @param[in] bus - Bus to attach to.\n * @param[in] objPath - Path to attach at.\n * @param[in] config - The parsed configuation file.\n * @param[in] parent - parent object.\n * @param[in] emitSignal - true if the object added signal needs to be\n * send.\n * @param[in] enabled - Override the lookup of nicEnabled\n *\/\n EthernetInterface(sdbusplus::bus_t& bus, stdplus::zstring_view objPath,\n const config::Parser& config, Manager& parent,\n bool emitSignal = true,\n std::optional enabled = std::nullopt);\n\n \/** @brief Function used to load the nameservers.\n *\/\n void loadNameServers(const config::Parser& config);\n\n \/** @brief Function to create ipAddress dbus object.\n * @param[in] addressType - Type of ip address.\n * @param[in] ipAddress- IP address.\n * @param[in] prefixLength - Length of prefix.\n *\/\n\n ObjectPath ip(IP::Protocol addressType, std::string ipAddress,\n uint8_t prefixLength, std::string) override;\n\n \/** @brief Function to create static neighbor dbus object.\n * @param[in] ipAddress - IP address.\n * @param[in] macAddress - Low level MAC address.\n *\/\n ObjectPath neighbor(std::string ipAddress, std::string macAddress) override;\n\n \/* @brief delete the dbus object of the given ipAddress.\n * @param[in] ipAddress - IP address.\n *\/\n void deleteObject(std::string_view ipAddress);\n\n \/* @brief delete the dbus object of the given ipAddress.\n * @param[in] ipAddress - IP address.\n *\/\n void deleteStaticNeighborObject(std::string_view ipAddress);\n\n \/* @brief delete the vlan dbus object of the given interface.\n * Also deletes the device file and the network file.\n * @param[in] interface - VLAN Interface.\n *\/\n void deleteVLANObject(stdplus::zstring_view interface);\n\n \/* @brief creates the dbus object(IPaddres) given in the address list.\n * @param[in] addrs - address list for which dbus objects needs\n * to create.\n *\/\n void createIPAddressObjects();\n\n \/* @brief creates the dbus object(Neighbor) given in the neighbor list.\n *\/\n void createStaticNeighborObjects();\n\n \/* @brief Gets the index of the interface on the system\n *\/\n unsigned ifIndex() const;\n\n \/* @brief Gets all the ip addresses.\n * @returns the list of ipAddress.\n *\/\n inline const auto& getAddresses() const\n {\n return addrs;\n }\n\n \/* @brief Gets all the static neighbor entries.\n * @returns Static neighbor map.\n *\/\n inline const auto& getStaticNeighbors() const\n {\n return staticNeighbors;\n }\n\n \/** Set value of DHCPEnabled *\/\n DHCPConf dhcpEnabled() const override;\n DHCPConf dhcpEnabled(DHCPConf value) override;\n using EthernetInterfaceIntf::dhcp4;\n bool dhcp4(bool value) override;\n using EthernetInterfaceIntf::dhcp6;\n bool dhcp6(bool value) override;\n\n \/** Retrieve Link State *\/\n bool linkUp() const override;\n\n \/** Retrieve MTU Size *\/\n size_t mtu() const override;\n\n \/** Set size of MTU *\/\n size_t mtu(size_t value) override;\n\n \/** Set value of NICEnabled *\/\n bool nicEnabled(bool value) override;\n\n \/** @brief sets the MAC address.\n * @param[in] value - MAC address which needs to be set on the system.\n * @returns macAddress of the interface or throws an error.\n *\/\n std::string macAddress(std::string value) override;\n\n \/** @brief check conf file for Router Advertisements\n *\n *\/\n bool ipv6AcceptRA(bool value) override;\n using EthernetInterfaceIntf::ipv6AcceptRA;\n\n \/** @brief sets the NTP servers.\n * @param[in] value - vector of NTP servers.\n *\/\n ServerList ntpServers(ServerList value) override;\n\n \/** @brief sets the Static DNS\/nameservers.\n * @param[in] value - vector of DNS servers.\n *\/\n\n ServerList staticNameServers(ServerList value) override;\n\n \/** @brief create Vlan interface.\n * @param[in] id- VLAN identifier.\n *\/\n ObjectPath createVLAN(VlanId id);\n\n \/** @brief load the vlan info from the system\n * and creates the ip address dbus objects.\n * @param[in] vlanID- VLAN identifier.\n *\/\n void loadVLAN(VlanId vlanID);\n\n \/** @brief write the network conf file with the in-memory objects.\n *\/\n void writeConfigurationFile();\n\n \/** @brief delete all dbus objects.\n *\/\n void deleteAll();\n\n \/** @brief set the default v4 gateway of the interface.\n * @param[in] gateway - default v4 gateway of the interface.\n *\/\n std::string defaultGateway(std::string gateway) override;\n\n \/** @brief set the default v6 gateway of the interface.\n * @param[in] gateway - default v6 gateway of the interface.\n *\/\n std::string defaultGateway6(std::string gateway) override;\n\n using EthernetInterfaceIntf::interfaceName;\n using EthernetInterfaceIntf::linkUp;\n using EthernetInterfaceIntf::mtu;\n using EthernetInterfaceIntf::nicEnabled;\n using MacAddressIntf::macAddress;\n\n using EthernetInterfaceIntf::defaultGateway;\n using EthernetInterfaceIntf::defaultGateway6;\n \/** @brief Absolute path of the resolv conf file *\/\n static constexpr auto resolvConfFile = \"\/etc\/resolv.conf\";\n\n protected:\n \/** @brief get the info of the ethernet interface.\n * @return tuple having the link speed,autonegotiation,duplexmode .\n *\/\n InterfaceInfo getInterfaceInfo() const;\n\n \/* @brief delete the vlan interface from system.\n * @param[in] interface - vlan Interface.\n *\/\n void deleteVLANFromSystem(stdplus::zstring_view interface);\n\n \/** @brief get the mac address of the interface.\n * @param[in] interfaceName - Network interface name.\n * @return macaddress on success\n *\/\n\n std::string getMACAddress(stdplus::const_zstring interfaceName) const;\n\n \/** @brief construct the ip address dbus object path.\n * @param[in] addressType - Type of ip address.\n * @param[in] ipAddress - IP address.\n * @param[in] prefixLength - Length of prefix.\n * @param[in] origin - The origin entry of the IP::Address\n\n * @return path of the address object.\n *\/\n std::string generateObjectPath(IP::Protocol addressType,\n std::string_view ipAddress,\n uint8_t prefixLength,\n IP::AddressOrigin origin) const;\n\n std::string\n generateStaticNeighborObjectPath(std::string_view ipAddress,\n std::string_view macAddress) const;\n\n \/** @brief get the NTP server list from the network conf\n *\n *\/\n ServerList getNTPServersFromConf();\n\n \/** @brief get the name server details from the network conf\n *\n *\/\n virtual ServerList getNameServerFromResolvd();\n\n \/** @brief Persistent sdbusplus DBus bus connection. *\/\n sdbusplus::bus_t& bus;\n\n \/** @brief Network Manager object. *\/\n Manager& manager;\n\n \/** @brief Persistent map of IPAddress dbus objects and their names *\/\n string_umap> addrs;\n\n \/** @brief Persistent map of Neighbor dbus objects and their names *\/\n string_umap> staticNeighbors;\n\n \/** @brief Persistent map of VLAN interface dbus objects and their names *\/\n string_umap> vlanInterfaces;\n\n \/** @brief Dbus object path *\/\n std::string objPath;\n\n friend class TestEthernetInterface;\n\n private:\n \/** @brief Determines if DHCP is active for the IP::Protocol supplied.\n * @param[in] protocol - Either IPv4 or IPv6\n * @returns true\/false value if DHCP is active for the input protocol\n *\/\n bool dhcpIsEnabled(IP::Protocol protocol);\n\n \/** @brief Determines if the address is manually assigned\n * @param[in] origin - The origin entry of the IP::Address\n * @returns true\/false value if the address is static\n *\/\n bool originIsManuallyAssigned(IP::AddressOrigin origin);\n\n \/** @brief Determines if the NIC is enabled in systemd\n * @returns true\/false value if the NIC is enabled\n *\/\n bool queryNicEnabled() const;\n\n std::string vlanIntfName(VlanId id) const;\n std::string vlanObjPath(VlanId id) const;\n};\n\n} \/\/ namespace network\n} \/\/ namespace phosphor\nethernet_interface: Remove unused resolvconf file#pragma once\n#include \"ipaddress.hpp\"\n#include \"neighbor.hpp\"\n#include \"types.hpp\"\n#include \"xyz\/openbmc_project\/Network\/IP\/Create\/server.hpp\"\n#include \"xyz\/openbmc_project\/Network\/Neighbor\/CreateStatic\/server.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace phosphor\n{\nnamespace network\n{\n\nusing Ifaces = sdbusplus::server::object_t<\n sdbusplus::xyz::openbmc_project::Network::server::EthernetInterface,\n sdbusplus::xyz::openbmc_project::Network::server::MACAddress,\n sdbusplus::xyz::openbmc_project::Network::IP::server::Create,\n sdbusplus::xyz::openbmc_project::Network::Neighbor::server::CreateStatic,\n sdbusplus::xyz::openbmc_project::Collection::server::DeleteAll>;\n\nusing IP = sdbusplus::xyz::openbmc_project::Network::server::IP;\n\nusing EthernetInterfaceIntf =\n sdbusplus::xyz::openbmc_project::Network::server::EthernetInterface;\nusing MacAddressIntf =\n sdbusplus::xyz::openbmc_project::Network::server::MACAddress;\n\nusing ServerList = std::vector;\nusing ObjectPath = sdbusplus::message::object_path;\n\nclass Manager;\n\nclass TestEthernetInterface;\n\nclass VlanInterface;\n\nnamespace config\n{\nclass Parser;\n}\n\nusing LinkSpeed = uint16_t;\nusing DuplexMode = uint8_t;\nusing Autoneg = uint8_t;\nusing LinkUp = bool;\nusing NICEnabled = bool;\nusing MTU = size_t;\nusing VlanId = uint32_t;\nusing InterfaceName = std::string;\nusing InterfaceInfo =\n std::tuple;\n\n\/** @class EthernetInterface\n * @brief OpenBMC Ethernet Interface implementation.\n * @details A concrete implementation for the\n * xyz.openbmc_project.Network.EthernetInterface DBus API.\n *\/\nclass EthernetInterface : public Ifaces\n{\n public:\n EthernetInterface() = delete;\n EthernetInterface(const EthernetInterface&) = delete;\n EthernetInterface& operator=(const EthernetInterface&) = delete;\n EthernetInterface(EthernetInterface&&) = delete;\n EthernetInterface& operator=(EthernetInterface&&) = delete;\n virtual ~EthernetInterface() = default;\n\n \/** @brief Constructor to put object onto bus at a dbus path.\n * @param[in] bus - Bus to attach to.\n * @param[in] objPath - Path to attach at.\n * @param[in] config - The parsed configuation file.\n * @param[in] parent - parent object.\n * @param[in] emitSignal - true if the object added signal needs to be\n * send.\n * @param[in] enabled - Override the lookup of nicEnabled\n *\/\n EthernetInterface(sdbusplus::bus_t& bus, stdplus::zstring_view objPath,\n const config::Parser& config, Manager& parent,\n bool emitSignal = true,\n std::optional enabled = std::nullopt);\n\n \/** @brief Function used to load the nameservers.\n *\/\n void loadNameServers(const config::Parser& config);\n\n \/** @brief Function to create ipAddress dbus object.\n * @param[in] addressType - Type of ip address.\n * @param[in] ipAddress- IP address.\n * @param[in] prefixLength - Length of prefix.\n *\/\n\n ObjectPath ip(IP::Protocol addressType, std::string ipAddress,\n uint8_t prefixLength, std::string) override;\n\n \/** @brief Function to create static neighbor dbus object.\n * @param[in] ipAddress - IP address.\n * @param[in] macAddress - Low level MAC address.\n *\/\n ObjectPath neighbor(std::string ipAddress, std::string macAddress) override;\n\n \/* @brief delete the dbus object of the given ipAddress.\n * @param[in] ipAddress - IP address.\n *\/\n void deleteObject(std::string_view ipAddress);\n\n \/* @brief delete the dbus object of the given ipAddress.\n * @param[in] ipAddress - IP address.\n *\/\n void deleteStaticNeighborObject(std::string_view ipAddress);\n\n \/* @brief delete the vlan dbus object of the given interface.\n * Also deletes the device file and the network file.\n * @param[in] interface - VLAN Interface.\n *\/\n void deleteVLANObject(stdplus::zstring_view interface);\n\n \/* @brief creates the dbus object(IPaddres) given in the address list.\n * @param[in] addrs - address list for which dbus objects needs\n * to create.\n *\/\n void createIPAddressObjects();\n\n \/* @brief creates the dbus object(Neighbor) given in the neighbor list.\n *\/\n void createStaticNeighborObjects();\n\n \/* @brief Gets the index of the interface on the system\n *\/\n unsigned ifIndex() const;\n\n \/* @brief Gets all the ip addresses.\n * @returns the list of ipAddress.\n *\/\n inline const auto& getAddresses() const\n {\n return addrs;\n }\n\n \/* @brief Gets all the static neighbor entries.\n * @returns Static neighbor map.\n *\/\n inline const auto& getStaticNeighbors() const\n {\n return staticNeighbors;\n }\n\n \/** Set value of DHCPEnabled *\/\n DHCPConf dhcpEnabled() const override;\n DHCPConf dhcpEnabled(DHCPConf value) override;\n using EthernetInterfaceIntf::dhcp4;\n bool dhcp4(bool value) override;\n using EthernetInterfaceIntf::dhcp6;\n bool dhcp6(bool value) override;\n\n \/** Retrieve Link State *\/\n bool linkUp() const override;\n\n \/** Retrieve MTU Size *\/\n size_t mtu() const override;\n\n \/** Set size of MTU *\/\n size_t mtu(size_t value) override;\n\n \/** Set value of NICEnabled *\/\n bool nicEnabled(bool value) override;\n\n \/** @brief sets the MAC address.\n * @param[in] value - MAC address which needs to be set on the system.\n * @returns macAddress of the interface or throws an error.\n *\/\n std::string macAddress(std::string value) override;\n\n \/** @brief check conf file for Router Advertisements\n *\n *\/\n bool ipv6AcceptRA(bool value) override;\n using EthernetInterfaceIntf::ipv6AcceptRA;\n\n \/** @brief sets the NTP servers.\n * @param[in] value - vector of NTP servers.\n *\/\n ServerList ntpServers(ServerList value) override;\n\n \/** @brief sets the Static DNS\/nameservers.\n * @param[in] value - vector of DNS servers.\n *\/\n\n ServerList staticNameServers(ServerList value) override;\n\n \/** @brief create Vlan interface.\n * @param[in] id- VLAN identifier.\n *\/\n ObjectPath createVLAN(VlanId id);\n\n \/** @brief load the vlan info from the system\n * and creates the ip address dbus objects.\n * @param[in] vlanID- VLAN identifier.\n *\/\n void loadVLAN(VlanId vlanID);\n\n \/** @brief write the network conf file with the in-memory objects.\n *\/\n void writeConfigurationFile();\n\n \/** @brief delete all dbus objects.\n *\/\n void deleteAll();\n\n \/** @brief set the default v4 gateway of the interface.\n * @param[in] gateway - default v4 gateway of the interface.\n *\/\n std::string defaultGateway(std::string gateway) override;\n\n \/** @brief set the default v6 gateway of the interface.\n * @param[in] gateway - default v6 gateway of the interface.\n *\/\n std::string defaultGateway6(std::string gateway) override;\n\n using EthernetInterfaceIntf::interfaceName;\n using EthernetInterfaceIntf::linkUp;\n using EthernetInterfaceIntf::mtu;\n using EthernetInterfaceIntf::nicEnabled;\n using MacAddressIntf::macAddress;\n\n using EthernetInterfaceIntf::defaultGateway;\n using EthernetInterfaceIntf::defaultGateway6;\n\n protected:\n \/** @brief get the info of the ethernet interface.\n * @return tuple having the link speed,autonegotiation,duplexmode .\n *\/\n InterfaceInfo getInterfaceInfo() const;\n\n \/* @brief delete the vlan interface from system.\n * @param[in] interface - vlan Interface.\n *\/\n void deleteVLANFromSystem(stdplus::zstring_view interface);\n\n \/** @brief get the mac address of the interface.\n * @param[in] interfaceName - Network interface name.\n * @return macaddress on success\n *\/\n\n std::string getMACAddress(stdplus::const_zstring interfaceName) const;\n\n \/** @brief construct the ip address dbus object path.\n * @param[in] addressType - Type of ip address.\n * @param[in] ipAddress - IP address.\n * @param[in] prefixLength - Length of prefix.\n * @param[in] origin - The origin entry of the IP::Address\n\n * @return path of the address object.\n *\/\n std::string generateObjectPath(IP::Protocol addressType,\n std::string_view ipAddress,\n uint8_t prefixLength,\n IP::AddressOrigin origin) const;\n\n std::string\n generateStaticNeighborObjectPath(std::string_view ipAddress,\n std::string_view macAddress) const;\n\n \/** @brief get the NTP server list from the network conf\n *\n *\/\n ServerList getNTPServersFromConf();\n\n \/** @brief get the name server details from the network conf\n *\n *\/\n virtual ServerList getNameServerFromResolvd();\n\n \/** @brief Persistent sdbusplus DBus bus connection. *\/\n sdbusplus::bus_t& bus;\n\n \/** @brief Network Manager object. *\/\n Manager& manager;\n\n \/** @brief Persistent map of IPAddress dbus objects and their names *\/\n string_umap> addrs;\n\n \/** @brief Persistent map of Neighbor dbus objects and their names *\/\n string_umap> staticNeighbors;\n\n \/** @brief Persistent map of VLAN interface dbus objects and their names *\/\n string_umap> vlanInterfaces;\n\n \/** @brief Dbus object path *\/\n std::string objPath;\n\n friend class TestEthernetInterface;\n\n private:\n \/** @brief Determines if DHCP is active for the IP::Protocol supplied.\n * @param[in] protocol - Either IPv4 or IPv6\n * @returns true\/false value if DHCP is active for the input protocol\n *\/\n bool dhcpIsEnabled(IP::Protocol protocol);\n\n \/** @brief Determines if the address is manually assigned\n * @param[in] origin - The origin entry of the IP::Address\n * @returns true\/false value if the address is static\n *\/\n bool originIsManuallyAssigned(IP::AddressOrigin origin);\n\n \/** @brief Determines if the NIC is enabled in systemd\n * @returns true\/false value if the NIC is enabled\n *\/\n bool queryNicEnabled() const;\n\n std::string vlanIntfName(VlanId id) const;\n std::string vlanObjPath(VlanId id) const;\n};\n\n} \/\/ namespace network\n} \/\/ namespace phosphor\n<|endoftext|>"} {"text":"#include \n#include \n\nextern \"C\" {\n #include \"ft2build.h\"\n #include FT_FREETYPE_H\n}\n\n#include \"freetype_interface.h\"\n#include \"grayscale_bitmap.h\"\n\nclass FreetypeMaintainer {\npublic:\n FreetypeMaintainer() : library(nullptr), fontFace(nullptr) {\n int error = FT_Init_FreeType(&library);\n if (error) {\n throw std::runtime_error(\"Unable to initalize Freetype library\");\n }\n };\n\n virtual ~FreetypeMaintainer() {\n if (fontFace != nullptr) {\n FT_Done_Face(fontFace);\n }\n\n FT_Done_FreeType(library);\n }\n\n FT_Library library;\n FT_Face fontFace;\n\nprivate:\n FreetypeMaintainer(const FreetypeMaintainer&);\n};\n\nstatic FreetypeMaintainer ft;\n\n#define FIXED_POINT_26_6_COEFF 2^6\n\nvoid setFontFile(const std::string& newFilePath) {\n #define SAME_AS_NEXT_ARG 0\n static const FT_UInt DEFAULT_HORIZ_RES = 72;\n static const FT_UInt DEFAULT_VERTICAL_RES = DEFAULT_HORIZ_RES;\n static const FT_Long FIRST_FACE_IN_FONT_INDEX = 0;\n\n int error = FT_New_Face(ft.library, newFilePath.c_str(),\n FIRST_FACE_IN_FONT_INDEX, &ft.fontFace);\n\n if (error == FT_Err_Unknown_File_Format) {\n std::stringstream err;\n err << \"The font file '\" << newFilePath << \"' could be opened and read, \"\n << \"but it appears that its font format is unsupported\";\n throw std::runtime_error(err.str());\n }\n else if (error) {\n std::stringstream err;\n err << \"The font file '\" << newFilePath << \"' either could not \"\n << \"be opened and read, or it is simply broken\";\n throw std::runtime_error(err.str());\n }\n\n if (!FT_IS_FIXED_WIDTH(ft.fontFace)) {\n throw std::runtime_error(\"Loaded font face must be monospaced\");\n }\n\n if (!FT_IS_SCALABLE(ft.fontFace)) {\n throw std::runtime_error(\"Loaded font face must be scaleble\");\n }\n\n error = FT_Set_Char_Size(ft.fontFace, SAME_AS_NEXT_ARG,\n 16 * FIXED_POINT_26_6_COEFF,\n DEFAULT_HORIZ_RES,\n DEFAULT_VERTICAL_RES);\n\n if (error) {\n throw std::runtime_error(\"Error while setting char size\");\n }\n}\n\nuint16_t getFontHeight() {\n return ft.fontFace->size->metrics.height \/ FIXED_POINT_26_6_COEFF;\n}\n\nuint16_t getFontWidth() {\n return ft.fontFace->size->metrics.max_advance \/ FIXED_POINT_26_6_COEFF;\n}\n\nGrayscaleBitmap getBitmapForAsciiSymbol(char symbol) {\n int error = FT_Load_Char( ft.fontFace, static_cast(symbol),\n FT_LOAD_RENDER);\n\n if (error) {\n throw std::runtime_error(\"Error while loading char\");\n }\n\n if (ft.fontFace->glyph->format != FT_GLYPH_FORMAT_BITMAP) {\n throw std::runtime_error(\"Freetype symbol glyph must have bitmap format\");\n }\n\n if (ft.fontFace->glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY) {\n throw std::runtime_error(\"Given Freetype bitmap is not 8-bit grayscale\");\n }\n\n return GrayscaleBitmap(ft.fontFace);\n}\ntyped const#include \n#include \n\nextern \"C\" {\n #include \"ft2build.h\"\n #include FT_FREETYPE_H\n}\n\n#include \"freetype_interface.h\"\n#include \"grayscale_bitmap.h\"\n\nclass FreetypeMaintainer {\npublic:\n FreetypeMaintainer() : library(nullptr), fontFace(nullptr) {\n int error = FT_Init_FreeType(&library);\n if (error) {\n throw std::runtime_error(\"Unable to initalize Freetype library\");\n }\n };\n\n virtual ~FreetypeMaintainer() {\n if (fontFace != nullptr) {\n FT_Done_Face(fontFace);\n }\n\n FT_Done_FreeType(library);\n }\n\n FT_Library library;\n FT_Face fontFace;\n\nprivate:\n FreetypeMaintainer(const FreetypeMaintainer&);\n};\n\nstatic FreetypeMaintainer ft;\n\nstatic const uint32_t FIXED_POINT_26_6_COEFF = 2^6;\n\nvoid setFontFile(const std::string& newFilePath) {\n #define SAME_AS_NEXT_ARG 0\n static const FT_UInt DEFAULT_HORIZ_RES = 72;\n static const FT_UInt DEFAULT_VERTICAL_RES = DEFAULT_HORIZ_RES;\n static const FT_Long FIRST_FACE_IN_FONT_INDEX = 0;\n\n int error = FT_New_Face(ft.library, newFilePath.c_str(),\n FIRST_FACE_IN_FONT_INDEX, &ft.fontFace);\n\n if (error == FT_Err_Unknown_File_Format) {\n std::stringstream err;\n err << \"The font file '\" << newFilePath << \"' could be opened and read, \"\n << \"but it appears that its font format is unsupported\";\n throw std::runtime_error(err.str());\n }\n else if (error) {\n std::stringstream err;\n err << \"The font file '\" << newFilePath << \"' either could not \"\n << \"be opened and read, or it is simply broken\";\n throw std::runtime_error(err.str());\n }\n\n if (!FT_IS_FIXED_WIDTH(ft.fontFace)) {\n throw std::runtime_error(\"Loaded font face must be monospaced\");\n }\n\n if (!FT_IS_SCALABLE(ft.fontFace)) {\n throw std::runtime_error(\"Loaded font face must be scaleble\");\n }\n\n error = FT_Set_Char_Size(ft.fontFace, SAME_AS_NEXT_ARG,\n 16 * FIXED_POINT_26_6_COEFF,\n DEFAULT_HORIZ_RES,\n DEFAULT_VERTICAL_RES);\n\n if (error) {\n throw std::runtime_error(\"Error while setting char size\");\n }\n}\n\nuint16_t getFontHeight() {\n return ft.fontFace->size->metrics.height \/ FIXED_POINT_26_6_COEFF;\n}\n\nuint16_t getFontWidth() {\n return ft.fontFace->size->metrics.max_advance \/ FIXED_POINT_26_6_COEFF;\n}\n\nGrayscaleBitmap getBitmapForAsciiSymbol(char symbol) {\n int error = FT_Load_Char( ft.fontFace, static_cast(symbol),\n FT_LOAD_RENDER);\n\n if (error) {\n throw std::runtime_error(\"Error while loading char\");\n }\n\n if (ft.fontFace->glyph->format != FT_GLYPH_FORMAT_BITMAP) {\n throw std::runtime_error(\"Freetype symbol glyph must have bitmap format\");\n }\n\n if (ft.fontFace->glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY) {\n throw std::runtime_error(\"Given Freetype bitmap is not 8-bit grayscale\");\n }\n\n return GrayscaleBitmap(ft.fontFace);\n}\n<|endoftext|>"} {"text":"#include \"gamelib\/utils\/json.hpp\"\n#include \"gamelib\/utils\/conversions.hpp\"\n#include \"gamelib\/core\/geometry\/GroupTransform.hpp\"\n#include \n\nnamespace gamelib\n{\n bool diffJson(const Json::Value& node, const Json::Value& compare, Json::Value* out_)\n {\n auto& out = *out_;\n\n if (node.type() != compare.type())\n {\n if (node.isIntegral() && compare.isIntegral() && node.asInt() == compare.asInt())\n return false;\n else if (node.isIntegral() && compare.isDouble() && math::almostEquals((double)node.asInt(), compare.asDouble()))\n return false;\n else if (compare.isIntegral() && node.isDouble() && math::almostEquals((double)compare.asInt(), node.asDouble()))\n return false;\n }\n else if (node.isObject())\n {\n bool diff = false;\n for (auto it = node.begin(), end = node.end(); it != end; ++it)\n {\n auto key = it.key().asString();\n if (!compare.isMember(key))\n {\n out[key] = *it;\n diff = true;\n }\n else\n {\n Json::Value val;\n if (diffJson(*it, compare[key], &val))\n {\n out[key] = val;\n diff = true;\n }\n }\n }\n return diff;\n }\n else if (node.isArray())\n {\n if (node.size() == compare.size())\n {\n for (Json::ArrayIndex i = 0; i < node.size(); ++i)\n {\n Json::Value tmp;\n if (diffJson(node[i], compare[i], &tmp))\n {\n out = node;\n return true;\n }\n }\n return false;\n }\n }\n else if (node.compare(compare) == 0)\n return false;\n\n out = node;\n return true;\n }\n\n\n bool loadJsonFromFile(const std::string& fname, Json::Value& node)\n {\n LOG(\"(Re)Loading \", fname, \"...\");\n std::ifstream f;\n f.open(fname.c_str());\n if (f.is_open())\n {\n f >> node;\n f.close();\n return true;\n }\n LOG_ERROR(\"Failed to load json from file \", fname);\n return false;\n }\n\n bool writeJsonToFile(const std::string& fname, const Json::Value& node)\n {\n LOG(\"Writing to file \", fname, \"...\");\n std::ofstream f;\n f.open(fname.c_str());\n if (f.is_open())\n {\n f << node.toStyledString();\n f.close();\n return true;\n }\n LOG_ERROR(\"Failed to write json to file \", fname);\n return false;\n }\n\n\n bool loadFromJson(const Json::Value& node, Transformable& transform)\n {\n math::Point2f pos = transform.getPosition();\n math::Vec2f scale = transform.getScale();\n float angle = transform.getRotation();\n auto parent = transform.getParent();\n\n if (parent)\n {\n pos -= parent->getPosition().asVector();\n scale \/= parent->getScale();\n angle -= parent->getRotation();\n }\n\n if (!loadFromJson(node, &pos, &scale, &angle, false))\n return false;\n\n if (parent)\n {\n pos += parent->getPosition().asVector();\n scale *= parent->getScale();\n angle += parent->getRotation();\n }\n\n transform.setPosition(pos);\n transform.setScale(scale);\n transform.setRotation(angle);\n return true;\n }\n\n bool loadFromJson(const Json::Value& node, math::Point2f* pos, math::Vec2f* scale, float* angle, bool clear)\n {\n \/\/ NOTE: It can't load but uses default, so no fail\n \/\/ if (!node.isObject())\n \/\/ return false;\n\n if (pos)\n loadFromJson(node[\"pos\"], pos->asVector(), clear);\n if (scale)\n loadFromJson(node[\"scale\"], *scale, clear);\n if (angle)\n *angle = node.get(\"angle\", clear ? 0 : *angle).asFloat();\n\n return true;\n }\n\n\n bool loadFromJson(const Json::Value& node, math::Point2f& p, bool clear)\n {\n return loadFromJson(node, p.asVector(), clear);\n }\n\n bool loadFromJson(const Json::Value& node, sf::Vector2f& p, bool clear)\n {\n return loadFromJson(node, convert(p), clear);\n }\n\n\n void writeToJson(Json::Value& node, const Transformable& transform)\n {\n auto pos = transform.getPosition();\n auto scale = transform.getScale();\n auto angle = transform.getRotation();\n auto parent = transform.getParent();\n\n if (parent)\n {\n pos -= parent->getPosition().asVector();\n scale \/= parent->getScale();\n angle -= parent->getRotation();\n }\n\n writeToJson(node, pos, scale, angle);\n }\n\n void writeToJson(Json::Value& node, const math::Point2f& pos, const math::Vec2f& scale, float angle)\n {\n writeToJson(node[\"pos\"], pos);\n writeToJson(node[\"scale\"], scale);\n node[\"angle\"] = angle;\n }\n\n\n void writeToJson(Json::Value& node, const math::Point2f& p)\n {\n writeToJson(node, p.asVector());\n }\n\n void writeToJson(Json::Value& node, const sf::Vector2f& vec)\n {\n writeToJson(node, convert(vec));\n }\n}\nFix incorrect scale value#include \"gamelib\/utils\/json.hpp\"\n#include \"gamelib\/utils\/conversions.hpp\"\n#include \"gamelib\/core\/geometry\/GroupTransform.hpp\"\n#include \n\nnamespace gamelib\n{\n bool diffJson(const Json::Value& node, const Json::Value& compare, Json::Value* out_)\n {\n auto& out = *out_;\n\n if (node.type() != compare.type())\n {\n if (node.isIntegral() && compare.isIntegral() && node.asInt() == compare.asInt())\n return false;\n else if (node.isIntegral() && compare.isDouble() && math::almostEquals((double)node.asInt(), compare.asDouble()))\n return false;\n else if (compare.isIntegral() && node.isDouble() && math::almostEquals((double)compare.asInt(), node.asDouble()))\n return false;\n }\n else if (node.isObject())\n {\n bool diff = false;\n for (auto it = node.begin(), end = node.end(); it != end; ++it)\n {\n auto key = it.key().asString();\n if (!compare.isMember(key))\n {\n out[key] = *it;\n diff = true;\n }\n else\n {\n Json::Value val;\n if (diffJson(*it, compare[key], &val))\n {\n out[key] = val;\n diff = true;\n }\n }\n }\n return diff;\n }\n else if (node.isArray())\n {\n if (node.size() == compare.size())\n {\n for (Json::ArrayIndex i = 0; i < node.size(); ++i)\n {\n Json::Value tmp;\n if (diffJson(node[i], compare[i], &tmp))\n {\n out = node;\n return true;\n }\n }\n return false;\n }\n }\n else if (node.compare(compare) == 0)\n return false;\n\n out = node;\n return true;\n }\n\n\n bool loadJsonFromFile(const std::string& fname, Json::Value& node)\n {\n LOG(\"(Re)Loading \", fname, \"...\");\n std::ifstream f;\n f.open(fname.c_str());\n if (f.is_open())\n {\n f >> node;\n f.close();\n return true;\n }\n LOG_ERROR(\"Failed to load json from file \", fname);\n return false;\n }\n\n bool writeJsonToFile(const std::string& fname, const Json::Value& node)\n {\n LOG(\"Writing to file \", fname, \"...\");\n std::ofstream f;\n f.open(fname.c_str());\n if (f.is_open())\n {\n f << node.toStyledString();\n f.close();\n return true;\n }\n LOG_ERROR(\"Failed to write json to file \", fname);\n return false;\n }\n\n\n bool loadFromJson(const Json::Value& node, Transformable& transform)\n {\n math::Point2f pos = transform.getPosition();\n math::Vec2f scale = transform.getScale();\n float angle = transform.getRotation();\n auto parent = transform.getParent();\n\n if (parent)\n {\n pos -= parent->getPosition().asVector();\n scale \/= parent->getScale();\n angle -= parent->getRotation();\n }\n\n if (!loadFromJson(node, &pos, &scale, &angle, false))\n return false;\n\n if (parent)\n {\n pos += parent->getPosition().asVector();\n scale *= parent->getScale();\n angle += parent->getRotation();\n }\n\n transform.setPosition(pos);\n transform.setScale(scale);\n transform.setRotation(angle);\n return true;\n }\n\n bool loadFromJson(const Json::Value& node, math::Point2f* pos, math::Vec2f* scale, float* angle, bool clear)\n {\n \/\/ NOTE: It can't load but uses default, so no fail\n \/\/ if (!node.isObject())\n \/\/ return false;\n\n if (scale && clear)\n scale->fill(1);\n\n if (pos)\n loadFromJson(node[\"pos\"], pos->asVector(), clear);\n if (scale)\n loadFromJson(node[\"scale\"], *scale, false);\n if (angle)\n *angle = node.get(\"angle\", clear ? 0 : *angle).asFloat();\n\n return true;\n }\n\n\n bool loadFromJson(const Json::Value& node, math::Point2f& p, bool clear)\n {\n return loadFromJson(node, p.asVector(), clear);\n }\n\n bool loadFromJson(const Json::Value& node, sf::Vector2f& p, bool clear)\n {\n return loadFromJson(node, convert(p), clear);\n }\n\n\n void writeToJson(Json::Value& node, const Transformable& transform)\n {\n auto pos = transform.getPosition();\n auto scale = transform.getScale();\n auto angle = transform.getRotation();\n auto parent = transform.getParent();\n\n if (parent)\n {\n pos -= parent->getPosition().asVector();\n scale \/= parent->getScale();\n angle -= parent->getRotation();\n }\n\n writeToJson(node, pos, scale, angle);\n }\n\n void writeToJson(Json::Value& node, const math::Point2f& pos, const math::Vec2f& scale, float angle)\n {\n writeToJson(node[\"pos\"], pos);\n writeToJson(node[\"scale\"], scale);\n node[\"angle\"] = angle;\n }\n\n\n void writeToJson(Json::Value& node, const math::Point2f& p)\n {\n writeToJson(node, p.asVector());\n }\n\n void writeToJson(Json::Value& node, const sf::Vector2f& vec)\n {\n writeToJson(node, convert(vec));\n }\n}\n<|endoftext|>"} {"text":"\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ bwtree_index.cpp\n\/\/\n\/\/ Identification: src\/backend\/index\/bwtree_index.cpp\n\/\/\n\/\/ Copyright (c) 2015-16, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"common\/logger.h\"\n#include \"index\/bwtree_index.h\"\n#include \"index\/index_key.h\"\n#include \"storage\/tuple.h\"\n\nnamespace peloton {\nnamespace index {\n\nBWTREE_TEMPLATE_ARGUMENTS\nBWTREE_INDEX_TYPE::BWTreeIndex(IndexMetadata *metadata) :\n \/\/ Base class\n Index{metadata},\n \/\/ Key \"less than\" relation comparator\n comparator{},\n \/\/ Key equality checker\n equals{},\n \/\/ Key hash function\n hash_func{},\n \/\/ NOTE: These two arguments need to be constructed in advance\n \/\/ and do not have trivial constructor\n container{comparator,\n equals,\n hash_func} {\n return;\n}\n\nBWTREE_TEMPLATE_ARGUMENTS\nBWTREE_INDEX_TYPE::~BWTreeIndex() {\n return;\n}\n\n\/*\n * InsertEntry() - insert a key-value pair into the map\n *\n * If the key value pair already exists in the map, just return false\n *\/\nBWTREE_TEMPLATE_ARGUMENTS\nbool\nBWTREE_INDEX_TYPE::InsertEntry(const storage::Tuple *key,\n const ItemPointer &location) {\n KeyType index_key;\n index_key.SetFromKey(key);\n \n ItemPointer *item_p = new ItemPointer{location};\n \n bool ret = container.Insert(index_key, item_p);\n \/\/ If insertion fails we just delete the new value and return false\n \/\/ to notify the caller\n if(ret == false) {\n delete item_p;\n }\n\n return ret;\n}\n\n\/*\n * DeleteEntry() - Removes a key-value pair\n *\n * If the key-value pair does not exists yet in the map return false\n *\/\nBWTREE_TEMPLATE_ARGUMENTS\nbool\nBWTREE_INDEX_TYPE::DeleteEntry(const storage::Tuple *key,\n const ItemPointer &location) {\n KeyType index_key;\n index_key.SetFromKey(key);\n \n \/\/ Must allocate new memory here\n ItemPointer *ip_p = new ItemPointer{location};\n \n \/\/ In Delete() since we just use the value for comparison (i.e. read-only)\n \/\/ it is unnecessary for us to allocate memory\n bool ret = container.DeleteExchange(index_key, &ip_p);\n \n \/\/ IF delete succeeds then DeleteExchange() will exchange the deleted\n \/\/ value into this variable\n if(ret == true) {\n \/\/delete ip_p;\n } else {\n \/\/ This will delete the unused memory\n delete ip_p;\n }\n\n return ret;\n}\n\nBWTREE_TEMPLATE_ARGUMENTS\nbool\nBWTREE_INDEX_TYPE::CondInsertEntry(const storage::Tuple *key,\n const ItemPointer &location,\n std::function predicate) {\n KeyType index_key;\n index_key.SetFromKey(key);\n \n ItemPointer *item_p = new ItemPointer{location};\n bool predicate_satisfied = false;\n \n \/\/ This function will complete them in one step\n \/\/ predicate will be set to nullptr if the predicate\n \/\/ returns true for some value\n bool ret = container.ConditionalInsert(index_key,\n item_p,\n predicate,\n &predicate_satisfied);\n\n \/\/ If predicate is not satisfied then we know insertion successes\n if(predicate_satisfied == false) {\n \/\/ So it should always succeed?\n assert(ret == true);\n } else {\n assert(ret == false);\n \n delete item_p;\n }\n\n return ret;\n}\n\n\nBWTREE_TEMPLATE_ARGUMENTS\nvoid\nBWTREE_INDEX_TYPE::Scan(const std::vector &values,\n const std::vector &key_column_ids,\n const std::vector &expr_types,\n const ScanDirectionType &scan_direction,\n std::vector &result) {\n KeyType index_key;\n\n \/\/ Checkif we have leading (leftmost) column equality\n \/\/ refer : http:\/\/www.postgresql.org\/docs\/8.2\/static\/indexes-multicolumn.html\n oid_t leading_column_id = 0;\n auto key_column_ids_itr = std::find(key_column_ids.begin(),\n key_column_ids.end(), leading_column_id);\n\n \/\/ SPECIAL CASE : leading column id is one of the key column ids\n \/\/ and is involved in a equality constraint\n bool special_case = false;\n if (key_column_ids_itr != key_column_ids.end()) {\n auto offset = std::distance(key_column_ids.begin(), key_column_ids_itr);\n if (expr_types[offset] == EXPRESSION_TYPE_COMPARE_EQUAL) {\n special_case = true;\n }\n }\n\n LOG_TRACE(\"Special case : %d \", special_case);\n\n \/\/ This is only a placeholder that cannot be moved but can be assigned to\n auto scan_begin_itr = container.NullIterator();\n\n std::unique_ptr start_key;\n bool all_constraints_are_equal = false;\n\n \/\/ If it is a special case, we can figure out the range to scan in the index\n if (special_case == true) {\n start_key.reset(new storage::Tuple(metadata->GetKeySchema(), true));\n\n \/\/ Construct the lower bound key tuple\n all_constraints_are_equal = ConstructLowerBoundTuple(\n start_key.get(), values, key_column_ids, expr_types);\n\n LOG_TRACE(\"All constraints are equal : %d \", all_constraints_are_equal);\n\n index_key.SetFromKey(start_key.get());\n\/*\n \/\/ If it is point query then we just do a GetValue() since GetValue()\n \/\/ is way more faster than scanning using iterator\n if(all_constraints_are_equal == true) {\n \/\/printf(\"All constraints are equal\\n\");\n \n \/\/ This retrieves a list of ItemPointer *\n container.GetValue(index_key, result);\n\n return;\n }\n*\/\n \/\/printf(\"Non special case\\n\");\n\n \/\/ This returns an iterator pointing to index_key's values\n scan_begin_itr = container.Begin(index_key);\n } else {\n scan_begin_itr = container.Begin();\n }\n\n switch (scan_direction) {\n case SCAN_DIRECTION_TYPE_FORWARD:\n case SCAN_DIRECTION_TYPE_BACKWARD: {\n \/\/ Scan the index entries in forward direction\n for (auto scan_itr = scan_begin_itr;\n scan_itr.IsEnd() == false;\n scan_itr++) {\n KeyType &scan_current_key = const_cast(scan_itr->first);\n \n auto tuple =\n scan_current_key.GetTupleForComparison(metadata->GetKeySchema());\n\n \/\/ Compare the current key in the scan with \"values\" based on\n \/\/ \"expression types\"\n \/\/ For instance, \"5\" EXPR_GREATER_THAN \"2\" is true\n if (Compare(tuple, key_column_ids, expr_types, values) == true) {\n result.push_back(scan_itr->second);\n } else {\n \/\/ We can stop scanning if we know that all constraints are equal\n if (all_constraints_are_equal == true) {\n break;\n }\n }\n }\n\n } break;\n\n case SCAN_DIRECTION_TYPE_INVALID:\n default:\n throw Exception(\"Invalid scan direction \\n\");\n break;\n }\n\n return;\n}\n\nBWTREE_TEMPLATE_ARGUMENTS\nvoid\nBWTREE_INDEX_TYPE::ScanAllKeys(std::vector &result) {\n auto it = container.Begin();\n\n \/\/ scan all entries\n while (it.IsEnd() == false) {\n result.push_back(it->second);\n it++;\n }\n\n return;\n}\n\nBWTREE_TEMPLATE_ARGUMENTS\nvoid\nBWTREE_INDEX_TYPE::ScanKey(const storage::Tuple *key,\n std::vector &result) {\n KeyType index_key;\n index_key.SetFromKey(key);\n\n \/\/ This function in BwTree fills a given vector\n container.GetValue(index_key, result);\n\n return;\n}\n\nBWTREE_TEMPLATE_ARGUMENTS\nstd::string\nBWTREE_INDEX_TYPE::GetTypeName() const {\n return \"BWTree\";\n}\n\n\/\/ NOTE: If ints key is used as an optimization just uncommend\n\/\/ the following in order to instanciation the template before it is\n\/\/ linked in linking stage\n\n\/*\ntemplate class BWTreeIndex,\n ItemPointer *,\n IntsComparator<1>,\n IntsEqualityChecker<1>,\n IntsHasher<1>,\n ItemPointerComparator,\n ItemPointerHashFunc>;\ntemplate class BWTreeIndex,\n ItemPointer *,\n IntsComparator<2>,\n IntsEqualityChecker<2>,\n IntsHasher<2>,\n ItemPointerComparator,\n ItemPointerHashFunc>;\ntemplate class BWTreeIndex,\n ItemPointer *,\n IntsComparator<3>,\n IntsEqualityChecker<3>,\n IntsHasher<3>,\n ItemPointerComparator,\n ItemPointerHashFunc>;\ntemplate class BWTreeIndex,\n ItemPointer *,\n IntsComparator<4>,\n IntsEqualityChecker<4>,\n IntsHasher<4>,\n ItemPointerComparator,\n ItemPointerHashFunc>;\n*\/\n\n\/\/ Generic key\ntemplate class BWTreeIndex,\n ItemPointer *,\n GenericComparator<4>,\n GenericEqualityChecker<4>,\n GenericHasher<4>,\n ItemPointerComparator,\n ItemPointerHashFunc>;\ntemplate class BWTreeIndex,\n ItemPointer *,\n GenericComparator<8>,\n GenericEqualityChecker<8>,\n GenericHasher<8>,\n ItemPointerComparator,\n ItemPointerHashFunc>;\ntemplate class BWTreeIndex,\n ItemPointer *,\n GenericComparator<16>,\n GenericEqualityChecker<16>,\n GenericHasher<16>,\n ItemPointerComparator,\n ItemPointerHashFunc>;\ntemplate class BWTreeIndex,\n ItemPointer *,\n GenericComparator<64>,\n GenericEqualityChecker<64>,\n GenericHasher<64>,\n ItemPointerComparator,\n ItemPointerHashFunc>;\ntemplate class BWTreeIndex,\n ItemPointer *,\n GenericComparator<256>,\n GenericEqualityChecker<256>,\n GenericHasher<256>,\n ItemPointerComparator,\n ItemPointerHashFunc>;\n\n\/\/ Tuple key\ntemplate class BWTreeIndex;\n\n} \/\/ End index namespace\n} \/\/ End peloton namespace\nChange constructor such that GC Thread is not started automatically\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ bwtree_index.cpp\n\/\/\n\/\/ Identification: src\/backend\/index\/bwtree_index.cpp\n\/\/\n\/\/ Copyright (c) 2015-16, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"common\/logger.h\"\n#include \"index\/bwtree_index.h\"\n#include \"index\/index_key.h\"\n#include \"storage\/tuple.h\"\n\nnamespace peloton {\nnamespace index {\n\nBWTREE_TEMPLATE_ARGUMENTS\nBWTREE_INDEX_TYPE::BWTreeIndex(IndexMetadata *metadata) :\n \/\/ Base class\n Index{metadata},\n \/\/ Key \"less than\" relation comparator\n comparator{},\n \/\/ Key equality checker\n equals{},\n \/\/ Key hash function\n hash_func{},\n \/\/ NOTE: These two arguments need to be constructed in advance\n \/\/ and do not have trivial constructor\n \/\/\n \/\/ NOTE 2: We set the first parameter to false to disable automatic GC\n \/\/\n container{false,\n comparator,\n equals,\n hash_func} {\n \n return;\n}\n\nBWTREE_TEMPLATE_ARGUMENTS\nBWTREE_INDEX_TYPE::~BWTreeIndex() {\n return;\n}\n\n\/*\n * InsertEntry() - insert a key-value pair into the map\n *\n * If the key value pair already exists in the map, just return false\n *\/\nBWTREE_TEMPLATE_ARGUMENTS\nbool\nBWTREE_INDEX_TYPE::InsertEntry(const storage::Tuple *key,\n const ItemPointer &location) {\n KeyType index_key;\n index_key.SetFromKey(key);\n \n ItemPointer *item_p = new ItemPointer{location};\n \n bool ret = container.Insert(index_key, item_p);\n \/\/ If insertion fails we just delete the new value and return false\n \/\/ to notify the caller\n if(ret == false) {\n delete item_p;\n }\n\n return ret;\n}\n\n\/*\n * DeleteEntry() - Removes a key-value pair\n *\n * If the key-value pair does not exists yet in the map return false\n *\/\nBWTREE_TEMPLATE_ARGUMENTS\nbool\nBWTREE_INDEX_TYPE::DeleteEntry(const storage::Tuple *key,\n const ItemPointer &location) {\n KeyType index_key;\n index_key.SetFromKey(key);\n \n \/\/ Must allocate new memory here\n ItemPointer *ip_p = new ItemPointer{location};\n \n \/\/ In Delete() since we just use the value for comparison (i.e. read-only)\n \/\/ it is unnecessary for us to allocate memory\n bool ret = container.DeleteExchange(index_key, &ip_p);\n \n \/\/ IF delete succeeds then DeleteExchange() will exchange the deleted\n \/\/ value into this variable\n if(ret == true) {\n \/\/delete ip_p;\n } else {\n \/\/ This will delete the unused memory\n delete ip_p;\n }\n\n return ret;\n}\n\nBWTREE_TEMPLATE_ARGUMENTS\nbool\nBWTREE_INDEX_TYPE::CondInsertEntry(const storage::Tuple *key,\n const ItemPointer &location,\n std::function predicate) {\n KeyType index_key;\n index_key.SetFromKey(key);\n \n ItemPointer *item_p = new ItemPointer{location};\n bool predicate_satisfied = false;\n \n \/\/ This function will complete them in one step\n \/\/ predicate will be set to nullptr if the predicate\n \/\/ returns true for some value\n bool ret = container.ConditionalInsert(index_key,\n item_p,\n predicate,\n &predicate_satisfied);\n\n \/\/ If predicate is not satisfied then we know insertion successes\n if(predicate_satisfied == false) {\n \/\/ So it should always succeed?\n assert(ret == true);\n } else {\n assert(ret == false);\n \n delete item_p;\n }\n\n return ret;\n}\n\n\nBWTREE_TEMPLATE_ARGUMENTS\nvoid\nBWTREE_INDEX_TYPE::Scan(const std::vector &values,\n const std::vector &key_column_ids,\n const std::vector &expr_types,\n const ScanDirectionType &scan_direction,\n std::vector &result) {\n KeyType index_key;\n\n \/\/ Checkif we have leading (leftmost) column equality\n \/\/ refer : http:\/\/www.postgresql.org\/docs\/8.2\/static\/indexes-multicolumn.html\n oid_t leading_column_id = 0;\n auto key_column_ids_itr = std::find(key_column_ids.begin(),\n key_column_ids.end(), leading_column_id);\n\n \/\/ SPECIAL CASE : leading column id is one of the key column ids\n \/\/ and is involved in a equality constraint\n bool special_case = false;\n if (key_column_ids_itr != key_column_ids.end()) {\n auto offset = std::distance(key_column_ids.begin(), key_column_ids_itr);\n if (expr_types[offset] == EXPRESSION_TYPE_COMPARE_EQUAL) {\n special_case = true;\n }\n }\n\n LOG_TRACE(\"Special case : %d \", special_case);\n\n \/\/ This is only a placeholder that cannot be moved but can be assigned to\n auto scan_begin_itr = container.NullIterator();\n\n std::unique_ptr start_key;\n bool all_constraints_are_equal = false;\n\n \/\/ If it is a special case, we can figure out the range to scan in the index\n if (special_case == true) {\n start_key.reset(new storage::Tuple(metadata->GetKeySchema(), true));\n\n \/\/ Construct the lower bound key tuple\n all_constraints_are_equal = ConstructLowerBoundTuple(\n start_key.get(), values, key_column_ids, expr_types);\n\n LOG_TRACE(\"All constraints are equal : %d \", all_constraints_are_equal);\n\n index_key.SetFromKey(start_key.get());\n\/*\n \/\/ If it is point query then we just do a GetValue() since GetValue()\n \/\/ is way more faster than scanning using iterator\n if(all_constraints_are_equal == true) {\n \/\/printf(\"All constraints are equal\\n\");\n \n \/\/ This retrieves a list of ItemPointer *\n container.GetValue(index_key, result);\n\n return;\n }\n*\/\n \/\/printf(\"Non special case\\n\");\n\n \/\/ This returns an iterator pointing to index_key's values\n scan_begin_itr = container.Begin(index_key);\n } else {\n scan_begin_itr = container.Begin();\n }\n\n switch (scan_direction) {\n case SCAN_DIRECTION_TYPE_FORWARD:\n case SCAN_DIRECTION_TYPE_BACKWARD: {\n \/\/ Scan the index entries in forward direction\n for (auto scan_itr = scan_begin_itr;\n scan_itr.IsEnd() == false;\n scan_itr++) {\n KeyType &scan_current_key = const_cast(scan_itr->first);\n \n auto tuple =\n scan_current_key.GetTupleForComparison(metadata->GetKeySchema());\n\n \/\/ Compare the current key in the scan with \"values\" based on\n \/\/ \"expression types\"\n \/\/ For instance, \"5\" EXPR_GREATER_THAN \"2\" is true\n if (Compare(tuple, key_column_ids, expr_types, values) == true) {\n result.push_back(scan_itr->second);\n } else {\n \/\/ We can stop scanning if we know that all constraints are equal\n if (all_constraints_are_equal == true) {\n break;\n }\n }\n }\n\n } break;\n\n case SCAN_DIRECTION_TYPE_INVALID:\n default:\n throw Exception(\"Invalid scan direction \\n\");\n break;\n }\n\n return;\n}\n\nBWTREE_TEMPLATE_ARGUMENTS\nvoid\nBWTREE_INDEX_TYPE::ScanAllKeys(std::vector &result) {\n auto it = container.Begin();\n\n \/\/ scan all entries\n while (it.IsEnd() == false) {\n result.push_back(it->second);\n it++;\n }\n\n return;\n}\n\nBWTREE_TEMPLATE_ARGUMENTS\nvoid\nBWTREE_INDEX_TYPE::ScanKey(const storage::Tuple *key,\n std::vector &result) {\n KeyType index_key;\n index_key.SetFromKey(key);\n\n \/\/ This function in BwTree fills a given vector\n container.GetValue(index_key, result);\n\n return;\n}\n\nBWTREE_TEMPLATE_ARGUMENTS\nstd::string\nBWTREE_INDEX_TYPE::GetTypeName() const {\n return \"BWTree\";\n}\n\n\/\/ NOTE: If ints key is used as an optimization just uncommend\n\/\/ the following in order to instanciation the template before it is\n\/\/ linked in linking stage\n\n\/*\ntemplate class BWTreeIndex,\n ItemPointer *,\n IntsComparator<1>,\n IntsEqualityChecker<1>,\n IntsHasher<1>,\n ItemPointerComparator,\n ItemPointerHashFunc>;\ntemplate class BWTreeIndex,\n ItemPointer *,\n IntsComparator<2>,\n IntsEqualityChecker<2>,\n IntsHasher<2>,\n ItemPointerComparator,\n ItemPointerHashFunc>;\ntemplate class BWTreeIndex,\n ItemPointer *,\n IntsComparator<3>,\n IntsEqualityChecker<3>,\n IntsHasher<3>,\n ItemPointerComparator,\n ItemPointerHashFunc>;\ntemplate class BWTreeIndex,\n ItemPointer *,\n IntsComparator<4>,\n IntsEqualityChecker<4>,\n IntsHasher<4>,\n ItemPointerComparator,\n ItemPointerHashFunc>;\n*\/\n\n\/\/ Generic key\ntemplate class BWTreeIndex,\n ItemPointer *,\n GenericComparator<4>,\n GenericEqualityChecker<4>,\n GenericHasher<4>,\n ItemPointerComparator,\n ItemPointerHashFunc>;\ntemplate class BWTreeIndex,\n ItemPointer *,\n GenericComparator<8>,\n GenericEqualityChecker<8>,\n GenericHasher<8>,\n ItemPointerComparator,\n ItemPointerHashFunc>;\ntemplate class BWTreeIndex,\n ItemPointer *,\n GenericComparator<16>,\n GenericEqualityChecker<16>,\n GenericHasher<16>,\n ItemPointerComparator,\n ItemPointerHashFunc>;\ntemplate class BWTreeIndex,\n ItemPointer *,\n GenericComparator<64>,\n GenericEqualityChecker<64>,\n GenericHasher<64>,\n ItemPointerComparator,\n ItemPointerHashFunc>;\ntemplate class BWTreeIndex,\n ItemPointer *,\n GenericComparator<256>,\n GenericEqualityChecker<256>,\n GenericHasher<256>,\n ItemPointerComparator,\n ItemPointerHashFunc>;\n\n\/\/ Tuple key\ntemplate class BWTreeIndex;\n\n} \/\/ End index namespace\n} \/\/ End peloton namespace\n<|endoftext|>"} {"text":"\n#include \"lib\/safeint3.hpp\"\n#include \"intrinsic_overflow.hpp\"\n#include \"vmachine.hpp\"\n\nusing namespace usagi;\n\n\/\/ VMにライブラリを登録する。\nvoid IntrinsicOverflow::regist(VMachine& vm) {\n vm.regist_intrinsic_func(\"llvm.sadd.with.overflow.i16\", IntrinsicOverflow::sadd, 16);\n vm.regist_intrinsic_func(\"llvm.sadd.with.overflow.i32\", IntrinsicOverflow::sadd, 32);\n vm.regist_intrinsic_func(\"llvm.sadd.with.overflow.i64\", IntrinsicOverflow::sadd, 64);\n\n vm.regist_intrinsic_func(\"llvm.smul.with.overflow.i16\", IntrinsicOverflow::smul, 16);\n vm.regist_intrinsic_func(\"llvm.smul.with.overflow.i32\", IntrinsicOverflow::smul, 32);\n vm.regist_intrinsic_func(\"llvm.smul.with.overflow.i64\", IntrinsicOverflow::smul, 64);\n\n vm.regist_intrinsic_func(\"llvm.ssub.with.overflow.i16\", IntrinsicOverflow::ssub, 16);\n vm.regist_intrinsic_func(\"llvm.ssub.with.overflow.i32\", IntrinsicOverflow::ssub, 32);\n vm.regist_intrinsic_func(\"llvm.ssub.with.overflow.i64\", IntrinsicOverflow::ssub, 64);\n\n vm.regist_intrinsic_func(\"llvm.uadd.with.overflow.i16\", IntrinsicOverflow::uadd, 16);\n vm.regist_intrinsic_func(\"llvm.uadd.with.overflow.i32\", IntrinsicOverflow::uadd, 32);\n vm.regist_intrinsic_func(\"llvm.uadd.with.overflow.i64\", IntrinsicOverflow::uadd, 64);\n\n vm.regist_intrinsic_func(\"llvm.umul.with.overflow.i16\", IntrinsicOverflow::umul, 16);\n vm.regist_intrinsic_func(\"llvm.umul.with.overflow.i32\", IntrinsicOverflow::umul, 32);\n vm.regist_intrinsic_func(\"llvm.umul.with.overflow.i64\", IntrinsicOverflow::umul, 64);\n\n vm.regist_intrinsic_func(\"llvm.usub.with.overflow.i16\", IntrinsicOverflow::usub, 16);\n vm.regist_intrinsic_func(\"llvm.usub.with.overflow.i32\", IntrinsicOverflow::usub, 32);\n vm.regist_intrinsic_func(\"llvm.usub.with.overflow.i64\", IntrinsicOverflow::usub, 64);\n}\n\n\/**\n * @param SFUNC SafeIntの演算関数\n * @param INT_T 計算のベースになる整数型\n * @param WIDTH 整数のビット幅\n *\/\n#define M_CASE_PER_WIDTH(SFUNC, INT_T, WIDTH)\t\t\t\t\\\n case WIDTH: {\t\t\t\t\t\t\t\t\\\n INT_T a = static_cast(VMachine::read_intrinsic_param_i##WIDTH(src, &seek)); \\\n INT_T b = static_cast(VMachine::read_intrinsic_param_i##WIDTH(src, &seek)); \\\n INT_T res;\t\t\t\t\t\t\t\t\\\n bool flg = SFUNC(a, b, res);\t\t\t\t\\\n *reinterpret_cast(vm.get_raw_addr(dst)) = res;\t\t\\\n *reinterpret_cast(vm.get_raw_addr(dst) + sizeof(INT_T)) = (flg ? 0x00 : 0xff); \\\n } break\n\n\/**\n * @param FNAME 作成する関数名\n * @param SFUNC SafeIntの演算関数\n * @param I16 16bit幅の計算のベースになる整数型\n * @param I32 32bit幅の計算のベースになる整数型\n * @param I64 64bit幅の計算のベースになる整数型\n *\/\n#define M_FUNC_PER_METHOD(FNAME, SFUNC, I16, I32, I64) \\\n bool IntrinsicOverflow::FNAME(VMachine& vm, Thread& th, IntrinsicFuncParam p, \\\n\t\t\t\tvaddr_t dst, std::vector& src) { \\\n int seek = 0;\t\t\t\t\t\t\t\\\n switch (p.i64) {\t\t\t\t\t\t\t\\\n M_CASE_PER_WIDTH(SFUNC, I16, 16);\t\t\t\t\t\\\n M_CASE_PER_WIDTH(SFUNC, I32, 32);\t\t\t\t\t\\\n M_CASE_PER_WIDTH(SFUNC, I64, 64);\t\t\t\t\t\\\n default: assert(false); break;\t\t\t\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n return false;\t\t\t\t\t\t\t\\\n }\n\nM_FUNC_PER_METHOD(sadd, SafeAdd, int16_t, int32_t, int64_t)\nM_FUNC_PER_METHOD(smul, SafeMultiply, int16_t, int32_t, int64_t)\nM_FUNC_PER_METHOD(ssub, SafeSubtract, int16_t, int32_t, int64_t)\nM_FUNC_PER_METHOD(uadd, SafeAdd, uint16_t, uint32_t, uint64_t)\nM_FUNC_PER_METHOD(umul, SafeMultiply, uint16_t, uint32_t, uint64_t)\nM_FUNC_PER_METHOD(usub, SafeSubtract, uint16_t, uint32_t, uint64_t)\n\n#undef M_FUNC_PER_METHOD\n#undef M_CASE_PER_WIDTH\nFix fault of compile on linux. refs #41\n#include \"intrinsic_overflow.hpp\"\n#include \"vmachine.hpp\"\n#include \"lib\/safeint3.hpp\"\n\nusing namespace usagi;\n\n\/\/ VMにライブラリを登録する。\nvoid IntrinsicOverflow::regist(VMachine& vm) {\n vm.regist_intrinsic_func(\"llvm.sadd.with.overflow.i16\", IntrinsicOverflow::sadd, 16);\n vm.regist_intrinsic_func(\"llvm.sadd.with.overflow.i32\", IntrinsicOverflow::sadd, 32);\n vm.regist_intrinsic_func(\"llvm.sadd.with.overflow.i64\", IntrinsicOverflow::sadd, 64);\n\n vm.regist_intrinsic_func(\"llvm.smul.with.overflow.i16\", IntrinsicOverflow::smul, 16);\n vm.regist_intrinsic_func(\"llvm.smul.with.overflow.i32\", IntrinsicOverflow::smul, 32);\n vm.regist_intrinsic_func(\"llvm.smul.with.overflow.i64\", IntrinsicOverflow::smul, 64);\n\n vm.regist_intrinsic_func(\"llvm.ssub.with.overflow.i16\", IntrinsicOverflow::ssub, 16);\n vm.regist_intrinsic_func(\"llvm.ssub.with.overflow.i32\", IntrinsicOverflow::ssub, 32);\n vm.regist_intrinsic_func(\"llvm.ssub.with.overflow.i64\", IntrinsicOverflow::ssub, 64);\n\n vm.regist_intrinsic_func(\"llvm.uadd.with.overflow.i16\", IntrinsicOverflow::uadd, 16);\n vm.regist_intrinsic_func(\"llvm.uadd.with.overflow.i32\", IntrinsicOverflow::uadd, 32);\n vm.regist_intrinsic_func(\"llvm.uadd.with.overflow.i64\", IntrinsicOverflow::uadd, 64);\n\n vm.regist_intrinsic_func(\"llvm.umul.with.overflow.i16\", IntrinsicOverflow::umul, 16);\n vm.regist_intrinsic_func(\"llvm.umul.with.overflow.i32\", IntrinsicOverflow::umul, 32);\n vm.regist_intrinsic_func(\"llvm.umul.with.overflow.i64\", IntrinsicOverflow::umul, 64);\n\n vm.regist_intrinsic_func(\"llvm.usub.with.overflow.i16\", IntrinsicOverflow::usub, 16);\n vm.regist_intrinsic_func(\"llvm.usub.with.overflow.i32\", IntrinsicOverflow::usub, 32);\n vm.regist_intrinsic_func(\"llvm.usub.with.overflow.i64\", IntrinsicOverflow::usub, 64);\n}\n\n\/**\n * @param SFUNC SafeIntの演算関数\n * @param INT_T 計算のベースになる整数型\n * @param WIDTH 整数のビット幅\n *\/\n#define M_CASE_PER_WIDTH(SFUNC, INT_T, WIDTH)\t\t\t\t\\\n case WIDTH: {\t\t\t\t\t\t\t\t\\\n INT_T a = static_cast(VMachine::read_intrinsic_param_i##WIDTH(src, &seek)); \\\n INT_T b = static_cast(VMachine::read_intrinsic_param_i##WIDTH(src, &seek)); \\\n INT_T res;\t\t\t\t\t\t\t\t\\\n bool flg = SFUNC(a, b, res);\t\t\t\t\\\n *reinterpret_cast(vm.get_raw_addr(dst)) = res;\t\t\\\n *reinterpret_cast(vm.get_raw_addr(dst) + sizeof(INT_T)) = (flg ? 0x00 : 0xff); \\\n } break\n\n\/**\n * @param FNAME 作成する関数名\n * @param SFUNC SafeIntの演算関数\n * @param I16 16bit幅の計算のベースになる整数型\n * @param I32 32bit幅の計算のベースになる整数型\n * @param I64 64bit幅の計算のベースになる整数型\n *\/\n#define M_FUNC_PER_METHOD(FNAME, SFUNC, I16, I32, I64) \\\n bool IntrinsicOverflow::FNAME(VMachine& vm, Thread& th, IntrinsicFuncParam p, \\\n\t\t\t\tvaddr_t dst, std::vector& src) { \\\n int seek = 0;\t\t\t\t\t\t\t\\\n switch (p.i64) {\t\t\t\t\t\t\t\\\n M_CASE_PER_WIDTH(SFUNC, I16, 16);\t\t\t\t\t\\\n M_CASE_PER_WIDTH(SFUNC, I32, 32);\t\t\t\t\t\\\n M_CASE_PER_WIDTH(SFUNC, I64, 64);\t\t\t\t\t\\\n default: assert(false); break;\t\t\t\t\t\\\n }\t\t\t\t\t\t\t\t\t\\\n return false;\t\t\t\t\t\t\t\\\n }\n\nM_FUNC_PER_METHOD(sadd, SafeAdd, int16_t, int32_t, int64_t)\nM_FUNC_PER_METHOD(smul, SafeMultiply, int16_t, int32_t, int64_t)\nM_FUNC_PER_METHOD(ssub, SafeSubtract, int16_t, int32_t, int64_t)\nM_FUNC_PER_METHOD(uadd, SafeAdd, uint16_t, uint32_t, uint64_t)\nM_FUNC_PER_METHOD(umul, SafeMultiply, uint16_t, uint32_t, uint64_t)\nM_FUNC_PER_METHOD(usub, SafeSubtract, uint16_t, uint32_t, uint64_t)\n\n#undef M_FUNC_PER_METHOD\n#undef M_CASE_PER_WIDTH\n<|endoftext|>"} {"text":"\/*-\n * Copyright (c) 2015 Alexander Nasonov.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\/\n\n #include \n #include \n\n\/*\n * The algorithm below is based on paper\n * Cache-Oblivious Peeling of Random Hypergraphs by Djamal Belazzougui,\n * Paolo Boldi, Giuseppe Ottaviano, Rossano Venturini, and Sebastiano\n * Vigna.\n * http:\/\/zola.di.unipi.it\/rossano\/wp-content\/papercite-data\/pdf\/dcc14.pdf\n *\/\nnamespace {\n\ntemplate\nstruct edge {\n\tT verts[R];\n\tT idx; \/\/ XXX\n};\n\n\/*\n * Data type for a valid oriented edge (v0, v1, v2), v1 < v2.\n * The first vertex v0 is implicit and is determined by an index\n * of the corresponding element in the oedges array.\n * If the degree of v0 is greater than 1, other members don't make\n * sense because they're a result of XORing multiple random values.\n *\/\ntemplate\nstruct oedge {\n\tT verts[R-1]; \/\/ v1 (and v2, if R==3).\n\tT degree; \/\/ Degree of v0.\n\tT edge;\n};\n\ntemplate\ninline void\nadd_remove_oedge(oedge *oedges, int delta, T e, T v0, T v1)\n{\n\n\toedges[v0].verts[0] ^= v1;\n\toedges[v0].degree += delta;\n\toedges[v0].edge ^= e;\n}\n\ntemplate\ninline void\nremove_edge(oedge *oedges, T e, T v0, T v1)\n{\n\n\treturn add_remove_oedge(oedges, -1, e, v0, v1);\n}\n\ntemplate\ninline void\nadd_remove_oedge(oedge *oedges, int delta, T e, T v0, T v1, T v2)\n{\n\n\toedges[v0].verts[v1 < v2 ? 0 : 1] ^= v1;\n\toedges[v0].verts[v1 < v2 ? 1 : 0] ^= v2;\n\toedges[v0].degree += delta;\n\toedges[v0].edge ^= e;\n}\n\ntemplate\ninline void\nremove_oedge(oedge *oedges, T e, T v0, T v1, T v2)\n{\n\n\treturn add_remove_oedge(oedges, -1, e, v0, v1, v2);\n}\n\ntemplate\ninline void\nadd_edge(oedge *oedges, T e, const T *verts)\n{\n\n\tadd_remove_oedge(oedges, 1, e, verts[0], verts[1]);\n\tadd_remove_oedge(oedges, 1, e, verts[1], verts[0]);\n}\n\ntemplate\ninline void\nadd_edge(oedge *oedges, T e, const T *verts)\n{\n\n\tadd_remove_oedge(oedges, 1, e, verts[0], verts[1], verts[2]);\n\tadd_remove_oedge(oedges, 1, e, verts[1], verts[0], verts[2]);\n\tadd_remove_oedge(oedges, 1, e, verts[2], verts[0], verts[1]);\n}\n\ntemplate\ninline size_t\nremove_vertex(oedge *oedges, T v0, T *order, size_t end)\n{\n\n\tif (oedges[v0].degree == 1) {\n\t\tconst T e = oedges[v0].edge;\n\t\tconst T v1 = oedges[v0].verts[0];\n\t\toedges[v0].degree = 0;\n\t\tremove_oedge(oedges, e, v1, v0);\n\t\torder[--end] = e;\n\t}\n\n\treturn end;\n}\n\ntemplate\ninline size_t\nremove_vertex(oedge *oedges, T v0, T *order, size_t end)\n{\n\n\tif (oedges[v0].degree == 1) {\n\t\tconst T e = oedges[v0].edge;\n\t\tconst T v1 = oedges[v0].verts[0];\n\t\tconst T v2 = oedges[v0].verts[1];\n\t\toedges[v0].degree = 0;\n\t\tremove_oedge(oedges, e, v1, v0, v2);\n\t\tremove_oedge(oedges, e, v2, v0, v1);\n\t\torder[--end] = e;\n\t}\n\n\treturn end;\n}\n\ntemplate\nvoid\nbuild_graph(Iter keys, size_t nkeys, Hash hash, size_t nverts,\n edge *edges, oedge *oedges)\n{\n\t\/\/ Partition size of an R-partite R-graph.\n\tconst T partsz = nverts \/ R;\n\tassert(partsz > 1 && (nverts % R) == 0);\n\n\tfor (size_t i = 0; i < nkeys; ++i, ++keys) {\n\t\tconst T *verts = hash(keys->key, keys->keylen);\n\t\tfor (size_t r = 0; r < R; ++r)\n\t\t\tedges[i].verts[r] = (verts[r] % partsz) + r * partsz;\n\t\tadd_edge(oedges, i, edges[i].verts);\n\t}\n}\n\ntemplate\nsize_t\npeel_graph(edge *edges, size_t nkeys,\n oedge *oedges, size_t nverts, T *order)\n{\n\tsize_t end = nkeys;\n\n\tfor (size_t i = 0; i < nkeys; ++i)\n\t\tend = remove_vertex(oedges, i, order, end);\n\n\tfor (size_t i = nkeys; i > 0 && i > end; --i) {\n\t\tconst edge *e = edges[order[i-1]];\n\t\tfor (size_t r = 0; r < R; ++r)\n\t\t\tend = remove_vertex(oedges, e->verts[r], order, end);\n\t}\n\n\treturn end;\n}\n\n} \/\/ namespace\nverts -> overts in struct oedge.\/*-\n * Copyright (c) 2015 Alexander Nasonov.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\/\n\n #include \n #include \n\n\/*\n * The algorithm below is based on paper\n * Cache-Oblivious Peeling of Random Hypergraphs by Djamal Belazzougui,\n * Paolo Boldi, Giuseppe Ottaviano, Rossano Venturini, and Sebastiano\n * Vigna.\n * http:\/\/zola.di.unipi.it\/rossano\/wp-content\/papercite-data\/pdf\/dcc14.pdf\n *\/\nnamespace {\n\ntemplate\nstruct edge {\n\tT verts[R]; \/\/ v0, v1 (and v2, if R==3).\n\tT idx; \/\/ XXX\n};\n\n\/*\n * Data type for a valid oriented edge (v0, v1, v2), v1 < v2.\n * The first vertex v0 is implicit and is determined by an index\n * of the corresponding element in the oedges array.\n * If the degree of v0 is greater than 1, other members don't make\n * sense because they're a result of XORing multiple random values.\n *\/\ntemplate\nstruct oedge {\n\tT overts[R-1]; \/\/ v1 (and v2, if R==3).\n\tT degree; \/\/ Degree of v0.\n\tT edge;\n};\n\ntemplate\ninline void\nadd_remove_oedge(oedge *oedges, int delta, T e, T v0, T v1)\n{\n\n\toedges[v0].overts[0] ^= v1;\n\toedges[v0].degree += delta;\n\toedges[v0].edge ^= e;\n}\n\ntemplate\ninline void\nremove_edge(oedge *oedges, T e, T v0, T v1)\n{\n\n\treturn add_remove_oedge(oedges, -1, e, v0, v1);\n}\n\ntemplate\ninline void\nadd_remove_oedge(oedge *oedges, int delta, T e, T v0, T v1, T v2)\n{\n\n\toedges[v0].overts[v1 < v2 ? 0 : 1] ^= v1;\n\toedges[v0].overts[v1 < v2 ? 1 : 0] ^= v2;\n\toedges[v0].degree += delta;\n\toedges[v0].edge ^= e;\n}\n\ntemplate\ninline void\nremove_oedge(oedge *oedges, T e, T v0, T v1, T v2)\n{\n\n\treturn add_remove_oedge(oedges, -1, e, v0, v1, v2);\n}\n\ntemplate\ninline void\nadd_edge(oedge *oedges, T e, const T *verts)\n{\n\n\tadd_remove_oedge(oedges, 1, e, verts[0], verts[1]);\n\tadd_remove_oedge(oedges, 1, e, verts[1], verts[0]);\n}\n\ntemplate\ninline void\nadd_edge(oedge *oedges, T e, const T *verts)\n{\n\n\tadd_remove_oedge(oedges, 1, e, verts[0], verts[1], verts[2]);\n\tadd_remove_oedge(oedges, 1, e, verts[1], verts[0], verts[2]);\n\tadd_remove_oedge(oedges, 1, e, verts[2], verts[0], verts[1]);\n}\n\ntemplate\ninline size_t\nremove_vertex(oedge *oedges, T v0, T *order, size_t end)\n{\n\n\tif (oedges[v0].degree == 1) {\n\t\tconst T e = oedges[v0].edge;\n\t\tconst T v1 = oedges[v0].overts[0];\n\t\toedges[v0].degree = 0;\n\t\tremove_oedge(oedges, e, v1, v0);\n\t\torder[--end] = e;\n\t}\n\n\treturn end;\n}\n\ntemplate\ninline size_t\nremove_vertex(oedge *oedges, T v0, T *order, size_t end)\n{\n\n\tif (oedges[v0].degree == 1) {\n\t\tconst T e = oedges[v0].edge;\n\t\tconst T v1 = oedges[v0].overts[0];\n\t\tconst T v2 = oedges[v0].overts[1];\n\t\toedges[v0].degree = 0;\n\t\tremove_oedge(oedges, e, v1, v0, v2);\n\t\tremove_oedge(oedges, e, v2, v0, v1);\n\t\torder[--end] = e;\n\t}\n\n\treturn end;\n}\n\ntemplate\nvoid\nbuild_graph(Iter keys, size_t nkeys, Hash hash, size_t nverts,\n edge *edges, oedge *oedges)\n{\n\t\/\/ Partition size of an R-partite R-graph.\n\tconst T partsz = nverts \/ R;\n\tassert(partsz > 1 && (nverts % R) == 0);\n\n\tfor (size_t i = 0; i < nkeys; ++i, ++keys) {\n\t\tconst T *verts = hash(keys->key, keys->keylen);\n\t\tfor (size_t r = 0; r < R; ++r)\n\t\t\tedges[i].verts[r] = (verts[r] % partsz) + r * partsz;\n\t\tadd_edge(oedges, i, edges[i].verts);\n\t}\n}\n\ntemplate\nsize_t\npeel_graph(edge *edges, size_t nkeys,\n oedge *oedges, size_t nverts, T *order)\n{\n\tsize_t end = nkeys;\n\n\tfor (size_t i = 0; i < nkeys; ++i)\n\t\tend = remove_vertex(oedges, i, order, end);\n\n\tfor (size_t i = nkeys; i > 0 && i > end; --i) {\n\t\tconst edge *e = edges[order[i-1]];\n\t\tfor (size_t r = 0; r < R; ++r)\n\t\t\tend = remove_vertex(oedges, e->verts[r], order, end);\n\t}\n\n\treturn end;\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"a few minor cleanups<|endoftext|>"} {"text":"push latest barnes-hut<|endoftext|>"} {"text":"#include \"stack.hpp\"\n#include \nSCENARIO(\"Stack: init\", \"[init]\") {\n\tstack a;\n\tREQUIRE(sizeof(a) != 0);\n\tREQUIRE(a.count() == 0);\n}\nSCENARIO(\"Stack: operator==\", \"[op==]\") {\n\tstack a, b;\n\ta.push(5);\n\ta.push(3);\n\ta.push(5);\n\tb.push(5);\n\tb.push(3);\n\tb.push(5);\n\tREQUIRE(a == b);\n}\nSCENARIO(\"Stack: operator=\", \"[op=]\") {\n\tstack a;\n\ta.push(1);\n\tstack b;\n\tb = a;\n\tREQUIRE(b == a);\n}\nSCENARIO(\"Stack: count\", \"[op=]\") {\n\tstack a;\n\ta.push(7);\n\ta.push(6);\n\ta.push(8);\n\ta.push(9);\n\tREQUIRE(a.count() == 4);\n}\nSCENARIO(\"Stack: pop\", \"[op=]\") {\n\tstack a;\n\ta.push(7);\n\ta.push(6);\n\ta.push(8);\n\ta.push(9);\n\ta.pop();\n\tREQUIRE(a.count() == 3);\n}\nUpdate init.cpp#include \"stack.hpp\"\n#include \nSCENARIO(\"stack: init\", \"[init]\") {\n\tstack a;\n\tREQUIRE(sizeof(a) != 0);\n\tREQUIRE(a.count() == 0);\n}\nSCENARIO(\"stack: operator==\", \"[op==]\") {\n\tstack a, b;\n\ta.push(5);\n\ta.push(3);\n\ta.push(5);\n\tb.push(5);\n\tb.push(3);\n\tb.push(5);\n\tREQUIRE(a == b);\n}\nSCENARIO(\"stack: operator=\", \"[op=]\") {\n\tstack a;\n\ta.push(1);\n\tstack b;\n\tb = a;\n\tREQUIRE(b == a);\n}\nSCENARIO(\"stack: count\", \"[op=]\") {\n\tstack a;\n\ta.push(7);\n\ta.push(6);\n\ta.push(8);\n\ta.push(9);\n\tREQUIRE(a.count() == 4);\n}\nSCENARIO(\"stack: pop\", \"[op=]\") {\n\tstack a;\n\ta.push(7);\n\ta.push(6);\n\ta.push(8);\n\ta.push(9);\n\ta.pop();\n\tREQUIRE(a.count() == 3);\n}\n<|endoftext|>"} {"text":"#include \n\/\/#include \n#include \n\n\nSCENARIO(\"Stack init\", \"[init\"){\n\tbool mark=false;\n\tstack st;\n\tst.push(1);\n\tst.push(2);\n\tif (st.count()!=0)\n\t{\n\t\tmark=true;\n\t}\n\tREQUIRE(mark);\n}\n\n\n\/*\nSCENARIO(\"Tree init\", \"[init]\") {\n Tree inttree;\n bool mark=false;\n mark=inttree.input(\"in.txt\");\n\t \n\t REQUIRE(mark);\n}\n\nSCENARIO(\"doubleTree init\", \"[init]\") {\n\tTree dtree;\n\tbool mark=false;\n mark=dtree.input(\"indouble.txt\");\n REQUIRE(mark);\n}\nSCENARIO(\"Insert node\",\"[insert]\") {\n\tTree inttree;\n\tbool mark=false;\n\tmark=inttree.insert_node(125);\n\tREQUIRE(mark);\n}\n\nSCENARIO(\"Output tree\",\"[output]\") {\n\tTree inttree;\n\tbool mark=false;\n\tinttree.input(\"in.txt\");\n\tmark=inttree.output(inttree.get_root());\n\tREQUIRE(mark);\n}\n\n\nSCENARIO(\"inorder walk\",\"[inorder]\") {\n\tTree inttree;\n\tbool mark=false;\n\tinttree.input(\"in.txt\");\n\tmark=inttree.inorder_walk(inttree.get_root());\n\tREQUIRE(mark);\n}\n\nSCENARIO(\"inorder walkd\",\"[inotderd]\") {\n\tTree dtree;\n\tbool mark=false;\n\tdtree.input(\"indouble.txt\");\n\tmark=dtree.inorder_walk(dtree.get_root());\n\tREQUIRE(mark);\n}\n\nSCENARIO(\"out<<\",\"[out]\") {\n\tbool mark;\n\tTree inttree;\n\tinttree.input(\"in.txt\");\n\tTreeNode* n=inttree.get_root();\n\tmark=true;\n\ttry\n\t{\n\t\tcout< inttree;\n\ttry\n\t{\n\t\tinttree.input(\"aavavasvas.txt\");\n\t}\n\tcatch (File_Not_Open & e)\n\t{\n\t marker=true;\n\t}\n\tREQUIRE(marker);\n}\n\nSCENARIO(\"Exception out\",\"[exceptout]\") {\n bool marker=false;\n\tTree inttree;\n\ttry\n\t{\n\t inttree.output(inttree.get_root());\n\t}\n\tcatch (Empty_tree & e)\n\t{\n\t marker=true;\n\t}\n\tREQUIRE(marker);\n}\n\nSCENARIO(\"Delete root\",\"[delete r ]\") {\n\t Tree inttree;\n\t inttree.input(\"in.txt\");\n\t \/\/удаление корня\n\t inttree.delete_node(inttree.get_root());\n\t REQUIRE(!inttree.search(inttree.get_root(),5));\n\t REQUIRE(inttree.search(inttree.get_root(),4));\n\t REQUIRE(inttree.search(inttree.get_root(),2));\n\t REQUIRE(inttree.search(inttree.get_root(),3));\n}\n\nSCENARIO(\"Delete node\",\"[delete n]\") {\n\t Tree inttree;\n\t inttree.input(\"in.txt\");\n\t \/\/удаление узла с левым дочерним узлом\n\t TreeNode* node;\n\t node=inttree.find_node(inttree.get_root(),4);\n\t inttree.delete_node(node);\n\t REQUIRE(!inttree.search(inttree.get_root(),4));\n\t REQUIRE(inttree.search(inttree.get_root(),5));\n\t REQUIRE(inttree.search(inttree.get_root(),2));\n\t REQUIRE(inttree.search(inttree.get_root(),3));\n}\n\n*\/\nUpdate init.cpp#include \n#include \n\n\nSCENARIO(\"Stack init\", \"[init\"){\n\tbool mark=false;\n\tstack st;\n\tif ((st.count()==0))\n\t{\n\t\tmark=true;\n\t}\n\tREQUIRE(mark);\n}\n\nSCENARIO(\"Stack push\", \"[push]\"){\n\tbool mark=false;\n\tstack st;\n\tst.push(1);\n\tst.push(2);\n\tif ((st.count()==2)&&(st.pop()==2)&&(st.pop()==1))\n\t{\n\t\tmark=true;\n\t}\n\tREQUIRE(mark);\n}\n\nSCENARIO(\"Stack pop\", \"[pop]\"){\n\tbool mark=false;\n\tstack st;\n\tst.push(123);\n\tif (st.pop()==123)\n\t{\n\t\tmark=true;\n\t}\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n\nTEST_CASE(\"Inline object\")\n{\n SECTION(\"Simple object\")\n {\n vili::node root\n = vili::parser::from_string(\"object: {a: 15, b: [16, 17], c: \\\"18\\\"}\");\n REQUIRE(root[\"object\"][\"a\"].as() == 15);\n REQUIRE(root[\"object\"][\"b\"].as() == vili::array { 16, 17 });\n REQUIRE(root[\"object\"][\"c\"].as() == \"18\");\n }\n}\n\nTEST_CASE(\"Multiline object\")\n{\n SECTION(\"Comma separator\")\n {\n vili::node root = vili::parser::from_string(\n \"object: { a: 15, b: [16, 17], c: \\\"18\\\"}\");\n REQUIRE(root[\"object\"][\"a\"].as() == 15);\n REQUIRE(root[\"object\"][\"b\"].as() == vili::array{ 16, 17 });\n REQUIRE(root[\"object\"][\"c\"].as() == \"18\");\n }\n\n SECTION(\"Newline separator\")\n {\n vili::node root = vili::parser::from_string(\n \"object: {\\n\"\n \"a: 15\\n\"\n \"b: [16, 17]\\n\"\n \"c: \\\"18\\\"\\n\"\n \"}\");\n REQUIRE(root[\"object\"][\"a\"].as() == 15);\n REQUIRE(root[\"object\"][\"b\"].as() == vili::array{ 16, 17 });\n REQUIRE(root[\"object\"][\"c\"].as() == \"18\");\n }\n\n SECTION(\"Mixed separator\")\n {\n vili::node root = vili::parser::from_string(\n \"object: {\\n\"\n \"a: 15,\\n\"\n \"b: [16, 17]\\n\"\n \"c: \\\"18\\\"\\n\"\n \"}\");\n REQUIRE(root[\"object\"][\"a\"].as() == 15);\n REQUIRE(root[\"object\"][\"b\"].as() == vili::array{ 16, 17 });\n REQUIRE(root[\"object\"][\"c\"].as() == \"18\");\n }\n\n SECTION(\"Eol and spaces\")\n {\n vili::node root = vili::parser::from_string(\n \"object: { \\n\"\n \" a: 15 \\n\"\n \" , \\n\"\n \"b: [16, 17] \\n\"\n \"\\n\"\n \" c: \\\"18\\\" \\n\"\n \"}\");\n REQUIRE(root[\"object\"][\"a\"].as() == 15);\n REQUIRE(root[\"object\"][\"b\"].as() == vili::array{ 16, 17 });\n REQUIRE(root[\"object\"][\"c\"].as() == \"18\");\n }\n\n}\n\nTEST_CASE(\"Nested objects\")\n{\n SECTION(\"One object inside object\")\n {\n vili::node root = vili::parser::from_string(\n \"object: {\\n\"\n \"a: 15,\\n\"\n \"b: {\\n\"\n \"a: 16, b: 17},\\n\"\n \"c: \\\"18\\\"\\n\"\n \"}\");\n REQUIRE(root[\"object\"][\"a\"].as() == 15);\n REQUIRE(root[\"object\"][\"b\"][\"a\"].as() == 16);\n REQUIRE(root[\"object\"][\"b\"][\"b\"].as() == 17);\n REQUIRE(root[\"object\"][\"c\"].as() == \"18\");\n }\n}\n\nTEST_CASE(\"Incorrect object\")\n{\n SECTION(\"Missing closing bracket\")\n {\n REQUIRE_THROWS_AS(vili::parser::from_string(\n \"object: {\\n\"\n \"a: 15,\\n\"\n \"b: [16, 17]\\n\"\n \"c: \\\"18\\\"\\n\"),\n vili::exceptions::parsing_error);\n }\n\n SECTION(\"Missing opening bracket\")\n {\n REQUIRE_THROWS_AS(vili::parser::from_string(\n \"object: \\n\"\n \"a: 15,\\n\"\n \"b: [16, 17]\\n\"\n \"c: \\\"18\\\"\\n\"\n \"}\"),\n vili::exceptions::parsing_error);\n }\n\n SECTION(\"Comma after last element\")\n {\n REQUIRE_THROWS_AS(vili::parser::from_string(\n \"object: {\\n\"\n \"a: 15,\\n\"\n \"b: [16, 17]\\n\"\n \"c: \\\"18\\\",\\n\"\n \"}\"),\n vili::exceptions::parsing_error);\n }\n\n SECTION(\"Missing comma\")\n {\n REQUIRE_THROWS_AS(vili::parser::from_string(\n \"object: {\\n\"\n \"a: 15,\\n\"\n \"b: [16, 17] c: \\\"18\\\",\\n\"\n \"}\"),\n vili::exceptions::parsing_error);\n }\n\n SECTION(\"Newline after opening bracket\")\n {\n REQUIRE_THROWS_AS(vili::parser::from_string(\n \"object: \\n\"\n \"{\\n\"\n \"a: 15,\\n\"\n \"b: [16, 17] c: \\\"18\\\",\\n\"\n \"}\"),\n vili::exceptions::parsing_error);\n }\n}Added empty object tests#include \n\n#include \n\nTEST_CASE(\"Inline object\")\n{\n SECTION(\"Simple object\")\n {\n vili::node root\n = vili::parser::from_string(\"object: {a: 15, b: [16, 17], c: \\\"18\\\"}\");\n REQUIRE(root[\"object\"][\"a\"].as() == 15);\n REQUIRE(root[\"object\"][\"b\"].as() == vili::array { 16, 17 });\n REQUIRE(root[\"object\"][\"c\"].as() == \"18\");\n }\n\n SECTION(\"Empty object\")\n {\n vili::node root\n = vili::parser::from_string(\"object: {}\");\n REQUIRE(root[\"object\"].empty());\n }\n}\n\nTEST_CASE(\"Multiline object\")\n{\n SECTION(\"Empty object\")\n {\n vili::node root = vili::parser::from_string(\n \"object: {\\n\"\n \" \\n\"\n \" }\");\n REQUIRE(root[\"object\"].empty());\n }\n\n SECTION(\"Comma separator\")\n {\n vili::node root = vili::parser::from_string(\n \"object: { a: 15, b: [16, 17], c: \\\"18\\\"}\");\n REQUIRE(root[\"object\"][\"a\"].as() == 15);\n REQUIRE(root[\"object\"][\"b\"].as() == vili::array{ 16, 17 });\n REQUIRE(root[\"object\"][\"c\"].as() == \"18\");\n }\n\n SECTION(\"Newline separator\")\n {\n vili::node root = vili::parser::from_string(\n \"object: {\\n\"\n \"a: 15\\n\"\n \"b: [16, 17]\\n\"\n \"c: \\\"18\\\"\\n\"\n \"}\");\n REQUIRE(root[\"object\"][\"a\"].as() == 15);\n REQUIRE(root[\"object\"][\"b\"].as() == vili::array{ 16, 17 });\n REQUIRE(root[\"object\"][\"c\"].as() == \"18\");\n }\n\n SECTION(\"Mixed separator\")\n {\n vili::node root = vili::parser::from_string(\n \"object: {\\n\"\n \"a: 15,\\n\"\n \"b: [16, 17]\\n\"\n \"c: \\\"18\\\"\\n\"\n \"}\");\n REQUIRE(root[\"object\"][\"a\"].as() == 15);\n REQUIRE(root[\"object\"][\"b\"].as() == vili::array{ 16, 17 });\n REQUIRE(root[\"object\"][\"c\"].as() == \"18\");\n }\n\n SECTION(\"Eol and spaces\")\n {\n vili::node root = vili::parser::from_string(\n \"object: { \\n\"\n \" a: 15 \\n\"\n \" , \\n\"\n \"b: [16, 17] \\n\"\n \"\\n\"\n \" c: \\\"18\\\" \\n\"\n \"}\");\n REQUIRE(root[\"object\"][\"a\"].as() == 15);\n REQUIRE(root[\"object\"][\"b\"].as() == vili::array{ 16, 17 });\n REQUIRE(root[\"object\"][\"c\"].as() == \"18\");\n }\n\n}\n\nTEST_CASE(\"Nested objects\")\n{\n SECTION(\"One object inside object\")\n {\n vili::node root = vili::parser::from_string(\n \"object: {\\n\"\n \"a: 15,\\n\"\n \"b: {\\n\"\n \"a: 16, b: 17},\\n\"\n \"c: \\\"18\\\"\\n\"\n \"}\");\n REQUIRE(root[\"object\"][\"a\"].as() == 15);\n REQUIRE(root[\"object\"][\"b\"][\"a\"].as() == 16);\n REQUIRE(root[\"object\"][\"b\"][\"b\"].as() == 17);\n REQUIRE(root[\"object\"][\"c\"].as() == \"18\");\n }\n}\n\nTEST_CASE(\"Incorrect object\")\n{\n SECTION(\"Missing closing bracket\")\n {\n REQUIRE_THROWS_AS(vili::parser::from_string(\n \"object: {\\n\"\n \"a: 15,\\n\"\n \"b: [16, 17]\\n\"\n \"c: \\\"18\\\"\\n\"),\n vili::exceptions::parsing_error);\n }\n\n SECTION(\"Missing opening bracket\")\n {\n REQUIRE_THROWS_AS(vili::parser::from_string(\n \"object: \\n\"\n \"a: 15,\\n\"\n \"b: [16, 17]\\n\"\n \"c: \\\"18\\\"\\n\"\n \"}\"),\n vili::exceptions::parsing_error);\n }\n\n SECTION(\"Comma after last element\")\n {\n REQUIRE_THROWS_AS(vili::parser::from_string(\n \"object: {\\n\"\n \"a: 15,\\n\"\n \"b: [16, 17]\\n\"\n \"c: \\\"18\\\",\\n\"\n \"}\"),\n vili::exceptions::parsing_error);\n }\n\n SECTION(\"Missing comma\")\n {\n REQUIRE_THROWS_AS(vili::parser::from_string(\n \"object: {\\n\"\n \"a: 15,\\n\"\n \"b: [16, 17] c: \\\"18\\\",\\n\"\n \"}\"),\n vili::exceptions::parsing_error);\n }\n\n SECTION(\"Newline after opening bracket\")\n {\n REQUIRE_THROWS_AS(vili::parser::from_string(\n \"object: \\n\"\n \"{\\n\"\n \"a: 15,\\n\"\n \"b: [16, 17] c: \\\"18\\\",\\n\"\n \"}\"),\n vili::exceptions::parsing_error);\n }\n}<|endoftext|>"} {"text":"#include \"CppUTest\/TestHarness.h\"\n\n#include \n\n#include \"vrp.h\"\n\nTEST_GROUP(ReadVrpFile)\n{\n Vrp *vrp;\n\n void setup(void)\n {\n vrp = new Vrp(\"Vrp-All\/E\/E-n13-k4.vrp\");\n }\n\n void teardown(void)\n {\n delete vrp;\n }\n};\n\nTEST(ReadVrpFile, name)\n{\n std::string name = vrp->name();\n\n CHECK_EQUAL(\"E-n13-k4\", name);\n}\n\nTEST(ReadVrpFile, demension)\n{\n LONGS_EQUAL(13, vrp->demension());\n}\n\nTEST(ReadVrpFile, edge_weight_type)\n{\n CHECK_EQUAL(\"EXPLICIT\", vrp->edge_weight_type());\n}\n不要な中間変数を削除#include \"CppUTest\/TestHarness.h\"\n\n#include \n\n#include \"vrp.h\"\n\nTEST_GROUP(ReadVrpFile)\n{\n Vrp *vrp;\n\n void setup(void)\n {\n vrp = new Vrp(\"Vrp-All\/E\/E-n13-k4.vrp\");\n }\n\n void teardown(void)\n {\n delete vrp;\n }\n};\n\nTEST(ReadVrpFile, name)\n{\n CHECK_EQUAL(\"E-n13-k4\", vrp->name());\n}\n\nTEST(ReadVrpFile, demension)\n{\n LONGS_EQUAL(13, vrp->demension());\n}\n\nTEST(ReadVrpFile, edge_weight_type)\n{\n CHECK_EQUAL(\"EXPLICIT\", vrp->edge_weight_type());\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ main2.cpp\n\/\/ test_SCUD\n\/\/\n\/\/ Created by Boris Vigman on 08\/07\/2017.\n\/\/ Copyright © 2017-2019 Boris Vigman. All rights reserved.\n\/\/\n\n\n#include \"scud.h\"\n\nusing namespace SCUD;\n\n#include \n#include \n#include \n#include \"vector\"\n\ntemplate class Queue1:public LinkableQueue{\n \n};\ntemplate class Dropper1:public LinkableDropper{\npublic:\n \n void processOnPush(TSchedulable sch, long long schedulingParam){\n int x=0;\n }\n void processOnPull(TSchedulable sch, long long schedulingParam){\n int x=0;\n }\n void processOnPullPush(TSchedulable sch, long long schedulingParam){\n int x=0;\n }\n};\nclass Source{\n char priority;\n float weight;\n int label;\n long long delay;\n Queue1 queue0;\n LinkableQueue queue1;\n Dropper1 drop0;\n LinkableDropper drop1;\n LinkablePass pass1,pass2;\n \/\/LinkablePass pass;\n void run(){\n SCUD_RC r0;\n drop1.unlink(&r0);\n drop0.setPriority(7);\n drop1.setPriority(priority);\n SCUD_RC rc= queue0.setPriority(priority);std::cout<0){\n SCUD_RC status=SCUD_RC_OK;\n \/\/queue.unlink(&status);\n \/\/std::cout<<\"loop: source\"<linkPredecessor(&drop1);\n \n \/\/}\n while(1){\n std::this_thread::sleep_for(std::chrono::milliseconds(delay));\n \n \/\/buildCompound();\n auto start= std::chrono::high_resolution_clock::now() ;\n \/\/drop0.push(label, label*10);\n queue0.push(label, 100);\n queue0.push(label, 100);\n queue0.push(label, 100);\n queue0.push(label, 100);\n auto end= std::chrono::high_resolution_clock::now() ;\n auto diff = end - start;\n \/\/std::cout<<\"Push delay=\"<(diff).count()<(diff).count()<::LinkedObjectsTuple lot1=drop1.unlink(&status);\n if(status!=SCUD_RC_OK){\n std::cout<::LinkedObjectsTuple lot2=queue0.unlink(&status);\n if(status!=SCUD_RC_OK){\n std::cout<::LinkedObjectsTuple lot3=queue1.unlink(&status);\n if(status!=SCUD_RC_OK){\n std::cout<* compoundBegin(){\n \/\/return &drop0;\n return &queue0;\n }\n Linkable* compoundEnd(){\n \/\/return &drop1;\n \/\/return &pass2;\n return &queue0;\n }\n};\n\nclass Sink{\n LinkableSchedulerPriority scheduler;\n \/\/LinkableSchedulerNaiveRR scheduler;\n \/\/LinkableSchedulerDRR scheduler;\n \/\/LinkableSchedulerWFQ scheduler;\n LinkableNull null;\n void run(){\n scheduler.setPriority(9);\n \/\/scheduler.setWeight(1);\n \n \/\/ while(1){\n \/\/ \/\/std::cout<<\"loop: sink\"<::Queueable res;\n \/\/\/\/ rc=next->pull(res);\n \/\/\/\/ if(rc==SCUD_RC_OK){\n \/\/\/\/ std::cout<<\"Sink: Pulled object \"<100000){\n \/\/\/\/ int x=0;\n \/\/\/\/ }\n \/\/ }\n }\npublic:\n Sink(Linkable* l){\n \n }\n std::thread start() {\n return std::thread([=] { run(); });\n }\n \n void buildCompound(){\n scheduler.linkSuccessor(&null);\n };\n void breakCompound(){\n SCUD_RC status=SCUD_RC_OK;\n null.unlink(&status);\n };\n Linkable* compoundBegin(){\n return &scheduler;\n }\n Linkable* compoundEnd(){\n return &null;\n }\n \n};\nclass Mixer{\n std::vector v;\n Sink* sink;\n std::vector output;\n void runlego(){\n while (1) {\n std::this_thread::sleep_for(std::chrono::milliseconds(1000));\n sink->breakCompound();\n std::this_thread::sleep_for(std::chrono::milliseconds(1000));\n sink->buildCompound();\n \n \/\/std::cout<<\"loop: mixer\"<breakCompound();\n }\n \n for(int i=0;ibuildCompound();\n std::this_thread::sleep_for(std::chrono::milliseconds(1000));\n sink->compoundBegin()->linkPredecessor(v[i]->compoundEnd());\n }\n }\n \n }\n void run()\n {\n SCUD_RC rc=SCUD_RC_OK;\n int s=v.size();\n sink->buildCompound();\n for(long i=s-1;i>-1;i--){\n v[i]->buildCompound();\n \/\/std::this_thread::sleep_for(std::chrono::milliseconds(1000));\n sink->compoundBegin()->linkPredecessor(v[i]->compoundEnd());\n }\n for(int i=0;ibreakCompound();\n }\n \n for(int i=0;ibuildCompound();\n std::this_thread::sleep_for(std::chrono::milliseconds(1000));\n sink->compoundBegin()->linkPredecessor(v[i]->compoundEnd());\n }\n while (1) {\n \/\/std::cout<<\"loop: mixer 0\"<::Queueable res;\n res.scheduled=-1;\n auto start= std::chrono::high_resolution_clock::now() ;\n rc=sink->compoundEnd()->pull(res);\n auto end= std::chrono::high_resolution_clock::now() ;\n auto diff = end - start;\n \/\/std::cout<<\"Pull delay=\"<(diff).count()< null;\n Sink si0(0);\n \n \n m.addSink(&si0);\n \n std::thread t1=s1.start();\n std::thread t2=s2.start();\n std::thread t3=s3.start();\n std::thread t4=s4.start();\n std::thread ti0=si0.start();\n \n std::thread m0=m.start();\n \/\/std::thread mlego=m.startlego();\n \n t1.join();\n t2.join();\n t3.join();\n t4.join();\n ti0.join();\n m0.join();\n \/\/mlego.join();\n \n std::cout << \"done!\\n\";\n}\n\nUpdate main.cpp\/\/\n\/\/ main2.cpp\n\/\/ test_SCUD\n\/\/\n\/\/ Created by Boris Vigman on 08\/07\/2017.\n\/\/ Copyright © 2017-2019 Boris Vigman. All rights reserved.\n\/\/\n\n\/*\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n \n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n \n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see .\n *\/\n\n#include \"scud.h\"\n\nusing namespace SCUD;\n\n#include \n#include \n#include \n#include \"vector\"\n\ntemplate class Queue1:public LinkableQueue{\n \n};\ntemplate class Dropper1:public LinkableDropper{\npublic:\n \n void processOnPush(TSchedulable sch, long long schedulingParam){\n int x=0;\n }\n void processOnPull(TSchedulable sch, long long schedulingParam){\n int x=0;\n }\n void processOnPullPush(TSchedulable sch, long long schedulingParam){\n int x=0;\n }\n};\nclass Source{\n char priority;\n float weight;\n int label;\n long long delay;\n Queue1 queue0;\n LinkableQueue queue1;\n Dropper1 drop0;\n LinkableDropper drop1;\n LinkablePass pass1,pass2;\n \/\/LinkablePass pass;\n void run(){\n SCUD_RC r0;\n drop1.unlink(&r0);\n drop0.setPriority(7);\n drop1.setPriority(priority);\n SCUD_RC rc= queue0.setPriority(priority);std::cout<0){\n SCUD_RC status=SCUD_RC_OK;\n \/\/queue.unlink(&status);\n \/\/std::cout<<\"loop: source\"<linkPredecessor(&drop1);\n \n \/\/}\n while(1){\n std::this_thread::sleep_for(std::chrono::milliseconds(delay));\n \n \/\/buildCompound();\n auto start= std::chrono::high_resolution_clock::now() ;\n \/\/drop0.push(label, label*10);\n queue0.push(label, 100);\n queue0.push(label, 100);\n queue0.push(label, 100);\n queue0.push(label, 100);\n auto end= std::chrono::high_resolution_clock::now() ;\n auto diff = end - start;\n \/\/std::cout<<\"Push delay=\"<(diff).count()<(diff).count()<::LinkedObjectsTuple lot1=drop1.unlink(&status);\n if(status!=SCUD_RC_OK){\n std::cout<::LinkedObjectsTuple lot2=queue0.unlink(&status);\n if(status!=SCUD_RC_OK){\n std::cout<::LinkedObjectsTuple lot3=queue1.unlink(&status);\n if(status!=SCUD_RC_OK){\n std::cout<* compoundBegin(){\n \/\/return &drop0;\n return &queue0;\n }\n Linkable* compoundEnd(){\n \/\/return &drop1;\n \/\/return &pass2;\n return &queue0;\n }\n};\n\nclass Sink{\n LinkableSchedulerPriority scheduler;\n \/\/LinkableSchedulerNaiveRR scheduler;\n \/\/LinkableSchedulerDRR scheduler;\n \/\/LinkableSchedulerWFQ scheduler;\n LinkableNull null;\n void run(){\n scheduler.setPriority(9);\n \/\/scheduler.setWeight(1);\n \n \/\/ while(1){\n \/\/ \/\/std::cout<<\"loop: sink\"<::Queueable res;\n \/\/\/\/ rc=next->pull(res);\n \/\/\/\/ if(rc==SCUD_RC_OK){\n \/\/\/\/ std::cout<<\"Sink: Pulled object \"<100000){\n \/\/\/\/ int x=0;\n \/\/\/\/ }\n \/\/ }\n }\npublic:\n Sink(Linkable* l){\n \n }\n std::thread start() {\n return std::thread([=] { run(); });\n }\n \n void buildCompound(){\n scheduler.linkSuccessor(&null);\n };\n void breakCompound(){\n SCUD_RC status=SCUD_RC_OK;\n null.unlink(&status);\n };\n Linkable* compoundBegin(){\n return &scheduler;\n }\n Linkable* compoundEnd(){\n return &null;\n }\n \n};\nclass Mixer{\n std::vector v;\n Sink* sink;\n std::vector output;\n void runlego(){\n while (1) {\n std::this_thread::sleep_for(std::chrono::milliseconds(1000));\n sink->breakCompound();\n std::this_thread::sleep_for(std::chrono::milliseconds(1000));\n sink->buildCompound();\n \n \/\/std::cout<<\"loop: mixer\"<breakCompound();\n }\n \n for(int i=0;ibuildCompound();\n std::this_thread::sleep_for(std::chrono::milliseconds(1000));\n sink->compoundBegin()->linkPredecessor(v[i]->compoundEnd());\n }\n }\n \n }\n void run()\n {\n SCUD_RC rc=SCUD_RC_OK;\n int s=v.size();\n sink->buildCompound();\n for(long i=s-1;i>-1;i--){\n v[i]->buildCompound();\n \/\/std::this_thread::sleep_for(std::chrono::milliseconds(1000));\n sink->compoundBegin()->linkPredecessor(v[i]->compoundEnd());\n }\n for(int i=0;ibreakCompound();\n }\n \n for(int i=0;ibuildCompound();\n std::this_thread::sleep_for(std::chrono::milliseconds(1000));\n sink->compoundBegin()->linkPredecessor(v[i]->compoundEnd());\n }\n while (1) {\n \/\/std::cout<<\"loop: mixer 0\"<::Queueable res;\n res.scheduled=-1;\n auto start= std::chrono::high_resolution_clock::now() ;\n rc=sink->compoundEnd()->pull(res);\n auto end= std::chrono::high_resolution_clock::now() ;\n auto diff = end - start;\n \/\/std::cout<<\"Pull delay=\"<(diff).count()< null;\n Sink si0(0);\n \n \n m.addSink(&si0);\n \n std::thread t1=s1.start();\n std::thread t2=s2.start();\n std::thread t3=s3.start();\n std::thread t4=s4.start();\n std::thread ti0=si0.start();\n \n std::thread m0=m.start();\n \/\/std::thread mlego=m.startlego();\n \n t1.join();\n t2.join();\n t3.join();\n t4.join();\n ti0.join();\n m0.join();\n \/\/mlego.join();\n \n std::cout << \"done!\\n\";\n}\n\n<|endoftext|>"} {"text":"INTEGRATION: CWS res32bit (1.3.10); FILE MERGED 2004\/10\/27 17:50:54 pl 1.3.10.3: minor updates 2004\/10\/22 15:10:23 pl 1.3.10.2: removed a warning 2004\/10\/22 13:54:35 pl 1.3.10.1: #i34513# free rsc of 32 bit constraints<|endoftext|>"} {"text":"\/\/=================================================================================================\n\/\/ Copyright (c) 2011, Johannes Meyer, TU Darmstadt\n\/\/ All rights reserved.\n\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of the Flight Systems and Automatic Control group,\n\/\/ TU Darmstadt, nor the names of its contributors may be used to\n\/\/ endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\/\/ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n\/\/ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\/\/ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/=================================================================================================\n\n#include \n#include \n\nnamespace hector_quadrotor_pose_estimation {\n\nQuadrotorPoseEstimationNode::QuadrotorPoseEstimationNode(const SystemPtr& system, const StatePtr& state)\n : PoseEstimationNode(system, state)\n{\n pose_estimation_->addMeasurement(new Baro(\"baro\"));\n}\n\nQuadrotorPoseEstimationNode::~QuadrotorPoseEstimationNode()\n{\n}\n\nbool QuadrotorPoseEstimationNode::init() {\n if (!PoseEstimationNode::init()) return false;\n baro_subscriber_ = getNodeHandle().subscribe(\"altimeter\", 10, &QuadrotorPoseEstimationNode::baroCallback, this);\n height_subscriber_.shutdown();\n return true;\n}\n\nvoid QuadrotorPoseEstimationNode::baroCallback(const hector_uav_msgs::AltimeterConstPtr& altimeter) {\n pose_estimation_->getMeasurement(\"baro\")->add(Baro::Update(altimeter->pressure, altimeter->qnh));\n}\n\n} \/\/ namespace hector_quadrotor_pose_estimation\nhector_pose_estimation_core: update raw baro height as position.z component in sensor pose\/\/=================================================================================================\n\/\/ Copyright (c) 2011, Johannes Meyer, TU Darmstadt\n\/\/ All rights reserved.\n\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of the Flight Systems and Automatic Control group,\n\/\/ TU Darmstadt, nor the names of its contributors may be used to\n\/\/ endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\/\/ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n\/\/ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\/\/ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/=================================================================================================\n\n#include \n#include \n\nnamespace hector_quadrotor_pose_estimation {\n\nQuadrotorPoseEstimationNode::QuadrotorPoseEstimationNode(const SystemPtr& system, const StatePtr& state)\n : PoseEstimationNode(system, state)\n{\n pose_estimation_->addMeasurement(new Baro(\"baro\"));\n}\n\nQuadrotorPoseEstimationNode::~QuadrotorPoseEstimationNode()\n{\n}\n\nbool QuadrotorPoseEstimationNode::init() {\n if (!PoseEstimationNode::init()) return false;\n baro_subscriber_ = getNodeHandle().subscribe(\"altimeter\", 10, &QuadrotorPoseEstimationNode::baroCallback, this);\n height_subscriber_.shutdown();\n return true;\n}\n\nvoid QuadrotorPoseEstimationNode::baroCallback(const hector_uav_msgs::AltimeterConstPtr& altimeter) {\n pose_estimation_->getMeasurement(\"baro\")->add(Baro::Update(altimeter->pressure, altimeter->qnh));\n\n if (sensor_pose_publisher_) {\n boost::shared_ptr baro = boost::static_pointer_cast(pose_estimation_->getMeasurement(\"baro\"));\n sensor_pose_.pose.position.z = baro->getModel()->getAltitude(Baro::Update(altimeter->pressure, altimeter->qnh)) - baro->getElevation();\n }\n}\n\n} \/\/ namespace hector_quadrotor_pose_estimation\n<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems,\n * University of Southern California\n * Jan Issac (jan.issac@gmail.com)\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n\/**\n * @date 05\/25\/2014\n * @author Jan Issac (jan.issac@gmail.com)\n * @author Manuel Wuthrich (manuel.wuthrich@gmail.com)\n * Max-Planck-Institute for Intelligent Systems, University of Southern California (USC)\n *\/\n\n#ifndef STATE_FILTERING_DISTRIBUTION_FEATURES_SAMPLEBALE_HPP\n#define STATE_FILTERING_DISTRIBUTION_FEATURES_SAMPLEBALE_HPP\n\n\n#include \n\nnamespace distributions\n{\n\ntemplate \nclass Sampleable: public Distribution\n{\npublic:\n typedef Distribution BaseType;\n typedef typename BaseType::ScalarType ScalarType;\n typedef typename BaseType::VectorType VectorType;\n\npublic:\n virtual ~Sampleable() { }\n\n virtual VectorType Sample() = 0;\n};\n\n}\n\n#endif\n- Uses ::sf namespace & removed distribution namespace. - Unified template parameters to . - Omitted suffix \"Type\" since it does not provide any further meaning.\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems,\n * University of Southern California\n * Jan Issac (jan.issac@gmail.com)\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n\/**\n * @date 05\/25\/2014\n * @author Jan Issac (jan.issac@gmail.com)\n * @author Manuel Wuthrich (manuel.wuthrich@gmail.com)\n * Max-Planck-Institute for Intelligent Systems,\n * University of Southern California (USC)\n *\/\n\n#ifndef STATE_FILTERING_DISTRIBUTION_FEATURES_SAMPLEBALE_HPP\n#define STATE_FILTERING_DISTRIBUTION_FEATURES_SAMPLEBALE_HPP\n\n\n\n\nnamespace sf\n{\n\ntemplate \nclass Sampleable\n{\npublic:\n virtual Vector Sample() = 0;\n};\n\n}\n\n#endif\n<|endoftext|>"} {"text":"\/* \n * File: Audio.h\n * Author: morgan\n *\n * Created on May 7, 2014, 9:41 PM\n *\/\n\n#ifndef MO_AUDIO_H\n#define\tMO_AUDIO_H\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"streamsource.hpp\"\n#include \"soundsource.hpp\"\n\nnamespace mo { \n\n \/*!\n * Audio player class. Uses OpenAL for Windows\/Linux\/OSX.\n *\/\n class Audio {\n public:\n Audio();\n virtual ~Audio();\n\n \/**\n * Play audio from a SoundSource object. A sound source contains one sound.\n * \n * @param source\n *\/\n void init(const SoundSource & source);\n\n \/**\n * Plays audio from a StreamSource. Which streams content from a file. This\n * method starts a new thread for each source playing.\n *\n * @brief play\n * @param stream_source\n *\/\n void init(const StreamSource & stream_source);\n\n \/**\n * Updates the internal source representation with data. Data\n * such as position, velocity, pitch and gain.\n *\n * @brief update\n * @param stream_source\n *\/\n void update(SoundSource & source);\n\n\t\t\/**\n\t\t* Updates the internal source representation with data. Data\n\t\t* such as position, velocity, pitch and gain.\n\t\t*\n\t\t* @brief update\n\t\t* @param stream_source\n\t\t*\/\n void update(StreamSource & source);\n\n\t\t\/**\n\t\t* Updates the internal source representation with data. Data\n\t\t* such as position, velocity, pitch and gain.\n\t\t*\n\t\t* @brief update\n\t\t* @param stream_source\n\t\t*\/\n glm::vec3 listener_position();\n\n\t\t\/**\n\t\t* Set the listener position. \n\t\t*\n\t\t* @brief listener_position\n\t\t* @param position\n\t\t*\/\n void listener_position(const glm::vec3 position);\n\n\t\t\/**\n\t\t* Get the listener position\n\t\t*\n\t\t* @brief listener_position\t\n\t\t*\/\n glm::vec3 listener_orientation();\n\n\t\t\/**\n\t\t* Set the listener orientation.\n\t\t*\n\t\t* @brief listener_orientation\n\t\t* @param orientation, up\n\t\t*\/\n void listener_orientation(const glm::vec3 orientation, const glm::vec3 up = glm::vec3(0.0f, 0.0f, 1.0f));\n \n\t\t\/**\n\t\t* Get the listener velocity.\n\t\t*\n\t\t* @brief listener_velocity\n\t\t*\/\n\t\tglm::vec3 listener_velocity();\n\n\t\t\/**\n\t\t* Set the listener velocity.\n\t\t*\n\t\t* @brief listener_velocity\n\t\t* @param velocity\n\t\t*\/\n void listener_velocity(const glm::vec3 velocity);\n private:\n\t\tstruct StreamThread {\n\t\t\tstd::shared_ptr thread;\n\t\t\tbool running;\n\t\t};\n\n ALCdevice * device_;\n ALCcontext * context_;\n\n using SourcePair = std::pair;\n using BufferPair = std::pair;\n using Sources = std::unordered_map;\n using Buffers = std::unordered_map; \n\n Sources sources_;\n Buffers buffers_; \n\n std::unordered_map stream_threads;\t\t\n };\n}\n\n#endif\t\/* MO_AUDIO_H *\/\n\nBatch update init.\/* \n * File: Audio.h\n * Author: morgan\n *\n * Created on May 7, 2014, 9:41 PM\n *\/\n\n#ifndef MO_AUDIO_H\n#define\tMO_AUDIO_H\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"streamsource.hpp\"\n#include \"soundsource.hpp\"\n\nnamespace mo { \n\n \/*!\n * Audio player class. Uses OpenAL for Windows\/Linux\/OSX.\n *\/\n class Audio {\n public:\n Audio();\n virtual ~Audio();\n\n template\n \/*!\n * A generalized init method\n *\n * @brief init\n * @param begin\n * @param end\n *\/\n void init(It begin, It end) {\n for (auto it = begin; it != end; it++){\n init(*it);\n }\n }\n\n \/**\n * Play audio from a SoundSource object. A sound source contains one sound.\n * \n * @param source\n *\/\n void init(const SoundSource & source);\n\n \/**\n * Plays audio from a StreamSource. Which streams content from a file. This\n * method starts a new thread for each source playing.\n *\n * @brief play\n * @param stream_source\n *\/\n void init(const StreamSource & stream_source);\n\n template\n \/*!\n * A generalized update method\n *\n * @brief init\n * @param begin iterator\n * @param end iterator\n *\/\n void update(It begin, It end) {\n for (auto it = begin; it != end; it++){\n update(*it);\n }\n }\n\n\n \/**\n * Updates the internal source representation with data. Data\n * such as position, velocity, pitch and gain.\n *\n * @brief update\n * @param stream_source\n *\/\n void update(SoundSource & source);\n\n\t\t\/**\n\t\t* Updates the internal source representation with data. Data\n\t\t* such as position, velocity, pitch and gain.\n\t\t*\n\t\t* @brief update\n\t\t* @param stream_source\n\t\t*\/\n void update(StreamSource & source);\n\n\t\t\/**\n\t\t* Updates the internal source representation with data. Data\n\t\t* such as position, velocity, pitch and gain.\n\t\t*\n\t\t* @brief update\n\t\t* @param stream_source\n\t\t*\/\n glm::vec3 listener_position();\n\n\t\t\/**\n\t\t* Set the listener position. \n\t\t*\n\t\t* @brief listener_position\n\t\t* @param position\n\t\t*\/\n void listener_position(const glm::vec3 position);\n\n\t\t\/**\n\t\t* Get the listener position\n\t\t*\n\t\t* @brief listener_position\t\n\t\t*\/\n glm::vec3 listener_orientation();\n\n\t\t\/**\n\t\t* Set the listener orientation.\n\t\t*\n\t\t* @brief listener_orientation\n\t\t* @param orientation, up\n\t\t*\/\n void listener_orientation(const glm::vec3 orientation, const glm::vec3 up = glm::vec3(0.0f, 0.0f, 1.0f));\n \n\t\t\/**\n\t\t* Get the listener velocity.\n\t\t*\n\t\t* @brief listener_velocity\n\t\t*\/\n\t\tglm::vec3 listener_velocity();\n\n\t\t\/**\n\t\t* Set the listener velocity.\n\t\t*\n\t\t* @brief listener_velocity\n\t\t* @param velocity\n\t\t*\/\n void listener_velocity(const glm::vec3 velocity);\n private:\n\t\tstruct StreamThread {\n\t\t\tstd::shared_ptr thread;\n\t\t\tbool running;\n\t\t};\n\n ALCdevice * device_;\n ALCcontext * context_;\n\n using SourcePair = std::pair;\n using BufferPair = std::pair;\n using Sources = std::unordered_map;\n using Buffers = std::unordered_map; \n\n Sources sources_;\n Buffers buffers_; \n\n std::unordered_map stream_threads;\t\t\n };\n}\n\n#endif\t\/* MO_AUDIO_H *\/\n\n<|endoftext|>"} {"text":"#include \"NumberTest.h\"\n#include \"SimpleAudioEngine.h\"\n#include \"LanguageManager.h\"\n#include \"Planet.h\"\n\n\nUSING_NS_CC;\nusing namespace CocosDenshion;\n\nbool NumberTest::tutActive = true;\nNumberTest * NumberTest::create(int _number, Sprite * _bg)\n{\n\tNumberTest * tip = new NumberTest();\n\n\tif (tip && tip->init())\n\t{\n\t\ttip->autorelease();\n\t\ttip->initNumberTest(_number, _bg);\n\t\treturn tip;\n\t}\n\tCC_SAFE_DELETE(tip);\n\treturn NULL;\n}\n\nNumberTest::~NumberTest()\n{\n\n}\n\nvoid NumberTest::initNumberTest(int _number, Sprite * _bg)\n{\n\tnumber = _number;\n\tsetupDirector();\n\tsetupBoundary();\n\tsetupSprite();\n\tsetupAudio();\n\tsetupLabel();\n\tconsumed = false;\n\tthis->setScale(0.9);\n\tbg = _bg;\n\tNumberTest::tutActive = true;\n\tBaseObject::initObject();\n}\n\nvoid NumberTest::setupDirector()\n{\n\tvisibleSize = Director::getInstance()->getVisibleSize();\n\twinSize = Director::getInstance()->getWinSize(); \/\/design size?\n\tframeSize = Director::getInstance()->getOpenGLView()->getFrameSize();\n\torigin = Director::getInstance()->getVisibleOrigin(); \/\/ common to all maps i hope\n}\n\nvoid NumberTest::setupBoundary()\n{\n\tboundary.shape = SHAPE::circle;\n\tboundary.active = true;\n\tboundary.r = 20;\n}\n\nvoid NumberTest::setupSprite()\n{\n\tauto sprite = Sprite::createWithSpriteFrameName(\"tip.png\");\n\tauto moveUp = EaseInOut::create(MoveBy::create(2, Vec2(0, 5.0f)), 2);\n\tauto moveBack = EaseInOut::create(MoveBy::create(2, Vec2(0, -5.0f)), 2);\n\tauto seq1 = Sequence::create(moveUp, moveBack, nullptr);\n\tsprite->runAction(RepeatForever::create(seq1));\n\tthis->addChild(sprite);\n}\n\nvoid NumberTest::setupAudio()\n{\n\tauto audio = SimpleAudioEngine::getInstance();\n\taudio->preloadEffect(\"sfx\/bot.wav\");\n\taudio->preloadEffect(\"sfx\/correct.wav\");\n\tlangCode = \"en\";\n\tif (CCApplication::getInstance()->getCurrentLanguage() == LanguageType::SWAHILI)\n\t\tlangCode = \"sw\";\n\tfor (int i = 0; i <= 10; i++)\n\t{\n\t\taudio->preloadEffect((\"sfx\/\" + langCode + \"\/digit_\" + std::to_string(i) + \".wav\").c_str());\n\t}\n}\n\nvoid NumberTest::setupLabel()\n{\n\tnumberLabel = Label::createWithTTF(std::to_string(number), LanguageManager::getString(\"font\"), 50);\n\tnumberLabel->setPosition(Vec2(0, 100));\n\tauto action0 = ScaleTo::create(0.3f, 1.1f, 1.1f);\n\tauto action1 = ScaleTo::create(0.3f, 0.99f, 0.99f);\n\tActionInterval *bouncingAction = Sequence::create(action0, action1, nullptr);\n\tauto action = RepeatForever::create(bouncingAction);\n\tnumberLabel->runAction(action);\n\tnumberLabel->setVisible(false);\n\tthis->addChild(numberLabel);\n}\n\nvoid NumberTest::addTut(Vec2 position)\n{\n\tSprite * touch = Sprite::createWithSpriteFrameName(\"touch.png\");\n\ttouch->setPosition(position);\n\ttouch->setOpacity(200);\n\tfloat d = 0.7;\n\tauto fadeO = FadeTo::create(d, 10);\n\tauto fadeI = FadeTo::create(d, 70);\n\tauto fadeTouch = Sequence::create(fadeO, fadeI, NULL);\n\ttouch->runAction(RepeatForever::create(fadeTouch));\n\ttouch->setScale(0.5);\n\n\tVec2 handPosition = position + Vec2(0, -20);\n\tSprite * hand = Sprite::createWithSpriteFrameName(\"hand.png\");\n\thand->setPosition(handPosition);\n\thand->setOpacity(70);\n\thand->setScale(0.5);\n\n\tbg->addChild(touch);\n\tbg->addChild(hand);\n}\n\nvoid NumberTest::update(bool hit)\n{\n\tif (hit && !isMessagevisible && !consumed)\n\t{\n\t\tauto audio = SimpleAudioEngine::getInstance();\n\t\tisMessagevisible = true;\n\t\taudio->playEffect(\"sfx\/bot.wav\");\n\n\t\tVector allActions;\n\t\tauto action = MoveTo::create(1.5, Vec2(0, 0));\n\t\tTargetedAction * t1 = TargetedAction::create(bg, action);\n\t\tallActions.pushBack(t1);\n\n\t\tVector menuItems;\n\t\tauto wrongChoice = [this, audio](Ref * sender) {\n\t\t\taudio->playEffect(\"sfx\/hurt.wav\");\n\t\t};\n\t\tauto rightChoice = [this, audio](Ref * sender) {\n\t\t\taudio->playEffect(\"sfx\/correct.wav\");\n\t\t\tauto * moveUp = MoveTo::create(1.5, Vec2(0, visibleSize.height));\n\t\t\tbg->runAction(moveUp);\n\t\t\tbg->removeAllChildren();\n\t\t\tconsumed = true;\n\t\t\tnumberLabel->setVisible(true);\n\t\t};\n\n\t\tint n = -1;\n\t\tint n2 = -1;\n\t\tint n3 = -1;\n\t\tint correctPicked = RandomHelper::random_int(1, 3);\n\t\tLabel * labelA = Label::createWithTTF(\"\", LanguageManager::getString(\"font\"), 120);\n\t\tlabelA->setScale(0.9);\n\t\tMenuItemLabel * mLabelA;\n\t\tif (correctPicked == 1)\n\t\t{\n\t\t\tlabelA->setString(std::to_string(number));\n\t\t\tmLabelA = MenuItemLabel::create(labelA, rightChoice);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tn = RandomHelper::random_int(1, 10);\n\t\t\twhile (n == number)\n\t\t\t{\n\t\t\t\tn = RandomHelper::random_int(1, 10);\n\t\t\t}\n\t\t\tn2 = n;\n\t\t\tlabelA->setString(std::to_string(n));\n\t\t\tmLabelA = MenuItemLabel::create(labelA, wrongChoice);\n\t\t}\n\n\t\tLabel * labelB = Label::createWithTTF(\"\", LanguageManager::getString(\"font\"), 120);\n\t\tlabelB->setScale(0.9);\n\t\tMenuItemLabel * mLabelB;\n\t\tif (correctPicked == 2)\n\t\t{\n\t\t\tlabelB->setString(std::to_string(number));\n\t\t\tmLabelB = MenuItemLabel::create(labelB, rightChoice);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tn = RandomHelper::random_int(1, 10);\n\t\t\twhile (n == number || n == n2)\n\t\t\t{\n\t\t\t\tn = RandomHelper::random_int(1, 10);\n\t\t\t}\n\t\t\tn3 = n;\n\t\t\tlabelB->setString(std::to_string(n));\n\t\t\tmLabelB = MenuItemLabel::create(labelB, wrongChoice);\n\t\t}\n\n\n\t\tLabel * labelC = Label::createWithTTF(\"\", LanguageManager::getString(\"font\"), 120);\n\t\tlabelC->setScale(0.9);\n\t\tMenuItemLabel * mLabelC;\n\t\tif (correctPicked == 3)\n\t\t{\n\t\t\tlabelC->setString(std::to_string(number));\n\t\t\tmLabelC = MenuItemLabel::create(labelC, rightChoice);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tn = RandomHelper::random_int(1, 10);\n\t\t\twhile (n == number || n == n3 || n == n2)\n\t\t\t{\n\t\t\t\tn = RandomHelper::random_int(1, 10);\n\t\t\t}\n\t\t\tlabelC->setString(std::to_string(n));\n\t\t\tmLabelC = MenuItemLabel::create(labelC, wrongChoice);\n\t\t}\n\n\t\tauto scaleUp = ScaleTo::create(1, 1.01);\n\t\tauto scaleDown = ScaleTo::create(1, 1);\n\t\tauto seqScale = Sequence::create(scaleUp, scaleDown, NULL);\n\t\tauto repScale = RepeatForever::create(seqScale);\n\t\tlabelA->runAction(repScale);\n\t\tlabelB->runAction(repScale->clone());\n\t\tlabelC->runAction(repScale->clone());\n\n\t\tmenuItems.pushBack(mLabelA);\n\t\tmenuItems.pushBack(mLabelB);\n\t\tmenuItems.pushBack(mLabelC);\n\t\tMenu * menu = Menu::createWithArray(menuItems);\n\t\tmenu->setPosition(Vec2(visibleSize.width - 100, visibleSize.height \/ 2));\n\t\tmenu->alignItemsVerticallyWithPadding(-20);\n\t\tmenu->setEnabled(false);\n\n\t\tmenu->setOpacity(100);\n\t\tbg->addChild(menu);\n\n\t\tauto scaleTo1 = ScaleTo::create(1.3, 1);\n\t\tint vLevel = 2;\n\t\tint hLevel = 1;\n\t\tfor (int i = 1; i <= number; i++)\n\t\t{\n\t\t\tauto planet = Planet::create(-1);\n\t\t\tplanet->setPosition(Vec2(105 * hLevel - 40, vLevel * visibleSize.height \/ 3));\n\t\t\tbg->addChild(planet);\n\t\t\thLevel++;\n\t\t\tif (i == 5)\n\t\t\t{\n\t\t\t\tvLevel = 1;\n\t\t\t\thLevel = 1;\n\t\t\t}\n\t\t\tplanet->setScale(0.01);\n\t\t\tTargetedAction * tA = TargetedAction::create(planet, scaleTo1);\n\t\t\tallActions.pushBack(tA);\n\t\t\tauto playAudio = CallFunc::create([this, i]() {\n\t\t\t\tauto audio = SimpleAudioEngine::getInstance();\n\t\t\t\taudio->playEffect((\"sfx\/\" + langCode + \"\/digit_\" + std::to_string(i) + \".wav\").c_str());\n\t\t\t});\n\t\t\tallActions.pushBack(playAudio);\n\t\t}\n\t\tauto * delay = DelayTime::create(1);\n\t\tallActions.pushBack(delay);\n\n\t\tauto * fadeIn = FadeIn::create(0.5);\n\t\tTargetedAction * fadeInMenu = TargetedAction::create(menu, fadeIn);\n\t\tallActions.pushBack(fadeInMenu);\n\n\t\tauto * enableMenuLambda = CallFunc::create([this, menu]() {\n\t\t\tmenu->setEnabled(true);\n\t\t\tif (NumberTest::tutActive)\n\t\t\t{\n\t\t\t\taddTut(Vec2(visibleSize.width - 100, visibleSize.height \/ 2 - 230));\n\t\t\t\taddTut(Vec2(visibleSize.width - 100, visibleSize.height \/ 2 - 60));\n\t\t\t\taddTut(Vec2(visibleSize.width - 100, visibleSize.height \/ 2 + 110));\n\t\t\t\tNumberTest::tutActive = false;\n\t\t\t}\n\t\t});\n\t\tallActions.pushBack(enableMenuLambda);\n\n\t\tauto seq = Sequence::create(allActions);\n\t\tbg->stopAllActions();\n\t\tbg->runAction(seq);\n\t}\n\telse if (!hit && isMessagevisible)\n\t{\n\t\tisMessagevisible = false;\n\t\tauto action = MoveTo::create(1.5, Vec2(0, visibleSize.height));\n\t\tbg->stopAllActions();\n\t\tbg->runAction(action);\n\t\tbg->removeAllChildren();\n\t}\n\n\tif (hit && !isMessagevisible && consumed)\n\t{\n\t\tisMessagevisible = true;\n\t\tauto audio = SimpleAudioEngine::getInstance();\n\t\taudio->playEffect((\"sfx\/\" + langCode + \"\/digit_\" + std::to_string(number) + \".wav\").c_str());\n\t}\n}\n\nAdded comments to the code for adding the hands and touch indicators#include \"NumberTest.h\"\n#include \"SimpleAudioEngine.h\"\n#include \"LanguageManager.h\"\n#include \"Planet.h\"\n\n\nUSING_NS_CC;\nusing namespace CocosDenshion;\n\nbool NumberTest::tutActive = true;\nNumberTest * NumberTest::create(int _number, Sprite * _bg)\n{\n\tNumberTest * tip = new NumberTest();\n\n\tif (tip && tip->init())\n\t{\n\t\ttip->autorelease();\n\t\ttip->initNumberTest(_number, _bg);\n\t\treturn tip;\n\t}\n\tCC_SAFE_DELETE(tip);\n\treturn NULL;\n}\n\nNumberTest::~NumberTest()\n{\n\n}\n\nvoid NumberTest::initNumberTest(int _number, Sprite * _bg)\n{\n\tnumber = _number;\n\tsetupDirector();\n\tsetupBoundary();\n\tsetupSprite();\n\tsetupAudio();\n\tsetupLabel();\n\tconsumed = false;\n\tthis->setScale(0.9);\n\tbg = _bg;\n\tNumberTest::tutActive = true;\n\tBaseObject::initObject();\n}\n\nvoid NumberTest::setupDirector()\n{\n\tvisibleSize = Director::getInstance()->getVisibleSize();\n\twinSize = Director::getInstance()->getWinSize(); \/\/design size?\n\tframeSize = Director::getInstance()->getOpenGLView()->getFrameSize();\n\torigin = Director::getInstance()->getVisibleOrigin(); \/\/ common to all maps i hope\n}\n\nvoid NumberTest::setupBoundary()\n{\n\tboundary.shape = SHAPE::circle;\n\tboundary.active = true;\n\tboundary.r = 20;\n}\n\nvoid NumberTest::setupSprite()\n{\n\tauto sprite = Sprite::createWithSpriteFrameName(\"tip.png\");\n\tauto moveUp = EaseInOut::create(MoveBy::create(2, Vec2(0, 5.0f)), 2);\n\tauto moveBack = EaseInOut::create(MoveBy::create(2, Vec2(0, -5.0f)), 2);\n\tauto seq1 = Sequence::create(moveUp, moveBack, nullptr);\n\tsprite->runAction(RepeatForever::create(seq1));\n\tthis->addChild(sprite);\n}\n\nvoid NumberTest::setupAudio()\n{\n\tauto audio = SimpleAudioEngine::getInstance();\n\taudio->preloadEffect(\"sfx\/bot.wav\");\n\taudio->preloadEffect(\"sfx\/correct.wav\");\n\tlangCode = \"en\";\n\tif (CCApplication::getInstance()->getCurrentLanguage() == LanguageType::SWAHILI)\n\t\tlangCode = \"sw\";\n\tfor (int i = 0; i <= 10; i++)\n\t{\n\t\taudio->preloadEffect((\"sfx\/\" + langCode + \"\/digit_\" + std::to_string(i) + \".wav\").c_str());\n\t}\n}\n\nvoid NumberTest::setupLabel()\n{\n\tnumberLabel = Label::createWithTTF(std::to_string(number), LanguageManager::getString(\"font\"), 50);\n\tnumberLabel->setPosition(Vec2(0, 100));\n\tauto action0 = ScaleTo::create(0.3f, 1.1f, 1.1f);\n\tauto action1 = ScaleTo::create(0.3f, 0.99f, 0.99f);\n\tActionInterval *bouncingAction = Sequence::create(action0, action1, nullptr);\n\tauto action = RepeatForever::create(bouncingAction);\n\tnumberLabel->runAction(action);\n\tnumberLabel->setVisible(false);\n\tthis->addChild(numberLabel);\n}\n\n\/*\n\tAdds the hand and touch indicators at the specified position for instruction\n*\/\nvoid NumberTest::addTut(Vec2 position)\n{\n\tSprite * touch = Sprite::createWithSpriteFrameName(\"touch.png\");\n\ttouch->setPosition(position);\n\ttouch->setOpacity(200);\n\tfloat d = 0.7;\n\tauto fadeO = FadeTo::create(d, 10);\n\tauto fadeI = FadeTo::create(d, 70);\n\tauto fadeTouch = Sequence::create(fadeO, fadeI, NULL);\n\ttouch->runAction(RepeatForever::create(fadeTouch));\n\ttouch->setScale(0.5);\n\n\tVec2 handPosition = position + Vec2(0, -20);\n\tSprite * hand = Sprite::createWithSpriteFrameName(\"hand.png\");\n\thand->setPosition(handPosition);\n\thand->setOpacity(70);\n\thand->setScale(0.5);\n\n\tbg->addChild(touch);\n\tbg->addChild(hand);\n}\n\nvoid NumberTest::update(bool hit)\n{\n\tif (hit && !isMessagevisible && !consumed)\n\t{\n\t\tauto audio = SimpleAudioEngine::getInstance();\n\t\tisMessagevisible = true;\n\t\taudio->playEffect(\"sfx\/bot.wav\");\n\n\t\tVector allActions;\n\t\tauto action = MoveTo::create(1.5, Vec2(0, 0));\n\t\tTargetedAction * t1 = TargetedAction::create(bg, action);\n\t\tallActions.pushBack(t1);\n\n\t\tVector menuItems;\n\t\tauto wrongChoice = [this, audio](Ref * sender) {\n\t\t\taudio->playEffect(\"sfx\/hurt.wav\");\n\t\t};\n\t\tauto rightChoice = [this, audio](Ref * sender) {\n\t\t\taudio->playEffect(\"sfx\/correct.wav\");\n\t\t\tauto * moveUp = MoveTo::create(1.5, Vec2(0, visibleSize.height));\n\t\t\tbg->runAction(moveUp);\n\t\t\tbg->removeAllChildren();\n\t\t\tconsumed = true;\n\t\t\tnumberLabel->setVisible(true);\n\t\t};\n\n\t\tint n = -1;\n\t\tint n2 = -1;\n\t\tint n3 = -1;\n\t\tint correctPicked = RandomHelper::random_int(1, 3);\n\t\tLabel * labelA = Label::createWithTTF(\"\", LanguageManager::getString(\"font\"), 120);\n\t\tlabelA->setScale(0.9);\n\t\tMenuItemLabel * mLabelA;\n\t\tif (correctPicked == 1)\n\t\t{\n\t\t\tlabelA->setString(std::to_string(number));\n\t\t\tmLabelA = MenuItemLabel::create(labelA, rightChoice);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tn = RandomHelper::random_int(1, 10);\n\t\t\twhile (n == number)\n\t\t\t{\n\t\t\t\tn = RandomHelper::random_int(1, 10);\n\t\t\t}\n\t\t\tn2 = n;\n\t\t\tlabelA->setString(std::to_string(n));\n\t\t\tmLabelA = MenuItemLabel::create(labelA, wrongChoice);\n\t\t}\n\n\t\tLabel * labelB = Label::createWithTTF(\"\", LanguageManager::getString(\"font\"), 120);\n\t\tlabelB->setScale(0.9);\n\t\tMenuItemLabel * mLabelB;\n\t\tif (correctPicked == 2)\n\t\t{\n\t\t\tlabelB->setString(std::to_string(number));\n\t\t\tmLabelB = MenuItemLabel::create(labelB, rightChoice);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tn = RandomHelper::random_int(1, 10);\n\t\t\twhile (n == number || n == n2)\n\t\t\t{\n\t\t\t\tn = RandomHelper::random_int(1, 10);\n\t\t\t}\n\t\t\tn3 = n;\n\t\t\tlabelB->setString(std::to_string(n));\n\t\t\tmLabelB = MenuItemLabel::create(labelB, wrongChoice);\n\t\t}\n\n\n\t\tLabel * labelC = Label::createWithTTF(\"\", LanguageManager::getString(\"font\"), 120);\n\t\tlabelC->setScale(0.9);\n\t\tMenuItemLabel * mLabelC;\n\t\tif (correctPicked == 3)\n\t\t{\n\t\t\tlabelC->setString(std::to_string(number));\n\t\t\tmLabelC = MenuItemLabel::create(labelC, rightChoice);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tn = RandomHelper::random_int(1, 10);\n\t\t\twhile (n == number || n == n3 || n == n2)\n\t\t\t{\n\t\t\t\tn = RandomHelper::random_int(1, 10);\n\t\t\t}\n\t\t\tlabelC->setString(std::to_string(n));\n\t\t\tmLabelC = MenuItemLabel::create(labelC, wrongChoice);\n\t\t}\n\n\t\tauto scaleUp = ScaleTo::create(1, 1.01);\n\t\tauto scaleDown = ScaleTo::create(1, 1);\n\t\tauto seqScale = Sequence::create(scaleUp, scaleDown, NULL);\n\t\tauto repScale = RepeatForever::create(seqScale);\n\t\tlabelA->runAction(repScale);\n\t\tlabelB->runAction(repScale->clone());\n\t\tlabelC->runAction(repScale->clone());\n\n\t\tmenuItems.pushBack(mLabelA);\n\t\tmenuItems.pushBack(mLabelB);\n\t\tmenuItems.pushBack(mLabelC);\n\t\tMenu * menu = Menu::createWithArray(menuItems);\n\t\tmenu->setPosition(Vec2(visibleSize.width - 100, visibleSize.height \/ 2));\n\t\tmenu->alignItemsVerticallyWithPadding(-20);\n\t\tmenu->setEnabled(false);\n\n\t\tmenu->setOpacity(100);\n\t\tbg->addChild(menu);\n\n\t\tauto scaleTo1 = ScaleTo::create(1.3, 1);\n\t\tint vLevel = 2;\n\t\tint hLevel = 1;\n\t\tfor (int i = 1; i <= number; i++)\n\t\t{\n\t\t\tauto planet = Planet::create(-1);\n\t\t\tplanet->setPosition(Vec2(105 * hLevel - 40, vLevel * visibleSize.height \/ 3));\n\t\t\tbg->addChild(planet);\n\t\t\thLevel++;\n\t\t\tif (i == 5)\n\t\t\t{\n\t\t\t\tvLevel = 1;\n\t\t\t\thLevel = 1;\n\t\t\t}\n\t\t\tplanet->setScale(0.01);\n\t\t\tTargetedAction * tA = TargetedAction::create(planet, scaleTo1);\n\t\t\tallActions.pushBack(tA);\n\t\t\tauto playAudio = CallFunc::create([this, i]() {\n\t\t\t\tauto audio = SimpleAudioEngine::getInstance();\n\t\t\t\taudio->playEffect((\"sfx\/\" + langCode + \"\/digit_\" + std::to_string(i) + \".wav\").c_str());\n\t\t\t});\n\t\t\tallActions.pushBack(playAudio);\n\t\t}\n\t\tauto * delay = DelayTime::create(1);\n\t\tallActions.pushBack(delay);\n\n\t\tauto * fadeIn = FadeIn::create(0.5);\n\t\tTargetedAction * fadeInMenu = TargetedAction::create(menu, fadeIn);\n\t\tallActions.pushBack(fadeInMenu);\n\n\t\tauto * enableMenuLambda = CallFunc::create([this, menu]() {\n\t\t\tmenu->setEnabled(true);\n\t\t\t\/\/Add the hand and touch indicators next to each of the numbers, \n\t\t\t\/\/tutActive will be set to false so the hands show up only the first time\n\t\t\tif (NumberTest::tutActive)\n\t\t\t{\n\t\t\t\t\/\/visibleSize correspond to the size currently visible in the screen\n\t\t\t\taddTut(Vec2(visibleSize.width - 100, visibleSize.height \/ 2 - 230));\n\t\t\t\taddTut(Vec2(visibleSize.width - 100, visibleSize.height \/ 2 - 60));\n\t\t\t\taddTut(Vec2(visibleSize.width - 100, visibleSize.height \/ 2 + 110));\n\t\t\t\tNumberTest::tutActive = false;\n\t\t\t}\n\t\t});\n\t\tallActions.pushBack(enableMenuLambda);\n\n\t\tauto seq = Sequence::create(allActions);\n\t\tbg->stopAllActions();\n\t\tbg->runAction(seq);\n\t}\n\telse if (!hit && isMessagevisible)\n\t{\n\t\tisMessagevisible = false;\n\t\tauto action = MoveTo::create(1.5, Vec2(0, visibleSize.height));\n\t\tbg->stopAllActions();\n\t\tbg->runAction(action);\n\t\tbg->removeAllChildren();\n\t}\n\n\tif (hit && !isMessagevisible && consumed)\n\t{\n\t\tisMessagevisible = true;\n\t\tauto audio = SimpleAudioEngine::getInstance();\n\t\taudio->playEffect((\"sfx\/\" + langCode + \"\/digit_\" + std::to_string(number) + \".wav\").c_str());\n\t}\n}\n\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtLocation module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** Other Usage\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qplacesearchrequest.h\"\n#include \"qgeocoordinate.h\"\n#include \"qgeoboundingarea.h\"\n\n#include \n\nQT_BEGIN_NAMESPACE\n\nclass QPlaceSearchRequestPrivate : public QSharedData\n{\npublic:\n QPlaceSearchRequestPrivate();\n QPlaceSearchRequestPrivate(const QPlaceSearchRequestPrivate &other);\n ~QPlaceSearchRequestPrivate();\n\n QPlaceSearchRequestPrivate &operator=(const QPlaceSearchRequestPrivate &other);\n bool operator==(const QPlaceSearchRequestPrivate &other) const;\n\n void clear();\n\n QString searchTerm;\n QList categories;\n QGeoBoundingArea *searchArea;\n int dymNumber;\n QtLocation::VisibilityScope visibilityScope;\n QPlaceSearchRequest::RelevanceHint relevanceHint;\n int limit;\n int offset;\n};\n\nQPlaceSearchRequestPrivate::QPlaceSearchRequestPrivate()\n : QSharedData(),\n searchArea(0), dymNumber(0),\n visibilityScope(QtLocation::UnspecifiedVisibility), relevanceHint(QPlaceSearchRequest::UnspecifiedHint),\n limit(-1), offset(0)\n{\n}\n\nQPlaceSearchRequestPrivate::QPlaceSearchRequestPrivate(const QPlaceSearchRequestPrivate &other)\n : QSharedData(other),\n searchTerm(other.searchTerm),\n categories(other.categories),\n dymNumber(other.dymNumber),\n visibilityScope(other.visibilityScope),\n relevanceHint(other.relevanceHint),\n limit(other.limit),\n offset(other.offset)\n{\n\n if (other.searchArea)\n searchArea = other.searchArea->clone();\n else\n searchArea = 0;\n}\n\nQPlaceSearchRequestPrivate::~QPlaceSearchRequestPrivate()\n{\n delete searchArea;\n}\n\nQPlaceSearchRequestPrivate &QPlaceSearchRequestPrivate::operator=(const QPlaceSearchRequestPrivate &other)\n{\n searchTerm = other.searchTerm;\n categories = other.categories;\n if (other.searchArea)\n searchArea = other.searchArea->clone();\n else\n searchArea = 0;\n dymNumber = other.dymNumber;\n visibilityScope = other.visibilityScope;\n relevanceHint = other.relevanceHint;\n limit = other.limit;\n offset = other.offset;\n}\n\nbool QPlaceSearchRequestPrivate::operator==(const QPlaceSearchRequestPrivate &other) const\n{\n bool searchAreaMatch = false;\n if ((searchArea == 0) && (other.searchArea == 0)) {\n searchAreaMatch = true;\n } else if (searchArea && other.searchArea) {\n if (*searchArea == *(other.searchArea))\n searchAreaMatch = true;\n else\n searchAreaMatch = false;\n } else {\n searchAreaMatch = false;\n }\n\n return (\n searchTerm == other.searchTerm\n && categories == other.categories\n && dymNumber == other.dymNumber\n && searchAreaMatch\n && visibilityScope == other.visibilityScope\n && relevanceHint == other.relevanceHint\n && limit == other.limit\n && offset == other.offset\n );\n}\n\nvoid QPlaceSearchRequestPrivate::clear()\n{\n limit = -1;\n offset = 0;\n searchTerm.clear();\n categories.clear();\n delete searchArea;\n searchArea = 0;\n dymNumber = 0;\n visibilityScope = QtLocation::UnspecifiedVisibility;\n relevanceHint = QPlaceSearchRequest::UnspecifiedHint;\n}\n\n\/*!\n \\class QPlaceSearchRequest\n \\inmodule QtLocation\n \\ingroup QtLocation-places\n \\since QtLocation 5.0\n\n \\brief The QPlaceSearchRequest class represents the set of parameters for a search request.\n\n A typical search request may look like the following:\n \\snippet snippets\/places\/requesthandler.h Search request\n\n Note that specifying a search center can be done by setting a circular search area that has\n a center but no radius. The default radius is set to -1, which indicates an undefined radius. The provider will\n interpret this as being free to choose its own default radius.\n\n The QPlaceSearchRequest will assume ownership of the bounding area and will be responsible\n for its destruction.\n\n The QPlaceSearchRequest is primarily used with the QPlaceManager to\n \\l {QPlaceManager::search()} {search for places}, however it is also\n used to provide parameters for \\l {QPlaceManager::textPredictions()}{generating text predictions}\n and \\l {QPlaceManager::recommendations()} {retreiving recommendations}. Note that depending on usage\n some parameters may not be relevant, e.g. the relevance hint is not important for text predictions. However\n in general most of the parameters are useful for each of these operations, eg for a recommendation, a search area\n and categories can be useful in narrowing down recommendation candidates.\n\n Also be aware that providers may vary by which parameters they support e.g. some providers may not support\n paging while others do, some providers may honor relevance hints while others may completely ignore them.\n*\/\n\n\/*!\n \\enum QPlaceSearchRequest::RelevanceHint\n\n Defines hints to help rank place results.\n \\value UnspecifiedHint\n No explicit hint has been specified.\n \\value DistanceHint\n Distance to a search center is relevant for the user. Closer places\n are more highly weighted. This hint is only useful\n if a circular bounding area is used in the query.\n \\value LexicalPlaceNameHint\n Alphabetic ordering of places according to name is relevant to the user.\n*\/\n\n\/*!\n Default constructor. Constructs an new request object.\n*\/\nQPlaceSearchRequest::QPlaceSearchRequest()\n : d_ptr(new QPlaceSearchRequestPrivate())\n{\n}\n\n\/*!\n Constructs a copy of \\a other.\n*\/\nQPlaceSearchRequest::QPlaceSearchRequest(const QPlaceSearchRequest &other)\n : d_ptr(other.d_ptr)\n{\n}\n\n\/*!\n Destroys the request object.\n*\/\nQPlaceSearchRequest::~QPlaceSearchRequest()\n{\n}\n\n\/*!\n Assigns \\a other to this search request and returns a reference\n to this search request.\n*\/\nQPlaceSearchRequest &QPlaceSearchRequest::operator= (const QPlaceSearchRequest & other)\n{\n Q_D(QPlaceSearchRequest);\n d_ptr = other.d_ptr;\n return *this;\n}\n\n\/*!\n Returns true if \\a other is equal to this search request,\n otherwise returns false.\n*\/\nbool QPlaceSearchRequest::operator== (const QPlaceSearchRequest &other) const\n{\n Q_D(const QPlaceSearchRequest);\n return *d == *other.d_func();\n}\n\n\/*!\n Returns true if \\a other is not equal to this search request,\n otherwise returns false.\n*\/\nbool QPlaceSearchRequest::operator!= (const QPlaceSearchRequest &other) const\n{\n Q_D(const QPlaceSearchRequest);\n return !(*d == *other.d_func());\n}\n\n\/*!\n Returns the search term.\n*\/\nQString QPlaceSearchRequest::searchTerm() const\n{\n Q_D(const QPlaceSearchRequest);\n return d->searchTerm;\n}\n\n\/*!\n Sets the search \\a term.\n*\/\nvoid QPlaceSearchRequest::setSearchTerm(const QString &term)\n{\n Q_D(QPlaceSearchRequest);\n d->searchTerm = term;\n}\n\n\/*!\n Return the categories to be used in the search request.\n Places need only to belong to one of the categories\n to be considered a match by the request.\n*\/\nQList QPlaceSearchRequest::categories() const\n{\n Q_D(const QPlaceSearchRequest);\n return d->categories;\n}\n\n\/*!\n Sets the search request to search by a single \\a category\n\n \\sa setCategories()\n*\/\nvoid QPlaceSearchRequest::setCategory(const QPlaceCategory &category)\n{\n Q_D(QPlaceSearchRequest);\n d->categories.clear();\n\n if (!category.categoryId().isEmpty())\n d->categories.append(category);\n}\n\n\/*!\n Sets the search request to search from the list of given \\a categories.\n\n It is possible that some backends may not support multiple categories. In this case,\n the first category is used and the rest are ignored.\n\n \\sa setCategory()\n*\/\nvoid QPlaceSearchRequest::setCategories(const QList &categories)\n{\n Q_D(QPlaceSearchRequest);\n d->categories = categories;\n}\n\n\/*!\n Returns search area. The default search area is a null pointer.\n*\/\nQGeoBoundingArea *QPlaceSearchRequest::searchArea() const\n{\n Q_D(const QPlaceSearchRequest);\n return d->searchArea;\n}\n\n\/*!\n Sets the search request to search within the given \\a area. Ownership of the \\a area is\n transferred to the request who is responsible for pointer deletion. If a new \\a area\n is being assigned, the old area is deleted.\n*\/\nvoid QPlaceSearchRequest::setSearchArea(QGeoBoundingArea *area)\n{\n Q_D(QPlaceSearchRequest);\n if (d->searchArea != area)\n delete d->searchArea;\n\n d->searchArea = area;\n}\n\n\/*!\n Returns the maximum number of search term corrections that may be returned.\n*\/\nint QPlaceSearchRequest::maximumCorrections() const\n{\n Q_D(const QPlaceSearchRequest);\n return d->dymNumber;\n}\n\n\/*!\n Sets maximum \\a number of search term corrections that may be returned.\n*\/\nvoid QPlaceSearchRequest::setMaximumCorrections(int number)\n{\n Q_D(QPlaceSearchRequest);\n d->dymNumber = number;\n}\n\n\/*!\n Returns the visibility scope used when searching for places. The default value is\n QtLocation::UnspecifiedVisibility meaning that no explicit scope has been assigned. It is up\n to the manager implementation to decide what scope it searches by default.\n*\/\nQtLocation::VisibilityScope QPlaceSearchRequest::visibilityScope() const\n{\n Q_D(const QPlaceSearchRequest);\n return d->visibilityScope;\n}\n\n\/*!\n Sets the visibiliy \\a scope used when searching for places.\n*\/\nvoid QPlaceSearchRequest::setVisibilityScope(QtLocation::VisibilityScope scope)\n{\n Q_D(QPlaceSearchRequest);\n d->visibilityScope = scope;\n}\n\n\/*!\n Returns the relevance hint of the request. The hint is given to the provider\n to help but not dictate the ranking of results. eg providng a distance hint\n may give closer places a higher ranking but it doesn't necessarily mean\n that he results will be ordered strictly according to distance.\n*\/\nQPlaceSearchRequest::RelevanceHint QPlaceSearchRequest::relevanceHint() const\n{\n Q_D(const QPlaceSearchRequest);\n return d->relevanceHint;\n}\n\n\/*!\n Sets the relevance \\a hint to be used when searching for a place.\n*\/\nvoid QPlaceSearchRequest::setRelevanceHint(QPlaceSearchRequest::RelevanceHint hint)\n{\n Q_D(QPlaceSearchRequest);\n d->relevanceHint = hint;\n}\n\n\/*!\n Returns the maximum number of search results to retrieve.\n\n A negative value for limit means that it is undefined. It is left up to the backend\n provider to choose an appropriate number of results to return.\n*\/\nint QPlaceSearchRequest::limit() const\n{\n Q_D(const QPlaceSearchRequest);\n return d->limit;\n}\n\n\/*!\n Set the maximum number of search results to retrieve to \\a limit.\n*\/\nvoid QPlaceSearchRequest::setLimit(int limit)\n{\n Q_D(QPlaceSearchRequest);\n d->limit = limit;\n}\n\n\/*!\n Returns the index of the first item that is to be retrieved.\n*\/\nint QPlaceSearchRequest::offset() const\n{\n Q_D(const QPlaceSearchRequest);\n return d->offset;\n}\n\n\/*!\n Sets the starting index of the first item to be retrieved\n to \\a offset.\n*\/\nvoid QPlaceSearchRequest::setOffset(int offset)\n{\n Q_D(QPlaceSearchRequest);\n d->offset = offset;\n}\n\n\/*!\n Clears the search request.\n*\/\nvoid QPlaceSearchRequest::clear()\n{\n Q_D(QPlaceSearchRequest);\n d->clear();\n}\n\ninline QPlaceSearchRequestPrivate* QPlaceSearchRequest::d_func()\n{\n return static_cast(d_ptr.data());\n}\n\ninline const QPlaceSearchRequestPrivate* QPlaceSearchRequest::d_func() const\n{\n return static_cast(d_ptr.constData());\n}\n\nQT_END_NAMESPACE\nMake QtLocation compile\/****************************************************************************\n**\n** Copyright (C) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtLocation module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** Other Usage\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qplacesearchrequest.h\"\n#include \"qgeocoordinate.h\"\n#include \"qgeoboundingarea.h\"\n\n#include \n#include \n\nQT_BEGIN_NAMESPACE\n\nclass QPlaceSearchRequestPrivate : public QSharedData\n{\npublic:\n QPlaceSearchRequestPrivate();\n QPlaceSearchRequestPrivate(const QPlaceSearchRequestPrivate &other);\n ~QPlaceSearchRequestPrivate();\n\n QPlaceSearchRequestPrivate &operator=(const QPlaceSearchRequestPrivate &other);\n bool operator==(const QPlaceSearchRequestPrivate &other) const;\n\n void clear();\n\n QString searchTerm;\n QList categories;\n QGeoBoundingArea *searchArea;\n int dymNumber;\n QtLocation::VisibilityScope visibilityScope;\n QPlaceSearchRequest::RelevanceHint relevanceHint;\n int limit;\n int offset;\n};\n\nQPlaceSearchRequestPrivate::QPlaceSearchRequestPrivate()\n : QSharedData(),\n searchArea(0), dymNumber(0),\n visibilityScope(QtLocation::UnspecifiedVisibility), relevanceHint(QPlaceSearchRequest::UnspecifiedHint),\n limit(-1), offset(0)\n{\n}\n\nQPlaceSearchRequestPrivate::QPlaceSearchRequestPrivate(const QPlaceSearchRequestPrivate &other)\n : QSharedData(other),\n searchTerm(other.searchTerm),\n categories(other.categories),\n dymNumber(other.dymNumber),\n visibilityScope(other.visibilityScope),\n relevanceHint(other.relevanceHint),\n limit(other.limit),\n offset(other.offset)\n{\n\n if (other.searchArea)\n searchArea = other.searchArea->clone();\n else\n searchArea = 0;\n}\n\nQPlaceSearchRequestPrivate::~QPlaceSearchRequestPrivate()\n{\n delete searchArea;\n}\n\nQPlaceSearchRequestPrivate &QPlaceSearchRequestPrivate::operator=(const QPlaceSearchRequestPrivate &other)\n{\n searchTerm = other.searchTerm;\n categories = other.categories;\n if (other.searchArea)\n searchArea = other.searchArea->clone();\n else\n searchArea = 0;\n dymNumber = other.dymNumber;\n visibilityScope = other.visibilityScope;\n relevanceHint = other.relevanceHint;\n limit = other.limit;\n offset = other.offset;\n}\n\nbool QPlaceSearchRequestPrivate::operator==(const QPlaceSearchRequestPrivate &other) const\n{\n bool searchAreaMatch = false;\n if ((searchArea == 0) && (other.searchArea == 0)) {\n searchAreaMatch = true;\n } else if (searchArea && other.searchArea) {\n if (*searchArea == *(other.searchArea))\n searchAreaMatch = true;\n else\n searchAreaMatch = false;\n } else {\n searchAreaMatch = false;\n }\n\n return (\n searchTerm == other.searchTerm\n && categories == other.categories\n && dymNumber == other.dymNumber\n && searchAreaMatch\n && visibilityScope == other.visibilityScope\n && relevanceHint == other.relevanceHint\n && limit == other.limit\n && offset == other.offset\n );\n}\n\nvoid QPlaceSearchRequestPrivate::clear()\n{\n limit = -1;\n offset = 0;\n searchTerm.clear();\n categories.clear();\n delete searchArea;\n searchArea = 0;\n dymNumber = 0;\n visibilityScope = QtLocation::UnspecifiedVisibility;\n relevanceHint = QPlaceSearchRequest::UnspecifiedHint;\n}\n\n\/*!\n \\class QPlaceSearchRequest\n \\inmodule QtLocation\n \\ingroup QtLocation-places\n \\since QtLocation 5.0\n\n \\brief The QPlaceSearchRequest class represents the set of parameters for a search request.\n\n A typical search request may look like the following:\n \\snippet snippets\/places\/requesthandler.h Search request\n\n Note that specifying a search center can be done by setting a circular search area that has\n a center but no radius. The default radius is set to -1, which indicates an undefined radius. The provider will\n interpret this as being free to choose its own default radius.\n\n The QPlaceSearchRequest will assume ownership of the bounding area and will be responsible\n for its destruction.\n\n The QPlaceSearchRequest is primarily used with the QPlaceManager to\n \\l {QPlaceManager::search()} {search for places}, however it is also\n used to provide parameters for \\l {QPlaceManager::textPredictions()}{generating text predictions}\n and \\l {QPlaceManager::recommendations()} {retreiving recommendations}. Note that depending on usage\n some parameters may not be relevant, e.g. the relevance hint is not important for text predictions. However\n in general most of the parameters are useful for each of these operations, eg for a recommendation, a search area\n and categories can be useful in narrowing down recommendation candidates.\n\n Also be aware that providers may vary by which parameters they support e.g. some providers may not support\n paging while others do, some providers may honor relevance hints while others may completely ignore them.\n*\/\n\n\/*!\n \\enum QPlaceSearchRequest::RelevanceHint\n\n Defines hints to help rank place results.\n \\value UnspecifiedHint\n No explicit hint has been specified.\n \\value DistanceHint\n Distance to a search center is relevant for the user. Closer places\n are more highly weighted. This hint is only useful\n if a circular bounding area is used in the query.\n \\value LexicalPlaceNameHint\n Alphabetic ordering of places according to name is relevant to the user.\n*\/\n\n\/*!\n Default constructor. Constructs an new request object.\n*\/\nQPlaceSearchRequest::QPlaceSearchRequest()\n : d_ptr(new QPlaceSearchRequestPrivate())\n{\n}\n\n\/*!\n Constructs a copy of \\a other.\n*\/\nQPlaceSearchRequest::QPlaceSearchRequest(const QPlaceSearchRequest &other)\n : d_ptr(other.d_ptr)\n{\n}\n\n\/*!\n Destroys the request object.\n*\/\nQPlaceSearchRequest::~QPlaceSearchRequest()\n{\n}\n\n\/*!\n Assigns \\a other to this search request and returns a reference\n to this search request.\n*\/\nQPlaceSearchRequest &QPlaceSearchRequest::operator= (const QPlaceSearchRequest & other)\n{\n Q_D(QPlaceSearchRequest);\n d_ptr = other.d_ptr;\n return *this;\n}\n\n\/*!\n Returns true if \\a other is equal to this search request,\n otherwise returns false.\n*\/\nbool QPlaceSearchRequest::operator== (const QPlaceSearchRequest &other) const\n{\n Q_D(const QPlaceSearchRequest);\n return *d == *other.d_func();\n}\n\n\/*!\n Returns true if \\a other is not equal to this search request,\n otherwise returns false.\n*\/\nbool QPlaceSearchRequest::operator!= (const QPlaceSearchRequest &other) const\n{\n Q_D(const QPlaceSearchRequest);\n return !(*d == *other.d_func());\n}\n\n\/*!\n Returns the search term.\n*\/\nQString QPlaceSearchRequest::searchTerm() const\n{\n Q_D(const QPlaceSearchRequest);\n return d->searchTerm;\n}\n\n\/*!\n Sets the search \\a term.\n*\/\nvoid QPlaceSearchRequest::setSearchTerm(const QString &term)\n{\n Q_D(QPlaceSearchRequest);\n d->searchTerm = term;\n}\n\n\/*!\n Return the categories to be used in the search request.\n Places need only to belong to one of the categories\n to be considered a match by the request.\n*\/\nQList QPlaceSearchRequest::categories() const\n{\n Q_D(const QPlaceSearchRequest);\n return d->categories;\n}\n\n\/*!\n Sets the search request to search by a single \\a category\n\n \\sa setCategories()\n*\/\nvoid QPlaceSearchRequest::setCategory(const QPlaceCategory &category)\n{\n Q_D(QPlaceSearchRequest);\n d->categories.clear();\n\n if (!category.categoryId().isEmpty())\n d->categories.append(category);\n}\n\n\/*!\n Sets the search request to search from the list of given \\a categories.\n\n It is possible that some backends may not support multiple categories. In this case,\n the first category is used and the rest are ignored.\n\n \\sa setCategory()\n*\/\nvoid QPlaceSearchRequest::setCategories(const QList &categories)\n{\n Q_D(QPlaceSearchRequest);\n d->categories = categories;\n}\n\n\/*!\n Returns search area. The default search area is a null pointer.\n*\/\nQGeoBoundingArea *QPlaceSearchRequest::searchArea() const\n{\n Q_D(const QPlaceSearchRequest);\n return d->searchArea;\n}\n\n\/*!\n Sets the search request to search within the given \\a area. Ownership of the \\a area is\n transferred to the request who is responsible for pointer deletion. If a new \\a area\n is being assigned, the old area is deleted.\n*\/\nvoid QPlaceSearchRequest::setSearchArea(QGeoBoundingArea *area)\n{\n Q_D(QPlaceSearchRequest);\n if (d->searchArea != area)\n delete d->searchArea;\n\n d->searchArea = area;\n}\n\n\/*!\n Returns the maximum number of search term corrections that may be returned.\n*\/\nint QPlaceSearchRequest::maximumCorrections() const\n{\n Q_D(const QPlaceSearchRequest);\n return d->dymNumber;\n}\n\n\/*!\n Sets maximum \\a number of search term corrections that may be returned.\n*\/\nvoid QPlaceSearchRequest::setMaximumCorrections(int number)\n{\n Q_D(QPlaceSearchRequest);\n d->dymNumber = number;\n}\n\n\/*!\n Returns the visibility scope used when searching for places. The default value is\n QtLocation::UnspecifiedVisibility meaning that no explicit scope has been assigned. It is up\n to the manager implementation to decide what scope it searches by default.\n*\/\nQtLocation::VisibilityScope QPlaceSearchRequest::visibilityScope() const\n{\n Q_D(const QPlaceSearchRequest);\n return d->visibilityScope;\n}\n\n\/*!\n Sets the visibiliy \\a scope used when searching for places.\n*\/\nvoid QPlaceSearchRequest::setVisibilityScope(QtLocation::VisibilityScope scope)\n{\n Q_D(QPlaceSearchRequest);\n d->visibilityScope = scope;\n}\n\n\/*!\n Returns the relevance hint of the request. The hint is given to the provider\n to help but not dictate the ranking of results. eg providng a distance hint\n may give closer places a higher ranking but it doesn't necessarily mean\n that he results will be ordered strictly according to distance.\n*\/\nQPlaceSearchRequest::RelevanceHint QPlaceSearchRequest::relevanceHint() const\n{\n Q_D(const QPlaceSearchRequest);\n return d->relevanceHint;\n}\n\n\/*!\n Sets the relevance \\a hint to be used when searching for a place.\n*\/\nvoid QPlaceSearchRequest::setRelevanceHint(QPlaceSearchRequest::RelevanceHint hint)\n{\n Q_D(QPlaceSearchRequest);\n d->relevanceHint = hint;\n}\n\n\/*!\n Returns the maximum number of search results to retrieve.\n\n A negative value for limit means that it is undefined. It is left up to the backend\n provider to choose an appropriate number of results to return.\n*\/\nint QPlaceSearchRequest::limit() const\n{\n Q_D(const QPlaceSearchRequest);\n return d->limit;\n}\n\n\/*!\n Set the maximum number of search results to retrieve to \\a limit.\n*\/\nvoid QPlaceSearchRequest::setLimit(int limit)\n{\n Q_D(QPlaceSearchRequest);\n d->limit = limit;\n}\n\n\/*!\n Returns the index of the first item that is to be retrieved.\n*\/\nint QPlaceSearchRequest::offset() const\n{\n Q_D(const QPlaceSearchRequest);\n return d->offset;\n}\n\n\/*!\n Sets the starting index of the first item to be retrieved\n to \\a offset.\n*\/\nvoid QPlaceSearchRequest::setOffset(int offset)\n{\n Q_D(QPlaceSearchRequest);\n d->offset = offset;\n}\n\n\/*!\n Clears the search request.\n*\/\nvoid QPlaceSearchRequest::clear()\n{\n Q_D(QPlaceSearchRequest);\n d->clear();\n}\n\ninline QPlaceSearchRequestPrivate* QPlaceSearchRequest::d_func()\n{\n return static_cast(d_ptr.data());\n}\n\ninline const QPlaceSearchRequestPrivate* QPlaceSearchRequest::d_func() const\n{\n return static_cast(d_ptr.constData());\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"\/\/ Scintilla source code edit control\n\/** @file LexScriptol.cxx\n ** Lexer for Scriptol.\n **\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"ILexer.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\n#include \"WordList.h\"\n#include \"LexAccessor.h\"\n#include \"Accessor.h\"\n#include \"StyleContext.h\"\n#include \"CharacterSet.h\"\n#include \"LexerModule.h\"\n\n#ifdef SCI_NAMESPACE\nusing namespace Scintilla;\n#endif\n\nstatic void ClassifyWordSol(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler, char *prevWord)\n{\n char s[100];\n bool wordIsNumber = isdigit(styler[start]) != 0;\n for (unsigned int i = 0; i < end - start + 1 && i < 30; i++)\n {\n s[i] = styler[start + i];\n s[i + 1] = '\\0';\n }\n char chAttr = SCE_SCRIPTOL_IDENTIFIER;\n if (0 == strcmp(prevWord, \"class\")) chAttr = SCE_SCRIPTOL_CLASSNAME;\n else if (wordIsNumber) chAttr = SCE_SCRIPTOL_NUMBER;\n else if (keywords.InList(s)) chAttr = SCE_SCRIPTOL_KEYWORD;\n else for (unsigned int i = 0; i < end - start + 1; i++) \/\/ test dotted idents\n {\n if (styler[start + i] == '.')\n {\n styler.ColourTo(start + i - 1, chAttr);\n styler.ColourTo(start + i, SCE_SCRIPTOL_OPERATOR);\n }\n }\n styler.ColourTo(end, chAttr);\n strcpy(prevWord, s);\n}\n\nstatic bool IsSolComment(Accessor &styler, int pos, int len)\n{\n if(len > 0)\n {\n char c = styler[pos];\n if(c == '`') return true;\n if(len > 1)\n {\n if(c == '\/')\n {\n c = styler[pos + 1];\n if(c == '\/') return true;\n if(c == '*') return true;\n }\n }\n }\n return false;\n}\n\nstatic bool IsSolStringStart(char ch)\n{\n if (ch == '\\'' || ch == '\"') return true;\n return false;\n}\n\nstatic bool IsSolWordStart(char ch)\n{\n return (iswordchar(ch) && !IsSolStringStart(ch));\n}\n\n\nstatic int GetSolStringState(Accessor &styler, int i, int *nextIndex)\n{\n\tchar ch = styler.SafeGetCharAt(i);\n\tchar chNext = styler.SafeGetCharAt(i + 1);\n\n if (ch != '\\\"' && ch != '\\'')\n {\n *nextIndex = i + 1;\n return SCE_SCRIPTOL_DEFAULT;\n\t}\n \/\/ ch is either single or double quotes in string\n \/\/ code below seem non-sense but is here for future extensions\n\tif (ch == chNext && ch == styler.SafeGetCharAt(i + 2))\n {\n *nextIndex = i + 3;\n if(ch == '\\\"') return SCE_SCRIPTOL_TRIPLE;\n if(ch == '\\'') return SCE_SCRIPTOL_TRIPLE;\n return SCE_SCRIPTOL_STRING;\n\t}\n else\n {\n *nextIndex = i + 1;\n if (ch == '\"') return SCE_SCRIPTOL_STRING;\n else return SCE_SCRIPTOL_STRING;\n\t}\n}\n\n\nstatic void ColouriseSolDoc(unsigned int startPos, int length, int initStyle,\n WordList *keywordlists[], Accessor &styler)\n {\n\n\tint lengthDoc = startPos + length;\n char stringType = '\\\"';\n\n\tif (startPos > 0)\n {\n int lineCurrent = styler.GetLine(startPos);\n if (lineCurrent > 0)\n {\n startPos = styler.LineStart(lineCurrent-1);\n if (startPos == 0) initStyle = SCE_SCRIPTOL_DEFAULT;\n else initStyle = styler.StyleAt(startPos-1);\n }\n\t}\n\n\tstyler.StartAt(startPos, 127);\n\n\tWordList &keywords = *keywordlists[0];\n\n\tint whingeLevel = styler.GetPropertyInt(\"tab.timmy.whinge.level\");\n\tchar prevWord[200];\n\tprevWord[0] = '\\0';\n if (length == 0) return;\n\n\tint state = initStyle & 31;\n\n\tint nextIndex = 0;\n char chPrev = ' ';\n char chPrev2 = ' ';\n char chNext = styler[startPos];\n\tstyler.StartSegment(startPos);\n\tbool atStartLine = true;\n\tint spaceFlags = 0;\n\tfor (int i = startPos; i < lengthDoc; i++)\n {\n\n if (atStartLine)\n {\n char chBad = static_cast(64);\n char chGood = static_cast(0);\n char chFlags = chGood;\n\n if (whingeLevel == 1)\n {\n chFlags = (spaceFlags & wsInconsistent) ? chBad : chGood;\n }\n else if (whingeLevel == 2)\n {\n chFlags = (spaceFlags & wsSpaceTab) ? chBad : chGood;\n }\n else if (whingeLevel == 3)\n {\n chFlags = (spaceFlags & wsSpace) ? chBad : chGood;\n }\n else if (whingeLevel == 4)\n {\n chFlags = (spaceFlags & wsTab) ? chBad : chGood;\n }\n styler.SetFlags(chFlags, static_cast(state));\n atStartLine = false;\n }\n\n char ch = chNext;\n chNext = styler.SafeGetCharAt(i + 1);\n\n if ((ch == '\\r' && chNext != '\\n') || (ch == '\\n') || (i == lengthDoc))\n {\n if ((state == SCE_SCRIPTOL_DEFAULT) ||\n (state == SCE_SCRIPTOL_TRIPLE) ||\n (state == SCE_SCRIPTOL_COMMENTBLOCK))\n {\n styler.ColourTo(i, state);\n }\n atStartLine = true;\n }\n\n if (styler.IsLeadByte(ch))\n {\n chNext = styler.SafeGetCharAt(i + 2);\n chPrev = ' ';\n chPrev2 = ' ';\n i += 1;\n continue;\n }\n\n if (state == SCE_SCRIPTOL_STRINGEOL)\n {\n if (ch != '\\r' && ch != '\\n')\n {\n styler.ColourTo(i - 1, state);\n state = SCE_SCRIPTOL_DEFAULT;\n }\n }\n\n if (state == SCE_SCRIPTOL_DEFAULT)\n {\n if (IsSolWordStart(ch))\n {\n styler.ColourTo(i - 1, state);\n state = SCE_SCRIPTOL_KEYWORD;\n }\n else if (ch == '`')\n {\n styler.ColourTo(i - 1, state);\n state = SCE_SCRIPTOL_COMMENTLINE;\n }\n else if (ch == '\/')\n {\n styler.ColourTo(i - 1, state);\n if(chNext == '\/') state = SCE_SCRIPTOL_CSTYLE;\n if(chNext == '*') state = SCE_SCRIPTOL_COMMENTBLOCK;\n }\n\n else if (IsSolStringStart(ch))\n {\n styler.ColourTo(i - 1, state);\n state = GetSolStringState(styler, i, &nextIndex);\n if(state == SCE_SCRIPTOL_STRING)\n {\n stringType = ch;\n }\n if (nextIndex != i + 1)\n {\n i = nextIndex - 1;\n ch = ' ';\n chPrev = ' ';\n chNext = styler.SafeGetCharAt(i + 1);\n }\n }\n else if (isoperator(ch))\n {\n styler.ColourTo(i - 1, state);\n styler.ColourTo(i, SCE_SCRIPTOL_OPERATOR);\n }\n }\n else if (state == SCE_SCRIPTOL_KEYWORD)\n {\n if (!iswordchar(ch))\n {\n ClassifyWordSol(styler.GetStartSegment(), i - 1, keywords, styler, prevWord);\n state = SCE_SCRIPTOL_DEFAULT;\n if (ch == '`')\n {\n state = chNext == '`' ? SCE_SCRIPTOL_PERSISTENT : SCE_SCRIPTOL_COMMENTLINE;\n }\n else if (IsSolStringStart(ch))\n {\n styler.ColourTo(i - 1, state);\n state = GetSolStringState(styler, i, &nextIndex);\n if (nextIndex != i + 1)\n {\n i = nextIndex - 1;\n ch = ' ';\n chPrev = ' ';\n chNext = styler.SafeGetCharAt(i + 1);\n }\n }\n else if (isoperator(ch))\n {\n styler.ColourTo(i, SCE_SCRIPTOL_OPERATOR);\n }\n }\n }\n else\n {\n if (state == SCE_SCRIPTOL_COMMENTLINE ||\n state == SCE_SCRIPTOL_PERSISTENT ||\n state == SCE_SCRIPTOL_CSTYLE)\n {\n if (ch == '\\r' || ch == '\\n')\n {\n styler.ColourTo(i - 1, state);\n state = SCE_SCRIPTOL_DEFAULT;\n }\n }\n else if(state == SCE_SCRIPTOL_COMMENTBLOCK)\n {\n if(chPrev == '*' && ch == '\/')\n {\n styler.ColourTo(i, state);\n state = SCE_SCRIPTOL_DEFAULT;\n }\n }\n else if ((state == SCE_SCRIPTOL_STRING) ||\n (state == SCE_SCRIPTOL_CHARACTER))\n {\n if ((ch == '\\r' || ch == '\\n') && (chPrev != '\\\\'))\n {\n styler.ColourTo(i - 1, state);\n state = SCE_SCRIPTOL_STRINGEOL;\n }\n else if (ch == '\\\\')\n {\n if (chNext == '\\\"' || chNext == '\\'' || chNext == '\\\\')\n {\n i++;\n ch = chNext;\n chNext = styler.SafeGetCharAt(i + 1);\n }\n }\n else if ((ch == '\\\"') || (ch == '\\''))\n {\n \/\/ must match the entered quote type\n if(ch == stringType)\n {\n styler.ColourTo(i, state);\n state = SCE_SCRIPTOL_DEFAULT;\n }\n }\n }\n else if (state == SCE_SCRIPTOL_TRIPLE)\n {\n if ((ch == '\\'' && chPrev == '\\'' && chPrev2 == '\\'') ||\n (ch == '\\\"' && chPrev == '\\\"' && chPrev2 == '\\\"'))\n {\n styler.ColourTo(i, state);\n state = SCE_SCRIPTOL_DEFAULT;\n }\n }\n\n }\n chPrev2 = chPrev;\n chPrev = ch;\n\t}\n if (state == SCE_SCRIPTOL_KEYWORD)\n {\n ClassifyWordSol(styler.GetStartSegment(),\n lengthDoc-1, keywords, styler, prevWord);\n\t}\n else\n {\n styler.ColourTo(lengthDoc-1, state);\n\t}\n}\n\nstatic void FoldSolDoc(unsigned int startPos, int length, int initStyle,\n\t\t\t\t\t\t WordList *[], Accessor &styler)\n {\n\tint lengthDoc = startPos + length;\n\n\tint lineCurrent = styler.GetLine(startPos);\n\tif (startPos > 0)\n {\n if (lineCurrent > 0)\n {\n lineCurrent--;\n startPos = styler.LineStart(lineCurrent);\n if (startPos == 0)\n initStyle = SCE_SCRIPTOL_DEFAULT;\n else\n initStyle = styler.StyleAt(startPos-1);\n }\n\t}\n\tint state = initStyle & 31;\n\tint spaceFlags = 0;\n int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsSolComment);\n if ((state == SCE_SCRIPTOL_TRIPLE))\n indentCurrent |= SC_FOLDLEVELWHITEFLAG;\n\tchar chNext = styler[startPos];\n\tfor (int i = startPos; i < lengthDoc; i++)\n {\n\t\tchar ch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i + 1);\n\t\tint style = styler.StyleAt(i) & 31;\n\n\t\tif ((ch == '\\r' && chNext != '\\n') || (ch == '\\n') || (i == lengthDoc))\n {\n int lev = indentCurrent;\n int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsSolComment);\n if (style == SCE_SCRIPTOL_TRIPLE)\n indentNext |= SC_FOLDLEVELWHITEFLAG;\n if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG))\n {\n \/\/ Only non whitespace lines can be headers\n if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK))\n {\n lev |= SC_FOLDLEVELHEADERFLAG;\n }\n else if (indentNext & SC_FOLDLEVELWHITEFLAG)\n {\n \/\/ Line after is blank so check the next - maybe should continue further?\n int spaceFlags2 = 0;\n int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsSolComment);\n if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK))\n {\n lev |= SC_FOLDLEVELHEADERFLAG;\n }\n }\n }\n indentCurrent = indentNext;\n styler.SetLevel(lineCurrent, lev);\n lineCurrent++;\n\t\t}\n\t}\n}\n\nLexerModule lmScriptol(SCLEX_SCRIPTOL, ColouriseSolDoc, \"scriptol\", FoldSolDoc);\nFix warning from Clang.\/\/ Scintilla source code edit control\n\/** @file LexScriptol.cxx\n ** Lexer for Scriptol.\n **\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"ILexer.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\n#include \"WordList.h\"\n#include \"LexAccessor.h\"\n#include \"Accessor.h\"\n#include \"StyleContext.h\"\n#include \"CharacterSet.h\"\n#include \"LexerModule.h\"\n\n#ifdef SCI_NAMESPACE\nusing namespace Scintilla;\n#endif\n\nstatic void ClassifyWordSol(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler, char *prevWord)\n{\n char s[100];\n bool wordIsNumber = isdigit(styler[start]) != 0;\n for (unsigned int i = 0; i < end - start + 1 && i < 30; i++)\n {\n s[i] = styler[start + i];\n s[i + 1] = '\\0';\n }\n char chAttr = SCE_SCRIPTOL_IDENTIFIER;\n if (0 == strcmp(prevWord, \"class\")) chAttr = SCE_SCRIPTOL_CLASSNAME;\n else if (wordIsNumber) chAttr = SCE_SCRIPTOL_NUMBER;\n else if (keywords.InList(s)) chAttr = SCE_SCRIPTOL_KEYWORD;\n else for (unsigned int i = 0; i < end - start + 1; i++) \/\/ test dotted idents\n {\n if (styler[start + i] == '.')\n {\n styler.ColourTo(start + i - 1, chAttr);\n styler.ColourTo(start + i, SCE_SCRIPTOL_OPERATOR);\n }\n }\n styler.ColourTo(end, chAttr);\n strcpy(prevWord, s);\n}\n\nstatic bool IsSolComment(Accessor &styler, int pos, int len)\n{\n if(len > 0)\n {\n char c = styler[pos];\n if(c == '`') return true;\n if(len > 1)\n {\n if(c == '\/')\n {\n c = styler[pos + 1];\n if(c == '\/') return true;\n if(c == '*') return true;\n }\n }\n }\n return false;\n}\n\nstatic bool IsSolStringStart(char ch)\n{\n if (ch == '\\'' || ch == '\"') return true;\n return false;\n}\n\nstatic bool IsSolWordStart(char ch)\n{\n return (iswordchar(ch) && !IsSolStringStart(ch));\n}\n\n\nstatic int GetSolStringState(Accessor &styler, int i, int *nextIndex)\n{\n\tchar ch = styler.SafeGetCharAt(i);\n\tchar chNext = styler.SafeGetCharAt(i + 1);\n\n if (ch != '\\\"' && ch != '\\'')\n {\n *nextIndex = i + 1;\n return SCE_SCRIPTOL_DEFAULT;\n\t}\n \/\/ ch is either single or double quotes in string\n \/\/ code below seem non-sense but is here for future extensions\n\tif (ch == chNext && ch == styler.SafeGetCharAt(i + 2))\n {\n *nextIndex = i + 3;\n if(ch == '\\\"') return SCE_SCRIPTOL_TRIPLE;\n if(ch == '\\'') return SCE_SCRIPTOL_TRIPLE;\n return SCE_SCRIPTOL_STRING;\n\t}\n else\n {\n *nextIndex = i + 1;\n if (ch == '\"') return SCE_SCRIPTOL_STRING;\n else return SCE_SCRIPTOL_STRING;\n\t}\n}\n\n\nstatic void ColouriseSolDoc(unsigned int startPos, int length, int initStyle,\n WordList *keywordlists[], Accessor &styler)\n {\n\n\tint lengthDoc = startPos + length;\n char stringType = '\\\"';\n\n\tif (startPos > 0)\n {\n int lineCurrent = styler.GetLine(startPos);\n if (lineCurrent > 0)\n {\n startPos = styler.LineStart(lineCurrent-1);\n if (startPos == 0) initStyle = SCE_SCRIPTOL_DEFAULT;\n else initStyle = styler.StyleAt(startPos-1);\n }\n\t}\n\n\tstyler.StartAt(startPos, 127);\n\n\tWordList &keywords = *keywordlists[0];\n\n\tint whingeLevel = styler.GetPropertyInt(\"tab.timmy.whinge.level\");\n\tchar prevWord[200];\n\tprevWord[0] = '\\0';\n if (length == 0) return;\n\n\tint state = initStyle & 31;\n\n\tint nextIndex = 0;\n char chPrev = ' ';\n char chPrev2 = ' ';\n char chNext = styler[startPos];\n\tstyler.StartSegment(startPos);\n\tbool atStartLine = true;\n\tint spaceFlags = 0;\n\tfor (int i = startPos; i < lengthDoc; i++)\n {\n\n if (atStartLine)\n {\n char chBad = static_cast(64);\n char chGood = static_cast(0);\n char chFlags = chGood;\n\n if (whingeLevel == 1)\n {\n chFlags = (spaceFlags & wsInconsistent) ? chBad : chGood;\n }\n else if (whingeLevel == 2)\n {\n chFlags = (spaceFlags & wsSpaceTab) ? chBad : chGood;\n }\n else if (whingeLevel == 3)\n {\n chFlags = (spaceFlags & wsSpace) ? chBad : chGood;\n }\n else if (whingeLevel == 4)\n {\n chFlags = (spaceFlags & wsTab) ? chBad : chGood;\n }\n styler.SetFlags(chFlags, static_cast(state));\n atStartLine = false;\n }\n\n char ch = chNext;\n chNext = styler.SafeGetCharAt(i + 1);\n\n if ((ch == '\\r' && chNext != '\\n') || (ch == '\\n') || (i == lengthDoc))\n {\n if ((state == SCE_SCRIPTOL_DEFAULT) ||\n (state == SCE_SCRIPTOL_TRIPLE) ||\n (state == SCE_SCRIPTOL_COMMENTBLOCK))\n {\n styler.ColourTo(i, state);\n }\n atStartLine = true;\n }\n\n if (styler.IsLeadByte(ch))\n {\n chNext = styler.SafeGetCharAt(i + 2);\n chPrev = ' ';\n chPrev2 = ' ';\n i += 1;\n continue;\n }\n\n if (state == SCE_SCRIPTOL_STRINGEOL)\n {\n if (ch != '\\r' && ch != '\\n')\n {\n styler.ColourTo(i - 1, state);\n state = SCE_SCRIPTOL_DEFAULT;\n }\n }\n\n if (state == SCE_SCRIPTOL_DEFAULT)\n {\n if (IsSolWordStart(ch))\n {\n styler.ColourTo(i - 1, state);\n state = SCE_SCRIPTOL_KEYWORD;\n }\n else if (ch == '`')\n {\n styler.ColourTo(i - 1, state);\n state = SCE_SCRIPTOL_COMMENTLINE;\n }\n else if (ch == '\/')\n {\n styler.ColourTo(i - 1, state);\n if(chNext == '\/') state = SCE_SCRIPTOL_CSTYLE;\n if(chNext == '*') state = SCE_SCRIPTOL_COMMENTBLOCK;\n }\n\n else if (IsSolStringStart(ch))\n {\n styler.ColourTo(i - 1, state);\n state = GetSolStringState(styler, i, &nextIndex);\n if(state == SCE_SCRIPTOL_STRING)\n {\n stringType = ch;\n }\n if (nextIndex != i + 1)\n {\n i = nextIndex - 1;\n ch = ' ';\n chPrev = ' ';\n chNext = styler.SafeGetCharAt(i + 1);\n }\n }\n else if (isoperator(ch))\n {\n styler.ColourTo(i - 1, state);\n styler.ColourTo(i, SCE_SCRIPTOL_OPERATOR);\n }\n }\n else if (state == SCE_SCRIPTOL_KEYWORD)\n {\n if (!iswordchar(ch))\n {\n ClassifyWordSol(styler.GetStartSegment(), i - 1, keywords, styler, prevWord);\n state = SCE_SCRIPTOL_DEFAULT;\n if (ch == '`')\n {\n state = chNext == '`' ? SCE_SCRIPTOL_PERSISTENT : SCE_SCRIPTOL_COMMENTLINE;\n }\n else if (IsSolStringStart(ch))\n {\n styler.ColourTo(i - 1, state);\n state = GetSolStringState(styler, i, &nextIndex);\n if (nextIndex != i + 1)\n {\n i = nextIndex - 1;\n ch = ' ';\n chPrev = ' ';\n chNext = styler.SafeGetCharAt(i + 1);\n }\n }\n else if (isoperator(ch))\n {\n styler.ColourTo(i, SCE_SCRIPTOL_OPERATOR);\n }\n }\n }\n else\n {\n if (state == SCE_SCRIPTOL_COMMENTLINE ||\n state == SCE_SCRIPTOL_PERSISTENT ||\n state == SCE_SCRIPTOL_CSTYLE)\n {\n if (ch == '\\r' || ch == '\\n')\n {\n styler.ColourTo(i - 1, state);\n state = SCE_SCRIPTOL_DEFAULT;\n }\n }\n else if(state == SCE_SCRIPTOL_COMMENTBLOCK)\n {\n if(chPrev == '*' && ch == '\/')\n {\n styler.ColourTo(i, state);\n state = SCE_SCRIPTOL_DEFAULT;\n }\n }\n else if ((state == SCE_SCRIPTOL_STRING) ||\n (state == SCE_SCRIPTOL_CHARACTER))\n {\n if ((ch == '\\r' || ch == '\\n') && (chPrev != '\\\\'))\n {\n styler.ColourTo(i - 1, state);\n state = SCE_SCRIPTOL_STRINGEOL;\n }\n else if (ch == '\\\\')\n {\n if (chNext == '\\\"' || chNext == '\\'' || chNext == '\\\\')\n {\n i++;\n ch = chNext;\n chNext = styler.SafeGetCharAt(i + 1);\n }\n }\n else if ((ch == '\\\"') || (ch == '\\''))\n {\n \/\/ must match the entered quote type\n if(ch == stringType)\n {\n styler.ColourTo(i, state);\n state = SCE_SCRIPTOL_DEFAULT;\n }\n }\n }\n else if (state == SCE_SCRIPTOL_TRIPLE)\n {\n if ((ch == '\\'' && chPrev == '\\'' && chPrev2 == '\\'') ||\n (ch == '\\\"' && chPrev == '\\\"' && chPrev2 == '\\\"'))\n {\n styler.ColourTo(i, state);\n state = SCE_SCRIPTOL_DEFAULT;\n }\n }\n\n }\n chPrev2 = chPrev;\n chPrev = ch;\n\t}\n if (state == SCE_SCRIPTOL_KEYWORD)\n {\n ClassifyWordSol(styler.GetStartSegment(),\n lengthDoc-1, keywords, styler, prevWord);\n\t}\n else\n {\n styler.ColourTo(lengthDoc-1, state);\n\t}\n}\n\nstatic void FoldSolDoc(unsigned int startPos, int length, int initStyle,\n\t\t\t\t\t\t WordList *[], Accessor &styler)\n {\n\tint lengthDoc = startPos + length;\n\n\tint lineCurrent = styler.GetLine(startPos);\n\tif (startPos > 0)\n {\n if (lineCurrent > 0)\n {\n lineCurrent--;\n startPos = styler.LineStart(lineCurrent);\n if (startPos == 0)\n initStyle = SCE_SCRIPTOL_DEFAULT;\n else\n initStyle = styler.StyleAt(startPos-1);\n }\n\t}\n\tint state = initStyle & 31;\n\tint spaceFlags = 0;\n int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsSolComment);\n if (state == SCE_SCRIPTOL_TRIPLE)\n indentCurrent |= SC_FOLDLEVELWHITEFLAG;\n\tchar chNext = styler[startPos];\n\tfor (int i = startPos; i < lengthDoc; i++)\n {\n\t\tchar ch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i + 1);\n\t\tint style = styler.StyleAt(i) & 31;\n\n\t\tif ((ch == '\\r' && chNext != '\\n') || (ch == '\\n') || (i == lengthDoc))\n {\n int lev = indentCurrent;\n int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsSolComment);\n if (style == SCE_SCRIPTOL_TRIPLE)\n indentNext |= SC_FOLDLEVELWHITEFLAG;\n if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG))\n {\n \/\/ Only non whitespace lines can be headers\n if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK))\n {\n lev |= SC_FOLDLEVELHEADERFLAG;\n }\n else if (indentNext & SC_FOLDLEVELWHITEFLAG)\n {\n \/\/ Line after is blank so check the next - maybe should continue further?\n int spaceFlags2 = 0;\n int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsSolComment);\n if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK))\n {\n lev |= SC_FOLDLEVELHEADERFLAG;\n }\n }\n }\n indentCurrent = indentNext;\n styler.SetLevel(lineCurrent, lev);\n lineCurrent++;\n\t\t}\n\t}\n}\n\nLexerModule lmScriptol(SCLEX_SCRIPTOL, ColouriseSolDoc, \"scriptol\", FoldSolDoc);\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2009 Nokia Corporation.\n *\n * Contact: Marius Vollmer \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\n *\/\n\n#include \n#include \n#include \"nanotree.h\"\n\nclass NanoTreeUnitTest : public QObject\n{\n Q_OBJECT\n\nprivate:\n NanoTree buildBasic();\n NanoTree buildComplex();\n\nprivate slots:\n void keyValue1();\n void keyValue2();\n};\n\nNanoTree NanoTreeUnitTest::buildBasic()\n{\n QVariantList param1;\n param1 << QVariant(\"param1\");\n param1 << QVariant(\"value1\");\n\n QVariantList param2;\n param2 << QVariant(\"param2\");\n param2 << QVariant(\"value2\");\n\n QVariantList tree;\n tree << QVariant(param1);\n tree << QVariant(param2);\n\n return NanoTree(tree);\n}\n\nNanoTree NanoTreeUnitTest::buildComplex()\n{\n QVariantList params;\n params << QVariant(\"params\");\n\n QVariantList param1;\n param1 << QVariant(\"param1\");\n param1 << QVariant(\"value1\");\n\n QVariantList param2;\n param2 << QVariant(\"param2\");\n param2 << QVariant(\"value2\");\n\n params << QVariant(param1);\n params << QVariant(param2);\n\n QVariantList doc;\n doc << QVariant(\"doc\");\n doc << QVariant(\"documentation\");\n\n QVariantList tree;\n tree << QVariant(params);\n tree << QVariant(doc);\n\n return NanoTree(tree);\n}\n\nvoid NanoTreeUnitTest::keyValue1()\n{\n NanoTree tree = buildBasic();\n QCOMPARE(tree.keyValue(\"param1\").toString(), QString(\"value1\"));\n QCOMPARE(tree.keyValue(\"param2\").toString(), QString(\"value2\"));\n}\n\nvoid NanoTreeUnitTest::keyValue2()\n{\n NanoTree tree = buildComplex();\n QCOMPARE(tree.keyValue(\"params\", \"param1\").toString(), QString(\"value1\"));\n QCOMPARE(tree.keyValue(\"params\", \"param2\").toString(), QString(\"value2\"));\n QCOMPARE(tree.keyValue(\"doc\").toString(), QString(\"documentation\"));\n}\n\n#include \"nanotreeunittest.moc\"\nQTEST_MAIN(NanoTreeUnitTest);\nNanoTree::keys() test.\/*\n * Copyright (C) 2009 Nokia Corporation.\n *\n * Contact: Marius Vollmer \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\n *\/\n\n#include \n#include \n#include \"nanotree.h\"\n\nclass NanoTreeUnitTest : public QObject\n{\n Q_OBJECT\n\nprivate:\n NanoTree buildBasic();\n NanoTree buildComplex();\n\nprivate slots:\n void keyValue1();\n void keyValue2();\n void keys();\n};\n\nNanoTree NanoTreeUnitTest::buildBasic()\n{\n QVariantList param1;\n param1 << QVariant(\"param1\");\n param1 << QVariant(\"value1\");\n\n QVariantList param2;\n param2 << QVariant(\"param2\");\n param2 << QVariant(\"value2\");\n\n QVariantList tree;\n tree << QVariant(param1);\n tree << QVariant(param2);\n\n return NanoTree(tree);\n}\n\nNanoTree NanoTreeUnitTest::buildComplex()\n{\n QVariantList params;\n params << QVariant(\"params\");\n\n QVariantList param1;\n param1 << QVariant(\"param1\");\n param1 << QVariant(\"value1\");\n\n QVariantList param2;\n param2 << QVariant(\"param2\");\n param2 << QVariant(\"value2\");\n\n params << QVariant(param1);\n params << QVariant(param2);\n\n QVariantList doc;\n doc << QVariant(\"doc\");\n doc << QVariant(\"documentation\");\n\n QVariantList tree;\n tree << QVariant(params);\n tree << QVariant(doc);\n\n return NanoTree(tree);\n}\n\nvoid NanoTreeUnitTest::keyValue1()\n{\n NanoTree tree = buildBasic();\n QCOMPARE(tree.keyValue(\"param1\").toString(), QString(\"value1\"));\n QCOMPARE(tree.keyValue(\"param2\").toString(), QString(\"value2\"));\n}\n\nvoid NanoTreeUnitTest::keyValue2()\n{\n NanoTree tree = buildComplex();\n QCOMPARE(tree.keyValue(\"params\", \"param1\").toString(), QString(\"value1\"));\n QCOMPARE(tree.keyValue(\"params\", \"param2\").toString(), QString(\"value2\"));\n QCOMPARE(tree.keyValue(\"doc\").toString(), QString(\"documentation\"));\n}\n\nvoid NanoTreeUnitTest::keys()\n{\n NanoTree tree = buildComplex();\n QStringList lst1 = tree.keys();\n\n QCOMPARE(lst1.size(), 2);\n QVERIFY(lst1.contains(\"params\"));\n QVERIFY(lst1.contains(\"doc\"));\n\n QStringList lst2 = tree.keyNode(\"params\").keys();\n QCOMPARE(lst2.size(), 2);\n QVERIFY(lst2.contains(\"param1\"));\n QVERIFY(lst2.contains(\"param2\"));\n\n}\n\n#include \"nanotreeunittest.moc\"\nQTEST_MAIN(NanoTreeUnitTest);\n<|endoftext|>"} {"text":"#include \"controllers\/pings\/PingController.hpp\"\n#include \"controllers\/pings\/PingModel.hpp\"\n\nnamespace chatterino {\n\nvoid PingController::initialize(Settings &settings, Paths &paths)\n{\n this->initialized_ = true;\n for (const QString &channelName : this->pingSetting_.getValue())\n {\n this->channelVector.append(channelName);\n }\n\n this->channelVector.delayedItemsChanged.connect([this] { \/\/\n this->pingSetting_.setValue(this->channelVector.raw());\n });\n}\n\nPingModel *PingController::createModel(QObject *parent)\n{\n PingModel *model = new PingModel(parent);\n model->initialize(&this->channelVector);\n return model;\n}\n\nbool PingController::isMuted(const QString &channelName)\n{\n for (const auto &channel : this->channelVector)\n {\n if (channelName.toLower() == channel.toLower())\n {\n return true;\n }\n }\n return false;\n}\n\nvoid PingController::muteChannel(const QString &channelName)\n{\n channelVector.append(channelName);\n}\n\nvoid PingController::unmuteChannel(const QString &channelName)\n{\n for (std::vector::size_type i = 0;\n i != channelVector.raw().size(); i++)\n {\n if (channelVector.raw()[i].toLower() == channelName.toLower())\n {\n channelVector.removeAt(i);\n i--;\n }\n }\n}\n\nbool PingController::toggleMuteChannel(const QString &channelName)\n{\n if (this->isMuted(channelName))\n {\n unmuteChannel(channelName);\n return false;\n }\n else\n {\n muteChannel(channelName);\n return true;\n }\n}\n\n} \/\/ namespace chatterino\nfixed formatting#include \"controllers\/pings\/PingController.hpp\"\n#include \"controllers\/pings\/PingModel.hpp\"\n\nnamespace chatterino {\n\nvoid PingController::initialize(Settings &settings, Paths &paths)\n{\n this->initialized_ = true;\n for (const QString &channelName : this->pingSetting_.getValue())\n {\n this->channelVector.append(channelName);\n }\n\n this->channelVector.delayedItemsChanged.connect([this] { \/\/\n this->pingSetting_.setValue(this->channelVector.raw());\n });\n}\n\nPingModel *PingController::createModel(QObject *parent)\n{\n PingModel *model = new PingModel(parent);\n model->initialize(&this->channelVector);\n return model;\n}\n\nbool PingController::isMuted(const QString &channelName)\n{\n for (const auto &channel : this->channelVector)\n {\n if (channelName.toLower() == channel.toLower())\n {\n return true;\n }\n }\n return false;\n}\n\nvoid PingController::muteChannel(const QString &channelName)\n{\n channelVector.append(channelName);\n}\n\nvoid PingController::unmuteChannel(const QString &channelName)\n{\n for (std::vector::size_type i = 0; i != channelVector.raw().size();\n i++)\n {\n if (channelVector.raw()[i].toLower() == channelName.toLower())\n {\n channelVector.removeAt(i);\n i--;\n }\n }\n}\n\nbool PingController::toggleMuteChannel(const QString &channelName)\n{\n if (this->isMuted(channelName))\n {\n unmuteChannel(channelName);\n return false;\n }\n else\n {\n muteChannel(channelName);\n return true;\n }\n}\n\n} \/\/ namespace chatterino\n<|endoftext|>"} {"text":"\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/fluid\/operators\/math\/fc.h\"\n#include \"paddle\/fluid\/operators\/jit\/kernels.h\"\n#include \"paddle\/fluid\/operators\/math\/blas.h\"\n\nnamespace paddle {\nnamespace operators {\nnamespace math {\n\ntemplate \nclass FCFunctor {\n public:\n void operator()(const platform::CPUDeviceContext& context, const int M,\n const int N, const int K, const T* X, const T* W, T* Y,\n const T* B = nullptr, bool relu = false,\n bool padding_weights = false) {\n auto blas = math::GetBlas(context);\n framework::Tensor Y1;\n T* Y1_data = nullptr;\n if (padding_weights) {\n const int NN = N + 4;\n const int KK = K + 4;\n framework::Tensor X1;\n T* X1_data = X1.mutable_data({M * KK}, platform::CPUPlace());\n Y1_data = Y1.mutable_data({M * (N + 4)}, platform::CPUPlace());\n#ifdef PADDLE_WITH_MKLML\n#pragma omp parallel for\n#endif\n for (int i = 0; i < M; i++) {\n memcpy(X1_data + i * KK, X + i * K, K * sizeof(T));\n }\n blas.GEMM(false, false, M, N, K, static_cast(1.0), X1_data, KK, W, NN,\n static_cast(0.0), Y1_data, NN);\n } else {\n blas.MatMul(M, N, K, X, W, Y);\n }\n if (B == NULL) {\n if (padding_weights) {\n#ifdef PADDLE_WITH_MKLML\n#pragma omp parallel for\n#endif\n for (int i = 0; i < M; i++) {\n memcpy(Y + i * N, Y1_data + i * (N + 4), N * sizeof(T));\n }\n }\n PADDLE_ENFORCE_EQ(relu, false,\n platform::errors::PermissionDenied(\n \"When bias is NULL, relu can not be true.\"));\n return;\n }\n if (relu) {\n auto compute =\n jit::KernelFuncs, platform::CPUPlace>::Cache()\n .At(N);\n for (int i = 0; i < M; i++) {\n T* dst = Y + i * N;\n T* src = (padding_weights) ? Y1_data + i * (N + 4) : dst;\n compute(B, src, dst, N);\n }\n } else {\n auto compute =\n jit::KernelFuncs, platform::CPUPlace>::Cache().At(\n N);\n#ifdef PADDLE_WITH_MKLML\n#pragma omp parallel for\n#endif\n for (int i = 0; i < M; i++) {\n T* dst = Y + i * N;\n T* src = (padding_weights) ? Y1_data + i * (N + 4) : dst;\n compute(B, src, dst, N);\n }\n }\n }\n};\n\ntemplate class FCFunctor;\ntemplate class FCFunctor;\n\n} \/\/ namespace math\n} \/\/ namespace operators\n} \/\/ namespace paddle\noptimize fc jit (#21878)\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/fluid\/operators\/math\/fc.h\"\n#include \"paddle\/fluid\/operators\/jit\/kernels.h\"\n#include \"paddle\/fluid\/operators\/math\/blas.h\"\n\nnamespace paddle {\nnamespace operators {\nnamespace math {\n\ntemplate \nclass FCFunctor {\n public:\n void operator()(const platform::CPUDeviceContext& context, const int M,\n const int N, const int K, const T* X, const T* W, T* Y,\n const T* B = nullptr, bool relu = false,\n bool padding_weights = false) {\n auto blas = math::GetBlas(context);\n framework::Tensor Y1;\n T* Y1_data = nullptr;\n if (padding_weights) {\n const int NN = N + 4;\n const int KK = K + 4;\n framework::Tensor X1;\n T* X1_data = X1.mutable_data({M * KK}, platform::CPUPlace());\n Y1_data = Y1.mutable_data({M * (N + 4)}, platform::CPUPlace());\n#ifdef PADDLE_WITH_MKLML\n#pragma omp parallel for\n#endif\n for (int i = 0; i < M; i++) {\n memcpy(X1_data + i * KK, X + i * K, K * sizeof(T));\n }\n blas.GEMM(false, false, M, N, K, static_cast(1.0), X1_data, KK, W, NN,\n static_cast(0.0), Y1_data, NN);\n } else {\n blas.MatMul(M, N, K, X, W, Y);\n }\n if (B == NULL) {\n if (padding_weights) {\n#ifdef PADDLE_WITH_MKLML\n#pragma omp parallel for\n#endif\n for (int i = 0; i < M; i++) {\n memcpy(Y + i * N, Y1_data + i * (N + 4), N * sizeof(T));\n }\n }\n PADDLE_ENFORCE_EQ(relu, false,\n platform::errors::PermissionDenied(\n \"When bias is NULL, relu can not be true.\"));\n return;\n }\n auto compute =\n relu\n ? jit::KernelFuncs,\n platform::CPUPlace>::Cache()\n .At(N)\n : jit::KernelFuncs, platform::CPUPlace>::Cache()\n .At(N);\n#ifdef PADDLE_WITH_MKLML\n#pragma omp parallel for\n#endif\n for (int i = 0; i < M; i++) {\n T* dst = Y + i * N;\n T* src = (padding_weights) ? Y1_data + i * (N + 4) : dst;\n compute(B, src, dst, N);\n }\n }\n};\n\ntemplate class FCFunctor;\ntemplate class FCFunctor;\n\n} \/\/ namespace math\n} \/\/ namespace operators\n} \/\/ namespace paddle\n<|endoftext|>"} {"text":"\/*\n * SessionBuild.cpp\n *\n * Copyright (C) 2009-12 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"SessionBuild.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace core;\n\nnamespace session {\nnamespace modules { \nnamespace build {\n\nnamespace {\n\nFilePath restartContextFilePath()\n{\n return module_context::scopedScratchPath().childPath(\n \"build_restart_context\");\n}\n\nvoid saveRestartContext(const FilePath& packageDir,\n const std::string& buildOutput)\n{\n \/\/ read package info\n r_util::RPackageInfo pkgInfo;\n Error error = pkgInfo.read(packageDir);\n if (error)\n {\n LOG_ERROR(error);\n return;\n }\n\n \/\/ save restart context\n core::Settings restartSettings;\n error = restartSettings.initialize(restartContextFilePath());\n if (error)\n {\n LOG_ERROR(error);\n return;\n }\n\n restartSettings.beginUpdate();\n restartSettings.set(\"package_name\", pkgInfo.name());\n restartSettings.set(\"build_output\", buildOutput);\n restartSettings.endUpdate();\n}\n\njson::Value collectRestartContext()\n{\n FilePath restartSettingsPath = restartContextFilePath();\n if (restartSettingsPath.exists())\n {\n \/\/ always cleanup the restart context on scope exit\n BOOST_SCOPE_EXIT( (&restartSettingsPath) )\n {\n Error error = restartSettingsPath.remove();\n if (error)\n LOG_ERROR(error);\n }\n BOOST_SCOPE_EXIT_END\n\n core::Settings restartSettings;\n Error error = restartSettings.initialize(restartContextFilePath());\n if (error)\n {\n LOG_ERROR(error);\n return json::Value();\n }\n\n json::Object restartJson;\n restartJson[\"package_name\"] = restartSettings.get(\"package_name\");\n restartJson[\"build_output\"] = restartSettings.get(\"build_output\");\n return restartJson;\n }\n else\n {\n return json::Value();\n }\n}\n\n\n\/\/ R command invocation -- has two representations, one to be submitted\n\/\/ (shellCmd_) and one to show the user (cmdString_)\nclass RCommand\n{\npublic:\n explicit RCommand(const FilePath& rBinDir)\n#ifdef _WIN32\n : shellCmd_(rBinDir.childPath(\"Rcmd.exe\"))\n#else\n : shellCmd_(rBinDir.childPath(\"R\"))\n#endif\n {\n#ifdef _WIN32\n cmdString_ = \"Rcmd.exe\";\n#else\n shellCmd_ << \"CMD\";\n cmdString_ = \"R CMD\";\n#endif\n }\n\n RCommand& operator<<(const std::string& arg)\n {\n cmdString_ += \" \" + arg;\n shellCmd_ << arg;\n return *this;\n }\n\n const std::string& commandString() const\n {\n return cmdString_;\n }\n\n const shell_utils::ShellCommand& shellCommand() const\n {\n return shellCmd_;\n }\n\nprivate:\n std::string cmdString_;\n shell_utils::ShellCommand shellCmd_;\n};\n\nclass Build : boost::noncopyable,\n public boost::enable_shared_from_this\n{\npublic:\n static boost::shared_ptr create(const std::string& type)\n {\n boost::shared_ptr pBuild(new Build());\n pBuild->start(type);\n return pBuild;\n }\n\nprivate:\n Build()\n : isRunning_(false), terminationRequested_(false), restartR_(false)\n {\n }\n\n void start(const std::string& type)\n {\n ClientEvent event(client_events::kBuildStarted);\n module_context::enqueClientEvent(event);\n\n isRunning_ = true;\n\n \/\/ read build options\n Error error = projects::projectContext().readBuildOptions(&options_);\n if (error)\n {\n terminateWithError(\"reading build options file\", error);\n return;\n }\n\n \/\/ callbacks\n core::system::ProcessCallbacks cb;\n cb.onContinue = boost::bind(&Build::onContinue,\n Build::shared_from_this());\n cb.onStdout = boost::bind(&Build::onOutput,\n Build::shared_from_this(), _2);\n cb.onStderr = boost::bind(&Build::onOutput,\n Build::shared_from_this(), _2);\n cb.onExit = boost::bind(&Build::onCompleted,\n Build::shared_from_this(),\n _1);\n\n \/\/ execute build\n executeBuild(type, cb);\n }\n\n\n void executeBuild(const std::string& type,\n const core::system::ProcessCallbacks& cb)\n {\n \/\/ options\n core::system::ProcessOptions options;\n options.terminateChildren = true;\n options.redirectStdErrToStdOut = true;\n\n const core::r_util::RProjectConfig& config = projectConfig();\n if (config.buildType == r_util::kBuildTypePackage)\n {\n FilePath packagePath = projectPath(config.packagePath);\n options.workingDir = packagePath.parent();\n executePackageBuild(type, packagePath, options, cb);\n }\n else if (config.buildType == r_util::kBuildTypeMakefile)\n {\n FilePath makefilePath = projectPath(config.makefilePath);\n options.workingDir = makefilePath;\n executeMakefileBuild(type, options, cb);\n }\n else if (config.buildType == r_util::kBuildTypeCustom)\n {\n FilePath scriptPath = projectPath(config.customScriptPath);\n options.workingDir = scriptPath.parent();\n executeCustomBuild(type, scriptPath, options, cb);\n }\n else\n {\n terminateWithError(\"Unrecognized build type: \" + config.buildType);\n }\n }\n\n void executePackageBuild(const std::string& type,\n const FilePath& packagePath,\n const core::system::ProcessOptions& options,\n const core::system::ProcessCallbacks& cb)\n {\n \/\/ get package info\n r_util::RPackageInfo pkgInfo;\n Error error = pkgInfo.read(packagePath);\n if (error)\n {\n terminateWithError(\"Reading package DESCRIPTION\", error);\n return;\n }\n\n \/\/ get R bin directory\n FilePath rBinDir;\n error = module_context::rBinDir(&rBinDir);\n if (error)\n {\n terminateWithError(\"attempting to locate R binary\", error);\n return;\n }\n\n \/\/ build command\n if (type == \"build-all\")\n {\n \/\/ restart R after build is completed\n restartR_ = true;\n\n \/\/ build command\n RCommand rCmd(rBinDir);\n rCmd << \"INSTALL\";\n rCmd << packagePath.filename();\n\n \/\/ show the user the command\n enqueBuildOutput(rCmd.commandString() + \"\\n\\n\");\n\n \/\/ run R CMD INSTALL \n module_context::processSupervisor().runCommand(rCmd.shellCommand(),\n options,\n cb);\n }\n\n else if (type == \"build-source-package\")\n {\n \/\/ compose the build command\n RCommand rCmd(rBinDir);\n rCmd << \"build\";\n rCmd << packagePath.filename();\n\n \/\/ show the user the command\n enqueBuildOutput(rCmd.commandString() + \"\\n\\n\");\n\n \/\/ set a success message\n successMessage_ = buildPackageSuccessMsg(\"Source\");\n\n \/\/ run R CMD build \n module_context::processSupervisor().runCommand(rCmd.shellCommand(),\n options,\n cb);\n }\n\n else if (type == \"build-binary-package\")\n {\n \/\/ compose the INSTALL --binary\n RCommand rCmd(rBinDir);\n rCmd << \"INSTALL\";\n rCmd << \"--build\";\n rCmd << packagePath.filename();\n\n \/\/ show the user the command\n enqueBuildOutput(rCmd.commandString() + \"\\n\\n\");\n\n \/\/ set a success message\n successMessage_ = \"\\n\" + buildPackageSuccessMsg(\"Binary\");\n\n \/\/ run R CMD INSTALL --build \n module_context::processSupervisor().runCommand(rCmd.shellCommand(),\n options,\n cb);\n }\n\n else if (type == \"check-package\")\n {\n \/\/ first build then check\n\n \/\/ compose the build command\n RCommand rCmd(rBinDir);\n rCmd << \"build\";\n rCmd << packagePath.filename();\n\n \/\/ compose the check command (will be executed by the onExit\n \/\/ handler of the build cmd)\n RCommand rCheckCmd(rBinDir);\n rCheckCmd << \"check\";\n rCheckCmd << pkgInfo.sourcePackageFilename();\n\n \/\/ special callback for build result\n system::ProcessCallbacks buildCb = cb;\n buildCb.onExit = boost::bind(&Build::onBuildForCheckCompleted,\n Build::shared_from_this(),\n _1,\n rCheckCmd,\n options,\n buildCb);\n\n \/\/ show the user the command\n enqueBuildOutput(rCmd.commandString() + \"\\n\\n\");\n\n \/\/ set a success message\n successMessage_ = \"R CMD check succeeded\\n\";\n\n \/\/ run the source build\n module_context::processSupervisor().runCommand(rCmd.shellCommand(),\n options,\n buildCb);\n }\n }\n\n\n void onBuildForCheckCompleted(\n int exitStatus,\n const RCommand& checkCmd,\n const core::system::ProcessOptions& checkOptions,\n const core::system::ProcessCallbacks& checkCb)\n {\n if (exitStatus == EXIT_SUCCESS)\n {\n \/\/ show the user the buld command\n enqueBuildOutput(checkCmd.commandString() + \"\\n\\n\");\n\n \/\/ run the check\n module_context::processSupervisor().runCommand(checkCmd.shellCommand(),\n checkOptions,\n checkCb);\n }\n else\n {\n boost::format fmt(\"\\nExited with status %1%.\\n\\n\");\n enqueBuildOutput(boost::str(fmt % exitStatus));\n enqueBuildCompleted();\n }\n }\n\n void executeMakefileBuild(const std::string& type,\n const core::system::ProcessOptions& options,\n const core::system::ProcessCallbacks& cb)\n {\n std::string make = \"make\";\n if (!options_.makefileArgs.empty())\n make += \" \" + options_.makefileArgs;\n\n std::string makeClean = make + \" clean\";\n\n std::string cmd;\n if (type == \"build-all\")\n {\n cmd = make;\n }\n else if (type == \"clean-all\")\n {\n cmd = makeClean;\n }\n else if (type == \"rebuild-all\")\n {\n cmd = shell_utils::join_and(makeClean, make);\n }\n\n module_context::processSupervisor().runCommand(cmd,\n options,\n cb);\n }\n\n void executeCustomBuild(const std::string& type,\n const FilePath& customScriptPath,\n const core::system::ProcessOptions& options,\n const core::system::ProcessCallbacks& cb)\n {\n module_context::processSupervisor().runCommand(\n shell_utils::ShellCommand(customScriptPath),\n options,\n cb);\n }\n\n FilePath projectPath(const std::string& path)\n {\n if (boost::algorithm::starts_with(path, \"~\/\") ||\n FilePath::isRootPath(path))\n {\n return module_context::resolveAliasedPath(path);\n }\n else\n {\n return projects::projectContext().directory().complete(path);\n }\n }\n\n void terminateWithError(const std::string& context,\n const Error& error)\n {\n std::string msg = \"Error \" + context + \": \" + error.summary();\n terminateWithError(msg);\n }\n\n void terminateWithError(const std::string& msg)\n {\n enqueBuildOutput(msg);\n enqueBuildCompleted();\n }\n\npublic:\n virtual ~Build()\n {\n }\n\n bool isRunning() const { return isRunning_; }\n\n const std::string& output() const { return output_; }\n\n void terminate()\n {\n enqueBuildOutput(\"\\n\");\n terminationRequested_ = true;\n }\n\nprivate:\n bool onContinue()\n {\n return !terminationRequested_;\n }\n\n void onOutput(const std::string& output)\n {\n enqueBuildOutput(output);\n }\n\n void onCompleted(int exitStatus)\n {\n if (exitStatus != EXIT_SUCCESS)\n {\n boost::format fmt(\"\\nExited with status %1%.\\n\\n\");\n enqueBuildOutput(boost::str(fmt % exitStatus));\n\n \/\/ never restart R after a failed build\n restartR_ = false;\n }\n else\n {\n if (!successMessage_.empty())\n enqueBuildOutput(successMessage_ + \"\\n\");\n }\n\n enqueBuildCompleted();\n }\n\n void enqueBuildOutput(const std::string& output)\n {\n output_.append(output);\n\n ClientEvent event(client_events::kBuildOutput, output);\n module_context::enqueClientEvent(event);\n }\n\n void enqueBuildCompleted()\n {\n isRunning_ = false;\n\n \/\/ save the restart context if necessary\n if ((projectConfig().buildType == r_util::kBuildTypePackage) && restartR_)\n {\n FilePath packagePath = projectPath(projectConfig().packagePath);\n saveRestartContext(packagePath, output_);\n }\n\n ClientEvent event(client_events::kBuildCompleted, restartR_);\n module_context::enqueClientEvent(event);\n }\n\n const r_util::RProjectConfig& projectConfig()\n {\n return projects::projectContext().config();\n }\n\n std::string buildPackageSuccessMsg(const std::string& type)\n {\n FilePath writtenPath = projectPath(projectConfig().packagePath).parent();\n std::string written = module_context::createAliasedPath(writtenPath);\n if (written == \"~\")\n written = writtenPath.absolutePath();\n\n return type + \" package written to \" + written;\n }\n\nprivate:\n bool isRunning_;\n bool terminationRequested_;\n std::string output_;\n projects::RProjectBuildOptions options_;\n std::string successMessage_;\n bool restartR_;\n};\n\nboost::shared_ptr s_pBuild;\n\n\nbool isBuildRunning()\n{\n return s_pBuild && s_pBuild->isRunning();\n}\n\nError startBuild(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ get type\n std::string type;\n Error error = json::readParam(request.params, 0, &type);\n if (error)\n return error;\n\n \/\/ if we have a build already running then just return false\n if (isBuildRunning())\n {\n pResponse->setResult(false);\n }\n else\n {\n s_pBuild = Build::create(type);\n pResponse->setResult(true);\n }\n\n return Success();\n}\n\n\n\nError terminateBuild(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n if (isBuildRunning())\n s_pBuild->terminate();\n\n pResponse->setResult(true);\n\n return Success();\n}\n\n} \/\/ anonymous namespace\n\n\njson::Value buildStateAsJson()\n{\n if (s_pBuild)\n {\n json::Object stateJson;\n stateJson[\"running\"] = s_pBuild->isRunning();\n stateJson[\"output\"] = s_pBuild->output();\n return stateJson;\n }\n else\n {\n return json::Value();\n }\n}\n\njson::Value buildRestartContext()\n{\n return collectRestartContext();\n}\n\nError initialize()\n{\n \/\/ install rpc methods\n using boost::bind;\n using namespace module_context;\n ExecBlock initBlock ;\n initBlock.addFunctions()\n (bind(registerRpcMethod, \"start_build\", startBuild))\n (bind(registerRpcMethod, \"terminate_build\", terminateBuild));\n return initBlock.execute();\n}\n\n\n} \/\/ namespace build\n} \/\/ namespace modules\n} \/\/ namesapce session\n\ndeliniate command strings in build output\/*\n * SessionBuild.cpp\n *\n * Copyright (C) 2009-12 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"SessionBuild.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace core;\n\nnamespace session {\nnamespace modules { \nnamespace build {\n\nnamespace {\n\nFilePath restartContextFilePath()\n{\n return module_context::scopedScratchPath().childPath(\n \"build_restart_context\");\n}\n\nvoid saveRestartContext(const FilePath& packageDir,\n const std::string& buildOutput)\n{\n \/\/ read package info\n r_util::RPackageInfo pkgInfo;\n Error error = pkgInfo.read(packageDir);\n if (error)\n {\n LOG_ERROR(error);\n return;\n }\n\n \/\/ save restart context\n core::Settings restartSettings;\n error = restartSettings.initialize(restartContextFilePath());\n if (error)\n {\n LOG_ERROR(error);\n return;\n }\n\n restartSettings.beginUpdate();\n restartSettings.set(\"package_name\", pkgInfo.name());\n restartSettings.set(\"build_output\", buildOutput);\n restartSettings.endUpdate();\n}\n\njson::Value collectRestartContext()\n{\n FilePath restartSettingsPath = restartContextFilePath();\n if (restartSettingsPath.exists())\n {\n \/\/ always cleanup the restart context on scope exit\n BOOST_SCOPE_EXIT( (&restartSettingsPath) )\n {\n Error error = restartSettingsPath.remove();\n if (error)\n LOG_ERROR(error);\n }\n BOOST_SCOPE_EXIT_END\n\n core::Settings restartSettings;\n Error error = restartSettings.initialize(restartContextFilePath());\n if (error)\n {\n LOG_ERROR(error);\n return json::Value();\n }\n\n json::Object restartJson;\n restartJson[\"package_name\"] = restartSettings.get(\"package_name\");\n restartJson[\"build_output\"] = restartSettings.get(\"build_output\");\n return restartJson;\n }\n else\n {\n return json::Value();\n }\n}\n\n\n\/\/ R command invocation -- has two representations, one to be submitted\n\/\/ (shellCmd_) and one to show the user (cmdString_)\nclass RCommand\n{\npublic:\n explicit RCommand(const FilePath& rBinDir)\n#ifdef _WIN32\n : shellCmd_(rBinDir.childPath(\"Rcmd.exe\"))\n#else\n : shellCmd_(rBinDir.childPath(\"R\"))\n#endif\n {\n#ifdef _WIN32\n cmdString_ = \"Rcmd.exe\";\n#else\n shellCmd_ << \"CMD\";\n cmdString_ = \"R CMD\";\n#endif\n }\n\n RCommand& operator<<(const std::string& arg)\n {\n cmdString_ += \" \" + arg;\n shellCmd_ << arg;\n return *this;\n }\n\n const std::string& commandString() const\n {\n return cmdString_;\n }\n\n const shell_utils::ShellCommand& shellCommand() const\n {\n return shellCmd_;\n }\n\nprivate:\n std::string cmdString_;\n shell_utils::ShellCommand shellCmd_;\n};\n\nclass Build : boost::noncopyable,\n public boost::enable_shared_from_this\n{\npublic:\n static boost::shared_ptr create(const std::string& type)\n {\n boost::shared_ptr pBuild(new Build());\n pBuild->start(type);\n return pBuild;\n }\n\nprivate:\n Build()\n : isRunning_(false), terminationRequested_(false), restartR_(false)\n {\n }\n\n void start(const std::string& type)\n {\n ClientEvent event(client_events::kBuildStarted);\n module_context::enqueClientEvent(event);\n\n isRunning_ = true;\n\n \/\/ read build options\n Error error = projects::projectContext().readBuildOptions(&options_);\n if (error)\n {\n terminateWithError(\"reading build options file\", error);\n return;\n }\n\n \/\/ callbacks\n core::system::ProcessCallbacks cb;\n cb.onContinue = boost::bind(&Build::onContinue,\n Build::shared_from_this());\n cb.onStdout = boost::bind(&Build::onOutput,\n Build::shared_from_this(), _2);\n cb.onStderr = boost::bind(&Build::onOutput,\n Build::shared_from_this(), _2);\n cb.onExit = boost::bind(&Build::onCompleted,\n Build::shared_from_this(),\n _1);\n\n \/\/ execute build\n executeBuild(type, cb);\n }\n\n\n void executeBuild(const std::string& type,\n const core::system::ProcessCallbacks& cb)\n {\n \/\/ options\n core::system::ProcessOptions options;\n options.terminateChildren = true;\n options.redirectStdErrToStdOut = true;\n\n const core::r_util::RProjectConfig& config = projectConfig();\n if (config.buildType == r_util::kBuildTypePackage)\n {\n FilePath packagePath = projectPath(config.packagePath);\n options.workingDir = packagePath.parent();\n executePackageBuild(type, packagePath, options, cb);\n }\n else if (config.buildType == r_util::kBuildTypeMakefile)\n {\n FilePath makefilePath = projectPath(config.makefilePath);\n options.workingDir = makefilePath;\n executeMakefileBuild(type, options, cb);\n }\n else if (config.buildType == r_util::kBuildTypeCustom)\n {\n FilePath scriptPath = projectPath(config.customScriptPath);\n options.workingDir = scriptPath.parent();\n executeCustomBuild(type, scriptPath, options, cb);\n }\n else\n {\n terminateWithError(\"Unrecognized build type: \" + config.buildType);\n }\n }\n\n void executePackageBuild(const std::string& type,\n const FilePath& packagePath,\n const core::system::ProcessOptions& options,\n const core::system::ProcessCallbacks& cb)\n {\n \/\/ get package info\n r_util::RPackageInfo pkgInfo;\n Error error = pkgInfo.read(packagePath);\n if (error)\n {\n terminateWithError(\"Reading package DESCRIPTION\", error);\n return;\n }\n\n \/\/ get R bin directory\n FilePath rBinDir;\n error = module_context::rBinDir(&rBinDir);\n if (error)\n {\n terminateWithError(\"attempting to locate R binary\", error);\n return;\n }\n\n \/\/ build command\n if (type == \"build-all\")\n {\n \/\/ restart R after build is completed\n restartR_ = true;\n\n \/\/ build command\n RCommand rCmd(rBinDir);\n rCmd << \"INSTALL\";\n rCmd << packagePath.filename();\n\n \/\/ show the user the command\n enqueCommandString(rCmd.commandString());\n\n \/\/ run R CMD INSTALL \n module_context::processSupervisor().runCommand(rCmd.shellCommand(),\n options,\n cb);\n }\n\n else if (type == \"build-source-package\")\n {\n \/\/ compose the build command\n RCommand rCmd(rBinDir);\n rCmd << \"build\";\n rCmd << packagePath.filename();\n\n \/\/ show the user the command\n enqueCommandString(rCmd.commandString());\n\n \/\/ set a success message\n successMessage_ = buildPackageSuccessMsg(\"Source\");\n\n \/\/ run R CMD build \n module_context::processSupervisor().runCommand(rCmd.shellCommand(),\n options,\n cb);\n }\n\n else if (type == \"build-binary-package\")\n {\n \/\/ compose the INSTALL --binary\n RCommand rCmd(rBinDir);\n rCmd << \"INSTALL\";\n rCmd << \"--build\";\n rCmd << packagePath.filename();\n\n \/\/ show the user the command\n enqueCommandString(rCmd.commandString());\n\n \/\/ set a success message\n successMessage_ = \"\\n\" + buildPackageSuccessMsg(\"Binary\");\n\n \/\/ run R CMD INSTALL --build \n module_context::processSupervisor().runCommand(rCmd.shellCommand(),\n options,\n cb);\n }\n\n else if (type == \"check-package\")\n {\n \/\/ first build then check\n\n \/\/ compose the build command\n RCommand rCmd(rBinDir);\n rCmd << \"build\";\n rCmd << packagePath.filename();\n\n \/\/ compose the check command (will be executed by the onExit\n \/\/ handler of the build cmd)\n RCommand rCheckCmd(rBinDir);\n rCheckCmd << \"check\";\n rCheckCmd << pkgInfo.sourcePackageFilename();\n\n \/\/ special callback for build result\n system::ProcessCallbacks buildCb = cb;\n buildCb.onExit = boost::bind(&Build::onBuildForCheckCompleted,\n Build::shared_from_this(),\n _1,\n rCheckCmd,\n options,\n buildCb);\n\n \/\/ show the user the command\n enqueCommandString(rCmd.commandString());\n\n \/\/ set a success message\n successMessage_ = \"R CMD check succeeded\\n\";\n\n \/\/ run the source build\n module_context::processSupervisor().runCommand(rCmd.shellCommand(),\n options,\n buildCb);\n }\n }\n\n\n void onBuildForCheckCompleted(\n int exitStatus,\n const RCommand& checkCmd,\n const core::system::ProcessOptions& checkOptions,\n const core::system::ProcessCallbacks& checkCb)\n {\n if (exitStatus == EXIT_SUCCESS)\n {\n \/\/ show the user the buld command\n enqueCommandString(checkCmd.commandString());\n\n \/\/ run the check\n module_context::processSupervisor().runCommand(checkCmd.shellCommand(),\n checkOptions,\n checkCb);\n }\n else\n {\n boost::format fmt(\"\\nExited with status %1%.\\n\\n\");\n enqueBuildOutput(boost::str(fmt % exitStatus));\n enqueBuildCompleted();\n }\n }\n\n void executeMakefileBuild(const std::string& type,\n const core::system::ProcessOptions& options,\n const core::system::ProcessCallbacks& cb)\n {\n std::string make = \"make\";\n if (!options_.makefileArgs.empty())\n make += \" \" + options_.makefileArgs;\n\n std::string makeClean = make + \" clean\";\n\n std::string cmd;\n if (type == \"build-all\")\n {\n cmd = make;\n }\n else if (type == \"clean-all\")\n {\n cmd = makeClean;\n }\n else if (type == \"rebuild-all\")\n {\n cmd = shell_utils::join_and(makeClean, make);\n }\n\n module_context::processSupervisor().runCommand(cmd,\n options,\n cb);\n }\n\n void executeCustomBuild(const std::string& type,\n const FilePath& customScriptPath,\n const core::system::ProcessOptions& options,\n const core::system::ProcessCallbacks& cb)\n {\n module_context::processSupervisor().runCommand(\n shell_utils::ShellCommand(customScriptPath),\n options,\n cb);\n }\n\n FilePath projectPath(const std::string& path)\n {\n if (boost::algorithm::starts_with(path, \"~\/\") ||\n FilePath::isRootPath(path))\n {\n return module_context::resolveAliasedPath(path);\n }\n else\n {\n return projects::projectContext().directory().complete(path);\n }\n }\n\n void terminateWithError(const std::string& context,\n const Error& error)\n {\n std::string msg = \"Error \" + context + \": \" + error.summary();\n terminateWithError(msg);\n }\n\n void terminateWithError(const std::string& msg)\n {\n enqueBuildOutput(msg);\n enqueBuildCompleted();\n }\n\npublic:\n virtual ~Build()\n {\n }\n\n bool isRunning() const { return isRunning_; }\n\n const std::string& output() const { return output_; }\n\n void terminate()\n {\n enqueBuildOutput(\"\\n\");\n terminationRequested_ = true;\n }\n\nprivate:\n bool onContinue()\n {\n return !terminationRequested_;\n }\n\n void onOutput(const std::string& output)\n {\n enqueBuildOutput(output);\n }\n\n void onCompleted(int exitStatus)\n {\n if (exitStatus != EXIT_SUCCESS)\n {\n boost::format fmt(\"\\nExited with status %1%.\\n\\n\");\n enqueBuildOutput(boost::str(fmt % exitStatus));\n\n \/\/ never restart R after a failed build\n restartR_ = false;\n }\n else\n {\n if (!successMessage_.empty())\n enqueBuildOutput(successMessage_ + \"\\n\");\n }\n\n enqueBuildCompleted();\n }\n\n void enqueBuildOutput(const std::string& output)\n {\n output_.append(output);\n\n ClientEvent event(client_events::kBuildOutput, output);\n module_context::enqueClientEvent(event);\n }\n\n void enqueCommandString(const std::string& cmd)\n {\n enqueBuildOutput(\"==> \" + cmd + \"\\n\\n\");\n }\n\n void enqueBuildCompleted()\n {\n isRunning_ = false;\n\n \/\/ save the restart context if necessary\n if ((projectConfig().buildType == r_util::kBuildTypePackage) && restartR_)\n {\n FilePath packagePath = projectPath(projectConfig().packagePath);\n saveRestartContext(packagePath, output_);\n }\n\n ClientEvent event(client_events::kBuildCompleted, restartR_);\n module_context::enqueClientEvent(event);\n }\n\n const r_util::RProjectConfig& projectConfig()\n {\n return projects::projectContext().config();\n }\n\n std::string buildPackageSuccessMsg(const std::string& type)\n {\n FilePath writtenPath = projectPath(projectConfig().packagePath).parent();\n std::string written = module_context::createAliasedPath(writtenPath);\n if (written == \"~\")\n written = writtenPath.absolutePath();\n\n return type + \" package written to \" + written;\n }\n\nprivate:\n bool isRunning_;\n bool terminationRequested_;\n std::string output_;\n projects::RProjectBuildOptions options_;\n std::string successMessage_;\n bool restartR_;\n};\n\nboost::shared_ptr s_pBuild;\n\n\nbool isBuildRunning()\n{\n return s_pBuild && s_pBuild->isRunning();\n}\n\nError startBuild(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ get type\n std::string type;\n Error error = json::readParam(request.params, 0, &type);\n if (error)\n return error;\n\n \/\/ if we have a build already running then just return false\n if (isBuildRunning())\n {\n pResponse->setResult(false);\n }\n else\n {\n s_pBuild = Build::create(type);\n pResponse->setResult(true);\n }\n\n return Success();\n}\n\n\n\nError terminateBuild(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n if (isBuildRunning())\n s_pBuild->terminate();\n\n pResponse->setResult(true);\n\n return Success();\n}\n\n} \/\/ anonymous namespace\n\n\njson::Value buildStateAsJson()\n{\n if (s_pBuild)\n {\n json::Object stateJson;\n stateJson[\"running\"] = s_pBuild->isRunning();\n stateJson[\"output\"] = s_pBuild->output();\n return stateJson;\n }\n else\n {\n return json::Value();\n }\n}\n\njson::Value buildRestartContext()\n{\n return collectRestartContext();\n}\n\nError initialize()\n{\n \/\/ install rpc methods\n using boost::bind;\n using namespace module_context;\n ExecBlock initBlock ;\n initBlock.addFunctions()\n (bind(registerRpcMethod, \"start_build\", startBuild))\n (bind(registerRpcMethod, \"terminate_build\", terminateBuild));\n return initBlock.execute();\n}\n\n\n} \/\/ namespace build\n} \/\/ namespace modules\n} \/\/ namesapce session\n\n<|endoftext|>"} {"text":"#include \"third_party\/tensorflow\/core\/framework\/op_kernel.h\"\n#include \"third_party\/tensorflow\/core\/framework\/shape_inference.h\"\n#include \"third_party\/tensorflow\/core\/framework\/tensor.h\"\n#include \"third_party\/tensorflow\/core\/framework\/types.h\"\n\nnamespace tensor2tensor {\nnamespace {\n\nusing ::tensorflow::DEVICE_CPU;\nusing ::tensorflow::OpKernel;\nusing ::tensorflow::OpKernelConstruction;\nusing ::tensorflow::OpKernelContext;\nusing ::tensorflow::Status;\nusing ::tensorflow::Tensor;\nusing ::tensorflow::TensorShape;\nusing ::tensorflow::shape_inference::InferenceContext;\n\n\/\/ TODO(noam): this op packs a dataset of pairs of sequences (inputs, targets)\n\/\/ Generalize later to an arbitrary number of sequences.\nREGISTER_OP(\"PackSequences2\")\n .Input(\"inputs: int64\")\n .Input(\"targets: int64\")\n .Input(\"inputs_max_length: int32\")\n .Input(\"targets_max_length: int32\")\n .Output(\"inputs_packed: int64\")\n .Output(\"inputs_segmentation: int32\")\n .Output(\"inputs_position: int32\")\n .Output(\"targets_packed: int64\")\n .Output(\"targets_segmentation: int32\")\n .Output(\"targets_position: int32\")\n .SetShapeFn([](InferenceContext* ctx) {\n for (int i=0; i < ctx->num_outputs(); i++) {\n ctx->set_output(i, ctx->Matrix(ctx->UnknownDim(),\n ctx->UnknownDim()));\n }\n return Status::OK();\n });\n\nclass PackSequences2Op : public OpKernel {\n public:\n explicit PackSequences2Op(\n OpKernelConstruction* ctx) : OpKernel(ctx) {\n }\n\n void Compute(OpKernelContext* ctx) override {\n auto inputs = ctx->input(0).matrix();\n auto targets = ctx->input(1).matrix();\n int inputs_max_length = ctx->input(2).scalar()();\n int targets_max_length = ctx->input(3).scalar()();\n int n = inputs.dimension(0);\n std::vector inputs_lengths(n);\n std::vector targets_lengths(n);\n int padded_inputs_length =\n std::min(static_cast(inputs.dimension(1)), inputs_max_length);\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < padded_inputs_length; j++) {\n if (inputs(i, j) != 0)\n inputs_lengths[i]++;\n }\n }\n int padded_targets_length =\n std::min(static_cast(targets.dimension(1)), targets_max_length);\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < padded_targets_length; j++) {\n if (targets(i, j) != 0)\n targets_lengths[i]++;\n }\n }\n int num_combined = 0;\n std::vector combined_inputs_length;\n std::vector combined_targets_length;\n std::vector > combined_sequence_ids;\n for (int seq_id = 0; seq_id < n; seq_id++) {\n int inputs_length = inputs_lengths[seq_id];\n int targets_length = targets_lengths[seq_id];\n for (int combined_id = std::max(0, num_combined - 10); true;\n combined_id++) {\n if (combined_id == num_combined) {\n combined_inputs_length.push_back(inputs_length);\n combined_targets_length.push_back(targets_length);\n combined_sequence_ids.push_back(std::vector(1, seq_id));\n num_combined++;\n break;\n } else if (\n (combined_inputs_length[combined_id] + inputs_length\n <= inputs_max_length) &&\n (combined_targets_length[combined_id] + targets_length\n <= targets_max_length)) {\n combined_inputs_length[combined_id] += inputs_length;\n combined_targets_length[combined_id] += targets_length;\n combined_sequence_ids[combined_id].push_back(seq_id);\n break;\n }\n }\n }\n\n auto output_shape_inputs = TensorShape(\n {static_cast(num_combined),\n static_cast(inputs_max_length)});\n auto output_shape_targets = TensorShape(\n {static_cast(num_combined),\n static_cast(targets_max_length)});\n\n Tensor* inputs_packed;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(\n 0, output_shape_inputs, &inputs_packed));\n auto inputs_packed_m = inputs_packed->matrix();\n inputs_packed_m.setZero();\n\n Tensor* inputs_segmentation;\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(\n 1, output_shape_inputs, &inputs_segmentation));\n auto inputs_segmentation_m = inputs_segmentation->matrix();\n inputs_segmentation_m.setZero();\n\n Tensor* inputs_position;\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(2, output_shape_inputs, &inputs_position));\n auto inputs_position_m = inputs_position->matrix();\n inputs_position_m.setZero();\n\n Tensor* targets_packed;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(\n 3, output_shape_targets, &targets_packed));\n auto targets_packed_m = targets_packed->matrix();\n targets_packed_m.setZero();\n\n Tensor* targets_segmentation;\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(\n 4, output_shape_targets, &targets_segmentation));\n auto targets_segmentation_m = targets_segmentation->matrix();\n targets_segmentation_m.setZero();\n\n Tensor* targets_position;\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(5, output_shape_targets, &targets_position));\n auto targets_position_m = targets_position->matrix();\n targets_position_m.setZero();\n\n for (int combined_id = 0; combined_id < num_combined; combined_id++) {\n int inputs_pos = 0;\n int targets_pos = 0;\n for (int i=0; i < combined_sequence_ids[combined_id].size(); i++) {\n int seq_id = combined_sequence_ids[combined_id][i];\n for (int j=0; j < inputs_lengths[seq_id]; j++) {\n inputs_packed_m(combined_id, inputs_pos) = inputs(seq_id, j);\n inputs_segmentation_m(combined_id, inputs_pos) = i + 1;\n inputs_position_m(combined_id, inputs_pos) = j;\n inputs_pos++;\n }\n for (int j=0; j < targets_lengths[seq_id]; j++) {\n targets_packed_m(combined_id, targets_pos) = targets(seq_id, j);\n targets_segmentation_m(combined_id, targets_pos) = i + 1;\n targets_position_m(combined_id, targets_pos) = j;\n targets_pos++;\n }\n }\n }\n }\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"PackSequences2\").Device(DEVICE_CPU),\n PackSequences2Op);\n\n} \/\/ namespace\n} \/\/ namespace tensor2tensor\nincrease window size of partially-built sequences in c++ packing op - results in more efficient packing.#include \"third_party\/tensorflow\/core\/framework\/op_kernel.h\"\n#include \"third_party\/tensorflow\/core\/framework\/shape_inference.h\"\n#include \"third_party\/tensorflow\/core\/framework\/tensor.h\"\n#include \"third_party\/tensorflow\/core\/framework\/types.h\"\n\nnamespace tensor2tensor {\nnamespace {\n\nusing ::tensorflow::DEVICE_CPU;\nusing ::tensorflow::OpKernel;\nusing ::tensorflow::OpKernelConstruction;\nusing ::tensorflow::OpKernelContext;\nusing ::tensorflow::Status;\nusing ::tensorflow::Tensor;\nusing ::tensorflow::TensorShape;\nusing ::tensorflow::shape_inference::InferenceContext;\n\n\/\/ TODO(noam): this op packs a dataset of pairs of sequences (inputs, targets)\n\/\/ Generalize later to an arbitrary number of sequences.\nREGISTER_OP(\"PackSequences2\")\n .Input(\"inputs: int64\")\n .Input(\"targets: int64\")\n .Input(\"inputs_max_length: int32\")\n .Input(\"targets_max_length: int32\")\n .Output(\"inputs_packed: int64\")\n .Output(\"inputs_segmentation: int32\")\n .Output(\"inputs_position: int32\")\n .Output(\"targets_packed: int64\")\n .Output(\"targets_segmentation: int32\")\n .Output(\"targets_position: int32\")\n .SetShapeFn([](InferenceContext* ctx) {\n for (int i=0; i < ctx->num_outputs(); i++) {\n ctx->set_output(i, ctx->Matrix(ctx->UnknownDim(),\n ctx->UnknownDim()));\n }\n return Status::OK();\n });\n\nclass PackSequences2Op : public OpKernel {\n public:\n explicit PackSequences2Op(\n OpKernelConstruction* ctx) : OpKernel(ctx) {\n }\n\n void Compute(OpKernelContext* ctx) override {\n auto inputs = ctx->input(0).matrix();\n auto targets = ctx->input(1).matrix();\n int inputs_max_length = ctx->input(2).scalar()();\n int targets_max_length = ctx->input(3).scalar()();\n int n = inputs.dimension(0);\n std::vector inputs_lengths(n);\n std::vector targets_lengths(n);\n int padded_inputs_length =\n std::min(static_cast(inputs.dimension(1)), inputs_max_length);\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < padded_inputs_length; j++) {\n if (inputs(i, j) != 0)\n inputs_lengths[i]++;\n }\n }\n int padded_targets_length =\n std::min(static_cast(targets.dimension(1)), targets_max_length);\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < padded_targets_length; j++) {\n if (targets(i, j) != 0)\n targets_lengths[i]++;\n }\n }\n int num_combined = 0;\n std::vector combined_inputs_length;\n std::vector combined_targets_length;\n std::vector > combined_sequence_ids;\n for (int seq_id = 0; seq_id < n; seq_id++) {\n int inputs_length = inputs_lengths[seq_id];\n int targets_length = targets_lengths[seq_id];\n for (int combined_id = std::max(0, num_combined - 1000); true;\n combined_id++) {\n if (combined_id == num_combined) {\n combined_inputs_length.push_back(inputs_length);\n combined_targets_length.push_back(targets_length);\n combined_sequence_ids.push_back(std::vector(1, seq_id));\n num_combined++;\n break;\n } else if (\n (combined_inputs_length[combined_id] + inputs_length\n <= inputs_max_length) &&\n (combined_targets_length[combined_id] + targets_length\n <= targets_max_length)) {\n combined_inputs_length[combined_id] += inputs_length;\n combined_targets_length[combined_id] += targets_length;\n combined_sequence_ids[combined_id].push_back(seq_id);\n break;\n }\n }\n }\n\n auto output_shape_inputs = TensorShape(\n {static_cast(num_combined),\n static_cast(inputs_max_length)});\n auto output_shape_targets = TensorShape(\n {static_cast(num_combined),\n static_cast(targets_max_length)});\n\n Tensor* inputs_packed;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(\n 0, output_shape_inputs, &inputs_packed));\n auto inputs_packed_m = inputs_packed->matrix();\n inputs_packed_m.setZero();\n\n Tensor* inputs_segmentation;\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(\n 1, output_shape_inputs, &inputs_segmentation));\n auto inputs_segmentation_m = inputs_segmentation->matrix();\n inputs_segmentation_m.setZero();\n\n Tensor* inputs_position;\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(2, output_shape_inputs, &inputs_position));\n auto inputs_position_m = inputs_position->matrix();\n inputs_position_m.setZero();\n\n Tensor* targets_packed;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(\n 3, output_shape_targets, &targets_packed));\n auto targets_packed_m = targets_packed->matrix();\n targets_packed_m.setZero();\n\n Tensor* targets_segmentation;\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(\n 4, output_shape_targets, &targets_segmentation));\n auto targets_segmentation_m = targets_segmentation->matrix();\n targets_segmentation_m.setZero();\n\n Tensor* targets_position;\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(5, output_shape_targets, &targets_position));\n auto targets_position_m = targets_position->matrix();\n targets_position_m.setZero();\n\n for (int combined_id = 0; combined_id < num_combined; combined_id++) {\n int inputs_pos = 0;\n int targets_pos = 0;\n for (int i=0; i < combined_sequence_ids[combined_id].size(); i++) {\n int seq_id = combined_sequence_ids[combined_id][i];\n for (int j=0; j < inputs_lengths[seq_id]; j++) {\n inputs_packed_m(combined_id, inputs_pos) = inputs(seq_id, j);\n inputs_segmentation_m(combined_id, inputs_pos) = i + 1;\n inputs_position_m(combined_id, inputs_pos) = j;\n inputs_pos++;\n }\n for (int j=0; j < targets_lengths[seq_id]; j++) {\n targets_packed_m(combined_id, targets_pos) = targets(seq_id, j);\n targets_segmentation_m(combined_id, targets_pos) = i + 1;\n targets_position_m(combined_id, targets_pos) = j;\n targets_pos++;\n }\n }\n }\n }\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"PackSequences2\").Device(DEVICE_CPU),\n PackSequences2Op);\n\n} \/\/ namespace\n} \/\/ namespace tensor2tensor\n<|endoftext|>"} {"text":"\n\/**\n * This file is part of the boostcache package.\n *\n * (c) Azat Khuzhin \n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n *\/\n\n#include \"session.h\"\n#include \"util\/log.h\"\n\n#include \n#include \n#include \n\n\nusing namespace boost::spirit::qi;\n\n\nvoid Session::start()\n{\n asyncRead();\n}\n\nvoid Session::asyncRead()\n{\n m_socket.async_read_some(boost::asio::buffer(m_buffer, MAX_BUFFER_LENGTH),\n boost::bind(&Session::handleRead, this,\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n}\n\nvoid Session::asyncWrite(const std::string& message)\n{\n boost::asio::async_write(m_socket,\n boost::asio::buffer(message),\n boost::bind(&Session::handleWrite, this,\n boost::asio::placeholders::error));\n}\n\nvoid Session::handleRead(const boost::system::error_code& error, size_t \/* bytesTransferred *\/)\n{\n if (error) {\n delete this;\n return;\n }\n\n handleReadParseCommand();\n}\n\nvoid Session::handleWrite(const boost::system::error_code& error)\n{\n if (error) {\n delete this;\n return;\n }\n\n asyncRead();\n}\n\n\/**\n * TODO: speedup parsing\n * TODO: more error-friendly parsing\n * TODO: add logging before every reset() call\n *\/\nvoid Session::handleReadParseCommand()\n{\n LOG(debug) << \"Try to read\/parser command \" << m_buffer\n << \"with \" << m_numberOfArguments << \" arguments, \"\n \"for \" << this;\n m_commandString += m_buffer;\n\n std::string line;\n std::istringstream stream(m_commandString);\n stream.seekg(m_commandOffset);\n\n \/\/ Number of arguments\n if (m_numberOfArguments < 0) {\n std::getline(stream, line);\n parse(line.begin(), line.end(),\n '*' >> int_ >> \"\\r\",\n m_numberOfArguments);\n\n if (m_numberOfArguments < 0) {\n LOG(debug) << \"Don't have number of arguments, for \" << this;\n\n reset();\n asyncRead();\n return;\n }\n\n commandArguments.reserve(m_numberOfArguments);\n m_numberOfArgumentsLeft = m_numberOfArguments;\n m_commandOffset = stream.tellg();\n\n LOG(info) << \"Have \" << m_numberOfArguments << \" number of arguments, \"\n << \"for \" << this;\n }\n\n char crLf[2];\n char *argument = NULL;\n int argumentLength = 0;\n while (m_numberOfArgumentsLeft && std::getline(stream, line)) {\n if (!parse(line.begin(), line.end(),\n '$' >> int_ >> \"\\r\",\n m_lastArgumentLength)\n ) {\n LOG(debug) << \"Can't find valid argument length, for \" << this;\n break;\n }\n LOG(debug) << \"Reading \" << m_lastArgumentLength << \" bytes, for \" << this;\n\n if (argumentLength < m_lastArgumentLength) {\n argument = (char *)realloc(argument, argumentLength + 1 \/* NULL byte *\/\n + m_lastArgumentLength);\n argumentLength += m_lastArgumentLength;\n }\n stream.read(argument, m_lastArgumentLength);\n argument[m_lastArgumentLength] = 0;\n if (!stream.good()) {\n \/**\n * TODO: add some internal counters for failover,\n * or smth like this\n *\/\n if (stream.bad()) {\n LOG(debug) << \"Bad stream, for \" << this;\n reset();\n }\n break;\n }\n \/\/ Read CRLF separator\n stream.read(crLf, 2);\n if (!stream.good()) {\n \/**\n * TODO: add some internal counters for failover,\n * or smth like this\n *\/\n if (stream.bad()) {\n LOG(debug) << \"Bad stream, for \" << this;\n reset();\n }\n break;\n }\n if (memcmp(crLf, \"\\r\\n\", 2) != 0) {\n LOG(debug) << \"Malfomed end of argument, for \" << this;\n reset();\n break;\n }\n \/\/ Save command argument\n LOG(debug) << \"Saving \" << argument << \" argument, for \" << this;\n commandArguments.push_back(argument);\n m_lastArgumentLength = -1;\n\n \/\/ Update some counters\/offsets\n --m_numberOfArgumentsLeft;\n m_commandOffset = stream.tellg();\n }\n\n if (!m_numberOfArgumentsLeft) {\n handleCommand();\n \/\/ Will be called asyncRead() in write callback\n } else {\n asyncRead();\n }\n}\n\nvoid Session::handleCommand()\n{\n LOG(info) << \"Handling new command, for \" << this;\n\n writeCommand();\n\n reset();\n}\n\nvoid Session::writeCommand()\n{\n std::string arguments;\n int i;\n for_each(commandArguments.begin(), commandArguments.end(),\n [&arguments, &i] (std::string argument)\n {\n arguments += ++i;\n arguments += \" \";\n arguments += argument;\n arguments += \"\\n\";\n }\n );\n\n asyncWrite(arguments);\n}\n\nvoid Session::reset()\n{\n m_commandString = \"\";\n m_commandOffset = 0;\n m_numberOfArguments = -1;\n m_numberOfArgumentsLeft = -1;\n m_lastArgumentLength = -1;\n\n commandArguments.clear();\n}[net\/session] we must reset internal counters when parsing of argLen fail\n\/**\n * This file is part of the boostcache package.\n *\n * (c) Azat Khuzhin \n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n *\/\n\n#include \"session.h\"\n#include \"util\/log.h\"\n\n#include \n#include \n#include \n\n\nusing namespace boost::spirit::qi;\n\n\nvoid Session::start()\n{\n asyncRead();\n}\n\nvoid Session::asyncRead()\n{\n m_socket.async_read_some(boost::asio::buffer(m_buffer, MAX_BUFFER_LENGTH),\n boost::bind(&Session::handleRead, this,\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n}\n\nvoid Session::asyncWrite(const std::string& message)\n{\n boost::asio::async_write(m_socket,\n boost::asio::buffer(message),\n boost::bind(&Session::handleWrite, this,\n boost::asio::placeholders::error));\n}\n\nvoid Session::handleRead(const boost::system::error_code& error, size_t \/* bytesTransferred *\/)\n{\n if (error) {\n delete this;\n return;\n }\n\n handleReadParseCommand();\n}\n\nvoid Session::handleWrite(const boost::system::error_code& error)\n{\n if (error) {\n delete this;\n return;\n }\n\n asyncRead();\n}\n\n\/**\n * TODO: speedup parsing\n * TODO: more error-friendly parsing\n * TODO: add logging before every reset() call\n *\/\nvoid Session::handleReadParseCommand()\n{\n LOG(debug) << \"Try to read\/parser command \" << m_buffer\n << \"with \" << m_numberOfArguments << \" arguments, \"\n \"for \" << this;\n m_commandString += m_buffer;\n\n std::string line;\n std::istringstream stream(m_commandString);\n stream.seekg(m_commandOffset);\n\n \/\/ Number of arguments\n if (m_numberOfArguments < 0) {\n std::getline(stream, line);\n parse(line.begin(), line.end(),\n '*' >> int_ >> \"\\r\",\n m_numberOfArguments);\n\n if (m_numberOfArguments < 0) {\n LOG(debug) << \"Don't have number of arguments, for \" << this;\n\n reset();\n asyncRead();\n return;\n }\n\n commandArguments.reserve(m_numberOfArguments);\n m_numberOfArgumentsLeft = m_numberOfArguments;\n m_commandOffset = stream.tellg();\n\n LOG(info) << \"Have \" << m_numberOfArguments << \" number of arguments, \"\n << \"for \" << this;\n }\n\n char crLf[2];\n char *argument = NULL;\n int argumentLength = 0;\n while (m_numberOfArgumentsLeft && std::getline(stream, line)) {\n if (!parse(line.begin(), line.end(),\n '$' >> int_ >> \"\\r\",\n m_lastArgumentLength)\n ) {\n LOG(debug) << \"Can't find valid argument length, for \" << this;\n reset();\n break;\n }\n LOG(debug) << \"Reading \" << m_lastArgumentLength << \" bytes, for \" << this;\n\n if (argumentLength < m_lastArgumentLength) {\n argument = (char *)realloc(argument, argumentLength + 1 \/* NULL byte *\/\n + m_lastArgumentLength);\n argumentLength += m_lastArgumentLength;\n }\n stream.read(argument, m_lastArgumentLength);\n argument[m_lastArgumentLength] = 0;\n if (!stream.good()) {\n \/**\n * TODO: add some internal counters for failover,\n * or smth like this\n *\/\n if (stream.bad()) {\n LOG(debug) << \"Bad stream, for \" << this;\n reset();\n }\n break;\n }\n \/\/ Read CRLF separator\n stream.read(crLf, 2);\n if (!stream.good()) {\n \/**\n * TODO: add some internal counters for failover,\n * or smth like this\n *\/\n if (stream.bad()) {\n LOG(debug) << \"Bad stream, for \" << this;\n reset();\n }\n break;\n }\n if (memcmp(crLf, \"\\r\\n\", 2) != 0) {\n LOG(debug) << \"Malfomed end of argument, for \" << this;\n reset();\n break;\n }\n \/\/ Save command argument\n LOG(debug) << \"Saving \" << argument << \" argument, for \" << this;\n commandArguments.push_back(argument);\n m_lastArgumentLength = -1;\n\n \/\/ Update some counters\/offsets\n --m_numberOfArgumentsLeft;\n m_commandOffset = stream.tellg();\n }\n\n if (!m_numberOfArgumentsLeft) {\n handleCommand();\n \/\/ Will be called asyncRead() in write callback\n } else {\n asyncRead();\n }\n}\n\nvoid Session::handleCommand()\n{\n LOG(info) << \"Handling new command, for \" << this;\n\n writeCommand();\n\n reset();\n}\n\nvoid Session::writeCommand()\n{\n std::string arguments;\n int i;\n for_each(commandArguments.begin(), commandArguments.end(),\n [&arguments, &i] (std::string argument)\n {\n arguments += ++i;\n arguments += \" \";\n arguments += argument;\n arguments += \"\\n\";\n }\n );\n\n asyncWrite(arguments);\n}\n\nvoid Session::reset()\n{\n m_commandString = \"\";\n m_commandOffset = 0;\n m_numberOfArguments = -1;\n m_numberOfArgumentsLeft = -1;\n m_lastArgumentLength = -1;\n\n commandArguments.clear();\n}<|endoftext|>"} {"text":"#ifdef DARWIN\n#include \n#endif \/\/ DARWIN\n\n#ifdef LINUX\n#include \n#include \n#include \n#endif \/\/ LINUX\n\n#if defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))\n#include \n#include \n#include \n#if defined(BSD)\n#include \n#endif\n#endif\n\n#include \n\n#include \n#include \n\nnamespace cxxu {\nnamespace system {\n\ninfo::info()\n{\n load();\n}\n\ninfo::~info()\n{}\n\nuint32_t\ninfo::logical_cpus() const\n{ return logical_cpus_; }\n\nuint64_t\ninfo::physical_memory() const\n{ return physical_memory_; }\n\nvoid\ninfo::load()\n{\n cpu_info();\n mem_info();\n}\n\nvoid\ninfo::cpu_info()\n{\n logical_cpus_ = 1;\n bool ok = true;\n\n#ifdef DARWIN\n std::size_t length = sizeof(logical_cpus_);\n\n if (sysctlbyname(\"hw.logicalcpu_max\", &logical_cpus_, &length, NULL, 0) != 0) {\n ok = false;\n }\n#endif \/\/ DARWIN\n\n#ifdef LINUX\n long nprocs = sysconf(_SC_NPROCESSORS_ONLN);\n\n if (nprocs == -1) {\n ok = false;\n }\n\n logical_cpus_ = static_cast(nprocs);\n#endif \/\/ LINUX\n\n if (!ok) {\n CXXU_DIE(\"failed to get logical cpu count\");\n }\n}\n\nvoid \ninfo::mem_info()\n{\n physical_memory_ = 0;\n\n#if defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))\n \/* UNIX variants. ------------------------------------------- *\/\n \/* Prefer sysctl() over sysconf() except sysctl() HW_REALMEM and HW_PHYSMEM *\/\n\n#if defined(CTL_HW) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM64))\n int mib[2];\n mib[0] = CTL_HW;\n #if defined(HW_MEMSIZE)\n mib[1] = HW_MEMSIZE; \/* OSX. --------------------- *\/\n #elif defined(HW_PHYSMEM64)\n mib[1] = HW_PHYSMEM64; \/* NetBSD, OpenBSD. --------- *\/\n #endif\n int64_t size = 0; \/* 64-bit *\/\n size_t len = sizeof( size );\n if ( sysctl( mib, 2, &size, &len, NULL, 0 ) == 0 ) {\n physical_memory_ (uint64_t)size;\n }\n\n#elif defined(_SC_AIX_REALMEM)\n \/* AIX. ----------------------------------------------------- *\/\n physical_memory_ = (uint64_t)sysconf( _SC_AIX_REALMEM ) * (uint64_t)1024L;\n\n#elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE)\n \/* FreeBSD, Linux, OpenBSD, and Solaris. -------------------- *\/\n physical_memory_ = (uint64_t)sysconf( _SC_PHYS_PAGES ) * (uint64_t)sysconf( _SC_PAGESIZE );\n\n#elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGE_SIZE)\n \/* Legacy. -------------------------------------------------- *\/\n physical_memory_ = (uint64_t)sysconf( _SC_PHYS_PAGES ) * (size_t)sysconf( _SC_PAGE_SIZE );\n\n#elif defined(CTL_HW) && (defined(HW_PHYSMEM) || defined(HW_REALMEM))\n \/* DragonFly BSD, FreeBSD, NetBSD, OpenBSD, and OSX. -------- *\/\n int mib[2];\n mib[0] = CTL_HW;\n#if defined(HW_REALMEM)\n mib[1] = HW_REALMEM; \/* FreeBSD. ----------------- *\/\n#elif defined(HW_PYSMEM)\n mib[1] = HW_PHYSMEM; \/* Others. ------------------ *\/\n#endif\n unsigned int size = 0; \/* 32-bit *\/\n size_t len = sizeof( size );\n if ( sysctl( mib, 2, &size, &len, NULL, 0 ) == 0 ) {\n physical_memory_ = (uint64_t)size;\n }\n \n#endif \/* sysctl and sysconf variants *\/\n#endif\n if (physical_memory_ == 0) {\n CXXU_DIE(\"failed to get physical memory size\");\n }\n}\n\n} \/\/ namespace system\n} \/\/ namespace cxxu\nadded missing include#ifdef DARWIN\n#include \n#endif \/\/ DARWIN\n\n#ifdef LINUX\n#include \n#include \n#include \n#endif \/\/ LINUX\n\n#if defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))\n#include \n#include \n#include \n#if defined(BSD)\n#include \n#endif\n#endif\n\n#include \n\n#include \n#include \n\nnamespace cxxu {\nnamespace system {\n\ninfo::info()\n{\n load();\n}\n\ninfo::~info()\n{}\n\nuint32_t\ninfo::logical_cpus() const\n{ return logical_cpus_; }\n\nuint64_t\ninfo::physical_memory() const\n{ return physical_memory_; }\n\nvoid\ninfo::load()\n{\n cpu_info();\n mem_info();\n}\n\nvoid\ninfo::cpu_info()\n{\n logical_cpus_ = 1;\n bool ok = true;\n\n#ifdef DARWIN\n std::size_t length = sizeof(logical_cpus_);\n\n if (sysctlbyname(\"hw.logicalcpu_max\", &logical_cpus_, &length, NULL, 0) != 0) {\n ok = false;\n }\n#endif \/\/ DARWIN\n\n#ifdef LINUX\n long nprocs = sysconf(_SC_NPROCESSORS_ONLN);\n\n if (nprocs == -1) {\n ok = false;\n }\n\n logical_cpus_ = static_cast(nprocs);\n#endif \/\/ LINUX\n\n if (!ok) {\n CXXU_DIE(\"failed to get logical cpu count\");\n }\n}\n\nvoid \ninfo::mem_info()\n{\n physical_memory_ = 0;\n\n#if defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))\n \/* UNIX variants. ------------------------------------------- *\/\n \/* Prefer sysctl() over sysconf() except sysctl() HW_REALMEM and HW_PHYSMEM *\/\n\n#if defined(CTL_HW) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM64))\n int mib[2];\n mib[0] = CTL_HW;\n #if defined(HW_MEMSIZE)\n mib[1] = HW_MEMSIZE; \/* OSX. --------------------- *\/\n #elif defined(HW_PHYSMEM64)\n mib[1] = HW_PHYSMEM64; \/* NetBSD, OpenBSD. --------- *\/\n #endif\n int64_t size = 0; \/* 64-bit *\/\n size_t len = sizeof( size );\n if ( sysctl( mib, 2, &size, &len, NULL, 0 ) == 0 ) {\n physical_memory_ = (uint64_t)size;\n }\n\n#elif defined(_SC_AIX_REALMEM)\n \/* AIX. ----------------------------------------------------- *\/\n physical_memory_ = (uint64_t)sysconf( _SC_AIX_REALMEM ) * (uint64_t)1024L;\n\n#elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE)\n \/* FreeBSD, Linux, OpenBSD, and Solaris. -------------------- *\/\n physical_memory_ = (uint64_t)sysconf( _SC_PHYS_PAGES ) * (uint64_t)sysconf( _SC_PAGESIZE );\n\n#elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGE_SIZE)\n \/* Legacy. -------------------------------------------------- *\/\n physical_memory_ = (uint64_t)sysconf( _SC_PHYS_PAGES ) * (size_t)sysconf( _SC_PAGE_SIZE );\n\n#elif defined(CTL_HW) && (defined(HW_PHYSMEM) || defined(HW_REALMEM))\n \/* DragonFly BSD, FreeBSD, NetBSD, OpenBSD, and OSX. -------- *\/\n int mib[2];\n mib[0] = CTL_HW;\n#if defined(HW_REALMEM)\n mib[1] = HW_REALMEM; \/* FreeBSD. ----------------- *\/\n#elif defined(HW_PYSMEM)\n mib[1] = HW_PHYSMEM; \/* Others. ------------------ *\/\n#endif\n unsigned int size = 0; \/* 32-bit *\/\n size_t len = sizeof( size );\n if ( sysctl( mib, 2, &size, &len, NULL, 0 ) == 0 ) {\n physical_memory_ = (uint64_t)size;\n }\n \n#endif \/* sysctl and sysconf variants *\/\n#endif\n if (physical_memory_ == 0) {\n CXXU_DIE(\"failed to get physical memory size\");\n }\n}\n\n} \/\/ namespace system\n} \/\/ namespace cxxu\n<|endoftext|>"} {"text":"\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/utils\/error_util.h\"\n\n#include \"tensorflow\/core\/lib\/core\/errors.h\"\n\nnamespace mlir {\n\nStatusScopedDiagnosticHandler::StatusScopedDiagnosticHandler(\n MLIRContext* context, bool propagate)\n : SourceMgrDiagnosticHandler(source_mgr_, context, diag_stream_),\n diag_stream_(diag_str_),\n propagate_(propagate) {\n setHandler([this](Diagnostic& diag) { return this->handler(&diag); });\n}\n\nStatusScopedDiagnosticHandler::~StatusScopedDiagnosticHandler() {\n \/\/ Verify errors were consumed and re-register old handler.\n bool all_errors_produced_were_consumed = ok();\n DCHECK(all_errors_produced_were_consumed) << \"Error status not consumed:\\n\"\n << diag_str_;\n}\n\nbool StatusScopedDiagnosticHandler::ok() const { return diag_str_.empty(); }\n\nStatus StatusScopedDiagnosticHandler::ConsumeStatus() {\n if (ok()) return Status::OK();\n\n \/\/ TODO(jpienaar) This should be combining status with one previously built\n \/\/ up.\n Status s = tensorflow::errors::Unknown(diag_str_);\n diag_str_.clear();\n return s;\n}\n\nStatus StatusScopedDiagnosticHandler::Combine(Status status) {\n if (status.ok()) return ConsumeStatus();\n\n \/\/ status is not-OK here, so if there was no diagnostics reported\n \/\/ additionally then return this error.\n if (ok()) return status;\n\n \/\/ Append the diagnostics reported to the status. This repeats the behavior of\n \/\/ TensorFlow's AppendToMessage without the additional formatting inserted\n \/\/ there.\n status = ::tensorflow::Status(\n status.code(), absl::StrCat(status.error_message(), diag_str_));\n diag_str_.clear();\n return status;\n}\n\nLogicalResult StatusScopedDiagnosticHandler::handler(Diagnostic* diag) {\n#ifndef NDEBUG\n size_t current_diag_str_size_ = diag_str_.size();\n#endif\n\n \/\/ Emit the diagnostic and flush the stream.\n emitDiagnostic(*diag);\n diag_stream_.flush();\n\n#ifndef NDEBUG\n \/\/ Emit non-errors to VLOG instead of the internal status.\n if (diag->getSeverity() != DiagnosticSeverity::Error) {\n VLOG(1) << diag_str_.substr(current_diag_str_size_);\n diag_str_.resize(current_diag_str_size_);\n }\n#endif\n\n \/\/ Return failure to signal propagation if necessary.\n return failure(propagate_);\n}\n\n} \/\/ namespace mlir\nDo not issue an error to TensorFlow when MLIR issues a warning\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/utils\/error_util.h\"\n\n#include \"tensorflow\/core\/lib\/core\/errors.h\"\n\nnamespace mlir {\n\nStatusScopedDiagnosticHandler::StatusScopedDiagnosticHandler(\n MLIRContext* context, bool propagate)\n : SourceMgrDiagnosticHandler(source_mgr_, context, diag_stream_),\n diag_stream_(diag_str_),\n propagate_(propagate) {\n setHandler([this](Diagnostic& diag) { return this->handler(&diag); });\n}\n\nStatusScopedDiagnosticHandler::~StatusScopedDiagnosticHandler() {\n \/\/ Verify errors were consumed and re-register old handler.\n bool all_errors_produced_were_consumed = ok();\n DCHECK(all_errors_produced_were_consumed) << \"Error status not consumed:\\n\"\n << diag_str_;\n}\n\nbool StatusScopedDiagnosticHandler::ok() const { return diag_str_.empty(); }\n\nStatus StatusScopedDiagnosticHandler::ConsumeStatus() {\n if (ok()) return Status::OK();\n\n \/\/ TODO(jpienaar) This should be combining status with one previously built\n \/\/ up.\n Status s = tensorflow::errors::Unknown(diag_str_);\n diag_str_.clear();\n return s;\n}\n\nStatus StatusScopedDiagnosticHandler::Combine(Status status) {\n if (status.ok()) return ConsumeStatus();\n\n \/\/ status is not-OK here, so if there was no diagnostics reported\n \/\/ additionally then return this error.\n if (ok()) return status;\n\n \/\/ Append the diagnostics reported to the status. This repeats the behavior of\n \/\/ TensorFlow's AppendToMessage without the additional formatting inserted\n \/\/ there.\n status = ::tensorflow::Status(\n status.code(), absl::StrCat(status.error_message(), diag_str_));\n diag_str_.clear();\n return status;\n}\n\nLogicalResult StatusScopedDiagnosticHandler::handler(Diagnostic* diag) {\n \/\/ Non-error diagnostic are ignored when VLOG isn't enabled.\n if (diag->getSeverity() != DiagnosticSeverity::Error && VLOG_IS_ON(1))\n return success();\n\n size_t current_diag_str_size_ = diag_str_.size();\n\n \/\/ Emit the diagnostic and flush the stream.\n emitDiagnostic(*diag);\n diag_stream_.flush();\n\n \/\/ Emit non-errors to VLOG instead of the internal status.\n if (diag->getSeverity() != DiagnosticSeverity::Error) {\n VLOG(1) << diag_str_.substr(current_diag_str_size_);\n diag_str_.resize(current_diag_str_size_);\n }\n\n \/\/ Return failure to signal propagation if necessary.\n return failure(propagate_);\n}\n\n} \/\/ namespace mlir\n<|endoftext|>"} {"text":"#include \"CHPFCRFFSplitVariablesAction.h\"\n#include \"Factory.h\"\n#include \"Parser.h\"\n#include \"FEProblem.h\"\n\n#include \n#include \n\n\/\/ libMesh includes\n#include \"libmesh\/string_to_enum.h\"\n\nconst Real CHPFCRFFSplitVariablesAction::_abs_zero_tol = 1e-12;\n\ntemplate<>\nInputParameters validParams()\n{\n InputParameters params = validParams();\n params.addParam(\"family\", \"LAGRANGE\", \"Specifies the family of FE shape functions to use for the L variables\");\n params.addParam(\"order\", \"FIRST\", \"Specifies the order of the FE shape function to use for the L variables\");\n params.addParam(\"scaling\", 1.0, \"Specifies a scaling factor to apply to the L variables\");\n params.addRequiredParam(\"num_L\", \"specifies the number of complex L variables will be solved for\");\n params.addRequiredParam(\"L_name_base\", \"Base name for the complex L variables\");\n params.addRequiredParam >(\"sub_filenames\", \"This is the filename of the sub.i file\");\n params.addRequiredParam(\"n_name\", \"Name of atomic density variable\");\n\n return params;\n}\n\nCHPFCRFFSplitVariablesAction::CHPFCRFFSplitVariablesAction(const std::string & name,\n InputParameters params) :\n Action(name, params),\n _num_L(getParam(\"num_L\")),\n _L_name_base(getParam(\"L_name_base\")),\n _sub_filenames(getParam >(\"sub_filenames\")),\n _n_name(getParam(\"n_name\"))\n{\n}\n\nvoid\nCHPFCRFFSplitVariablesAction::act()\n{\n std::vector execute_options = SetupInterface::getExecuteOptions();\n execute_options[0] = \"timestep_begin\";\n\n \/\/ Setup MultiApp\n InputParameters poly_params = _factory.getValidParams(\"TransientMultiApp\");\n poly_params.set(\"app_type\") = \"MarmotApp\";\n poly_params.set >(\"execute_on\") = execute_options;\n poly_params.set >(\"input_files\") = _sub_filenames;\n poly_params.set(\"max_procs_per_app\") = 1;\n\n Point one(0.0, 0.0, 0.0);\n\n std::vector positions;\n positions.push_back(one);\n\n poly_params.set >(\"positions\") = positions;\n\n _problem->addMultiApp(\"TransientMultiApp\", \"HHEquationSolver\", poly_params);\n\n poly_params = _factory.getValidParams(\"MultiAppNearestNodeTransfer\");\n poly_params.set(\"direction\") = \"to_multiapp\";\n poly_params.set >(\"execute_on\") = execute_options;\n poly_params.set(\"variable\") = _n_name;\n poly_params.set(\"source_variable\") = _n_name;\n poly_params.set(\"multi_app\") = \"HHEquationSolver\";\n\n\n \/\/ Create Name for Transfer\n std::string trans_name = _n_name;\n trans_name.append(\"_trans\");\n\n _problem->addTransfer(\"MultiAppNearestNodeTransfer\", trans_name, poly_params);\n\n\n\n#ifdef DEBUG\n Moose::err << \"Inside the CHPFCRFFSplitVariablesAction Object\\n\";\n Moose::err << \"VariableBase: \" << _L_name_base\n << \"\\torder: \" << getParam(\"order\")\n << \"\\tfamily: \" << getParam(\"family\") << std::endl;\n#endif\n\n \/\/ Loop through the number of L variables\n for (unsigned int l = 0; l < _num_L; ++l)\n {\n \/\/ Create L base name\n std::string L_name = _L_name_base;\n std::stringstream out;\n out << l;\n L_name.append(out.str());\n\n \/\/ Create real L variable\n std::string real_name = L_name;\n real_name.append(\"_real\");\n\n\n#ifdef DEBUG\n Moose::err << \"Real name = \" << real_name << std::endl;\n#endif\n\n _problem->addAuxVariable(real_name,\n FEType(Utility::string_to_enum(getParam(\"order\")),\n Utility::string_to_enum(getParam(\"family\"))));\n\n poly_params = _factory.getValidParams(\"MultiAppNearestNodeTransfer\");\n poly_params.set(\"direction\") = \"from_multiapp\";\n poly_params.set(\"variable\") = real_name;\n poly_params.set(\"source_variable\") = real_name;\n poly_params.set(\"multi_app\") = \"HHEquationSolver\";\n\n\n \/\/ Create Name for Transfer\n std::string trans_name = real_name;\n trans_name.append(\"_trans\");\n\n _problem->addTransfer(\"MultiAppNearestNodeTransfer\", trans_name, poly_params);\n\n if (l > 0)\n {\n \/\/ Create imaginary L variable IF l > 0\n std::string imag_name = L_name;\n imag_name.append(\"_imag\");\n\n#ifdef DEBUG\n Moose::err << \"Imaginary name = \" << imag_name << std::endl;\n#endif\n\n _problem->addAuxVariable(imag_name,\n FEType(Utility::string_to_enum(getParam(\"order\")),\n Utility::string_to_enum(getParam(\"family\"))));\n\n poly_params = _factory.getValidParams(\"MultiAppNearestNodeTransfer\");\n poly_params.set(\"direction\") = \"from_multiapp\";\n poly_params.set(\"variable\") = imag_name;\n poly_params.set(\"source_variable\") = imag_name;\n poly_params.set(\"multi_app\") = \"HHEquationSolver\";\n\n \/\/ Create Name for Transfer\n std::string trans_name = imag_name;\n trans_name.append(\"_trans\");\n\n _problem->addTransfer(\"MultiAppNearestNodeTransfer\", trans_name, poly_params);\n }\n\n }\n\n}\nConvert \"execute_on\" parameter to MultiMooseEnum closes #53#include \"CHPFCRFFSplitVariablesAction.h\"\n#include \"Factory.h\"\n#include \"Parser.h\"\n#include \"FEProblem.h\"\n\n#include \n#include \n\n\/\/ libMesh includes\n#include \"libmesh\/string_to_enum.h\"\n\nconst Real CHPFCRFFSplitVariablesAction::_abs_zero_tol = 1e-12;\n\ntemplate<>\nInputParameters validParams()\n{\n InputParameters params = validParams();\n params.addParam(\"family\", \"LAGRANGE\", \"Specifies the family of FE shape functions to use for the L variables\");\n params.addParam(\"order\", \"FIRST\", \"Specifies the order of the FE shape function to use for the L variables\");\n params.addParam(\"scaling\", 1.0, \"Specifies a scaling factor to apply to the L variables\");\n params.addRequiredParam(\"num_L\", \"specifies the number of complex L variables will be solved for\");\n params.addRequiredParam(\"L_name_base\", \"Base name for the complex L variables\");\n params.addRequiredParam >(\"sub_filenames\", \"This is the filename of the sub.i file\");\n params.addRequiredParam(\"n_name\", \"Name of atomic density variable\");\n\n return params;\n}\n\nCHPFCRFFSplitVariablesAction::CHPFCRFFSplitVariablesAction(const std::string & name,\n InputParameters params) :\n Action(name, params),\n _num_L(getParam(\"num_L\")),\n _L_name_base(getParam(\"L_name_base\")),\n _sub_filenames(getParam >(\"sub_filenames\")),\n _n_name(getParam(\"n_name\"))\n{\n}\n\nvoid\nCHPFCRFFSplitVariablesAction::act()\n{\n MultiMooseEnum execute_options(SetupInterface::getExecuteOptions());\n execute_options = \"timestep_begin\";\n\n \/\/ Setup MultiApp\n InputParameters poly_params = _factory.getValidParams(\"TransientMultiApp\");\n poly_params.set(\"app_type\") = \"MarmotApp\";\n poly_params.set(\"execute_on\") = execute_options;\n poly_params.set >(\"input_files\") = _sub_filenames;\n poly_params.set(\"max_procs_per_app\") = 1;\n\n Point one(0.0, 0.0, 0.0);\n\n std::vector positions;\n positions.push_back(one);\n\n poly_params.set >(\"positions\") = positions;\n\n _problem->addMultiApp(\"TransientMultiApp\", \"HHEquationSolver\", poly_params);\n\n poly_params = _factory.getValidParams(\"MultiAppNearestNodeTransfer\");\n poly_params.set(\"direction\") = \"to_multiapp\";\n poly_params.set(\"execute_on\") = execute_options;\n poly_params.set(\"variable\") = _n_name;\n poly_params.set(\"source_variable\") = _n_name;\n poly_params.set(\"multi_app\") = \"HHEquationSolver\";\n\n\n \/\/ Create Name for Transfer\n std::string trans_name = _n_name;\n trans_name.append(\"_trans\");\n\n _problem->addTransfer(\"MultiAppNearestNodeTransfer\", trans_name, poly_params);\n\n\n\n#ifdef DEBUG\n Moose::err << \"Inside the CHPFCRFFSplitVariablesAction Object\\n\";\n Moose::err << \"VariableBase: \" << _L_name_base\n << \"\\torder: \" << getParam(\"order\")\n << \"\\tfamily: \" << getParam(\"family\") << std::endl;\n#endif\n\n \/\/ Loop through the number of L variables\n for (unsigned int l = 0; l < _num_L; ++l)\n {\n \/\/ Create L base name\n std::string L_name = _L_name_base;\n std::stringstream out;\n out << l;\n L_name.append(out.str());\n\n \/\/ Create real L variable\n std::string real_name = L_name;\n real_name.append(\"_real\");\n\n\n#ifdef DEBUG\n Moose::err << \"Real name = \" << real_name << std::endl;\n#endif\n\n _problem->addAuxVariable(real_name,\n FEType(Utility::string_to_enum(getParam(\"order\")),\n Utility::string_to_enum(getParam(\"family\"))));\n\n poly_params = _factory.getValidParams(\"MultiAppNearestNodeTransfer\");\n poly_params.set(\"direction\") = \"from_multiapp\";\n poly_params.set(\"variable\") = real_name;\n poly_params.set(\"source_variable\") = real_name;\n poly_params.set(\"multi_app\") = \"HHEquationSolver\";\n\n\n \/\/ Create Name for Transfer\n std::string trans_name = real_name;\n trans_name.append(\"_trans\");\n\n _problem->addTransfer(\"MultiAppNearestNodeTransfer\", trans_name, poly_params);\n\n if (l > 0)\n {\n \/\/ Create imaginary L variable IF l > 0\n std::string imag_name = L_name;\n imag_name.append(\"_imag\");\n\n#ifdef DEBUG\n Moose::err << \"Imaginary name = \" << imag_name << std::endl;\n#endif\n\n _problem->addAuxVariable(imag_name,\n FEType(Utility::string_to_enum(getParam(\"order\")),\n Utility::string_to_enum(getParam(\"family\"))));\n\n poly_params = _factory.getValidParams(\"MultiAppNearestNodeTransfer\");\n poly_params.set(\"direction\") = \"from_multiapp\";\n poly_params.set(\"variable\") = imag_name;\n poly_params.set(\"source_variable\") = imag_name;\n poly_params.set(\"multi_app\") = \"HHEquationSolver\";\n\n \/\/ Create Name for Transfer\n std::string trans_name = imag_name;\n trans_name.append(\"_trans\");\n\n _problem->addTransfer(\"MultiAppNearestNodeTransfer\", trans_name, poly_params);\n }\n\n }\n\n}\n<|endoftext|>"} {"text":"\/*\n* DSA\n* (C) 1999-2010,2014 Jack Lloyd\n*\n* Distributed under the terms of the Botan license\n*\/\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace Botan {\n\n\/*\n* DSA_PublicKey Constructor\n*\/\nDSA_PublicKey::DSA_PublicKey(const DL_Group& grp, const BigInt& y1)\n {\n group = grp;\n y = y1;\n }\n\n\/*\n* Create a DSA private key\n*\/\nDSA_PrivateKey::DSA_PrivateKey(RandomNumberGenerator& rng,\n const DL_Group& grp,\n const BigInt& x_arg)\n {\n group = grp;\n x = x_arg;\n\n if(x == 0)\n x = BigInt::random_integer(rng, 2, group_q() - 1);\n\n y = power_mod(group_g(), x, group_p());\n\n if(x_arg == 0)\n gen_check(rng);\n else\n load_check(rng);\n }\n\nDSA_PrivateKey::DSA_PrivateKey(const AlgorithmIdentifier& alg_id,\n const secure_vector& key_bits,\n RandomNumberGenerator& rng) :\n DL_Scheme_PrivateKey(alg_id, key_bits, DL_Group::ANSI_X9_57)\n {\n y = power_mod(group_g(), x, group_p());\n\n load_check(rng);\n }\n\n\/*\n* Check Private DSA Parameters\n*\/\nbool DSA_PrivateKey::check_key(RandomNumberGenerator& rng, bool strong) const\n {\n if(!DL_Scheme_PrivateKey::check_key(rng, strong) || x >= group_q())\n return false;\n\n if(!strong)\n return true;\n\n return KeyPair::signature_consistency_check(rng, *this, \"EMSA1(SHA-1)\");\n }\n\nDSA_Signature_Operation::DSA_Signature_Operation(const DSA_PrivateKey& dsa,\n const std::string& emsa) :\n q(dsa.group_q()),\n x(dsa.get_x()),\n powermod_g_p(dsa.group_g(), dsa.group_p()),\n mod_q(dsa.group_q()),\n m_hash(hash_for_deterministic_signature(emsa))\n {\n }\n\nsecure_vector\nDSA_Signature_Operation::sign(const byte msg[], size_t msg_len,\n RandomNumberGenerator& rng)\n {\n rng.add_entropy(msg, msg_len);\n\n BigInt i(msg, msg_len);\n\n if(i >= q)\n i -= q;\n\n const BigInt k = generate_rfc6979_nonce(x, q, i, m_hash);\n\n auto future_r = std::async(std::launch::async,\n [&]() { return mod_q.reduce(powermod_g_p(k)); });\n\n BigInt s = inverse_mod(k, q);\n const BigInt r = future_r.get();\n s = mod_q.multiply(s, mul_add(x, r, i));\n\n \/\/ With overwhelming probability, a bug rather than actual zero r\/s\n BOTAN_ASSERT(s != 0, \"invalid s\");\n BOTAN_ASSERT(r != 0, \"invalid r\");\n\n secure_vector output(2*q.bytes());\n r.binary_encode(&output[output.size() \/ 2 - r.bytes()]);\n s.binary_encode(&output[output.size() - s.bytes()]);\n return output;\n }\n\nDSA_Verification_Operation::DSA_Verification_Operation(const DSA_PublicKey& dsa) :\n q(dsa.group_q()), y(dsa.get_y())\n {\n powermod_g_p = Fixed_Base_Power_Mod(dsa.group_g(), dsa.group_p());\n powermod_y_p = Fixed_Base_Power_Mod(y, dsa.group_p());\n mod_p = Modular_Reducer(dsa.group_p());\n mod_q = Modular_Reducer(dsa.group_q());\n }\n\nbool DSA_Verification_Operation::verify(const byte msg[], size_t msg_len,\n const byte sig[], size_t sig_len)\n {\n if(sig_len != 2*q.bytes() || msg_len > q.bytes())\n return false;\n\n BigInt r(sig, q.bytes());\n BigInt s(sig + q.bytes(), q.bytes());\n BigInt i(msg, msg_len);\n\n if(r <= 0 || r >= q || s <= 0 || s >= q)\n return false;\n\n s = inverse_mod(s, q);\n\n auto future_s_i = std::async(std::launch::async,\n [&]() { return powermod_g_p(mod_q.multiply(s, i)); });\n\n BigInt s_r = powermod_y_p(mod_q.multiply(s, r));\n BigInt s_i = future_s_i.get();\n\n s = mod_p.multiply(s_i, s_r);\n\n return (mod_q.reduce(s) == r);\n }\n\n}\nNo need to reseed RNG in DSA sign as RNG is no longer used\/*\n* DSA\n* (C) 1999-2010,2014 Jack Lloyd\n*\n* Distributed under the terms of the Botan license\n*\/\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace Botan {\n\n\/*\n* DSA_PublicKey Constructor\n*\/\nDSA_PublicKey::DSA_PublicKey(const DL_Group& grp, const BigInt& y1)\n {\n group = grp;\n y = y1;\n }\n\n\/*\n* Create a DSA private key\n*\/\nDSA_PrivateKey::DSA_PrivateKey(RandomNumberGenerator& rng,\n const DL_Group& grp,\n const BigInt& x_arg)\n {\n group = grp;\n x = x_arg;\n\n if(x == 0)\n x = BigInt::random_integer(rng, 2, group_q() - 1);\n\n y = power_mod(group_g(), x, group_p());\n\n if(x_arg == 0)\n gen_check(rng);\n else\n load_check(rng);\n }\n\nDSA_PrivateKey::DSA_PrivateKey(const AlgorithmIdentifier& alg_id,\n const secure_vector& key_bits,\n RandomNumberGenerator& rng) :\n DL_Scheme_PrivateKey(alg_id, key_bits, DL_Group::ANSI_X9_57)\n {\n y = power_mod(group_g(), x, group_p());\n\n load_check(rng);\n }\n\n\/*\n* Check Private DSA Parameters\n*\/\nbool DSA_PrivateKey::check_key(RandomNumberGenerator& rng, bool strong) const\n {\n if(!DL_Scheme_PrivateKey::check_key(rng, strong) || x >= group_q())\n return false;\n\n if(!strong)\n return true;\n\n return KeyPair::signature_consistency_check(rng, *this, \"EMSA1(SHA-1)\");\n }\n\nDSA_Signature_Operation::DSA_Signature_Operation(const DSA_PrivateKey& dsa,\n const std::string& emsa) :\n q(dsa.group_q()),\n x(dsa.get_x()),\n powermod_g_p(dsa.group_g(), dsa.group_p()),\n mod_q(dsa.group_q()),\n m_hash(hash_for_deterministic_signature(emsa))\n {\n }\n\nsecure_vector\nDSA_Signature_Operation::sign(const byte msg[], size_t msg_len,\n RandomNumberGenerator&)\n {\n BigInt i(msg, msg_len);\n\n while(i >= q)\n i -= q;\n\n const BigInt k = generate_rfc6979_nonce(x, q, i, m_hash);\n\n auto future_r = std::async(std::launch::async,\n [&]() { return mod_q.reduce(powermod_g_p(k)); });\n\n BigInt s = inverse_mod(k, q);\n const BigInt r = future_r.get();\n s = mod_q.multiply(s, mul_add(x, r, i));\n\n \/\/ With overwhelming probability, a bug rather than actual zero r\/s\n BOTAN_ASSERT(s != 0, \"invalid s\");\n BOTAN_ASSERT(r != 0, \"invalid r\");\n\n secure_vector output(2*q.bytes());\n r.binary_encode(&output[output.size() \/ 2 - r.bytes()]);\n s.binary_encode(&output[output.size() - s.bytes()]);\n return output;\n }\n\nDSA_Verification_Operation::DSA_Verification_Operation(const DSA_PublicKey& dsa) :\n q(dsa.group_q()), y(dsa.get_y())\n {\n powermod_g_p = Fixed_Base_Power_Mod(dsa.group_g(), dsa.group_p());\n powermod_y_p = Fixed_Base_Power_Mod(y, dsa.group_p());\n mod_p = Modular_Reducer(dsa.group_p());\n mod_q = Modular_Reducer(dsa.group_q());\n }\n\nbool DSA_Verification_Operation::verify(const byte msg[], size_t msg_len,\n const byte sig[], size_t sig_len)\n {\n if(sig_len != 2*q.bytes() || msg_len > q.bytes())\n return false;\n\n BigInt r(sig, q.bytes());\n BigInt s(sig + q.bytes(), q.bytes());\n BigInt i(msg, msg_len);\n\n if(r <= 0 || r >= q || s <= 0 || s >= q)\n return false;\n\n s = inverse_mod(s, q);\n\n auto future_s_i = std::async(std::launch::async,\n [&]() { return powermod_g_p(mod_q.multiply(s, i)); });\n\n BigInt s_r = powermod_y_p(mod_q.multiply(s, r));\n BigInt s_i = future_s_i.get();\n\n s = mod_p.multiply(s_i, s_r);\n\n return (mod_q.reduce(s) == r);\n }\n\n}\n<|endoftext|>"} {"text":"\/\/ This file is part of the KDE libraries\n\/\/ Copyright (C) 2010 Dominik Haumann \n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Library General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) version 3.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Library General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Library General Public License\n\/\/ along with this library; see the file COPYING.LIB. If not, write to\n\/\/ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301, USA.\n\n#include \"katescript.h\"\n#include \"katescriptdocument.h\"\n#include \"katescriptview.h\"\n#include \"kateview.h\"\n#include \"katedocument.h\"\n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace Kate {\nnamespace Script {\n \nbool readFile(const QString& sourceUrl, QString& sourceCode)\n{\n sourceCode = QString();\n\n QFile file(sourceUrl);\n if (!file.open(QIODevice::ReadOnly)) {\n kDebug(13050) << i18n(\"Unable to find '%1'\", sourceUrl);\n return false;\n } else {\n QTextStream stream(&file);\n stream.setCodec(\"UTF-8\");\n sourceCode = stream.readAll();\n file.close();\n }\n return true;\n}\n \nQScriptValue require(QScriptContext *context, QScriptEngine *engine)\n{\n \/**\n * just search for all given scripts and eval them\n *\/\n for(int i = 0; i < context->argumentCount(); ++i) {\n \/**\n * get full name of file\n *\/\n const QString name = context->argument(i).toString();\n\n printf (\"want to load %s\\n\", qPrintable (name));\n\n const QString fullName = KGlobal::dirs()->findResource (\"data\", \"katepart\/script\/libraries\/\" + name);\n\n printf (\"want to load fullName %s\\n\", qPrintable (fullName));\n \n \/**\n * check include guard\n *\/\n QScriptValue require_guard = engine->globalObject().property (\"require_guard\");\n if (require_guard.property (fullName).toBool ())\n continue;\n \n \/**\n * try to read complete file\n * skip non-existing files\n *\/\n\n printf (\"before read fullName %s\\n\", qPrintable (fullName));\n QString code;\n if (!readFile (fullName, code))\n continue;\n printf (\"after read fullName %s\\n\", qPrintable (fullName));\n \n \/**\n * eval in current script engine\n *\/\n engine->evaluate (code, fullName);\n if (engine->hasUncaughtException())\n printf (\"after eval fullName %s had exception\\n\", qPrintable (fullName));\n\n printf (\"after eval fullName %s\\n\", qPrintable (fullName));\n \n \/**\n * set include guard\n *\/\n require_guard.setProperty (fullName, QScriptValue (true));\n }\n \n \/**\n * no return value\n *\/\n return engine->nullValue();\n}\n\nQScriptValue debug(QScriptContext *context, QScriptEngine *engine)\n{\n QStringList message;\n for(int i = 0; i < context->argumentCount(); ++i) {\n message << context->argument(i).toString();\n }\n \/\/ debug in blue to distance from other debug output if necessary\n std::cerr << \"\\033[34m\" << qPrintable(message.join(\" \")) << \"\\033[0m\\n\";\n return engine->nullValue();\n}\n\n\/\/BEGIN code adapted from kdelibs\/kross\/modules\/translation.cpp\n\/\/\/ helper function to do the substitution from QtScript > QVariant > real values\nKLocalizedString substituteArguments( const KLocalizedString &kls, const QVariantList &arguments, int max = 99 )\n{\n KLocalizedString ls = kls;\n int cnt = qMin( arguments.count(), max ); \/\/ QString supports max 99\n for ( int i = 0; i < cnt; ++i ) {\n QVariant arg = arguments[i];\n switch ( arg.type() ) {\n case QVariant::Int: ls = ls.subs(arg.toInt()); break;\n case QVariant::UInt: ls = ls.subs(arg.toUInt()); break;\n case QVariant::LongLong: ls = ls.subs(arg.toLongLong()); break;\n case QVariant::ULongLong: ls = ls.subs(arg.toULongLong()); break;\n case QVariant::Double: ls = ls.subs(arg.toDouble()); break;\n default: ls = ls.subs(arg.toString()); break;\n }\n }\n return ls;\n}\n\n\/\/\/ i18n(\"text\", arguments [optional])\nQScriptValue i18n( QScriptContext *context, QScriptEngine *engine )\n{\n Q_UNUSED(engine)\n QString text;\n QVariantList args;\n const int argCount = context->argumentCount();\n\n if (argCount == 0) {\n kWarning(13050) << \"wrong usage of i18n:\" << context->backtrace().join(\"\\n\\t\");\n }\n\n if (argCount > 0) {\n text = context->argument(0).toString();\n }\n\n for (int i = 1; i < argCount; ++i) {\n args << context->argument(i).toVariant();\n }\n\n KLocalizedString ls = ki18n(text.toUtf8());\n return substituteArguments( ls, args ).toString();\n}\n\n\/\/\/ i18nc(\"context\", \"text\", arguments [optional])\nQScriptValue i18nc( QScriptContext *context, QScriptEngine *engine )\n{\n Q_UNUSED(engine)\n QString text;\n QString textContext;\n QVariantList args;\n const int argCount = context->argumentCount();\n\n if (argCount < 2) {\n kWarning(13050) << \"wrong usage of i18nc:\" << context->backtrace().join(\"\\n\\t\");\n }\n\n if (argCount > 0) {\n textContext = context->argument(0).toString();\n }\n\n if (argCount > 1) {\n text = context->argument(1).toString();\n }\n\n for (int i = 2; i < argCount; ++i) {\n args << context->argument(i).toVariant();\n }\n\n KLocalizedString ls = ki18nc(textContext.toUtf8(), text.toUtf8());\n return substituteArguments( ls, args ).toString();\n}\n\n\/\/\/ i18np(\"singular\", \"plural\", number, arguments [optional])\nQScriptValue i18np( QScriptContext *context, QScriptEngine *engine )\n{\n Q_UNUSED(engine)\n QString trSingular;\n QString trPlural;\n int number = 0;\n QVariantList args;\n const int argCount = context->argumentCount();\n\n if (argCount < 3) {\n kWarning(13050) << \"wrong usage of i18np:\" << context->backtrace().join(\"\\n\\t\");\n }\n\n if (argCount > 0) {\n trSingular = context->argument(0).toString();\n }\n\n if (argCount > 1) {\n trPlural = context->argument(1).toString();\n }\n\n if (argCount > 2) {\n number = context->argument(2).toInt32();\n }\n\n for (int i = 3; i < argCount; ++i) {\n args << context->argument(i).toVariant();\n }\n\n KLocalizedString ls = ki18np(trSingular.toUtf8(), trPlural.toUtf8()).subs(number);\n return substituteArguments( ls, args, 98 ).toString();\n}\n\n\/\/\/ i18ncp(\"context\", \"singular\", \"plural\", number, arguments [optional])\nQScriptValue i18ncp( QScriptContext *context, QScriptEngine *engine )\n{\n Q_UNUSED(engine)\n QString trContext;\n QString trSingular;\n QString trPlural;\n int number = 0;\n QVariantList args;\n const int argCount = context->argumentCount();\n\n if (argCount < 4) {\n kWarning(13050) << \"wrong usage of i18ncp:\" << context->backtrace().join(\"\\n\\t\");\n }\n\n if (argCount > 0) {\n trContext = context->argument(0).toString();\n }\n\n if (argCount > 1) {\n trSingular = context->argument(1).toString();\n }\n\n if (argCount > 2) {\n trPlural = context->argument(2).toString();\n }\n\n if (argCount > 3) {\n number = context->argument(3).toInt32();\n }\n\n for (int i = 4; i < argCount; ++i) {\n args << context->argument(i).toVariant();\n }\n\n KLocalizedString ls = ki18ncp(trContext.toUtf8(), trSingular.toUtf8(), trPlural.toUtf8()).subs( number );\n return substituteArguments( ls, args, 98 ).toString();\n}\n\/\/END code adapted from kdelibs\/kross\/modules\/translation.cpp\n\n}\n}\n\n\/\/ kate: space-indent on; indent-width 2; replace-tabs on;\nrequire requires some hackery :(\/\/ This file is part of the KDE libraries\n\/\/ Copyright (C) 2010 Dominik Haumann \n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Library General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) version 3.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Library General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Library General Public License\n\/\/ along with this library; see the file COPYING.LIB. If not, write to\n\/\/ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301, USA.\n\n#include \"katescript.h\"\n#include \"katescriptdocument.h\"\n#include \"katescriptview.h\"\n#include \"kateview.h\"\n#include \"katedocument.h\"\n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace Kate {\nnamespace Script {\n \nbool readFile(const QString& sourceUrl, QString& sourceCode)\n{\n sourceCode = QString();\n\n QFile file(sourceUrl);\n if (!file.open(QIODevice::ReadOnly)) {\n kDebug(13050) << i18n(\"Unable to find '%1'\", sourceUrl);\n return false;\n } else {\n QTextStream stream(&file);\n stream.setCodec(\"UTF-8\");\n sourceCode = stream.readAll();\n file.close();\n }\n return true;\n}\n \nQScriptValue require(QScriptContext *context, QScriptEngine *engine)\n{\n \/**\n * just search for all given scripts and eval them\n *\/\n for(int i = 0; i < context->argumentCount(); ++i) {\n \/**\n * get full name of file\n * skip on errors\n *\/\n const QString name = context->argument(i).toString();\n const QString fullName = KGlobal::dirs()->findResource (\"data\", \"katepart\/script\/libraries\/\" + name);\n if (fullName.isEmpty())\n continue;\n\n \/**\n * check include guard\n *\/\n QScriptValue require_guard = engine->globalObject().property (\"require_guard\");\n if (require_guard.property (fullName).toBool ())\n continue;\n \n \/**\n * try to read complete file\n * skip non-existing files\n *\/\n QString code;\n if (!readFile (fullName, code))\n continue;\n\n \/**\n * fixup QScriptContext\n * else the nested evaluate will not work :\/\n * see http:\/\/www.qtcentre.org\/threads\/31027-QtScript-nesting-with-include-imports-or-spawned-script-engines\n * http:\/\/www.qtcentre.org\/threads\/20432-Can-I-include-a-script-from-script\n *\/\n QScriptContext *context = engine->currentContext();\n QScriptContext *parent = context->parentContext();\n if (parent) {\n context->setActivationObject(context->parentContext()->activationObject());\n context->setThisObject(context->parentContext()->thisObject());\n }\n\n \/**\n * eval in current script engine\n *\/\n engine->evaluate (code, fullName);\n \n \/**\n * set include guard\n *\/\n require_guard.setProperty (fullName, QScriptValue (true));\n }\n \n \/**\n * no return value\n *\/\n return engine->nullValue();\n}\n\nQScriptValue debug(QScriptContext *context, QScriptEngine *engine)\n{\n QStringList message;\n for(int i = 0; i < context->argumentCount(); ++i) {\n message << context->argument(i).toString();\n }\n \/\/ debug in blue to distance from other debug output if necessary\n std::cerr << \"\\033[34m\" << qPrintable(message.join(\" \")) << \"\\033[0m\\n\";\n return engine->nullValue();\n}\n\n\/\/BEGIN code adapted from kdelibs\/kross\/modules\/translation.cpp\n\/\/\/ helper function to do the substitution from QtScript > QVariant > real values\nKLocalizedString substituteArguments( const KLocalizedString &kls, const QVariantList &arguments, int max = 99 )\n{\n KLocalizedString ls = kls;\n int cnt = qMin( arguments.count(), max ); \/\/ QString supports max 99\n for ( int i = 0; i < cnt; ++i ) {\n QVariant arg = arguments[i];\n switch ( arg.type() ) {\n case QVariant::Int: ls = ls.subs(arg.toInt()); break;\n case QVariant::UInt: ls = ls.subs(arg.toUInt()); break;\n case QVariant::LongLong: ls = ls.subs(arg.toLongLong()); break;\n case QVariant::ULongLong: ls = ls.subs(arg.toULongLong()); break;\n case QVariant::Double: ls = ls.subs(arg.toDouble()); break;\n default: ls = ls.subs(arg.toString()); break;\n }\n }\n return ls;\n}\n\n\/\/\/ i18n(\"text\", arguments [optional])\nQScriptValue i18n( QScriptContext *context, QScriptEngine *engine )\n{\n Q_UNUSED(engine)\n QString text;\n QVariantList args;\n const int argCount = context->argumentCount();\n\n if (argCount == 0) {\n kWarning(13050) << \"wrong usage of i18n:\" << context->backtrace().join(\"\\n\\t\");\n }\n\n if (argCount > 0) {\n text = context->argument(0).toString();\n }\n\n for (int i = 1; i < argCount; ++i) {\n args << context->argument(i).toVariant();\n }\n\n KLocalizedString ls = ki18n(text.toUtf8());\n return substituteArguments( ls, args ).toString();\n}\n\n\/\/\/ i18nc(\"context\", \"text\", arguments [optional])\nQScriptValue i18nc( QScriptContext *context, QScriptEngine *engine )\n{\n Q_UNUSED(engine)\n QString text;\n QString textContext;\n QVariantList args;\n const int argCount = context->argumentCount();\n\n if (argCount < 2) {\n kWarning(13050) << \"wrong usage of i18nc:\" << context->backtrace().join(\"\\n\\t\");\n }\n\n if (argCount > 0) {\n textContext = context->argument(0).toString();\n }\n\n if (argCount > 1) {\n text = context->argument(1).toString();\n }\n\n for (int i = 2; i < argCount; ++i) {\n args << context->argument(i).toVariant();\n }\n\n KLocalizedString ls = ki18nc(textContext.toUtf8(), text.toUtf8());\n return substituteArguments( ls, args ).toString();\n}\n\n\/\/\/ i18np(\"singular\", \"plural\", number, arguments [optional])\nQScriptValue i18np( QScriptContext *context, QScriptEngine *engine )\n{\n Q_UNUSED(engine)\n QString trSingular;\n QString trPlural;\n int number = 0;\n QVariantList args;\n const int argCount = context->argumentCount();\n\n if (argCount < 3) {\n kWarning(13050) << \"wrong usage of i18np:\" << context->backtrace().join(\"\\n\\t\");\n }\n\n if (argCount > 0) {\n trSingular = context->argument(0).toString();\n }\n\n if (argCount > 1) {\n trPlural = context->argument(1).toString();\n }\n\n if (argCount > 2) {\n number = context->argument(2).toInt32();\n }\n\n for (int i = 3; i < argCount; ++i) {\n args << context->argument(i).toVariant();\n }\n\n KLocalizedString ls = ki18np(trSingular.toUtf8(), trPlural.toUtf8()).subs(number);\n return substituteArguments( ls, args, 98 ).toString();\n}\n\n\/\/\/ i18ncp(\"context\", \"singular\", \"plural\", number, arguments [optional])\nQScriptValue i18ncp( QScriptContext *context, QScriptEngine *engine )\n{\n Q_UNUSED(engine)\n QString trContext;\n QString trSingular;\n QString trPlural;\n int number = 0;\n QVariantList args;\n const int argCount = context->argumentCount();\n\n if (argCount < 4) {\n kWarning(13050) << \"wrong usage of i18ncp:\" << context->backtrace().join(\"\\n\\t\");\n }\n\n if (argCount > 0) {\n trContext = context->argument(0).toString();\n }\n\n if (argCount > 1) {\n trSingular = context->argument(1).toString();\n }\n\n if (argCount > 2) {\n trPlural = context->argument(2).toString();\n }\n\n if (argCount > 3) {\n number = context->argument(3).toInt32();\n }\n\n for (int i = 4; i < argCount; ++i) {\n args << context->argument(i).toVariant();\n }\n\n KLocalizedString ls = ki18ncp(trContext.toUtf8(), trSingular.toUtf8(), trPlural.toUtf8()).subs( number );\n return substituteArguments( ls, args, 98 ).toString();\n}\n\/\/END code adapted from kdelibs\/kross\/modules\/translation.cpp\n\n}\n}\n\n\/\/ kate: space-indent on; indent-width 2; replace-tabs on;\n<|endoftext|>"} {"text":"#include \"response.h\"\n#include \"client.h\"\n#include \"settings.h\"\n\n#include \"timing\/timingfactory.h\"\n#include \"channel.h\"\n#include \"log\/logger.h\"\n#include \"types.h\"\n\nLOGGER(Response);\n\nResponse::Response(QObject *parent)\n: QObject(parent)\n{\n}\n\nResponse::~Response()\n{\n}\n\nvoid Response::finished()\n{\n}\n\nLoginResponse::LoginResponse(QObject *parent)\n: Response(parent)\n, m_registeredDevice(false)\n{\n}\n\nbool LoginResponse::fillFromVariant(const QVariantMap &variant)\n{\n m_apiKey = variant.value(\"api_key\").toString();\n m_registeredDevice = variant.value(\"registered_device\").toBool();\n\n return !m_apiKey.isEmpty();\n}\n\nvoid LoginResponse::finished()\n{\n Client *client = Client::instance();\n\n \/\/ Update the settings\n Settings *settings = client->settings();\n settings->setApiKey(m_apiKey);\n\n \/\/ Set registered status (after settings!)\n client->setStatus(Client::Registered);\n}\n\nQString LoginResponse::apiKey() const\n{\n return m_apiKey;\n}\n\nbool LoginResponse::registeredDevice() const\n{\n return m_registeredDevice;\n}\n\n\nRegisterDeviceResponse::RegisterDeviceResponse(QObject *parent)\n: Response(parent)\n{\n}\n\nbool RegisterDeviceResponse::fillFromVariant(const QVariantMap &variant)\n{\n Q_UNUSED(variant);\n return true;\n}\n\n\nGetConfigResponse::GetConfigResponse(QObject *parent)\n: Response(parent)\n{\n}\n\nbool GetConfigResponse::fillFromVariant(const QVariantMap &variant)\n{\n m_supervisorChannel = Channel::fromVariant(variant.value(\"supervisor_channel\"));\n m_keepaliveChannel = Channel::fromVariant(variant.value(\"keepalive_channel\"));\n m_configChannel = Channel::fromVariant(variant.value(\"config_channel\"));\n m_reportChannel = Channel::fromVariant(variant.value(\"report_channel\"));\n\n return true;\n}\n\nQVariant GetConfigResponse::toVariant() const\n{\n QVariantMap map;\n map.insert(\"supervisor_channel\", m_supervisorChannel.toVariant());\n map.insert(\"keepalive_channel\", m_keepaliveChannel.toVariant());\n map.insert(\"config_channel\", m_configChannel.toVariant());\n map.insert(\"report_channel\", m_reportChannel.toVariant());\n return map;\n}\n\nvoid GetConfigResponse::finished()\n{\n \/\/ Sync the settings\n Client *client = Client::instance();\n Settings *settings = client->settings();\n settings->sync();\n\n emit responseChanged();\n}\n\nQString GetConfigResponse::supervisorAddress() const\n{\n return m_supervisorChannel.target();\n}\n\nTimingPtr GetConfigResponse::supervisorTiming() const\n{\n return m_supervisorChannel.timing();\n}\n\nQString GetConfigResponse::keepaliveAddress() const\n{\n return m_keepaliveChannel.target();\n}\n\nTimingPtr GetConfigResponse::keepaliveTiming() const\n{\n return m_keepaliveChannel.timing();\n}\n\nvoid GetConfigResponse::setConfigAddress(const QString &address)\n{\n m_configChannel.setTarget(address);\n}\n\nQString GetConfigResponse::configAddress() const\n{\n return m_configChannel.target();\n}\n\nTimingPtr GetConfigResponse::configTiming() const\n{\n return m_configChannel.timing();\n}\n\nQString GetConfigResponse::reportAddress() const\n{\n return m_reportChannel.target();\n}\n\nTimingPtr GetConfigResponse::reportTiming() const\n{\n return m_reportChannel.timing();\n}\n\nQList GetInstructionResponse::taskIds() const\n{\n return m_taskIds;\n}\n\nQList GetInstructionResponse::scheduleIds() const\n{\n return m_scheduleIds;\n}\n\nbool GetInstructionResponse::fillFromVariant(const QVariantMap &variant)\n{\n m_taskIds.clear();\n\n foreach (const QVariant &entry, variant.value(\"tasks\").toList())\n {\n m_taskIds.append(entry.toInt());\n }\n\n m_scheduleIds.clear();\n\n foreach (const QVariant &entry, variant.value(\"tasks\").toList())\n {\n m_scheduleIds.append(entry.toInt());\n }\n\n LOG_DEBUG(QString(\"Received %1 tasks\").arg(m_taskIds.size()));\n LOG_DEBUG(QString(\"Received %1 schedules\").arg(m_scheduleIds.size()));\n\n return true;\n}\n\n\nbool GetScheduleResponse::fillFromVariant(const QVariantMap &variant)\n{\n QVariantMap variantMap = variant.value(\"object\").toMap();\n\n \/\/ validate task\n TestDefinition test = TestDefinition::fromVariant(variantMap.value(\"task\"));\n\n \/\/ get timing and merge into task FIXME this is an evil hack\n TimingPtr timing = TimingFactory::timingFromVariant(variantMap.value(\"timing\"));\n test.setTiming(timing);\n\n if (m_validator.validate(test) == TaskValidator::Valid)\n {\n m_tasks.append(test);\n }\n else\n {\n \/\/ TODO: Get more information\n LOG_DEBUG(QString(\"Received invalid task, ignoring.\"));\n }\n\n return true;\n}\n\nTestDefinitionList GetScheduleResponse::tasks() const\n{\n return m_tasks;\n}\nResponse function for schedules#include \"response.h\"\n#include \"client.h\"\n#include \"settings.h\"\n\n#include \"timing\/timingfactory.h\"\n#include \"channel.h\"\n#include \"log\/logger.h\"\n#include \"types.h\"\n\nLOGGER(Response);\n\nResponse::Response(QObject *parent)\n: QObject(parent)\n{\n}\n\nResponse::~Response()\n{\n}\n\nvoid Response::finished()\n{\n}\n\nLoginResponse::LoginResponse(QObject *parent)\n: Response(parent)\n, m_registeredDevice(false)\n{\n}\n\nbool LoginResponse::fillFromVariant(const QVariantMap &variant)\n{\n m_apiKey = variant.value(\"api_key\").toString();\n m_registeredDevice = variant.value(\"registered_device\").toBool();\n\n return !m_apiKey.isEmpty();\n}\n\nvoid LoginResponse::finished()\n{\n Client *client = Client::instance();\n\n \/\/ Update the settings\n Settings *settings = client->settings();\n settings->setApiKey(m_apiKey);\n\n \/\/ Set registered status (after settings!)\n client->setStatus(Client::Registered);\n}\n\nQString LoginResponse::apiKey() const\n{\n return m_apiKey;\n}\n\nbool LoginResponse::registeredDevice() const\n{\n return m_registeredDevice;\n}\n\n\nRegisterDeviceResponse::RegisterDeviceResponse(QObject *parent)\n: Response(parent)\n{\n}\n\nbool RegisterDeviceResponse::fillFromVariant(const QVariantMap &variant)\n{\n Q_UNUSED(variant);\n return true;\n}\n\n\nGetConfigResponse::GetConfigResponse(QObject *parent)\n: Response(parent)\n{\n}\n\nbool GetConfigResponse::fillFromVariant(const QVariantMap &variant)\n{\n m_supervisorChannel = Channel::fromVariant(variant.value(\"supervisor_channel\"));\n m_keepaliveChannel = Channel::fromVariant(variant.value(\"keepalive_channel\"));\n m_configChannel = Channel::fromVariant(variant.value(\"config_channel\"));\n m_reportChannel = Channel::fromVariant(variant.value(\"report_channel\"));\n\n return true;\n}\n\nQVariant GetConfigResponse::toVariant() const\n{\n QVariantMap map;\n map.insert(\"supervisor_channel\", m_supervisorChannel.toVariant());\n map.insert(\"keepalive_channel\", m_keepaliveChannel.toVariant());\n map.insert(\"config_channel\", m_configChannel.toVariant());\n map.insert(\"report_channel\", m_reportChannel.toVariant());\n return map;\n}\n\nvoid GetConfigResponse::finished()\n{\n \/\/ Sync the settings\n Client *client = Client::instance();\n Settings *settings = client->settings();\n settings->sync();\n\n emit responseChanged();\n}\n\nQString GetConfigResponse::supervisorAddress() const\n{\n return m_supervisorChannel.target();\n}\n\nTimingPtr GetConfigResponse::supervisorTiming() const\n{\n return m_supervisorChannel.timing();\n}\n\nQString GetConfigResponse::keepaliveAddress() const\n{\n return m_keepaliveChannel.target();\n}\n\nTimingPtr GetConfigResponse::keepaliveTiming() const\n{\n return m_keepaliveChannel.timing();\n}\n\nvoid GetConfigResponse::setConfigAddress(const QString &address)\n{\n m_configChannel.setTarget(address);\n}\n\nQString GetConfigResponse::configAddress() const\n{\n return m_configChannel.target();\n}\n\nTimingPtr GetConfigResponse::configTiming() const\n{\n return m_configChannel.timing();\n}\n\nQString GetConfigResponse::reportAddress() const\n{\n return m_reportChannel.target();\n}\n\nTimingPtr GetConfigResponse::reportTiming() const\n{\n return m_reportChannel.timing();\n}\n\nQList GetInstructionResponse::taskIds() const\n{\n return m_taskIds;\n}\n\nQList GetInstructionResponse::scheduleIds() const\n{\n return m_scheduleIds;\n}\n\nbool GetInstructionResponse::fillFromVariant(const QVariantMap &variant)\n{\n m_taskIds.clear();\n\n foreach (const QVariant &entry, variant.value(\"tasks\").toList())\n {\n m_taskIds.append(entry.toInt());\n }\n\n m_scheduleIds.clear();\n\n foreach (const QVariant &entry, variant.value(\"tasks\").toList())\n {\n m_scheduleIds.append(entry.toInt());\n }\n\n LOG_DEBUG(QString(\"Received %1 tasks\").arg(m_taskIds.size()));\n LOG_DEBUG(QString(\"Received %1 schedules\").arg(m_scheduleIds.size()));\n\n return true;\n}\n\n\nbool GetScheduleResponse::fillFromVariant(const QVariantMap &variant)\n{\n\n foreach (const QVariant &entry, variant.value(\"objects\").toList())\n {\n QVariantMap variantMap = entry.toMap();\n\n \/\/ generate task\n TestDefinition test = TestDefinition::fromVariant(variantMap.value(\"task\"));\n\n \/\/ get timing and merge into task FIXME this is an evil hack\n TimingPtr timing = TimingFactory::timingFromVariant(variantMap.value(\"timing\"));\n test.setTiming(timing);\n\n if (m_validator.validate(test) == TaskValidator::Valid)\n {\n m_tasks.append(test);\n }\n else\n {\n \/\/ TODO: Get more information\n LOG_DEBUG(QString(\"Received invalid task, ignoring.\"));\n }\n }\n\n\n\n return true;\n}\n\nTestDefinitionList GetScheduleResponse::tasks() const\n{\n return m_tasks;\n}\n<|endoftext|>"} {"text":"\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n\/\/ Include this before af\/opencl.h\n\/\/ Causes conflict between system cl.hpp and opencl\/cl.hpp\n#if defined(WITH_GRAPHICS)\n#include \n#endif\n\n#if defined(OS_MAC)\n#include \n#include \n#else\n#include \n#endif \/\/ !__APPLE__\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::string;\nusing std::vector;\nusing std::ostringstream;\nusing std::runtime_error;\n\nusing cl::Platform;\nusing cl::Context;\nusing cl::CommandQueue;\nusing cl::Device;\n\nnamespace opencl\n{\n\n#if defined (OS_MAC)\nstatic const std::string CL_GL_SHARING_EXT = \"cl_APPLE_gl_sharing\";\n#else\nstatic const std::string CL_GL_SHARING_EXT = \"cl_khr_gl_sharing\";\n#endif\n\nstatic const char *get_system(void)\n{\n return\n#if defined(ARCH_32)\n \"32-bit \"\n#elif defined(ARCH_64)\n \"64-bit \"\n#endif\n\n#if defined(OS_LNX)\n \"Linux\";\n#elif defined(OS_WIN)\n \"Windows\";\n#elif defined(OS_MAC)\n \"Mac OSX\";\n#endif\n}\n\nDeviceManager& DeviceManager::getInstance()\n{\n static DeviceManager my_instance;\n return my_instance;\n}\n\nDeviceManager::~DeviceManager()\n{\n \/\/TODO: FIXME:\n \/\/ OpenCL libs on Windows platforms\n \/\/ are crashing the application at program exit\n \/\/ most probably a reference counting issue based\n \/\/ on the investigation done so far. This problem\n \/\/ doesn't seem to happen on Linux or MacOSX.\n \/\/ So, clean up OpenCL resources on non-Windows platforms\n#ifndef OS_WIN\n for (auto q: mQueues) delete q;\n for (auto d : mDevices) delete d;\n for (auto c : mContexts) delete c;\n for (auto p : mPlatforms) delete p;\n#endif\n}\n\nvoid DeviceManager::setContext(int device)\n{\n mActiveQId = device;\n mActiveCtxId = device;\n}\n\nDeviceManager::DeviceManager()\n : mActiveCtxId(0), mActiveQId(0)\n{\n try {\n std::vector platforms;\n Platform::get(&platforms);\n\n cl_device_type DEVC_TYPES[] = {\n CL_DEVICE_TYPE_GPU,\n#ifndef OS_MAC\n CL_DEVICE_TYPE_ACCELERATOR,\n CL_DEVICE_TYPE_CPU\n#endif\n };\n\n for (auto &platform : platforms)\n mPlatforms.push_back(new Platform(platform));\n\n unsigned nDevices = 0;\n for (auto devType : DEVC_TYPES) {\n for (auto &platform : platforms) {\n\n cl_context_properties cps[3] = {CL_CONTEXT_PLATFORM,\n (cl_context_properties)(platform()),\n 0};\n\n std::vector devs;\n try {\n platform.getDevices(devType, &devs);\n } catch(const cl::Error &err) {\n if (err.err() != CL_DEVICE_NOT_FOUND) {\n throw;\n }\n }\n\n for (auto dev : devs) {\n nDevices++;\n Context *ctx = new Context(dev, cps);\n CommandQueue *cq = new CommandQueue(*ctx, dev);\n mDevices.push_back(new Device(dev));\n mContexts.push_back(ctx);\n mQueues.push_back(cq);\n mCtxOffsets.push_back(nDevices);\n mIsGLSharingOn.push_back(false);\n }\n }\n }\n\n const char* deviceENV = getenv(\"AF_OPENCL_DEFAULT_DEVICE\");\n if(deviceENV) {\n std::stringstream s(deviceENV);\n int def_device = -1;\n s >> def_device;\n if(def_device < 0 || def_device >= (int)nDevices) {\n printf(\"WARNING: AF_OPENCL_DEFAULT_DEVICE is out of range\\n\");\n printf(\"Setting default device as 0\\n\");\n } else {\n setContext(def_device);\n }\n }\n } catch (const cl::Error &error) {\n CL_TO_AF_ERROR(error);\n }\n \/* loop over devices and replace contexts with\n * OpenGL shared contexts whereever applicable *\/\n#if defined(WITH_GRAPHICS)\n \/\/ Define AF_DISABLE_GRAPHICS with any value to disable initialization\n const char* noGraphicsENV = getenv(\"AF_DISABLE_GRAPHICS\");\n if(!noGraphicsENV) { \/\/ If AF_DISABLE_GRAPHICS is not defined\n try {\n int devCount = mDevices.size();\n fg::Window* wHandle = graphics::ForgeManager::getInstance().getMainWindow();\n for(int i=0; i(std::isspace))));\n return s;\n}\n\nstatic std::string platformMap(std::string &platStr)\n{\n static bool isFirst = true;\n\n typedef std::map strmap_t;\n static strmap_t platMap;\n if (isFirst) {\n platMap[\"NVIDIA CUDA\"] = \"NVIDIA \";\n platMap[\"Intel(R) OpenCL\"] = \"INTEL \";\n platMap[\"AMD Accelerated Parallel Processing\"] = \"AMD \";\n platMap[\"Intel Gen OCL Driver\"] = \"BEIGNET \";\n platMap[\"Apple\"] = \"APPLE \";\n isFirst = false;\n }\n\n strmap_t::iterator idx = platMap.find(platStr);\n\n if (idx == platMap.end()) {\n return platStr;\n } else {\n return idx->second;\n }\n}\n\nstd::string getInfo()\n{\n ostringstream info;\n info << \"ArrayFire v\" << AF_VERSION\n << \" (OpenCL, \" << get_system() << \", build \" << AF_REVISION << \")\" << std::endl;\n\n unsigned nDevices = 0;\n for (auto context : DeviceManager::getInstance().mContexts) {\n vector devices = context->getInfo();\n\n for(auto &device:devices) {\n const Platform platform(device.getInfo());\n string platStr = platform.getInfo();\n bool show_braces = ((unsigned)getActiveDeviceId() == nDevices);\n string dstr = device.getInfo();\n\n string id = (show_braces ? string(\"[\") : \"-\") + std::to_string(nDevices) +\n (show_braces ? string(\"]\") : \"-\");\n info << id << \" \" << platformMap(platStr) << \": \" << ltrim(dstr) << \" \";\n#ifndef NDEBUG\n info << device.getInfo();\n info << \" Device driver \" << device.getInfo();\n info << \" FP64 Support(\"\n << (device.getInfo()>0 ? \"True\" : \"False\")\n << \")\";\n#endif\n info << std::endl;\n\n nDevices++;\n }\n }\n return info.str();\n}\n\nstd::string getPlatformName(const cl::Device &device)\n{\n const Platform platform(device.getInfo());\n std::string platStr = platform.getInfo();\n return platformMap(platStr);\n}\n\nint getDeviceCount()\n{\n return DeviceManager::getInstance().mQueues.size();\n}\n\nint getActiveDeviceId()\n{\n return DeviceManager::getInstance().mActiveQId;\n}\n\nconst Context& getContext()\n{\n DeviceManager& devMngr = DeviceManager::getInstance();\n return *(devMngr.mContexts[devMngr.mActiveCtxId]);\n}\n\nCommandQueue& getQueue()\n{\n DeviceManager& devMngr = DeviceManager::getInstance();\n return *(devMngr.mQueues[devMngr.mActiveQId]);\n}\n\nconst cl::Device& getDevice()\n{\n DeviceManager& devMngr = DeviceManager::getInstance();\n return *(devMngr.mDevices[devMngr.mActiveQId]);\n}\n\nbool isGLSharingSupported()\n{\n DeviceManager& devMngr = DeviceManager::getInstance();\n return devMngr.mIsGLSharingOn[devMngr.mActiveQId];\n}\n\nbool isDoubleSupported(int device)\n{\n DeviceManager& devMngr = DeviceManager::getInstance();\n return (devMngr.mDevices[device]->getInfo()>0);\n}\n\nvoid devprop(char* d_name, char* d_platform, char *d_toolkit, char* d_compute)\n{\n unsigned nDevices = 0;\n unsigned currActiveDevId = (unsigned)getActiveDeviceId();\n bool devset = false;\n\n for (auto context : DeviceManager::getInstance().mContexts) {\n vector devices = context->getInfo();\n\n for (auto &device : devices) {\n const Platform platform(device.getInfo());\n string platStr = platform.getInfo();\n\n if (currActiveDevId == nDevices) {\n string dev_str;\n device.getInfo(CL_DEVICE_NAME, &dev_str);\n string com_str = device.getInfo();\n com_str = com_str.substr(7, 3);\n\n \/\/ strip out whitespace from the device string:\n const std::string& whitespace = \" \\t\";\n const auto strBegin = dev_str.find_first_not_of(whitespace);\n const auto strEnd = dev_str.find_last_not_of(whitespace);\n const auto strRange = strEnd - strBegin + 1;\n dev_str = dev_str.substr(strBegin, strRange);\n\n \/\/ copy to output\n snprintf(d_name, 64, \"%s\", dev_str.c_str());\n snprintf(d_platform, 10, \"OpenCL\");\n snprintf(d_toolkit, 64, \"%s\", platStr.c_str());\n snprintf(d_compute, 10, \"%s\", com_str.c_str());\n devset = true;\n }\n if(devset) break;\n nDevices++;\n }\n if(devset) break;\n }\n\n \/\/ Sanitize input\n for (int i = 0; i < 31; i++) {\n if (d_name[i] == ' ') {\n if (d_name[i + 1] == 0 || d_name[i + 1] == ' ') d_name[i] = 0;\n else d_name[i] = '_';\n }\n }\n}\n\nint setDevice(int device)\n{\n DeviceManager& devMngr = DeviceManager::getInstance();\n\n if (device >= (int)devMngr.mQueues.size() ||\n device>= (int)DeviceManager::MAX_DEVICES) {\n \/\/throw runtime_error(\"@setDevice: invalid device index\");\n return -1;\n }\n else {\n int old = devMngr.mActiveQId;\n devMngr.setContext(device);\n return old;\n }\n}\n\nvoid sync(int device)\n{\n try {\n int currDevice = getActiveDeviceId();\n setDevice(device);\n getQueue().finish();\n setDevice(currDevice);\n } catch (const cl::Error &ex) {\n CL_TO_AF_ERROR(ex);\n }\n}\n\nbool checkExtnAvailability(const Device &pDevice, std::string pName)\n{\n bool ret_val = false;\n \/\/ find the extension required\n std::string exts = pDevice.getInfo();\n std::stringstream ss(exts);\n std::string item;\n while (std::getline(ss,item,' ')) {\n if (item==pName) {\n ret_val = true;\n break;\n }\n }\n return ret_val;\n}\n\n#if defined(WITH_GRAPHICS)\nvoid DeviceManager::markDeviceForInterop(const int device, const fg::Window* wHandle)\n{\n try {\n if (device >= (int)mQueues.size() ||\n device>= (int)DeviceManager::MAX_DEVICES) {\n throw cl::Error(CL_INVALID_DEVICE, \"Invalid device passed for CL-GL Interop\");\n }\n else {\n mQueues[device]->finish();\n\n \/\/ check if the device has CL_GL sharing extension enabled\n bool temp = checkExtnAvailability(*mDevices[device], CL_GL_SHARING_EXT);\n if (!temp) {\n printf(\"Device[%d] has no support for OpenGL Interoperation\\n\",device);\n \/* return silently if given device has not OpenGL sharing extension\n * enabled so that regular queue is used for it *\/\n return;\n }\n\n \/\/ call forge to get OpenGL sharing context and details\n cl::Platform plat(mDevices[device]->getInfo());\n#ifdef OS_MAC\n CGLContextObj cgl_current_ctx = CGLGetCurrentContext();\n CGLShareGroupObj cgl_share_group = CGLGetShareGroup(cgl_current_ctx);\n\n cl_context_properties cps[] = {\n CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, (cl_context_properties)cgl_share_group,\n 0\n };\n#else\n cl_context_properties cps[] = {\n CL_GL_CONTEXT_KHR, (cl_context_properties)wHandle->context(),\n#if defined(_WIN32) || defined(_MSC_VER)\n CL_WGL_HDC_KHR, (cl_context_properties)wHandle->display(),\n#else\n CL_GLX_DISPLAY_KHR, (cl_context_properties)wHandle->display(),\n#endif\n CL_CONTEXT_PLATFORM, (cl_context_properties)plat(),\n 0\n };\n#endif\n Context * ctx = new Context(*mDevices[device], cps);\n CommandQueue * cq = new CommandQueue(*ctx, *mDevices[device]);\n\n delete mContexts[device];\n delete mQueues[device];\n\n mContexts[device] = ctx;\n mQueues[device] = cq;\n }\n mIsGLSharingOn[device] = true;\n } catch (const cl::Error &ex) {\n \/* If replacing the original context with GL shared context\n * failes, don't throw an error and instead fall back to\n * original context and use copy via host to support graphics\n * on that particular OpenCL device. So mark it as no GL sharing *\/\n }\n}\n#endif\n\n}\n\nusing namespace opencl;\n\naf_err afcl_get_context(cl_context *ctx, const bool retain)\n{\n *ctx = getContext()();\n if (retain) clRetainContext(*ctx);\n return AF_SUCCESS;\n}\n\n\naf_err afcl_get_queue(cl_command_queue *queue, const bool retain)\n{\n *queue = getQueue()();\n if (retain) clRetainCommandQueue(*queue);\n return AF_SUCCESS;\n}\n\naf_err afcl_get_device_id(cl_device_id *id)\n{\n *id = getDevice()();\n return AF_SUCCESS;\n}\nMoved GL headers in platform.cpp inside WITH_GRAPHICS block\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n\/\/ Include this before af\/opencl.h\n\/\/ Causes conflict between system cl.hpp and opencl\/cl.hpp\n#if defined(WITH_GRAPHICS)\n\n#include \n\n#if defined(OS_MAC)\n#include \n#include \n#else\n#include \n#endif \/\/ !__APPLE__\n\n#endif\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::string;\nusing std::vector;\nusing std::ostringstream;\nusing std::runtime_error;\n\nusing cl::Platform;\nusing cl::Context;\nusing cl::CommandQueue;\nusing cl::Device;\n\nnamespace opencl\n{\n\n#if defined (OS_MAC)\nstatic const std::string CL_GL_SHARING_EXT = \"cl_APPLE_gl_sharing\";\n#else\nstatic const std::string CL_GL_SHARING_EXT = \"cl_khr_gl_sharing\";\n#endif\n\nstatic const char *get_system(void)\n{\n return\n#if defined(ARCH_32)\n \"32-bit \"\n#elif defined(ARCH_64)\n \"64-bit \"\n#endif\n\n#if defined(OS_LNX)\n \"Linux\";\n#elif defined(OS_WIN)\n \"Windows\";\n#elif defined(OS_MAC)\n \"Mac OSX\";\n#endif\n}\n\nDeviceManager& DeviceManager::getInstance()\n{\n static DeviceManager my_instance;\n return my_instance;\n}\n\nDeviceManager::~DeviceManager()\n{\n \/\/TODO: FIXME:\n \/\/ OpenCL libs on Windows platforms\n \/\/ are crashing the application at program exit\n \/\/ most probably a reference counting issue based\n \/\/ on the investigation done so far. This problem\n \/\/ doesn't seem to happen on Linux or MacOSX.\n \/\/ So, clean up OpenCL resources on non-Windows platforms\n#ifndef OS_WIN\n for (auto q: mQueues) delete q;\n for (auto d : mDevices) delete d;\n for (auto c : mContexts) delete c;\n for (auto p : mPlatforms) delete p;\n#endif\n}\n\nvoid DeviceManager::setContext(int device)\n{\n mActiveQId = device;\n mActiveCtxId = device;\n}\n\nDeviceManager::DeviceManager()\n : mActiveCtxId(0), mActiveQId(0)\n{\n try {\n std::vector platforms;\n Platform::get(&platforms);\n\n cl_device_type DEVC_TYPES[] = {\n CL_DEVICE_TYPE_GPU,\n#ifndef OS_MAC\n CL_DEVICE_TYPE_ACCELERATOR,\n CL_DEVICE_TYPE_CPU\n#endif\n };\n\n for (auto &platform : platforms)\n mPlatforms.push_back(new Platform(platform));\n\n unsigned nDevices = 0;\n for (auto devType : DEVC_TYPES) {\n for (auto &platform : platforms) {\n\n cl_context_properties cps[3] = {CL_CONTEXT_PLATFORM,\n (cl_context_properties)(platform()),\n 0};\n\n std::vector devs;\n try {\n platform.getDevices(devType, &devs);\n } catch(const cl::Error &err) {\n if (err.err() != CL_DEVICE_NOT_FOUND) {\n throw;\n }\n }\n\n for (auto dev : devs) {\n nDevices++;\n Context *ctx = new Context(dev, cps);\n CommandQueue *cq = new CommandQueue(*ctx, dev);\n mDevices.push_back(new Device(dev));\n mContexts.push_back(ctx);\n mQueues.push_back(cq);\n mCtxOffsets.push_back(nDevices);\n mIsGLSharingOn.push_back(false);\n }\n }\n }\n\n const char* deviceENV = getenv(\"AF_OPENCL_DEFAULT_DEVICE\");\n if(deviceENV) {\n std::stringstream s(deviceENV);\n int def_device = -1;\n s >> def_device;\n if(def_device < 0 || def_device >= (int)nDevices) {\n printf(\"WARNING: AF_OPENCL_DEFAULT_DEVICE is out of range\\n\");\n printf(\"Setting default device as 0\\n\");\n } else {\n setContext(def_device);\n }\n }\n } catch (const cl::Error &error) {\n CL_TO_AF_ERROR(error);\n }\n \/* loop over devices and replace contexts with\n * OpenGL shared contexts whereever applicable *\/\n#if defined(WITH_GRAPHICS)\n \/\/ Define AF_DISABLE_GRAPHICS with any value to disable initialization\n const char* noGraphicsENV = getenv(\"AF_DISABLE_GRAPHICS\");\n if(!noGraphicsENV) { \/\/ If AF_DISABLE_GRAPHICS is not defined\n try {\n int devCount = mDevices.size();\n fg::Window* wHandle = graphics::ForgeManager::getInstance().getMainWindow();\n for(int i=0; i(std::isspace))));\n return s;\n}\n\nstatic std::string platformMap(std::string &platStr)\n{\n static bool isFirst = true;\n\n typedef std::map strmap_t;\n static strmap_t platMap;\n if (isFirst) {\n platMap[\"NVIDIA CUDA\"] = \"NVIDIA \";\n platMap[\"Intel(R) OpenCL\"] = \"INTEL \";\n platMap[\"AMD Accelerated Parallel Processing\"] = \"AMD \";\n platMap[\"Intel Gen OCL Driver\"] = \"BEIGNET \";\n platMap[\"Apple\"] = \"APPLE \";\n isFirst = false;\n }\n\n strmap_t::iterator idx = platMap.find(platStr);\n\n if (idx == platMap.end()) {\n return platStr;\n } else {\n return idx->second;\n }\n}\n\nstd::string getInfo()\n{\n ostringstream info;\n info << \"ArrayFire v\" << AF_VERSION\n << \" (OpenCL, \" << get_system() << \", build \" << AF_REVISION << \")\" << std::endl;\n\n unsigned nDevices = 0;\n for (auto context : DeviceManager::getInstance().mContexts) {\n vector devices = context->getInfo();\n\n for(auto &device:devices) {\n const Platform platform(device.getInfo());\n string platStr = platform.getInfo();\n bool show_braces = ((unsigned)getActiveDeviceId() == nDevices);\n string dstr = device.getInfo();\n\n string id = (show_braces ? string(\"[\") : \"-\") + std::to_string(nDevices) +\n (show_braces ? string(\"]\") : \"-\");\n info << id << \" \" << platformMap(platStr) << \": \" << ltrim(dstr) << \" \";\n#ifndef NDEBUG\n info << device.getInfo();\n info << \" Device driver \" << device.getInfo();\n info << \" FP64 Support(\"\n << (device.getInfo()>0 ? \"True\" : \"False\")\n << \")\";\n#endif\n info << std::endl;\n\n nDevices++;\n }\n }\n return info.str();\n}\n\nstd::string getPlatformName(const cl::Device &device)\n{\n const Platform platform(device.getInfo());\n std::string platStr = platform.getInfo();\n return platformMap(platStr);\n}\n\nint getDeviceCount()\n{\n return DeviceManager::getInstance().mQueues.size();\n}\n\nint getActiveDeviceId()\n{\n return DeviceManager::getInstance().mActiveQId;\n}\n\nconst Context& getContext()\n{\n DeviceManager& devMngr = DeviceManager::getInstance();\n return *(devMngr.mContexts[devMngr.mActiveCtxId]);\n}\n\nCommandQueue& getQueue()\n{\n DeviceManager& devMngr = DeviceManager::getInstance();\n return *(devMngr.mQueues[devMngr.mActiveQId]);\n}\n\nconst cl::Device& getDevice()\n{\n DeviceManager& devMngr = DeviceManager::getInstance();\n return *(devMngr.mDevices[devMngr.mActiveQId]);\n}\n\nbool isGLSharingSupported()\n{\n DeviceManager& devMngr = DeviceManager::getInstance();\n return devMngr.mIsGLSharingOn[devMngr.mActiveQId];\n}\n\nbool isDoubleSupported(int device)\n{\n DeviceManager& devMngr = DeviceManager::getInstance();\n return (devMngr.mDevices[device]->getInfo()>0);\n}\n\nvoid devprop(char* d_name, char* d_platform, char *d_toolkit, char* d_compute)\n{\n unsigned nDevices = 0;\n unsigned currActiveDevId = (unsigned)getActiveDeviceId();\n bool devset = false;\n\n for (auto context : DeviceManager::getInstance().mContexts) {\n vector devices = context->getInfo();\n\n for (auto &device : devices) {\n const Platform platform(device.getInfo());\n string platStr = platform.getInfo();\n\n if (currActiveDevId == nDevices) {\n string dev_str;\n device.getInfo(CL_DEVICE_NAME, &dev_str);\n string com_str = device.getInfo();\n com_str = com_str.substr(7, 3);\n\n \/\/ strip out whitespace from the device string:\n const std::string& whitespace = \" \\t\";\n const auto strBegin = dev_str.find_first_not_of(whitespace);\n const auto strEnd = dev_str.find_last_not_of(whitespace);\n const auto strRange = strEnd - strBegin + 1;\n dev_str = dev_str.substr(strBegin, strRange);\n\n \/\/ copy to output\n snprintf(d_name, 64, \"%s\", dev_str.c_str());\n snprintf(d_platform, 10, \"OpenCL\");\n snprintf(d_toolkit, 64, \"%s\", platStr.c_str());\n snprintf(d_compute, 10, \"%s\", com_str.c_str());\n devset = true;\n }\n if(devset) break;\n nDevices++;\n }\n if(devset) break;\n }\n\n \/\/ Sanitize input\n for (int i = 0; i < 31; i++) {\n if (d_name[i] == ' ') {\n if (d_name[i + 1] == 0 || d_name[i + 1] == ' ') d_name[i] = 0;\n else d_name[i] = '_';\n }\n }\n}\n\nint setDevice(int device)\n{\n DeviceManager& devMngr = DeviceManager::getInstance();\n\n if (device >= (int)devMngr.mQueues.size() ||\n device>= (int)DeviceManager::MAX_DEVICES) {\n \/\/throw runtime_error(\"@setDevice: invalid device index\");\n return -1;\n }\n else {\n int old = devMngr.mActiveQId;\n devMngr.setContext(device);\n return old;\n }\n}\n\nvoid sync(int device)\n{\n try {\n int currDevice = getActiveDeviceId();\n setDevice(device);\n getQueue().finish();\n setDevice(currDevice);\n } catch (const cl::Error &ex) {\n CL_TO_AF_ERROR(ex);\n }\n}\n\nbool checkExtnAvailability(const Device &pDevice, std::string pName)\n{\n bool ret_val = false;\n \/\/ find the extension required\n std::string exts = pDevice.getInfo();\n std::stringstream ss(exts);\n std::string item;\n while (std::getline(ss,item,' ')) {\n if (item==pName) {\n ret_val = true;\n break;\n }\n }\n return ret_val;\n}\n\n#if defined(WITH_GRAPHICS)\nvoid DeviceManager::markDeviceForInterop(const int device, const fg::Window* wHandle)\n{\n try {\n if (device >= (int)mQueues.size() ||\n device>= (int)DeviceManager::MAX_DEVICES) {\n throw cl::Error(CL_INVALID_DEVICE, \"Invalid device passed for CL-GL Interop\");\n }\n else {\n mQueues[device]->finish();\n\n \/\/ check if the device has CL_GL sharing extension enabled\n bool temp = checkExtnAvailability(*mDevices[device], CL_GL_SHARING_EXT);\n if (!temp) {\n printf(\"Device[%d] has no support for OpenGL Interoperation\\n\",device);\n \/* return silently if given device has not OpenGL sharing extension\n * enabled so that regular queue is used for it *\/\n return;\n }\n\n \/\/ call forge to get OpenGL sharing context and details\n cl::Platform plat(mDevices[device]->getInfo());\n#ifdef OS_MAC\n CGLContextObj cgl_current_ctx = CGLGetCurrentContext();\n CGLShareGroupObj cgl_share_group = CGLGetShareGroup(cgl_current_ctx);\n\n cl_context_properties cps[] = {\n CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, (cl_context_properties)cgl_share_group,\n 0\n };\n#else\n cl_context_properties cps[] = {\n CL_GL_CONTEXT_KHR, (cl_context_properties)wHandle->context(),\n#if defined(_WIN32) || defined(_MSC_VER)\n CL_WGL_HDC_KHR, (cl_context_properties)wHandle->display(),\n#else\n CL_GLX_DISPLAY_KHR, (cl_context_properties)wHandle->display(),\n#endif\n CL_CONTEXT_PLATFORM, (cl_context_properties)plat(),\n 0\n };\n#endif\n Context * ctx = new Context(*mDevices[device], cps);\n CommandQueue * cq = new CommandQueue(*ctx, *mDevices[device]);\n\n delete mContexts[device];\n delete mQueues[device];\n\n mContexts[device] = ctx;\n mQueues[device] = cq;\n }\n mIsGLSharingOn[device] = true;\n } catch (const cl::Error &ex) {\n \/* If replacing the original context with GL shared context\n * failes, don't throw an error and instead fall back to\n * original context and use copy via host to support graphics\n * on that particular OpenCL device. So mark it as no GL sharing *\/\n }\n}\n#endif\n\n}\n\nusing namespace opencl;\n\naf_err afcl_get_context(cl_context *ctx, const bool retain)\n{\n *ctx = getContext()();\n if (retain) clRetainContext(*ctx);\n return AF_SUCCESS;\n}\n\n\naf_err afcl_get_queue(cl_command_queue *queue, const bool retain)\n{\n *queue = getQueue()();\n if (retain) clRetainCommandQueue(*queue);\n return AF_SUCCESS;\n}\n\naf_err afcl_get_device_id(cl_device_id *id)\n{\n *id = getDevice()();\n return AF_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/*\n * This is mcs; a modular configuration system.\n *\n * Copyright (c) 2007 Diego Pettenò \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * 3. The name of the author may not be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\n * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n\nextern \"C\" {\n\n #include \"libmcs\/mcs.h\"\n\n\/* ***************************************************************** *\/\n\n extern mcs_backend_t mcs_backend;\n}\n\ntypedef struct {\n\tKConfig *cfg;\n} mcs_kconfig_handle_t;\n\nnamespace {\n\n\tmcs_handle_t *\n\tmcs_kconfig_new(char *domain)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *)calloc(sizeof(mcs_kconfig_handle_t), 1);\n\t\tmcs_handle_t *out = (mcs_handle_t *)calloc(sizeof(mcs_handle_t), 1);\n\n\t\tif (!KApplication::kApplication())\n\t\t{\n\t \t\t\/* Initialise a fake KDE application if none present *\/\n\t\t\tstatic char *fake_argv[] = { \"mcs_backend\" };\n\n\t\t\tKCmdLineArgs::init(1, fake_argv, \"mcs_backend\", \"MCS KConfig Backend\",\n\t\t\t\t\"Just a fake application to be able to use KConfig backend with non-KDE applications.\",\n\t\t\t\t\"9999\", false);\n\t\t\tnew KApplication(false, false);\n\t\t}\n\n\t\tout->base = &mcs_backend;\n\t\tout->mcs_priv_handle = h;\n\n\t\th->cfg = new KConfig(domain);\n\n\t\treturn out;\n\t}\n\n\tvoid\n\tmcs_kconfig_destroy(mcs_handle_t *self)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\tdelete h->cfg;\n\t\tfree(h);\n\n\t\tfree(self);\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_get_string(mcs_handle_t *self, const char *section,\n\t\t\t const char *key, char **value)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\tif ( ! h->cfg->hasGroup(section) )\n\t\t\treturn MCS_FAIL;\n\n\t\th->cfg->setGroup(section);\n\t\tif ( ! h->cfg->hasKey(key) )\n\t\t\treturn MCS_FAIL;\n\n\t\tQString entry = h->cfg->readEntry(key);\n\t\t*value = strdup(entry.latin1());\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_get_int(mcs_handle_t *self, const char *section,\n\t\t const char *key, int *value)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\tif ( ! h->cfg->hasGroup(section) )\n\t\t\treturn MCS_FAIL;\n\n\t\th->cfg->setGroup(section);\n\t\tif ( ! h->cfg->hasKey(key) )\n\t\t\treturn MCS_FAIL;\n\n\t\t*value = h->cfg->readNumEntry(key);\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_get_bool(mcs_handle_t *self, const char *section,\n\t\t\t const char *key, int *value)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\tif ( ! h->cfg->hasGroup(section) )\n\t\t\treturn MCS_FAIL;\n\n\t\th->cfg->setGroup(section);\n\t\tif ( ! h->cfg->hasKey(key) )\n\t\t\treturn MCS_FAIL;\n\n\t\t*value = h->cfg->readBoolEntry(key);\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_get_float(mcs_handle_t *self, const char *section,\n\t\t\t const char *key, float *value)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\tif ( ! h->cfg->hasGroup(section) )\n\t\t\treturn MCS_FAIL;\n\n\t\th->cfg->setGroup(section);\n\t\tif ( ! h->cfg->hasKey(key) )\n\t\t\treturn MCS_FAIL;\n\n\t\t*value = (float)(h->cfg->readDoubleNumEntry(key));\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_get_double(mcs_handle_t *self, const char *section,\n\t\t\t const char *key, double *value)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\tif ( ! h->cfg->hasGroup(section) )\n\t\t\treturn MCS_FAIL;\n\n\t\th->cfg->setGroup(section);\n\t\tif ( ! h->cfg->hasKey(key) )\n\t\t\treturn MCS_FAIL;\n\n\t\t*value = h->cfg->readDoubleNumEntry(key);\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_set_string(mcs_handle_t *self, const char *section,\n\t\t\t const char *key, const char *value)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\th->cfg->setGroup(section);\n\t\tif ( ! value )\n\t\t\th->cfg->writeEntry(key, QString::null);\n\t\telse\n\t\t\th->cfg->writeEntry(key, value);\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_set_int(mcs_handle_t *self, const char *section,\n\t\t\t const char *key, int value)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\th->cfg->setGroup(section);\n\t\th->cfg->writeEntry(key, value);\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_set_bool(mcs_handle_t *self, const char *section,\n\t\t\t const char *key, int value)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\th->cfg->setGroup(section);\n\t\th->cfg->writeEntry(key, bool(value));\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_set_float(mcs_handle_t *self, const char *section,\n\t\t\t const char *key, float value)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\th->cfg->setGroup(section);\n\t\th->cfg->writeEntry(key, value);\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_set_double(mcs_handle_t *self, const char *section,\n\t\t\t const char *key, double value)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\th->cfg->setGroup(section);\n\t\th->cfg->writeEntry(key, value);\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_unset_key(mcs_handle_t *self, const char *section,\n\t\t\t const char *key)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\th->cfg->deleteEntry(section, key);\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_list_t *\n\tmcs_kconfig_get_groups(mcs_handle_t *self)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\t\tmcs_list_t *out = NULL;\n\n\t\tQStringList list = h->cfg->groupList();\n\n\t\tfor (QStringList::const_iterator i = list.constBegin();\n\t\t\ti != list.constEnd(); i++)\n\t\t{\n\t\t\tQString str = *i;\n\n\t\t\tout = mcs_list_append(out, strdup(str.toLocal8Bit().constData()));\n\t\t}\n\n\t\treturn out;\n\t}\n};\n\nmcs_backend_t mcs_backend = {\n\tNULL,\n\t\"kconfig\",\n\tmcs_kconfig_new,\n\tmcs_kconfig_destroy,\n\n\tmcs_kconfig_get_string,\n\tmcs_kconfig_get_int,\n\tmcs_kconfig_get_bool,\n\tmcs_kconfig_get_float,\n\tmcs_kconfig_get_double,\n\n\tmcs_kconfig_set_string,\n\tmcs_kconfig_set_int,\n\tmcs_kconfig_set_bool,\n\tmcs_kconfig_set_float,\n\tmcs_kconfig_set_double,\n\n\tmcs_kconfig_unset_key,\n\n\tNULL,\n\tmcs_kconfig_get_groups\n};\nthanks for the tip Crazy_Hopper.\/*\n * This is mcs; a modular configuration system.\n *\n * Copyright (c) 2007 Diego Pettenò \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * 3. The name of the author may not be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\n * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n\nextern \"C\" {\n\n #include \"libmcs\/mcs.h\"\n\n\/* ***************************************************************** *\/\n\n extern mcs_backend_t mcs_backend;\n}\n\ntypedef struct {\n\tKConfig *cfg;\n} mcs_kconfig_handle_t;\n\nnamespace {\n\n\tmcs_handle_t *\n\tmcs_kconfig_new(char *domain)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *)calloc(sizeof(mcs_kconfig_handle_t), 1);\n\t\tmcs_handle_t *out = (mcs_handle_t *)calloc(sizeof(mcs_handle_t), 1);\n\n\t\tif (!KApplication::kApplication())\n\t\t{\n\t \t\t\/* Initialise a fake KDE application if none present *\/\n\t\t\tstatic char *fake_argv[] = { \"mcs_backend\" };\n\n\t\t\tKCmdLineArgs::init(1, fake_argv, \"mcs_backend\", \"MCS KConfig Backend\",\n\t\t\t\t\"Just a fake application to be able to use KConfig backend with non-KDE applications.\",\n\t\t\t\t\"9999\", false);\n\t\t\tnew KApplication(false, false);\n\t\t}\n\n\t\tout->base = &mcs_backend;\n\t\tout->mcs_priv_handle = h;\n\n\t\th->cfg = new KConfig(domain);\n\n\t\treturn out;\n\t}\n\n\tvoid\n\tmcs_kconfig_destroy(mcs_handle_t *self)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\tdelete h->cfg;\n\t\tfree(h);\n\n\t\tfree(self);\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_get_string(mcs_handle_t *self, const char *section,\n\t\t\t const char *key, char **value)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\tif ( ! h->cfg->hasGroup(section) )\n\t\t\treturn MCS_FAIL;\n\n\t\th->cfg->setGroup(section);\n\t\tif ( ! h->cfg->hasKey(key) )\n\t\t\treturn MCS_FAIL;\n\n\t\tQString entry = h->cfg->readEntry(key);\n\t\t*value = strdup(entry.latin1());\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_get_int(mcs_handle_t *self, const char *section,\n\t\t const char *key, int *value)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\tif ( ! h->cfg->hasGroup(section) )\n\t\t\treturn MCS_FAIL;\n\n\t\th->cfg->setGroup(section);\n\t\tif ( ! h->cfg->hasKey(key) )\n\t\t\treturn MCS_FAIL;\n\n\t\t*value = h->cfg->readNumEntry(key);\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_get_bool(mcs_handle_t *self, const char *section,\n\t\t\t const char *key, int *value)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\tif ( ! h->cfg->hasGroup(section) )\n\t\t\treturn MCS_FAIL;\n\n\t\th->cfg->setGroup(section);\n\t\tif ( ! h->cfg->hasKey(key) )\n\t\t\treturn MCS_FAIL;\n\n\t\t*value = h->cfg->readBoolEntry(key);\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_get_float(mcs_handle_t *self, const char *section,\n\t\t\t const char *key, float *value)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\tif ( ! h->cfg->hasGroup(section) )\n\t\t\treturn MCS_FAIL;\n\n\t\th->cfg->setGroup(section);\n\t\tif ( ! h->cfg->hasKey(key) )\n\t\t\treturn MCS_FAIL;\n\n\t\t*value = (float)(h->cfg->readDoubleNumEntry(key));\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_get_double(mcs_handle_t *self, const char *section,\n\t\t\t const char *key, double *value)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\tif ( ! h->cfg->hasGroup(section) )\n\t\t\treturn MCS_FAIL;\n\n\t\th->cfg->setGroup(section);\n\t\tif ( ! h->cfg->hasKey(key) )\n\t\t\treturn MCS_FAIL;\n\n\t\t*value = h->cfg->readDoubleNumEntry(key);\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_set_string(mcs_handle_t *self, const char *section,\n\t\t\t const char *key, const char *value)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\th->cfg->setGroup(section);\n\t\tif ( ! value )\n\t\t\th->cfg->writeEntry(key, QString::null);\n\t\telse\n\t\t\th->cfg->writeEntry(key, value);\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_set_int(mcs_handle_t *self, const char *section,\n\t\t\t const char *key, int value)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\th->cfg->setGroup(section);\n\t\th->cfg->writeEntry(key, value);\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_set_bool(mcs_handle_t *self, const char *section,\n\t\t\t const char *key, int value)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\th->cfg->setGroup(section);\n\t\th->cfg->writeEntry(key, bool(value));\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_set_float(mcs_handle_t *self, const char *section,\n\t\t\t const char *key, float value)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\th->cfg->setGroup(section);\n\t\th->cfg->writeEntry(key, value);\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_set_double(mcs_handle_t *self, const char *section,\n\t\t\t const char *key, double value)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\th->cfg->setGroup(section);\n\t\th->cfg->writeEntry(key, value);\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_response_t\n\tmcs_kconfig_unset_key(mcs_handle_t *self, const char *section,\n\t\t\t const char *key)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\n\t\th->cfg->deleteEntry(section, key);\n\n\t\treturn MCS_OK;\n\t}\n\n\tmcs_list_t *\n\tmcs_kconfig_get_groups(mcs_handle_t *self)\n\t{\n\t\tmcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;\n\t\tmcs_list_t *out = NULL;\n\n\t\tQStringList list = h->cfg->groupList();\n\n\t\tfor (QStringList::const_iterator i = list.constBegin();\n\t\t\ti != list.constEnd(); i++)\n\t\t{\n\t\t\tQString str = *i;\n\n\t\t\tout = mcs_list_append(out, strdup(str.local8Bit().constData()));\n\t\t}\n\n\t\treturn out;\n\t}\n};\n\nmcs_backend_t mcs_backend = {\n\tNULL,\n\t\"kconfig\",\n\tmcs_kconfig_new,\n\tmcs_kconfig_destroy,\n\n\tmcs_kconfig_get_string,\n\tmcs_kconfig_get_int,\n\tmcs_kconfig_get_bool,\n\tmcs_kconfig_get_float,\n\tmcs_kconfig_get_double,\n\n\tmcs_kconfig_set_string,\n\tmcs_kconfig_set_int,\n\tmcs_kconfig_set_bool,\n\tmcs_kconfig_set_float,\n\tmcs_kconfig_set_double,\n\n\tmcs_kconfig_unset_key,\n\n\tNULL,\n\tmcs_kconfig_get_groups\n};\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing stan::gm::argument;\nusing stan::gm::arg_id;\nusing stan::gm::arg_data;\nusing stan::gm::arg_init;\nusing stan::gm::arg_random;\nusing stan::gm::arg_output;\nusing stan::gm::argument_parser;\nusing stan::gm::error_codes;\n\nclass StanGmArgumentsArgumentParser : public testing::Test {\npublic:\n void SetUp() {\n \/\/ copied setup from src\/stan\/gm\/command.hpp\n \/\/ FIXME: move to factory?\n valid_arguments.push_back(new arg_id());\n valid_arguments.push_back(new arg_data());\n valid_arguments.push_back(new arg_init());\n valid_arguments.push_back(new arg_random());\n valid_arguments.push_back(new arg_output());\n \n parser = new argument_parser(valid_arguments);\n }\n void TearDown() {\n for (int i = 0; i < valid_arguments.size(); ++i)\n delete valid_arguments.at(i);\n delete(parser);\n }\n \n std::vector valid_arguments;\n argument_parser* parser;\n int err_code;\n boost::iostreams::stream< boost::iostreams::null_sink > null_ostream;\n};\n\n \nTEST_F(StanGmArgumentsArgumentParser, default) {\n const char* argv[] = {};\n int argc = 0;\n \n err_code = parser->parse_args(argc, argv, &null_ostream, &null_ostream);\n EXPECT_EQ(int(error_codes::USAGE), err_code);\n}\n\nTEST_F(StanGmArgumentsArgumentParser, help) {\n const char* argv[] = {\"help\"};\n int argc = 1;\n \n err_code = parser->parse_args(argc, argv, &null_ostream, &null_ostream);\n EXPECT_EQ(int(error_codes::OK), err_code);\n}\n\nTEST_F(StanGmArgumentsArgumentParser, unrecognized_argument) {\n const char* argv[] = {\"foo\"};\n int argc = 1;\n \n err_code = parser->parse_args(argc, argv, &null_ostream, &null_ostream);\n EXPECT_EQ(int(error_codes::USAGE), err_code);\n}\nFixed argument_parser_test to account for argv requiring that the first element be the executable name#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing stan::gm::argument;\nusing stan::gm::arg_id;\nusing stan::gm::arg_data;\nusing stan::gm::arg_init;\nusing stan::gm::arg_random;\nusing stan::gm::arg_output;\nusing stan::gm::argument_parser;\nusing stan::gm::error_codes;\n\nclass StanGmArgumentsArgumentParser : public testing::Test {\npublic:\n void SetUp() {\n \/\/ copied setup from src\/stan\/gm\/command.hpp\n \/\/ FIXME: move to factory?\n valid_arguments.push_back(new arg_id());\n valid_arguments.push_back(new arg_data());\n valid_arguments.push_back(new arg_init());\n valid_arguments.push_back(new arg_random());\n valid_arguments.push_back(new arg_output());\n \n parser = new argument_parser(valid_arguments);\n }\n void TearDown() {\n for (int i = 0; i < valid_arguments.size(); ++i)\n delete valid_arguments.at(i);\n delete(parser);\n }\n \n std::vector valid_arguments;\n argument_parser* parser;\n int err_code;\n boost::iostreams::stream< boost::iostreams::null_sink > null_ostream;\n};\n\n \nTEST_F(StanGmArgumentsArgumentParser, default) {\n const char* argv[] = {};\n int argc = 0;\n \n err_code = parser->parse_args(argc, argv, &null_ostream, &null_ostream);\n EXPECT_EQ(int(error_codes::USAGE), err_code);\n}\n\nTEST_F(StanGmArgumentsArgumentParser, help) {\n const char* argv[] = {\"model_name\", \"help\"};\n int argc = 2;\n \n err_code = parser->parse_args(argc, argv, &null_ostream, &null_ostream);\n EXPECT_EQ(int(error_codes::OK), err_code);\n}\n\nTEST_F(StanGmArgumentsArgumentParser, unrecognized_argument) {\n const char* argv[] = {\"foo\"};\n int argc = 1;\n \n err_code = parser->parse_args(argc, argv, &null_ostream, &null_ostream);\n EXPECT_EQ(int(error_codes::USAGE), err_code);\n}\n<|endoftext|>"} {"text":"#include \"counter.h\"\n\nnamespace best_documenter {\n Counter::Counter(std::shared_ptr github) {\n github_ = github;\n }\n\n Counter::~Counter() {\n }\n\n std::shared_ptr Counter::compute() {\n auto result = std::make_shared();\n\n for (auto& repo : repos_) {\n auto commits = github->fetchReposCommits(\"pine613\", \"dotfiles\", &err);\n if (!err.empty()) std::cout << err << std::endl;\n }\n\n return result;\n }\n\n GitHubCommitArrayPtr Counter::fetchReposCommits(\n const std::string& repo,\n std::string* err\n )\n {\n auto slashPos = repo.find('\/');\n\n if (slashPos == std::string::npos) {\n *err = \"Invalid repository name\";\n return GitHubCommitArrayPtr();\n }\n\n auto owner = repo.substr(0, repo.find('\/'));\n auto name = repo.substr(repo.find('\/') + 1);\n auto commits = github_->fetchReposCommits(\n std::move(owner),\n std::move(name),\n err);\n\n return std::move(commits);\n }\n}\nfix(counter): fix compile errors#include \"counter.h\"\n\nnamespace best_documenter {\n Counter::Counter(std::shared_ptr github) {\n github_ = github;\n }\n\n Counter::~Counter() {\n }\n\n std::shared_ptr Counter::compute() {\n auto result = std::make_shared();\n std::string err;\n\n for (auto& repo : repos_) {\n auto commits = github_->fetchReposCommits(\"pine613\", \"dotfiles\", &err);\n if (!err.empty()) {\n std::cout << err << std::endl;\n return result;\n }\n }\n\n return std::move(result);\n }\n\n GitHubCommitArrayPtr Counter::fetchReposCommits(\n const std::string& repo,\n std::string* err\n )\n {\n auto slashPos = repo.find('\/');\n\n if (slashPos == std::string::npos) {\n *err = \"Invalid repository name\";\n return GitHubCommitArrayPtr();\n }\n\n auto owner = repo.substr(0, repo.find('\/'));\n auto name = repo.substr(repo.find('\/') + 1);\n auto commits = github_->fetchReposCommits(\n std::move(owner),\n std::move(name),\n err);\n\n return std::move(commits);\n }\n}\n<|endoftext|>"} {"text":"\/*===================================================================\n\n The Medical Imaging Interaction Toolkit (MITK)\n\n Copyright (c) German Cancer Research Center,\n Division of Medical and Biological Informatics.\n All rights reserved.\n\n This software is distributed WITHOUT ANY WARRANTY; without\n even the implied warranty of MERCHANTABILITY or FITNESS FOR\n A PARTICULAR PURPOSE.\n\n See LICENSE.txt or http:\/\/www.mitk.org for details.\n\n ===================================================================*\/\n\n#include \"mitkEventFactory.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace\n{\n std::vector &split(const std::string &s, char delim, std::vector &elems)\n {\n std::stringstream ss(s);\n std::string item;\n while (std::getline(ss, item, delim))\n {\n elems.push_back(item);\n }\n return elems;\n }\n\n std::vector split(const std::string &s, char delim)\n {\n std::vector < std::string > elems;\n return split(s, delim, elems);\n }\n}\n\nmitk::InteractionEvent::Pointer mitk::EventFactory::CreateEvent(PropertyList::Pointer list)\n{\n\/\/\n std::string eventClass, eventVariant;\n list->GetStringProperty(InteractionEventConst::xmlParameterEventClass().c_str(), eventClass);\n list->GetStringProperty(InteractionEventConst::xmlParameterEventVariant().c_str(), eventVariant);\n\n\/\/ Query all possible attributes, if they are not present, set their default values.\n\/\/ Position Events & Key Events\n std::string strModifiers;\n InteractionEvent::ModifierKeys modifiers = InteractionEvent::NoKey;\n std::string strEventButton;\n InteractionEvent::MouseButtons eventButton = InteractionEvent::NoButton;\n std::string strButtonState;\n InteractionEvent::MouseButtons buttonState = InteractionEvent::NoButton;\n std::string strKey;\n std::string key;\n std::string strWheelDelta;\n int wheelDelta;\n std::string strSignalName = \"\";\n\n Point2D pos;\n pos.Fill(0);\n\n\/\/ Parse modifier information\n if (list->GetStringProperty(InteractionEventConst::xmlEventPropertyModifier().c_str(), strModifiers))\n {\n std::vector mods = split(strModifiers, ',');\n for (std::vector::iterator it = mods.begin(); it != mods.end(); ++it)\n {\n std::transform((*it).begin(), (*it).end(), (*it).begin(), ::toupper);\n if (*it == \"CTRL\")\n {\n modifiers = modifiers | InteractionEvent::ControlKey;\n }\n else if (*it == \"ALT\")\n {\n modifiers = modifiers | InteractionEvent::AltKey;\n }\n else if (*it == \"SHIFT\")\n {\n modifiers = modifiers | InteractionEvent::ShiftKey;\n }\n else\n {\n MITK_WARN<< \"mitkEventFactory: Invalid event modifier in config file :\" << (*it);\n }\n }\n }\n\n\/\/ Set EventButton\n if (list->GetStringProperty(InteractionEventConst::xmlEventPropertyEventButton().c_str(), strEventButton))\n {\n std::transform(strEventButton.begin(), strEventButton.end(), strEventButton.begin(), ::toupper);\n if (strEventButton == \"MIDDLEMOUSEBUTTON\")\n {\n eventButton = InteractionEvent::MiddleMouseButton;\n }\n else if (strEventButton == \"LEFTMOUSEBUTTON\")\n {\n eventButton = InteractionEvent::LeftMouseButton;\n }\n else if (strEventButton == \"RIGHTMOUSEBUTTON\")\n {\n eventButton = InteractionEvent::RightMouseButton;\n }\n else\n {\n MITK_WARN<< \"mitkEventFactory: Invalid event button in config file: \" << strEventButton;\n }\n }\n\n\/\/ Parse ButtonStates\n if (list->GetStringProperty(InteractionEventConst::xmlEventPropertyButtonState().c_str(), strButtonState))\n {\n std::vector mods = split(strButtonState, ',');\n for (std::vector::iterator it = mods.begin(); it != mods.end(); ++it)\n {\n std::transform((*it).begin(), (*it).end(), (*it).begin(), ::toupper);\n if (*it == \"MIDDLEMOUSEBUTTON\")\n {\n buttonState = buttonState | InteractionEvent::MiddleMouseButton;\n }\n else if (*it == \"LEFTMOUSEBUTTON\")\n {\n buttonState = buttonState | InteractionEvent::LeftMouseButton;\n }\n else if (*it == \"RIGHTMOUSEBUTTON\")\n {\n buttonState = buttonState | InteractionEvent::RightMouseButton;\n }\n else\n {\n MITK_WARN<< \"mitkEventFactory: Invalid event buttonstate in config file:\" << (*it);\n }\n }\n }\n\n\/\/ Key\n if (!list->GetStringProperty(InteractionEventConst::xmlEventPropertyKey().c_str(), strKey))\n {\n key = \"\";\n }\n else\n {\n key = strKey;\n }\n\/\/ WheelDelta\n if (!list->GetStringProperty(InteractionEventConst::xmlEventPropertyScrollDirection().c_str(), strWheelDelta))\n {\n wheelDelta = 0;\n }\n else\n {\n std::transform(strWheelDelta.begin(), strWheelDelta.end(), strWheelDelta.begin(), ::toupper);\n if (strWheelDelta == \"DOWN\")\n {\n wheelDelta = -1;\n }\n else\n {\n wheelDelta = 1;\n }\n }\n\/\/ Internal Signals Name\n list->GetStringProperty(InteractionEventConst::xmlEventPropertySignalName().c_str(), strSignalName);\n\n \/*\n * Here the objects are created\n *\/\n\n mitk::InteractionEvent::Pointer event;\n std::transform(eventClass.begin(), eventClass.end(), eventClass.begin(), ::toupper);\n\n if (eventClass == \"MOUSEPRESSEVENT\")\n {\n \/\/ buttonstates incorporate the event button (as in Qt)\n buttonState = buttonState | eventButton;\n event = MousePressEvent::New(NULL, pos, buttonState, modifiers, eventButton);\n }\n else if (eventClass == \"MOUSEMOVEEVENT\")\n {\n event = MouseMoveEvent::New(NULL, pos, buttonState, modifiers);\n }\n else if (eventClass == \"MOUSERELEASEEVENT\")\n {\n event = MouseReleaseEvent::New(NULL, pos, buttonState, modifiers, eventButton);\n }\n else if (eventClass == \"INTERACTIONKEYEVENT\")\n {\n event = InteractionKeyEvent::New(NULL, key, modifiers);\n }\n else if (eventClass == \"MOUSEWHEELEVENT\")\n {\n event = MouseWheelEvent::New(NULL, pos, buttonState, modifiers, wheelDelta);\n }\n else if (eventClass == \"INTERACTIONPOSITIONEVENT\")\n {\n event = InteractionPositionEvent::New(NULL, pos);\n }\n else if (eventClass == \"INTERNALEVENT\")\n {\n event = InternalEvent::New(NULL, NULL, strSignalName);\n }\n else if (eventClass == \"INTERACTIONEVENT\")\n {\n event = InteractionEvent::New(NULL);\n }\n if (event.IsNull())\n {\n MITK_WARN<< \"Event couldn't be constructed. Please check your StateMachine patterns and config files\\n for the following event class, which is not valid: \" << eventClass;\n return NULL;\n }\n return event;\n}\nadded mousedoubleclick event to EventFactory\/*===================================================================\n\n The Medical Imaging Interaction Toolkit (MITK)\n\n Copyright (c) German Cancer Research Center,\n Division of Medical and Biological Informatics.\n All rights reserved.\n\n This software is distributed WITHOUT ANY WARRANTY; without\n even the implied warranty of MERCHANTABILITY or FITNESS FOR\n A PARTICULAR PURPOSE.\n\n See LICENSE.txt or http:\/\/www.mitk.org for details.\n\n ===================================================================*\/\n\n#include \"mitkEventFactory.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace\n{\n std::vector &split(const std::string &s, char delim, std::vector &elems)\n {\n std::stringstream ss(s);\n std::string item;\n while (std::getline(ss, item, delim))\n {\n elems.push_back(item);\n }\n return elems;\n }\n\n std::vector split(const std::string &s, char delim)\n {\n std::vector < std::string > elems;\n return split(s, delim, elems);\n }\n}\n\nmitk::InteractionEvent::Pointer mitk::EventFactory::CreateEvent(PropertyList::Pointer list)\n{\n\/\/\n std::string eventClass, eventVariant;\n list->GetStringProperty(InteractionEventConst::xmlParameterEventClass().c_str(), eventClass);\n list->GetStringProperty(InteractionEventConst::xmlParameterEventVariant().c_str(), eventVariant);\n\n\/\/ Query all possible attributes, if they are not present, set their default values.\n\/\/ Position Events & Key Events\n std::string strModifiers;\n InteractionEvent::ModifierKeys modifiers = InteractionEvent::NoKey;\n std::string strEventButton;\n InteractionEvent::MouseButtons eventButton = InteractionEvent::NoButton;\n std::string strButtonState;\n InteractionEvent::MouseButtons buttonState = InteractionEvent::NoButton;\n std::string strKey;\n std::string key;\n std::string strWheelDelta;\n int wheelDelta;\n std::string strSignalName = \"\";\n\n Point2D pos;\n pos.Fill(0);\n\n\/\/ Parse modifier information\n if (list->GetStringProperty(InteractionEventConst::xmlEventPropertyModifier().c_str(), strModifiers))\n {\n std::vector mods = split(strModifiers, ',');\n for (std::vector::iterator it = mods.begin(); it != mods.end(); ++it)\n {\n std::transform((*it).begin(), (*it).end(), (*it).begin(), ::toupper);\n if (*it == \"CTRL\")\n {\n modifiers = modifiers | InteractionEvent::ControlKey;\n }\n else if (*it == \"ALT\")\n {\n modifiers = modifiers | InteractionEvent::AltKey;\n }\n else if (*it == \"SHIFT\")\n {\n modifiers = modifiers | InteractionEvent::ShiftKey;\n }\n else\n {\n MITK_WARN<< \"mitkEventFactory: Invalid event modifier in config file :\" << (*it);\n }\n }\n }\n\n\/\/ Set EventButton\n if (list->GetStringProperty(InteractionEventConst::xmlEventPropertyEventButton().c_str(), strEventButton))\n {\n std::transform(strEventButton.begin(), strEventButton.end(), strEventButton.begin(), ::toupper);\n if (strEventButton == \"MIDDLEMOUSEBUTTON\")\n {\n eventButton = InteractionEvent::MiddleMouseButton;\n }\n else if (strEventButton == \"LEFTMOUSEBUTTON\")\n {\n eventButton = InteractionEvent::LeftMouseButton;\n }\n else if (strEventButton == \"RIGHTMOUSEBUTTON\")\n {\n eventButton = InteractionEvent::RightMouseButton;\n }\n else\n {\n MITK_WARN<< \"mitkEventFactory: Invalid event button in config file: \" << strEventButton;\n }\n }\n\n\/\/ Parse ButtonStates\n if (list->GetStringProperty(InteractionEventConst::xmlEventPropertyButtonState().c_str(), strButtonState))\n {\n std::vector mods = split(strButtonState, ',');\n for (std::vector::iterator it = mods.begin(); it != mods.end(); ++it)\n {\n std::transform((*it).begin(), (*it).end(), (*it).begin(), ::toupper);\n if (*it == \"MIDDLEMOUSEBUTTON\")\n {\n buttonState = buttonState | InteractionEvent::MiddleMouseButton;\n }\n else if (*it == \"LEFTMOUSEBUTTON\")\n {\n buttonState = buttonState | InteractionEvent::LeftMouseButton;\n }\n else if (*it == \"RIGHTMOUSEBUTTON\")\n {\n buttonState = buttonState | InteractionEvent::RightMouseButton;\n }\n else\n {\n MITK_WARN<< \"mitkEventFactory: Invalid event buttonstate in config file:\" << (*it);\n }\n }\n }\n\n\/\/ Key\n if (!list->GetStringProperty(InteractionEventConst::xmlEventPropertyKey().c_str(), strKey))\n {\n key = \"\";\n }\n else\n {\n key = strKey;\n }\n\/\/ WheelDelta\n if (!list->GetStringProperty(InteractionEventConst::xmlEventPropertyScrollDirection().c_str(), strWheelDelta))\n {\n wheelDelta = 0;\n }\n else\n {\n std::transform(strWheelDelta.begin(), strWheelDelta.end(), strWheelDelta.begin(), ::toupper);\n if (strWheelDelta == \"DOWN\")\n {\n wheelDelta = -1;\n }\n else\n {\n wheelDelta = 1;\n }\n }\n\/\/ Internal Signals Name\n list->GetStringProperty(InteractionEventConst::xmlEventPropertySignalName().c_str(), strSignalName);\n\n \/*\n * Here the objects are created\n *\/\n\n mitk::InteractionEvent::Pointer event;\n std::transform(eventClass.begin(), eventClass.end(), eventClass.begin(), ::toupper);\n\n if (eventClass == \"MOUSEPRESSEVENT\")\n {\n \/\/ buttonstates incorporate the event button (as in Qt)\n buttonState = buttonState | eventButton;\n event = MousePressEvent::New(NULL, pos, buttonState, modifiers, eventButton);\n }\n else if (eventClass == \"MOUSEDOUBLECLICKEVENT\")\n {\n buttonState = buttonState | eventButton;\n event = MouseDoubleClickEvent::New(NULL, pos, buttonState, modifiers, eventButton);\n }\n else if (eventClass == \"MOUSEMOVEEVENT\")\n {\n event = MouseMoveEvent::New(NULL, pos, buttonState, modifiers);\n }\n else if (eventClass == \"MOUSERELEASEEVENT\")\n {\n event = MouseReleaseEvent::New(NULL, pos, buttonState, modifiers, eventButton);\n }\n else if (eventClass == \"INTERACTIONKEYEVENT\")\n {\n event = InteractionKeyEvent::New(NULL, key, modifiers);\n }\n else if (eventClass == \"MOUSEWHEELEVENT\")\n {\n event = MouseWheelEvent::New(NULL, pos, buttonState, modifiers, wheelDelta);\n }\n else if (eventClass == \"INTERACTIONPOSITIONEVENT\")\n {\n event = InteractionPositionEvent::New(NULL, pos);\n }\n else if (eventClass == \"INTERNALEVENT\")\n {\n event = InternalEvent::New(NULL, NULL, strSignalName);\n }\n else if (eventClass == \"INTERACTIONEVENT\")\n {\n event = InteractionEvent::New(NULL);\n }\n if (event.IsNull())\n {\n MITK_WARN<< \"Event couldn't be constructed. Please check your StateMachine patterns and config files\\n for the following event class, which is not valid: \" << eventClass;\n return NULL;\n }\n return event;\n}\n<|endoftext|>"} {"text":"#pragma once\n#include \"neural_network.hpp\"\n\nnamespace Hippocrates::Trained {\n\ntemplate\nclass Classifier : public NeuralNetwork {\npublic:\n\tusing NeuralNetwork::NeuralNetwork;\n\tClassifier() : NeuralNetwork(){ };\n\tClassifier(const NeuralNetwork& other) : NeuralNetwork(other){};\n\tClassifier(NeuralNetwork&& other) : NeuralNetwork(std::move(other)){};\n\n\tauto Classify(const Type::neuron_values_t& inputs) {\n\t\tconst auto outputs = GetOutputsUsingInputs(inputs);\n\t\tconst auto maxOutput = std::max_element(outputs.begin(), outputs.end());\n\t\tconst auto outputIndex = std::distance(outputs.begin(), maxOutput);\n\t\treturn static_cast(outputIndex);\n\t}\n};\n\n}\nAdd dependency#pragma once\n#include \n#include \"neural_network.hpp\"\n\nnamespace Hippocrates::Trained {\n\ntemplate\nclass Classifier : public NeuralNetwork {\npublic:\n\tusing NeuralNetwork::NeuralNetwork;\n\tClassifier() : NeuralNetwork(){ };\n\tClassifier(const NeuralNetwork& other) : NeuralNetwork(other){};\n\tClassifier(NeuralNetwork&& other) : NeuralNetwork(std::move(other)){};\n\n\tauto Classify(const Type::neuron_values_t& inputs) {\n\t\tconst auto outputs = GetOutputsUsingInputs(inputs);\n\t\tconst auto maxOutput = std::max_element(outputs.begin(), outputs.end());\n\t\tconst auto outputIndex = std::distance(outputs.begin(), maxOutput);\n\t\treturn static_cast(outputIndex);\n\t}\n};\n\n}\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: postgis.cc 44 2005-04-22 18:53:54Z pavlenko $\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"connection_manager.hpp\"\n#include \"postgis.hpp\"\n\nDATASOURCE_PLUGIN(postgis_datasource)\n\nconst std::string postgis_datasource::GEOMETRY_COLUMNS=\"geometry_columns\";\nconst std::string postgis_datasource::SPATIAL_REF_SYS=\"spatial_ref_system\";\n\nusing std::clog;\nusing std::endl;\n\nusing boost::lexical_cast;\nusing boost::bad_lexical_cast;\nusing boost::shared_ptr;\n\npostgis_datasource::postgis_datasource(parameters const& params)\n : datasource (params),\n table_(params.get(\"table\")),\n type_(datasource::Vector),\n extent_initialized_(false),\n desc_(params.get(\"type\")),\n creator_(params.get(\"host\"),\n params.get(\"port\"),\n params.get(\"dbname\"),\n params.get(\"user\"),\n params.get(\"password\")) \n{ \n\n unsigned initial_size;\n unsigned max_size;\n \n try \n {\n initial_size = boost::lexical_cast(params_.get(\"initial_size\")); \n }\n catch (bad_lexical_cast& )\n {\n initial_size = 1;\n }\n \n try \n {\n max_size = boost::lexical_cast(params_.get(\"max_size\")); \n }\n catch (bad_lexical_cast&)\n {\n max_size = 10;\n }\n \n ConnectionManager *mgr=ConnectionManager::instance(); \n mgr->registerPool(creator_, initial_size, max_size);\n \n shared_ptr > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr conn = pool->borrowObject();\n if (conn && conn->isOK())\n {\n PoolGuard,shared_ptr > > guard(conn,pool);\n std::string table_name=table_from_sql(table_);\n std::ostringstream s;\n s << \"select f_geometry_column,srid,type from \";\n s << GEOMETRY_COLUMNS <<\" where f_table_name='\" << table_name<<\"'\";\n \n shared_ptr rs=conn->executeQuery(s.str());\n \n if (rs->next())\n {\n try \n {\n srid_ = lexical_cast(rs->getValue(\"srid\"));\n desc_.set_srid(srid_);\n }\n catch (bad_lexical_cast &ex)\n {\n clog << ex.what() << endl;\n }\n geometryColumn_=rs->getValue(\"f_geometry_column\");\n std::string postgisType=rs->getValue(\"type\");\n }\n rs->close();\n \n \/\/ collect attribute desc\n s.str(\"\");\n s << \"select * from \"<executeQuery(s.str());\n if (rs->next())\n {\n int count = rs->getNumFields();\n for (int i=0;igetFieldName(i);\n int length = rs->getFieldLength(i);\n\t\t \n int type_oid = rs->getTypeOID(i);\n switch (type_oid)\n {\n case 21: \/\/ int2\n case 23: \/\/ int4\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer,false,length));\n break;\n case 700: \/\/ float4 \n case 701: \/\/ float8\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double,false,length));\n case 1042: \/\/ bpchar\n case 1043: \/\/ varchar\n case 25: \/\/ text\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));\n break;\n default: \/\/ shouldn't get here\n#ifdef MAPNIK_DEBUG\n clog << \"unknown type_oid=\"< const& box=q.get_bbox();\n ConnectionManager *mgr=ConnectionManager::instance();\n shared_ptr > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr conn = pool->borrowObject();\n if (conn && conn->isOK())\n { \n PoolGuard,shared_ptr > > guard(conn,pool);\n std::ostringstream s;\n \n s << \"select asbinary(\"< const& props=q.property_names();\n std::set::const_iterator pos=props.begin();\n std::set::const_iterator end=props.end();\n while (pos != end)\n {\n s <<\",\\\"\"<<*pos<<\"\\\"\";\n ++pos;\n }\t \n s << \" from \" << table_<<\" where \"< rs=conn->executeQuery(s.str(),1);\n return featureset_ptr(new postgis_featureset(rs,props.size()));\n }\n }\n return featureset_ptr();\n}\n\nfeatureset_ptr postgis_datasource::features_at_point(coord2d const& pt) const\n{\n ConnectionManager *mgr=ConnectionManager::instance();\n shared_ptr > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr conn = pool->borrowObject();\n if (conn && conn->isOK())\n { \n PoolGuard,shared_ptr > > guard(conn,pool);\n std::ostringstream s;\n \n s << \"select asbinary(\" << geometryColumn_ << \") as geom\";\n \n std::vector::const_iterator itr = desc_.get_descriptors().begin();\n std::vector::const_iterator end = desc_.get_descriptors().end();\n unsigned size=0;\n while (itr != end)\n {\n s <<\",\\\"\"<< itr->get_name() << \"\\\"\";\n ++itr;\n ++size;\n }\n \n s << \" from \" << table_<<\" where \"< rs=conn->executeQuery(s.str(),1);\n return featureset_ptr(new postgis_featureset(rs, size));\n }\n }\n return featureset_ptr();\n}\n\nEnvelope postgis_datasource::envelope() const\n{\n if (extent_initialized_) return extent_;\n \n ConnectionManager *mgr=ConnectionManager::instance();\n shared_ptr > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr conn = pool->borrowObject();\n if (conn && conn->isOK())\n {\n std::ostringstream s;\n std::string table_name = table_from_sql(table_);\n if (params_.get(\"estimate_extent\") == \"true\")\n {\n s << \"select xmin(ext),ymin(ext),xmax(ext),ymax(ext)\"\n << \" from (select estimated_extent('\" \n << table_name <<\"','\" \n << geometryColumn_ << \"') as ext) as tmp\";\n }\n else \n {\n s << \"select xmin(ext),ymin(ext),xmax(ext),ymax(ext)\"\n << \" from (select extent(\" < rs=conn->executeQuery(s.str());\n if (rs->next())\n {\n try \n {\n double lox=lexical_cast(rs->getValue(0));\n double loy=lexical_cast(rs->getValue(1));\n double hix=lexical_cast(rs->getValue(2));\n double hiy=lexical_cast(rs->getValue(3));\t\t \n extent_.init(lox,loy,hix,hiy);\n extent_initialized_ = true;\n }\n catch (bad_lexical_cast &ex)\n {\n clog << ex.what() << endl;\n }\n }\n rs->close();\n }\n }\n return extent_;\n}\n\npostgis_datasource::~postgis_datasource() {}\nappend namespace to 'transform' to support buiding with STLport.\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: postgis.cc 44 2005-04-22 18:53:54Z pavlenko $\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"connection_manager.hpp\"\n#include \"postgis.hpp\"\n\nDATASOURCE_PLUGIN(postgis_datasource)\n\nconst std::string postgis_datasource::GEOMETRY_COLUMNS=\"geometry_columns\";\nconst std::string postgis_datasource::SPATIAL_REF_SYS=\"spatial_ref_system\";\n\nusing std::clog;\nusing std::endl;\n\nusing boost::lexical_cast;\nusing boost::bad_lexical_cast;\nusing boost::shared_ptr;\n\npostgis_datasource::postgis_datasource(parameters const& params)\n : datasource (params),\n table_(params.get(\"table\")),\n type_(datasource::Vector),\n extent_initialized_(false),\n desc_(params.get(\"type\")),\n creator_(params.get(\"host\"),\n params.get(\"port\"),\n params.get(\"dbname\"),\n params.get(\"user\"),\n params.get(\"password\")) \n{ \n\n unsigned initial_size;\n unsigned max_size;\n \n try \n {\n initial_size = boost::lexical_cast(params_.get(\"initial_size\")); \n }\n catch (bad_lexical_cast& )\n {\n initial_size = 1;\n }\n \n try \n {\n max_size = boost::lexical_cast(params_.get(\"max_size\")); \n }\n catch (bad_lexical_cast&)\n {\n max_size = 10;\n }\n \n ConnectionManager *mgr=ConnectionManager::instance(); \n mgr->registerPool(creator_, initial_size, max_size);\n \n shared_ptr > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr conn = pool->borrowObject();\n if (conn && conn->isOK())\n {\n PoolGuard,shared_ptr > > guard(conn,pool);\n std::string table_name=table_from_sql(table_);\n std::ostringstream s;\n s << \"select f_geometry_column,srid,type from \";\n s << GEOMETRY_COLUMNS <<\" where f_table_name='\" << table_name<<\"'\";\n \n shared_ptr rs=conn->executeQuery(s.str());\n \n if (rs->next())\n {\n try \n {\n srid_ = lexical_cast(rs->getValue(\"srid\"));\n desc_.set_srid(srid_);\n }\n catch (bad_lexical_cast &ex)\n {\n clog << ex.what() << endl;\n }\n geometryColumn_=rs->getValue(\"f_geometry_column\");\n std::string postgisType=rs->getValue(\"type\");\n }\n rs->close();\n \n \/\/ collect attribute desc\n s.str(\"\");\n s << \"select * from \"<executeQuery(s.str());\n if (rs->next())\n {\n int count = rs->getNumFields();\n for (int i=0;igetFieldName(i);\n int length = rs->getFieldLength(i);\n\t\t \n int type_oid = rs->getTypeOID(i);\n switch (type_oid)\n {\n case 21: \/\/ int2\n case 23: \/\/ int4\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer,false,length));\n break;\n case 700: \/\/ float4 \n case 701: \/\/ float8\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double,false,length));\n case 1042: \/\/ bpchar\n case 1043: \/\/ varchar\n case 25: \/\/ text\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));\n break;\n default: \/\/ shouldn't get here\n#ifdef MAPNIK_DEBUG\n clog << \"unknown type_oid=\"< const& box=q.get_bbox();\n ConnectionManager *mgr=ConnectionManager::instance();\n shared_ptr > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr conn = pool->borrowObject();\n if (conn && conn->isOK())\n { \n PoolGuard,shared_ptr > > guard(conn,pool);\n std::ostringstream s;\n \n s << \"select asbinary(\"< const& props=q.property_names();\n std::set::const_iterator pos=props.begin();\n std::set::const_iterator end=props.end();\n while (pos != end)\n {\n s <<\",\\\"\"<<*pos<<\"\\\"\";\n ++pos;\n }\t \n s << \" from \" << table_<<\" where \"< rs=conn->executeQuery(s.str(),1);\n return featureset_ptr(new postgis_featureset(rs,props.size()));\n }\n }\n return featureset_ptr();\n}\n\nfeatureset_ptr postgis_datasource::features_at_point(coord2d const& pt) const\n{\n ConnectionManager *mgr=ConnectionManager::instance();\n shared_ptr > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr conn = pool->borrowObject();\n if (conn && conn->isOK())\n { \n PoolGuard,shared_ptr > > guard(conn,pool);\n std::ostringstream s;\n \n s << \"select asbinary(\" << geometryColumn_ << \") as geom\";\n \n std::vector::const_iterator itr = desc_.get_descriptors().begin();\n std::vector::const_iterator end = desc_.get_descriptors().end();\n unsigned size=0;\n while (itr != end)\n {\n s <<\",\\\"\"<< itr->get_name() << \"\\\"\";\n ++itr;\n ++size;\n }\n \n s << \" from \" << table_<<\" where \"< rs=conn->executeQuery(s.str(),1);\n return featureset_ptr(new postgis_featureset(rs, size));\n }\n }\n return featureset_ptr();\n}\n\nEnvelope postgis_datasource::envelope() const\n{\n if (extent_initialized_) return extent_;\n \n ConnectionManager *mgr=ConnectionManager::instance();\n shared_ptr > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr conn = pool->borrowObject();\n if (conn && conn->isOK())\n {\n std::ostringstream s;\n std::string table_name = table_from_sql(table_);\n if (params_.get(\"estimate_extent\") == \"true\")\n {\n s << \"select xmin(ext),ymin(ext),xmax(ext),ymax(ext)\"\n << \" from (select estimated_extent('\" \n << table_name <<\"','\" \n << geometryColumn_ << \"') as ext) as tmp\";\n }\n else \n {\n s << \"select xmin(ext),ymin(ext),xmax(ext),ymax(ext)\"\n << \" from (select extent(\" < rs=conn->executeQuery(s.str());\n if (rs->next())\n {\n try \n {\n double lox=lexical_cast(rs->getValue(0));\n double loy=lexical_cast(rs->getValue(1));\n double hix=lexical_cast(rs->getValue(2));\n double hiy=lexical_cast(rs->getValue(3));\t\t \n extent_.init(lox,loy,hix,hiy);\n extent_initialized_ = true;\n }\n catch (bad_lexical_cast &ex)\n {\n clog << ex.what() << endl;\n }\n }\n rs->close();\n }\n }\n return extent_;\n}\n\npostgis_datasource::~postgis_datasource() {}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2013-2017, Matt Godbolt\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#include \"internal\/PageRequest.h\"\n\n#include \n#include \n\nnamespace seasocks {\n\nPageRequest::PageRequest(\n const sockaddr_in& remoteAddress,\n const std::string& requestUri,\n Server& server,\n Verb verb,\n HeaderMap&& headers)\n : _credentials(std::make_shared()),\n _remoteAddress(remoteAddress),\n _requestUri(requestUri),\n _server(server),\n _verb(verb),\n _headers(std::move(headers)),\n _contentLength(getUintHeader(\"Content-Length\")) {\n}\n\nbool PageRequest::consumeContent(std::vector& buffer) {\n if (buffer.size() < _contentLength) {\n return false;\n }\n if (buffer.size() == _contentLength) {\n _content.swap(buffer);\n } else {\n _content.assign(buffer.begin(), buffer.begin() + _contentLength);\n buffer.erase(buffer.begin(), buffer.begin() + _contentLength);\n }\n return true;\n}\n\nsize_t PageRequest::getUintHeader(const std::string& name) const {\n const auto iter = _headers.find(name);\n if (iter == _headers.end()) {\n return 0u;\n }\n try {\n const auto val = std::stoi(iter->second);\n } catch (const std::logic_error&) {\n return 0u;\n }\n if (val < 0) {\n return 0u;\n }\n return static_cast(val);\n}\n\n} \/\/ namespace seasocks\nFix variable scope\/\/ Copyright (c) 2013-2017, Matt Godbolt\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#include \"internal\/PageRequest.h\"\n\n#include \n#include \n#include \n\nnamespace seasocks {\n\nPageRequest::PageRequest(\n const sockaddr_in& remoteAddress,\n const std::string& requestUri,\n Server& server,\n Verb verb,\n HeaderMap&& headers)\n : _credentials(std::make_shared()),\n _remoteAddress(remoteAddress),\n _requestUri(requestUri),\n _server(server),\n _verb(verb),\n _headers(std::move(headers)),\n _contentLength(getUintHeader(\"Content-Length\")) {\n}\n\nbool PageRequest::consumeContent(std::vector& buffer) {\n if (buffer.size() < _contentLength) {\n return false;\n }\n if (buffer.size() == _contentLength) {\n _content.swap(buffer);\n } else {\n _content.assign(buffer.begin(), buffer.begin() + _contentLength);\n buffer.erase(buffer.begin(), buffer.begin() + _contentLength);\n }\n return true;\n}\n\nsize_t PageRequest::getUintHeader(const std::string& name) const {\n const auto iter = _headers.find(name);\n if (iter == _headers.end()) {\n return 0u;\n }\n try {\n return std::max(std::stoi(iter->second), 0);\n } catch (const std::logic_error&) {\n return 0u;\n }\n}\n\n} \/\/ namespace seasocks\n<|endoftext|>"} {"text":"#include \"oemhandler.h\"\n#include \n#include \n#include \n\nvoid register_netfn_oem_partial_esel() __attribute__((constructor));\n\nconst char *g_esel_path = \"\/tmp\/\";\nuint16_t g_record_id = 0x0100;\n\n\n#define LSMSSWAP(x,y) ((y)<<8|(x))\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ For the First partial add eSEL the SEL Record ID and offset\n\/\/ value should be 0x0000. The extended data needs to be in\n\/\/ the form of an IPMI SEL Event Record, with Event sensor type\n\/\/ of 0xDF and Event Message format of 0x04. The returned\n\/\/ Record ID should be used for all partial eSEL adds.\n\/\/\n\/\/ This function creates a \/tmp\/esel# file to store the\n\/\/ incoming partial esel. It is the role of some other\n\/\/ function to commit the error log in to long term\n\/\/ storage. Likely via the ipmi add_sel command.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nipmi_ret_t ipmi_ibm_oem_partial_esel(ipmi_netfn_t netfn, ipmi_cmd_t cmd,\n ipmi_request_t request, ipmi_response_t response,\n ipmi_data_len_t data_len, ipmi_context_t context)\n{\n esel_request_t *reqptr = (esel_request_t*) request;\n FILE *fp;\n short offset = 0;\n uint8_t rlen;\n ipmi_ret_t rc = IPMI_CC_OK;\n char string[64];\n const char *pio;\n\n\n offset = LSMSSWAP(reqptr->offsetls, reqptr->offsetms);\n\n snprintf(string, sizeof(string), \"%s%s%02x%02x\", g_esel_path, \"esel\", reqptr->selrecordms, reqptr->selrecordls);\n\n\n \/\/ Length is the number of request bytes minus the header itself.\n \/\/ The header contains an extra byte to indicate the start of\n \/\/ the data (so didn't need to worry about word\/byte boundaries)\n \/\/ hence the -1...\n rlen = (*data_len) - (uint8_t) (sizeof(esel_request_t));\n\n\n printf(\"IPMI PARTIAL ESEL for %s Offset = %d Length = %d\\n\",\n string, offset, rlen);\n\n\n \/\/ Rules state for a Partial eSel that the first write of a\n \/\/ new esel will be the sensor data record. We will use that\n \/\/ to indicate this is a new record rather then an ofset in\n \/\/ my next commit TODO\n if (offset == 0) {\n pio = \"wb\";\n } else {\n pio = \"rb+\";\n }\n\n if ((fp = fopen(string, pio)) != NULL) {\n fseek(fp, offset, SEEK_SET);\n fwrite(reqptr+1,rlen,1,fp);\n fclose(fp);\n\n\n *data_len = sizeof(g_record_id);\n memcpy(response, &g_record_id, *data_len);\n\n\n } else {\n fprintf(stderr, \"Error trying to perform %s for esel%s\\n\",pio, string);\n rc = IPMI_CC_INVALID;\n *data_len = 0;\n }\n\n return rc;\n}\n\n\nvoid register_netfn_oem_partial_esel()\n{\n printf(\"Registering NetFn:[0x%X], Cmd:[0x%X]\\n\",NETFUN_OEM, IPMI_CMD_PESEL);\n ipmi_register_callback(NETFUN_OEM, IPMI_CMD_PESEL, NULL, ipmi_ibm_oem_partial_esel);\n return;\n}\nFixed byte swapped esel log name so logs are saved#include \"oemhandler.h\"\n#include \n#include \n#include \n\nvoid register_netfn_oem_partial_esel() __attribute__((constructor));\n\nconst char *g_esel_path = \"\/tmp\/\";\nuint16_t g_record_id = 0x0100;\n\n\n#define LSMSSWAP(x,y) ((y)<<8|(x))\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ For the First partial add eSEL the SEL Record ID and offset\n\/\/ value should be 0x0000. The extended data needs to be in\n\/\/ the form of an IPMI SEL Event Record, with Event sensor type\n\/\/ of 0xDF and Event Message format of 0x04. The returned\n\/\/ Record ID should be used for all partial eSEL adds.\n\/\/\n\/\/ This function creates a \/tmp\/esel# file to store the\n\/\/ incoming partial esel. It is the role of some other\n\/\/ function to commit the error log in to long term\n\/\/ storage. Likely via the ipmi add_sel command.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nipmi_ret_t ipmi_ibm_oem_partial_esel(ipmi_netfn_t netfn, ipmi_cmd_t cmd,\n ipmi_request_t request, ipmi_response_t response,\n ipmi_data_len_t data_len, ipmi_context_t context)\n{\n esel_request_t *reqptr = (esel_request_t*) request;\n FILE *fp;\n short recid, offset = 0;\n uint8_t rlen;\n ipmi_ret_t rc = IPMI_CC_OK;\n char string[64];\n const char *pio;\n\n recid = LSMSSWAP(reqptr->selrecordls, reqptr->selrecordms);\n offset = LSMSSWAP(reqptr->offsetls, reqptr->offsetms);\n\n if (!recid && !offset) {\n \/\/ OpenPOWER Host Interface spec says if RecordID and Offset are\n \/\/ 0 then then this is a new request\n pio = \"wb\";\n snprintf(string, sizeof(string), \"%s%s%02x%02x\", g_esel_path, \"esel\", (g_record_id&0xFF00>>8), (g_record_id&0xFF));\n } else {\n pio = \"rb+\";\n snprintf(string, sizeof(string), \"%s%s%02x%02x\", g_esel_path, \"esel\", reqptr->selrecordms, reqptr->selrecordls);\n }\n\n \/\/ Length is the number of request bytes minus the header itself.\n \/\/ The header contains an extra byte to indicate the start of\n \/\/ the data (so didn't need to worry about word\/byte boundaries)\n \/\/ hence the -1...\n rlen = (*data_len) - (uint8_t) (sizeof(esel_request_t));\n\n\n printf(\"IPMI PARTIAL ESEL for %s Offset = %d Length = %d\\n\",\n string, offset, rlen);\n\n\n if ((fp = fopen(string, pio)) != NULL) {\n fseek(fp, offset, SEEK_SET);\n fwrite(reqptr+1,rlen,1,fp);\n fclose(fp);\n\n *data_len = sizeof(g_record_id);\n memcpy(response, &g_record_id, *data_len);\n } else {\n fprintf(stderr, \"Error trying to perform %s for esel%s\\n\",pio, string);\n rc = IPMI_CC_INVALID;\n *data_len = 0;\n }\n\n return rc;\n}\n\n\nvoid register_netfn_oem_partial_esel()\n{\n printf(\"Registering NetFn:[0x%X], Cmd:[0x%X]\\n\",NETFUN_OEM, IPMI_CMD_PESEL);\n ipmi_register_callback(NETFUN_OEM, IPMI_CMD_PESEL, NULL, ipmi_ibm_oem_partial_esel);\n return;\n}\n<|endoftext|>"} {"text":"#include \n#include \"..\/system\/engine.h\"\n#include \"..\/renderer\/renderer.h\"\n#include \"..\/renderer\/forms.h\"\n#include \"..\/math\/vector.h\"\n#include \"messagebox.h\"\n\nusing std::istringstream;\nusing namespace Gui;\nusing Graphics::Color;\nusing Math::Vector3D;\nusing Math::Vector2D;\n\n\/\/The MessageBox constructor\nMessageBox::MessageBox(){\n handleClicks_ = NULL;\n input_.setColors(Vector3D(1,1,0.1f),Color(51,2,2,255));\n input_.setSpan(Vector2D(75,18));\n bgColor_ = Color(0,0,0,200);\/\/178);\n fgColor_ = Color(255,0,0,255);\n setText(\" OK\");\n span_ = Vector2D(800, 600);\n setPosition(Vector2D(100,100));\n}\n\nMessageBox::MessageBox(const MessageBox& m){\n std::cerr << \"MessageBox copy constructor not yet implemented\\n\";\n}\n\n\/\/and destructor\nMessageBox::~MessageBox(){\n}\n\nvoid MessageBox::process(){\n \/\/close messageBox\n \/\/find yourself\n list< ::Gui::Button*>& buts = System::Engine::instance()->getButtons();\n list< ::Gui::Button* >::iterator iter;\n int idx = 0;\n for (iter = buts.begin(); iter != buts.end(); iter++){\n if (*iter == this){\n break;\n }\n idx++;\n }\n System::Engine::instance()->removeButtonListener(idx, false);\n}\n\nvoid MessageBox::setPosition(const ::Math::Vector2D& pos){\n pos_ = pos;\n Vector2D inpos = pos;\n inpos.x += (short)(0.5*span_.x-75.0\/2.0);\n inpos.y += (short)(0.05*span_.y);\n input_.setPosition(inpos);\n}\n\nvoid MessageBox::setMessage(const string& text){\n istringstream str(text);\n unsigned maxchars = span_.x\/10-1;\n unsigned chars = 0;\n string word;\n string line = \"\";\n while (str >> word){\n \/\/the word does not fit into the current line\n if (chars + word.size() > maxchars){\n msg_.push_back(line);\n line = \"\";\n chars = 0;\n }\n \/\/concatenate word to current line\n line += word + \" \";\n chars += word.size()+1;\n }\n msg_.push_back(line);\n}\n\nvoid MessageBox::render(){\n Graphics::Renderer* rend = System::Engine::instance()->getRenderer();\n \n rend->blendFunc(Graphics::BLEND_SRC_ALPHA, Graphics::BLEND_ONE_MINUS_SRC_ALPHA);\n rend->enableTexturing(false);\n\n \/\/draw background\n rend->setColor(&bgColor_);\/\/_.r, bgColor_.g, bgColor_.b, opacity_);\n System::Engine::instance()->getForms()->activateQuad();\n System::Engine::instance()->getForms()->drawQuad(pos_, span_);\n \n \/\/draw console text\n rend->enableTexturing(true);\n rend->blendFunc(Graphics::BLEND_SRC_ALPHA, Graphics::BLEND_ONE);\n System::Engine::instance()->getFont(1)->setColor(fgColor_);\n int y = pos_.y + span_.y - 20;\n for (list::iterator iter = msg_.begin(); iter != msg_.end(); iter++){\n System::Engine::instance()->getFont(1)->glPrint(pos_.x, y, (*iter).c_str(), 0, 0.0);\n y -= 20;\n }\n input_.render();\n}\nmessagebox has now callback capability#include \n#include \"..\/system\/engine.h\"\n#include \"..\/renderer\/renderer.h\"\n#include \"..\/renderer\/forms.h\"\n#include \"..\/math\/vector.h\"\n#include \"messagebox.h\"\n\nusing std::istringstream;\nusing namespace Gui;\nusing Graphics::Color;\nusing Math::Vector3D;\nusing Math::Vector2D;\n\n\/\/The MessageBox constructor\nMessageBox::MessageBox(){\n handleClicks_ = NULL;\n input_.setColors(Vector3D(1,1,0.1f),Color(51,2,2,255));\n input_.setSpan(Vector2D(75,18));\n bgColor_ = Color(0,0,0,200);\/\/178);\n fgColor_ = Color(255,0,0,255);\n setText(\" OK\");\n span_ = Vector2D(800, 600);\n setPosition(Vector2D(100,100));\n}\n\nMessageBox::MessageBox(const MessageBox& m){\n std::cerr << \"MessageBox copy constructor not yet implemented\\n\";\n}\n\n\/\/and destructor\nMessageBox::~MessageBox(){\n}\n\nvoid MessageBox::process(){\n \/\/close messageBox\n \/\/find yourself\n list< ::Gui::Button*>& buts = System::Engine::instance()->getButtons();\n list< ::Gui::Button* >::iterator iter;\n int idx = 0;\n for (iter = buts.begin(); iter != buts.end(); iter++){\n if (*iter == this){\n break;\n }\n idx++;\n }\n System::Engine::instance()->removeButtonListener(idx, false);\n if (handleClicks_)\n (*handleClicks_)();\n}\n\nvoid MessageBox::setPosition(const ::Math::Vector2D& pos){\n pos_ = pos;\n Vector2D inpos = pos;\n inpos.x += (short)(0.5*span_.x-75.0\/2.0);\n inpos.y += (short)(0.05*span_.y);\n input_.setPosition(inpos);\n}\n\nvoid MessageBox::setMessage(const string& text){\n istringstream str(text);\n unsigned maxchars = span_.x\/10-1;\n unsigned chars = 0;\n string word;\n string line = \"\";\n while (str >> word){\n \/\/the word does not fit into the current line\n if (chars + word.size() > maxchars){\n msg_.push_back(line);\n line = \"\";\n chars = 0;\n }\n \/\/concatenate word to current line\n line += word + \" \";\n chars += word.size()+1;\n }\n msg_.push_back(line);\n}\n\nvoid MessageBox::render(){\n Graphics::Renderer* rend = System::Engine::instance()->getRenderer();\n \n rend->blendFunc(Graphics::BLEND_SRC_ALPHA, Graphics::BLEND_ONE_MINUS_SRC_ALPHA);\n rend->enableTexturing(false);\n\n \/\/draw background\n rend->setColor(&bgColor_);\/\/_.r, bgColor_.g, bgColor_.b, opacity_);\n System::Engine::instance()->getForms()->activateQuad();\n System::Engine::instance()->getForms()->drawQuad(pos_, span_);\n \n \/\/draw console text\n rend->enableTexturing(true);\n rend->blendFunc(Graphics::BLEND_SRC_ALPHA, Graphics::BLEND_ONE);\n System::Engine::instance()->getFont(1)->setColor(fgColor_);\n int y = pos_.y + span_.y - 20;\n for (list::iterator iter = msg_.begin(); iter != msg_.end(); iter++){\n System::Engine::instance()->getFont(1)->glPrint(pos_.x, y, (*iter).c_str(), 0, 0.0);\n y -= 20;\n }\n input_.render();\n}\n<|endoftext|>"} {"text":"#include \"openhevcfilter.h\"\n\n#include \"statisticsinterface.h\"\n\n#include \"common.h\"\n#include \"settingskeys.h\"\n#include \"logger.h\"\n\n#include \n\nenum OHThreadType {OH_THREAD_FRAME = 1, OH_THREAD_SLICE = 2, OH_THREAD_FRAMESLICE = 3};\n\nOpenHEVCFilter::OpenHEVCFilter(uint32_t sessionID, StatisticsInterface *stats,\n std::shared_ptr hwResources):\n Filter(QString::number(sessionID), \"OpenHEVC\", stats, hwResources, DT_HEVCVIDEO, DT_YUV420VIDEO),\n handle_(),\n vpsReceived_(false),\n spsReceived_(false),\n ppsReceived_(false),\n slices_(true),\n sessionID_(sessionID),\n threads_(-1)\n{}\n\n\nbool OpenHEVCFilter::init()\n{\n Logger::getLogger()->printNormal(this, \"Starting to initiate OpenHEVC\");\n QSettings settings(settingsFile, settingsFileFormat);\n\n threads_ = settings.value(SettingsKey::videoOpenHEVCThreads).toInt();\n handle_ = libOpenHevcInit(threads_, OH_THREAD_FRAME);\n\n \/\/libOpenHevcSetDebugMode(handle_, 0);\n if(libOpenHevcStartDecoder(handle_) == -1)\n {\n Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this, \"Failed to start decoder.\");\n return false;\n }\n libOpenHevcSetTemporalLayer_id(handle_, 0);\n libOpenHevcSetActiveDecoders(handle_, 0);\n libOpenHevcSetViewLayers(handle_, 0);\n Logger::getLogger()->printNormal(this, \"OpenHEVC initiation successful.\", \n {\"Version\"}, {libOpenHevcVersion(handle_)});\n\n \/\/ This is because we don't know anything about the incoming stream\n maxBufferSize_ = -1; \/\/ no buffer limit\n\n setPriority(QThread::HighPriority);\n\n return true;\n}\n\n\nvoid OpenHEVCFilter::uninit()\n{\n Logger::getLogger()->printNormal(this, \"Uniniating.\");\n libOpenHevcFlush(handle_);\n libOpenHevcClose(handle_);\n}\n\n\nvoid OpenHEVCFilter::updateSettings()\n{\n QSettings settings(settingsFile, settingsFileFormat);\n if (settings.value(SettingsKey::videoOpenHEVCThreads).toInt() != threads_)\n {\n uninit();\n init();\n }\n Filter::updateSettings();\n}\n\n\nvoid OpenHEVCFilter::combineFrame(std::unique_ptr& combinedFrame)\n{\n if(sliceBuffer_.size() == 0)\n {\n Logger::getLogger()->printWarning(this, \"No previous slices\");\n return;\n }\n\n combinedFrame = std::unique_ptr(shallowDataCopy(sliceBuffer_.at(0).get()));\n combinedFrame->data_size = 0;\n\n for(unsigned int i = 0; i < sliceBuffer_.size(); ++i)\n {\n combinedFrame->data_size += sliceBuffer_.at(i)->data_size;\n }\n\n combinedFrame->data = std::unique_ptr(new uchar[combinedFrame->data_size]);\n\n uint32_t dataWritten = 0;\n for(unsigned int i = 0; i < sliceBuffer_.size(); ++i)\n {\n memcpy(combinedFrame->data.get() + dataWritten,\n sliceBuffer_.at(i)->data.get(), sliceBuffer_.at(i)->data_size );\n dataWritten += sliceBuffer_.at(i)->data_size;\n }\n\n if(slices_ && sliceBuffer_.size() == 1)\n {\n slices_ = false;\n Logger::getLogger()->printPeerError(this, \"Detected no slices in incoming stream.\");\n uninit();\n init();\n }\n\n sliceBuffer_.clear();\n\n return;\n}\n\nvoid OpenHEVCFilter::process()\n{\n std::unique_ptr input = getInput();\n while(input)\n {\n getStats()->addReceivePacket(sessionID_, \"Video\", input->data_size);\n\n const unsigned char *buff = input->data.get();\n\n bool nextSlice = buff[0] == 0\n && buff[1] == 0\n && buff[2] == 0;\n\n if(!slices_ && buff[0] == 0\n && buff[1] == 0\n && buff[2] == 1)\n {\n slices_ = true;\n Logger::getLogger()->printNormal(this, \"Detected slices in incoming stream\");\n uninit();\n init();\n }\n\n bool vps = (buff[4] >> 1) == 32;\n if (!vpsReceived_ && vps)\n {\n Logger::getLogger()->printDebug(DEBUG_NORMAL, this, \"VPS found\");\n vpsReceived_ = true;\n }\n\n bool sps = (buff[4] >> 1) == 33;\n if (!spsReceived_ && sps)\n {\n Logger::getLogger()->printDebug(DEBUG_NORMAL, this, \"SPS found\");\n spsReceived_ = true;\n }\n\n bool pps = (buff[4] >> 1) == 34;\n if (!ppsReceived_ && pps)\n {\n Logger::getLogger()->printDebug(DEBUG_NORMAL, this, \"PPS found\");\n ppsReceived_ = true;\n }\n\n if((vpsReceived_ && spsReceived_ && ppsReceived_) || vps || sps || pps)\n {\n if(nextSlice && sliceBuffer_.size() != 0)\n {\n std::unique_ptr frame;\n combineFrame(frame);\n\n if (frame == nullptr)\n {\n break;\n }\n\n int gotPicture = libOpenHevcDecode(handle_, frame->data.get(), frame->data_size, frame->presentationTime);\n\n OpenHevc_Frame openHevcFrame;\n if( gotPicture == -1)\n {\n Logger::getLogger()->printDebug(DEBUG_ERROR, this, \"Error while decoding.\");\n }\n else if( libOpenHevcGetOutput(handle_, gotPicture, &openHevcFrame) == -1 )\n {\n Logger::getLogger()->printDebug(DEBUG_ERROR, this, \"Failed to get output.\");\n }\n else if(gotPicture)\n {\n libOpenHevcGetPictureInfo(handle_, &openHevcFrame.frameInfo);\n\n\n frame->vInfo->width = openHevcFrame.frameInfo.nWidth;\n frame->vInfo->height = openHevcFrame.frameInfo.nHeight;\n uint32_t finalDataSize = frame->vInfo->width*frame->vInfo->height +\n frame->vInfo->width*frame->vInfo->height\/2;\n std::unique_ptr yuv_frame(new uchar[finalDataSize]);\n\n uint8_t* pY = (uint8_t*)yuv_frame.get();\n uint8_t* pU = (uint8_t*)&(yuv_frame.get()[frame->vInfo->width*frame->vInfo->height]);\n uint8_t* pV = (uint8_t*)&(yuv_frame.get()[frame->vInfo->width*frame->vInfo->height +\n frame->vInfo->width*frame->vInfo->height\/4]);\n\n uint32_t s_stride = openHevcFrame.frameInfo.nYPitch;\n uint32_t qs_stride = openHevcFrame.frameInfo.nUPitch\/2;\n\n uint32_t d_stride = frame->vInfo->width\/2;\n uint32_t dd_stride = frame->vInfo->width;\n\n for (int i=0; ivInfo->height; i++) {\n memcpy(pY, (uint8_t *) openHevcFrame.pvY + i*s_stride, dd_stride);\n pY += dd_stride;\n\n if (! (i%2) ) {\n memcpy(pU, (uint8_t *) openHevcFrame.pvU + i*qs_stride, d_stride);\n pU += d_stride;\n\n memcpy(pV, (uint8_t *) openHevcFrame.pvV + i*qs_stride, d_stride);\n pV += d_stride;\n }\n }\n\n \/\/ TODO: put delay into deque, and set timestamp accordingly to get more accurate latency.\n\n frame->type = DT_YUV420VIDEO;\n if (openHevcFrame.frameInfo.frameRate.den != 0)\n {\n frame->vInfo->framerate = openHevcFrame.frameInfo.frameRate.num\/openHevcFrame.frameInfo.frameRate.den;\n }\n else\n {\n frame->vInfo->framerate = openHevcFrame.frameInfo.frameRate.num;\n }\n frame->data_size = finalDataSize;\n frame->data = std::move(yuv_frame);\n\n sendOutput(std::move(frame));\n }\n }\n sliceBuffer_.push_back(std::move(input));\n }\n\n input = getInput();\n }\n}\nrefactor(Processing): Print warning when waiting for first intra#include \"openhevcfilter.h\"\n\n#include \"statisticsinterface.h\"\n\n#include \"common.h\"\n#include \"settingskeys.h\"\n#include \"logger.h\"\n\n#include \n\nenum OHThreadType {OH_THREAD_FRAME = 1, OH_THREAD_SLICE = 2, OH_THREAD_FRAMESLICE = 3};\n\nOpenHEVCFilter::OpenHEVCFilter(uint32_t sessionID, StatisticsInterface *stats,\n std::shared_ptr hwResources):\n Filter(QString::number(sessionID), \"OpenHEVC\", stats, hwResources, DT_HEVCVIDEO, DT_YUV420VIDEO),\n handle_(),\n vpsReceived_(false),\n spsReceived_(false),\n ppsReceived_(false),\n slices_(true),\n sessionID_(sessionID),\n threads_(-1)\n{}\n\n\nbool OpenHEVCFilter::init()\n{\n Logger::getLogger()->printNormal(this, \"Starting to initiate OpenHEVC\");\n QSettings settings(settingsFile, settingsFileFormat);\n\n threads_ = settings.value(SettingsKey::videoOpenHEVCThreads).toInt();\n handle_ = libOpenHevcInit(threads_, OH_THREAD_FRAME);\n\n \/\/libOpenHevcSetDebugMode(handle_, 0);\n if(libOpenHevcStartDecoder(handle_) == -1)\n {\n Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this, \"Failed to start decoder.\");\n return false;\n }\n libOpenHevcSetTemporalLayer_id(handle_, 0);\n libOpenHevcSetActiveDecoders(handle_, 0);\n libOpenHevcSetViewLayers(handle_, 0);\n Logger::getLogger()->printNormal(this, \"OpenHEVC initiation successful.\", \n {\"Version\"}, {libOpenHevcVersion(handle_)});\n\n \/\/ This is because we don't know anything about the incoming stream\n maxBufferSize_ = -1; \/\/ no buffer limit\n\n setPriority(QThread::HighPriority);\n\n return true;\n}\n\n\nvoid OpenHEVCFilter::uninit()\n{\n Logger::getLogger()->printNormal(this, \"Uniniating.\");\n libOpenHevcFlush(handle_);\n libOpenHevcClose(handle_);\n}\n\n\nvoid OpenHEVCFilter::updateSettings()\n{\n QSettings settings(settingsFile, settingsFileFormat);\n if (settings.value(SettingsKey::videoOpenHEVCThreads).toInt() != threads_)\n {\n uninit();\n init();\n }\n Filter::updateSettings();\n}\n\n\nvoid OpenHEVCFilter::combineFrame(std::unique_ptr& combinedFrame)\n{\n if(sliceBuffer_.size() == 0)\n {\n Logger::getLogger()->printWarning(this, \"No previous slices\");\n return;\n }\n\n combinedFrame = std::unique_ptr(shallowDataCopy(sliceBuffer_.at(0).get()));\n combinedFrame->data_size = 0;\n\n for(unsigned int i = 0; i < sliceBuffer_.size(); ++i)\n {\n combinedFrame->data_size += sliceBuffer_.at(i)->data_size;\n }\n\n combinedFrame->data = std::unique_ptr(new uchar[combinedFrame->data_size]);\n\n uint32_t dataWritten = 0;\n for(unsigned int i = 0; i < sliceBuffer_.size(); ++i)\n {\n memcpy(combinedFrame->data.get() + dataWritten,\n sliceBuffer_.at(i)->data.get(), sliceBuffer_.at(i)->data_size );\n dataWritten += sliceBuffer_.at(i)->data_size;\n }\n\n if(slices_ && sliceBuffer_.size() == 1)\n {\n slices_ = false;\n Logger::getLogger()->printPeerError(this, \"Detected no slices in incoming stream.\");\n uninit();\n init();\n }\n\n sliceBuffer_.clear();\n\n return;\n}\n\nvoid OpenHEVCFilter::process()\n{\n std::unique_ptr input = getInput();\n while(input)\n {\n getStats()->addReceivePacket(sessionID_, \"Video\", input->data_size);\n\n const unsigned char *buff = input->data.get();\n\n bool nextSlice = buff[0] == 0\n && buff[1] == 0\n && buff[2] == 0;\n\n if(!slices_ && buff[0] == 0\n && buff[1] == 0\n && buff[2] == 1)\n {\n slices_ = true;\n Logger::getLogger()->printNormal(this, \"Detected slices in incoming stream\");\n uninit();\n init();\n }\n\n bool vps = (buff[4] >> 1) == 32;\n if (!vpsReceived_ && vps)\n {\n Logger::getLogger()->printDebug(DEBUG_NORMAL, this, \"VPS found\");\n vpsReceived_ = true;\n }\n\n bool sps = (buff[4] >> 1) == 33;\n if (!spsReceived_ && sps)\n {\n Logger::getLogger()->printDebug(DEBUG_NORMAL, this, \"SPS found\");\n spsReceived_ = true;\n }\n\n bool pps = (buff[4] >> 1) == 34;\n if (!ppsReceived_ && pps)\n {\n Logger::getLogger()->printDebug(DEBUG_NORMAL, this, \"PPS found\");\n ppsReceived_ = true;\n }\n\n if(slices_ || (vpsReceived_ && spsReceived_ && ppsReceived_) || vps || sps || pps)\n {\n if(nextSlice && sliceBuffer_.size() != 0)\n {\n std::unique_ptr frame;\n combineFrame(frame);\n\n if (frame == nullptr)\n {\n break;\n }\n\n int gotPicture = libOpenHevcDecode(handle_, frame->data.get(), frame->data_size, frame->presentationTime);\n\n OpenHevc_Frame openHevcFrame;\n if( gotPicture == -1)\n {\n Logger::getLogger()->printDebug(DEBUG_ERROR, this, \"Error while decoding.\");\n }\n else if( libOpenHevcGetOutput(handle_, gotPicture, &openHevcFrame) == -1 )\n {\n Logger::getLogger()->printDebug(DEBUG_ERROR, this, \"Failed to get output.\");\n }\n else if(gotPicture)\n {\n libOpenHevcGetPictureInfo(handle_, &openHevcFrame.frameInfo);\n\n\n frame->vInfo->width = openHevcFrame.frameInfo.nWidth;\n frame->vInfo->height = openHevcFrame.frameInfo.nHeight;\n uint32_t finalDataSize = frame->vInfo->width*frame->vInfo->height +\n frame->vInfo->width*frame->vInfo->height\/2;\n std::unique_ptr yuv_frame(new uchar[finalDataSize]);\n\n uint8_t* pY = (uint8_t*)yuv_frame.get();\n uint8_t* pU = (uint8_t*)&(yuv_frame.get()[frame->vInfo->width*frame->vInfo->height]);\n uint8_t* pV = (uint8_t*)&(yuv_frame.get()[frame->vInfo->width*frame->vInfo->height +\n frame->vInfo->width*frame->vInfo->height\/4]);\n\n uint32_t s_stride = openHevcFrame.frameInfo.nYPitch;\n uint32_t qs_stride = openHevcFrame.frameInfo.nUPitch\/2;\n\n uint32_t d_stride = frame->vInfo->width\/2;\n uint32_t dd_stride = frame->vInfo->width;\n\n for (int i=0; ivInfo->height; i++) {\n memcpy(pY, (uint8_t *) openHevcFrame.pvY + i*s_stride, dd_stride);\n pY += dd_stride;\n\n if (! (i%2) ) {\n memcpy(pU, (uint8_t *) openHevcFrame.pvU + i*qs_stride, d_stride);\n pU += d_stride;\n\n memcpy(pV, (uint8_t *) openHevcFrame.pvV + i*qs_stride, d_stride);\n pV += d_stride;\n }\n }\n\n \/\/ TODO: put delay into deque, and set timestamp accordingly to get more accurate latency.\n\n frame->type = DT_YUV420VIDEO;\n if (openHevcFrame.frameInfo.frameRate.den != 0)\n {\n frame->vInfo->framerate = openHevcFrame.frameInfo.frameRate.num\/openHevcFrame.frameInfo.frameRate.den;\n }\n else\n {\n frame->vInfo->framerate = openHevcFrame.frameInfo.frameRate.num;\n }\n frame->data_size = finalDataSize;\n frame->data = std::move(yuv_frame);\n\n sendOutput(std::move(frame));\n }\n }\n sliceBuffer_.push_back(std::move(input));\n }\n else\n {\n Logger::getLogger()->printWarning(this, \"Discarding frame until necessary structures have arrived\");\n }\n\n input = getInput();\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n#include \"core\/animation\/css\/CSSTransitionData.h\"\n\n#include \"core\/animation\/Timing.h\"\n\nnamespace blink {\n\nCSSTransitionData::CSSTransitionData()\n{\n m_propertyList.append(initialProperty());\n}\n\nCSSTransitionData::CSSTransitionData(const CSSTransitionData& other)\n : CSSTimingData(other)\n , m_propertyList(other.m_propertyList)\n{\n}\n\nbool CSSTransitionData::transitionsMatchForStyleRecalc(const CSSTransitionData& other) const\n{\n return m_propertyList == other.m_propertyList;\n}\n\nTiming CSSTransitionData::convertToTiming(size_t index) const\n{\n ASSERT(index < m_propertyList.size());\n \/\/ Note that the backwards fill part is required for delay to work.\n Timing timing = CSSTimingData::convertToTiming(index);\n timing.fillMode = Timing::FillModeBoth;\n return timing;\n}\n\n} \/\/ namespace blink\nAnimations: Change fill mode of transitions to backwards not both\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n#include \"core\/animation\/css\/CSSTransitionData.h\"\n\n#include \"core\/animation\/Timing.h\"\n\nnamespace blink {\n\nCSSTransitionData::CSSTransitionData()\n{\n m_propertyList.append(initialProperty());\n}\n\nCSSTransitionData::CSSTransitionData(const CSSTransitionData& other)\n : CSSTimingData(other)\n , m_propertyList(other.m_propertyList)\n{\n}\n\nbool CSSTransitionData::transitionsMatchForStyleRecalc(const CSSTransitionData& other) const\n{\n return m_propertyList == other.m_propertyList;\n}\n\nTiming CSSTransitionData::convertToTiming(size_t index) const\n{\n ASSERT(index < m_propertyList.size());\n \/\/ Note that the backwards fill part is required for delay to work.\n Timing timing = CSSTimingData::convertToTiming(index);\n timing.fillMode = Timing::FillModeBackwards;\n return timing;\n}\n\n} \/\/ namespace blink\n<|endoftext|>"} {"text":"#include \"ConnectionList.hpp\"\r\n\r\nvoid AbstractConnection::disconnect()\r\n{\r\n\tThreadDataLocker lock1(outerLock_);\r\n\tThreadDataLocker lock2(innerLock_);\r\n\tdoDisconnect();\r\n}\r\n\r\nbool AbstractConnection::tryDisconnectWithLock(ThreadDataRef const & lock)\r\n{\r\n\tif(lock != outerLock_) return false;\r\n\tThreadDataLocker lock2(innerLock_);\r\n\tdoDisconnect();\r\n\treturn true;\r\n}\r\n\r\nvoid AbstractConnection::doDisconnect()\r\n{\r\n\tif(!sourceList_ && !targetList_) return;\r\n\tassert(sourceList_ && targetList_);\r\n\r\n\t{\r\n\t\tConnectionsVector & connections = sourceList_->data_.mutableRef();\r\n\t\tAbstractConnection * & xs = connections[sourceIndex_];\r\n\t\tassert(xs == this);\r\n\t\txs = connections.back();\r\n\t\txs->sourceIndex_ = sourceIndex_;\r\n\t\tconnections.pop_back();\r\n\t\tsourceIndex_ = npos; sourceList_ = 0;\r\n\t\trelease();\r\n\t}\r\n\t{\r\n\t\tConnectionsVector & connections = targetList_->data_.mutableRef();\r\n\t\tAbstractConnection * & xt = connections[targetIndex_];\r\n\t\tassert(xt == this);\r\n\t\txt = connections.back();\r\n\t\txt->targetIndex_ = targetIndex_;\r\n\t\tconnections.pop_back();\r\n\t\ttargetIndex_ = npos; targetList_ = 0;\r\n\t\trelease();\r\n\t}\r\n}\r\n\r\nConnectionList::ConnectionList()\r\n\t: lock_(ThreadDataRef::current())\r\n\t, data_()\r\n{\r\n}\r\n\r\nConnectionList::~ConnectionList()\r\n{\r\n\tassert(!data_.isBorrowed());\r\n\tdisconnectAll();\r\n}\r\n\r\nvoid ConnectionList::connect(ConnectionList * peer, AbstractConnection * conn)\r\n{\r\n\tconn->outerLock_ = this->lock_;\r\n\tconn->innerLock_ = peer->lock_;\r\n\tconn->outerLock_.makeBefore(conn->innerLock_);\r\n\r\n\tThreadDataLocker lock1(conn->outerLock_);\r\n\tThreadDataLocker lock2(conn->innerLock_);\r\n\r\n\t{\r\n\t\tassert(!conn->sourceList_ && conn->sourceIndex_ == AbstractConnection::npos);\r\n\t\tConnectionsVector & connections = data_.mutableRef();\r\n\t\tconn->sourceList_ = this;\r\n\t\tconn->sourceIndex_ = connections.size();\r\n\t\tconnections.push_back(conn);\r\n\t\tconn->retain();\r\n\t}\r\n\t{\r\n\t\tassert(!conn->targetList_ && conn->targetIndex_ == AbstractConnection::npos);\r\n\t\tConnectionsVector & connections = data_.mutableRef();\r\n\t\tconn->targetList_ = peer;\r\n\t\tconn->targetIndex_ = connections.size();\r\n\t\tconnections.push_back(conn);\r\n\t\tconn->retain();\r\n\t}\r\n}\r\n\r\n#define mutable_iterate(it, container) \\\r\n\tConnectionsVector::iterator it = (container).begin(); it != (container).end(); ++it\r\n\r\n#define const_iterate(it, container) \\\r\n\tConnectionsVector::const_iterator it = (container).begin(); it != (container).end(); ++it\r\n\r\nclass ConnectionList::NullComparer\r\n{\r\npublic:\r\n\tbool operator()(AbstractConnection const * conn) const { (void)conn; return true; }\r\n};\r\n\r\nclass ConnectionList::DelegateComparer\r\n{\r\npublic:\r\n\tDelegateComparer(AbstractDelegate const & deleg) : deleg_(deleg) {}\r\n\tbool operator()(AbstractConnection const * conn) const { return conn->recieverDelegate() == deleg_; }\r\nprivate:\r\n\tAbstractDelegate const & deleg_;\r\n};\r\n\r\nclass ConnectionList::PeerComparer\r\n{\r\npublic:\r\n\tPeerComparer(ConnectionList * peer) : peer_(peer) {}\r\n\tbool operator()(AbstractConnection const * conn) const { return conn->hasPeer(peer_); }\r\nprivate:\r\n\tConnectionList * const peer_;\r\n};\r\n\r\nclass ConnectionList::FullComparer\r\n{\r\npublic:\r\n\tFullComparer(ConnectionList * peer, AbstractDelegate const & deleg) : e_(peer), d_(deleg) {}\r\n\tbool operator()(AbstractConnection const * conn) const { return e_(conn) && d_(conn); }\r\nprivate:\r\n\tPeerComparer e_;\r\n\tDelegateComparer d_;\r\n};\r\n\r\nsize_t ConnectionList::connectionCount() const\r\n{\r\n\tThreadDataLocker lock(lock_);\r\n\treturn data_.constRef().size();\r\n}\r\n\r\ntemplate inline size_t ConnectionList::getConnectionCount(Comparer const & comp) const\r\n{\r\n\tThreadDataLocker lock(lock_);\r\n\tConnectionsVector const & connections = data_.constRef();\r\n\tsize_t retVal = 0;\r\n\tfor(const_iterate(it, connections))\r\n\t{\r\n\t\tAbstractConnection const * conn = *it;\r\n\t\tif(comp(conn)) ++retVal;\r\n\t}\r\n\treturn retVal;\r\n}\r\n\r\nsize_t ConnectionList::connectionCount(AbstractDelegate const & deleg) const\r\n{\r\n\tDelegateComparer comp(deleg);\r\n\treturn getConnectionCount(comp);\r\n}\r\n\r\nsize_t ConnectionList::connectionCount(ConnectionList * peer) const\r\n{\r\n\tPeerComparer comp(peer);\r\n\treturn getConnectionCount(comp);\r\n}\r\n\r\nsize_t ConnectionList::connectionCount(ConnectionList * peer, AbstractDelegate const & deleg) const\r\n{\r\n\tFullComparer comp(peer, deleg);\r\n\treturn getConnectionCount(comp);\r\n}\r\n\r\nbool ConnectionList::hasConnections() const\r\n{\r\n\tThreadDataLocker lock(lock_);\r\n\treturn !data_.constRef().empty();\r\n}\r\n\r\ntemplate inline bool ConnectionList::getHasConnections(Comparer const & comp) const\r\n{\r\n\tThreadDataLocker lock(lock_);\r\n\tConnectionsVector const & connections = data_.constRef();\t\r\n\tfor(const_iterate(it, connections))\r\n\t{\r\n\t\tAbstractConnection const * conn = *it;\r\n\t\tif(comp(conn)) return true;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nbool ConnectionList::hasConnections(AbstractDelegate const & deleg) const\r\n{\r\n\tDelegateComparer comp(deleg);\r\n\treturn getHasConnections(comp);\r\n}\r\n\r\nbool ConnectionList::hasConnections(ConnectionList * peer) const\r\n{\r\n\tPeerComparer comp(peer);\r\n\treturn getHasConnections(comp);\r\n}\r\n\r\nbool ConnectionList::hasConnections(ConnectionList * peer, AbstractDelegate const & deleg) const\r\n{\r\n\tFullComparer comp(peer, deleg);\r\n\treturn getHasConnections(comp);\r\n}\r\n\r\ntemplate inline size_t ConnectionList::doDisconnectAll(Comparer const & comp)\r\n{\r\n\tConnectionsVector needRelock;\r\n\tsize_t retVal = 0;\r\n\t{\r\n\t\tThreadDataLocker lock(lock_);\r\n\t\tConnectionsVector & connections = data_.mutableRef();\r\n\t\tfor(size_t i = 0; i < connections.size(); )\r\n\t\t{\r\n\t\t\tAbstractConnection * conn = connections.at(i);\r\n\t\t\tif(!comp(conn))\r\n\t\t\t{\r\n\t\t\t\t++i;\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\t++retVal;\r\n\t\t\tbool done = conn->tryDisconnectWithLock(lock_);\r\n\t\t\tif(!done)\r\n\t\t\t{\r\n\t\t\t\tconn->retain();\r\n\t\t\t\tneedRelock.push_back(conn);\r\n\t\t\t\t++i;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfor(const_iterate(it, needRelock))\r\n\t{\r\n\t\tAbstractConnection * conn = *it;\r\n\t\tconn->disconnect();\r\n\t\tconn->release();\r\n\t}\r\n\treturn retVal;\r\n}\r\n\r\nsize_t ConnectionList::disconnectAll()\r\n{\r\n\tNullComparer comp;\r\n\treturn doDisconnectAll(comp);\r\n}\r\n\r\nsize_t ConnectionList::disconnectAll(AbstractDelegate const & deleg)\r\n{\r\n\tDelegateComparer comp(deleg);\r\n\treturn doDisconnectAll(comp);\r\n}\r\n\r\nsize_t ConnectionList::disconnectAll(ConnectionList * peer, AbstractDelegate const & deleg)\r\n{\r\n\tFullComparer comp(peer, deleg);\r\n\treturn doDisconnectAll(comp);\r\n}\r\n\r\nsize_t ConnectionList::disconnectAll(ConnectionList * peer)\r\n{\r\n\tPeerComparer comp(peer);\r\n\treturn doDisconnectAll(comp);\r\n}\r\n\r\ntemplate inline bool ConnectionList::doDisconnectOne(Comparer const & comp)\r\n{\r\n\tAbstractConnection * needRelock = 0;\r\n\t{\r\n\t\tThreadDataLocker lock(lock_);\r\n\t\tConnectionsVector & connections = data_.mutableRef();\r\n\t\tfor(size_t i = 0; i < connections.size(); )\r\n\t\t{\r\n\t\t\tAbstractConnection * conn = connections.at(i);\r\n\t\t\tif(!comp(conn))\r\n\t\t\t{\r\n\t\t\t\t++i;\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tbool done = conn->tryDisconnectWithLock(lock_);\r\n\t\t\tif(done) return true;\r\n\t\t\tneedRelock = conn;\r\n\t\t\tconn->retain();\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tif(!needRelock) return false;\r\n\r\n\tneedRelock->disconnect();\r\n\tneedRelock->release();\r\n\treturn true;\r\n}\r\n\r\nbool ConnectionList::disconnectOne(AbstractDelegate const & deleg)\r\n{\r\n\tDelegateComparer comp(deleg);\r\n\treturn doDisconnectOne(comp);\r\n}\r\n\r\nbool ConnectionList::disconnectOne(ConnectionList * peer)\r\n{\r\n\tPeerComparer comp(peer);\r\n\treturn doDisconnectOne(comp);\r\n}\r\n\r\nbool ConnectionList::disconnectOne(ConnectionList * peer, AbstractDelegate const & deleg)\r\n{\r\n\tFullComparer comp(peer, deleg);\r\n\treturn doDisconnectOne(comp);\r\n}\r\n-: Fixed: bug in ConnectionList::connect()#include \"ConnectionList.hpp\"\r\n\r\nvoid AbstractConnection::disconnect()\r\n{\r\n\tThreadDataLocker lock1(outerLock_);\r\n\tThreadDataLocker lock2(innerLock_);\r\n\tdoDisconnect();\r\n}\r\n\r\nbool AbstractConnection::tryDisconnectWithLock(ThreadDataRef const & lock)\r\n{\r\n\tif(lock != outerLock_) return false;\r\n\tThreadDataLocker lock2(innerLock_);\r\n\tdoDisconnect();\r\n\treturn true;\r\n}\r\n\r\nvoid AbstractConnection::doDisconnect()\r\n{\r\n\tif(!sourceList_ && !targetList_) return;\r\n\tassert(sourceList_ && targetList_);\r\n\r\n\t{\r\n\t\tConnectionsVector & connections = sourceList_->data_.mutableRef();\r\n\t\tAbstractConnection * & xs = connections[sourceIndex_];\r\n\t\tassert(xs == this);\r\n\t\txs = connections.back();\r\n\t\txs->sourceIndex_ = sourceIndex_;\r\n\t\tconnections.pop_back();\r\n\t\tsourceIndex_ = npos; sourceList_ = 0;\r\n\t\trelease();\r\n\t}\r\n\t{\r\n\t\tConnectionsVector & connections = targetList_->data_.mutableRef();\r\n\t\tAbstractConnection * & xt = connections[targetIndex_];\r\n\t\tassert(xt == this);\r\n\t\txt = connections.back();\r\n\t\txt->targetIndex_ = targetIndex_;\r\n\t\tconnections.pop_back();\r\n\t\ttargetIndex_ = npos; targetList_ = 0;\r\n\t\trelease();\r\n\t}\r\n}\r\n\r\nConnectionList::ConnectionList()\r\n\t: lock_(ThreadDataRef::current())\r\n\t, data_()\r\n{\r\n}\r\n\r\nConnectionList::~ConnectionList()\r\n{\r\n\tassert(!data_.isBorrowed());\r\n\tdisconnectAll();\r\n}\r\n\r\nvoid ConnectionList::connect(ConnectionList * peer, AbstractConnection * conn)\r\n{\r\n\tconn->outerLock_ = this->lock_;\r\n\tconn->innerLock_ = peer->lock_;\r\n\tconn->outerLock_.makeBefore(conn->innerLock_);\r\n\r\n\tThreadDataLocker lock1(conn->outerLock_);\r\n\tThreadDataLocker lock2(conn->innerLock_);\r\n\r\n\t{\r\n\t\tassert(!conn->sourceList_ && conn->sourceIndex_ == AbstractConnection::npos);\r\n\t\tConnectionsVector & connections = data_.mutableRef();\r\n\t\tconn->sourceList_ = this;\r\n\t\tconn->sourceIndex_ = connections.size();\r\n\t\tconnections.push_back(conn);\r\n\t\tconn->retain();\r\n\t}\r\n\t{\r\n\t\tassert(!conn->targetList_ && conn->targetIndex_ == AbstractConnection::npos);\r\n\t\tConnectionsVector & connections = peer->data_.mutableRef();\r\n\t\tconn->targetList_ = peer;\r\n\t\tconn->targetIndex_ = connections.size();\r\n\t\tconnections.push_back(conn);\r\n\t\tconn->retain();\r\n\t}\r\n}\r\n\r\n#define mutable_iterate(it, container) \\\r\n\tConnectionsVector::iterator it = (container).begin(); it != (container).end(); ++it\r\n\r\n#define const_iterate(it, container) \\\r\n\tConnectionsVector::const_iterator it = (container).begin(); it != (container).end(); ++it\r\n\r\nclass ConnectionList::NullComparer\r\n{\r\npublic:\r\n\tbool operator()(AbstractConnection const * conn) const { (void)conn; return true; }\r\n};\r\n\r\nclass ConnectionList::DelegateComparer\r\n{\r\npublic:\r\n\tDelegateComparer(AbstractDelegate const & deleg) : deleg_(deleg) {}\r\n\tbool operator()(AbstractConnection const * conn) const { return conn->recieverDelegate() == deleg_; }\r\nprivate:\r\n\tAbstractDelegate const & deleg_;\r\n};\r\n\r\nclass ConnectionList::PeerComparer\r\n{\r\npublic:\r\n\tPeerComparer(ConnectionList * peer) : peer_(peer) {}\r\n\tbool operator()(AbstractConnection const * conn) const { return conn->hasPeer(peer_); }\r\nprivate:\r\n\tConnectionList * const peer_;\r\n};\r\n\r\nclass ConnectionList::FullComparer\r\n{\r\npublic:\r\n\tFullComparer(ConnectionList * peer, AbstractDelegate const & deleg) : e_(peer), d_(deleg) {}\r\n\tbool operator()(AbstractConnection const * conn) const { return e_(conn) && d_(conn); }\r\nprivate:\r\n\tPeerComparer e_;\r\n\tDelegateComparer d_;\r\n};\r\n\r\nsize_t ConnectionList::connectionCount() const\r\n{\r\n\tThreadDataLocker lock(lock_);\r\n\treturn data_.constRef().size();\r\n}\r\n\r\ntemplate inline size_t ConnectionList::getConnectionCount(Comparer const & comp) const\r\n{\r\n\tThreadDataLocker lock(lock_);\r\n\tConnectionsVector const & connections = data_.constRef();\r\n\tsize_t retVal = 0;\r\n\tfor(const_iterate(it, connections))\r\n\t{\r\n\t\tAbstractConnection const * conn = *it;\r\n\t\tif(comp(conn)) ++retVal;\r\n\t}\r\n\treturn retVal;\r\n}\r\n\r\nsize_t ConnectionList::connectionCount(AbstractDelegate const & deleg) const\r\n{\r\n\tDelegateComparer comp(deleg);\r\n\treturn getConnectionCount(comp);\r\n}\r\n\r\nsize_t ConnectionList::connectionCount(ConnectionList * peer) const\r\n{\r\n\tPeerComparer comp(peer);\r\n\treturn getConnectionCount(comp);\r\n}\r\n\r\nsize_t ConnectionList::connectionCount(ConnectionList * peer, AbstractDelegate const & deleg) const\r\n{\r\n\tFullComparer comp(peer, deleg);\r\n\treturn getConnectionCount(comp);\r\n}\r\n\r\nbool ConnectionList::hasConnections() const\r\n{\r\n\tThreadDataLocker lock(lock_);\r\n\treturn !data_.constRef().empty();\r\n}\r\n\r\ntemplate inline bool ConnectionList::getHasConnections(Comparer const & comp) const\r\n{\r\n\tThreadDataLocker lock(lock_);\r\n\tConnectionsVector const & connections = data_.constRef();\t\r\n\tfor(const_iterate(it, connections))\r\n\t{\r\n\t\tAbstractConnection const * conn = *it;\r\n\t\tif(comp(conn)) return true;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nbool ConnectionList::hasConnections(AbstractDelegate const & deleg) const\r\n{\r\n\tDelegateComparer comp(deleg);\r\n\treturn getHasConnections(comp);\r\n}\r\n\r\nbool ConnectionList::hasConnections(ConnectionList * peer) const\r\n{\r\n\tPeerComparer comp(peer);\r\n\treturn getHasConnections(comp);\r\n}\r\n\r\nbool ConnectionList::hasConnections(ConnectionList * peer, AbstractDelegate const & deleg) const\r\n{\r\n\tFullComparer comp(peer, deleg);\r\n\treturn getHasConnections(comp);\r\n}\r\n\r\ntemplate inline size_t ConnectionList::doDisconnectAll(Comparer const & comp)\r\n{\r\n\tConnectionsVector needRelock;\r\n\tsize_t retVal = 0;\r\n\t{\r\n\t\tThreadDataLocker lock(lock_);\r\n\t\tConnectionsVector & connections = data_.mutableRef();\r\n\t\tfor(size_t i = 0; i < connections.size(); )\r\n\t\t{\r\n\t\t\tAbstractConnection * conn = connections.at(i);\r\n\t\t\tif(!comp(conn))\r\n\t\t\t{\r\n\t\t\t\t++i;\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\t++retVal;\r\n\t\t\tbool done = conn->tryDisconnectWithLock(lock_);\r\n\t\t\tif(!done)\r\n\t\t\t{\r\n\t\t\t\tconn->retain();\r\n\t\t\t\tneedRelock.push_back(conn);\r\n\t\t\t\t++i;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfor(const_iterate(it, needRelock))\r\n\t{\r\n\t\tAbstractConnection * conn = *it;\r\n\t\tconn->disconnect();\r\n\t\tconn->release();\r\n\t}\r\n\treturn retVal;\r\n}\r\n\r\nsize_t ConnectionList::disconnectAll()\r\n{\r\n\tNullComparer comp;\r\n\treturn doDisconnectAll(comp);\r\n}\r\n\r\nsize_t ConnectionList::disconnectAll(AbstractDelegate const & deleg)\r\n{\r\n\tDelegateComparer comp(deleg);\r\n\treturn doDisconnectAll(comp);\r\n}\r\n\r\nsize_t ConnectionList::disconnectAll(ConnectionList * peer, AbstractDelegate const & deleg)\r\n{\r\n\tFullComparer comp(peer, deleg);\r\n\treturn doDisconnectAll(comp);\r\n}\r\n\r\nsize_t ConnectionList::disconnectAll(ConnectionList * peer)\r\n{\r\n\tPeerComparer comp(peer);\r\n\treturn doDisconnectAll(comp);\r\n}\r\n\r\ntemplate inline bool ConnectionList::doDisconnectOne(Comparer const & comp)\r\n{\r\n\tAbstractConnection * needRelock = 0;\r\n\t{\r\n\t\tThreadDataLocker lock(lock_);\r\n\t\tConnectionsVector & connections = data_.mutableRef();\r\n\t\tfor(size_t i = 0; i < connections.size(); )\r\n\t\t{\r\n\t\t\tAbstractConnection * conn = connections.at(i);\r\n\t\t\tif(!comp(conn))\r\n\t\t\t{\r\n\t\t\t\t++i;\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tbool done = conn->tryDisconnectWithLock(lock_);\r\n\t\t\tif(done) return true;\r\n\t\t\tneedRelock = conn;\r\n\t\t\tconn->retain();\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tif(!needRelock) return false;\r\n\r\n\tneedRelock->disconnect();\r\n\tneedRelock->release();\r\n\treturn true;\r\n}\r\n\r\nbool ConnectionList::disconnectOne(AbstractDelegate const & deleg)\r\n{\r\n\tDelegateComparer comp(deleg);\r\n\treturn doDisconnectOne(comp);\r\n}\r\n\r\nbool ConnectionList::disconnectOne(ConnectionList * peer)\r\n{\r\n\tPeerComparer comp(peer);\r\n\treturn doDisconnectOne(comp);\r\n}\r\n\r\nbool ConnectionList::disconnectOne(ConnectionList * peer, AbstractDelegate const & deleg)\r\n{\r\n\tFullComparer comp(peer, deleg);\r\n\treturn doDisconnectOne(comp);\r\n}\r\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (c) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtMultimedia module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at http:\/\/www.qtsoftware.com\/contact.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qmediaplayercontrol.h\"\n#include \"qabstractmediacontrol_p.h\"\n#include \"qmediasource.h\"\n\n\n\/*!\n \\class QMediaPlayerControl\n \\ingroup multimedia\n\n \\preliminary\n \\brief The abstract class for controling media playback, this is proivided\n by a QAbstractMediaService object, and is used by QMediaPlayer for playback.\n\n \\sa QAbstractMediaSerice, QMediaPlayer\n*\/\n\nQMediaPlayerControl::~QMediaPlayerControl()\n{\n}\n\nQMediaPlayerControl::QMediaPlayerControl(QObject *parent):\n QAbstractMediaControl(*new QAbstractMediaControlPrivate, parent)\n{\n\/\/ addPropertyWatch(\"position\");\n}\nFix typos.\/****************************************************************************\n**\n** Copyright (c) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtMultimedia module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at http:\/\/www.qtsoftware.com\/contact.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qmediaplayercontrol.h\"\n#include \"qabstractmediacontrol_p.h\"\n#include \"qmediasource.h\"\n\n\n\/*!\n \\class QMediaPlayerControl\n \\ingroup multimedia\n\n \\preliminary\n \\brief The abstract class for controling media playback, this is provided\n by a QAbstractMediaService object, and is used by QMediaPlayer for playback.\n\n \\sa QAbstractMediaService, QMediaPlayer\n*\/\n\nQMediaPlayerControl::~QMediaPlayerControl()\n{\n}\n\nQMediaPlayerControl::QMediaPlayerControl(QObject *parent):\n QAbstractMediaControl(*new QAbstractMediaControlPrivate, parent)\n{\n\/\/ addPropertyWatch(\"position\");\n}\n<|endoftext|>"} {"text":"\/* dtkComposerEvaluator.cpp ---\n *\n * Author: tkloczko\n * Copyright (C) 2011 - Thibaud Kloczko, Inria.\n * Created: Mon Jan 30 11:34:40 2012 (+0100)\n * Version: $Id$\n * Last-Updated: Fri Sep 28 23:01:51 2012 (+0200)\n * By: tkloczko\n * Update #: 782\n *\/\n\n\/* Commentary:\n *\n *\/\n\n\/* Change log:\n *\n *\/\n\n#include \"dtkComposerEvaluator.h\"\n#include \"dtkComposerEvaluator_p.h\"\n#include \"dtkComposerGraph.h\"\n#include \"dtkComposerGraphEdge.h\"\n#include \"dtkComposerGraphNode.h\"\n#include \"dtkComposerGraphNodeBegin.h\"\n#include \"dtkComposerGraphNodeEnd.h\"\n\n#include \n#include \n\n#include \n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helper definitions\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#define DTK_DEBUG_COMPOSER_EVALUATION 0\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ dtkComposerEvaluatorPrivate\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ dtkComposerEvaluator\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ndtkComposerEvaluator::dtkComposerEvaluator(QObject *parent) : QObject(parent), d(new dtkComposerEvaluatorPrivate)\n{\n d->should_stop = false;\n d->stack.setCapacity(1024);\n d->max_stack_size = 0;\n}\n\ndtkComposerEvaluator::~dtkComposerEvaluator(void)\n{\n delete d;\n\n d = NULL;\n}\n\n\nvoid dtkComposerEvaluator::setGraph(dtkComposerGraph *graph)\n{\n d->graph = graph;\n}\n\nvoid dtkComposerEvaluator::run(bool run_concurrent)\n{\n QTime time; time.start();\n\n d->stack.clear();\n d->stack.append(d->graph->root());\n\n emit evaluationStarted();\n\n while (this->step(run_concurrent) && !d->should_stop);\n if (!d->should_stop) {\n QString msg = QString(\"Evaluation finished in %1 ms\").arg(time.elapsed());\n dtkInfo() << msg;\n dtkNotify(msg,30000);\n d->max_stack_size = 0;\n } else {\n QString msg = QString(\"Evaluation stopped after %1 ms\").arg(time.elapsed());\n dtkInfo() << msg;\n dtkNotify(msg,30000);\n }\n\n d->should_stop = false;\n\n emit evaluationStopped();\n}\n\nvoid dtkComposerEvaluator::stop(void)\n{\n d->should_stop = true;\n}\n\nvoid dtkComposerEvaluator::reset(void)\n{\n d->stack.clear();\n d->should_stop = false;\n}\n\nvoid dtkComposerEvaluator::cont(bool run_concurrent)\n{\n\n if (d->stack.isEmpty()) {\n this->run(run_concurrent);\n return;\n }\n\n\n while (this->step(run_concurrent) && !d->should_stop);\n if (!d->should_stop) {\n QString msg = QString(\"Evaluation resumed and finished\");\n dtkInfo() << msg;\n dtkNotify(msg,30000);\n } else {\n QString msg = QString(\"Evaluation stopped \");\n dtkInfo() << msg;\n dtkNotify(msg,30000);\n dtkInfo() << \"stack size: \" << d->stack.size();\n }\n\n d->should_stop = false;\n\n emit evaluationStopped();\n}\n\nvoid dtkComposerEvaluator::logStack(void)\n{\n \/\/ QListIterator i(d->stack);\n \/\/ dtkDebug() << \"stack content:\";\n \/\/ while (i.hasNext())\n \/\/ dtkDebug() << i.next()->title();\n \/\/ dtkDebug() << \"stack end\";\n}\n\nvoid dtkComposerEvaluator::next(bool run_concurrent)\n{\n if (d->stack.isEmpty())\n return;\n\n dtkComposerGraphNode *first = d->stack.first();\n if (dynamic_cast(first)) {\n \/\/ Begin node, look for the corresponding End node\n dtkComposerGraphNode *end = NULL;\n foreach(dtkComposerGraphNode *n, d->graph->nodes())\n if ((dynamic_cast(n)) && n->wrapee() == first->wrapee()) {\n end = n;\n end->setBreakPoint();\n break;\n }\n while (d->current != end) \/\/ we must continue if a node inside the begin\/end contains a breakpoint\n this->cont(run_concurrent);\n this->step(run_concurrent); \/\/ eval End\n } else {\n this->step(run_concurrent);\n }\n}\n\nbool dtkComposerEvaluator::step(bool run_concurrent)\n{\n if (d->stack.isEmpty())\n return false;\n\n d->current = d->stack.takeFirst();\n \/\/ dtkTrace() << \"handle \" << d->current->title();\n bool runnable = true;\n\n dtkComposerGraphNodeList::const_iterator it;\n dtkComposerGraphNodeList::const_iterator ite;\n dtkComposerGraphNode *node ;\n\n dtkComposerGraphNodeList preds = d->current->predecessors();\n it = preds.constBegin();\n ite = preds.constEnd();\n while(it != ite) {\n node = *it++;\n if (node->status() != dtkComposerGraphNode::Done) {\n if (!node->endloop()) {\n runnable = false;\n break;\n } else {\n \/\/ predecessor is an end loop, we can continue, but we must unset the endloop flag.\n \/\/ dtkTrace() << \"predecessor of \"<< d->current->title() << \" is an end loop, continue\" << node->title();\n node->setEndLoop(false);\n }\n }\n }\n\n if (runnable) {\n if (d->current->breakpoint() && d->current->status() == dtkComposerGraphNode::Ready ) {\n dtkTrace() << \"break point reached\";\n d->current->setStatus(dtkComposerGraphNode::Break);\n d->stack.append( d->current);\n return false;\n }\n if (run_concurrent && (d->current->kind() == dtkComposerGraphNode::Process)){\n \/\/ dtkDebug() << \"running process node in another thread\"<< d->current->title();\n QtConcurrent::run(d->current, &dtkComposerGraphNode::eval);\n } else if ((d->current->kind() == dtkComposerGraphNode::View)) {\n connect(this, SIGNAL(runMainThread()), d->current, SLOT(eval()),Qt::BlockingQueuedConnection);\n \/\/ dtkTrace() << \"emit signal and wait for GUI thread to run the node\";\n emit runMainThread();\n disconnect(this, SIGNAL(runMainThread()), d->current, SLOT(eval()));\n } else {\n \/\/ dtkTrace() << \"evaluating leaf node\"<< d->current->title();\n d->current->eval();\n }\n\n dtkComposerGraphNodeList s = d->current->successors();\n it = s.constBegin();\n ite = s.constEnd();\n while(it != ite) {\n node = *it++;\n bool stacked = false;\n if (!d->stack.isEmpty()) {\n int j = d->stack.firstIndex();\n while(j <= d->stack.lastIndex() && !stacked)\n stacked = (d->stack.at(j++) == node);\n }\n \/\/ dtkTrace() << \"add successor to stack \" << node->title();\n if (!stacked)\n d->stack.append(node);\n }\n } else if (run_concurrent) {\n dtkTrace() << \"add back current node to stack: \"<< d->current->title();\n d->stack.append(d->current);\n }\n \/\/ if (d->stack.size() > d->max_stack_size) {\n \/\/ d->max_stack_size = d->stack.size();\n \/\/ dtkDebug() << \"Max stack size raised: \"<< d->max_stack_size;\n \/\/ }\n\n return !d->stack.isEmpty();\n}\nLats one ;-) ....\/* dtkComposerEvaluator.cpp ---\n *\n * Author: tkloczko\n * Copyright (C) 2011 - Thibaud Kloczko, Inria.\n * Created: Mon Jan 30 11:34:40 2012 (+0100)\n * Version: $Id$\n * Last-Updated: Fri Sep 28 23:59:12 2012 (+0200)\n * By: tkloczko\n * Update #: 787\n *\/\n\n\/* Commentary:\n *\n *\/\n\n\/* Change log:\n *\n *\/\n\n#include \"dtkComposerEvaluator.h\"\n#include \"dtkComposerEvaluator_p.h\"\n#include \"dtkComposerGraph.h\"\n#include \"dtkComposerGraphEdge.h\"\n#include \"dtkComposerGraphNode.h\"\n#include \"dtkComposerGraphNodeBegin.h\"\n#include \"dtkComposerGraphNodeEnd.h\"\n\n#include \n#include \n\n#include \n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helper definitions\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#define DTK_DEBUG_COMPOSER_EVALUATION 0\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ dtkComposerEvaluatorPrivate\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ dtkComposerEvaluator\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ndtkComposerEvaluator::dtkComposerEvaluator(QObject *parent) : QObject(parent), d(new dtkComposerEvaluatorPrivate)\n{\n d->should_stop = false;\n d->stack.setCapacity(1024);\n d->max_stack_size = 0;\n}\n\ndtkComposerEvaluator::~dtkComposerEvaluator(void)\n{\n delete d;\n\n d = NULL;\n}\n\n\nvoid dtkComposerEvaluator::setGraph(dtkComposerGraph *graph)\n{\n d->graph = graph;\n}\n\nvoid dtkComposerEvaluator::run(bool run_concurrent)\n{\n QTime time; time.start();\n\n d->stack.clear();\n d->stack.append(d->graph->root());\n\n emit evaluationStarted();\n\n while (this->step(run_concurrent) && !d->should_stop);\n if (!d->should_stop) {\n QString msg = QString(\"Evaluation finished in %1 ms\").arg(time.elapsed());\n dtkInfo() << msg;\n dtkNotify(msg,30000);\n d->max_stack_size = 0;\n } else {\n QString msg = QString(\"Evaluation stopped after %1 ms\").arg(time.elapsed());\n dtkInfo() << msg;\n dtkNotify(msg,30000);\n }\n\n d->should_stop = false;\n\n emit evaluationStopped();\n}\n\nvoid dtkComposerEvaluator::stop(void)\n{\n d->should_stop = true;\n}\n\nvoid dtkComposerEvaluator::reset(void)\n{\n d->stack.clear();\n d->should_stop = false;\n}\n\nvoid dtkComposerEvaluator::cont(bool run_concurrent)\n{\n\n if (d->stack.isEmpty()) {\n this->run(run_concurrent);\n return;\n }\n\n\n while (this->step(run_concurrent) && !d->should_stop);\n if (!d->should_stop) {\n QString msg = QString(\"Evaluation resumed and finished\");\n dtkInfo() << msg;\n dtkNotify(msg,30000);\n } else {\n QString msg = QString(\"Evaluation stopped \");\n dtkInfo() << msg;\n dtkNotify(msg,30000);\n dtkInfo() << \"stack size: \" << d->stack.size();\n }\n\n d->should_stop = false;\n\n emit evaluationStopped();\n}\n\nvoid dtkComposerEvaluator::logStack(void)\n{\n \/\/ QListIterator i(d->stack);\n \/\/ dtkDebug() << \"stack content:\";\n \/\/ while (i.hasNext())\n \/\/ dtkDebug() << i.next()->title();\n \/\/ dtkDebug() << \"stack end\";\n}\n\nvoid dtkComposerEvaluator::next(bool run_concurrent)\n{\n if (d->stack.isEmpty())\n return;\n\n dtkComposerGraphNode *first = d->stack.first();\n if (dynamic_cast(first)) {\n \/\/ Begin node, look for the corresponding End node\n dtkComposerGraphNode *end = NULL;\n foreach(dtkComposerGraphNode *n, d->graph->nodes())\n if ((dynamic_cast(n)) && n->wrapee() == first->wrapee()) {\n end = n;\n end->setBreakPoint();\n break;\n }\n while (d->current != end) \/\/ we must continue if a node inside the begin\/end contains a breakpoint\n this->cont(run_concurrent);\n this->step(run_concurrent); \/\/ eval End\n } else {\n this->step(run_concurrent);\n }\n}\n\nbool dtkComposerEvaluator::step(bool run_concurrent)\n{\n if (d->stack.isEmpty())\n return false;\n\n d->current = d->stack.takeFirst();\n \/\/ dtkTrace() << \"handle \" << d->current->title();\n bool runnable = true;\n\n dtkComposerGraphNodeList::const_iterator it;\n dtkComposerGraphNodeList::const_iterator ite;\n dtkComposerGraphNode *node ;\n\n dtkComposerGraphNodeList preds = d->current->predecessors();\n it = preds.constBegin();\n ite = preds.constEnd();\n while(it != ite) {\n node = *it++;\n if (node->status() != dtkComposerGraphNode::Done) {\n if (!node->endloop()) {\n runnable = false;\n break;\n } else {\n \/\/ predecessor is an end loop, we can continue, but we must unset the endloop flag.\n \/\/ dtkTrace() << \"predecessor of \"<< d->current->title() << \" is an end loop, continue\" << node->title();\n node->setEndLoop(false);\n }\n }\n }\n\n if (runnable) {\n if (d->current->breakpoint() && d->current->status() == dtkComposerGraphNode::Ready ) {\n dtkTrace() << \"break point reached\";\n d->current->setStatus(dtkComposerGraphNode::Break);\n d->stack.append( d->current);\n return false;\n }\n if (run_concurrent && (d->current->kind() == dtkComposerGraphNode::Process)){\n \/\/ dtkDebug() << \"running process node in another thread\"<< d->current->title();\n QtConcurrent::run(d->current, &dtkComposerGraphNode::eval);\n } else if ((d->current->kind() == dtkComposerGraphNode::View)) {\n connect(this, SIGNAL(runMainThread()), d->current, SLOT(eval()),Qt::BlockingQueuedConnection);\n \/\/ dtkTrace() << \"emit signal and wait for GUI thread to run the node\";\n emit runMainThread();\n disconnect(this, SIGNAL(runMainThread()), d->current, SLOT(eval()));\n } else {\n \/\/ dtkTrace() << \"evaluating leaf node\"<< d->current->title();\n d->current->eval();\n }\n\n dtkComposerGraphNodeList s = d->current->successors();\n it = s.constBegin();\n ite = s.constEnd();\n if (!d->stack.isEmpty()) {\n while(it != ite) {\n node = *it++;\n bool stacked = false;\n int j = d->stack.firstIndex();\n while(j <= d->stack.lastIndex() && !stacked)\n stacked = (d->stack.at(j++) == node);\n \/\/ dtkTrace() << \"add successor to stack \" << node->title();\n if (!stacked)\n d->stack.append(node);\n }\n } else {\n while(it != ite)\n d->stack.append(*it++); \n }\n \n\n \/\/ while(it != ite) {\n \/\/ node = *it++;\n \/\/ bool stacked = false;\n \/\/ if (!d->stack.isEmpty()) {\n \/\/ int j = d->stack.firstIndex();\n \/\/ while(j <= d->stack.lastIndex() && !stacked)\n \/\/ stacked = (d->stack.at(j++) == node);\n \/\/ }\n \/\/ \/\/ dtkTrace() << \"add successor to stack \" << node->title();\n \/\/ if (!stacked)\n \/\/ d->stack.append(node);\n \/\/ }\n } else if (run_concurrent) {\n dtkTrace() << \"add back current node to stack: \"<< d->current->title();\n d->stack.append(d->current);\n }\n \/\/ if (d->stack.size() > d->max_stack_size) {\n \/\/ d->max_stack_size = d->stack.size();\n \/\/ dtkDebug() << \"Max stack size raised: \"<< d->max_stack_size;\n \/\/ }\n\n return !d->stack.isEmpty();\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n *\n * Copyright (c) 2013-2014 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n \/* @file enginefailure.cpp\n * Helper class for a fixedwing engine failure mode\n *\n * @author Thomas Gubler \n *\/\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"navigator.h\"\n#include \"enginefailure.h\"\n\n#define DELAY_SIGMA\t0.01f\n\nEngineFailure::EngineFailure(Navigator *navigator, const char *name) :\n\tMissionBlock(navigator, name),\n\t_ef_state(EF_STATE_NONE)\n{\n\t\/* load initial params *\/\n\tupdateParams();\n\t\/* initial reset *\/\n\ton_inactive();\n}\n\nEngineFailure::~EngineFailure()\n{\n}\n\nvoid\nEngineFailure::on_inactive()\n{\n\t_ef_state = EF_STATE_NONE;\n}\n\nvoid\nEngineFailure::on_activation()\n{\n\t_ef_state = EF_STATE_LOITERDOWN;\n\tset_ef_item();\n}\n\nvoid\nEngineFailure::on_active()\n{\n\tif (is_mission_item_reached()) {\n\t\tadvance_ef();\n\t\tset_ef_item();\n\t}\n}\n\nvoid\nEngineFailure::set_ef_item()\n{\n\tstruct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet();\n\n\t\/* make sure we have the latest params *\/\n\tupdateParams();\n\n\tset_previous_pos_setpoint();\n\t_navigator->set_can_loiter_at_sp(false);\n\n\tswitch (_ef_state) {\n\tcase EF_STATE_LOITERDOWN: {\n\t\t\/\/XXX create mission item at ground (below?) here\n\n\t\t_mission_item.lat = _navigator->get_global_position()->lat;\n\t\t_mission_item.lon = _navigator->get_global_position()->lon;\n\t\t_mission_item.altitude_is_relative = false;\n\t\t \/\/XXX setting altitude to a very low value, evaluate other options\n\t\t_mission_item.altitude = _navigator->get_home_position()->alt - 1000.0f;\n\t\t_mission_item.yaw = NAN;\n\t\t_mission_item.loiter_radius = _navigator->get_loiter_radius();\n\t\t_mission_item.loiter_direction = 1;\n\t\t_mission_item.nav_cmd = NAV_CMD_LOITER_UNLIMITED;\n\t\t_mission_item.acceptance_radius = _navigator->get_acceptance_radius();\n\t\t_mission_item.pitch_min = 0.0f;\n\t\t_mission_item.autocontinue = true;\n\t\t_mission_item.origin = ORIGIN_ONBOARD;\n\n\t\t_navigator->set_can_loiter_at_sp(true);\n\t\tbreak;\n\t}\n\tdefault:\n\t\tbreak;\n\t}\n\n\treset_mission_item_reached();\n\n\t\/* convert mission item to current position setpoint and make it valid *\/\n\tmission_item_to_position_setpoint(&_mission_item, &pos_sp_triplet->current);\n\tpos_sp_triplet->next.valid = false;\n\n\t_navigator->set_position_setpoint_triplet_updated();\n}\n\nvoid\nEngineFailure::advance_ef()\n{\n\tswitch (_ef_state) {\n\tcase EF_STATE_NONE:\n\t\t_ef_state = EF_STATE_LOITERDOWN;\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\nengine fail: small state machine fix\/****************************************************************************\n *\n * Copyright (c) 2013-2014 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n \/* @file enginefailure.cpp\n * Helper class for a fixedwing engine failure mode\n *\n * @author Thomas Gubler \n *\/\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"navigator.h\"\n#include \"enginefailure.h\"\n\n#define DELAY_SIGMA\t0.01f\n\nEngineFailure::EngineFailure(Navigator *navigator, const char *name) :\n\tMissionBlock(navigator, name),\n\t_ef_state(EF_STATE_NONE)\n{\n\t\/* load initial params *\/\n\tupdateParams();\n\t\/* initial reset *\/\n\ton_inactive();\n}\n\nEngineFailure::~EngineFailure()\n{\n}\n\nvoid\nEngineFailure::on_inactive()\n{\n\t_ef_state = EF_STATE_NONE;\n}\n\nvoid\nEngineFailure::on_activation()\n{\n\t_ef_state = EF_STATE_NONE;\n\tadvance_ef();\n\tset_ef_item();\n}\n\nvoid\nEngineFailure::on_active()\n{\n\tif (is_mission_item_reached()) {\n\t\tadvance_ef();\n\t\tset_ef_item();\n\t}\n}\n\nvoid\nEngineFailure::set_ef_item()\n{\n\tstruct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet();\n\n\t\/* make sure we have the latest params *\/\n\tupdateParams();\n\n\tset_previous_pos_setpoint();\n\t_navigator->set_can_loiter_at_sp(false);\n\n\tswitch (_ef_state) {\n\tcase EF_STATE_LOITERDOWN: {\n\t\t\/\/XXX create mission item at ground (below?) here\n\n\t\t_mission_item.lat = _navigator->get_global_position()->lat;\n\t\t_mission_item.lon = _navigator->get_global_position()->lon;\n\t\t_mission_item.altitude_is_relative = false;\n\t\t \/\/XXX setting altitude to a very low value, evaluate other options\n\t\t_mission_item.altitude = _navigator->get_home_position()->alt - 1000.0f;\n\t\t_mission_item.yaw = NAN;\n\t\t_mission_item.loiter_radius = _navigator->get_loiter_radius();\n\t\t_mission_item.loiter_direction = 1;\n\t\t_mission_item.nav_cmd = NAV_CMD_LOITER_UNLIMITED;\n\t\t_mission_item.acceptance_radius = _navigator->get_acceptance_radius();\n\t\t_mission_item.pitch_min = 0.0f;\n\t\t_mission_item.autocontinue = true;\n\t\t_mission_item.origin = ORIGIN_ONBOARD;\n\n\t\t_navigator->set_can_loiter_at_sp(true);\n\t\tbreak;\n\t}\n\tdefault:\n\t\tbreak;\n\t}\n\n\treset_mission_item_reached();\n\n\t\/* convert mission item to current position setpoint and make it valid *\/\n\tmission_item_to_position_setpoint(&_mission_item, &pos_sp_triplet->current);\n\tpos_sp_triplet->next.valid = false;\n\n\t_navigator->set_position_setpoint_triplet_updated();\n}\n\nvoid\nEngineFailure::advance_ef()\n{\n\tswitch (_ef_state) {\n\tcase EF_STATE_NONE:\n\t\tmavlink_log_info(_navigator->get_mavlink_fd(), \"#audio: Engine failure. Loitering down\");\n\t\t_ef_state = EF_STATE_LOITERDOWN;\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\n<|endoftext|>"} {"text":"\/\/===-- asan_linux.cc -----------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file is a part of AddressSanitizer, an address sanity checker.\n\/\/\n\/\/ Linux-specific details.\n\/\/===----------------------------------------------------------------------===\/\/\n#ifdef __linux__\n\n#include \"asan_interceptors.h\"\n#include \"asan_internal.h\"\n#include \"asan_lock.h\"\n#include \"asan_procmaps.h\"\n#include \"asan_thread.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef ANDROID\n\/\/ FIXME: where to get ucontext on Android?\n#include \n#endif\n\nnamespace __asan {\n\nvoid *AsanDoesNotSupportStaticLinkage() {\n \/\/ This will fail to link with -static.\n return &_DYNAMIC; \/\/ defined in link.h\n}\n\nvoid GetPcSpBp(void *context, uintptr_t *pc, uintptr_t *sp, uintptr_t *bp) {\n#ifdef ANDROID\n *pc = *sp = *bp = 0;\n#elif defined(__arm__)\n ucontext_t *ucontext = (ucontext_t*)context;\n *pc = ucontext->uc_mcontext.arm_pc;\n *bp = ucontext->uc_mcontext.arm_fp;\n *sp = ucontext->uc_mcontext.arm_sp;\n# elif defined(__x86_64__)\n ucontext_t *ucontext = (ucontext_t*)context;\n *pc = ucontext->uc_mcontext.gregs[REG_RIP];\n *bp = ucontext->uc_mcontext.gregs[REG_RBP];\n *sp = ucontext->uc_mcontext.gregs[REG_RSP];\n# elif defined(__i386__)\n ucontext_t *ucontext = (ucontext_t*)context;\n *pc = ucontext->uc_mcontext.gregs[REG_EIP];\n *bp = ucontext->uc_mcontext.gregs[REG_EBP];\n *sp = ucontext->uc_mcontext.gregs[REG_ESP];\n#else\n# error \"Unsupported arch\"\n#endif\n}\n\nbool AsanInterceptsSignal(int signum) {\n return signum == SIGSEGV && FLAG_handle_segv;\n}\n\nstatic void *asan_mmap(void *addr, size_t length, int prot, int flags,\n int fd, uint64_t offset) {\n# if __WORDSIZE == 64\n return (void *)syscall(__NR_mmap, addr, length, prot, flags, fd, offset);\n# else\n return (void *)syscall(__NR_mmap2, addr, length, prot, flags, fd, offset);\n# endif\n}\n\nvoid *AsanMmapSomewhereOrDie(size_t size, const char *mem_type) {\n size = RoundUpTo(size, kPageSize);\n void *res = asan_mmap(0, size,\n PROT_READ | PROT_WRITE,\n MAP_PRIVATE | MAP_ANON, -1, 0);\n if (res == (void*)-1) {\n OutOfMemoryMessageAndDie(mem_type, size);\n }\n return res;\n}\n\nvoid *AsanMmapFixedNoReserve(uintptr_t fixed_addr, size_t size) {\n return asan_mmap((void*)fixed_addr, size,\n PROT_READ | PROT_WRITE,\n MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE,\n 0, 0);\n}\n\nvoid *AsanMmapFixedReserve(uintptr_t fixed_addr, size_t size) {\n return asan_mmap((void*)fixed_addr, size,\n PROT_READ | PROT_WRITE,\n MAP_PRIVATE | MAP_ANON | MAP_FIXED,\n 0, 0);\n}\n\nvoid *AsanMprotect(uintptr_t fixed_addr, size_t size) {\n return asan_mmap((void*)fixed_addr, size,\n PROT_NONE,\n MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE,\n 0, 0);\n}\n\nvoid AsanUnmapOrDie(void *addr, size_t size) {\n if (!addr || !size) return;\n int res = syscall(__NR_munmap, addr, size);\n if (res != 0) {\n Report(\"Failed to unmap\\n\");\n AsanDie();\n }\n}\n\nsize_t AsanWrite(int fd, const void *buf, size_t count) {\n return (size_t)syscall(__NR_write, fd, buf, count);\n}\n\nint AsanOpenReadonly(const char* filename) {\n return open(filename, O_RDONLY);\n}\n\n\/\/ Like getenv, but reads env directly from \/proc and does not use libc.\n\/\/ This function should be called first inside __asan_init.\nconst char* AsanGetEnv(const char* name) {\n static char *environ;\n static size_t len;\n static bool inited;\n if (!inited) {\n inited = true;\n size_t environ_size;\n len = ReadFileToBuffer(\"\/proc\/self\/environ\",\n &environ, &environ_size, 1 << 20);\n }\n if (!environ || len == 0) return NULL;\n size_t namelen = internal_strlen(name);\n const char *p = environ;\n while (*p != '\\0') { \/\/ will happen at the \\0\\0 that terminates the buffer\n \/\/ proc file has the format NAME=value\\0NAME=value\\0NAME=value\\0...\n const char* endp =\n (char*)internal_memchr(p, '\\0', len - (p - environ));\n if (endp == NULL) \/\/ this entry isn't NUL terminated\n return NULL;\n else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') \/\/ Match.\n return p + namelen + 1; \/\/ point after =\n p = endp + 1;\n }\n return NULL; \/\/ Not found.\n}\n\nsize_t AsanRead(int fd, void *buf, size_t count) {\n return (size_t)syscall(__NR_read, fd, buf, count);\n}\n\nint AsanClose(int fd) {\n return close(fd);\n}\n\nAsanProcMaps::AsanProcMaps() {\n proc_self_maps_buff_len_ =\n ReadFileToBuffer(\"\/proc\/self\/maps\", &proc_self_maps_buff_,\n &proc_self_maps_buff_mmaped_size_, 1 << 20);\n CHECK(proc_self_maps_buff_len_ > 0);\n \/\/ AsanWrite(2, proc_self_maps_buff_, proc_self_maps_buff_len_);\n Reset();\n}\n\nAsanProcMaps::~AsanProcMaps() {\n AsanUnmapOrDie(proc_self_maps_buff_, proc_self_maps_buff_mmaped_size_);\n}\n\nvoid AsanProcMaps::Reset() {\n current_ = proc_self_maps_buff_;\n}\n\nbool AsanProcMaps::Next(uintptr_t *start, uintptr_t *end,\n uintptr_t *offset, char filename[],\n size_t filename_size) {\n char *last = proc_self_maps_buff_ + proc_self_maps_buff_len_;\n if (current_ >= last) return false;\n int consumed = 0;\n char flags[10];\n int major, minor;\n uintptr_t inode;\n char *next_line = (char*)internal_memchr(current_, '\\n', last - current_);\n if (next_line == NULL)\n next_line = last;\n if (SScanf(current_,\n \"%lx-%lx %4s %lx %x:%x %ld %n\",\n start, end, flags, offset, &major, &minor,\n &inode, &consumed) != 7)\n return false;\n current_ += consumed;\n \/\/ Skip spaces.\n while (current_ < next_line && *current_ == ' ')\n current_++;\n \/\/ Fill in the filename.\n size_t i = 0;\n while (current_ < next_line) {\n if (filename && i < filename_size - 1)\n filename[i++] = *current_;\n current_++;\n }\n if (filename && i < filename_size)\n filename[i] = 0;\n current_ = next_line + 1;\n return true;\n}\n\nstruct DlIterateData {\n int count;\n uintptr_t addr;\n uintptr_t offset;\n char *filename;\n size_t filename_size;\n};\n\nstatic int dl_iterate_phdr_callback(struct dl_phdr_info *info,\n size_t size, void *raw_data) {\n DlIterateData *data = (DlIterateData*)raw_data;\n int count = data->count++;\n if (info->dlpi_addr > data->addr)\n return 0;\n if (count == 0) {\n \/\/ The first item (the main executable) does not have a so name,\n \/\/ but we can just read it from \/proc\/self\/exe.\n size_t path_len = readlink(\"\/proc\/self\/exe\",\n data->filename, data->filename_size - 1);\n data->filename[path_len] = 0;\n } else {\n CHECK(info->dlpi_name);\n real_strncpy(data->filename, info->dlpi_name, data->filename_size);\n }\n data->offset = data->addr - info->dlpi_addr;\n return 1;\n}\n\n\/\/ Gets the object name and the offset using dl_iterate_phdr.\nbool AsanProcMaps::GetObjectNameAndOffset(uintptr_t addr, uintptr_t *offset,\n char filename[],\n size_t filename_size) {\n DlIterateData data;\n data.count = 0;\n data.addr = addr;\n data.filename = filename;\n data.filename_size = filename_size;\n if (dl_iterate_phdr(dl_iterate_phdr_callback, &data)) {\n *offset = data.offset;\n return true;\n }\n return false;\n}\n\nvoid AsanThread::SetThreadStackTopAndBottom() {\n if (tid() == 0) {\n \/\/ This is the main thread. Libpthread may not be initialized yet.\n struct rlimit rl;\n CHECK(getrlimit(RLIMIT_STACK, &rl) == 0);\n\n \/\/ Find the mapping that contains a stack variable.\n AsanProcMaps proc_maps;\n uintptr_t start, end, offset;\n uintptr_t prev_end = 0;\n while (proc_maps.Next(&start, &end, &offset, NULL, 0)) {\n if ((uintptr_t)&rl < end)\n break;\n prev_end = end;\n }\n CHECK((uintptr_t)&rl >= start && (uintptr_t)&rl < end);\n\n \/\/ Get stacksize from rlimit, but clip it so that it does not overlap\n \/\/ with other mappings.\n size_t stacksize = rl.rlim_cur;\n if (stacksize > end - prev_end)\n stacksize = end - prev_end;\n if (stacksize > kMaxThreadStackSize)\n stacksize = kMaxThreadStackSize;\n stack_top_ = end;\n stack_bottom_ = end - stacksize;\n CHECK(AddrIsInStack((uintptr_t)&rl));\n return;\n }\n pthread_attr_t attr;\n CHECK(pthread_getattr_np(pthread_self(), &attr) == 0);\n size_t stacksize = 0;\n void *stackaddr = NULL;\n pthread_attr_getstack(&attr, &stackaddr, &stacksize);\n pthread_attr_destroy(&attr);\n\n stack_top_ = (uintptr_t)stackaddr + stacksize;\n stack_bottom_ = (uintptr_t)stackaddr;\n \/\/ When running with unlimited stack size, we still want to set some limit.\n \/\/ The unlimited stack size is caused by 'ulimit -s unlimited'.\n \/\/ Also, for some reason, GNU make spawns subrocesses with unlimited stack.\n if (stacksize > kMaxThreadStackSize) {\n stack_bottom_ = stack_top_ - kMaxThreadStackSize;\n }\n CHECK(AddrIsInStack((uintptr_t)&attr));\n}\n\nAsanLock::AsanLock(LinkerInitialized) {\n \/\/ We assume that pthread_mutex_t initialized to all zeroes is a valid\n \/\/ unlocked mutex. We can not use PTHREAD_MUTEX_INITIALIZER as it triggers\n \/\/ a gcc warning:\n \/\/ extended initializer lists only available with -std=c++0x or -std=gnu++0x\n}\n\nvoid AsanLock::Lock() {\n CHECK(sizeof(pthread_mutex_t) <= sizeof(opaque_storage_));\n pthread_mutex_lock((pthread_mutex_t*)&opaque_storage_);\n CHECK(!owner_);\n owner_ = (uintptr_t)pthread_self();\n}\n\nvoid AsanLock::Unlock() {\n CHECK(owner_ == (uintptr_t)pthread_self());\n owner_ = 0;\n pthread_mutex_unlock((pthread_mutex_t*)&opaque_storage_);\n}\n\n} \/\/ namespace __asan\n\n#endif \/\/ __linux__\n[asan] Implement GetObjectNameAndOffset on ARM.\/\/===-- asan_linux.cc -----------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file is a part of AddressSanitizer, an address sanity checker.\n\/\/\n\/\/ Linux-specific details.\n\/\/===----------------------------------------------------------------------===\/\/\n#ifdef __linux__\n\n#include \"asan_interceptors.h\"\n#include \"asan_internal.h\"\n#include \"asan_lock.h\"\n#include \"asan_procmaps.h\"\n#include \"asan_thread.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef ANDROID\n\/\/ FIXME: where to get ucontext on Android?\n#include \n#endif\n\nnamespace __asan {\n\nvoid *AsanDoesNotSupportStaticLinkage() {\n \/\/ This will fail to link with -static.\n return &_DYNAMIC; \/\/ defined in link.h\n}\n\nvoid GetPcSpBp(void *context, uintptr_t *pc, uintptr_t *sp, uintptr_t *bp) {\n#ifdef ANDROID\n *pc = *sp = *bp = 0;\n#elif defined(__arm__)\n ucontext_t *ucontext = (ucontext_t*)context;\n *pc = ucontext->uc_mcontext.arm_pc;\n *bp = ucontext->uc_mcontext.arm_fp;\n *sp = ucontext->uc_mcontext.arm_sp;\n# elif defined(__x86_64__)\n ucontext_t *ucontext = (ucontext_t*)context;\n *pc = ucontext->uc_mcontext.gregs[REG_RIP];\n *bp = ucontext->uc_mcontext.gregs[REG_RBP];\n *sp = ucontext->uc_mcontext.gregs[REG_RSP];\n# elif defined(__i386__)\n ucontext_t *ucontext = (ucontext_t*)context;\n *pc = ucontext->uc_mcontext.gregs[REG_EIP];\n *bp = ucontext->uc_mcontext.gregs[REG_EBP];\n *sp = ucontext->uc_mcontext.gregs[REG_ESP];\n#else\n# error \"Unsupported arch\"\n#endif\n}\n\nbool AsanInterceptsSignal(int signum) {\n return signum == SIGSEGV && FLAG_handle_segv;\n}\n\nstatic void *asan_mmap(void *addr, size_t length, int prot, int flags,\n int fd, uint64_t offset) {\n# if __WORDSIZE == 64\n return (void *)syscall(__NR_mmap, addr, length, prot, flags, fd, offset);\n# else\n return (void *)syscall(__NR_mmap2, addr, length, prot, flags, fd, offset);\n# endif\n}\n\nvoid *AsanMmapSomewhereOrDie(size_t size, const char *mem_type) {\n size = RoundUpTo(size, kPageSize);\n void *res = asan_mmap(0, size,\n PROT_READ | PROT_WRITE,\n MAP_PRIVATE | MAP_ANON, -1, 0);\n if (res == (void*)-1) {\n OutOfMemoryMessageAndDie(mem_type, size);\n }\n return res;\n}\n\nvoid *AsanMmapFixedNoReserve(uintptr_t fixed_addr, size_t size) {\n return asan_mmap((void*)fixed_addr, size,\n PROT_READ | PROT_WRITE,\n MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE,\n 0, 0);\n}\n\nvoid *AsanMmapFixedReserve(uintptr_t fixed_addr, size_t size) {\n return asan_mmap((void*)fixed_addr, size,\n PROT_READ | PROT_WRITE,\n MAP_PRIVATE | MAP_ANON | MAP_FIXED,\n 0, 0);\n}\n\nvoid *AsanMprotect(uintptr_t fixed_addr, size_t size) {\n return asan_mmap((void*)fixed_addr, size,\n PROT_NONE,\n MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE,\n 0, 0);\n}\n\nvoid AsanUnmapOrDie(void *addr, size_t size) {\n if (!addr || !size) return;\n int res = syscall(__NR_munmap, addr, size);\n if (res != 0) {\n Report(\"Failed to unmap\\n\");\n AsanDie();\n }\n}\n\nsize_t AsanWrite(int fd, const void *buf, size_t count) {\n return (size_t)syscall(__NR_write, fd, buf, count);\n}\n\nint AsanOpenReadonly(const char* filename) {\n return open(filename, O_RDONLY);\n}\n\n\/\/ Like getenv, but reads env directly from \/proc and does not use libc.\n\/\/ This function should be called first inside __asan_init.\nconst char* AsanGetEnv(const char* name) {\n static char *environ;\n static size_t len;\n static bool inited;\n if (!inited) {\n inited = true;\n size_t environ_size;\n len = ReadFileToBuffer(\"\/proc\/self\/environ\",\n &environ, &environ_size, 1 << 20);\n }\n if (!environ || len == 0) return NULL;\n size_t namelen = internal_strlen(name);\n const char *p = environ;\n while (*p != '\\0') { \/\/ will happen at the \\0\\0 that terminates the buffer\n \/\/ proc file has the format NAME=value\\0NAME=value\\0NAME=value\\0...\n const char* endp =\n (char*)internal_memchr(p, '\\0', len - (p - environ));\n if (endp == NULL) \/\/ this entry isn't NUL terminated\n return NULL;\n else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') \/\/ Match.\n return p + namelen + 1; \/\/ point after =\n p = endp + 1;\n }\n return NULL; \/\/ Not found.\n}\n\nsize_t AsanRead(int fd, void *buf, size_t count) {\n return (size_t)syscall(__NR_read, fd, buf, count);\n}\n\nint AsanClose(int fd) {\n return close(fd);\n}\n\nAsanProcMaps::AsanProcMaps() {\n proc_self_maps_buff_len_ =\n ReadFileToBuffer(\"\/proc\/self\/maps\", &proc_self_maps_buff_,\n &proc_self_maps_buff_mmaped_size_, 1 << 20);\n CHECK(proc_self_maps_buff_len_ > 0);\n \/\/ AsanWrite(2, proc_self_maps_buff_, proc_self_maps_buff_len_);\n Reset();\n}\n\nAsanProcMaps::~AsanProcMaps() {\n AsanUnmapOrDie(proc_self_maps_buff_, proc_self_maps_buff_mmaped_size_);\n}\n\nvoid AsanProcMaps::Reset() {\n current_ = proc_self_maps_buff_;\n}\n\nbool AsanProcMaps::Next(uintptr_t *start, uintptr_t *end,\n uintptr_t *offset, char filename[],\n size_t filename_size) {\n char *last = proc_self_maps_buff_ + proc_self_maps_buff_len_;\n if (current_ >= last) return false;\n int consumed = 0;\n char flags[10];\n int major, minor;\n uintptr_t inode;\n char *next_line = (char*)internal_memchr(current_, '\\n', last - current_);\n if (next_line == NULL)\n next_line = last;\n if (SScanf(current_,\n \"%lx-%lx %4s %lx %x:%x %ld %n\",\n start, end, flags, offset, &major, &minor,\n &inode, &consumed) != 7)\n return false;\n current_ += consumed;\n \/\/ Skip spaces.\n while (current_ < next_line && *current_ == ' ')\n current_++;\n \/\/ Fill in the filename.\n size_t i = 0;\n while (current_ < next_line) {\n if (filename && i < filename_size - 1)\n filename[i++] = *current_;\n current_++;\n }\n if (filename && i < filename_size)\n filename[i] = 0;\n current_ = next_line + 1;\n return true;\n}\n\n#ifdef __arm__\n\n\/\/ Gets the object name and the offset by walking AsanProcMaps.\nbool AsanProcMaps::GetObjectNameAndOffset(uintptr_t addr, uintptr_t *offset,\n char filename[],\n size_t filename_size) {\n AsanProcMaps proc_maps;\n uintptr_t start, end, file_offset;\n while (proc_maps.Next(&start, &end, &file_offset, filename, filename_size)) {\n if (addr >= start && addr < end) {\n *offset = (addr - start) + file_offset;\n return true;\n }\n }\n if (filename_size)\n filename[0] = '\\0';\n return false;\n}\n\n#else \/\/ __arm__\n\nstruct DlIterateData {\n int count;\n uintptr_t addr;\n uintptr_t offset;\n char *filename;\n size_t filename_size;\n};\n\nstatic int dl_iterate_phdr_callback(struct dl_phdr_info *info,\n size_t size, void *raw_data) {\n DlIterateData *data = (DlIterateData*)raw_data;\n int count = data->count++;\n if (info->dlpi_addr > data->addr)\n return 0;\n if (count == 0) {\n \/\/ The first item (the main executable) does not have a so name,\n \/\/ but we can just read it from \/proc\/self\/exe.\n size_t path_len = readlink(\"\/proc\/self\/exe\",\n data->filename, data->filename_size - 1);\n data->filename[path_len] = 0;\n } else {\n CHECK(info->dlpi_name);\n real_strncpy(data->filename, info->dlpi_name, data->filename_size);\n }\n data->offset = data->addr - info->dlpi_addr;\n return 1;\n}\n\n\/\/ Gets the object name and the offset using dl_iterate_phdr.\nbool AsanProcMaps::GetObjectNameAndOffset(uintptr_t addr, uintptr_t *offset,\n char filename[],\n size_t filename_size) {\n DlIterateData data;\n data.count = 0;\n data.addr = addr;\n data.filename = filename;\n data.filename_size = filename_size;\n if (dl_iterate_phdr(dl_iterate_phdr_callback, &data)) {\n *offset = data.offset;\n return true;\n }\n return false;\n}\n\n#endif \/\/ __arm__\n\nvoid AsanThread::SetThreadStackTopAndBottom() {\n if (tid() == 0) {\n \/\/ This is the main thread. Libpthread may not be initialized yet.\n struct rlimit rl;\n CHECK(getrlimit(RLIMIT_STACK, &rl) == 0);\n\n \/\/ Find the mapping that contains a stack variable.\n AsanProcMaps proc_maps;\n uintptr_t start, end, offset;\n uintptr_t prev_end = 0;\n while (proc_maps.Next(&start, &end, &offset, NULL, 0)) {\n if ((uintptr_t)&rl < end)\n break;\n prev_end = end;\n }\n CHECK((uintptr_t)&rl >= start && (uintptr_t)&rl < end);\n\n \/\/ Get stacksize from rlimit, but clip it so that it does not overlap\n \/\/ with other mappings.\n size_t stacksize = rl.rlim_cur;\n if (stacksize > end - prev_end)\n stacksize = end - prev_end;\n if (stacksize > kMaxThreadStackSize)\n stacksize = kMaxThreadStackSize;\n stack_top_ = end;\n stack_bottom_ = end - stacksize;\n CHECK(AddrIsInStack((uintptr_t)&rl));\n return;\n }\n pthread_attr_t attr;\n CHECK(pthread_getattr_np(pthread_self(), &attr) == 0);\n size_t stacksize = 0;\n void *stackaddr = NULL;\n pthread_attr_getstack(&attr, &stackaddr, &stacksize);\n pthread_attr_destroy(&attr);\n\n stack_top_ = (uintptr_t)stackaddr + stacksize;\n stack_bottom_ = (uintptr_t)stackaddr;\n \/\/ When running with unlimited stack size, we still want to set some limit.\n \/\/ The unlimited stack size is caused by 'ulimit -s unlimited'.\n \/\/ Also, for some reason, GNU make spawns subrocesses with unlimited stack.\n if (stacksize > kMaxThreadStackSize) {\n stack_bottom_ = stack_top_ - kMaxThreadStackSize;\n }\n CHECK(AddrIsInStack((uintptr_t)&attr));\n}\n\nAsanLock::AsanLock(LinkerInitialized) {\n \/\/ We assume that pthread_mutex_t initialized to all zeroes is a valid\n \/\/ unlocked mutex. We can not use PTHREAD_MUTEX_INITIALIZER as it triggers\n \/\/ a gcc warning:\n \/\/ extended initializer lists only available with -std=c++0x or -std=gnu++0x\n}\n\nvoid AsanLock::Lock() {\n CHECK(sizeof(pthread_mutex_t) <= sizeof(opaque_storage_));\n pthread_mutex_lock((pthread_mutex_t*)&opaque_storage_);\n CHECK(!owner_);\n owner_ = (uintptr_t)pthread_self();\n}\n\nvoid AsanLock::Unlock() {\n CHECK(owner_ == (uintptr_t)pthread_self());\n owner_ = 0;\n pthread_mutex_unlock((pthread_mutex_t*)&opaque_storage_);\n}\n\n} \/\/ namespace __asan\n\n#endif \/\/ __linux__\n<|endoftext|>"} {"text":"\/\/\n\/\/ PackageReporter.cpp\n\/\/ Emojicode\n\/\/\n\/\/ Created by Theo Weidmann on 02\/05\/16.\n\/\/ Copyright © 2016 Theo Weidmann. All rights reserved.\n\/\/\n\n#include \n#include \n#include \n#include \n#include \"utf8.h\"\n#include \"Function.hpp\"\n#include \"Class.hpp\"\n#include \"EmojicodeCompiler.hpp\"\n#include \"Enum.hpp\"\n#include \"Protocol.hpp\"\n#include \"PackageReporter.hpp\"\n#include \"TypeContext.hpp\"\n\nenum ReturnManner {\n Return,\n NoReturn,\n CanReturnNothingness\n};\n\nvoid reportDocumentation(const EmojicodeString &documentation) {\n if (documentation.size() == 0) {\n return;\n }\n \n const char *d = documentation.utf8CString();\n printf(\"\\\"documentation\\\":\");\n printJSONStringToFile(d, stdout);\n putc(',', stdout);\n delete [] d;\n}\n\nvoid reportType(const char *key, Type type, TypeContext tc) {\n auto returnTypeName = type.toString(tc, false).c_str();\n \n if (key) {\n printf(\"\\\"%s\\\": {\\\"package\\\": \\\"%s\\\", \\\"name\\\": \\\"%s\\\", \\\"optional\\\": %s}\",\n key, type.typePackage(), returnTypeName, type.optional() ? \"true\" : \"false\");\n }\n else {\n printf(\"{\\\"package\\\": \\\"%s\\\", \\\"name\\\": \\\"%s\\\", \\\"optional\\\": %s}\",\n type.typePackage(), returnTypeName, type.optional() ? \"true\" : \"false\");\n }\n}\n\nvoid commaPrinter(bool *b) {\n if (*b) {\n putc(',', stdout);\n }\n *b = true;\n}\n\nvoid reportGenericArguments(std::map map, std::vector constraints,\n size_t superCount, TypeContext tc) {\n printf(\"\\\"genericArguments\\\": [\");\n \n auto gans = std::vector(map.size());\n for (auto it : map) {\n gans[it.second.reference - superCount] = it.first;\n }\n \n auto reported = false;\n \n for (size_t i = 0; i < gans.size(); i++) {\n auto gan = gans[i];\n auto utf8 = gan.utf8CString();\n commaPrinter(&reported);\n printf(\"{\\\"name\\\": \");\n printJSONStringToFile(utf8, stdout);\n printf(\",\");\n reportType(\"constraint\", constraints[i], tc);\n printf(\"}\");\n delete [] utf8;\n }\n \n printf(\"],\");\n}\n\nvoid reportFunctionInformation(Function *p, ReturnManner returnm, bool last, TypeContext tc) {\n ecCharToCharStack(p->name, nameString);\n \n printf(\"{\");\n printf(\"\\\"name\\\": \\\"%s\\\",\", nameString);\n if (p->access == PRIVATE) {\n printf(\"\\\"access\\\": \\\"🔒\\\",\");\n }\n else if (p->access == PROTECTED) {\n printf(\"\\\"access\\\": \\\"🔐\\\",\");\n }\n else {\n printf(\"\\\"access\\\": \\\"🔓\\\",\");\n }\n \n if (returnm == Return) {\n reportType(\"returnType\", p->returnType, tc);\n putc(',', stdout);\n }\n else if (returnm == CanReturnNothingness) {\n printf(\"\\\"canReturnNothingness\\\": true,\");\n }\n \n reportGenericArguments(p->genericArgumentVariables, p->genericArgumentConstraints, 0, tc);\n reportDocumentation(p->documentationToken);\n \n printf(\"\\\"arguments\\\": [\");\n for (int i = 0; i < p->arguments.size(); i++) {\n printf(\"{\");\n auto argument = p->arguments[i];\n \n const char *varname = argument.name.value.utf8CString();\n \n reportType(\"type\", argument.type, tc);\n printf(\",\\\"name\\\":\");\n printJSONStringToFile(varname, stdout);\n printf(\"}%s\", i + 1 == p->arguments.size() ? \"\" : \",\");\n \n delete [] varname;\n }\n printf(\"]\");\n \n printf(\"}%s\", last ? \"\" : \",\");\n}\n\nvoid reportPackage(Package *package) {\n std::list enums;\n std::list classes;\n std::list protocols;\n \n for (auto exported : package->exportedTypes()) { \/\/ TODO: Add Value Type\n switch (exported.type.type()) {\n case TT_CLASS:\n classes.push_back(exported.type.eclass());\n break;\n case TT_ENUM:\n enums.push_back(exported.type.eenum());\n break;\n case TT_PROTOCOL:\n protocols.push_back(exported.type.protocol());\n break;\n default:\n break;\n }\n }\n \n bool printedClass = false;\n printf(\"{\");\n printf(\"\\\"classes\\\": [\");\n for (auto eclass : classes) {\n if (printedClass) {\n putchar(',');\n }\n printedClass = true;\n \n printf(\"{\");\n \n ecCharToCharStack(eclass->name(), className);\n printf(\"\\\"name\\\": \\\"%s\\\",\", className);\n \n reportGenericArguments(eclass->ownGenericArgumentVariables(), eclass->genericArgumentConstraints(),\n eclass->superGenericArguments().size(), TypeContext(Type(eclass)));\n reportDocumentation(eclass->documentation());\n \n if (eclass->superclass) {\n ecCharToCharStack(eclass->superclass->name(), superClassName);\n printf(\"\\\"superclass\\\": {\\\"package\\\": \\\"%s\\\", \\\"name\\\": \\\"%s\\\"},\",\n eclass->superclass->package()->name(), superClassName);\n }\n \n printf(\"\\\"methods\\\": [\");\n for (size_t i = 0; i < eclass->methodList().size(); i++) {\n Method *method = eclass->methodList()[i];\n reportFunctionInformation(method, Return, i + 1 == eclass->methodList().size(),\n TypeContext(Type(eclass), method));\n }\n printf(\"],\");\n \n printf(\"\\\"initializers\\\": [\");\n for (size_t i = 0; i < eclass->initializerList().size(); i++) {\n Initializer *initializer = eclass->initializerList()[i];\n reportFunctionInformation(initializer, initializer->canReturnNothingness ? CanReturnNothingness : NoReturn,\n i + 1 == eclass->initializerList().size(),\n TypeContext(Type(eclass), initializer));\n }\n printf(\"],\");\n \n printf(\"\\\"classMethods\\\": [\");\n for (size_t i = 0; i < eclass->classMethodList().size(); i++) {\n ClassMethod *classMethod = eclass->classMethodList()[i];\n reportFunctionInformation(classMethod, Return, eclass->classMethodList().size() == i + 1,\n TypeContext(Type(eclass), classMethod));\n }\n printf(\"],\");\n \n printf(\"\\\"conformsTo\\\": [\");\n bool printedProtocol = false;\n for (auto protocol : eclass->protocols()) {\n commaPrinter(&printedProtocol);\n reportType(nullptr, protocol, TypeContext(Type(eclass)));\n }\n printf(\"]}\");\n }\n printf(\"],\");\n \n printf(\"\\\"enums\\\": [\");\n bool printedEnum = false;\n for (auto eenum : enums) {\n if (printedEnum) {\n putchar(',');\n }\n printf(\"{\");\n \n printedEnum = true;\n \n ecCharToCharStack(eenum->name(), enumName);\n printf(\"\\\"name\\\": \\\"%s\\\",\", enumName);\n \n reportDocumentation(eenum->documentation());\n \n bool printedValue = false;\n printf(\"\\\"values\\\": [\");\n for (auto it : eenum->values()) {\n ecCharToCharStack(it.first, value);\n if (printedValue) {\n putchar(',');\n }\n printf(\"\\\"%s\\\"\", value);\n printedValue = true;\n }\n printf(\"]}\");\n }\n printf(\"],\");\n \n printf(\"\\\"protocols\\\": [\");\n bool printedProtocol = false;\n for (auto protocol : protocols) {\n if (printedProtocol) {\n putchar(',');\n }\n printedProtocol = true;\n printf(\"{\");\n \n ecCharToCharStack(protocol->name(), protocolName);\n printf(\"\\\"name\\\": \\\"%s\\\",\", protocolName);\n \n reportGenericArguments(protocol->ownGenericArgumentVariables(), protocol->genericArgumentConstraints(),\n protocol->superGenericArguments().size(), Type(protocol, false));\n reportDocumentation(protocol->documentation());\n \n printf(\"\\\"methods\\\": [\");\n for (size_t i = 0; i < protocol->methods().size(); i++) {\n Method *method = protocol->methods()[i];\n reportFunctionInformation(method, Return, i + 1 == protocol->methods().size(),\n TypeContext(Type(protocol, false)));\n }\n printf(\"]}\");\n }\n printf(\"]\");\n printf(\"}\");\n}📃 Report on value types\/\/\n\/\/ PackageReporter.cpp\n\/\/ Emojicode\n\/\/\n\/\/ Created by Theo Weidmann on 02\/05\/16.\n\/\/ Copyright © 2016 Theo Weidmann. All rights reserved.\n\/\/\n\n#include \n#include \n#include \n#include \n#include \"utf8.h\"\n#include \"Function.hpp\"\n#include \"Class.hpp\"\n#include \"EmojicodeCompiler.hpp\"\n#include \"Enum.hpp\"\n#include \"Protocol.hpp\"\n#include \"PackageReporter.hpp\"\n#include \"TypeContext.hpp\"\n#include \"ValueType.hpp\"\n\nenum ReturnManner {\n Return,\n NoReturn,\n CanReturnNothingness\n};\n\nvoid reportDocumentation(const EmojicodeString &documentation) {\n if (documentation.size() == 0) {\n return;\n }\n \n const char *d = documentation.utf8CString();\n printf(\"\\\"documentation\\\":\");\n printJSONStringToFile(d, stdout);\n putc(',', stdout);\n delete [] d;\n}\n\nvoid reportType(const char *key, Type type, TypeContext tc) {\n auto returnTypeName = type.toString(tc, false).c_str();\n \n if (key) {\n printf(\"\\\"%s\\\": {\\\"package\\\": \\\"%s\\\", \\\"name\\\": \\\"%s\\\", \\\"optional\\\": %s}\",\n key, type.typePackage(), returnTypeName, type.optional() ? \"true\" : \"false\");\n }\n else {\n printf(\"{\\\"package\\\": \\\"%s\\\", \\\"name\\\": \\\"%s\\\", \\\"optional\\\": %s}\",\n type.typePackage(), returnTypeName, type.optional() ? \"true\" : \"false\");\n }\n}\n\nvoid commaPrinter(bool *b) {\n if (*b) {\n putc(',', stdout);\n }\n *b = true;\n}\n\nvoid reportGenericArguments(std::map map, std::vector constraints,\n size_t superCount, TypeContext tc) {\n printf(\"\\\"genericArguments\\\": [\");\n \n auto gans = std::vector(map.size());\n for (auto it : map) {\n gans[it.second.reference - superCount] = it.first;\n }\n \n auto reported = false;\n \n for (size_t i = 0; i < gans.size(); i++) {\n auto gan = gans[i];\n auto utf8 = gan.utf8CString();\n commaPrinter(&reported);\n printf(\"{\\\"name\\\": \");\n printJSONStringToFile(utf8, stdout);\n printf(\",\");\n reportType(\"constraint\", constraints[i], tc);\n printf(\"}\");\n delete [] utf8;\n }\n \n printf(\"],\");\n}\n\nvoid reportFunctionInformation(Function *p, ReturnManner returnm, bool last, TypeContext tc) {\n ecCharToCharStack(p->name, nameString);\n \n printf(\"{\");\n printf(\"\\\"name\\\": \\\"%s\\\",\", nameString);\n if (p->access == PRIVATE) {\n printf(\"\\\"access\\\": \\\"🔒\\\",\");\n }\n else if (p->access == PROTECTED) {\n printf(\"\\\"access\\\": \\\"🔐\\\",\");\n }\n else {\n printf(\"\\\"access\\\": \\\"🔓\\\",\");\n }\n \n if (returnm == Return) {\n reportType(\"returnType\", p->returnType, tc);\n putc(',', stdout);\n }\n else if (returnm == CanReturnNothingness) {\n printf(\"\\\"canReturnNothingness\\\": true,\");\n }\n \n reportGenericArguments(p->genericArgumentVariables, p->genericArgumentConstraints, 0, tc);\n reportDocumentation(p->documentationToken);\n \n printf(\"\\\"arguments\\\": [\");\n for (int i = 0; i < p->arguments.size(); i++) {\n printf(\"{\");\n auto argument = p->arguments[i];\n \n const char *varname = argument.name.value.utf8CString();\n \n reportType(\"type\", argument.type, tc);\n printf(\",\\\"name\\\":\");\n printJSONStringToFile(varname, stdout);\n printf(\"}%s\", i + 1 == p->arguments.size() ? \"\" : \",\");\n \n delete [] varname;\n }\n printf(\"]\");\n \n printf(\"}%s\", last ? \"\" : \",\");\n}\n\nvoid reportPackage(Package *package) {\n std::list enums;\n std::list classes;\n std::list protocols;\n std::list valueTypes;\n \n for (auto exported : package->exportedTypes()) { \/\/ TODO: Add Value Type\n switch (exported.type.type()) {\n case TT_CLASS:\n classes.push_back(exported.type.eclass());\n break;\n case TT_ENUM:\n enums.push_back(exported.type.eenum());\n break;\n case TT_PROTOCOL:\n protocols.push_back(exported.type.protocol());\n break;\n case TT_VALUE_TYPE:\n valueTypes.push_back(exported.type.valueType());\n break;\n default:\n break;\n }\n }\n \n printf(\"{\");\n \n bool printedValueType = false;\n printf(\"\\\"valueTypes\\\": [\");\n for (auto vt : valueTypes) {\n auto vtcontext = TypeContext(Type(vt, false));\n if (printedValueType) {\n putchar(',');\n }\n printedValueType = true;\n \n printf(\"{\");\n \n ecCharToCharStack(vt->name(), className);\n printf(\"\\\"name\\\": \\\"%s\\\",\", className);\n \n reportGenericArguments(vt->ownGenericArgumentVariables(), vt->genericArgumentConstraints(),\n vt->superGenericArguments().size(), vtcontext);\n reportDocumentation(vt->documentation());\n \n printf(\"\\\"methods\\\": [\");\n for (size_t i = 0; i < vt->methodList().size(); i++) {\n Method *method = vt->methodList()[i];\n reportFunctionInformation(method, Return, i + 1 == vt->methodList().size(),\n TypeContext(Type(vt, false), method));\n }\n printf(\"],\");\n \n printf(\"\\\"initializers\\\": [\");\n for (size_t i = 0; i < vt->initializerList().size(); i++) {\n Initializer *initializer = vt->initializerList()[i];\n reportFunctionInformation(initializer, initializer->canReturnNothingness ? CanReturnNothingness : NoReturn,\n i + 1 == vt->initializerList().size(),\n TypeContext(Type(vt, false), initializer));\n }\n printf(\"],\");\n \n printf(\"\\\"classMethods\\\": [\");\n for (size_t i = 0; i < vt->classMethodList().size(); i++) {\n ClassMethod *classMethod = vt->classMethodList()[i];\n reportFunctionInformation(classMethod, Return, vt->classMethodList().size() == i + 1,\n TypeContext(Type(vt, false), classMethod));\n }\n printf(\"]}\");\n }\n printf(\"],\");\n \n bool printedClass = false;\n printf(\"\\\"classes\\\": [\");\n for (auto eclass : classes) {\n if (printedClass) {\n putchar(',');\n }\n printedClass = true;\n \n printf(\"{\");\n \n ecCharToCharStack(eclass->name(), className);\n printf(\"\\\"name\\\": \\\"%s\\\",\", className);\n \n reportGenericArguments(eclass->ownGenericArgumentVariables(), eclass->genericArgumentConstraints(),\n eclass->superGenericArguments().size(), TypeContext(Type(eclass)));\n reportDocumentation(eclass->documentation());\n \n if (eclass->superclass) {\n ecCharToCharStack(eclass->superclass->name(), superClassName);\n printf(\"\\\"superclass\\\": {\\\"package\\\": \\\"%s\\\", \\\"name\\\": \\\"%s\\\"},\",\n eclass->superclass->package()->name(), superClassName);\n }\n \n printf(\"\\\"methods\\\": [\");\n for (size_t i = 0; i < eclass->methodList().size(); i++) {\n Method *method = eclass->methodList()[i];\n reportFunctionInformation(method, Return, i + 1 == eclass->methodList().size(),\n TypeContext(Type(eclass), method));\n }\n printf(\"],\");\n \n printf(\"\\\"initializers\\\": [\");\n for (size_t i = 0; i < eclass->initializerList().size(); i++) {\n Initializer *initializer = eclass->initializerList()[i];\n reportFunctionInformation(initializer, initializer->canReturnNothingness ? CanReturnNothingness : NoReturn,\n i + 1 == eclass->initializerList().size(),\n TypeContext(Type(eclass), initializer));\n }\n printf(\"],\");\n \n printf(\"\\\"classMethods\\\": [\");\n for (size_t i = 0; i < eclass->classMethodList().size(); i++) {\n ClassMethod *classMethod = eclass->classMethodList()[i];\n reportFunctionInformation(classMethod, Return, eclass->classMethodList().size() == i + 1,\n TypeContext(Type(eclass), classMethod));\n }\n printf(\"],\");\n \n printf(\"\\\"conformsTo\\\": [\");\n bool printedProtocol = false;\n for (auto protocol : eclass->protocols()) {\n commaPrinter(&printedProtocol);\n reportType(nullptr, protocol, TypeContext(Type(eclass)));\n }\n printf(\"]}\");\n }\n printf(\"],\");\n \n printf(\"\\\"enums\\\": [\");\n bool printedEnum = false;\n for (auto eenum : enums) {\n if (printedEnum) {\n putchar(',');\n }\n printf(\"{\");\n \n printedEnum = true;\n \n ecCharToCharStack(eenum->name(), enumName);\n printf(\"\\\"name\\\": \\\"%s\\\",\", enumName);\n \n reportDocumentation(eenum->documentation());\n \n bool printedValue = false;\n printf(\"\\\"values\\\": [\");\n for (auto it : eenum->values()) {\n ecCharToCharStack(it.first, value);\n if (printedValue) {\n putchar(',');\n }\n printf(\"\\\"%s\\\"\", value);\n printedValue = true;\n }\n printf(\"]}\");\n }\n printf(\"],\");\n \n printf(\"\\\"protocols\\\": [\");\n bool printedProtocol = false;\n for (auto protocol : protocols) {\n if (printedProtocol) {\n putchar(',');\n }\n printedProtocol = true;\n printf(\"{\");\n \n ecCharToCharStack(protocol->name(), protocolName);\n printf(\"\\\"name\\\": \\\"%s\\\",\", protocolName);\n \n reportGenericArguments(protocol->ownGenericArgumentVariables(), protocol->genericArgumentConstraints(),\n protocol->superGenericArguments().size(), Type(protocol, false));\n reportDocumentation(protocol->documentation());\n \n printf(\"\\\"methods\\\": [\");\n for (size_t i = 0; i < protocol->methods().size(); i++) {\n Method *method = protocol->methods()[i];\n reportFunctionInformation(method, Return, i + 1 == protocol->methods().size(),\n TypeContext(Type(protocol, false)));\n }\n printf(\"]}\");\n }\n printf(\"]\");\n printf(\"}\");\n}<|endoftext|>"} {"text":"\/*******************************************************************************\n* Copyright 2017-2018 Intel Corporation\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*******************************************************************************\/\n\n#include \n#include \n#include \n\n#include \"ngraph\/node.hpp\"\n#include \"ngraph\/ops\/avg_pool.hpp\"\n#include \"ngraph\/ops\/convolution.hpp\"\n#include \"ngraph\/ops\/max_pool.hpp\"\n\n#include \"mkldnn_utils.hpp\"\n\nnamespace ngraph\n{\n namespace runtime\n {\n namespace cpu\n {\n namespace mkldnn_utils\n {\n#define TI(x) std::type_index(typeid(x))\n\n const std::unordered_set s_op_registry{\n TI(ngraph::op::AvgPool),\n TI(ngraph::op::AvgPoolBackprop),\n TI(ngraph::op::Convolution),\n TI(ngraph::op::ConvolutionBackpropData),\n TI(ngraph::op::ConvolutionBackpropFilters),\n TI(ngraph::op::MaxPool)};\n\n bool IsMKLDNNOp(ngraph::Node& op)\n {\n return (s_op_registry.find(TI(op)) != s_op_registry.end());\n }\n\n mkldnn::memory::format\n CreateNativeDataFormat(const ngraph::runtime::cpu::LayoutDescriptor& layout)\n {\n switch (layout.get_shape().size())\n {\n case 1: return mkldnn::memory::format::x;\n case 2: return mkldnn::memory::format::nc;\n case 4: return mkldnn::memory::format::nchw;\n default: return mkldnn::memory::format::format_undef;\n }\n }\n }\n }\n }\n}\nAdded MaxPoolBackprop to the mkldnn_util\/*******************************************************************************\n* Copyright 2017-2018 Intel Corporation\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*******************************************************************************\/\n\n#include \n#include \n#include \n\n#include \"ngraph\/node.hpp\"\n#include \"ngraph\/ops\/avg_pool.hpp\"\n#include \"ngraph\/ops\/convolution.hpp\"\n#include \"ngraph\/ops\/max_pool.hpp\"\n\n#include \"mkldnn_utils.hpp\"\n\nnamespace ngraph\n{\n namespace runtime\n {\n namespace cpu\n {\n namespace mkldnn_utils\n {\n#define TI(x) std::type_index(typeid(x))\n\n const std::unordered_set s_op_registry{\n TI(ngraph::op::AvgPool),\n TI(ngraph::op::AvgPoolBackprop),\n TI(ngraph::op::Convolution),\n TI(ngraph::op::ConvolutionBackpropData),\n TI(ngraph::op::ConvolutionBackpropFilters),\n TI(ngraph::op::MaxPool),\n T1(ngraph::op::MaxPoolBackprop)};\n\n bool IsMKLDNNOp(ngraph::Node& op)\n {\n return (s_op_registry.find(TI(op)) != s_op_registry.end());\n }\n\n mkldnn::memory::format\n CreateNativeDataFormat(const ngraph::runtime::cpu::LayoutDescriptor& layout)\n {\n switch (layout.get_shape().size())\n {\n case 1: return mkldnn::memory::format::x;\n case 2: return mkldnn::memory::format::nc;\n case 4: return mkldnn::memory::format::nchw;\n default: return mkldnn::memory::format::format_undef;\n }\n }\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\n\/\/ define before any includes\n#define BOOST_SPIRIT_THREADSAFE\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"proj.hpp\"\n#include \"path-mapper.h\"\n\n#include \"git-revision.h\"\n#define VERSION \"0.0.0\"\n\n#if __GNUC__ >= 3\n# define likely(x) __builtin_expect(!!(x), 1)\n# define unlikely(x) __builtin_expect(!!(x), 0)\n#else\n# define likely(x) (x)\n# define unlikely(x) (x)\n#endif\n\n#define CANVAS_SCALE 8\n#define RENDER_SIZE (TILE_SIZE*(CANVAS_SCALE+1))\n\n\n\/\/ typedef std::tuple triplet;\n\/\/ Since boost::lockfree::queue supports only a type that \"has_trivial_assign\", \n\/\/ we encode a triple (zoom, x, y) into a single 64bit value divided as (16, 24, 24)-bits.\ntypedef uint64_t triplet; \nstatic inline triplet pack(uint32_t z, uint32_t x, uint32_t y) {\n z &= 0xFFFF;\n x &= 0xFFFFFF;\n y &= 0xFFFFFF;\n\n triplet val = z;\n val <<= 24;\n val |= x;\n val <<= 24;\n val |= y;\n return val;\n}\nstatic inline void unpack(triplet val, uint32_t& z, uint32_t& x, uint32_t& y) {\n y = (uint32_t)(val & 0xFFFFFF);\n val >>= 24;\n x = (uint32_t)(val & 0xFFFFFF);\n val >>= 24;\n z = (uint32_t)(val & 0xFFFF);\n}\nboost::lockfree::queue> queue;\nboost::atomic done (false);\nboost::atomic removed(0); \/\/ # of tiles removed.\nboost::atomic skipped(0); \/\/ # of tiles that are non-existent or failed to unlink(), thus skipped.\nbool echo_back = false; \/\/ If true, print each processed line to stdout, invariant during the execution\nboost::timer::cpu_timer* timer;\n\nvoid worker(const boost::filesystem::path& base_path) {\n\n const std::string& base_as_string = base_path.string();\n size_t base_len = base_as_string.length();\n\n \/\/ tile_path holds the full path base_path\/nnn\/...\/nnn.png to remove\n char* tile_path = (char*)alloca(base_len + 28);\n strncpy(tile_path, base_as_string.c_str(), base_len);\n\n \/\/ tp_head points to the end of base_path in tile_path\n char* tp_head = tile_path + base_len;\n if (tile_path[base_len-1] != '\/') {\n tile_path[base_len] = '\/';\n ++tp_head;\n }\n\n#define EXISTS(p) boost::filesystem::exists(p)\n#define DO_REMOVE(tile_id) { \\\n unpack(tile_id, z, x, y); \\\n to_physical_path(tp_head, z, x, y, PNG); \\\n if (!EXISTS( (boost::filesystem::path(tile_path)) )) { \\\n ++skipped; \\\n } else { \\\n if ( likely(unlink(tile_path) == 0) ) { \\\n ++removed; \\\n if (echo_back) { \\\n printf(\"%u\/%u\/%u\\n\", z, x, y); \\\n } \\\n } else { \\\n ++skipped; \\\n } \\\n } \\\n}\n triplet tile_id;\n uint32_t z, x, y;\n while (!done) {\n while (queue.pop(tile_id)) {\n DO_REMOVE(tile_id);\n }\n }\n\n while (queue.pop(tile_id)) {\n DO_REMOVE(tile_id)\n }\n}\n\nvoid dry_worker(const boost::filesystem::path& base_path) {\n\n const std::string& base_as_string = base_path.string();\n size_t base_len = base_as_string.length();\n\n \/\/ tile_path holds the full path base_path\/nnn\/...\/nnn.png to remove\n char* tile_path = (char*)alloca(base_len + 28);\n strncpy(tile_path, base_as_string.c_str(), base_len);\n\n \/\/ tp_head points to the end of base_path in tile_path\n char* tp_head = tile_path + base_len;\n if (tile_path[base_len-1] != '\/') {\n tile_path[base_len] = '\/';\n ++tp_head;\n }\n\n#define EXISTS(p) boost::filesystem::exists(p)\n#define DO_DRY_RUN(tile_id) { \\\n unpack(tile_id, z, x, y); \\\n to_physical_path(tp_head, z, x, y, PNG); \\\n if (!EXISTS( (boost::filesystem::path(tile_path)) )) { \\\n ++skipped; \\\n } else { \\\n printf(\"%s will be removed\\n\", tile_path); \\\n ++removed; \\\n } \\\n}\n triplet tile_id;\n uint32_t z, x, y;\n while (!done) {\n while (queue.pop(tile_id)) {\n DO_DRY_RUN(tile_id);\n }\n }\n\n while (queue.pop(tile_id)) {\n DO_DRY_RUN(tile_id)\n }\n}\n\n\/*\nexpire-tiles -p base-path [-f expire-list-file] [-t num-threads]\nremoves tiles listed in expire-list-file under base-path.\nOptions:\n -p,--prefix base-path: a valid directory name, into which tiles are rendered\n -f,--file expire-list-file: the list of tiles to expire: \n a tile list consists of lines, each of which is slash-delimited triple of integers\n z\/x\/y\n each line denotes the logical path of a tile, without suffix.\n Example:\n 15\/5252\/11331\n 15\/5253\/11331\n 15\/7540\/11128\n ...\n When this option is omitted, or '-' is given, stdin is used.\n -t,--threads n: the number of threads to render\n + defaults to boost::thread::hardware_concurrency()\n -d,--dry-run\n + only echoes the tile paths to be expired, without actual removing\n -e,--echo-back\n + prints each successfully processed line to stdout, this is useful when pipelining another process such as re-rendering\n -v,--version\n -h,--help\n*\/\nint main(int ac, char** av) {\n try { \n std::string base;\n std::string list_file;\n unsigned int nthreads;\n bool dry_run = false;\n \/** Define and parse the program options \n *\/ \n namespace po = boost::program_options; \n po::options_description desc(\n \"expire-tiles -p base-path [-f expire-list-file] [-t num-threads]\\n\"\n \"removes tiles listed in expire-list-file under base-path.\\n\\n\"\n \"Options\"\n ); \n desc.add_options() \n (\"help,h\", \"Prints help messages\")\n (\"version,v\", \"Prints version info.\")\n (\"prefix,p\", po::value(&base)->value_name(\"base-path\")->required(), \"Specifies the base directory into which tile are rendered\") \n (\"file,f\", po::value(&list_file)->value_name(\"expire-list-file\")->default_value(\"(stdin)\"), \"Specifies the list of tiles to expire\") \n (\"echo-back,e\", \"prints each successfully processed line to stdout, this is useful when pipelining another process such as re-rendering\")\n (\"threads,t\", \n po::value(&nthreads)->value_name(\"n\")->default_value(boost::thread::hardware_concurrency()), \n \"Specifies the number of threas to render\\n\"\n \" + defaults to boost::thread::hardware_concurrency()\") \n (\"dry-run,d\", \n \"Only estimates the number of tiles, does not actually render\\n\") \n ;\n if (ac <= 1) {\n \/\/ No options are given.\n \/\/ Just print the usage w.o. error messages.\n std::cerr << desc;\n return 0;\n }\n po::variables_map vm; \n\n try { \n po::store(po::command_line_parser(ac, av).options(desc).run(), vm); \/\/ throws on error \n\n \/\/ --help\n if ( vm.count(\"help\") ) { \n std::cerr << desc;\n return 0; \n } \n\n if ( vm.count(\"version\") ) {\n std::cout << (\n VERSION \" (commit: \" GIT_REVISION_SHORT \")\" \n ) << std::endl;\n return 0;\n }\n\n \/\/ --dry-run\n if ( vm.count(\"dry-run\") ) {\n dry_run = true;\n }\n\n \/\/ --echo-back\n if ( vm.count(\"echo-back\") ) {\n echo_back = true;\n }\n\n po::notify(vm); \/\/ throws on error, so do after help in case \n \/\/ there are any problems \n if ( !vm.count(\"expire-list-file\") || list_file == \"(stdin)\") {\n list_file = \"-\";\n }\n \n } catch(po::required_option& e) { \n std::cerr << desc << std::endl;\n std::cerr << \"ERROR: \" << e.what() << std::endl << std::endl; \n return -1; \n } catch(po::error& e) { \n std::cerr << desc << std::endl;\n std::cerr << \"ERROR: \" << e.what() << std::endl << std::endl; \n return -1; \n }\n\n \/\/ Check if base-path is really there.\n const boost::filesystem::path base_path(base);\n if (!boost::filesystem::exists(base)) {\n std::cerr << \"ERROR: The base path \" << base << \" does not exist.\" << std::endl << std::endl; \n return -1;\n }\n\n \/\/ Open the list file\n std::istream* in;\n if (list_file == \"-\") {\n in = &std::cin;\n } else {\n try {\n in = new std::ifstream(list_file);\n } catch (std::runtime_error& e) {\n std::cerr << \"ERROR: \" << e.what() << std::endl << std::endl; \n return -1; \n }\n }\n std::cout \n << \"Now expiration begins:\" << std::endl\n << \" Base path : \" << base_path.string() << std::endl\n << \" List file : \" << (base == \"-\" ? \"(stdin)\" : list_file) << std::endl\n ;\n timer = new boost::timer::cpu_timer;\n\n \/\/ Awake renderer threads\n boost::thread_group consumer_threads;\n for (int i = 0; i != nthreads; ++i) {\n consumer_threads.create_thread(boost::bind( dry_run ? dry_worker : worker, base_path));\n }\n\n \/\/ Let it run!\n try {\n std::string line;\n uint64_t lineno = 0;\n uint32_t z, x, y;\n std::getline(*in, line);\n while (std::getline(*in, line)) {\n ++lineno;\n std::vector tokens;\n boost::split(tokens, line, boost::is_from_range('\/','\/'));\n if (tokens.size() != 3 ||\n !boost::conversion::try_lexical_convert(tokens[0], z) ||\n !boost::conversion::try_lexical_convert(tokens[1], x) ||\n !boost::conversion::try_lexical_convert(tokens[2], y) ) {\n std::cerr << \"WARN: skipped illfomed line: \" << line << \" (line at \" << lineno << \")\" << std::endl;\n }\n uint64_t tile_id = pack(z, x, y);\n while (!queue.push(tile_id)) {}\n }\n } catch (std::runtime_error& e) {\n std::cerr << \"ERROR: \" << e.what() << std::endl << std::endl; \n return -1; \n }\n done = true;\n consumer_threads.join_all();\n\n if (in != &std::cin) {\n delete in;\n } \n\n std::cout \n << timer->format() << std::endl\n << removed << \" tiles removed.\" << std::endl\n << skipped << \" tiles did not exist or could not unlink(), thus skipped.\" << std::endl\n << \"Completed!\" << std::endl;\n ;\n } catch(std::exception& e) { \n std::cerr << \"Unhandled Exception reached the top of main: \" \n << e.what() << \", application will now exit\" << std::endl; \n return -1; \n\n } \n return 0; \n}\nSwipe away boost::conversion::try_lexical_convert(), which is only available w. boost >= 1.56\n\/\/ define before any includes\n#define BOOST_SPIRIT_THREADSAFE\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"proj.hpp\"\n#include \"path-mapper.h\"\n\n#include \"git-revision.h\"\n#define VERSION \"0.0.0\"\n\n#if __GNUC__ >= 3\n# define likely(x) __builtin_expect(!!(x), 1)\n# define unlikely(x) __builtin_expect(!!(x), 0)\n#else\n# define likely(x) (x)\n# define unlikely(x) (x)\n#endif\n\n#define CANVAS_SCALE 8\n#define RENDER_SIZE (TILE_SIZE*(CANVAS_SCALE+1))\n\n\n\/\/ typedef std::tuple triplet;\n\/\/ Since boost::lockfree::queue supports only a type that \"has_trivial_assign\", \n\/\/ we encode a triple (zoom, x, y) into a single 64bit value divided as (16, 24, 24)-bits.\ntypedef uint64_t triplet; \nstatic inline triplet pack(uint32_t z, uint32_t x, uint32_t y) {\n z &= 0xFFFF;\n x &= 0xFFFFFF;\n y &= 0xFFFFFF;\n\n triplet val = z;\n val <<= 24;\n val |= x;\n val <<= 24;\n val |= y;\n return val;\n}\nstatic inline void unpack(triplet val, uint32_t& z, uint32_t& x, uint32_t& y) {\n y = (uint32_t)(val & 0xFFFFFF);\n val >>= 24;\n x = (uint32_t)(val & 0xFFFFFF);\n val >>= 24;\n z = (uint32_t)(val & 0xFFFF);\n}\nboost::lockfree::queue> queue;\nboost::atomic done (false);\nboost::atomic removed(0); \/\/ # of tiles removed.\nboost::atomic skipped(0); \/\/ # of tiles that are non-existent or failed to unlink(), thus skipped.\nbool echo_back = false; \/\/ If true, print each processed line to stdout, invariant during the execution\nboost::timer::cpu_timer* timer;\n\nvoid worker(const boost::filesystem::path& base_path) {\n\n const std::string& base_as_string = base_path.string();\n size_t base_len = base_as_string.length();\n\n \/\/ tile_path holds the full path base_path\/nnn\/...\/nnn.png to remove\n char* tile_path = (char*)alloca(base_len + 28);\n strncpy(tile_path, base_as_string.c_str(), base_len);\n\n \/\/ tp_head points to the end of base_path in tile_path\n char* tp_head = tile_path + base_len;\n if (tile_path[base_len-1] != '\/') {\n tile_path[base_len] = '\/';\n ++tp_head;\n }\n\n#define EXISTS(p) boost::filesystem::exists(p)\n#define DO_REMOVE(tile_id) { \\\n unpack(tile_id, z, x, y); \\\n to_physical_path(tp_head, z, x, y, PNG); \\\n if (!EXISTS( (boost::filesystem::path(tile_path)) )) { \\\n ++skipped; \\\n } else { \\\n if ( likely(unlink(tile_path) == 0) ) { \\\n ++removed; \\\n if (echo_back) { \\\n printf(\"%u\/%u\/%u\\n\", z, x, y); \\\n } \\\n } else { \\\n ++skipped; \\\n } \\\n } \\\n}\n triplet tile_id;\n uint32_t z, x, y;\n while (!done) {\n while (queue.pop(tile_id)) {\n DO_REMOVE(tile_id);\n }\n }\n\n while (queue.pop(tile_id)) {\n DO_REMOVE(tile_id)\n }\n}\n\nvoid dry_worker(const boost::filesystem::path& base_path) {\n\n const std::string& base_as_string = base_path.string();\n size_t base_len = base_as_string.length();\n\n \/\/ tile_path holds the full path base_path\/nnn\/...\/nnn.png to remove\n char* tile_path = (char*)alloca(base_len + 28);\n strncpy(tile_path, base_as_string.c_str(), base_len);\n\n \/\/ tp_head points to the end of base_path in tile_path\n char* tp_head = tile_path + base_len;\n if (tile_path[base_len-1] != '\/') {\n tile_path[base_len] = '\/';\n ++tp_head;\n }\n\n#define EXISTS(p) boost::filesystem::exists(p)\n#define DO_DRY_RUN(tile_id) { \\\n unpack(tile_id, z, x, y); \\\n to_physical_path(tp_head, z, x, y, PNG); \\\n if (!EXISTS( (boost::filesystem::path(tile_path)) )) { \\\n ++skipped; \\\n } else { \\\n printf(\"%s will be removed\\n\", tile_path); \\\n ++removed; \\\n } \\\n}\n triplet tile_id;\n uint32_t z, x, y;\n while (!done) {\n while (queue.pop(tile_id)) {\n DO_DRY_RUN(tile_id);\n }\n }\n\n while (queue.pop(tile_id)) {\n DO_DRY_RUN(tile_id)\n }\n}\n\n\/*\nexpire-tiles -p base-path [-f expire-list-file] [-t num-threads]\nremoves tiles listed in expire-list-file under base-path.\nOptions:\n -p,--prefix base-path: a valid directory name, into which tiles are rendered\n -f,--file expire-list-file: the list of tiles to expire: \n a tile list consists of lines, each of which is slash-delimited triple of integers\n z\/x\/y\n each line denotes the logical path of a tile, without suffix.\n Example:\n 15\/5252\/11331\n 15\/5253\/11331\n 15\/7540\/11128\n ...\n When this option is omitted, or '-' is given, stdin is used.\n -t,--threads n: the number of threads to render\n + defaults to boost::thread::hardware_concurrency()\n -d,--dry-run\n + only echoes the tile paths to be expired, without actual removing\n -e,--echo-back\n + prints each successfully processed line to stdout, this is useful when pipelining another process such as re-rendering\n -v,--version\n -h,--help\n*\/\n\ntemplate \nstatic inline bool try_lexical_convert(const std::string& tk, T& r) {\n try {\n r = boost::lexical_cast(tk);\n return true;\n } catch (boost::bad_lexical_cast& e) {\n return false;\n }\n}\nint main(int ac, char** av) {\n try { \n std::string base;\n std::string list_file;\n unsigned int nthreads;\n bool dry_run = false;\n \/** Define and parse the program options \n *\/ \n namespace po = boost::program_options; \n po::options_description desc(\n \"expire-tiles -p base-path [-f expire-list-file] [-t num-threads]\\n\"\n \"removes tiles listed in expire-list-file under base-path.\\n\\n\"\n \"Options\"\n ); \n desc.add_options() \n (\"help,h\", \"Prints help messages\")\n (\"version,v\", \"Prints version info.\")\n (\"prefix,p\", po::value(&base)->value_name(\"base-path\")->required(), \"Specifies the base directory into which tile are rendered\") \n (\"file,f\", po::value(&list_file)->value_name(\"expire-list-file\")->default_value(\"(stdin)\"), \"Specifies the list of tiles to expire\") \n (\"echo-back,e\", \"prints each successfully processed line to stdout, this is useful when pipelining another process such as re-rendering\")\n (\"threads,t\", \n po::value(&nthreads)->value_name(\"n\")->default_value(boost::thread::hardware_concurrency()), \n \"Specifies the number of threas to render\\n\"\n \" + defaults to boost::thread::hardware_concurrency()\") \n (\"dry-run,d\", \n \"Only estimates the number of tiles, does not actually render\\n\") \n ;\n if (ac <= 1) {\n \/\/ No options are given.\n \/\/ Just print the usage w.o. error messages.\n std::cerr << desc;\n return 0;\n }\n po::variables_map vm; \n\n try { \n po::store(po::command_line_parser(ac, av).options(desc).run(), vm); \/\/ throws on error \n\n \/\/ --help\n if ( vm.count(\"help\") ) { \n std::cerr << desc;\n return 0; \n } \n\n if ( vm.count(\"version\") ) {\n std::cout << (\n VERSION \" (commit: \" GIT_REVISION_SHORT \")\" \n ) << std::endl;\n return 0;\n }\n\n \/\/ --dry-run\n if ( vm.count(\"dry-run\") ) {\n dry_run = true;\n }\n\n \/\/ --echo-back\n if ( vm.count(\"echo-back\") ) {\n echo_back = true;\n }\n\n po::notify(vm); \/\/ throws on error, so do after help in case \n \/\/ there are any problems \n if ( !vm.count(\"expire-list-file\") || list_file == \"(stdin)\") {\n list_file = \"-\";\n }\n \n } catch(po::required_option& e) { \n std::cerr << desc << std::endl;\n std::cerr << \"ERROR: \" << e.what() << std::endl << std::endl; \n return -1; \n } catch(po::error& e) { \n std::cerr << desc << std::endl;\n std::cerr << \"ERROR: \" << e.what() << std::endl << std::endl; \n return -1; \n }\n\n \/\/ Check if base-path is really there.\n const boost::filesystem::path base_path(base);\n if (!boost::filesystem::exists(base)) {\n std::cerr << \"ERROR: The base path \" << base << \" does not exist.\" << std::endl << std::endl; \n return -1;\n }\n\n \/\/ Open the list file\n std::istream* in;\n if (list_file == \"-\") {\n in = &std::cin;\n } else {\n try {\n in = new std::ifstream(list_file);\n } catch (std::runtime_error& e) {\n std::cerr << \"ERROR: \" << e.what() << std::endl << std::endl; \n return -1; \n }\n }\n std::cout \n << \"Now expiration begins:\" << std::endl\n << \" Base path : \" << base_path.string() << std::endl\n << \" List file : \" << (base == \"-\" ? \"(stdin)\" : list_file) << std::endl\n ;\n timer = new boost::timer::cpu_timer;\n\n \/\/ Awake renderer threads\n boost::thread_group consumer_threads;\n for (int i = 0; i != nthreads; ++i) {\n consumer_threads.create_thread(boost::bind( dry_run ? dry_worker : worker, base_path));\n }\n\n \/\/ Let it run!\n try {\n std::string line;\n uint64_t lineno = 0;\n uint32_t z, x, y;\n while (std::getline(*in, line)) {\n ++lineno;\n std::vector tokens;\n boost::split(tokens, line, boost::is_from_range('\/','\/'));\n if (tokens.size() != 3 ||\n !try_lexical_convert(tokens[0], z) ||\n !try_lexical_convert(tokens[1], x) ||\n !try_lexical_convert(tokens[2], y) ) {\n std::cerr << \"WARN: skipped illfomed line: \" << line << \" (line at \" << lineno << \")\" << std::endl;\n continue;\n }\n uint64_t tile_id = pack(z, x, y);\n while (!queue.push(tile_id)) {}\n }\n } catch (std::runtime_error& e) {\n std::cerr << \"ERROR: \" << e.what() << std::endl << std::endl; \n return -1; \n }\n done = true;\n consumer_threads.join_all();\n\n if (in != &std::cin) {\n delete in;\n } \n\n std::cout \n << timer->format() << std::endl\n << removed << \" tiles removed.\" << std::endl\n << skipped << \" tiles did not exist or could not unlink(), thus skipped.\" << std::endl\n << \"Completed!\" << std::endl;\n ;\n } catch(std::exception& e) { \n std::cerr << \"Unhandled Exception reached the top of main: \" \n << e.what() << \", application will now exit\" << std::endl; \n return -1; \n\n } \n return 0; \n}\n<|endoftext|>"} {"text":"\/\/ This file is part of OpenMVG, an Open Multiple View Geometry C++ library.\n\n\/\/ Copyright (c) 2014 Romuald Perrot, Pierre Moulon, Chris Sweeney.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#ifndef OPENMVG_IMAGE_IMAGE_CONVOLUTION_HPP\n#define OPENMVG_IMAGE_IMAGE_CONVOLUTION_HPP\n\n#include \n#include \n\n#include \"openMVG\/image\/image_container.hpp\"\n#include \"openMVG\/image\/image_convolution_base.hpp\"\n#include \"openMVG\/numeric\/accumulator_trait.hpp\"\n#include \"openMVG\/numeric\/eigen_alias_definition.hpp\"\n\n\/**\n ** @file Standard 2D image convolution functions :\n ** - vertical\n ** - horizontal\n ** - 2D (using standard 2d kernel of with separable kernels)\n **\/\n\nnamespace openMVG\n{\nnamespace image\n{\n\n\/**\n ** General image convolution by a kernel\n ** assume kernel has odd size in both dimensions and (border pixel are copied)\n ** @param img source image\n ** @param kernel convolution kernel\n ** @param out resulting image\n **\/\ntemplate\nvoid ImageConvolution( const Image & img , const Mat & kernel , Image & out )\n{\n const int kernel_width = kernel.cols();\n const int kernel_height = kernel.rows();\n\n assert( kernel_width % 2 != 0 && kernel_height % 2 != 0 );\n\n using pix_t = typename Image::Tpixel;\n using acc_pix_t = typename Accumulator< pix_t >::Type;\n\n out.resize( img.Width() , img.Height() );\n\n for (int row = 0; row < img.rows(); ++row )\n {\n for (int col = 0; col < img.cols(); ++col )\n {\n acc_pix_t sum = acc_pix_t( );\n\n for (int i = 0; i < kernel_height; ++i )\n {\n for (int j = 0; j < kernel_width; ++j )\n {\n int idy = row + i - kernel_height \/ 2;\n int idx = col + j - kernel_width \/ 2;\n\n \/\/ Get correct value\n idx = idx < 0 ? 0 : ( idx >= img.cols() ? img.cols() - 1 : idx );\n idy = idy < 0 ? 0 : ( idy >= img.rows() ? img.rows() - 1 : idy );\n\n sum += kernel( i , j ) * img( idy , idx );\n }\n }\n out( row , col ) = sum;\n }\n }\n}\n\n\/**\n ** Horizontal (1d) convolution\n ** assume kernel has odd size\n ** @param img Input image\n ** @param kernel convolution kernel\n ** @param out Output image\n **\/\ntemplate\nvoid ImageHorizontalConvolution( const ImageTypeIn & img , const Kernel & kernel , ImageTypeOut & out )\n{\n using pix_t = typename ImageTypeIn::Tpixel;\n\n const int rows ( img.rows() );\n const int cols ( img.cols() );\n\n out.resize( cols , rows );\n\n const int kernel_width = kernel.size();\n const int half_kernel_width = kernel_width \/ 2;\n\n std::vector> line( cols + kernel_width );\n\n for (int row = 0; row < rows; ++row )\n {\n \/\/ Copy line\n const pix_t start_pix = img.coeffRef( row , 0 );\n for (int k = 0; k < half_kernel_width; ++k ) \/\/ pad before\n {\n line[ k ] = start_pix;\n }\n std::memcpy( &line[0] + half_kernel_width, img.data() + row * cols, sizeof( pix_t ) * cols );\n const pix_t end_pix = img.coeffRef( row , cols - 1 );\n for (int k = 0; k < half_kernel_width; ++k ) \/\/ pad after\n {\n line[ k + half_kernel_width + cols ] = end_pix;\n }\n\n \/\/ Apply convolution\n conv_buffer_( &line[0] , kernel.data() , cols , kernel_width );\n\n std::memcpy( out.data() + row * cols, &line[0], sizeof( pix_t ) * cols );\n }\n}\n\n\/**\n ** Vertical (1d) convolution\n ** assume kernel has odd size\n ** @param img Input image\n ** @param kernel convolution kernel\n ** @param out Output image\n **\/\ntemplate\nvoid ImageVerticalConvolution( const ImageTypeIn & img , const Kernel & kernel , ImageTypeOut & out )\n{\n using pix_t = typename ImageTypeIn::Tpixel;\n\n const int kernel_width = kernel.size();\n const int half_kernel_width = kernel_width \/ 2;\n\n const int rows = img.rows();\n const int cols = img.cols();\n\n out.resize( cols , rows );\n\n std::vector> line( rows + kernel_width );\n\n for (int col = 0; col < cols; ++col )\n {\n \/\/ Copy column\n for (int k = 0; k < half_kernel_width; ++k )\n {\n line[ k ] = img.coeffRef( 0 , col );\n }\n for (int k = 0; k < rows; ++k )\n {\n line[ k + half_kernel_width ] = img.coeffRef( k , col );\n }\n for (int k = 0; k < half_kernel_width; ++k )\n {\n line[ k + half_kernel_width + rows ] = img.coeffRef( rows - 1 , col );\n }\n\n \/\/ Apply convolution\n conv_buffer_( &line[0] , kernel.data() , rows , kernel_width );\n\n for (int row = 0; row < rows; ++row )\n {\n out.coeffRef( row , col ) = line[row];\n }\n }\n}\n\n\/**\n ** Separable 2D convolution\n ** (nxm kernel is replaced by two 1D convolution of (size n then size m) )\n ** @param img source image\n ** @param horiz_k horizontal kernel\n ** @param vert_k vertical kernel\n ** @param out output image\n **\/\ntemplate\nvoid ImageSeparableConvolution( const ImageType & img ,\n const Kernel & horiz_k ,\n const Kernel & vert_k ,\n ImageType & out )\n{\n \/\/ Cast the Kernel to the appropriate type\n using pix_t = typename ImageType::Tpixel;\n using VecKernel = Eigen::Matrix::Type, Eigen::Dynamic, 1>;\n const VecKernel horiz_k_cast = horiz_k.template cast< typename Accumulator::Type >();\n const VecKernel vert_k_cast = vert_k.template cast< typename Accumulator::Type >();\n\n ImageType tmp;\n ImageHorizontalConvolution( img , horiz_k_cast , tmp );\n ImageVerticalConvolution( tmp , vert_k_cast , out );\n}\n\nusing RowMatrixXf = Eigen::Matrix;\n\n\/\/\/ Specialization for Float based image (for arbitrary sized kernel)\ninline void SeparableConvolution2d( const RowMatrixXf& image,\n const Eigen::Matrix& kernel_x,\n const Eigen::Matrix& kernel_y,\n RowMatrixXf* out )\n{\n const int sigma_y = static_cast( kernel_y.cols() );\n const int half_sigma_y = static_cast( kernel_y.cols() ) \/ 2;\n\n \/\/ Convolving a vertical filter across rows is the same thing as transpose\n \/\/ multiply i.e. kernel_y^t * rows. This will give us the convoled value for\n \/\/ each row. However, care must be taken at the top and bottom borders.\n const Eigen::Matrix reverse_kernel_y = kernel_y.reverse();\n#if defined(OPENMVG_USE_OPENMP)\n #pragma omp parallel for schedule(dynamic)\n#endif\n for ( int i = 0; i < half_sigma_y; i++ )\n {\n const int forward_size = i + half_sigma_y + 1;\n const int reverse_size = sigma_y - forward_size;\n out->row( i ) = kernel_y.tail( forward_size ) *\n image.block( 0, 0, forward_size, image.cols() ) +\n reverse_kernel_y.tail( reverse_size ) *\n image.block( 1, 0, reverse_size, image.cols() );\n\n \/\/ Apply the same technique for the end rows.\n out->row( image.rows() - i - 1 ) =\n kernel_y.head( forward_size ) *\n image.block( image.rows() - forward_size, 0, forward_size, image.cols() )\n +\n reverse_kernel_y.head( reverse_size ) *\n image.block( image.rows() - reverse_size - 1, 0, reverse_size, image.cols() );\n }\n\n \/\/ Applying the rest of the y filter.\n#if defined(OPENMVG_USE_OPENMP)\n #pragma omp parallel for schedule(dynamic)\n#endif\n for ( int row = half_sigma_y; row < image.rows() - half_sigma_y; row++ )\n {\n out->row( row ) = kernel_y * image.block( row - half_sigma_y, 0, sigma_y, out->cols() );\n }\n\n const int sigma_x = static_cast( kernel_x.cols() );\n const int half_sigma_x = static_cast( kernel_x.cols() \/ 2 );\n\n \/\/ Convolving with the horizontal filter is easy. Rather than using the kernel\n \/\/ as a sliding window, we use the row pixels as a sliding window around the\n \/\/ filter. We prepend and append the proper border values so that we are sure\n \/\/ to end up with the correct convolved values.\n Eigen::RowVectorXf temp_row( image.cols() + sigma_x - 1 );\n#if defined(OPENMVG_USE_OPENMP)\n #pragma omp parallel for firstprivate(temp_row), schedule(dynamic)\n#endif\n for ( int row = 0; row < out->rows(); row++ )\n {\n temp_row.head( half_sigma_x ) =\n out->row( row ).segment( 1, half_sigma_x ).reverse();\n temp_row.segment( half_sigma_x, image.cols() ) = out->row( row );\n temp_row.tail( half_sigma_x ) =\n out->row( row )\n .segment( image.cols() - 2 - half_sigma_x, half_sigma_x )\n .reverse();\n\n \/\/ Convolve the row. We perform the first step here explicitly so that we\n \/\/ avoid setting the row equal to zero.\n out->row( row ) = kernel_x( 0 ) * temp_row.head( image.cols() );\n for ( int i = 1; i < sigma_x; i++ )\n {\n out->row( row ) += kernel_x( i ) * temp_row.segment( i, image.cols() );\n }\n }\n}\n\n\n\/**\n* @brief Specialization for Image in order to use SeparableConvolution2d\n* @param img Input image\n* @param horiz_k Kernel used for horizontal convolution\n* @param vert_k Kernl used for vertical convolution\n* @param[out] out Convolved image\n*\/\ntemplate\nvoid ImageSeparableConvolution( const Image & img ,\n const Kernel & horiz_k ,\n const Kernel & vert_k ,\n Image & out )\n{\n \/\/ Cast the Kernel to the appropriate type\n using pix_t = Image::Tpixel;\n using VecKernel = Eigen::Matrix::Type, Eigen::Dynamic, 1>;\n const VecKernel horiz_k_cast = horiz_k.template cast< typename openMVG::Accumulator::Type >();\n const VecKernel vert_k_cast = vert_k.template cast< typename openMVG::Accumulator::Type >();\n\n out.resize( img.Width(), img.Height() );\n SeparableConvolution2d( img.GetMat(), horiz_k_cast, vert_k_cast, &( ( Image::Base& )out ) );\n}\n\n} \/\/ namespace image\n} \/\/ namespace openMVG\n\n#endif \/\/ OPENMVG_IMAGE_IMAGE_CONVOLUTION_HPP\n[image] Fix a useless cast.\/\/ This file is part of OpenMVG, an Open Multiple View Geometry C++ library.\n\n\/\/ Copyright (c) 2014 Romuald Perrot, Pierre Moulon, Chris Sweeney.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#ifndef OPENMVG_IMAGE_IMAGE_CONVOLUTION_HPP\n#define OPENMVG_IMAGE_IMAGE_CONVOLUTION_HPP\n\n#include \n#include \n\n#include \"openMVG\/image\/image_container.hpp\"\n#include \"openMVG\/image\/image_convolution_base.hpp\"\n#include \"openMVG\/numeric\/accumulator_trait.hpp\"\n#include \"openMVG\/numeric\/eigen_alias_definition.hpp\"\n\n\/**\n ** @file Standard 2D image convolution functions :\n ** - vertical\n ** - horizontal\n ** - 2D (using standard 2d kernel of with separable kernels)\n **\/\n\nnamespace openMVG\n{\nnamespace image\n{\n\n\/**\n ** General image convolution by a kernel\n ** assume kernel has odd size in both dimensions and (border pixel are copied)\n ** @param img source image\n ** @param kernel convolution kernel\n ** @param out resulting image\n **\/\ntemplate\nvoid ImageConvolution( const Image & img , const Mat & kernel , Image & out )\n{\n const int kernel_width = kernel.cols();\n const int kernel_height = kernel.rows();\n\n assert( kernel_width % 2 != 0 && kernel_height % 2 != 0 );\n\n using pix_t = typename Image::Tpixel;\n using acc_pix_t = typename Accumulator< pix_t >::Type;\n\n out.resize( img.Width() , img.Height() );\n\n for (int row = 0; row < img.rows(); ++row )\n {\n for (int col = 0; col < img.cols(); ++col )\n {\n acc_pix_t sum = acc_pix_t( );\n\n for (int i = 0; i < kernel_height; ++i )\n {\n for (int j = 0; j < kernel_width; ++j )\n {\n int idy = row + i - kernel_height \/ 2;\n int idx = col + j - kernel_width \/ 2;\n\n \/\/ Get correct value\n idx = idx < 0 ? 0 : ( idx >= img.cols() ? img.cols() - 1 : idx );\n idy = idy < 0 ? 0 : ( idy >= img.rows() ? img.rows() - 1 : idy );\n\n sum += kernel( i , j ) * img( idy , idx );\n }\n }\n out( row , col ) = sum;\n }\n }\n}\n\n\/**\n ** Horizontal (1d) convolution\n ** assume kernel has odd size\n ** @param img Input image\n ** @param kernel convolution kernel\n ** @param out Output image\n **\/\ntemplate\nvoid ImageHorizontalConvolution( const ImageTypeIn & img , const Kernel & kernel , ImageTypeOut & out )\n{\n using pix_t = typename ImageTypeIn::Tpixel;\n\n const int rows ( img.rows() );\n const int cols ( img.cols() );\n\n out.resize( cols , rows );\n\n const int kernel_width = kernel.size();\n const int half_kernel_width = kernel_width \/ 2;\n\n std::vector> line( cols + kernel_width );\n\n for (int row = 0; row < rows; ++row )\n {\n \/\/ Copy line\n const pix_t start_pix = img.coeffRef( row , 0 );\n for (int k = 0; k < half_kernel_width; ++k ) \/\/ pad before\n {\n line[ k ] = start_pix;\n }\n std::memcpy( &line[0] + half_kernel_width, img.data() + row * cols, sizeof( pix_t ) * cols );\n const pix_t end_pix = img.coeffRef( row , cols - 1 );\n for (int k = 0; k < half_kernel_width; ++k ) \/\/ pad after\n {\n line[ k + half_kernel_width + cols ] = end_pix;\n }\n\n \/\/ Apply convolution\n conv_buffer_( &line[0] , kernel.data() , cols , kernel_width );\n\n std::memcpy( out.data() + row * cols, &line[0], sizeof( pix_t ) * cols );\n }\n}\n\n\/**\n ** Vertical (1d) convolution\n ** assume kernel has odd size\n ** @param img Input image\n ** @param kernel convolution kernel\n ** @param out Output image\n **\/\ntemplate\nvoid ImageVerticalConvolution( const ImageTypeIn & img , const Kernel & kernel , ImageTypeOut & out )\n{\n using pix_t = typename ImageTypeIn::Tpixel;\n\n const int kernel_width = kernel.size();\n const int half_kernel_width = kernel_width \/ 2;\n\n const int rows = img.rows();\n const int cols = img.cols();\n\n out.resize( cols , rows );\n\n std::vector> line( rows + kernel_width );\n\n for (int col = 0; col < cols; ++col )\n {\n \/\/ Copy column\n for (int k = 0; k < half_kernel_width; ++k )\n {\n line[ k ] = img.coeffRef( 0 , col );\n }\n for (int k = 0; k < rows; ++k )\n {\n line[ k + half_kernel_width ] = img.coeffRef( k , col );\n }\n for (int k = 0; k < half_kernel_width; ++k )\n {\n line[ k + half_kernel_width + rows ] = img.coeffRef( rows - 1 , col );\n }\n\n \/\/ Apply convolution\n conv_buffer_( &line[0] , kernel.data() , rows , kernel_width );\n\n for (int row = 0; row < rows; ++row )\n {\n out.coeffRef( row , col ) = line[row];\n }\n }\n}\n\n\/**\n ** Separable 2D convolution\n ** (nxm kernel is replaced by two 1D convolution of (size n then size m) )\n ** @param img source image\n ** @param horiz_k horizontal kernel\n ** @param vert_k vertical kernel\n ** @param out output image\n **\/\ntemplate\nvoid ImageSeparableConvolution( const ImageType & img ,\n const Kernel & horiz_k ,\n const Kernel & vert_k ,\n ImageType & out )\n{\n \/\/ Cast the Kernel to the appropriate type\n using pix_t = typename ImageType::Tpixel;\n using VecKernel = Eigen::Matrix::Type, Eigen::Dynamic, 1>;\n const VecKernel horiz_k_cast = horiz_k.template cast< typename Accumulator::Type >();\n const VecKernel vert_k_cast = vert_k.template cast< typename Accumulator::Type >();\n\n ImageType tmp;\n ImageHorizontalConvolution( img , horiz_k_cast , tmp );\n ImageVerticalConvolution( tmp , vert_k_cast , out );\n}\n\nusing RowMatrixXf = Eigen::Matrix;\n\n\/\/\/ Specialization for Float based image (for arbitrary sized kernel)\ninline void SeparableConvolution2d( const RowMatrixXf& image,\n const Eigen::Matrix& kernel_x,\n const Eigen::Matrix& kernel_y,\n RowMatrixXf* out )\n{\n const int sigma_y = static_cast( kernel_y.cols() );\n const int half_sigma_y = static_cast( kernel_y.cols() ) \/ 2;\n\n \/\/ Convolving a vertical filter across rows is the same thing as transpose\n \/\/ multiply i.e. kernel_y^t * rows. This will give us the convoled value for\n \/\/ each row. However, care must be taken at the top and bottom borders.\n const Eigen::Matrix reverse_kernel_y = kernel_y.reverse();\n#if defined(OPENMVG_USE_OPENMP)\n #pragma omp parallel for schedule(dynamic)\n#endif\n for ( int i = 0; i < half_sigma_y; i++ )\n {\n const int forward_size = i + half_sigma_y + 1;\n const int reverse_size = sigma_y - forward_size;\n out->row( i ) = kernel_y.tail( forward_size ) *\n image.block( 0, 0, forward_size, image.cols() ) +\n reverse_kernel_y.tail( reverse_size ) *\n image.block( 1, 0, reverse_size, image.cols() );\n\n \/\/ Apply the same technique for the end rows.\n out->row( image.rows() - i - 1 ) =\n kernel_y.head( forward_size ) *\n image.block( image.rows() - forward_size, 0, forward_size, image.cols() )\n +\n reverse_kernel_y.head( reverse_size ) *\n image.block( image.rows() - reverse_size - 1, 0, reverse_size, image.cols() );\n }\n\n \/\/ Applying the rest of the y filter.\n#if defined(OPENMVG_USE_OPENMP)\n #pragma omp parallel for schedule(dynamic)\n#endif\n for ( int row = half_sigma_y; row < image.rows() - half_sigma_y; row++ )\n {\n out->row( row ) = kernel_y * image.block( row - half_sigma_y, 0, sigma_y, out->cols() );\n }\n\n const int sigma_x = static_cast( kernel_x.cols() );\n const int half_sigma_x = static_cast( kernel_x.cols() \/ 2 );\n\n \/\/ Convolving with the horizontal filter is easy. Rather than using the kernel\n \/\/ as a sliding window, we use the row pixels as a sliding window around the\n \/\/ filter. We prepend and append the proper border values so that we are sure\n \/\/ to end up with the correct convolved values.\n Eigen::RowVectorXf temp_row( image.cols() + sigma_x - 1 );\n#if defined(OPENMVG_USE_OPENMP)\n #pragma omp parallel for firstprivate(temp_row), schedule(dynamic)\n#endif\n for ( int row = 0; row < out->rows(); row++ )\n {\n temp_row.head( half_sigma_x ) =\n out->row( row ).segment( 1, half_sigma_x ).reverse();\n temp_row.segment( half_sigma_x, image.cols() ) = out->row( row );\n temp_row.tail( half_sigma_x ) =\n out->row( row )\n .segment( image.cols() - 2 - half_sigma_x, half_sigma_x )\n .reverse();\n\n \/\/ Convolve the row. We perform the first step here explicitly so that we\n \/\/ avoid setting the row equal to zero.\n out->row( row ) = kernel_x( 0 ) * temp_row.head( image.cols() );\n for ( int i = 1; i < sigma_x; i++ )\n {\n out->row( row ) += kernel_x( i ) * temp_row.segment( i, image.cols() );\n }\n }\n}\n\n\n\/**\n* @brief Specialization for Image in order to use SeparableConvolution2d\n* @param img Input image\n* @param horiz_k Kernel used for horizontal convolution\n* @param vert_k Kernl used for vertical convolution\n* @param[out] out Convolved image\n*\/\ntemplate\nvoid ImageSeparableConvolution( const Image & img ,\n const Kernel & horiz_k ,\n const Kernel & vert_k ,\n Image & out )\n{\n \/\/ Cast the Kernel to the appropriate type\n using pix_t = Image::Tpixel;\n using VecKernel = Eigen::Matrix::Type, Eigen::Dynamic, 1>;\n const VecKernel horiz_k_cast = horiz_k.template cast< typename openMVG::Accumulator::Type >();\n const VecKernel vert_k_cast = vert_k.template cast< typename openMVG::Accumulator::Type >();\n\n out.resize( img.Width(), img.Height() );\n SeparableConvolution2d( img.GetMat(), horiz_k_cast, vert_k_cast, &out );\n}\n\n} \/\/ namespace image\n} \/\/ namespace openMVG\n\n#endif \/\/ OPENMVG_IMAGE_IMAGE_CONVOLUTION_HPP\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"core\/global.h\"\n#include \"util\/Role.h\"\n#include \"core\/RoleFactory.h\"\n#include \"util\/Datagram.h\"\n\nstatic ConfigVariable bind_addr(\"bind\", \"0.0.0.0:7198\");\n\nclass ClientAgent : public Role\n{\npublic:\n\tClientAgent(RoleConfig roleconfig) : Role(roleconfig)\n\t{\n\t\tstd::stringstream ss;\n\t\tss << \"Client Agent (\" << bind_addr.get_rval(roleconfig) << \")\";\n\t\tm_log = new LogCategory(\"clientagent\", ss.str());\n\t}\n\n\t~ClientAgent()\n\t{\n\t\tdelete m_log;\n\t}\n\n\tvoid handle_datagram(Datagram &in_dg, DatagramIterator &dgi)\n\t{\n\n\t}\n\nprivate:\n\tLogCategory *m_log;\n};\n\nstatic RoleFactoryItem ca_fact(\"clientagent\");\nClientAgent: Style conformance#include \n#include \n\n#include \"core\/global.h\"\n#include \"util\/Role.h\"\n#include \"core\/RoleFactory.h\"\n#include \"util\/Datagram.h\"\n\nstatic ConfigVariable bind_addr(\"bind\", \"0.0.0.0:7198\");\n\nclass ClientAgent : public Role\n{\n\tpublic:\n\t\tClientAgent(RoleConfig roleconfig) : Role(roleconfig)\n\t\t{\n\t\t\tstd::stringstream ss;\n\t\t\tss << \"Client Agent (\" << bind_addr.get_rval(roleconfig) << \")\";\n\t\t\tm_log = new LogCategory(\"clientagent\", ss.str());\n\t\t}\n\n\t\t~ClientAgent()\n\t\t{\n\t\t\tdelete m_log;\n\t\t}\n\n\t\tvoid handle_datagram(Datagram &in_dg, DatagramIterator &dgi)\n\t\t{\n\n\t\t}\n\n\tprivate:\n\t\tLogCategory *m_log;\n};\n\nstatic RoleFactoryItem ca_fact(\"clientagent\");\n<|endoftext|>"} {"text":"#include \n\n#include \n\n#include \"Backends.h\"\n#include \"DTIDESplash.h\"\n#include \"DTIDE.h\"\n\nextern \"C\"\n{\n#include \n#include \n#include \n#include \n#include \n}\n\nint main(int argc, char** argv)\n{\n \/\/ Some set up required for toolchain to work.\n debug_setlevel(LEVEL_VERBOSE);\n osutil_setarg0(bautofree(bfromcstr(argv[0])));\n isetmode(IMODE_BIG);\n \n \/\/ Show version information.\n version_print(bautofree(bfromcstr(\"IDE\")));\n\n \/\/ Start glfw.\n glfwInit();\n\n \/\/ Now start the IDE.\n QApplication app(argc, argv);\n\n std::list toolchains;\n toolchains.insert(toolchains.end(), new DCPUToolchain());\n\n \/*DTIDESplash* splash = new DTIDESplash(toolchains);\n if(!splash->exec())\n return 0;\n\n DTIDE mainWindow(splash->toolchain, splash->fileName);*\/\n\n DTIDE mainWindow(new DCPUToolchain(), \"test.dasm16\");\n mainWindow.show();\n\n int returncode = app.exec();\n glfwTerminate();\n return returncode;\n}\n\nAdded missing include for IDE.#include \n\n#include \n\n#include \"Backends.h\"\n#include \"DTIDESplash.h\"\n#include \"DTIDE.h\"\n\nextern \"C\"\n{\n#include \n#include \n#include \n#include \n#include \n#include \n}\n\nint main(int argc, char** argv)\n{\n \/\/ Some set up required for toolchain to work.\n debug_setlevel(LEVEL_VERBOSE);\n osutil_setarg0(bautofree(bfromcstr(argv[0])));\n isetmode(IMODE_BIG);\n \n \/\/ Show version information.\n version_print(bautofree(bfromcstr(\"IDE\")));\n\n \/\/ Start glfw.\n glfwInit();\n\n \/\/ Now start the IDE.\n QApplication app(argc, argv);\n\n std::list toolchains;\n toolchains.insert(toolchains.end(), new DCPUToolchain());\n\n \/*DTIDESplash* splash = new DTIDESplash(toolchains);\n if(!splash->exec())\n return 0;\n\n DTIDE mainWindow(splash->toolchain, splash->fileName);*\/\n\n DTIDE mainWindow(new DCPUToolchain(), \"test.dasm16\");\n mainWindow.show();\n\n int returncode = app.exec();\n glfwTerminate();\n return returncode;\n}\n\n<|endoftext|>"} {"text":"\/*\n\tAuthor: Brent Pease (embeddedlibraryfeedback@gmail.com)\n\n\tThe MIT License (MIT)\n\n\tCopyright (c) 2015-FOREVER Brent Pease\n\n\tPermission is hereby granted, free of charge, to any person obtaining a copy\n\tof this software and associated documentation files (the \"Software\"), to deal\n\tin the Software without restriction, including without limitation the rights\n\tto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\tcopies of the Software, and to permit persons to whom the Software is\n\tfurnished to do so, subject to the following conditions:\n\n\tThe above copyright notice and this permission notice shall be included in all\n\tcopies or substantial portions of the Software.\n\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\tIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\tFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\tAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\tLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\tOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\tSOFTWARE.\n\n\tSFE_TSL2561 illumination sensor library for Arduino\n\tMike Grusin, SparkFun Electronics\n\t\n\tThis library provides functions to access the TAOS TSL2561\n\tIllumination Sensor.\n\t\n\tOur example code uses the \"beerware\" license. You can do anything\n\tyou like with this code. No really, anything. If you find it useful,\n\tbuy me a beer someday.\n\n\tversion 1.0 2013\/09\/20 MDG initial version\n\tUpdated to Arduino 1.6.4 5\/2015\n\n\tLuminsoity sensor code included from Sparkfun's TSL2561 library to avoid requiring\n\tthe user to download and install that library on their own.\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n\nenum ELuminositySensor\n{\n\teGain_1X = 0,\n\teGain_16X = 1,\n\n\teIntegrationTime_13_7ms = 0,\n\teIntegrationTime_101ms = 1,\n\teIntegrationTime_402ms = 2,\n\teIntegrationTime_Manual = 3,\n\n};\n\n#define TSL2561_ADDR_0 0x29 \/\/ address with '0' shorted on board\n#define TSL2561_ADDR 0x39 \/\/ default address\n#define TSL2561_ADDR_1 0x49 \/\/ address with '1' shorted on board\n\n\/\/ TSL2561 registers\n\n#define TSL2561_CMD 0x80\n#define TSL2561_CMD_CLEAR 0xC0\n#define\tTSL2561_REG_CONTROL 0x00\n#define\tTSL2561_REG_TIMING 0x01\n#define\tTSL2561_REG_THRESH_L 0x02\n#define\tTSL2561_REG_THRESH_H 0x04\n#define\tTSL2561_REG_INTCTL 0x06\n#define\tTSL2561_REG_ID 0x0A\n#define\tTSL2561_REG_DATA_0 0x0C\n#define\tTSL2561_REG_DATA_1 0x0E\n\nCModule_LuminositySensor\tCModule_LuminositySensor::module;\nCModule_LuminositySensor*\tgLuminositySensor;\n\nCModule_LuminositySensor::CModule_LuminositySensor(\n\t)\n\t:\n\tCModule(\n\t\t\"lumn\",\n\t\tsizeof(SLuminositySettings),\n\t\t1,\n\t\t&settings,\n\t\t500000,\n\t\t1)\n{\n\tgLuminositySensor = this;\n}\n\nfloat\nCModule_LuminositySensor::GetActualLux(\n\tvoid)\n{\n\treturn (float)lux;\n}\n\nfloat\nCModule_LuminositySensor::GetNormalizedBrightness(\n\tvoid)\n{\n\treturn (float)normalized;\n}\n\nvoid\nCModule_LuminositySensor::SetMinMaxLux(\n\tfloat\tinMinLux,\n\tfloat\tinMaxLux,\n\tbool\tinUpdateEEPROM)\n{\n\tsettings.minBrightnessLux = inMinLux;\n\tsettings.maxBrightnessLux = inMaxLux;\n\tif(inUpdateEEPROM)\n\t{\n\t\tEEPROMSave();\n\t}\n}\n\nbool\nCModule_LuminositySensor::SerialCmdGetLux(\n\tint\t\t\tinArgC,\n\tchar const*\tinArgv[])\n{\n\tDebugMsg(eDbgLevel_Basic, \"lux = %f\\n\", GetActualLux());\n\n\treturn true;\n}\n\nbool\nCModule_LuminositySensor::SerialCmdConfig(\n\tint\t\t\tinArgC,\n\tchar const*\tinArgv[])\n{\n\tsettings.gain = atoi(inArgv[1]);\n\tsettings.time = atoi(inArgv[2]);\n\tEEPROMSave();\n\n\tSetupSensor();\n\n\treturn true;\n}\n\t\nvoid\nCModule_LuminositySensor::SetupSensor(\n\tvoid)\n{\n\tswitch (settings.time)\n\t{\n\t\tcase 0: integrationTimeMS = 14; break;\n\t\tcase 1: integrationTimeMS = 101; break;\n\t\tcase 2: integrationTimeMS = 402; break;\n\t\tdefault: integrationTimeMS = 0;\n\t}\n\n\t\/\/ Turn off sensing to config\n\tWriteI2CByte(TSL2561_REG_CONTROL,0x00);\n\n\t\/\/ Get timing byte\n\tunsigned char timing;\n\tif(ReadI2CByte(TSL2561_REG_TIMING, timing))\n\t{\n\t\t\/\/ Set gain (0 or 1)\n\t\tif (settings.gain)\n\t\t\ttiming |= 0x10;\n\t\telse\n\t\t\ttiming &= ~0x10;\n\n\t\t\/\/ Set integration time (0 to 3)\n\t\ttiming &= ~0x03;\n\t\ttiming |= (settings.time & 0x03);\n\n\t\t\/\/ Write modified timing byte back to device\n\t\tWriteI2CByte(TSL2561_REG_TIMING,timing);\n\t}\n\n\t\/\/ Write 0x03 to command byte (power on)\n\tWriteI2CByte(TSL2561_REG_CONTROL,0x03);\n}\n\nvoid\nCModule_LuminositySensor::Setup(\n\tvoid)\n{\n\treturn;\n\n\t_i2c_address = TSL2561_ADDR; \/\/ just assume default address for now\n\tWire.begin();\n\t\t\n\tuint8_t\tsensorID;\n\tbool\tsuccess;\n\n\tsuccess = ReadI2CByte(TSL2561_REG_ID, sensorID);\n\tif(success == false || sensorID != 0x50)\n\t{\n\t\tSetEnabledState(false);\n\t\treturn;\n\t}\n\t\t\n\tgSerialCmd->RegisterCommand(\"lumin_get_lux\", this, static_cast(&CModule_LuminositySensor::SerialCmdGetLux));\n\tgSerialCmd->RegisterCommand(\"lumin_config\", this, static_cast(&CModule_LuminositySensor::SerialCmdConfig));\n\n\tSetupSensor();\n}\n\nvoid\nCModule_LuminositySensor::Update(\n\tuint32_t inDeltaTimeUS)\n{\n\treturn;\n\n\tuint16_t data0, data1;\n\n\tReadI2CUInt16(TSL2561_REG_DATA_0, data0);\n\tReadI2CUInt16(TSL2561_REG_DATA_1,data1);\n\n\tbool\tgood;\n\n\tgood = GetLux(settings.gain, integrationTimeMS, data0, data1, lux);\n\tif(good)\n\t{\n\t\tdouble adjLux = lux;\n\t\tif(adjLux < settings.minBrightnessLux) adjLux = settings.minBrightnessLux;\n\t\tif(adjLux > settings.maxBrightnessLux) adjLux = settings.maxBrightnessLux;\n\n\t\tnormalized = float((adjLux - settings.minBrightnessLux) \/ (settings.maxBrightnessLux - settings.minBrightnessLux));\n\n\t\t\/\/Serial.printf(\"%f %f\\n\", lux, normalized);\n\t}\n}\n\nbool\nCModule_LuminositySensor::GetLux(\n\tunsigned char\tinGain, \n\tunsigned int\tinMS, \n\tunsigned int\tinCH0, \n\tunsigned int\tinCH1, \n\tdouble&\t\t\toutLux)\n{\n\t\/\/ Convert raw data to lux\n\t\/\/ gain: 0 (1X) or 1 (16X), see setTiming()\n\t\/\/ ms: integration time in ms, from setTiming() or from manual integration\n\t\/\/ CH0, CH1: results from getData()\n\t\/\/ lux will be set to resulting lux calculation\n\t\/\/ returns true (1) if calculation was successful\n\t\/\/ RETURNS false (0) AND lux = 0.0 IF EITHER SENSOR WAS SATURATED (0XFFFF)\n\n\tdouble ratio, d0, d1;\n\n\t\/\/ Determine if either sensor saturated (0xFFFF)\n\t\/\/ If so, abandon ship (calculation will not be accurate)\n\tif ((inCH0 == 0xFFFF) || (inCH1 == 0xFFFF))\n\t{\n\t\toutLux = 0.0;\n\t\treturn false;\n\t}\n\n\t\/\/ Convert from unsigned integer to floating point\n\td0 = inCH0; \n\td1 = inCH1;\n\n\t\/\/ We will need the ratio for subsequent calculations\n\tratio = d1 \/ d0;\n\n\t\/\/ Normalize for integration time\n\td0 *= (402.0\/inMS);\n\td1 *= (402.0\/inMS);\n\n\t\/\/ Normalize for gain\n\tif (!inGain)\n\t{\n\t\td0 *= 16;\n\t\td1 *= 16;\n\t}\n\n\t\/\/ Determine lux per datasheet equations:\n\t\n\tif (ratio < 0.5)\n\t{\n\t\toutLux = 0.0304 * d0 - 0.062 * d0 * pow(ratio, 1.4);\n\t\treturn true;\n\t}\n\n\tif (ratio < 0.61)\n\t{\n\t\toutLux = 0.0224 * d0 - 0.031 * d1;\n\t\treturn true;\n\t}\n\n\tif (ratio < 0.80)\n\t{\n\t\toutLux = 0.0128 * d0 - 0.0153 * d1;\n\t\treturn true;\n\t}\n\n\tif (ratio < 1.30)\n\t{\n\t\toutLux = 0.00146 * d0 - 0.00112 * d1;\n\t\treturn true;\n\t}\n\n\toutLux = 0.0;\n\n\treturn true;\n}\n\nbool \nCModule_LuminositySensor::ReadI2CByte(\n\tuint8_t\t\tinAddress, \n\tuint8_t&\toutValue)\n{\n\t\/\/ Reads a byte from a TSL2561 address\n\t\/\/ Address: TSL2561 address (0 to 15)\n\t\/\/ Value will be set to stored byte\n\t\/\/ Returns true (1) if successful, false (0) if there was an I2C error\n\t\/\/ (Also see getError() above)\n\n\t\/\/ Set up command byte for read\n\tWire.beginTransmission(_i2c_address);\n\tWire.write((inAddress & 0x0F) | TSL2561_CMD);\n\t_error = Wire.endTransmission();\n\n\t\/\/ Read requested byte\n\tif (_error == 0)\n\t{\n\t\tWire.requestFrom(_i2c_address, 1);\n\t\tif (Wire.available() == 1)\n\t\t{\n\t\t\toutValue = Wire.read();\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nbool\nCModule_LuminositySensor::WriteI2CByte(\n\tuint8_t\tinAddress,\n\tuint8_t\tinValue)\n{\n\t\/\/ Write a byte to a TSL2561 address\n\t\/\/ Address: TSL2561 address (0 to 15)\n\t\/\/ Value: byte to write to address\n\t\/\/ Returns true (1) if successful, false (0) if there was an I2C error\n\t\/\/ (Also see getError() above)\n\n\t\/\/ Set up command byte for write\n\tWire.beginTransmission(_i2c_address);\n\tWire.write((inAddress & 0x0F) | TSL2561_CMD);\n\t\/\/ Write byte\n\tWire.write(inValue);\n\t_error = Wire.endTransmission();\n\n\treturn _error == 0;\n}\n\nbool\nCModule_LuminositySensor::ReadI2CUInt16(\n\tuint8_t\t\tinAddress,\n\tuint16_t&\toutValue)\n{\n\t\/\/ Reads an unsigned integer (16 bits) from a TSL2561 address (low byte first)\n\t\/\/ Address: TSL2561 address (0 to 15), low byte first\n\t\/\/ Value will be set to stored unsigned integer\n\t\/\/ Returns true (1) if successful, false (0) if there was an I2C error\n\t\/\/ (Also see getError() above)\n\n\tchar high, low;\n\t\n\t\/\/ Set up command byte for read\n\tWire.beginTransmission(_i2c_address);\n\tWire.write((inAddress & 0x0F) | TSL2561_CMD);\n\t_error = Wire.endTransmission();\n\n\t\/\/ Read two bytes (low and high)\n\tif (_error == 0)\n\t{\n\t\tWire.requestFrom(_i2c_address, 2);\n\t\tif (Wire.available() == 2)\n\t\t{\n\t\t\tlow = Wire.read();\n\t\t\thigh = Wire.read();\n\t\t\t\/\/ Combine bytes into unsigned int\n\t\t\toutValue = word(high,low);\n\t\t\treturn true;\n\t\t}\n\t}\t\n\n\treturn false;\n}\n\nbool \nCModule_LuminositySensor::WriteI2CUInt16(\n\tuint8_t\t\tinAddress, \n\tuint16_t\tinValue)\n{\n\t\/\/ Write an unsigned integer (16 bits) to a TSL2561 address (low byte first)\n\t\/\/ Address: TSL2561 address (0 to 15), low byte first\n\t\/\/ Value: unsigned int to write to address\n\t\/\/ Returns true (1) if successful, false (0) if there was an I2C error\n\t\/\/ (Also see getError() above)\n\t\/\/ Split int into lower and upper bytes, write each byte\n\tif (WriteI2CByte(inAddress, lowByte(inValue)) \n\t\t&& WriteI2CByte(inAddress + 1, highByte(inValue)))\n\t{\n\t\treturn true;\n\t}\n\n\treturn false;\n}\nRe-enable luminosity settings\/*\n\tAuthor: Brent Pease (embeddedlibraryfeedback@gmail.com)\n\n\tThe MIT License (MIT)\n\n\tCopyright (c) 2015-FOREVER Brent Pease\n\n\tPermission is hereby granted, free of charge, to any person obtaining a copy\n\tof this software and associated documentation files (the \"Software\"), to deal\n\tin the Software without restriction, including without limitation the rights\n\tto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\tcopies of the Software, and to permit persons to whom the Software is\n\tfurnished to do so, subject to the following conditions:\n\n\tThe above copyright notice and this permission notice shall be included in all\n\tcopies or substantial portions of the Software.\n\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\tIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\tFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\tAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\tLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\tOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\tSOFTWARE.\n\n\tSFE_TSL2561 illumination sensor library for Arduino\n\tMike Grusin, SparkFun Electronics\n\t\n\tThis library provides functions to access the TAOS TSL2561\n\tIllumination Sensor.\n\t\n\tOur example code uses the \"beerware\" license. You can do anything\n\tyou like with this code. No really, anything. If you find it useful,\n\tbuy me a beer someday.\n\n\tversion 1.0 2013\/09\/20 MDG initial version\n\tUpdated to Arduino 1.6.4 5\/2015\n\n\tLuminsoity sensor code included from Sparkfun's TSL2561 library to avoid requiring\n\tthe user to download and install that library on their own.\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n\nenum ELuminositySensor\n{\n\teGain_1X = 0,\n\teGain_16X = 1,\n\n\teIntegrationTime_13_7ms = 0,\n\teIntegrationTime_101ms = 1,\n\teIntegrationTime_402ms = 2,\n\teIntegrationTime_Manual = 3,\n\n};\n\n#define TSL2561_ADDR_0 0x29 \/\/ address with '0' shorted on board\n#define TSL2561_ADDR 0x39 \/\/ default address\n#define TSL2561_ADDR_1 0x49 \/\/ address with '1' shorted on board\n\n\/\/ TSL2561 registers\n\n#define TSL2561_CMD 0x80\n#define TSL2561_CMD_CLEAR 0xC0\n#define\tTSL2561_REG_CONTROL 0x00\n#define\tTSL2561_REG_TIMING 0x01\n#define\tTSL2561_REG_THRESH_L 0x02\n#define\tTSL2561_REG_THRESH_H 0x04\n#define\tTSL2561_REG_INTCTL 0x06\n#define\tTSL2561_REG_ID 0x0A\n#define\tTSL2561_REG_DATA_0 0x0C\n#define\tTSL2561_REG_DATA_1 0x0E\n\nCModule_LuminositySensor\tCModule_LuminositySensor::module;\nCModule_LuminositySensor*\tgLuminositySensor;\n\nCModule_LuminositySensor::CModule_LuminositySensor(\n\t)\n\t:\n\tCModule(\n\t\t\"lumn\",\n\t\tsizeof(SLuminositySettings),\n\t\t1,\n\t\t&settings,\n\t\t500000,\n\t\t1)\n{\n\tgLuminositySensor = this;\n}\n\nfloat\nCModule_LuminositySensor::GetActualLux(\n\tvoid)\n{\n\treturn (float)lux;\n}\n\nfloat\nCModule_LuminositySensor::GetNormalizedBrightness(\n\tvoid)\n{\n\treturn (float)normalized;\n}\n\nvoid\nCModule_LuminositySensor::SetMinMaxLux(\n\tfloat\tinMinLux,\n\tfloat\tinMaxLux,\n\tbool\tinUpdateEEPROM)\n{\n\tsettings.minBrightnessLux = inMinLux;\n\tsettings.maxBrightnessLux = inMaxLux;\n\tif(inUpdateEEPROM)\n\t{\n\t\tEEPROMSave();\n\t}\n}\n\nbool\nCModule_LuminositySensor::SerialCmdGetLux(\n\tint\t\t\tinArgC,\n\tchar const*\tinArgv[])\n{\n\tDebugMsg(eDbgLevel_Basic, \"lux = %f\\n\", GetActualLux());\n\n\treturn true;\n}\n\nbool\nCModule_LuminositySensor::SerialCmdConfig(\n\tint\t\t\tinArgC,\n\tchar const*\tinArgv[])\n{\n\tsettings.gain = atoi(inArgv[1]);\n\tsettings.time = atoi(inArgv[2]);\n\tEEPROMSave();\n\n\tSetupSensor();\n\n\treturn true;\n}\n\t\nvoid\nCModule_LuminositySensor::SetupSensor(\n\tvoid)\n{\n\tswitch (settings.time)\n\t{\n\t\tcase 0: integrationTimeMS = 14; break;\n\t\tcase 1: integrationTimeMS = 101; break;\n\t\tcase 2: integrationTimeMS = 402; break;\n\t\tdefault: integrationTimeMS = 0;\n\t}\n\n\t\/\/ Turn off sensing to config\n\tWriteI2CByte(TSL2561_REG_CONTROL,0x00);\n\n\t\/\/ Get timing byte\n\tunsigned char timing;\n\tif(ReadI2CByte(TSL2561_REG_TIMING, timing))\n\t{\n\t\t\/\/ Set gain (0 or 1)\n\t\tif (settings.gain)\n\t\t\ttiming |= 0x10;\n\t\telse\n\t\t\ttiming &= ~0x10;\n\n\t\t\/\/ Set integration time (0 to 3)\n\t\ttiming &= ~0x03;\n\t\ttiming |= (settings.time & 0x03);\n\n\t\t\/\/ Write modified timing byte back to device\n\t\tWriteI2CByte(TSL2561_REG_TIMING,timing);\n\t}\n\n\t\/\/ Write 0x03 to command byte (power on)\n\tWriteI2CByte(TSL2561_REG_CONTROL,0x03);\n}\n\nvoid\nCModule_LuminositySensor::Setup(\n\tvoid)\n{\n\t_i2c_address = TSL2561_ADDR; \/\/ just assume default address for now\n\tWire.begin();\n\t\t\n\tuint8_t\tsensorID;\n\tbool\tsuccess;\n\n\tsuccess = ReadI2CByte(TSL2561_REG_ID, sensorID);\n\tif(success == false || sensorID != 0x50)\n\t{\n\t\tSetEnabledState(false);\n\t\treturn;\n\t}\n\t\t\n\tgSerialCmd->RegisterCommand(\"lumin_get_lux\", this, static_cast(&CModule_LuminositySensor::SerialCmdGetLux));\n\tgSerialCmd->RegisterCommand(\"lumin_config\", this, static_cast(&CModule_LuminositySensor::SerialCmdConfig));\n\n\tSetupSensor();\n}\n\nvoid\nCModule_LuminositySensor::Update(\n\tuint32_t inDeltaTimeUS)\n{\n\n\tuint16_t data0, data1;\n\n\tReadI2CUInt16(TSL2561_REG_DATA_0, data0);\n\tReadI2CUInt16(TSL2561_REG_DATA_1,data1);\n\n\tbool\tgood;\n\n\tgood = GetLux(settings.gain, integrationTimeMS, data0, data1, lux);\n\tif(good)\n\t{\n\t\tdouble adjLux = lux;\n\t\tif(adjLux < settings.minBrightnessLux) adjLux = settings.minBrightnessLux;\n\t\tif(adjLux > settings.maxBrightnessLux) adjLux = settings.maxBrightnessLux;\n\n\t\tnormalized = float((adjLux - settings.minBrightnessLux) \/ (settings.maxBrightnessLux - settings.minBrightnessLux));\n\n\t\t\/\/Serial.printf(\"%f %f\\n\", lux, normalized);\n\t}\n}\n\nbool\nCModule_LuminositySensor::GetLux(\n\tunsigned char\tinGain, \n\tunsigned int\tinMS, \n\tunsigned int\tinCH0, \n\tunsigned int\tinCH1, \n\tdouble&\t\t\toutLux)\n{\n\t\/\/ Convert raw data to lux\n\t\/\/ gain: 0 (1X) or 1 (16X), see setTiming()\n\t\/\/ ms: integration time in ms, from setTiming() or from manual integration\n\t\/\/ CH0, CH1: results from getData()\n\t\/\/ lux will be set to resulting lux calculation\n\t\/\/ returns true (1) if calculation was successful\n\t\/\/ RETURNS false (0) AND lux = 0.0 IF EITHER SENSOR WAS SATURATED (0XFFFF)\n\n\tdouble ratio, d0, d1;\n\n\t\/\/ Determine if either sensor saturated (0xFFFF)\n\t\/\/ If so, abandon ship (calculation will not be accurate)\n\tif ((inCH0 == 0xFFFF) || (inCH1 == 0xFFFF))\n\t{\n\t\toutLux = 0.0;\n\t\treturn false;\n\t}\n\n\t\/\/ Convert from unsigned integer to floating point\n\td0 = inCH0; \n\td1 = inCH1;\n\n\t\/\/ We will need the ratio for subsequent calculations\n\tratio = d1 \/ d0;\n\n\t\/\/ Normalize for integration time\n\td0 *= (402.0\/inMS);\n\td1 *= (402.0\/inMS);\n\n\t\/\/ Normalize for gain\n\tif (!inGain)\n\t{\n\t\td0 *= 16;\n\t\td1 *= 16;\n\t}\n\n\t\/\/ Determine lux per datasheet equations:\n\t\n\tif (ratio < 0.5)\n\t{\n\t\toutLux = 0.0304 * d0 - 0.062 * d0 * pow(ratio, 1.4);\n\t\treturn true;\n\t}\n\n\tif (ratio < 0.61)\n\t{\n\t\toutLux = 0.0224 * d0 - 0.031 * d1;\n\t\treturn true;\n\t}\n\n\tif (ratio < 0.80)\n\t{\n\t\toutLux = 0.0128 * d0 - 0.0153 * d1;\n\t\treturn true;\n\t}\n\n\tif (ratio < 1.30)\n\t{\n\t\toutLux = 0.00146 * d0 - 0.00112 * d1;\n\t\treturn true;\n\t}\n\n\toutLux = 0.0;\n\n\treturn true;\n}\n\nbool \nCModule_LuminositySensor::ReadI2CByte(\n\tuint8_t\t\tinAddress, \n\tuint8_t&\toutValue)\n{\n\t\/\/ Reads a byte from a TSL2561 address\n\t\/\/ Address: TSL2561 address (0 to 15)\n\t\/\/ Value will be set to stored byte\n\t\/\/ Returns true (1) if successful, false (0) if there was an I2C error\n\t\/\/ (Also see getError() above)\n\n\t\/\/ Set up command byte for read\n\tWire.beginTransmission(_i2c_address);\n\tWire.write((inAddress & 0x0F) | TSL2561_CMD);\n\t_error = Wire.endTransmission();\n\n\t\/\/ Read requested byte\n\tif (_error == 0)\n\t{\n\t\tWire.requestFrom(_i2c_address, 1);\n\t\tif (Wire.available() == 1)\n\t\t{\n\t\t\toutValue = Wire.read();\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nbool\nCModule_LuminositySensor::WriteI2CByte(\n\tuint8_t\tinAddress,\n\tuint8_t\tinValue)\n{\n\t\/\/ Write a byte to a TSL2561 address\n\t\/\/ Address: TSL2561 address (0 to 15)\n\t\/\/ Value: byte to write to address\n\t\/\/ Returns true (1) if successful, false (0) if there was an I2C error\n\t\/\/ (Also see getError() above)\n\n\t\/\/ Set up command byte for write\n\tWire.beginTransmission(_i2c_address);\n\tWire.write((inAddress & 0x0F) | TSL2561_CMD);\n\t\/\/ Write byte\n\tWire.write(inValue);\n\t_error = Wire.endTransmission();\n\n\treturn _error == 0;\n}\n\nbool\nCModule_LuminositySensor::ReadI2CUInt16(\n\tuint8_t\t\tinAddress,\n\tuint16_t&\toutValue)\n{\n\t\/\/ Reads an unsigned integer (16 bits) from a TSL2561 address (low byte first)\n\t\/\/ Address: TSL2561 address (0 to 15), low byte first\n\t\/\/ Value will be set to stored unsigned integer\n\t\/\/ Returns true (1) if successful, false (0) if there was an I2C error\n\t\/\/ (Also see getError() above)\n\n\tchar high, low;\n\t\n\t\/\/ Set up command byte for read\n\tWire.beginTransmission(_i2c_address);\n\tWire.write((inAddress & 0x0F) | TSL2561_CMD);\n\t_error = Wire.endTransmission();\n\n\t\/\/ Read two bytes (low and high)\n\tif (_error == 0)\n\t{\n\t\tWire.requestFrom(_i2c_address, 2);\n\t\tif (Wire.available() == 2)\n\t\t{\n\t\t\tlow = Wire.read();\n\t\t\thigh = Wire.read();\n\t\t\t\/\/ Combine bytes into unsigned int\n\t\t\toutValue = word(high,low);\n\t\t\treturn true;\n\t\t}\n\t}\t\n\n\treturn false;\n}\n\nbool \nCModule_LuminositySensor::WriteI2CUInt16(\n\tuint8_t\t\tinAddress, \n\tuint16_t\tinValue)\n{\n\t\/\/ Write an unsigned integer (16 bits) to a TSL2561 address (low byte first)\n\t\/\/ Address: TSL2561 address (0 to 15), low byte first\n\t\/\/ Value: unsigned int to write to address\n\t\/\/ Returns true (1) if successful, false (0) if there was an I2C error\n\t\/\/ (Also see getError() above)\n\t\/\/ Split int into lower and upper bytes, write each byte\n\tif (WriteI2CByte(inAddress, lowByte(inValue)) \n\t\t&& WriteI2CByte(inAddress + 1, highByte(inValue)))\n\t{\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef HAVE_COMMIT\n#include \n#endif\n\n#ifdef HAVE_LIBGNUTLS\n#include \n#endif\n\n#include \n\nextern Context context;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nCmdDiagnostics::CmdDiagnostics ()\n{\n _keyword = \"diagnostics\";\n _usage = \"task diagnostics\";\n _description = STRING_CMD_DIAG_USAGE;\n _read_only = true;\n _displays_id = false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ This command will generate output that is intended to help diagnose problems.\n\/\/\n\/\/ Although this will change over time, initially this command will answer the\n\/\/ kind of questions we always have to ask whenever something is wrong.\nint CmdDiagnostics::execute (std::string& output)\n{\n Color bold;\n if (context.color ())\n bold = Color (\"bold\");\n\n std::stringstream out;\n out << \"\\n\"\n << bold.colorize (PACKAGE_STRING)\n << \"\\n\";\n\n out << \" \" << STRING_CMD_DIAG_PLATFORM << \": \"\n <<\n#if defined (DARWIN)\n \"Darwin\"\n#elif defined (SOLARIS)\n \"Solaris\"\n#elif defined (CYGWIN)\n \"Cygwin\"\n#elif defined (HAIKU)\n \"Haiku\"\n#elif defined (OPENBSD)\n \"OpenBSD\"\n#elif defined (FREEBSD)\n \"FreeBSD\"\n#elif defined (NETBSD)\n \"NetBSD\"\n#elif defined (LINUX)\n \"Linux\"\n#elif defined (KFREEBSD)\n \"GNU\/kFreeBSD\"\n#elif defined (GNUHURD)\n \"GNU\/Hurd\"\n#else\n STRING_CMD_DIAG_UNKNOWN\n#endif\n << \"\\n\\n\";\n\n \/\/ Compiler.\n out << bold.colorize (STRING_CMD_DIAG_COMPILER)\n << \"\\n\"\n#ifdef __VERSION__\n << \" \" << STRING_CMD_DIAG_VERSION << \": \"\n << __VERSION__ << \"\\n\"\n#endif\n << \" \" << STRING_CMD_DIAG_CAPS << \":\"\n#ifdef __STDC__\n << \" +stdc\"\n#endif\n#ifdef __STDC_HOSTED__\n << \" +stdc_hosted\"\n#endif\n#ifdef __STDC_VERSION__\n << \" +\" << __STDC_VERSION__\n#endif\n#ifdef _POSIX_VERSION\n << \" +\" << _POSIX_VERSION\n#endif\n#ifdef _POSIX2_C_VERSION\n << \" +\" << _POSIX2_C_VERSION\n#endif\n#ifdef _ILP32\n << \" +ILP32\"\n#endif\n#ifdef _LP64\n << \" +LP64\"\n#endif\n << \" +c\" << 8 * sizeof (char)\n << \" +i\" << 8 * sizeof (int)\n << \" +l\" << 8 * sizeof (long)\n << \" +vp\" << 8 * sizeof (void*)\n << \" +time_t\" << 8 * sizeof (time_t)\n << \"\\n\";\n\n \/\/ Compiler compliance level.\n std::string compliance = \"non-compliant\";\n#ifdef __cplusplus\n int level = __cplusplus;\n if (level == 199711)\n compliance = \"C++98\/03\";\n else if (level == 201103)\n compliance = \"C++11\";\n else\n compliance = format (level);\n#endif\n out << \" \" << STRING_CMD_DIAG_COMPLIANCE\n << \": \"\n << compliance\n << \"\\n\\n\";\n\n out << bold.colorize (STRING_CMD_DIAG_FEATURES)\n << \"\\n\"\n\n \/\/ Build date.\n << \" \" << STRING_CMD_DIAG_BUILT << \": \" << __DATE__ << \" \" << __TIME__ << \"\\n\"\n#ifdef HAVE_COMMIT\n << \" \" << STRING_CMD_DIAG_COMMIT << \": \" << COMMIT << \"\\n\"\n#endif\n << \" CMake: \" << CMAKE_VERSION << \"\\n\"\n << \" \" << STRING_CMD_DIAG_CAPS << \":\"\n#ifdef HAVE_LIBGNUTLS\n << \" +tls\"\n#else\n << \" -tls\"\n#endif\n << \"\\n\";\n\n out << \" libuuid: \"\n#ifdef HAVE_UUID_UNPARSE_LOWER\n << \"libuuid + uuid_unparse_lower\"\n#else\n << \"libuuid, no uuid_unparse_lower\"\n#endif\n << \"\\n\";\n\n out << \" libgnutls: \"\n#ifdef HAVE_LIBGNUTLS\n#ifdef GNUTLS_VERSION\n << GNUTLS_VERSION\n#elif defined LIBGNUTLS_VERSION\n << LIBGNUTLS_VERSION\n#endif\n#else\n << \"n\/a\"\n#endif\n << \"\\n\";\n\n out << \" Build type: \"\n#ifdef CMAKE_BUILD_TYPE\n << CMAKE_BUILD_TYPE\n#else\n << \"-\"\n#endif\n << \"\\n\\n\";\n\n \/\/ Config: .taskrc found, readable, writable\n out << bold.colorize (STRING_CMD_DIAG_CONFIG)\n << \"\\n\"\n << \" File: \" << context.config._original_file._data << \" \"\n << (context.config._original_file.exists ()\n ? STRING_CMD_DIAG_FOUND\n : STRING_CMD_DIAG_MISSING)\n << \", \" << context.config._original_file.size () << \" \" << \"bytes\"\n << \", mode \"\n << std::setbase (8)\n << context.config._original_file.mode ()\n << \"\\n\";\n\n \/\/ Config: data.location found, readable, writable\n File location (context.config.get (\"data.location\"));\n out << \" Data: \" << location._data << \" \"\n << (location.exists ()\n ? STRING_CMD_DIAG_FOUND\n : STRING_CMD_DIAG_MISSING)\n << \", \" << (location.is_directory () ? \"dir\" : \"?\")\n << \", mode \"\n << std::setbase (8)\n << location.mode ()\n << \"\\n\";\n\n char* env = getenv (\"TASKRC\");\n if (env)\n out << \" TASKRC: \"\n << env\n << \"\\n\";\n\n env = getenv (\"TASKDATA\");\n if (env)\n out << \" TASKDATA: \"\n << env\n << \"\\n\";\n\n out << \" Locking: \"\n << (context.config.getBoolean (\"locking\")\n ? STRING_CMD_DIAG_ENABLED\n : STRING_CMD_DIAG_DISABLED)\n << \"\\n\";\n\n out << \" GC: \"\n << (context.config.getBoolean (\"gc\")\n ? STRING_CMD_DIAG_ENABLED\n : STRING_CMD_DIAG_DISABLED)\n << \"\\n\";\n\n \/\/ Determine rc.editor\/$EDITOR\/$VISUAL.\n char* peditor;\n if (context.config.get (\"editor\") != \"\")\n out << \" rc.editor: \" << context.config.get (\"editor\") << \"\\n\";\n else if ((peditor = getenv (\"VISUAL\")) != NULL)\n out << \" $VISUAL: \" << peditor << \"\\n\";\n else if ((peditor = getenv (\"EDITOR\")) != NULL)\n out << \" $EDITOR: \" << peditor << \"\\n\";\n\n out << \" Server: \"\n << context.config.get (\"taskd.server\")\n << \"\\n\";\n\n if (context.config.get (\"taskd.ca\") != \"\")\n out << \" CA: \"\n << context.config.get (\"taskd.ca\")\n << (File (context.config.get (\"taskd.ca\")).readable ()\n ? \" (readable)\" : \" (not readable)\")\n << \"\\n\";\n\n std::string trust_value = context.config.get (\"taskd.trust\");\n if (trust_value == \"strict\" ||\n trust_value == \"ignore hostname\" ||\n trust_value == \"allow all\")\n out << \" Trust: \" << trust_value << \"\\n\";\n else\n out << \" Trust: Bad value - see 'man taskrc'\\n\";\n\n out << \"Certificate: \"\n << context.config.get (\"taskd.certificate\")\n << (File (context.config.get (\"taskd.certificate\")).readable ()\n ? \" (readable)\" : \" (not readable)\")\n << \"\\n\";\n\n out << \" Key: \"\n << context.config.get (\"taskd.key\")\n << (File (context.config.get (\"taskd.key\")).readable ()\n ? \" (readable)\" : \" (not readable)\")\n << \"\\n\";\n\n out << \" Ciphers: \"\n << context.config.get (\"taskd.ciphers\")\n << \"\\n\";\n\n \/\/ Get credentials, but mask out the key.\n std::string credentials = context.config.get (\"taskd.credentials\");\n std::string::size_type last_slash = credentials.rfind ('\/');\n if (last_slash != std::string::npos)\n credentials = credentials.substr (0, last_slash)\n + \"\/\"\n + std::string (credentials.length () - last_slash - 1, '*');\n\n out << \" Creds: \"\n << credentials\n << \"\\n\\n\";\n\n \/\/ Disaply hook status.\n out << bold.colorize (STRING_CMD_DIAG_HOOKS)\n << \"\\n\"\n << \" Scripts: \"\n << (context.config.getBoolean (\"hooks\") ? STRING_CMD_DIAG_HOOK_ENABLE : STRING_CMD_DIAG_HOOK_DISABLE)\n << \"\\n\";\n\n std::vector hooks = context.hooks.list ();\n if (hooks.size ())\n {\n std::vector ::iterator h;\n for (h = hooks.begin (); h != hooks.end (); ++h)\n {\n Path p (*h);\n std::string name = p.name ();\n out << \" \"\n << *h\n << (p.executable () ? format (\" ({1})\", STRING_CMD_DIAG_HOOK_EXEC) : format (\" ({1})\", STRING_CMD_DIAG_HOOK_NO_EXEC))\n << (p.is_link () ? format (\" ({1})\", STRING_CMD_DIAG_HOOK_SYMLINK) : \"\")\n << ((name.substr (0, 6) == \"on-add\" ||\n name.substr (0, 9) == \"on-modify\" ||\n name.substr (0, 9) == \"on-launch\" ||\n name.substr (0, 7) == \"on-exit\") ? \"\" : format (\" ({1})\", STRING_CMD_DIAG_HOOK_NAME))\n << \"\\n\";\n }\n }\n else\n out << format (\" ({1})\\n\", STRING_CMD_DIAG_NONE);\n\n out << \"\\n\";\n\n \/\/ Verify UUIDs are all unique.\n out << bold.colorize (STRING_CMD_DIAG_TESTS)\n << \"\\n\";\n {\n \/\/ Determine terminal details.\n const char* term = getenv (\"TERM\");\n out << \" $TERM: \"\n << (term ? term : STRING_CMD_DIAG_NONE)\n << \" (\"\n << context.getWidth ()\n << \"x\"\n << context.getHeight ()\n << \")\\n\";\n\n \/\/ Scan tasks for duplicate UUIDs.\n std::vector all = context.tdb2.all_tasks ();\n std::map seen;\n std::vector dups;\n std::string uuid;\n std::vector ::iterator i;\n for (i = all.begin (); i != all.end (); ++i)\n {\n uuid = i->get (\"uuid\");\n if (seen.find (uuid) != seen.end ())\n dups.push_back (uuid);\n else\n seen[uuid] = 0;\n }\n\n out << \" Dups: \"\n << format (STRING_CMD_DIAG_UUID_SCAN, all.size ())\n << \"\\n\";\n\n if (dups.size ())\n {\n std::vector ::iterator d;\n for (d = dups.begin (); d != dups.end (); ++d)\n out << \" \" << format (STRING_CMD_DIAG_UUID_DUP, *d) << \"\\n\";\n }\n else\n {\n out << \" \" << STRING_CMD_DIAG_UUID_NO_DUP\n << \"\\n\";\n }\n }\n\n out << \"\\n\";\n output = out.str ();\n return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nDiagnostics: Removed 'Build caps' line\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef HAVE_COMMIT\n#include \n#endif\n\n#ifdef HAVE_LIBGNUTLS\n#include \n#endif\n\n#include \n\nextern Context context;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nCmdDiagnostics::CmdDiagnostics ()\n{\n _keyword = \"diagnostics\";\n _usage = \"task diagnostics\";\n _description = STRING_CMD_DIAG_USAGE;\n _read_only = true;\n _displays_id = false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ This command will generate output that is intended to help diagnose problems.\n\/\/\n\/\/ Although this will change over time, initially this command will answer the\n\/\/ kind of questions we always have to ask whenever something is wrong.\nint CmdDiagnostics::execute (std::string& output)\n{\n Color bold;\n if (context.color ())\n bold = Color (\"bold\");\n\n std::stringstream out;\n out << \"\\n\"\n << bold.colorize (PACKAGE_STRING)\n << \"\\n\";\n\n out << \" \" << STRING_CMD_DIAG_PLATFORM << \": \"\n <<\n#if defined (DARWIN)\n \"Darwin\"\n#elif defined (SOLARIS)\n \"Solaris\"\n#elif defined (CYGWIN)\n \"Cygwin\"\n#elif defined (HAIKU)\n \"Haiku\"\n#elif defined (OPENBSD)\n \"OpenBSD\"\n#elif defined (FREEBSD)\n \"FreeBSD\"\n#elif defined (NETBSD)\n \"NetBSD\"\n#elif defined (LINUX)\n \"Linux\"\n#elif defined (KFREEBSD)\n \"GNU\/kFreeBSD\"\n#elif defined (GNUHURD)\n \"GNU\/Hurd\"\n#else\n STRING_CMD_DIAG_UNKNOWN\n#endif\n << \"\\n\\n\";\n\n \/\/ Compiler.\n out << bold.colorize (STRING_CMD_DIAG_COMPILER)\n << \"\\n\"\n#ifdef __VERSION__\n << \" \" << STRING_CMD_DIAG_VERSION << \": \"\n << __VERSION__ << \"\\n\"\n#endif\n << \" \" << STRING_CMD_DIAG_CAPS << \":\"\n#ifdef __STDC__\n << \" +stdc\"\n#endif\n#ifdef __STDC_HOSTED__\n << \" +stdc_hosted\"\n#endif\n#ifdef __STDC_VERSION__\n << \" +\" << __STDC_VERSION__\n#endif\n#ifdef _POSIX_VERSION\n << \" +\" << _POSIX_VERSION\n#endif\n#ifdef _POSIX2_C_VERSION\n << \" +\" << _POSIX2_C_VERSION\n#endif\n#ifdef _ILP32\n << \" +ILP32\"\n#endif\n#ifdef _LP64\n << \" +LP64\"\n#endif\n << \" +c\" << 8 * sizeof (char)\n << \" +i\" << 8 * sizeof (int)\n << \" +l\" << 8 * sizeof (long)\n << \" +vp\" << 8 * sizeof (void*)\n << \" +time_t\" << 8 * sizeof (time_t)\n << \"\\n\";\n\n \/\/ Compiler compliance level.\n std::string compliance = \"non-compliant\";\n#ifdef __cplusplus\n int level = __cplusplus;\n if (level == 199711)\n compliance = \"C++98\/03\";\n else if (level == 201103)\n compliance = \"C++11\";\n else\n compliance = format (level);\n#endif\n out << \" \" << STRING_CMD_DIAG_COMPLIANCE\n << \": \"\n << compliance\n << \"\\n\\n\";\n\n out << bold.colorize (STRING_CMD_DIAG_FEATURES)\n << \"\\n\"\n\n \/\/ Build date.\n << \" \" << STRING_CMD_DIAG_BUILT << \": \" << __DATE__ << \" \" << __TIME__ << \"\\n\"\n#ifdef HAVE_COMMIT\n << \" \" << STRING_CMD_DIAG_COMMIT << \": \" << COMMIT << \"\\n\"\n#endif\n << \" CMake: \" << CMAKE_VERSION << \"\\n\";\n\n out << \" libuuid: \"\n#ifdef HAVE_UUID_UNPARSE_LOWER\n << \"libuuid + uuid_unparse_lower\"\n#else\n << \"libuuid, no uuid_unparse_lower\"\n#endif\n << \"\\n\";\n\n out << \" libgnutls: \"\n#ifdef HAVE_LIBGNUTLS\n#ifdef GNUTLS_VERSION\n << GNUTLS_VERSION\n#elif defined LIBGNUTLS_VERSION\n << LIBGNUTLS_VERSION\n#endif\n#else\n << \"n\/a\"\n#endif\n << \"\\n\";\n\n out << \" Build type: \"\n#ifdef CMAKE_BUILD_TYPE\n << CMAKE_BUILD_TYPE\n#else\n << \"-\"\n#endif\n << \"\\n\\n\";\n\n \/\/ Config: .taskrc found, readable, writable\n out << bold.colorize (STRING_CMD_DIAG_CONFIG)\n << \"\\n\"\n << \" File: \" << context.config._original_file._data << \" \"\n << (context.config._original_file.exists ()\n ? STRING_CMD_DIAG_FOUND\n : STRING_CMD_DIAG_MISSING)\n << \", \" << context.config._original_file.size () << \" \" << \"bytes\"\n << \", mode \"\n << std::setbase (8)\n << context.config._original_file.mode ()\n << \"\\n\";\n\n \/\/ Config: data.location found, readable, writable\n File location (context.config.get (\"data.location\"));\n out << \" Data: \" << location._data << \" \"\n << (location.exists ()\n ? STRING_CMD_DIAG_FOUND\n : STRING_CMD_DIAG_MISSING)\n << \", \" << (location.is_directory () ? \"dir\" : \"?\")\n << \", mode \"\n << std::setbase (8)\n << location.mode ()\n << \"\\n\";\n\n char* env = getenv (\"TASKRC\");\n if (env)\n out << \" TASKRC: \"\n << env\n << \"\\n\";\n\n env = getenv (\"TASKDATA\");\n if (env)\n out << \" TASKDATA: \"\n << env\n << \"\\n\";\n\n out << \" Locking: \"\n << (context.config.getBoolean (\"locking\")\n ? STRING_CMD_DIAG_ENABLED\n : STRING_CMD_DIAG_DISABLED)\n << \"\\n\";\n\n out << \" GC: \"\n << (context.config.getBoolean (\"gc\")\n ? STRING_CMD_DIAG_ENABLED\n : STRING_CMD_DIAG_DISABLED)\n << \"\\n\";\n\n \/\/ Determine rc.editor\/$EDITOR\/$VISUAL.\n char* peditor;\n if (context.config.get (\"editor\") != \"\")\n out << \" rc.editor: \" << context.config.get (\"editor\") << \"\\n\";\n else if ((peditor = getenv (\"VISUAL\")) != NULL)\n out << \" $VISUAL: \" << peditor << \"\\n\";\n else if ((peditor = getenv (\"EDITOR\")) != NULL)\n out << \" $EDITOR: \" << peditor << \"\\n\";\n\n out << \" Server: \"\n << context.config.get (\"taskd.server\")\n << \"\\n\";\n\n if (context.config.get (\"taskd.ca\") != \"\")\n out << \" CA: \"\n << context.config.get (\"taskd.ca\")\n << (File (context.config.get (\"taskd.ca\")).readable ()\n ? \" (readable)\" : \" (not readable)\")\n << \"\\n\";\n\n std::string trust_value = context.config.get (\"taskd.trust\");\n if (trust_value == \"strict\" ||\n trust_value == \"ignore hostname\" ||\n trust_value == \"allow all\")\n out << \" Trust: \" << trust_value << \"\\n\";\n else\n out << \" Trust: Bad value - see 'man taskrc'\\n\";\n\n out << \"Certificate: \"\n << context.config.get (\"taskd.certificate\")\n << (File (context.config.get (\"taskd.certificate\")).readable ()\n ? \" (readable)\" : \" (not readable)\")\n << \"\\n\";\n\n out << \" Key: \"\n << context.config.get (\"taskd.key\")\n << (File (context.config.get (\"taskd.key\")).readable ()\n ? \" (readable)\" : \" (not readable)\")\n << \"\\n\";\n\n out << \" Ciphers: \"\n << context.config.get (\"taskd.ciphers\")\n << \"\\n\";\n\n \/\/ Get credentials, but mask out the key.\n std::string credentials = context.config.get (\"taskd.credentials\");\n std::string::size_type last_slash = credentials.rfind ('\/');\n if (last_slash != std::string::npos)\n credentials = credentials.substr (0, last_slash)\n + \"\/\"\n + std::string (credentials.length () - last_slash - 1, '*');\n\n out << \" Creds: \"\n << credentials\n << \"\\n\\n\";\n\n \/\/ Disaply hook status.\n out << bold.colorize (STRING_CMD_DIAG_HOOKS)\n << \"\\n\"\n << \" Scripts: \"\n << (context.config.getBoolean (\"hooks\") ? STRING_CMD_DIAG_HOOK_ENABLE : STRING_CMD_DIAG_HOOK_DISABLE)\n << \"\\n\";\n\n std::vector hooks = context.hooks.list ();\n if (hooks.size ())\n {\n std::vector ::iterator h;\n for (h = hooks.begin (); h != hooks.end (); ++h)\n {\n Path p (*h);\n std::string name = p.name ();\n out << \" \"\n << *h\n << (p.executable () ? format (\" ({1})\", STRING_CMD_DIAG_HOOK_EXEC) : format (\" ({1})\", STRING_CMD_DIAG_HOOK_NO_EXEC))\n << (p.is_link () ? format (\" ({1})\", STRING_CMD_DIAG_HOOK_SYMLINK) : \"\")\n << ((name.substr (0, 6) == \"on-add\" ||\n name.substr (0, 9) == \"on-modify\" ||\n name.substr (0, 9) == \"on-launch\" ||\n name.substr (0, 7) == \"on-exit\") ? \"\" : format (\" ({1})\", STRING_CMD_DIAG_HOOK_NAME))\n << \"\\n\";\n }\n }\n else\n out << format (\" ({1})\\n\", STRING_CMD_DIAG_NONE);\n\n out << \"\\n\";\n\n \/\/ Verify UUIDs are all unique.\n out << bold.colorize (STRING_CMD_DIAG_TESTS)\n << \"\\n\";\n {\n \/\/ Determine terminal details.\n const char* term = getenv (\"TERM\");\n out << \" $TERM: \"\n << (term ? term : STRING_CMD_DIAG_NONE)\n << \" (\"\n << context.getWidth ()\n << \"x\"\n << context.getHeight ()\n << \")\\n\";\n\n \/\/ Scan tasks for duplicate UUIDs.\n std::vector all = context.tdb2.all_tasks ();\n std::map seen;\n std::vector dups;\n std::string uuid;\n std::vector ::iterator i;\n for (i = all.begin (); i != all.end (); ++i)\n {\n uuid = i->get (\"uuid\");\n if (seen.find (uuid) != seen.end ())\n dups.push_back (uuid);\n else\n seen[uuid] = 0;\n }\n\n out << \" Dups: \"\n << format (STRING_CMD_DIAG_UUID_SCAN, all.size ())\n << \"\\n\";\n\n if (dups.size ())\n {\n std::vector ::iterator d;\n for (d = dups.begin (); d != dups.end (); ++d)\n out << \" \" << format (STRING_CMD_DIAG_UUID_DUP, *d) << \"\\n\";\n }\n else\n {\n out << \" \" << STRING_CMD_DIAG_UUID_NO_DUP\n << \"\\n\";\n }\n }\n\n out << \"\\n\";\n output = out.str ();\n return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2017 The Khronos Group Inc.\n\/\/ Copyright (c) 2017 Valve Corporation\n\/\/ Copyright (c) 2017 LunarG, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Authors: Mark Young \n\/\/ Nat Brown \n\/\/\n\n#include \n#include \"xr_dependencies.h\"\n\n#if defined DISABLE_STD_FILESYSTEM\n#define USE_EXPERIMENTAL_FS 0\n#define USE_FINAL_FS 0\n\n#else\n\/\/ If the C++ macro is set to the version containing C++17, it must support\n\/\/ the final C++17 package\n#if __cplusplus >= 201703L\n#define USE_EXPERIMENTAL_FS 0\n#define USE_FINAL_FS 1\n\n#elif defined(_MSC_VER) && _MSC_VER >= 1900\n\n#if defined(_HAS_CXX17) && _HAS_CXX17\n\/\/ When MSC supports c++17 use package.\n#define USE_EXPERIMENTAL_FS 0\n#define USE_FINAL_FS 1\n#else\n\/\/ MSC before c++17 need to use package.\n#define USE_EXPERIMENTAL_FS 1\n#define USE_FINAL_FS 0\n#endif \/\/ !_HAS_CXX17\n\n\/\/ Right now, GCC still only supports the experimental filesystem items starting in GCC 6\n#elif (__GNUC__ >= 6)\n#define USE_EXPERIMENTAL_FS 1\n#define USE_FINAL_FS 0\n\n\/\/ If Clang, check for feature support\n#elif defined(__clang__) && (__cpp_lib_filesystem || __cpp_lib_experimental_filesystem)\n#if __cpp_lib_filesystem\n#define USE_EXPERIMENTAL_FS 0\n#define USE_FINAL_FS 1\n#else\n#define USE_EXPERIMENTAL_FS 1\n#define USE_FINAL_FS 0\n#endif\n\n\/\/ If all above fails, fall back to standard C++ and OS-specific items\n#else\n#define USE_EXPERIMENTAL_FS 0\n#define USE_FINAL_FS 0\n#endif\n#endif\n\n#if USE_FINAL_FS == 1\n#include \n#define FS_PREFIX std::filesystem\n#elif USE_EXPERIMENTAL_FS == 1\n#if (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)\n#error \"Windows universal application doesn't support system::experimental::filesystem\"\n#endif\n#include \n#define FS_PREFIX std::experimental::filesystem\n#elif defined(XR_USE_PLATFORM_WIN32)\n\/\/ Windows fallback includes\n#include \n#include \n#include \n#else\n\/\/ Linux\/Apple fallback includes\n#include \n#include \n#include \n#include \n#include \n#include \n#endif\n\n#include \"filesystem_utils.hpp\"\n\n#if defined(XR_USE_PLATFORM_WIN32)\n#define PATH_SEPARATOR ';'\n#define DIRECTORY_SYMBOL '\\\\'\n#else\n#define PATH_SEPARATOR ':'\n#define DIRECTORY_SYMBOL '\/'\n#endif\n\n#if (USE_FINAL_FS == 1) || (USE_EXPERIMENTAL_FS == 1)\n\/\/ We can use one of the C++ filesystem packages\n\nbool FileSysUtilsIsRegularFile(const std::string& path) {\n try {\n return FS_PREFIX::is_regular_file(path);\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsIsDirectory(const std::string& path) {\n try {\n return FS_PREFIX::is_directory(path);\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsPathExists(const std::string& path) {\n try {\n return FS_PREFIX::exists(path);\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsIsAbsolutePath(const std::string& path) {\n try {\n FS_PREFIX::path file_path(path);\n return file_path.is_absolute();\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsGetCurrentPath(std::string& path) {\n try {\n FS_PREFIX::path cur_path = FS_PREFIX::current_path();\n path = cur_path.string();\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) {\n try {\n FS_PREFIX::path path_var(file_path);\n parent_path = path_var.parent_path().string();\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) {\n try {\n absolute = FS_PREFIX::absolute(path).string();\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) {\n try {\n FS_PREFIX::path parent_path(parent);\n FS_PREFIX::path child_path(child);\n FS_PREFIX::path full_path = parent_path \/ child_path;\n combined = full_path.string();\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsParsePathList(std::string& path_list, std::vector& paths) {\n try {\n std::string::size_type start = 0;\n std::string::size_type location = path_list.find(PATH_SEPARATOR);\n while (location != std::string::npos) {\n paths.push_back(path_list.substr(start, location));\n start = location + 1;\n location = path_list.find(PATH_SEPARATOR, start);\n }\n paths.push_back(path_list.substr(start, location));\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsFindFilesInPath(const std::string& path, std::vector& files) {\n try {\n for (auto& dir_iter : FS_PREFIX::directory_iterator(path)) {\n files.push_back(dir_iter.path().filename().string());\n }\n return true;\n } catch (...) {\n }\n return false;\n}\n\n#elif defined(XR_OS_WINDOWS)\n\n\/\/ Workaround for MS VS 2010\/2013 don't support the experimental filesystem\n\nbool FileSysUtilsIsRegularFile(const std::string& path) {\n try {\n return (1 != PathIsDirectoryA(path.c_str()));\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsIsDirectory(const std::string& path) {\n try {\n return (1 == PathIsDirectoryA(path.c_str()));\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsPathExists(const std::string& path) {\n try {\n return (1 == PathFileExistsA(path.c_str()));\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsIsAbsolutePath(const std::string& path) {\n try {\n if ((path[0] == '\\\\') || (path[1] == ':' && (path[2] == '\\\\' || path[2] == '\/'))) {\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetCurrentPath(std::string& path) {\n try {\n char tmp_path[MAX_PATH];\n if (nullptr != _getcwd(tmp_path, MAX_PATH - 1)) {\n path = tmp_path;\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) {\n try {\n std::string full_path;\n if (FileSysUtilsGetAbsolutePath(file_path, full_path)) {\n std::string::size_type lastSeperator = full_path.find_last_of(DIRECTORY_SYMBOL);\n parent_path = (lastSeperator == 0) ? full_path : full_path.substr(0, lastSeperator - 1);\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) {\n try {\n char tmp_path[MAX_PATH];\n if (0 != GetFullPathNameA(path.c_str(), MAX_PATH, tmp_path, NULL)) {\n absolute = tmp_path;\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) {\n try {\n std::string::size_type parent_len = parent.length();\n if (0 == parent_len || \".\" == parent || \".\\\\\" == parent || \".\/\" == parent) {\n combined = child;\n return true;\n }\n char last_char = parent[parent_len - 1];\n if (last_char == DIRECTORY_SYMBOL) {\n parent_len--;\n }\n combined = parent.substr(0, parent_len) + DIRECTORY_SYMBOL + child;\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsParsePathList(std::string& path_list, std::vector& paths) {\n try {\n std::string::size_type start = 0;\n std::string::size_type location = path_list.find(PATH_SEPARATOR);\n while (location != std::string::npos) {\n paths.push_back(path_list.substr(start, location));\n start = location + 1;\n location = path_list.find(PATH_SEPARATOR, start);\n }\n paths.push_back(path_list.substr(start, location));\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsFindFilesInPath(const std::string& path, std::vector& files) {\n try {\n WIN32_FIND_DATAA file_data;\n HANDLE file_handle = FindFirstFileA(path.c_str(), &file_data);\n if (file_handle != INVALID_HANDLE_VALUE) {\n do {\n if (!(file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {\n files.push_back(file_data.cFileName);\n }\n } while (FindNextFileA(file_handle, &file_data));\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\n#else \/\/ XR_OS_LINUX\/XR_OS_APPLE fallback\n\n#include \n#include \n#include \n#include \n#include \n\n\/\/ simple POSIX-compatible implementation of the pieces used by OpenXR\n\nbool FileSysUtilsIsRegularFile(const std::string& path) {\n try {\n struct stat path_stat;\n stat(path.c_str(), &path_stat);\n return S_ISREG(path_stat.st_mode);\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsIsDirectory(const std::string& path) {\n try {\n struct stat path_stat;\n stat(path.c_str(), &path_stat);\n return S_ISDIR(path_stat.st_mode);\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsPathExists(const std::string& path) {\n try {\n return (access(path.c_str(), F_OK) != -1);\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsIsAbsolutePath(const std::string& path) {\n try {\n return (path[0] == DIRECTORY_SYMBOL);\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetCurrentPath(std::string& path) {\n try {\n char tmp_path[PATH_MAX];\n if (nullptr != getcwd(tmp_path, PATH_MAX - 1)) {\n path = tmp_path;\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) {\n try {\n std::string full_path;\n if (FileSysUtilsGetAbsolutePath(file_path, full_path)) {\n std::string::size_type lastSeperator = full_path.find_last_of(DIRECTORY_SYMBOL);\n parent_path = (lastSeperator == 0) ? full_path : full_path.substr(0, lastSeperator - 1);\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) {\n try {\n char buf[PATH_MAX];\n if (nullptr != realpath(path.c_str(), buf)) {\n absolute = buf;\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) {\n try {\n std::string::size_type parent_len = parent.length();\n if (0 == parent_len || \".\" == parent || \".\/\" == parent) {\n combined = child;\n return true;\n }\n char last_char = parent[parent_len - 1];\n if (last_char == DIRECTORY_SYMBOL) {\n parent_len--;\n }\n combined = parent.substr(0, parent_len) + DIRECTORY_SYMBOL + child;\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsParsePathList(std::string& path_list, std::vector& paths) {\n try {\n std::string::size_type start = 0;\n std::string::size_type location = path_list.find(PATH_SEPARATOR);\n while (location != std::string::npos) {\n paths.push_back(path_list.substr(start, location));\n start = location + 1;\n location = path_list.find(PATH_SEPARATOR, start);\n }\n paths.push_back(path_list.substr(start, location));\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsFindFilesInPath(const std::string& path, std::vector& files) {\n try {\n DIR* dir;\n struct dirent* entry;\n dir = opendir(path.c_str());\n while (dir && (entry = readdir(dir))) {\n files.push_back(entry->d_name);\n }\n closedir(dir);\n return true;\n } catch (...) {\n }\n return false;\n}\n\n#endif\nfix minor substr error\/\/ Copyright (c) 2017 The Khronos Group Inc.\n\/\/ Copyright (c) 2017 Valve Corporation\n\/\/ Copyright (c) 2017 LunarG, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Authors: Mark Young \n\/\/ Nat Brown \n\/\/\n\n#include \n#include \"xr_dependencies.h\"\n\n#if defined DISABLE_STD_FILESYSTEM\n#define USE_EXPERIMENTAL_FS 0\n#define USE_FINAL_FS 0\n\n#else\n\/\/ If the C++ macro is set to the version containing C++17, it must support\n\/\/ the final C++17 package\n#if __cplusplus >= 201703L\n#define USE_EXPERIMENTAL_FS 0\n#define USE_FINAL_FS 1\n\n#elif defined(_MSC_VER) && _MSC_VER >= 1900\n\n#if defined(_HAS_CXX17) && _HAS_CXX17\n\/\/ When MSC supports c++17 use package.\n#define USE_EXPERIMENTAL_FS 0\n#define USE_FINAL_FS 1\n#else\n\/\/ MSC before c++17 need to use package.\n#define USE_EXPERIMENTAL_FS 1\n#define USE_FINAL_FS 0\n#endif \/\/ !_HAS_CXX17\n\n\/\/ Right now, GCC still only supports the experimental filesystem items starting in GCC 6\n#elif (__GNUC__ >= 6)\n#define USE_EXPERIMENTAL_FS 1\n#define USE_FINAL_FS 0\n\n\/\/ If Clang, check for feature support\n#elif defined(__clang__) && (__cpp_lib_filesystem || __cpp_lib_experimental_filesystem)\n#if __cpp_lib_filesystem\n#define USE_EXPERIMENTAL_FS 0\n#define USE_FINAL_FS 1\n#else\n#define USE_EXPERIMENTAL_FS 1\n#define USE_FINAL_FS 0\n#endif\n\n\/\/ If all above fails, fall back to standard C++ and OS-specific items\n#else\n#define USE_EXPERIMENTAL_FS 0\n#define USE_FINAL_FS 0\n#endif\n#endif\n\n#if USE_FINAL_FS == 1\n#include \n#define FS_PREFIX std::filesystem\n#elif USE_EXPERIMENTAL_FS == 1\n#if (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)\n#error \"Windows universal application doesn't support system::experimental::filesystem\"\n#endif\n#include \n#define FS_PREFIX std::experimental::filesystem\n#elif defined(XR_USE_PLATFORM_WIN32)\n\/\/ Windows fallback includes\n#include \n#include \n#include \n#else\n\/\/ Linux\/Apple fallback includes\n#include \n#include \n#include \n#include \n#include \n#include \n#endif\n\n#include \"filesystem_utils.hpp\"\n\n#if defined(XR_USE_PLATFORM_WIN32)\n#define PATH_SEPARATOR ';'\n#define DIRECTORY_SYMBOL '\\\\'\n#else\n#define PATH_SEPARATOR ':'\n#define DIRECTORY_SYMBOL '\/'\n#endif\n\n#if (USE_FINAL_FS == 1) || (USE_EXPERIMENTAL_FS == 1)\n\/\/ We can use one of the C++ filesystem packages\n\nbool FileSysUtilsIsRegularFile(const std::string& path) {\n try {\n return FS_PREFIX::is_regular_file(path);\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsIsDirectory(const std::string& path) {\n try {\n return FS_PREFIX::is_directory(path);\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsPathExists(const std::string& path) {\n try {\n return FS_PREFIX::exists(path);\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsIsAbsolutePath(const std::string& path) {\n try {\n FS_PREFIX::path file_path(path);\n return file_path.is_absolute();\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsGetCurrentPath(std::string& path) {\n try {\n FS_PREFIX::path cur_path = FS_PREFIX::current_path();\n path = cur_path.string();\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) {\n try {\n FS_PREFIX::path path_var(file_path);\n parent_path = path_var.parent_path().string();\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) {\n try {\n absolute = FS_PREFIX::absolute(path).string();\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) {\n try {\n FS_PREFIX::path parent_path(parent);\n FS_PREFIX::path child_path(child);\n FS_PREFIX::path full_path = parent_path \/ child_path;\n combined = full_path.string();\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsParsePathList(std::string& path_list, std::vector& paths) {\n try {\n std::string::size_type start = 0;\n std::string::size_type location = path_list.find(PATH_SEPARATOR);\n while (location != std::string::npos) {\n paths.push_back(path_list.substr(start, location));\n start = location + 1;\n location = path_list.find(PATH_SEPARATOR, start);\n }\n paths.push_back(path_list.substr(start, location));\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsFindFilesInPath(const std::string& path, std::vector& files) {\n try {\n for (auto& dir_iter : FS_PREFIX::directory_iterator(path)) {\n files.push_back(dir_iter.path().filename().string());\n }\n return true;\n } catch (...) {\n }\n return false;\n}\n\n#elif defined(XR_OS_WINDOWS)\n\n\/\/ Workaround for MS VS 2010\/2013 don't support the experimental filesystem\n\nbool FileSysUtilsIsRegularFile(const std::string& path) {\n try {\n return (1 != PathIsDirectoryA(path.c_str()));\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsIsDirectory(const std::string& path) {\n try {\n return (1 == PathIsDirectoryA(path.c_str()));\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsPathExists(const std::string& path) {\n try {\n return (1 == PathFileExistsA(path.c_str()));\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsIsAbsolutePath(const std::string& path) {\n try {\n if ((path[0] == '\\\\') || (path[1] == ':' && (path[2] == '\\\\' || path[2] == '\/'))) {\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetCurrentPath(std::string& path) {\n try {\n char tmp_path[MAX_PATH];\n if (nullptr != _getcwd(tmp_path, MAX_PATH - 1)) {\n path = tmp_path;\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) {\n try {\n std::string full_path;\n if (FileSysUtilsGetAbsolutePath(file_path, full_path)) {\n std::string::size_type lastSeperator = full_path.find_last_of(DIRECTORY_SYMBOL);\n parent_path = (lastSeperator == 0) ? full_path : full_path.substr(0, lastSeperator);\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) {\n try {\n char tmp_path[MAX_PATH];\n if (0 != GetFullPathNameA(path.c_str(), MAX_PATH, tmp_path, NULL)) {\n absolute = tmp_path;\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) {\n try {\n std::string::size_type parent_len = parent.length();\n if (0 == parent_len || \".\" == parent || \".\\\\\" == parent || \".\/\" == parent) {\n combined = child;\n return true;\n }\n char last_char = parent[parent_len - 1];\n if (last_char == DIRECTORY_SYMBOL) {\n parent_len--;\n }\n combined = parent.substr(0, parent_len) + DIRECTORY_SYMBOL + child;\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsParsePathList(std::string& path_list, std::vector& paths) {\n try {\n std::string::size_type start = 0;\n std::string::size_type location = path_list.find(PATH_SEPARATOR);\n while (location != std::string::npos) {\n paths.push_back(path_list.substr(start, location));\n start = location + 1;\n location = path_list.find(PATH_SEPARATOR, start);\n }\n paths.push_back(path_list.substr(start, location));\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsFindFilesInPath(const std::string& path, std::vector& files) {\n try {\n WIN32_FIND_DATAA file_data;\n HANDLE file_handle = FindFirstFileA(path.c_str(), &file_data);\n if (file_handle != INVALID_HANDLE_VALUE) {\n do {\n if (!(file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {\n files.push_back(file_data.cFileName);\n }\n } while (FindNextFileA(file_handle, &file_data));\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\n#else \/\/ XR_OS_LINUX\/XR_OS_APPLE fallback\n\n#include \n#include \n#include \n#include \n#include \n\n\/\/ simple POSIX-compatible implementation of the pieces used by OpenXR\n\nbool FileSysUtilsIsRegularFile(const std::string& path) {\n try {\n struct stat path_stat;\n stat(path.c_str(), &path_stat);\n return S_ISREG(path_stat.st_mode);\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsIsDirectory(const std::string& path) {\n try {\n struct stat path_stat;\n stat(path.c_str(), &path_stat);\n return S_ISDIR(path_stat.st_mode);\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsPathExists(const std::string& path) {\n try {\n return (access(path.c_str(), F_OK) != -1);\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsIsAbsolutePath(const std::string& path) {\n try {\n return (path[0] == DIRECTORY_SYMBOL);\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetCurrentPath(std::string& path) {\n try {\n char tmp_path[PATH_MAX];\n if (nullptr != getcwd(tmp_path, PATH_MAX - 1)) {\n path = tmp_path;\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) {\n try {\n std::string full_path;\n if (FileSysUtilsGetAbsolutePath(file_path, full_path)) {\n std::string::size_type lastSeperator = full_path.find_last_of(DIRECTORY_SYMBOL);\n parent_path = (lastSeperator == 0) ? full_path : full_path.substr(0, lastSeperator - 1);\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) {\n try {\n char buf[PATH_MAX];\n if (nullptr != realpath(path.c_str(), buf)) {\n absolute = buf;\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) {\n try {\n std::string::size_type parent_len = parent.length();\n if (0 == parent_len || \".\" == parent || \".\/\" == parent) {\n combined = child;\n return true;\n }\n char last_char = parent[parent_len - 1];\n if (last_char == DIRECTORY_SYMBOL) {\n parent_len--;\n }\n combined = parent.substr(0, parent_len) + DIRECTORY_SYMBOL + child;\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsParsePathList(std::string& path_list, std::vector& paths) {\n try {\n std::string::size_type start = 0;\n std::string::size_type location = path_list.find(PATH_SEPARATOR);\n while (location != std::string::npos) {\n paths.push_back(path_list.substr(start, location));\n start = location + 1;\n location = path_list.find(PATH_SEPARATOR, start);\n }\n paths.push_back(path_list.substr(start, location));\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsFindFilesInPath(const std::string& path, std::vector& files) {\n try {\n DIR* dir;\n struct dirent* entry;\n dir = opendir(path.c_str());\n while (dir && (entry = readdir(dir))) {\n files.push_back(entry->d_name);\n }\n closedir(dir);\n return true;\n } catch (...) {\n }\n return false;\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/===-- gccas.cpp - The \"optimizing assembler\" used by the GCC frontend ---===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This utility is designed to be used by the GCC frontend for creating bytecode\n\/\/ files from its intermediate LLVM assembly. The requirements for this utility\n\/\/ are thus slightly different than that of the standard `as' util.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Analysis\/LoadValueNumbering.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/Assembly\/Parser.h\"\n#include \"llvm\/Bytecode\/WriteBytecodePass.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"Support\/CommandLine.h\"\n#include \"Support\/Signals.h\"\n#include \n#include \n\nusing namespace llvm;\n\nnamespace {\n cl::opt\n InputFilename(cl::Positional,cl::desc(\"\"),cl::init(\"-\"));\n\n cl::opt \n OutputFilename(\"o\", cl::desc(\"Override output filename\"),\n cl::value_desc(\"filename\"));\n\n cl::opt \n Verify(\"verify\", cl::desc(\"Verify each pass result\"));\n\n cl::opt\n DisableInline(\"disable-inlining\", cl::desc(\"Do not run the inliner pass\"));\n}\n\n\nstatic inline void addPass(PassManager &PM, Pass *P) {\n \/\/ Add the pass to the pass manager...\n PM.add(P);\n \n \/\/ If we are verifying all of the intermediate steps, add the verifier...\n if (Verify) PM.add(createVerifierPass());\n}\n\n\nvoid AddConfiguredTransformationPasses(PassManager &PM) {\n PM.add(createVerifierPass()); \/\/ Verify that input is correct\n addPass(PM, createLowerSetJmpPass()); \/\/ Lower llvm.setjmp\/.longjmp\n addPass(PM, createFunctionResolvingPass()); \/\/ Resolve (...) functions\n addPass(PM, createCFGSimplificationPass()); \/\/ Clean up disgusting code\n addPass(PM, createRaiseAllocationsPass()); \/\/ call %malloc -> malloc inst\n addPass(PM, createGlobalDCEPass()); \/\/ Remove unused globals\n addPass(PM, createIPConstantPropagationPass());\/\/ IP Constant Propagation\n addPass(PM, createDeadArgEliminationPass()); \/\/ Dead argument elimination\n\n addPass(PM, createPruneEHPass()); \/\/ Remove dead EH info\n\n if (!DisableInline)\n addPass(PM, createFunctionInliningPass()); \/\/ Inline small functions\n\n addPass(PM, createInstructionCombiningPass()); \/\/ Cleanup code for raise\n\n \/\/ HACK HACK HACK. This pass should be extended to support calls like 'call\n \/\/ (const expr cast (free))(Ty *). Until it does so, we have to run it after\n \/\/ instruction combining. This should be removed after PLDI!\n addPass(PM, createRaiseAllocationsPass()); \/\/ call %malloc -> malloc inst\n\n addPass(PM, createRaisePointerReferencesPass());\/\/ Recover type information\n addPass(PM, createTailDuplicationPass()); \/\/ Simplify cfg by copying code\n addPass(PM, createCFGSimplificationPass()); \/\/ Merge & remove BBs\n addPass(PM, createScalarReplAggregatesPass()); \/\/ Break up aggregate allocas\n addPass(PM, createTailCallEliminationPass()); \/\/ Eliminate tail calls\n addPass(PM, createInstructionCombiningPass()); \/\/ Combine silly seq's\n\n addPass(PM, createReassociatePass()); \/\/ Reassociate expressions\n addPass(PM, createInstructionCombiningPass()); \/\/ Combine silly seq's\n addPass(PM, createCFGSimplificationPass()); \/\/ Merge & remove BBs\n addPass(PM, createLICMPass()); \/\/ Hoist loop invariants\n addPass(PM, createLoadValueNumberingPass()); \/\/ GVN for load instructions\n addPass(PM, createGCSEPass()); \/\/ Remove common subexprs\n addPass(PM, createSCCPPass()); \/\/ Constant prop with SCCP\n\n \/\/ Run instcombine after redundancy elimination to exploit opportunities\n \/\/ opened up by them.\n addPass(PM, createInstructionCombiningPass());\n addPass(PM, createIndVarSimplifyPass()); \/\/ Canonicalize indvars\n addPass(PM, createAggressiveDCEPass()); \/\/ SSA based 'Aggressive DCE'\n addPass(PM, createCFGSimplificationPass()); \/\/ Merge & remove BBs\n addPass(PM, createDeadTypeEliminationPass()); \/\/ Eliminate dead types\n addPass(PM, createConstantMergePass()); \/\/ Merge dup global constants\n}\n\n\nint main(int argc, char **argv) {\n cl::ParseCommandLineOptions(argc, argv, \" llvm .s -> .o assembler for GCC\\n\");\n\n std::auto_ptr M;\n try {\n \/\/ Parse the file now...\n M.reset(ParseAssemblyFile(InputFilename));\n } catch (const ParseException &E) {\n std::cerr << argv[0] << \": \" << E.getMessage() << \"\\n\";\n return 1;\n }\n\n if (M.get() == 0) {\n std::cerr << argv[0] << \": assembly didn't read correctly.\\n\";\n return 1;\n }\n\n std::ostream *Out = 0;\n if (OutputFilename == \"\") { \/\/ Didn't specify an output filename?\n if (InputFilename == \"-\") {\n OutputFilename = \"-\";\n } else {\n std::string IFN = InputFilename;\n int Len = IFN.length();\n if (IFN[Len-2] == '.' && IFN[Len-1] == 's') { \/\/ Source ends in .s?\n OutputFilename = std::string(IFN.begin(), IFN.end()-2);\n } else {\n OutputFilename = IFN; \/\/ Append a .o to it\n }\n OutputFilename += \".o\";\n }\n }\n\n if (OutputFilename == \"-\")\n Out = &std::cout;\n else {\n Out = new std::ofstream(OutputFilename.c_str(), std::ios::out);\n\n \/\/ Make sure that the Out file gets unlinked from the disk if we get a\n \/\/ signal\n RemoveFileOnSignal(OutputFilename);\n }\n\n \n if (!Out->good()) {\n std::cerr << argv[0] << \": error opening \" << OutputFilename << \"!\\n\";\n return 1;\n }\n\n \/\/ In addition to just parsing the input from GCC, we also want to spiff it up\n \/\/ a little bit. Do this now.\n \/\/\n PassManager Passes;\n\n \/\/ Add an appropriate TargetData instance for this module...\n Passes.add(new TargetData(\"gccas\", M.get()));\n\n \/\/ Add all of the transformation passes to the pass manager to do the cleanup\n \/\/ and optimization of the GCC output.\n \/\/\n AddConfiguredTransformationPasses(Passes);\n\n \/\/ Write bytecode to file...\n Passes.add(new WriteBytecodePass(Out));\n\n \/\/ Run our queue of passes all at once now, efficiently.\n Passes.run(*M.get());\n\n if (Out != &std::cout) delete Out;\n return 0;\n}\nIt is now after pldi. This issue has been fixed, so remove the hack\/\/===-- gccas.cpp - The \"optimizing assembler\" used by the GCC frontend ---===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This utility is designed to be used by the GCC frontend for creating bytecode\n\/\/ files from its intermediate LLVM assembly. The requirements for this utility\n\/\/ are thus slightly different than that of the standard `as' util.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Analysis\/LoadValueNumbering.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/Assembly\/Parser.h\"\n#include \"llvm\/Bytecode\/WriteBytecodePass.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"Support\/CommandLine.h\"\n#include \"Support\/Signals.h\"\n#include \n#include \n\nusing namespace llvm;\n\nnamespace {\n cl::opt\n InputFilename(cl::Positional,cl::desc(\"\"),cl::init(\"-\"));\n\n cl::opt \n OutputFilename(\"o\", cl::desc(\"Override output filename\"),\n cl::value_desc(\"filename\"));\n\n cl::opt \n Verify(\"verify\", cl::desc(\"Verify each pass result\"));\n\n cl::opt\n DisableInline(\"disable-inlining\", cl::desc(\"Do not run the inliner pass\"));\n}\n\n\nstatic inline void addPass(PassManager &PM, Pass *P) {\n \/\/ Add the pass to the pass manager...\n PM.add(P);\n \n \/\/ If we are verifying all of the intermediate steps, add the verifier...\n if (Verify) PM.add(createVerifierPass());\n}\n\n\nvoid AddConfiguredTransformationPasses(PassManager &PM) {\n PM.add(createVerifierPass()); \/\/ Verify that input is correct\n addPass(PM, createLowerSetJmpPass()); \/\/ Lower llvm.setjmp\/.longjmp\n addPass(PM, createFunctionResolvingPass()); \/\/ Resolve (...) functions\n addPass(PM, createCFGSimplificationPass()); \/\/ Clean up disgusting code\n addPass(PM, createRaiseAllocationsPass()); \/\/ call %malloc -> malloc inst\n addPass(PM, createGlobalDCEPass()); \/\/ Remove unused globals\n addPass(PM, createIPConstantPropagationPass());\/\/ IP Constant Propagation\n addPass(PM, createDeadArgEliminationPass()); \/\/ Dead argument elimination\n\n addPass(PM, createPruneEHPass()); \/\/ Remove dead EH info\n\n if (!DisableInline)\n addPass(PM, createFunctionInliningPass()); \/\/ Inline small functions\n\n addPass(PM, createInstructionCombiningPass()); \/\/ Cleanup code for raise\n addPass(PM, createRaisePointerReferencesPass());\/\/ Recover type information\n addPass(PM, createTailDuplicationPass()); \/\/ Simplify cfg by copying code\n addPass(PM, createCFGSimplificationPass()); \/\/ Merge & remove BBs\n addPass(PM, createScalarReplAggregatesPass()); \/\/ Break up aggregate allocas\n addPass(PM, createTailCallEliminationPass()); \/\/ Eliminate tail calls\n addPass(PM, createInstructionCombiningPass()); \/\/ Combine silly seq's\n\n addPass(PM, createReassociatePass()); \/\/ Reassociate expressions\n addPass(PM, createInstructionCombiningPass()); \/\/ Combine silly seq's\n addPass(PM, createCFGSimplificationPass()); \/\/ Merge & remove BBs\n addPass(PM, createLICMPass()); \/\/ Hoist loop invariants\n addPass(PM, createLoadValueNumberingPass()); \/\/ GVN for load instructions\n addPass(PM, createGCSEPass()); \/\/ Remove common subexprs\n addPass(PM, createSCCPPass()); \/\/ Constant prop with SCCP\n\n \/\/ Run instcombine after redundancy elimination to exploit opportunities\n \/\/ opened up by them.\n addPass(PM, createInstructionCombiningPass());\n addPass(PM, createIndVarSimplifyPass()); \/\/ Canonicalize indvars\n addPass(PM, createAggressiveDCEPass()); \/\/ SSA based 'Aggressive DCE'\n addPass(PM, createCFGSimplificationPass()); \/\/ Merge & remove BBs\n addPass(PM, createDeadTypeEliminationPass()); \/\/ Eliminate dead types\n addPass(PM, createConstantMergePass()); \/\/ Merge dup global constants\n}\n\n\nint main(int argc, char **argv) {\n cl::ParseCommandLineOptions(argc, argv, \" llvm .s -> .o assembler for GCC\\n\");\n\n std::auto_ptr M;\n try {\n \/\/ Parse the file now...\n M.reset(ParseAssemblyFile(InputFilename));\n } catch (const ParseException &E) {\n std::cerr << argv[0] << \": \" << E.getMessage() << \"\\n\";\n return 1;\n }\n\n if (M.get() == 0) {\n std::cerr << argv[0] << \": assembly didn't read correctly.\\n\";\n return 1;\n }\n\n std::ostream *Out = 0;\n if (OutputFilename == \"\") { \/\/ Didn't specify an output filename?\n if (InputFilename == \"-\") {\n OutputFilename = \"-\";\n } else {\n std::string IFN = InputFilename;\n int Len = IFN.length();\n if (IFN[Len-2] == '.' && IFN[Len-1] == 's') { \/\/ Source ends in .s?\n OutputFilename = std::string(IFN.begin(), IFN.end()-2);\n } else {\n OutputFilename = IFN; \/\/ Append a .o to it\n }\n OutputFilename += \".o\";\n }\n }\n\n if (OutputFilename == \"-\")\n Out = &std::cout;\n else {\n Out = new std::ofstream(OutputFilename.c_str(), std::ios::out);\n\n \/\/ Make sure that the Out file gets unlinked from the disk if we get a\n \/\/ signal\n RemoveFileOnSignal(OutputFilename);\n }\n\n \n if (!Out->good()) {\n std::cerr << argv[0] << \": error opening \" << OutputFilename << \"!\\n\";\n return 1;\n }\n\n \/\/ In addition to just parsing the input from GCC, we also want to spiff it up\n \/\/ a little bit. Do this now.\n \/\/\n PassManager Passes;\n\n \/\/ Add an appropriate TargetData instance for this module...\n Passes.add(new TargetData(\"gccas\", M.get()));\n\n \/\/ Add all of the transformation passes to the pass manager to do the cleanup\n \/\/ and optimization of the GCC output.\n \/\/\n AddConfiguredTransformationPasses(Passes);\n\n \/\/ Write bytecode to file...\n Passes.add(new WriteBytecodePass(Out));\n\n \/\/ Run our queue of passes all at once now, efficiently.\n Passes.run(*M.get());\n\n if (Out != &std::cout) delete Out;\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/===----------------------------------------------------------------------===\/\/\n\/\/ LLVM 'GCCAS' UTILITY \n\/\/\n\/\/ This utility is designed to be used by the GCC frontend for creating\n\/\/ bytecode files from it's intermediate llvm assembly. The requirements for\n\/\/ this utility are thus slightly different than that of the standard as util.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Assembly\/Parser.h\"\n#include \"llvm\/Transforms\/RaisePointerReferences.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Analysis\/LoadValueNumbering.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/Bytecode\/WriteBytecodePass.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"Support\/CommandLine.h\"\n#include \"Support\/Signals.h\"\n#include \n#include \nusing std::cerr;\n\n\/\/ FIXME: This should eventually be parameterized...\nstatic TargetData TD(\"opt target\");\n\nstatic cl::opt\nInputFilename(cl::Positional, cl::desc(\"\"), cl::Required);\n\nstatic cl::opt \nOutputFilename(\"o\", cl::desc(\"Override output filename\"),\n cl::value_desc(\"filename\"));\n\nstatic cl::opt\nRunNPasses(\"stopAfterNPasses\",\n cl::desc(\"Only run the first N passes of gccas\"), cl::Hidden,\n cl::value_desc(\"# passes\"));\n\nstatic cl::opt \nVerify(\"verify\", cl::desc(\"Verify each pass result\"));\n\n\nstatic inline void addPass(PassManager &PM, Pass *P) {\n static int NumPassesCreated = 0;\n \n \/\/ If we haven't already created the number of passes that was requested...\n if (RunNPasses == 0 || RunNPasses > NumPassesCreated) {\n \/\/ Add the pass to the pass manager...\n PM.add(P);\n\n \/\/ If we are verifying all of the intermediate steps, add the verifier...\n if (Verify) PM.add(createVerifierPass());\n\n \/\/ Keep track of how many passes we made for -stopAfterNPasses\n ++NumPassesCreated;\n } else {\n delete P; \/\/ We don't want this pass to run, just delete it now\n }\n}\n\n\nvoid AddConfiguredTransformationPasses(PassManager &PM) {\n if (Verify) PM.add(createVerifierPass());\n\n addPass(PM, createFunctionResolvingPass()); \/\/ Resolve (...) functions\n addPass(PM, createGlobalDCEPass()); \/\/ Kill unused uinit g-vars\n addPass(PM, createDeadTypeEliminationPass()); \/\/ Eliminate dead types\n addPass(PM, createConstantMergePass()); \/\/ Merge dup global constants\n addPass(PM, createVerifierPass()); \/\/ Verify that input is correct\n addPass(PM, createDeadInstEliminationPass()); \/\/ Remove Dead code\/vars\n addPass(PM, createRaiseAllocationsPass()); \/\/ call %malloc -> malloc inst\n addPass(PM, createIndVarSimplifyPass()); \/\/ Simplify indvars\n addPass(PM, createRaisePointerReferencesPass(TD));\/\/ Recover type information\n addPass(PM, createInstructionCombiningPass()); \/\/ Combine silly seq's\n addPass(PM, createPromoteMemoryToRegister()); \/\/ Promote alloca's to regs\n addPass(PM, createReassociatePass()); \/\/ Reassociate expressions\n \/\/addPass(PM, createCorrelatedExpressionEliminationPass());\/\/ Kill corr branches\n addPass(PM, createInstructionCombiningPass()); \/\/ Combine silly seq's\n addPass(PM, createCFGSimplificationPass()); \/\/ Merge & remove BBs\n addPass(PM, createLICMPass()); \/\/ Hoist loop invariants\n addPass(PM, createLoadValueNumberingPass()); \/\/ GVN for load instructions\n addPass(PM, createGCSEPass()); \/\/ Remove common subexprs\n addPass(PM, createSCCPPass()); \/\/ Constant prop with SCCP\n\n \/\/ Run instcombine after redundancy elimination to exploit opportunities\n \/\/ opened up by them.\n addPass(PM, createInstructionCombiningPass());\n addPass(PM, createAggressiveDCEPass()); \/\/ SSA based 'Agressive DCE'\n addPass(PM, createCFGSimplificationPass()); \/\/ Merge & remove BBs\n}\n\n\nint main(int argc, char **argv) {\n cl::ParseCommandLineOptions(argc, argv, \" llvm .s -> .o assembler for GCC\\n\");\n\n std::auto_ptr M;\n try {\n \/\/ Parse the file now...\n M.reset(ParseAssemblyFile(InputFilename));\n } catch (const ParseException &E) {\n cerr << argv[0] << \": \" << E.getMessage() << \"\\n\";\n return 1;\n }\n\n if (M.get() == 0) {\n cerr << argv[0] << \": assembly didn't read correctly.\\n\";\n return 1;\n }\n \n if (OutputFilename == \"\") { \/\/ Didn't specify an output filename?\n std::string IFN = InputFilename;\n int Len = IFN.length();\n if (IFN[Len-2] == '.' && IFN[Len-1] == 's') { \/\/ Source ends in .s?\n OutputFilename = std::string(IFN.begin(), IFN.end()-2);\n } else {\n OutputFilename = IFN; \/\/ Append a .o to it\n }\n OutputFilename += \".o\";\n }\n\n std::ofstream Out(OutputFilename.c_str(), std::ios::out);\n if (!Out.good()) {\n cerr << argv[0] << \": error opening \" << OutputFilename << \"!\\n\";\n return 1;\n }\n\n \/\/ Make sure that the Out file gets unlink'd from the disk if we get a SIGINT\n RemoveFileOnSignal(OutputFilename);\n\n \/\/ In addition to just parsing the input from GCC, we also want to spiff it up\n \/\/ a little bit. Do this now.\n \/\/\n PassManager Passes;\n\n \/\/ Add all of the transformation passes to the pass manager to do the cleanup\n \/\/ and optimization of the GCC output.\n \/\/\n AddConfiguredTransformationPasses(Passes);\n\n \/\/ Write bytecode to file...\n Passes.add(new WriteBytecodePass(&Out));\n\n \/\/ Run our queue of passes all at once now, efficiently.\n Passes.run(*M.get());\n return 0;\n}\nNamespacify command line options\/\/===----------------------------------------------------------------------===\/\/\n\/\/ LLVM 'GCCAS' UTILITY \n\/\/\n\/\/ This utility is designed to be used by the GCC frontend for creating\n\/\/ bytecode files from it's intermediate llvm assembly. The requirements for\n\/\/ this utility are thus slightly different than that of the standard as util.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Assembly\/Parser.h\"\n#include \"llvm\/Transforms\/RaisePointerReferences.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Analysis\/LoadValueNumbering.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/Bytecode\/WriteBytecodePass.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"Support\/CommandLine.h\"\n#include \"Support\/Signals.h\"\n#include \n#include \nusing std::cerr;\n\nnamespace {\n \/\/ FIXME: This should eventually be parameterized...\n TargetData TD(\"gccas target\");\n\n cl::opt\n InputFilename(cl::Positional, cl::desc(\"\"),cl::Required);\n\n cl::opt \n OutputFilename(\"o\", cl::desc(\"Override output filename\"),\n cl::value_desc(\"filename\"));\n\n cl::opt\n RunNPasses(\"stopAfterNPasses\",\n cl::desc(\"Only run the first N passes of gccas\"), cl::Hidden,\n cl::value_desc(\"# passes\"));\n\n cl::opt \n Verify(\"verify\", cl::desc(\"Verify each pass result\"));\n\n}\n\n\nstatic inline void addPass(PassManager &PM, Pass *P) {\n static int NumPassesCreated = 0;\n \n \/\/ If we haven't already created the number of passes that was requested...\n if (RunNPasses == 0 || RunNPasses > NumPassesCreated) {\n \/\/ Add the pass to the pass manager...\n PM.add(P);\n\n \/\/ If we are verifying all of the intermediate steps, add the verifier...\n if (Verify) PM.add(createVerifierPass());\n\n \/\/ Keep track of how many passes we made for -stopAfterNPasses\n ++NumPassesCreated;\n } else {\n delete P; \/\/ We don't want this pass to run, just delete it now\n }\n}\n\n\nvoid AddConfiguredTransformationPasses(PassManager &PM) {\n if (Verify) PM.add(createVerifierPass());\n\n addPass(PM, createFunctionResolvingPass()); \/\/ Resolve (...) functions\n addPass(PM, createGlobalDCEPass()); \/\/ Kill unused uinit g-vars\n addPass(PM, createDeadTypeEliminationPass()); \/\/ Eliminate dead types\n addPass(PM, createConstantMergePass()); \/\/ Merge dup global constants\n addPass(PM, createVerifierPass()); \/\/ Verify that input is correct\n addPass(PM, createDeadInstEliminationPass()); \/\/ Remove Dead code\/vars\n addPass(PM, createRaiseAllocationsPass()); \/\/ call %malloc -> malloc inst\n addPass(PM, createIndVarSimplifyPass()); \/\/ Simplify indvars\n addPass(PM, createRaisePointerReferencesPass(TD));\/\/ Recover type information\n addPass(PM, createInstructionCombiningPass()); \/\/ Combine silly seq's\n addPass(PM, createPromoteMemoryToRegister()); \/\/ Promote alloca's to regs\n addPass(PM, createReassociatePass()); \/\/ Reassociate expressions\n \/\/addPass(PM, createCorrelatedExpressionEliminationPass());\/\/ Kill corr branches\n addPass(PM, createInstructionCombiningPass()); \/\/ Combine silly seq's\n addPass(PM, createCFGSimplificationPass()); \/\/ Merge & remove BBs\n addPass(PM, createLICMPass()); \/\/ Hoist loop invariants\n addPass(PM, createLoadValueNumberingPass()); \/\/ GVN for load instructions\n addPass(PM, createGCSEPass()); \/\/ Remove common subexprs\n addPass(PM, createSCCPPass()); \/\/ Constant prop with SCCP\n\n \/\/ Run instcombine after redundancy elimination to exploit opportunities\n \/\/ opened up by them.\n addPass(PM, createInstructionCombiningPass());\n addPass(PM, createAggressiveDCEPass()); \/\/ SSA based 'Agressive DCE'\n addPass(PM, createCFGSimplificationPass()); \/\/ Merge & remove BBs\n}\n\n\nint main(int argc, char **argv) {\n cl::ParseCommandLineOptions(argc, argv, \" llvm .s -> .o assembler for GCC\\n\");\n\n std::auto_ptr M;\n try {\n \/\/ Parse the file now...\n M.reset(ParseAssemblyFile(InputFilename));\n } catch (const ParseException &E) {\n cerr << argv[0] << \": \" << E.getMessage() << \"\\n\";\n return 1;\n }\n\n if (M.get() == 0) {\n cerr << argv[0] << \": assembly didn't read correctly.\\n\";\n return 1;\n }\n \n if (OutputFilename == \"\") { \/\/ Didn't specify an output filename?\n std::string IFN = InputFilename;\n int Len = IFN.length();\n if (IFN[Len-2] == '.' && IFN[Len-1] == 's') { \/\/ Source ends in .s?\n OutputFilename = std::string(IFN.begin(), IFN.end()-2);\n } else {\n OutputFilename = IFN; \/\/ Append a .o to it\n }\n OutputFilename += \".o\";\n }\n\n std::ofstream Out(OutputFilename.c_str(), std::ios::out);\n if (!Out.good()) {\n cerr << argv[0] << \": error opening \" << OutputFilename << \"!\\n\";\n return 1;\n }\n\n \/\/ Make sure that the Out file gets unlink'd from the disk if we get a SIGINT\n RemoveFileOnSignal(OutputFilename);\n\n \/\/ In addition to just parsing the input from GCC, we also want to spiff it up\n \/\/ a little bit. Do this now.\n \/\/\n PassManager Passes;\n\n \/\/ Add all of the transformation passes to the pass manager to do the cleanup\n \/\/ and optimization of the GCC output.\n \/\/\n AddConfiguredTransformationPasses(Passes);\n\n \/\/ Write bytecode to file...\n Passes.add(new WriteBytecodePass(&Out));\n\n \/\/ Run our queue of passes all at once now, efficiently.\n Passes.run(*M.get());\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/===- gccld.cpp - LLVM 'ld' compatible linker ----------------------------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This utility is intended to be compatible with GCC, and follows standard\n\/\/ system 'ld' conventions. As such, the default output file is .\/a.out.\n\/\/ Additionally, this program outputs a shell script that is used to invoke LLI\n\/\/ to execute the program. In this manner, the generated executable (a.out for\n\/\/ example), is directly executable, whereas the bytecode file actually lives in\n\/\/ the a.out.bc file generated by this program. Also, Force is on by default.\n\/\/\n\/\/ Note that if someone (or a script) deletes the executable program generated,\n\/\/ the .bc file will be left around. Considering that this is a temporary hack,\n\/\/ I'm not too worried about this.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"gccld.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Bytecode\/Reader.h\"\n#include \"llvm\/Bytecode\/WriteBytecodePass.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Transforms\/Utils\/Linker.h\"\n#include \"Support\/CommandLine.h\"\n#include \"Support\/FileUtilities.h\"\n#include \"Support\/Signals.h\"\n#include \"Support\/SystemUtils.h\"\n#include \n#include \n\nnamespace {\n cl::list \n InputFilenames(cl::Positional, cl::desc(\"\"),\n cl::OneOrMore);\n\n cl::opt \n OutputFilename(\"o\", cl::desc(\"Override output filename\"), cl::init(\"a.out\"),\n cl::value_desc(\"filename\"));\n\n cl::opt \n Verbose(\"v\", cl::desc(\"Print information about actions taken\"));\n \n cl::list \n LibPaths(\"L\", cl::desc(\"Specify a library search path\"), cl::Prefix,\n cl::value_desc(\"directory\"));\n\n cl::list \n Libraries(\"l\", cl::desc(\"Specify libraries to link to\"), cl::Prefix,\n cl::value_desc(\"library prefix\"));\n\n cl::opt\n Strip(\"s\", cl::desc(\"Strip symbol info from executable\"));\n\n cl::opt\n NoInternalize(\"disable-internalize\",\n cl::desc(\"Do not mark all symbols as internal\"));\n static cl::alias\n ExportDynamic(\"export-dynamic\", cl::desc(\"Alias for -disable-internalize\"),\n cl::aliasopt(NoInternalize));\n\n cl::opt\n LinkAsLibrary(\"link-as-library\", cl::desc(\"Link the .bc files together as a\"\n \" library, not an executable\"));\n\n cl::opt \n Native(\"native\",\n cl::desc(\"Generate a native binary instead of a shell script\"));\n \n \/\/ Compatibility options that are ignored but supported by LD\n cl::opt\n CO3(\"soname\", cl::Hidden, cl::desc(\"Compatibility option: ignored\"));\n cl::opt\n CO4(\"version-script\", cl::Hidden, cl::desc(\"Compatibility option: ignored\"));\n cl::opt\n CO5(\"eh-frame-hdr\", cl::Hidden, cl::desc(\"Compatibility option: ignored\"));\n cl::opt\n CO6(\"r\", cl::Hidden, cl::desc(\"Compatibility option: ignored\"));\n}\n\n\/\/\n\/\/ Function: PrintAndReturn ()\n\/\/\n\/\/ Description:\n\/\/ Prints a message (usually error message) to standard error (stderr) and\n\/\/ returns a value usable for an exit status.\n\/\/\n\/\/ Inputs:\n\/\/ progname - The name of the program (i.e. argv[0]).\n\/\/ Message - The message to print to standard error.\n\/\/ Extra - Extra information to print between the program name and thei\n\/\/ message. It is optional.\n\/\/\n\/\/ Outputs:\n\/\/ None.\n\/\/\n\/\/ Return value:\n\/\/ Returns a value that can be used as the exit status (i.e. for exit()).\n\/\/\nint\nPrintAndReturn (const char *progname,\n const std::string &Message,\n const std::string &Extra)\n{\n std::cerr << progname << Extra << \": \" << Message << \"\\n\";\n return 1;\n}\n\n\/\/\n\/\/\n\/\/ Function: CopyEnv()\n\/\/\n\/\/ Description:\n\/\/\tThis function takes an array of environment variables and makes a\n\/\/\tcopy of it. This copy can then be manipulated any way the caller likes\n\/\/ without affecting the process's real environment.\n\/\/\n\/\/ Inputs:\n\/\/ envp - An array of C strings containing an environment.\n\/\/\n\/\/ Outputs:\n\/\/ None.\n\/\/\n\/\/ Return value:\n\/\/ NULL - An error occurred.\n\/\/\n\/\/ Otherwise, a pointer to a new array of C strings is returned. Every string\n\/\/ in the array is a duplicate of the one in the original array (i.e. we do\n\/\/ not copy the char *'s from one array to another).\n\/\/\nchar ** CopyEnv(char ** const envp) {\n \/\/ Count the number of entries in the old list;\n unsigned entries; \/\/ The number of entries in the old environment list\n for (entries = 0; envp[entries] != NULL; entries++)\n {\n ;\n }\n\n \/\/ Add one more entry for the NULL pointer that ends the list.\n ++entries;\n\n \/\/ If there are no entries at all, just return NULL.\n if (entries == 0)\n return NULL;\n\n \/\/ Allocate a new environment list.\n char **newenv;\n if ((newenv = new (char *) [entries]) == NULL)\n return NULL;\n\n \/\/ Make a copy of the list. Don't forget the NULL that ends the list.\n entries = 0;\n while (envp[entries] != NULL) {\n newenv[entries] = new char[strlen (envp[entries]) + 1];\n strcpy (newenv[entries], envp[entries]);\n ++entries;\n }\n newenv[entries] = NULL;\n\n return newenv;\n}\n\n\n\/\/\n\/\/ Function: RemoveEnv()\n\/\/\n\/\/ Description:\n\/\/\tRemove the specified environment variable from the environment array.\n\/\/\n\/\/ Inputs:\n\/\/\tname - The name of the variable to remove. It cannot be NULL.\n\/\/\tenvp - The array of environment variables. It cannot be NULL.\n\/\/\n\/\/ Outputs:\n\/\/\tenvp - The pointer to the specified variable name is removed.\n\/\/\n\/\/ Return value:\n\/\/\tNone.\n\/\/\n\/\/ Notes:\n\/\/ This is mainly done because functions to remove items from the environment\n\/\/ are not available across all platforms. In particular, Solaris does not\n\/\/ seem to have an unsetenv() function or a setenv() function (or they are\n\/\/ undocumented if they do exist).\n\/\/\nvoid RemoveEnv(const char * name, char ** const envp) {\n for (unsigned index=0; envp[index] != NULL; index++) {\n \/\/ Find the first equals sign in the array and make it an EOS character.\n char *p = strchr (envp[index], '=');\n if (p == NULL)\n continue;\n else\n *p = '\\0';\n\n \/\/ Compare the two strings. If they are equal, zap this string.\n \/\/ Otherwise, restore it.\n if (!strcmp(name, envp[index]))\n *envp[index] = '\\0';\n else\n *p = '=';\n }\n\n return;\n}\n\n\nint main(int argc, char **argv, char **envp) {\n cl::ParseCommandLineOptions(argc, argv, \" llvm linker for GCC\\n\");\n\n std::string ErrorMessage;\n std::auto_ptr Composite(LoadObject(InputFilenames[0], ErrorMessage));\n if (Composite.get() == 0)\n return PrintAndReturn(argv[0], ErrorMessage);\n\n \/\/ We always look first in the current directory when searching for libraries.\n LibPaths.insert(LibPaths.begin(), \".\");\n\n \/\/ If the user specified an extra search path in their environment, respect\n \/\/ it.\n if (char *SearchPath = getenv(\"LLVM_LIB_SEARCH_PATH\"))\n LibPaths.push_back(SearchPath);\n\n \/\/ Remove any consecutive duplicates of the same library...\n Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),\n Libraries.end());\n\n \/\/ Link in all of the files\n if (LinkFiles(argv[0], Composite.get(), InputFilenames, Verbose))\n return 1; \/\/ Error already printed\n\n if (!LinkAsLibrary)\n LinkLibraries(argv[0], Composite.get(), Libraries, LibPaths,\n Verbose, Native);\n\n \/\/ Link in all of the libraries next...\n\n \/\/ Create the output file.\n std::string RealBytecodeOutput = OutputFilename;\n if (!LinkAsLibrary) RealBytecodeOutput += \".bc\";\n std::ofstream Out(RealBytecodeOutput.c_str());\n if (!Out.good())\n return PrintAndReturn(argv[0], \"error opening '\" + RealBytecodeOutput +\n \"' for writing!\");\n\n \/\/ Ensure that the bytecode file gets removed from the disk if we get a\n \/\/ SIGINT signal.\n RemoveFileOnSignal(RealBytecodeOutput);\n\n \/\/ Generate the bytecode file.\n if (GenerateBytecode(Composite.get(), Strip, !NoInternalize, &Out)) {\n Out.close();\n return PrintAndReturn(argv[0], \"error generating bytcode\");\n }\n\n \/\/ Close the bytecode file.\n Out.close();\n\n \/\/ If we are not linking a library, generate either a native executable\n \/\/ or a JIT shell script, depending upon what the user wants.\n if (!LinkAsLibrary) {\n \/\/ If the user wants to generate a native executable, compile it from the\n \/\/ bytecode file.\n \/\/\n \/\/ Otherwise, create a script that will run the bytecode through the JIT.\n if (Native) {\n \/\/ Name of the Assembly Language output file\n std::string AssemblyFile = OutputFilename + \".s\";\n\n \/\/ Mark the output files for removal if we get an interrupt.\n RemoveFileOnSignal(AssemblyFile);\n RemoveFileOnSignal(OutputFilename);\n\n \/\/ Determine the locations of the llc and gcc programs.\n std::string llc = FindExecutable(\"llc\", argv[0]);\n std::string gcc = FindExecutable(\"gcc\", argv[0]);\n if (llc.empty())\n return PrintAndReturn(argv[0], \"Failed to find llc\");\n\n if (gcc.empty())\n return PrintAndReturn(argv[0], \"Failed to find gcc\");\n\n \/\/ Generate an assembly language file for the bytecode.\n if (Verbose) std::cout << \"Generating Assembly Code\\n\";\n GenerateAssembly(AssemblyFile, RealBytecodeOutput, llc, envp);\n if (Verbose) std::cout << \"Generating Native Code\\n\";\n GenerateNative(OutputFilename, AssemblyFile, Libraries, LibPaths,\n gcc, envp);\n\n \/\/ Remove the assembly language file.\n removeFile (AssemblyFile);\n } else {\n \/\/ Output the script to start the program...\n std::ofstream Out2(OutputFilename.c_str());\n if (!Out2.good())\n return PrintAndReturn(argv[0], \"error opening '\" + OutputFilename +\n \"' for writing!\");\n Out2 << \"#!\/bin\/sh\\nlli $0.bc $*\\n\";\n Out2.close();\n }\n \n \/\/ Make the script executable...\n MakeFileExecutable(OutputFilename);\n\n \/\/ Make the bytecode file readable and directly executable in LLEE as well\n MakeFileExecutable(RealBytecodeOutput);\n MakeFileReadable(RealBytecodeOutput);\n }\n\n return 0;\n}\nMake -r work, fixing PR 91\/\/===- gccld.cpp - LLVM 'ld' compatible linker ----------------------------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This utility is intended to be compatible with GCC, and follows standard\n\/\/ system 'ld' conventions. As such, the default output file is .\/a.out.\n\/\/ Additionally, this program outputs a shell script that is used to invoke LLI\n\/\/ to execute the program. In this manner, the generated executable (a.out for\n\/\/ example), is directly executable, whereas the bytecode file actually lives in\n\/\/ the a.out.bc file generated by this program. Also, Force is on by default.\n\/\/\n\/\/ Note that if someone (or a script) deletes the executable program generated,\n\/\/ the .bc file will be left around. Considering that this is a temporary hack,\n\/\/ I'm not too worried about this.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"gccld.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Bytecode\/Reader.h\"\n#include \"llvm\/Bytecode\/WriteBytecodePass.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Transforms\/Utils\/Linker.h\"\n#include \"Support\/CommandLine.h\"\n#include \"Support\/FileUtilities.h\"\n#include \"Support\/Signals.h\"\n#include \"Support\/SystemUtils.h\"\n#include \n#include \n\nnamespace {\n cl::list \n InputFilenames(cl::Positional, cl::desc(\"\"),\n cl::OneOrMore);\n\n cl::opt \n OutputFilename(\"o\", cl::desc(\"Override output filename\"), cl::init(\"a.out\"),\n cl::value_desc(\"filename\"));\n\n cl::opt \n Verbose(\"v\", cl::desc(\"Print information about actions taken\"));\n \n cl::list \n LibPaths(\"L\", cl::desc(\"Specify a library search path\"), cl::Prefix,\n cl::value_desc(\"directory\"));\n\n cl::list \n Libraries(\"l\", cl::desc(\"Specify libraries to link to\"), cl::Prefix,\n cl::value_desc(\"library prefix\"));\n\n cl::opt\n Strip(\"s\", cl::desc(\"Strip symbol info from executable\"));\n\n cl::opt\n NoInternalize(\"disable-internalize\",\n cl::desc(\"Do not mark all symbols as internal\"));\n cl::alias\n ExportDynamic(\"export-dynamic\", cl::desc(\"Alias for -disable-internalize\"),\n cl::aliasopt(NoInternalize));\n\n cl::opt\n LinkAsLibrary(\"link-as-library\", cl::desc(\"Link the .bc files together as a\"\n \" library, not an executable\"));\n cl::alias\n Relink(\"r\", cl::desc(\"Alias for -link-as-library\"),\n cl::aliasopt(LinkAsLibrary));\n\n cl::opt \n Native(\"native\",\n cl::desc(\"Generate a native binary instead of a shell script\"));\n \n \/\/ Compatibility options that are ignored but supported by LD\n cl::opt\n CO3(\"soname\", cl::Hidden, cl::desc(\"Compatibility option: ignored\"));\n cl::opt\n CO4(\"version-script\", cl::Hidden, cl::desc(\"Compatibility option: ignored\"));\n cl::opt\n CO5(\"eh-frame-hdr\", cl::Hidden, cl::desc(\"Compatibility option: ignored\"));\n}\n\n\/\/\n\/\/ Function: PrintAndReturn ()\n\/\/\n\/\/ Description:\n\/\/ Prints a message (usually error message) to standard error (stderr) and\n\/\/ returns a value usable for an exit status.\n\/\/\n\/\/ Inputs:\n\/\/ progname - The name of the program (i.e. argv[0]).\n\/\/ Message - The message to print to standard error.\n\/\/ Extra - Extra information to print between the program name and thei\n\/\/ message. It is optional.\n\/\/\n\/\/ Outputs:\n\/\/ None.\n\/\/\n\/\/ Return value:\n\/\/ Returns a value that can be used as the exit status (i.e. for exit()).\n\/\/\nint\nPrintAndReturn (const char *progname,\n const std::string &Message,\n const std::string &Extra)\n{\n std::cerr << progname << Extra << \": \" << Message << \"\\n\";\n return 1;\n}\n\n\/\/\n\/\/\n\/\/ Function: CopyEnv()\n\/\/\n\/\/ Description:\n\/\/\tThis function takes an array of environment variables and makes a\n\/\/\tcopy of it. This copy can then be manipulated any way the caller likes\n\/\/ without affecting the process's real environment.\n\/\/\n\/\/ Inputs:\n\/\/ envp - An array of C strings containing an environment.\n\/\/\n\/\/ Outputs:\n\/\/ None.\n\/\/\n\/\/ Return value:\n\/\/ NULL - An error occurred.\n\/\/\n\/\/ Otherwise, a pointer to a new array of C strings is returned. Every string\n\/\/ in the array is a duplicate of the one in the original array (i.e. we do\n\/\/ not copy the char *'s from one array to another).\n\/\/\nchar ** CopyEnv(char ** const envp) {\n \/\/ Count the number of entries in the old list;\n unsigned entries; \/\/ The number of entries in the old environment list\n for (entries = 0; envp[entries] != NULL; entries++)\n {\n ;\n }\n\n \/\/ Add one more entry for the NULL pointer that ends the list.\n ++entries;\n\n \/\/ If there are no entries at all, just return NULL.\n if (entries == 0)\n return NULL;\n\n \/\/ Allocate a new environment list.\n char **newenv;\n if ((newenv = new (char *) [entries]) == NULL)\n return NULL;\n\n \/\/ Make a copy of the list. Don't forget the NULL that ends the list.\n entries = 0;\n while (envp[entries] != NULL) {\n newenv[entries] = new char[strlen (envp[entries]) + 1];\n strcpy (newenv[entries], envp[entries]);\n ++entries;\n }\n newenv[entries] = NULL;\n\n return newenv;\n}\n\n\n\/\/\n\/\/ Function: RemoveEnv()\n\/\/\n\/\/ Description:\n\/\/\tRemove the specified environment variable from the environment array.\n\/\/\n\/\/ Inputs:\n\/\/\tname - The name of the variable to remove. It cannot be NULL.\n\/\/\tenvp - The array of environment variables. It cannot be NULL.\n\/\/\n\/\/ Outputs:\n\/\/\tenvp - The pointer to the specified variable name is removed.\n\/\/\n\/\/ Return value:\n\/\/\tNone.\n\/\/\n\/\/ Notes:\n\/\/ This is mainly done because functions to remove items from the environment\n\/\/ are not available across all platforms. In particular, Solaris does not\n\/\/ seem to have an unsetenv() function or a setenv() function (or they are\n\/\/ undocumented if they do exist).\n\/\/\nvoid RemoveEnv(const char * name, char ** const envp) {\n for (unsigned index=0; envp[index] != NULL; index++) {\n \/\/ Find the first equals sign in the array and make it an EOS character.\n char *p = strchr (envp[index], '=');\n if (p == NULL)\n continue;\n else\n *p = '\\0';\n\n \/\/ Compare the two strings. If they are equal, zap this string.\n \/\/ Otherwise, restore it.\n if (!strcmp(name, envp[index]))\n *envp[index] = '\\0';\n else\n *p = '=';\n }\n\n return;\n}\n\n\nint main(int argc, char **argv, char **envp) {\n cl::ParseCommandLineOptions(argc, argv, \" llvm linker for GCC\\n\");\n\n std::string ErrorMessage;\n std::auto_ptr Composite(LoadObject(InputFilenames[0], ErrorMessage));\n if (Composite.get() == 0)\n return PrintAndReturn(argv[0], ErrorMessage);\n\n \/\/ We always look first in the current directory when searching for libraries.\n LibPaths.insert(LibPaths.begin(), \".\");\n\n \/\/ If the user specified an extra search path in their environment, respect\n \/\/ it.\n if (char *SearchPath = getenv(\"LLVM_LIB_SEARCH_PATH\"))\n LibPaths.push_back(SearchPath);\n\n \/\/ Remove any consecutive duplicates of the same library...\n Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),\n Libraries.end());\n\n \/\/ Link in all of the files\n if (LinkFiles(argv[0], Composite.get(), InputFilenames, Verbose))\n return 1; \/\/ Error already printed\n\n if (!LinkAsLibrary)\n LinkLibraries(argv[0], Composite.get(), Libraries, LibPaths,\n Verbose, Native);\n\n \/\/ Link in all of the libraries next...\n\n \/\/ Create the output file.\n std::string RealBytecodeOutput = OutputFilename;\n if (!LinkAsLibrary) RealBytecodeOutput += \".bc\";\n std::ofstream Out(RealBytecodeOutput.c_str());\n if (!Out.good())\n return PrintAndReturn(argv[0], \"error opening '\" + RealBytecodeOutput +\n \"' for writing!\");\n\n \/\/ Ensure that the bytecode file gets removed from the disk if we get a\n \/\/ SIGINT signal.\n RemoveFileOnSignal(RealBytecodeOutput);\n\n \/\/ Generate the bytecode file.\n if (GenerateBytecode(Composite.get(), Strip, !NoInternalize, &Out)) {\n Out.close();\n return PrintAndReturn(argv[0], \"error generating bytcode\");\n }\n\n \/\/ Close the bytecode file.\n Out.close();\n\n \/\/ If we are not linking a library, generate either a native executable\n \/\/ or a JIT shell script, depending upon what the user wants.\n if (!LinkAsLibrary) {\n \/\/ If the user wants to generate a native executable, compile it from the\n \/\/ bytecode file.\n \/\/\n \/\/ Otherwise, create a script that will run the bytecode through the JIT.\n if (Native) {\n \/\/ Name of the Assembly Language output file\n std::string AssemblyFile = OutputFilename + \".s\";\n\n \/\/ Mark the output files for removal if we get an interrupt.\n RemoveFileOnSignal(AssemblyFile);\n RemoveFileOnSignal(OutputFilename);\n\n \/\/ Determine the locations of the llc and gcc programs.\n std::string llc = FindExecutable(\"llc\", argv[0]);\n std::string gcc = FindExecutable(\"gcc\", argv[0]);\n if (llc.empty())\n return PrintAndReturn(argv[0], \"Failed to find llc\");\n\n if (gcc.empty())\n return PrintAndReturn(argv[0], \"Failed to find gcc\");\n\n \/\/ Generate an assembly language file for the bytecode.\n if (Verbose) std::cout << \"Generating Assembly Code\\n\";\n GenerateAssembly(AssemblyFile, RealBytecodeOutput, llc, envp);\n if (Verbose) std::cout << \"Generating Native Code\\n\";\n GenerateNative(OutputFilename, AssemblyFile, Libraries, LibPaths,\n gcc, envp);\n\n \/\/ Remove the assembly language file.\n removeFile (AssemblyFile);\n } else {\n \/\/ Output the script to start the program...\n std::ofstream Out2(OutputFilename.c_str());\n if (!Out2.good())\n return PrintAndReturn(argv[0], \"error opening '\" + OutputFilename +\n \"' for writing!\");\n Out2 << \"#!\/bin\/sh\\nlli $0.bc $*\\n\";\n Out2.close();\n }\n \n \/\/ Make the script executable...\n MakeFileExecutable(OutputFilename);\n\n \/\/ Make the bytecode file readable and directly executable in LLEE as well\n MakeFileExecutable(RealBytecodeOutput);\n MakeFileReadable(RealBytecodeOutput);\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n#include \"condor_common.h\"\n#include \"matchmaker.h\"\n\n\/\/ for daemon core\nchar *mySubSystem = \"NEGOTIATOR\";\n\n\/\/ the matchmaker object\nMatchmaker matchMaker;\n\nint main_init (int, char *[])\n{\n\t\/\/ read in params\n\tmatchMaker.initialize ();\n\treturn TRUE;\n}\n\nint main_shutdown_graceful()\n{\n\tmatchMaker.invalidateNegotiatorAd();\n\tDC_Exit(0);\n\treturn 0;\n}\n\n\nint main_shutdown_fast()\n{\n\tDC_Exit(0);\n\treturn 0;\n}\n\nint\nmain_config( bool \/* is_full *\/ )\n{\n\treturn (matchMaker.reinitialize ());\n}\n\n\nvoid\nmain_pre_dc_init( int \/* argc *\/, char** \/* argv *\/ )\n{\n}\n\n\nvoid\nmain_pre_command_sock_init( )\n{\n}\n\nWindows doesn't think char** and char*[] are equivalent when declaring the type of the function's arguments.\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n#include \"condor_common.h\"\n#include \"matchmaker.h\"\n\n\/\/ for daemon core\nchar *mySubSystem = \"NEGOTIATOR\";\n\n\/\/ the matchmaker object\nMatchmaker matchMaker;\n\nint main_init (int, char *[])\n{\n\t\/\/ read in params\n\tmatchMaker.initialize ();\n\treturn TRUE;\n}\n\nint main_shutdown_graceful()\n{\n\tmatchMaker.invalidateNegotiatorAd();\n\tDC_Exit(0);\n\treturn 0;\n}\n\n\nint main_shutdown_fast()\n{\n\tDC_Exit(0);\n\treturn 0;\n}\n\nint\nmain_config( bool \/* is_full *\/ )\n{\n\treturn (matchMaker.reinitialize ());\n}\n\n\nvoid\nmain_pre_dc_init( int \/* argc *\/, char*[] \/* argv *\/ )\n{\n}\n\n\nvoid\nmain_pre_command_sock_init( )\n{\n}\n\n<|endoftext|>"} {"text":"#ifndef NANOCV_OPTIMIZE_OPTIMIZER_HPP\n#define NANOCV_OPTIMIZE_OPTIMIZER_HPP\n\n#include \"core\/optimize\/result.hpp\"\n#include \"core\/optimize\/problem.hpp\"\n#include \n#include \n\nnamespace ncv\n{\n namespace optimize\n {\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ optimization methods (GD, CGD, LBFGS) starting from the initial value (guess) x0.\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n template\n <\n typename tscalar,\n typename tsize,\n typename top_size, \/\/ dimensionality operator: size = op()\n typename top_fval, \/\/ function value operator: f = op(x)\n typename top_grad, \/\/ function value and gradient operator: f = op(x, g)\n typename top_wlog, \/\/ warning logging operator: op(\"message\")\n typename top_elog, \/\/ error logging operator: op(\"message\")\n typename top_ulog, \/\/ update (with current result\/solution) logging operator: op(result)\n\n \/\/ disable for not valid types!\n typename tvalid_tscalar = typename std::enable_if::value>::type,\n typename tvalid_tsize = typename std::enable_if::value>::type\n >\n class optimizer_t\n {\n public:\n\n typedef problem_t tproblem;\n typedef result_t tresult;\n typedef typename tresult::tstate tstate;\n typedef typename tresult::tvector tvector;\n\n \/\/ gradient descent starting from the initial value (guess) x0\n static tresult gd(\n const tproblem& problem,\n const tvector& x0,\n tsize max_iterations, \/\/ maximum number of iterations\n tscalar epsilon, \/\/ convergence precision\n const top_wlog& op_wlog = top_wlog(),\n const top_elog& op_elog = top_elog(),\n const top_ulog& op_ulog = top_ulog())\n {\n return _gd(problem, x0, max_iterations, epsilon, op_wlog, op_elog, op_ulog);\n }\n\n \/\/ conjugate gradient descent starting from the initial value (guess) x0\n static tresult cgd(\n const tproblem& problem,\n const tvector& x0,\n tsize max_iterations, \/\/ maximum number of iterations\n tscalar epsilon, \/\/ convergence precision\n const top_wlog& op_wlog = top_wlog(),\n const top_elog& op_elog = top_elog(),\n const top_ulog& op_ulog = top_ulog())\n {\n return _cgd(problem, x0, max_iterations, epsilon, op_wlog, op_elog, op_ulog);\n }\n\n \/\/ limited memory bfgs (l-bfgs) starting from the initial value (guess) x0\n static tresult lbfgs(\n const tproblem& problem,\n const tvector& x0,\n tsize max_iterations, \/\/ maximum number of iterations\n tscalar epsilon, \/\/ convergence precision\n tsize hist_size = 8, \/\/ hessian approximation history size\n const top_wlog& op_wlog = top_wlog(),\n const top_elog& op_elog = top_elog(),\n const top_ulog& op_ulog = top_ulog())\n {\n return _lbfgs(problem, x0, max_iterations, epsilon, hist_size, op_wlog, op_elog, op_ulog);\n }\n\n private:\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ check and force a descent direction\n static tscalar descent(tstate& st, const top_wlog& wlog)\n {\n tscalar dg = st.d.dot(st.g);\n if (dg > std::numeric_limits::min())\n {\n if (wlog)\n {\n wlog(\"not a descent direction!\");\n }\n st.d = -st.g;\n dg = st.d.dot(st.g);\n }\n\n return dg;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n private:\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ line-search methods to find the scalar that reduces\n \/\/ the function value (the most) along the direction d: argmin(t) f(x + t * d).\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ Armijo (sufficient decrease) condition\n static tscalar ls_armijo(const tproblem& problem, tstate& st, const top_wlog& wlog,\n tscalar alpha = 0.2, tscalar beta = 0.7, tsize max_iters = 64)\n {\n const tscalar dg = descent(st, wlog);\n\n tscalar t = 1;\n for (tsize i = 0; i < max_iters; i ++, t = beta * t)\n {\n if (problem.f(st.x + t * st.d) < st.f + t * alpha * dg)\n {\n return t;\n }\n }\n\n return 0;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ helper function: strong Wolfe (sufficient decrease and curvature) conditions\n static tscalar ls_zoom(const tproblem& problem, const tstate& st,\n tscalar& ft, tvector& gt,\n tscalar tlo, tscalar thi, tscalar ftlo, tscalar fthi,\n tscalar c1, tscalar c2, tsize max_iters = 64)\n {\n const tscalar dg = st.d.dot(st.g);\n\n \/\/ (Nocedal & Wright (numerical optimization 2nd) @ p.60)\n for (tsize i = 0; i < max_iters; i ++)\n {\n const tscalar t = (tlo + thi) \/ 2;\n\n \/\/ check sufficient decrease\n ft = problem.f(st.x + t * st.d, gt);\n if (ft > st.f + c1 * t * dg || ft >= ftlo)\n {\n thi = t;\n fthi = ft;\n }\n\n \/\/ check curvature\n else\n {\n const tscalar dg1 = gt.dot(st.d);\n if (std::fabs(dg1) <= -c2 * dg)\n {\n return t;\n }\n\n if (dg1 * (thi - tlo) >= 0)\n {\n thi = tlo;\n fthi = ftlo;\n }\n\n tlo = t;\n ftlo = ft;\n }\n }\n\n return 0;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ strong Wolfe (sufficient decrease and curvature) conditions\n static tscalar ls_strong_wolfe(const tproblem& problem, tstate& st, const top_wlog& wlog,\n tscalar& ft, tvector& gt,\n tscalar c1 = 1e-4, tscalar c2 = 0.1, tsize max_iters = 64)\n {\n const tscalar dg = descent(st, wlog);\n\n const tscalar tmax = 1000;\n\n tscalar t0 = 0, ft0 = std::numeric_limits::max();\n tscalar t = 1;\n\n \/\/ (Nocedal & Wright (numerical optimization 2nd) @ p.60)\n for (tsize i = 0; i < max_iters; i ++)\n {\n \/\/ check sufficient decrease\n ft = problem.f(st.x + t * st.d, gt);\n if (ft > st.f + c1 * t * dg || ft >= ft0)\n {\n return ls_zoom(problem, st, ft, gt, t0, t, ft0, ft, c1, c2, max_iters);\n }\n\n \/\/ check curvature\n const tscalar dg1 = gt.dot(st.d);\n if (std::fabs(dg1) <= -c2 * dg)\n {\n return t;\n }\n\n if (dg1 >= 0)\n {\n return ls_zoom(problem, st, ft, gt, t, t0, ft, ft0, c1, c2, max_iters);\n }\n\n t0 = t;\n t = std::min(tmax, t * 3);\n ft0 = ft;\n }\n\n return 0;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n static tresult _gd(\n const tproblem& problem,\n const tvector& x0,\n tsize max_iterations,\n tscalar epsilon,\n const top_wlog& op_wlog = top_wlog(),\n const top_elog& op_elog = top_elog(),\n const top_ulog& op_ulog = top_ulog())\n {\n assert(problem.size() == static_cast(x0.size()));\n\n tresult result(problem.size());\n tstate cstate(problem, x0);\n\n \/\/ iterate until convergence\n for (tsize i = 0; i < max_iterations; i ++)\n {\n result.update(problem, cstate);\n if (op_ulog)\n {\n op_ulog(result);\n }\n\n \/\/ check convergence\n if (cstate.converged(epsilon))\n {\n break;\n }\n\n \/\/ descent direction\n cstate.d = -cstate.g;\n\n \/\/ update solution\n const tscalar t = ls_armijo(problem, cstate, op_wlog);\n if (t < std::numeric_limits::epsilon())\n {\n if (op_elog)\n {\n op_elog(\"line-search failed for GD!\");\n }\n break;\n }\n cstate.update(problem, t);\n }\n\n return result;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n static tresult _cgd(\n const tproblem& problem,\n const tvector& x0,\n tsize max_iterations,\n tscalar epsilon,\n const top_wlog& op_wlog = top_wlog(),\n const top_elog& op_elog = top_elog(),\n const top_ulog& op_ulog = top_ulog())\n {\n assert(problem.size() == static_cast(x0.size()));\n\n tresult result(problem.size());\n tstate cstate(problem, x0), pstate = cstate;\n\n tscalar ft;\n tvector gt;\n\n \/\/ iterate until convergence\n for (tsize i = 0; i < max_iterations; i ++)\n {\n result.update(problem, cstate);\n if (op_ulog)\n {\n op_ulog(result);\n }\n\n \/\/ check convergence\n if (cstate.converged(epsilon))\n {\n break;\n }\n\n \/\/ descent direction (Polak–Ribière updates)\n if (i == 0)\n {\n cstate.d = -cstate.g;\n }\n else\n {\n const tscalar beta = cstate.g.dot(cstate.g - pstate.g) \/\n pstate.g.dot(pstate.g);\n cstate.d = -cstate.g + std::max(static_cast(0), beta) * pstate.d;\n }\n\n \/\/ update solution\n const tscalar t = ls_strong_wolfe(problem, cstate, op_wlog, ft, gt, 1e-4, 0.1);\n if (t < std::numeric_limits::epsilon())\n {\n if (op_elog)\n {\n op_elog(\"line-search failed for CGD!\");\n }\n break;\n }\n pstate = cstate;\n cstate.update(t, ft, gt);\n }\n\n return result;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n static tresult _lbfgs(\n const tproblem& problem,\n const tvector& x0,\n tsize max_iterations,\n tscalar epsilon,\n tsize hist_size = 8,\n const top_wlog& op_wlog = top_wlog(),\n const top_elog& op_elog = top_elog(),\n const top_ulog& op_ulog = top_ulog())\n {\n assert(problem.size() == static_cast(x0.size()));\n\n tresult result(problem.size());\n std::deque ss, ys;\n tstate cstate(problem, x0), pstate = cstate;\n\n tvector q, r;\n tscalar ft;\n tvector gt;\n\n \/\/ iterate until convergence\n for (tsize i = 0; i < max_iterations; i ++)\n {\n result.update(problem, cstate);\n if (op_ulog)\n {\n op_ulog(result);\n }\n\n \/\/ check convergence\n if (cstate.converged(epsilon))\n {\n break;\n }\n\n \/\/ descent direction\n \/\/ (LBFGS - Nocedal & Wright (numerical optimization 2nd) notations @ p.178)\n q = cstate.g;\n\n typename std::deque::const_reverse_iterator itr_s = ss.rbegin();\n typename std::deque::const_reverse_iterator itr_y = ys.rbegin();\n std::vector alphas;\n for (tsize j = 1; j <= hist_size && i >= j; j ++)\n {\n const tvector& s = (*itr_s ++);\n const tvector& y = (*itr_y ++);\n\n const tscalar alpha = s.dot(q) \/ s.dot(y);\n q.noalias() -= alpha * y;\n alphas.push_back(alpha);\n }\n\n if (i == 0)\n {\n r = q;\n }\n else\n {\n const tvector& s = *ss.rbegin();\n const tvector& y = *ys.rbegin();\n r = s.dot(y) \/ y.dot(y) * q;\n }\n\n typename std::deque::const_iterator it_s = ss.begin();\n typename std::deque::const_iterator it_y = ys.begin();\n typename std::vector::const_reverse_iterator itr_alpha = alphas.rbegin();\n for (tsize j = 1; j <= hist_size && i >= j; j ++)\n {\n const tvector& s = (*it_s ++);\n const tvector& y = (*it_y ++);\n\n const tscalar alpha = *(itr_alpha ++);\n const tscalar beta = y.dot(r) \/ s.dot(y);\n r.noalias() += s * (alpha - beta);\n }\n\n cstate.d = -r;\n\n \/\/ update solution\n const tscalar t = ls_strong_wolfe(problem, cstate, op_wlog, ft, gt, 0.1, 0.9);\n if (t < std::numeric_limits::epsilon())\n {\n if (op_elog)\n {\n op_elog(\"line-search failed for LBFGS!\");\n }\n break;\n }\n pstate = cstate;\n cstate.update(t, ft, gt);\n\n ss.push_back(cstate.x - pstate.x);\n ys.push_back(cstate.g - pstate.g);\n if (ss.size() > hist_size)\n {\n ss.pop_front();\n ys.pop_front();\n }\n }\n\n return result;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n };\n }\n}\n\n#endif \/\/ NANOCV_OPTIMIZE_OPTIMIZER_HPP\nfix LBFGS convergence test#ifndef NANOCV_OPTIMIZE_OPTIMIZER_HPP\n#define NANOCV_OPTIMIZE_OPTIMIZER_HPP\n\n#include \"core\/optimize\/result.hpp\"\n#include \"core\/optimize\/problem.hpp\"\n#include \n#include \n\nnamespace ncv\n{\n namespace optimize\n {\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ optimization methods (GD, CGD, LBFGS) starting from the initial value (guess) x0.\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n template\n <\n typename tscalar,\n typename tsize,\n typename top_size, \/\/ dimensionality operator: size = op()\n typename top_fval, \/\/ function value operator: f = op(x)\n typename top_grad, \/\/ function value and gradient operator: f = op(x, g)\n typename top_wlog, \/\/ warning logging operator: op(\"message\")\n typename top_elog, \/\/ error logging operator: op(\"message\")\n typename top_ulog, \/\/ update (with current result\/solution) logging operator: op(result)\n\n \/\/ disable for not valid types!\n typename tvalid_tscalar = typename std::enable_if::value>::type,\n typename tvalid_tsize = typename std::enable_if::value>::type\n >\n class optimizer_t\n {\n public:\n\n typedef problem_t tproblem;\n typedef result_t tresult;\n typedef typename tresult::tstate tstate;\n typedef typename tresult::tvector tvector;\n\n \/\/ gradient descent starting from the initial value (guess) x0\n static tresult gd(\n const tproblem& problem,\n const tvector& x0,\n tsize max_iterations, \/\/ maximum number of iterations\n tscalar epsilon, \/\/ convergence precision\n const top_wlog& op_wlog = top_wlog(),\n const top_elog& op_elog = top_elog(),\n const top_ulog& op_ulog = top_ulog())\n {\n return _gd(problem, x0, max_iterations, epsilon, op_wlog, op_elog, op_ulog);\n }\n\n \/\/ conjugate gradient descent starting from the initial value (guess) x0\n static tresult cgd(\n const tproblem& problem,\n const tvector& x0,\n tsize max_iterations, \/\/ maximum number of iterations\n tscalar epsilon, \/\/ convergence precision\n const top_wlog& op_wlog = top_wlog(),\n const top_elog& op_elog = top_elog(),\n const top_ulog& op_ulog = top_ulog())\n {\n return _cgd(problem, x0, max_iterations, epsilon, op_wlog, op_elog, op_ulog);\n }\n\n \/\/ limited memory bfgs (l-bfgs) starting from the initial value (guess) x0\n static tresult lbfgs(\n const tproblem& problem,\n const tvector& x0,\n tsize max_iterations, \/\/ maximum number of iterations\n tscalar epsilon, \/\/ convergence precision\n tsize hist_size = 8, \/\/ hessian approximation history size\n const top_wlog& op_wlog = top_wlog(),\n const top_elog& op_elog = top_elog(),\n const top_ulog& op_ulog = top_ulog())\n {\n return _lbfgs(problem, x0, max_iterations, epsilon, hist_size, op_wlog, op_elog, op_ulog);\n }\n\n private:\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ check and force a descent direction\n static tscalar descent(tstate& st, const top_wlog& wlog)\n {\n tscalar dg = st.d.dot(st.g);\n if (dg > std::numeric_limits::min())\n {\n if (wlog)\n {\n wlog(\"not a descent direction!\");\n }\n st.d = -st.g;\n dg = st.d.dot(st.g);\n }\n\n return dg;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n private:\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ line-search methods to find the scalar that reduces\n \/\/ the function value (the most) along the direction d: argmin(t) f(x + t * d).\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ Armijo (sufficient decrease) condition\n static tscalar ls_armijo(const tproblem& problem, tstate& st, const top_wlog& wlog,\n tscalar alpha = 0.2, tscalar beta = 0.7, tsize max_iters = 64)\n {\n const tscalar dg = descent(st, wlog);\n\n tscalar t = 1;\n for (tsize i = 0; i < max_iters; i ++, t = beta * t)\n {\n if (problem.f(st.x + t * st.d) < st.f + t * alpha * dg)\n {\n return t;\n }\n }\n\n return 0;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ helper function: strong Wolfe (sufficient decrease and curvature) conditions\n static tscalar ls_zoom(const tproblem& problem, const tstate& st,\n tscalar& ft, tvector& gt,\n tscalar tlo, tscalar thi, tscalar ftlo, tscalar fthi,\n tscalar c1, tscalar c2, tsize max_iters = 64)\n {\n const tscalar dg = st.d.dot(st.g);\n\n \/\/ (Nocedal & Wright (numerical optimization 2nd) @ p.60)\n for (tsize i = 0; i < max_iters; i ++)\n {\n const tscalar t = (tlo + thi) \/ 2;\n\n \/\/ check sufficient decrease\n ft = problem.f(st.x + t * st.d, gt);\n if (ft > st.f + c1 * t * dg || ft >= ftlo)\n {\n thi = t;\n fthi = ft;\n }\n\n \/\/ check curvature\n else\n {\n const tscalar dg1 = gt.dot(st.d);\n if (std::fabs(dg1) <= -c2 * dg)\n {\n return t;\n }\n\n if (dg1 * (thi - tlo) >= 0)\n {\n thi = tlo;\n fthi = ftlo;\n }\n\n tlo = t;\n ftlo = ft;\n }\n }\n\n return 0;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ strong Wolfe (sufficient decrease and curvature) conditions\n static tscalar ls_strong_wolfe(const tproblem& problem, tstate& st, const top_wlog& wlog,\n tscalar& ft, tvector& gt,\n tscalar c1 = 1e-4, tscalar c2 = 0.1, tsize max_iters = 64)\n {\n const tscalar dg = descent(st, wlog);\n\n const tscalar tmax = 1000;\n\n tscalar t0 = 0, ft0 = std::numeric_limits::max();\n tscalar t = 1;\n\n \/\/ (Nocedal & Wright (numerical optimization 2nd) @ p.60)\n for (tsize i = 0; i < max_iters; i ++)\n {\n \/\/ check sufficient decrease\n ft = problem.f(st.x + t * st.d, gt);\n if (ft > st.f + c1 * t * dg || ft >= ft0)\n {\n return ls_zoom(problem, st, ft, gt, t0, t, ft0, ft, c1, c2, max_iters);\n }\n\n \/\/ check curvature\n const tscalar dg1 = gt.dot(st.d);\n if (std::fabs(dg1) <= -c2 * dg)\n {\n return t;\n }\n\n if (dg1 >= 0)\n {\n return ls_zoom(problem, st, ft, gt, t, t0, ft, ft0, c1, c2, max_iters);\n }\n\n t0 = t;\n t = std::min(tmax, t * 3);\n ft0 = ft;\n }\n\n return 0;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n static tresult _gd(\n const tproblem& problem,\n const tvector& x0,\n tsize max_iterations,\n tscalar epsilon,\n const top_wlog& op_wlog = top_wlog(),\n const top_elog& op_elog = top_elog(),\n const top_ulog& op_ulog = top_ulog())\n {\n assert(problem.size() == static_cast(x0.size()));\n\n tresult result(problem.size());\n tstate cstate(problem, x0);\n\n \/\/ iterate until convergence\n for (tsize i = 0; i < max_iterations; i ++)\n {\n result.update(problem, cstate);\n if (op_ulog)\n {\n op_ulog(result);\n }\n\n \/\/ check convergence\n if (cstate.converged(epsilon))\n {\n break;\n }\n\n \/\/ descent direction\n cstate.d = -cstate.g;\n\n \/\/ update solution\n const tscalar t = ls_armijo(problem, cstate, op_wlog);\n if (t < std::numeric_limits::epsilon())\n {\n if (op_elog)\n {\n op_elog(\"line-search failed for GD!\");\n }\n break;\n }\n cstate.update(problem, t);\n }\n\n return result;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n static tresult _cgd(\n const tproblem& problem,\n const tvector& x0,\n tsize max_iterations,\n tscalar epsilon,\n const top_wlog& op_wlog = top_wlog(),\n const top_elog& op_elog = top_elog(),\n const top_ulog& op_ulog = top_ulog())\n {\n assert(problem.size() == static_cast(x0.size()));\n\n tresult result(problem.size());\n tstate cstate(problem, x0), pstate = cstate;\n\n tscalar ft;\n tvector gt;\n\n \/\/ iterate until convergence\n for (tsize i = 0; i < max_iterations; i ++)\n {\n result.update(problem, cstate);\n if (op_ulog)\n {\n op_ulog(result);\n }\n\n \/\/ check convergence\n if (cstate.converged(epsilon))\n {\n break;\n }\n\n \/\/ descent direction (Polak–Ribière updates)\n if (i == 0)\n {\n cstate.d = -cstate.g;\n }\n else\n {\n const tscalar beta = cstate.g.dot(cstate.g - pstate.g) \/\n pstate.g.dot(pstate.g);\n cstate.d = -cstate.g + std::max(static_cast(0), beta) * pstate.d;\n }\n\n \/\/ update solution\n const tscalar t = ls_strong_wolfe(problem, cstate, op_wlog, ft, gt, 1e-4, 0.1);\n if (t < std::numeric_limits::epsilon())\n {\n if (op_elog)\n {\n op_elog(\"line-search failed for CGD!\");\n }\n break;\n }\n pstate = cstate;\n cstate.update(t, ft, gt);\n }\n\n return result;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n static tresult _lbfgs(\n const tproblem& problem,\n const tvector& x0,\n tsize max_iterations,\n tscalar epsilon,\n tsize hist_size = 8,\n const top_wlog& op_wlog = top_wlog(),\n const top_elog& op_elog = top_elog(),\n const top_ulog& op_ulog = top_ulog())\n {\n assert(problem.size() == static_cast(x0.size()));\n\n tresult result(problem.size());\n std::deque ss, ys;\n tstate cstate(problem, x0), pstate = cstate;\n\n tvector q, r;\n tscalar ft;\n tvector gt;\n\n \/\/ iterate until convergence\n for (tsize i = 0; i < max_iterations; i ++)\n {\n result.update(problem, cstate);\n if (op_ulog)\n {\n op_ulog(result);\n }\n\n \/\/ check convergence\n if (i > hist_size && cstate.converged(epsilon))\n {\n break;\n }\n\n \/\/ descent direction\n \/\/ (LBFGS - Nocedal & Wright (numerical optimization 2nd) notations @ p.178)\n q = cstate.g;\n\n typename std::deque::const_reverse_iterator itr_s = ss.rbegin();\n typename std::deque::const_reverse_iterator itr_y = ys.rbegin();\n std::vector alphas;\n for (tsize j = 1; j <= hist_size && i >= j; j ++)\n {\n const tvector& s = (*itr_s ++);\n const tvector& y = (*itr_y ++);\n\n const tscalar alpha = s.dot(q) \/ s.dot(y);\n q.noalias() -= alpha * y;\n alphas.push_back(alpha);\n }\n\n if (i == 0)\n {\n r = q;\n }\n else\n {\n const tvector& s = *ss.rbegin();\n const tvector& y = *ys.rbegin();\n r = s.dot(y) \/ y.dot(y) * q;\n }\n\n typename std::deque::const_iterator it_s = ss.begin();\n typename std::deque::const_iterator it_y = ys.begin();\n typename std::vector::const_reverse_iterator itr_alpha = alphas.rbegin();\n for (tsize j = 1; j <= hist_size && i >= j; j ++)\n {\n const tvector& s = (*it_s ++);\n const tvector& y = (*it_y ++);\n\n const tscalar alpha = *(itr_alpha ++);\n const tscalar beta = y.dot(r) \/ s.dot(y);\n r.noalias() += s * (alpha - beta);\n }\n\n cstate.d = -r;\n\n \/\/ update solution\n const tscalar t = ls_strong_wolfe(problem, cstate, op_wlog, ft, gt, 0.1, 0.9);\n if (t < std::numeric_limits::epsilon())\n {\n if (op_elog)\n {\n op_elog(\"line-search failed for LBFGS!\");\n }\n break;\n }\n pstate = cstate;\n cstate.update(t, ft, gt);\n\n ss.push_back(cstate.x - pstate.x);\n ys.push_back(cstate.g - pstate.g);\n if (ss.size() > hist_size)\n {\n ss.pop_front();\n ys.pop_front();\n }\n }\n\n return result;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n };\n }\n}\n\n#endif \/\/ NANOCV_OPTIMIZE_OPTIMIZER_HPP\n<|endoftext|>"} {"text":"\/\/ Copyright (c) .NET Foundation and contributors. All rights reserved.\n\/\/ Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n#include \"pal.h\"\n#include \"args.h\"\n#include \"trace.h\"\n#include \"deps_resolver.h\"\n#include \"utils.h\"\n#include \"coreclr.h\"\n\nenum StatusCode\n{\n \/\/ 0x80 prefix to distinguish from corehost main's error codes.\n InvalidArgFailure = 0x81,\n CoreClrResolveFailure = 0x82,\n CoreClrBindFailure = 0x83,\n CoreClrInitFailure = 0x84,\n CoreClrExeFailure = 0x85,\n ResolverInitFailure = 0x86,\n ResolverResolveFailure = 0x87,\n};\n\n\/\/ ----------------------------------------------------------------------\n\/\/ resolve_clr_path: Resolve CLR Path in priority order\n\/\/\n\/\/ Description:\n\/\/ Check if CoreCLR library exists in runtime servicing dir or app\n\/\/ local or DOTNET_HOME directory in that order of priority. If these\n\/\/ fail to locate CoreCLR, then check platform-specific search.\n\/\/\n\/\/ Returns:\n\/\/ \"true\" if path to the CoreCLR dir can be resolved in \"clr_path\"\n\/\/ parameter. Else, returns \"false\" with \"clr_path\" unmodified.\n\/\/\nbool resolve_clr_path(const arguments_t& args, pal::string_t* clr_path)\n{\n const pal::string_t* dirs[] = {\n &args.dotnet_runtime_servicing, \/\/ DOTNET_RUNTIME_SERVICING\n &args.app_dir, \/\/ APP LOCAL\n &args.dotnet_home \/\/ DOTNET_HOME\n };\n for (int i = 0; i < sizeof(dirs) \/ sizeof(dirs[0]); ++i)\n {\n if (dirs[i]->empty())\n {\n continue;\n }\n\n \/\/ App dir should contain coreclr, so skip appending path.\n pal::string_t cur_dir = *dirs[i];\n if (dirs[i] != &args.app_dir)\n {\n append_path(&cur_dir, _X(\"runtime\"));\n append_path(&cur_dir, _X(\"coreclr\"));\n }\n\n \/\/ Found coreclr in priority order.\n if (coreclr_exists_in_dir(cur_dir))\n {\n clr_path->assign(cur_dir);\n return true;\n }\n }\n\n \/\/ Use platform-specific search algorithm\n pal::string_t home_dir = args.dotnet_home;\n if (pal::find_coreclr(&home_dir))\n {\n clr_path->assign(home_dir);\n return true;\n }\n return false;\n}\n\nint run(const arguments_t& args, const pal::string_t& clr_path)\n{\n \/\/ Load the deps resolver\n deps_resolver_t resolver(args);\n if (!resolver.valid())\n {\n trace::error(_X(\"Invalid .deps file\"));\n return StatusCode::ResolverInitFailure;\n }\n\n \/\/ Add packages directory\n pal::string_t packages_dir = args.nuget_packages;\n if (!pal::directory_exists(packages_dir))\n {\n (void)pal::get_default_packages_directory(&packages_dir);\n }\n trace::info(_X(\"Package directory: %s\"), packages_dir.empty() ? _X(\"not specified\") : packages_dir.c_str());\n\n probe_paths_t probe_paths;\n if (!resolver.resolve_probe_paths(args.app_dir, packages_dir, args.dotnet_packages_cache, clr_path, &probe_paths))\n {\n return StatusCode::ResolverResolveFailure;\n }\n\n \/\/ Build CoreCLR properties\n const char* property_keys[] = {\n \"TRUSTED_PLATFORM_ASSEMBLIES\",\n \"APP_PATHS\",\n \"APP_NI_PATHS\",\n \"NATIVE_DLL_SEARCH_DIRECTORIES\",\n \"PLATFORM_RESOURCE_ROOTS\",\n \"AppDomainCompatSwitch\",\n \/\/ TODO: pipe this from corehost.json\n \"SERVER_GC\",\n };\n\n auto tpa_paths_cstr = pal::to_stdstring(probe_paths.tpa);\n auto app_base_cstr = pal::to_stdstring(args.app_dir);\n auto native_dirs_cstr = pal::to_stdstring(probe_paths.native);\n auto culture_dirs_cstr = pal::to_stdstring(probe_paths.culture);\n\n \/\/ Workaround for dotnet\/cli Issue #488 and #652\n pal::string_t server_gc;\n std::string server_gc_cstr = (pal::getenv(_X(\"COREHOST_SERVER_GC\"), &server_gc) && !server_gc.empty()) ? pal::to_stdstring(server_gc) : \"1\";\n\n const char* property_values[] = {\n \/\/ TRUSTED_PLATFORM_ASSEMBLIES\n tpa_paths_cstr.c_str(),\n \/\/ APP_PATHS\n app_base_cstr.c_str(),\n \/\/ APP_NI_PATHS\n app_base_cstr.c_str(),\n \/\/ NATIVE_DLL_SEARCH_DIRECTORIES\n native_dirs_cstr.c_str(),\n \/\/ PLATFORM_RESOURCE_ROOTS\n culture_dirs_cstr.c_str(),\n \/\/ AppDomainCompatSwitch\n \"UseLatestBehaviorWhenTFMNotSpecified\",\n \/\/ SERVER_GC\n server_gc_cstr.c_str(),\n };\n\n size_t property_size = sizeof(property_keys) \/ sizeof(property_keys[0]);\n\n \/\/ Bind CoreCLR\n if (!coreclr::bind(clr_path))\n {\n trace::error(_X(\"Failed to bind to coreclr\"));\n return StatusCode::CoreClrBindFailure;\n }\n\n \/\/ Verbose logging\n if (trace::is_enabled())\n {\n for (size_t i = 0; i < property_size; ++i)\n {\n pal::string_t key, val;\n pal::to_palstring(property_keys[i], &key);\n pal::to_palstring(property_values[i], &val);\n trace::verbose(_X(\"Property %s = %s\"), key.c_str(), val.c_str());\n }\n }\n\n std::string own_path;\n pal::to_stdstring(args.own_path.c_str(), &own_path);\n\n \/\/ Initialize CoreCLR\n coreclr::host_handle_t host_handle;\n coreclr::domain_id_t domain_id;\n auto hr = coreclr::initialize(\n own_path.c_str(),\n \"clrhost\",\n property_keys,\n property_values,\n property_size,\n &host_handle,\n &domain_id);\n if (!SUCCEEDED(hr))\n {\n trace::error(_X(\"Failed to initialize CoreCLR, HRESULT: 0x%X\"), hr);\n return StatusCode::CoreClrInitFailure;\n }\n\n if (trace::is_enabled())\n {\n pal::string_t arg_str;\n for (int i = 0; i < args.app_argc; i++)\n {\n arg_str.append(args.app_argv[i]);\n arg_str.append(_X(\",\"));\n }\n trace::info(_X(\"Launch host: %s app: %s, argc: %d args: %s\"), args.own_path.c_str(),\n args.managed_application.c_str(), args.app_argc, arg_str.c_str());\n }\n\n \/\/ Initialize with empty strings\n std::vector argv_strs(args.app_argc);\n std::vector argv(args.app_argc);\n for (int i = 0; i < args.app_argc; i++)\n {\n pal::to_stdstring(args.app_argv[i], &argv_strs[i]);\n argv[i] = argv_strs[i].c_str();\n }\n\n std::string managed_app = pal::to_stdstring(args.managed_application);\n\n \/\/ Execute the application\n unsigned int exit_code = 1;\n hr = coreclr::execute_assembly(\n host_handle,\n domain_id,\n argv.size(),\n argv.data(),\n managed_app.c_str(),\n &exit_code);\n if (!SUCCEEDED(hr))\n {\n trace::error(_X(\"Failed to execute managed app, HRESULT: 0x%X\"), hr);\n return StatusCode::CoreClrExeFailure;\n }\n\n \/\/ Shut down the CoreCLR\n hr = coreclr::shutdown(host_handle, domain_id);\n if (!SUCCEEDED(hr))\n {\n trace::warning(_X(\"Failed to shut down CoreCLR, HRESULT: 0x%X\"), hr);\n }\n\n coreclr::unload();\n\n return exit_code;\n}\n\nSHARED_API int corehost_main(const int argc, const pal::char_t* argv[])\n{\n trace::setup();\n\n \/\/ Take care of arguments\n arguments_t args;\n if (!parse_arguments(argc, argv, args))\n {\n return StatusCode::InvalidArgFailure;\n }\n\n \/\/ Resolve CLR path\n pal::string_t clr_path;\n if (!resolve_clr_path(args, &clr_path))\n {\n trace::error(_X(\"Could not resolve coreclr path\"));\n return StatusCode::CoreClrResolveFailure;\n }\n pal::realpath(&clr_path);\n return run(args, clr_path);\n}\nSet AppContext BaseDirectory\/\/ Copyright (c) .NET Foundation and contributors. All rights reserved.\n\/\/ Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n#include \"pal.h\"\n#include \"args.h\"\n#include \"trace.h\"\n#include \"deps_resolver.h\"\n#include \"utils.h\"\n#include \"coreclr.h\"\n\nenum StatusCode\n{\n \/\/ 0x80 prefix to distinguish from corehost main's error codes.\n InvalidArgFailure = 0x81,\n CoreClrResolveFailure = 0x82,\n CoreClrBindFailure = 0x83,\n CoreClrInitFailure = 0x84,\n CoreClrExeFailure = 0x85,\n ResolverInitFailure = 0x86,\n ResolverResolveFailure = 0x87,\n};\n\n\/\/ ----------------------------------------------------------------------\n\/\/ resolve_clr_path: Resolve CLR Path in priority order\n\/\/\n\/\/ Description:\n\/\/ Check if CoreCLR library exists in runtime servicing dir or app\n\/\/ local or DOTNET_HOME directory in that order of priority. If these\n\/\/ fail to locate CoreCLR, then check platform-specific search.\n\/\/\n\/\/ Returns:\n\/\/ \"true\" if path to the CoreCLR dir can be resolved in \"clr_path\"\n\/\/ parameter. Else, returns \"false\" with \"clr_path\" unmodified.\n\/\/\nbool resolve_clr_path(const arguments_t& args, pal::string_t* clr_path)\n{\n const pal::string_t* dirs[] = {\n &args.dotnet_runtime_servicing, \/\/ DOTNET_RUNTIME_SERVICING\n &args.app_dir, \/\/ APP LOCAL\n &args.dotnet_home \/\/ DOTNET_HOME\n };\n for (int i = 0; i < sizeof(dirs) \/ sizeof(dirs[0]); ++i)\n {\n if (dirs[i]->empty())\n {\n continue;\n }\n\n \/\/ App dir should contain coreclr, so skip appending path.\n pal::string_t cur_dir = *dirs[i];\n if (dirs[i] != &args.app_dir)\n {\n append_path(&cur_dir, _X(\"runtime\"));\n append_path(&cur_dir, _X(\"coreclr\"));\n }\n\n \/\/ Found coreclr in priority order.\n if (coreclr_exists_in_dir(cur_dir))\n {\n clr_path->assign(cur_dir);\n return true;\n }\n }\n\n \/\/ Use platform-specific search algorithm\n pal::string_t home_dir = args.dotnet_home;\n if (pal::find_coreclr(&home_dir))\n {\n clr_path->assign(home_dir);\n return true;\n }\n return false;\n}\n\nint run(const arguments_t& args, const pal::string_t& clr_path)\n{\n \/\/ Load the deps resolver\n deps_resolver_t resolver(args);\n if (!resolver.valid())\n {\n trace::error(_X(\"Invalid .deps file\"));\n return StatusCode::ResolverInitFailure;\n }\n\n \/\/ Add packages directory\n pal::string_t packages_dir = args.nuget_packages;\n if (!pal::directory_exists(packages_dir))\n {\n (void)pal::get_default_packages_directory(&packages_dir);\n }\n trace::info(_X(\"Package directory: %s\"), packages_dir.empty() ? _X(\"not specified\") : packages_dir.c_str());\n\n probe_paths_t probe_paths;\n if (!resolver.resolve_probe_paths(args.app_dir, packages_dir, args.dotnet_packages_cache, clr_path, &probe_paths))\n {\n return StatusCode::ResolverResolveFailure;\n }\n\n \/\/ Build CoreCLR properties\n const char* property_keys[] = {\n \"TRUSTED_PLATFORM_ASSEMBLIES\",\n \"APP_PATHS\",\n \"APP_NI_PATHS\",\n \"NATIVE_DLL_SEARCH_DIRECTORIES\",\n \"PLATFORM_RESOURCE_ROOTS\",\n \"AppDomainCompatSwitch\",\n \/\/ TODO: pipe this from corehost.json\n \"SERVER_GC\",\n \/\/ Workaround: mscorlib does not resolve symlinks for AppContext.BaseDirectory dotnet\/coreclr\/issues\/2128\n \"APP_CONTEXT_BASE_DIRECTORY\",\n };\n\n auto tpa_paths_cstr = pal::to_stdstring(probe_paths.tpa);\n auto app_base_cstr = pal::to_stdstring(args.app_dir);\n auto native_dirs_cstr = pal::to_stdstring(probe_paths.native);\n auto culture_dirs_cstr = pal::to_stdstring(probe_paths.culture);\n\n \/\/ Workaround for dotnet\/cli Issue #488 and #652\n pal::string_t server_gc;\n std::string server_gc_cstr = (pal::getenv(_X(\"COREHOST_SERVER_GC\"), &server_gc) && !server_gc.empty()) ? pal::to_stdstring(server_gc) : \"1\";\n\n const char* property_values[] = {\n \/\/ TRUSTED_PLATFORM_ASSEMBLIES\n tpa_paths_cstr.c_str(),\n \/\/ APP_PATHS\n app_base_cstr.c_str(),\n \/\/ APP_NI_PATHS\n app_base_cstr.c_str(),\n \/\/ NATIVE_DLL_SEARCH_DIRECTORIES\n native_dirs_cstr.c_str(),\n \/\/ PLATFORM_RESOURCE_ROOTS\n culture_dirs_cstr.c_str(),\n \/\/ AppDomainCompatSwitch\n \"UseLatestBehaviorWhenTFMNotSpecified\",\n \/\/ SERVER_GC\n server_gc_cstr.c_str(),\n \/\/ APP_CONTEXT_BASE_DIRECTORY\n app_base_cstr.c_str()\n };\n\n size_t property_size = sizeof(property_keys) \/ sizeof(property_keys[0]);\n\n \/\/ Bind CoreCLR\n if (!coreclr::bind(clr_path))\n {\n trace::error(_X(\"Failed to bind to coreclr\"));\n return StatusCode::CoreClrBindFailure;\n }\n\n \/\/ Verbose logging\n if (trace::is_enabled())\n {\n for (size_t i = 0; i < property_size; ++i)\n {\n pal::string_t key, val;\n pal::to_palstring(property_keys[i], &key);\n pal::to_palstring(property_values[i], &val);\n trace::verbose(_X(\"Property %s = %s\"), key.c_str(), val.c_str());\n }\n }\n\n std::string own_path;\n pal::to_stdstring(args.own_path.c_str(), &own_path);\n\n \/\/ Initialize CoreCLR\n coreclr::host_handle_t host_handle;\n coreclr::domain_id_t domain_id;\n auto hr = coreclr::initialize(\n own_path.c_str(),\n \"clrhost\",\n property_keys,\n property_values,\n property_size,\n &host_handle,\n &domain_id);\n if (!SUCCEEDED(hr))\n {\n trace::error(_X(\"Failed to initialize CoreCLR, HRESULT: 0x%X\"), hr);\n return StatusCode::CoreClrInitFailure;\n }\n\n if (trace::is_enabled())\n {\n pal::string_t arg_str;\n for (int i = 0; i < args.app_argc; i++)\n {\n arg_str.append(args.app_argv[i]);\n arg_str.append(_X(\",\"));\n }\n trace::info(_X(\"Launch host: %s app: %s, argc: %d args: %s\"), args.own_path.c_str(),\n args.managed_application.c_str(), args.app_argc, arg_str.c_str());\n }\n\n \/\/ Initialize with empty strings\n std::vector argv_strs(args.app_argc);\n std::vector argv(args.app_argc);\n for (int i = 0; i < args.app_argc; i++)\n {\n pal::to_stdstring(args.app_argv[i], &argv_strs[i]);\n argv[i] = argv_strs[i].c_str();\n }\n\n std::string managed_app = pal::to_stdstring(args.managed_application);\n\n \/\/ Execute the application\n unsigned int exit_code = 1;\n hr = coreclr::execute_assembly(\n host_handle,\n domain_id,\n argv.size(),\n argv.data(),\n managed_app.c_str(),\n &exit_code);\n if (!SUCCEEDED(hr))\n {\n trace::error(_X(\"Failed to execute managed app, HRESULT: 0x%X\"), hr);\n return StatusCode::CoreClrExeFailure;\n }\n\n \/\/ Shut down the CoreCLR\n hr = coreclr::shutdown(host_handle, domain_id);\n if (!SUCCEEDED(hr))\n {\n trace::warning(_X(\"Failed to shut down CoreCLR, HRESULT: 0x%X\"), hr);\n }\n\n coreclr::unload();\n\n return exit_code;\n}\n\nSHARED_API int corehost_main(const int argc, const pal::char_t* argv[])\n{\n trace::setup();\n\n \/\/ Take care of arguments\n arguments_t args;\n if (!parse_arguments(argc, argv, args))\n {\n return StatusCode::InvalidArgFailure;\n }\n\n \/\/ Resolve CLR path\n pal::string_t clr_path;\n if (!resolve_clr_path(args, &clr_path))\n {\n trace::error(_X(\"Could not resolve coreclr path\"));\n return StatusCode::CoreClrResolveFailure;\n }\n pal::realpath(&clr_path);\n return run(args, clr_path);\n}\n<|endoftext|>"} {"text":"\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"mtimestamp.h\"\n\n#include \"mdebug.h\"\n#include \n#include \n#include \n#include \n#include \n\nvoid M_CORE_EXPORT mTimestampStream(const QString &module, const QString &file, const QString &scope, const QString &msg)\n{\n static const QString format(\"%1.%2 MARK|%3|%4|%5\");\n static const QChar fill('0');\n QString output;\n struct timeval tv;\n\n gettimeofday(&tv, 0);\n\n output = format.arg(tv.tv_sec).arg(tv.tv_usec, 6, 10, fill).arg(file).arg(scope).arg(msg);\n mWarning(module) << output;\n}\nChanges: use QTime instead of gettimeofday\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"mtimestamp.h\"\n\n#include \"mdebug.h\"\n#include \n\nvoid M_CORE_EXPORT mTimestampStream(const QString &module, const QString &file, const QString &scope, const QString &msg)\n{\n static const QString format(\"MARK|%3|%4|%5\");\n QString output = format.arg(file).arg(scope).arg(msg);\n mWarning(module) << QTime::currentTime() << output;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) the JPEG XL Project Authors. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n#include \"lib\/extras\/enc\/apng.h\"\n\n\/\/ Parts of this code are taken from apngdis, which has the following license:\n\/* APNG Disassembler 2.8\n *\n * Deconstructs APNG files into individual frames.\n *\n * http:\/\/apngdis.sourceforge.net\n *\n * Copyright (c) 2010-2015 Max Stepin\n * maxst at users.sourceforge.net\n *\n * zlib license\n * ------------\n *\n * This software is provided 'as-is', without any express or implied\n * warranty. In no event will the authors be held liable for any damages\n * arising from the use of this software.\n *\n * Permission is granted to anyone to use this software for any purpose,\n * including commercial applications, and to alter it and redistribute it\n * freely, subject to the following restrictions:\n *\n * 1. The origin of this software must not be misrepresented; you must not\n * claim that you wrote the original software. If you use this software\n * in a product, an acknowledgment in the product documentation would be\n * appreciated but is not required.\n * 2. Altered source versions must be plainly marked as such, and must not be\n * misrepresented as being the original software.\n * 3. This notice may not be removed or altered from any source distribution.\n *\n *\/\n\n#include \n#include \n\n#include \n#include \n\n#include \"jxl\/encode.h\"\n#include \"lib\/extras\/packed_image_convert.h\"\n#include \"lib\/jxl\/base\/compiler_specific.h\"\n#include \"lib\/jxl\/base\/printf_macros.h\"\n#include \"lib\/jxl\/color_encoding_internal.h\"\n#include \"lib\/jxl\/dec_external_image.h\"\n#include \"lib\/jxl\/enc_color_management.h\"\n#include \"lib\/jxl\/enc_image_bundle.h\"\n#include \"lib\/jxl\/exif.h\"\n#include \"lib\/jxl\/frame_header.h\"\n#include \"lib\/jxl\/headers.h\"\n#include \"lib\/jxl\/image.h\"\n#include \"lib\/jxl\/image_bundle.h\"\n#include \"png.h\" \/* original (unpatched) libpng is ok *\/\n\nnamespace jxl {\nnamespace extras {\n\nnamespace {\n\nclass APNGEncoder : public Encoder {\n public:\n std::vector AcceptedFormats() const override {\n std::vector formats;\n for (const uint32_t num_channels : {1, 2, 3, 4}) {\n for (const JxlDataType data_type : {JXL_TYPE_UINT8, JXL_TYPE_UINT16}) {\n for (JxlEndianness endianness : {JXL_BIG_ENDIAN, JXL_LITTLE_ENDIAN}) {\n formats.push_back(JxlPixelFormat{\/*num_channels=*\/num_channels,\n \/*data_type=*\/data_type,\n \/*endianness=*\/endianness,\n \/*align=*\/0});\n }\n }\n }\n return formats;\n }\n Status Encode(const PackedPixelFile& ppf, EncodedImage* encoded_image,\n ThreadPool* pool) const override {\n encoded_image->icc.clear();\n encoded_image->bitstreams.resize(1);\n CodecInOut io;\n JXL_RETURN_IF_ERROR(ConvertPackedPixelFileToCodecInOut(ppf, pool, &io));\n return EncodeImageAPNG(&io, io.metadata.m.color_encoding,\n ppf.info.bits_per_sample, pool,\n &encoded_image->bitstreams.front());\n }\n};\n\nstatic void PngWrite(png_structp png_ptr, png_bytep data, png_size_t length) {\n std::vector* bytes =\n static_cast*>(png_get_io_ptr(png_ptr));\n bytes->insert(bytes->end(), data, data + length);\n}\n\n\/\/ Stores XMP and EXIF\/IPTC into key\/value strings for PNG\nclass BlobsWriterPNG {\n public:\n static Status Encode(const Blobs& blobs, std::vector* strings) {\n if (!blobs.exif.empty()) {\n \/\/ PNG viewers typically ignore Exif orientation but not all of them do\n \/\/ (and e.g. cjxl doesn't), so we overwrite the Exif orientation to the\n \/\/ identity to avoid repeated orientation.\n std::vector exif = blobs.exif;\n ResetExifOrientation(exif);\n JXL_RETURN_IF_ERROR(EncodeBase16(\"exif\", exif, strings));\n }\n if (!blobs.iptc.empty()) {\n JXL_RETURN_IF_ERROR(EncodeBase16(\"iptc\", blobs.iptc, strings));\n }\n if (!blobs.xmp.empty()) {\n JXL_RETURN_IF_ERROR(EncodeBase16(\"xmp\", blobs.xmp, strings));\n }\n return true;\n }\n\n private:\n static JXL_INLINE char EncodeNibble(const uint8_t nibble) {\n JXL_ASSERT(nibble < 16);\n return (nibble < 10) ? '0' + nibble : 'a' + nibble - 10;\n }\n\n static Status EncodeBase16(const std::string& type,\n const std::vector& bytes,\n std::vector* strings) {\n \/\/ Encoding: base16 with newline after 72 chars.\n const size_t base16_size =\n 2 * bytes.size() + DivCeil(bytes.size(), size_t(36)) + 1;\n std::string base16;\n base16.reserve(base16_size);\n for (size_t i = 0; i < bytes.size(); ++i) {\n if (i % 36 == 0) base16.push_back('\\n');\n base16.push_back(EncodeNibble(bytes[i] >> 4));\n base16.push_back(EncodeNibble(bytes[i] & 0x0F));\n }\n base16.push_back('\\n');\n JXL_ASSERT(base16.length() == base16_size);\n\n char key[30];\n snprintf(key, sizeof(key), \"Raw profile type %s\", type.c_str());\n\n char header[30];\n snprintf(header, sizeof(header), \"\\n%s\\n%8\" PRIuS, type.c_str(),\n bytes.size());\n\n strings->push_back(std::string(key));\n strings->push_back(std::string(header) + base16);\n return true;\n }\n};\n\n} \/\/ namespace\n\nstd::unique_ptr GetAPNGEncoder() {\n return jxl::make_unique();\n}\n\nStatus EncodeImageAPNG(const CodecInOut* io, const ColorEncoding& c_desired,\n size_t bits_per_sample, ThreadPool* pool,\n std::vector* bytes) {\n if (bits_per_sample > 8) {\n bits_per_sample = 16;\n } else if (bits_per_sample < 8) {\n \/\/ PNG can also do 4, 2, and 1 bits per sample, but it isn't implemented\n bits_per_sample = 8;\n }\n\n size_t count = 0;\n bool have_anim = io->metadata.m.have_animation;\n size_t anim_chunks = 0;\n int W = 0, H = 0;\n\n for (size_t i = 0; i < io->frames.size(); i++) {\n auto& frame = io->frames[i];\n if (!have_anim && i + 1 < io->frames.size()) continue;\n png_structp png_ptr;\n png_infop info_ptr;\n\n png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);\n\n if (!png_ptr) return JXL_FAILURE(\"Could not init png encoder\");\n\n info_ptr = png_create_info_struct(png_ptr);\n if (!info_ptr) return JXL_FAILURE(\"Could not init png info struct\");\n\n png_set_write_fn(png_ptr, bytes, PngWrite, NULL);\n png_set_flush(png_ptr, 0);\n\n ImageBundle ib = frame.Copy();\n const size_t alpha_bits = ib.HasAlpha() ? bits_per_sample : 0;\n ImageMetadata metadata = io->metadata.m;\n ImageBundle store(&metadata);\n const ImageBundle* transformed;\n JXL_RETURN_IF_ERROR(TransformIfNeeded(ib, c_desired, GetJxlCms(), pool,\n &store, &transformed));\n size_t stride = ib.oriented_xsize() *\n DivCeil(c_desired.Channels() * bits_per_sample + alpha_bits,\n kBitsPerByte);\n std::vector raw_bytes(stride * ib.oriented_ysize());\n JXL_RETURN_IF_ERROR(ConvertToExternal(\n *transformed, bits_per_sample, \/*float_out=*\/false,\n c_desired.Channels() + (ib.HasAlpha() ? 1 : 0), JXL_BIG_ENDIAN, stride,\n pool, raw_bytes.data(), raw_bytes.size(),\n \/*out_callback=*\/{}, metadata.GetOrientation()));\n\n int width = ib.oriented_xsize();\n int height = ib.oriented_ysize();\n\n png_byte color_type =\n (c_desired.Channels() == 3 ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_GRAY);\n if (ib.HasAlpha()) color_type |= PNG_COLOR_MASK_ALPHA;\n png_byte bit_depth = bits_per_sample;\n\n png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth, color_type,\n PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE,\n PNG_FILTER_TYPE_BASE);\n if (count == 0) {\n W = width;\n H = height;\n\n \/\/ TODO(jon): instead of always setting an iCCP, could try to avoid that\n \/\/ have to avoid warnings on the ICC profile becoming fatal\n png_set_benign_errors(png_ptr, 1);\n png_set_iCCP(png_ptr, info_ptr, \"1\", 0, c_desired.ICC().data(),\n c_desired.ICC().size());\n\n std::vector textstrings;\n JXL_RETURN_IF_ERROR(BlobsWriterPNG::Encode(io->blobs, &textstrings));\n for (size_t kk = 0; kk + 1 < textstrings.size(); kk += 2) {\n png_text text;\n text.key = const_cast(textstrings[kk].c_str());\n text.text = const_cast(textstrings[kk + 1].c_str());\n text.compression = PNG_TEXT_COMPRESSION_zTXt;\n png_set_text(png_ptr, info_ptr, &text, 1);\n }\n\n png_write_info(png_ptr, info_ptr);\n } else {\n \/\/ fake writing a header, otherwise libpng gets confused\n size_t pos = bytes->size();\n png_write_info(png_ptr, info_ptr);\n bytes->resize(pos);\n }\n\n if (have_anim) {\n if (count == 0) {\n png_byte adata[8];\n png_save_uint_32(adata, io->frames.size());\n png_save_uint_32(adata + 4, io->metadata.m.animation.num_loops);\n png_byte actl[5] = \"acTL\";\n png_write_chunk(png_ptr, actl, adata, 8);\n }\n png_byte fdata[26];\n JXL_ASSERT(W == width);\n JXL_ASSERT(H == height);\n \/\/ TODO(jon): also make this work for the non-coalesced case\n png_save_uint_32(fdata, anim_chunks++);\n png_save_uint_32(fdata + 4, width);\n png_save_uint_32(fdata + 8, height);\n png_save_uint_32(fdata + 12, 0);\n png_save_uint_32(fdata + 16, 0);\n png_save_uint_16(\n fdata + 20,\n frame.duration * io->metadata.m.animation.tps_denominator);\n png_save_uint_16(fdata + 22, io->metadata.m.animation.tps_numerator);\n fdata[24] = 1;\n fdata[25] = 0;\n png_byte fctl[5] = \"fcTL\";\n png_write_chunk(png_ptr, fctl, fdata, 26);\n }\n\n std::vector rows(height);\n for (int y = 0; y < height; ++y) {\n rows[y] = raw_bytes.data() + y * stride;\n }\n\n png_write_flush(png_ptr);\n const size_t pos = bytes->size();\n png_write_image(png_ptr, &rows[0]);\n png_write_flush(png_ptr);\n if (count > 0) {\n std::vector fdata(4);\n png_save_uint_32(fdata.data(), anim_chunks++);\n size_t p = pos;\n while (p + 8 < bytes->size()) {\n size_t len = png_get_uint_32(bytes->data() + p);\n JXL_ASSERT(bytes->operator[](p + 4) == 'I');\n JXL_ASSERT(bytes->operator[](p + 5) == 'D');\n JXL_ASSERT(bytes->operator[](p + 6) == 'A');\n JXL_ASSERT(bytes->operator[](p + 7) == 'T');\n fdata.insert(fdata.end(), bytes->data() + p + 8,\n bytes->data() + p + 8 + len);\n p += len + 12;\n }\n bytes->resize(pos);\n\n png_byte fdat[5] = \"fdAT\";\n png_write_chunk(png_ptr, fdat, fdata.data(), fdata.size());\n }\n\n count++;\n if (count == io->frames.size() || !have_anim) png_write_end(png_ptr, NULL);\n\n png_destroy_write_struct(&png_ptr, &info_ptr);\n }\n\n return true;\n}\n\n} \/\/ namespace extras\n} \/\/ namespace jxl\nAdd support for producing PNGs with the cICP chunk.\/\/ Copyright (c) the JPEG XL Project Authors. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n#include \"lib\/extras\/enc\/apng.h\"\n\n\/\/ Parts of this code are taken from apngdis, which has the following license:\n\/* APNG Disassembler 2.8\n *\n * Deconstructs APNG files into individual frames.\n *\n * http:\/\/apngdis.sourceforge.net\n *\n * Copyright (c) 2010-2015 Max Stepin\n * maxst at users.sourceforge.net\n *\n * zlib license\n * ------------\n *\n * This software is provided 'as-is', without any express or implied\n * warranty. In no event will the authors be held liable for any damages\n * arising from the use of this software.\n *\n * Permission is granted to anyone to use this software for any purpose,\n * including commercial applications, and to alter it and redistribute it\n * freely, subject to the following restrictions:\n *\n * 1. The origin of this software must not be misrepresented; you must not\n * claim that you wrote the original software. If you use this software\n * in a product, an acknowledgment in the product documentation would be\n * appreciated but is not required.\n * 2. Altered source versions must be plainly marked as such, and must not be\n * misrepresented as being the original software.\n * 3. This notice may not be removed or altered from any source distribution.\n *\n *\/\n\n#include \n#include \n\n#include \n#include \n\n#include \"jxl\/encode.h\"\n#include \"lib\/extras\/packed_image_convert.h\"\n#include \"lib\/jxl\/base\/compiler_specific.h\"\n#include \"lib\/jxl\/base\/printf_macros.h\"\n#include \"lib\/jxl\/color_encoding_internal.h\"\n#include \"lib\/jxl\/dec_external_image.h\"\n#include \"lib\/jxl\/enc_color_management.h\"\n#include \"lib\/jxl\/enc_image_bundle.h\"\n#include \"lib\/jxl\/exif.h\"\n#include \"lib\/jxl\/frame_header.h\"\n#include \"lib\/jxl\/headers.h\"\n#include \"lib\/jxl\/image.h\"\n#include \"lib\/jxl\/image_bundle.h\"\n#include \"png.h\" \/* original (unpatched) libpng is ok *\/\n\nnamespace jxl {\nnamespace extras {\n\nnamespace {\n\nclass APNGEncoder : public Encoder {\n public:\n std::vector AcceptedFormats() const override {\n std::vector formats;\n for (const uint32_t num_channels : {1, 2, 3, 4}) {\n for (const JxlDataType data_type : {JXL_TYPE_UINT8, JXL_TYPE_UINT16}) {\n for (JxlEndianness endianness : {JXL_BIG_ENDIAN, JXL_LITTLE_ENDIAN}) {\n formats.push_back(JxlPixelFormat{\/*num_channels=*\/num_channels,\n \/*data_type=*\/data_type,\n \/*endianness=*\/endianness,\n \/*align=*\/0});\n }\n }\n }\n return formats;\n }\n Status Encode(const PackedPixelFile& ppf, EncodedImage* encoded_image,\n ThreadPool* pool) const override {\n encoded_image->icc.clear();\n encoded_image->bitstreams.resize(1);\n CodecInOut io;\n JXL_RETURN_IF_ERROR(ConvertPackedPixelFileToCodecInOut(ppf, pool, &io));\n return EncodeImageAPNG(&io, io.metadata.m.color_encoding,\n ppf.info.bits_per_sample, pool,\n &encoded_image->bitstreams.front());\n }\n};\n\nstatic void PngWrite(png_structp png_ptr, png_bytep data, png_size_t length) {\n std::vector* bytes =\n static_cast*>(png_get_io_ptr(png_ptr));\n bytes->insert(bytes->end(), data, data + length);\n}\n\n\/\/ Stores XMP and EXIF\/IPTC into key\/value strings for PNG\nclass BlobsWriterPNG {\n public:\n static Status Encode(const Blobs& blobs, std::vector* strings) {\n if (!blobs.exif.empty()) {\n \/\/ PNG viewers typically ignore Exif orientation but not all of them do\n \/\/ (and e.g. cjxl doesn't), so we overwrite the Exif orientation to the\n \/\/ identity to avoid repeated orientation.\n std::vector exif = blobs.exif;\n ResetExifOrientation(exif);\n JXL_RETURN_IF_ERROR(EncodeBase16(\"exif\", exif, strings));\n }\n if (!blobs.iptc.empty()) {\n JXL_RETURN_IF_ERROR(EncodeBase16(\"iptc\", blobs.iptc, strings));\n }\n if (!blobs.xmp.empty()) {\n JXL_RETURN_IF_ERROR(EncodeBase16(\"xmp\", blobs.xmp, strings));\n }\n return true;\n }\n\n private:\n static JXL_INLINE char EncodeNibble(const uint8_t nibble) {\n JXL_ASSERT(nibble < 16);\n return (nibble < 10) ? '0' + nibble : 'a' + nibble - 10;\n }\n\n static Status EncodeBase16(const std::string& type,\n const std::vector& bytes,\n std::vector* strings) {\n \/\/ Encoding: base16 with newline after 72 chars.\n const size_t base16_size =\n 2 * bytes.size() + DivCeil(bytes.size(), size_t(36)) + 1;\n std::string base16;\n base16.reserve(base16_size);\n for (size_t i = 0; i < bytes.size(); ++i) {\n if (i % 36 == 0) base16.push_back('\\n');\n base16.push_back(EncodeNibble(bytes[i] >> 4));\n base16.push_back(EncodeNibble(bytes[i] & 0x0F));\n }\n base16.push_back('\\n');\n JXL_ASSERT(base16.length() == base16_size);\n\n char key[30];\n snprintf(key, sizeof(key), \"Raw profile type %s\", type.c_str());\n\n char header[30];\n snprintf(header, sizeof(header), \"\\n%s\\n%8\" PRIuS, type.c_str(),\n bytes.size());\n\n strings->push_back(std::string(key));\n strings->push_back(std::string(header) + base16);\n return true;\n }\n};\n\n} \/\/ namespace\n\nstd::unique_ptr GetAPNGEncoder() {\n return jxl::make_unique();\n}\n\nStatus EncodeImageAPNG(const CodecInOut* io, const ColorEncoding& c_desired,\n size_t bits_per_sample, ThreadPool* pool,\n std::vector* bytes) {\n if (bits_per_sample > 8) {\n bits_per_sample = 16;\n } else if (bits_per_sample < 8) {\n \/\/ PNG can also do 4, 2, and 1 bits per sample, but it isn't implemented\n bits_per_sample = 8;\n }\n\n png_byte cicp_data[4] = {};\n png_unknown_chunk cicp_chunk;\n\n size_t count = 0;\n bool have_anim = io->metadata.m.have_animation;\n size_t anim_chunks = 0;\n int W = 0, H = 0;\n\n for (size_t i = 0; i < io->frames.size(); i++) {\n auto& frame = io->frames[i];\n if (!have_anim && i + 1 < io->frames.size()) continue;\n png_structp png_ptr;\n png_infop info_ptr;\n\n png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);\n\n if (!png_ptr) return JXL_FAILURE(\"Could not init png encoder\");\n\n info_ptr = png_create_info_struct(png_ptr);\n if (!info_ptr) return JXL_FAILURE(\"Could not init png info struct\");\n\n png_set_write_fn(png_ptr, bytes, PngWrite, NULL);\n png_set_flush(png_ptr, 0);\n\n ImageBundle ib = frame.Copy();\n const size_t alpha_bits = ib.HasAlpha() ? bits_per_sample : 0;\n ImageMetadata metadata = io->metadata.m;\n ImageBundle store(&metadata);\n const ImageBundle* transformed;\n JXL_RETURN_IF_ERROR(TransformIfNeeded(ib, c_desired, GetJxlCms(), pool,\n &store, &transformed));\n size_t stride = ib.oriented_xsize() *\n DivCeil(c_desired.Channels() * bits_per_sample + alpha_bits,\n kBitsPerByte);\n std::vector raw_bytes(stride * ib.oriented_ysize());\n JXL_RETURN_IF_ERROR(ConvertToExternal(\n *transformed, bits_per_sample, \/*float_out=*\/false,\n c_desired.Channels() + (ib.HasAlpha() ? 1 : 0), JXL_BIG_ENDIAN, stride,\n pool, raw_bytes.data(), raw_bytes.size(),\n \/*out_callback=*\/{}, metadata.GetOrientation()));\n\n int width = ib.oriented_xsize();\n int height = ib.oriented_ysize();\n\n png_byte color_type =\n (c_desired.Channels() == 3 ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_GRAY);\n if (ib.HasAlpha()) color_type |= PNG_COLOR_MASK_ALPHA;\n png_byte bit_depth = bits_per_sample;\n\n png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth, color_type,\n PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE,\n PNG_FILTER_TYPE_BASE);\n if (count == 0) {\n W = width;\n H = height;\n\n if (!c_desired.WantICC() && c_desired.primaries != Primaries::kCustom &&\n !c_desired.tf.IsUnknown() && !c_desired.tf.IsGamma() &&\n (c_desired.white_point == WhitePoint::kD65 ||\n (c_desired.white_point == WhitePoint::kDCI &&\n c_desired.primaries == Primaries::kP3))) {\n cicp_data[0] = c_desired.primaries != Primaries::kP3\n ? static_cast(c_desired.primaries)\n : c_desired.white_point == WhitePoint::kD65 ? 12\n : 11;\n cicp_data[1] =\n static_cast(c_desired.tf.GetTransferFunction());\n cicp_data[3] = 1;\n cicp_chunk.data = cicp_data;\n cicp_chunk.size = sizeof(cicp_data);\n cicp_chunk.location = PNG_HAVE_PLTE;\n memcpy(cicp_chunk.name, \"cICP\", 5);\n png_set_keep_unknown_chunks(\n png_ptr, 3, reinterpret_cast(\"cICP\"), 1);\n png_set_unknown_chunks(png_ptr, info_ptr, &cicp_chunk, 1);\n }\n \/\/ TODO(jon): instead of always setting an iCCP, could try to avoid that\n \/\/ have to avoid warnings on the ICC profile becoming fatal\n png_set_benign_errors(png_ptr, 1);\n png_set_iCCP(png_ptr, info_ptr, \"1\", 0, c_desired.ICC().data(),\n c_desired.ICC().size());\n\n std::vector textstrings;\n JXL_RETURN_IF_ERROR(BlobsWriterPNG::Encode(io->blobs, &textstrings));\n for (size_t kk = 0; kk + 1 < textstrings.size(); kk += 2) {\n png_text text;\n text.key = const_cast(textstrings[kk].c_str());\n text.text = const_cast(textstrings[kk + 1].c_str());\n text.compression = PNG_TEXT_COMPRESSION_zTXt;\n png_set_text(png_ptr, info_ptr, &text, 1);\n }\n\n png_write_info(png_ptr, info_ptr);\n } else {\n \/\/ fake writing a header, otherwise libpng gets confused\n size_t pos = bytes->size();\n png_write_info(png_ptr, info_ptr);\n bytes->resize(pos);\n }\n\n if (have_anim) {\n if (count == 0) {\n png_byte adata[8];\n png_save_uint_32(adata, io->frames.size());\n png_save_uint_32(adata + 4, io->metadata.m.animation.num_loops);\n png_byte actl[5] = \"acTL\";\n png_write_chunk(png_ptr, actl, adata, 8);\n }\n png_byte fdata[26];\n JXL_ASSERT(W == width);\n JXL_ASSERT(H == height);\n \/\/ TODO(jon): also make this work for the non-coalesced case\n png_save_uint_32(fdata, anim_chunks++);\n png_save_uint_32(fdata + 4, width);\n png_save_uint_32(fdata + 8, height);\n png_save_uint_32(fdata + 12, 0);\n png_save_uint_32(fdata + 16, 0);\n png_save_uint_16(\n fdata + 20,\n frame.duration * io->metadata.m.animation.tps_denominator);\n png_save_uint_16(fdata + 22, io->metadata.m.animation.tps_numerator);\n fdata[24] = 1;\n fdata[25] = 0;\n png_byte fctl[5] = \"fcTL\";\n png_write_chunk(png_ptr, fctl, fdata, 26);\n }\n\n std::vector rows(height);\n for (int y = 0; y < height; ++y) {\n rows[y] = raw_bytes.data() + y * stride;\n }\n\n png_write_flush(png_ptr);\n const size_t pos = bytes->size();\n png_write_image(png_ptr, &rows[0]);\n png_write_flush(png_ptr);\n if (count > 0) {\n std::vector fdata(4);\n png_save_uint_32(fdata.data(), anim_chunks++);\n size_t p = pos;\n while (p + 8 < bytes->size()) {\n size_t len = png_get_uint_32(bytes->data() + p);\n JXL_ASSERT(bytes->operator[](p + 4) == 'I');\n JXL_ASSERT(bytes->operator[](p + 5) == 'D');\n JXL_ASSERT(bytes->operator[](p + 6) == 'A');\n JXL_ASSERT(bytes->operator[](p + 7) == 'T');\n fdata.insert(fdata.end(), bytes->data() + p + 8,\n bytes->data() + p + 8 + len);\n p += len + 12;\n }\n bytes->resize(pos);\n\n png_byte fdat[5] = \"fdAT\";\n png_write_chunk(png_ptr, fdat, fdata.data(), fdata.size());\n }\n\n count++;\n if (count == io->frames.size() || !have_anim) png_write_end(png_ptr, NULL);\n\n png_destroy_write_struct(&png_ptr, &info_ptr);\n }\n\n return true;\n}\n\n} \/\/ namespace extras\n} \/\/ namespace jxl\n<|endoftext|>"} {"text":"\/***********************************************************************\n tcp_connection.cpp - Implements the TCPConnection class.\n\n Copyright (c) 2007 by Educational Technology Resources, Inc.\n Others may also hold copyrights on code in this file. See the\n CREDITS file in the top directory of the distribution for details.\n\n This file is part of MySQL++.\n\n MySQL++ is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n MySQL++ is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with MySQL++; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301\n USA\n***********************************************************************\/\n\n#define MYSQLPP_NOT_HEADER\n#include \"common.h\"\n#include \"tcp_connection.h\"\n\n#include \"exceptions.h\"\n\n#if !defined(MYSQLPP_PLATFORM_WINDOWS)\n#\tinclude \n#endif\n\n#include \n\nusing namespace std;\n\nnamespace mysqlpp {\n\n\nbool\nTCPConnection::connect(cchar* addr, cchar* db, cchar* user, cchar* pass)\n{\n\terror_message_.clear();\n\n\tunsigned int port = 0;\n\tstring address;\n\tif (addr) {\n\t\taddress = addr;\n\t\tif (!parse_address(address, port, error_message_)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tif (error_message_.empty()) {\n\t\treturn Connection::connect(db, address.c_str(), user, pass, port);\n\t}\n\telse {\n\t\tif (throw_exceptions()) {\n\t\t\tthrow ConnectionFailed(error_message_.c_str());\n\t\t}\n\t\telse {\n\t\t\treturn false;\n\t\t}\n\t}\n}\n\n\nbool\nTCPConnection::parse_address(string& addr, unsigned int& port,\n\t\tstring& error)\n{\n\terror.clear();\n\t\n\t\/\/ Pull off service name or port number, if any\n\tstring service;\n\tif (addr[0] == '[') {\n\t\t\/\/ Might be IPv6 address plus port\/service in RFC 2732 form.\n\t\tstring::size_type pos = addr.find(']');\n\t\tif ((pos == string::npos) ||\n\t\t\t\t(addr.find(':', pos + 1) != (pos + 1)) ||\n\t\t\t\t(addr.find_first_of(\"[]\", pos + 2) != string::npos)) {\n\t\t\terror = \"Malformed IPv6 [address]:service combination\";\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/ We can separate address from port\/service now\n\t\tservice = addr.substr(pos + 2);\n\t\taddr = addr.substr(1, pos - 1);\n\n\t\t\/\/ Ensure that address part is empty or has at least two colons\n\t\tif (addr.size() &&\n\t\t\t\t(((pos = addr.find(':')) == string::npos) ||\n\t\t\t\t(addr.find(':', pos + 1) == string::npos))) {\n\t\t\terror = \"IPv6 literal needs at least two colons\";\n\t\t\treturn false;\n\t\t}\n\t}\n\telse {\n\t\t\/\/ Can only be IPv4 address, so check for 0-1 colons\n\t\tstring::size_type pos = addr.find(':');\n\t\tif (pos != string::npos) {\n\t\t\tif (addr.find(':', pos + 1) != string::npos) {\n\t\t\t\terror = \"IPv4 address:service combo can have only one colon\";\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tservice = addr.substr(pos + 1);\n\t\t\taddr = addr.substr(0, pos);\n\t\t}\n\t}\n\n\t\/\/ Turn service into a port number\n\tif (service.empty()) {\n\t\tport = 0;\n\t}\n\telse {\n\t\tif (isdigit(service[0])) {\n\t\t\tport = atoi(service.c_str());\n\t\t\tif ((port < 1) || (port > USHRT_MAX)) {\n\t\t\t\terror = \"Invalid TCP port number \" + service;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tservent* pse = getservbyname(service.c_str(), \"tcp\");\n\t\t\tif (pse) {\n\t\t\t\tport = ntohs(pse->s_port);\n\t\t\t}\n\t\t\telse {\n\t\t\t\terror = \"Failed to look up TCP service \" + service;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Ensure that there are only alphanumeric characters, dots,\n\t\/\/ dashes and colons in address. Anything else must be an error.\n\tfor (string::const_iterator it = addr.begin(); it != addr.end(); ++it) {\n\t\tstring::value_type c = *it;\n\t\tif (!(isalnum(c) || (c == '.') || (c == '-') || (c == ':'))) {\n\t\t\terror = \"Bad character '\";\n\t\t\terror += c;\n\t\t\terror += \"' in TCP\/IP address\";\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\n\n} \/\/ end namespace mysqlpp\n\nFixed a bug with non-default port numbers passed separately from server spec. It was getting zeroed incorrectly. Fix by Bart Verstraete.\/***********************************************************************\n tcp_connection.cpp - Implements the TCPConnection class.\n\n Copyright (c) 2007 by Educational Technology Resources, Inc.\n Others may also hold copyrights on code in this file. See the\n CREDITS file in the top directory of the distribution for details.\n\n This file is part of MySQL++.\n\n MySQL++ is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n MySQL++ is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with MySQL++; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301\n USA\n***********************************************************************\/\n\n#define MYSQLPP_NOT_HEADER\n#include \"common.h\"\n#include \"tcp_connection.h\"\n\n#include \"exceptions.h\"\n\n#if !defined(MYSQLPP_PLATFORM_WINDOWS)\n#\tinclude \n#endif\n\n#include \n\nusing namespace std;\n\nnamespace mysqlpp {\n\n\nbool\nTCPConnection::connect(cchar* addr, cchar* db, cchar* user, cchar* pass)\n{\n\terror_message_.clear();\n\n\tunsigned int port = 0;\n\tstring address;\n\tif (addr) {\n\t\taddress = addr;\n\t\tif (!parse_address(address, port, error_message_)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tif (error_message_.empty()) {\n\t\treturn Connection::connect(db, address.c_str(), user, pass, port);\n\t}\n\telse {\n\t\tif (throw_exceptions()) {\n\t\t\tthrow ConnectionFailed(error_message_.c_str());\n\t\t}\n\t\telse {\n\t\t\treturn false;\n\t\t}\n\t}\n}\n\n\nbool\nTCPConnection::parse_address(string& addr, unsigned int& port,\n\t\tstring& error)\n{\n\terror.clear();\n\t\n\t\/\/ Pull off service name or port number, if any\n\tstring service;\n\tif (addr[0] == '[') {\n\t\t\/\/ Might be IPv6 address plus port\/service in RFC 2732 form.\n\t\tstring::size_type pos = addr.find(']');\n\t\tif ((pos == string::npos) ||\n\t\t\t\t(addr.find(':', pos + 1) != (pos + 1)) ||\n\t\t\t\t(addr.find_first_of(\"[]\", pos + 2) != string::npos)) {\n\t\t\terror = \"Malformed IPv6 [address]:service combination\";\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/ We can separate address from port\/service now\n\t\tservice = addr.substr(pos + 2);\n\t\taddr = addr.substr(1, pos - 1);\n\n\t\t\/\/ Ensure that address part is empty or has at least two colons\n\t\tif (addr.size() &&\n\t\t\t\t(((pos = addr.find(':')) == string::npos) ||\n\t\t\t\t(addr.find(':', pos + 1) == string::npos))) {\n\t\t\terror = \"IPv6 literal needs at least two colons\";\n\t\t\treturn false;\n\t\t}\n\t}\n\telse {\n\t\t\/\/ Can only be IPv4 address, so check for 0-1 colons\n\t\tstring::size_type pos = addr.find(':');\n\t\tif (pos != string::npos) {\n\t\t\tif (addr.find(':', pos + 1) != string::npos) {\n\t\t\t\terror = \"IPv4 address:service combo can have only one colon\";\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tservice = addr.substr(pos + 1);\n\t\t\taddr = addr.substr(0, pos);\n\t\t}\n\t}\n\n\t\/\/ Turn service into a port number, if it was given. If not, don't\n\t\/\/ overwrite port because it could have a legal value passed in from\n\t\/\/ Connection.\n\tif (!service.empty()) {\n\t\tif (isdigit(service[0])) {\n\t\t\tport = atoi(service.c_str());\n\t\t\tif ((port < 1) || (port > USHRT_MAX)) {\n\t\t\t\terror = \"Invalid TCP port number \" + service;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tservent* pse = getservbyname(service.c_str(), \"tcp\");\n\t\t\tif (pse) {\n\t\t\t\tport = ntohs(pse->s_port);\n\t\t\t}\n\t\t\telse {\n\t\t\t\terror = \"Failed to look up TCP service \" + service;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Ensure that there are only alphanumeric characters, dots,\n\t\/\/ dashes and colons in address. Anything else must be an error.\n\tfor (string::const_iterator it = addr.begin(); it != addr.end(); ++it) {\n\t\tstring::value_type c = *it;\n\t\tif (!(isalnum(c) || (c == '.') || (c == '-') || (c == ':'))) {\n\t\t\terror = \"Bad character '\";\n\t\t\terror += c;\n\t\t\terror += \"' in TCP\/IP address\";\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\n\n} \/\/ end namespace mysqlpp\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 BitPay Inc.\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \"univalue.h\"\n#include \"univalue_escapes.h\"\n\nusing namespace std;\n\nstatic string json_escape(const string& inS)\n{\n string outS;\n outS.reserve(inS.size() * 2);\n\n for (unsigned int i = 0; i < inS.size(); i++) {\n unsigned char ch = inS[i];\n const char *escStr = escapes[ch];\n\n if (escStr)\n outS += escStr;\n else\n outS += ch;\n }\n\n return outS;\n}\n\nstring UniValue::write(unsigned int prettyIndent,\n unsigned int indentLevel) const\n{\n string s;\n s.reserve(1024);\n\n unsigned int modIndent = indentLevel;\n if (modIndent == 0)\n modIndent = 1;\n\n switch (typ) {\n case VNULL:\n s += \"null\";\n break;\n case VOBJ:\n writeObject(prettyIndent, modIndent, s);\n break;\n case VARR:\n writeArray(prettyIndent, modIndent, s);\n break;\n case VSTR:\n s += \"\\\"\" + json_escape(val) + \"\\\"\";\n break;\n case VNUM:\n s += val;\n break;\n case VBOOL:\n s += (val == \"1\" ? \"true\" : \"false\");\n break;\n }\n\n return s;\n}\n\nstatic void indentStr(unsigned int prettyIndent, unsigned int indentLevel, string& s)\n{\n s.append(prettyIndent * indentLevel, ' ');\n}\n\nvoid UniValue::writeArray(unsigned int prettyIndent, unsigned int indentLevel, string& s) const\n{\n s += \"[\";\n if (prettyIndent)\n s += \"\\n\";\n\n for (unsigned int i = 0; i < values.size(); i++) {\n if (prettyIndent)\n indentStr(prettyIndent, indentLevel, s);\n s += values[i].write(prettyIndent, indentLevel + 1);\n if (i != (values.size() - 1)) {\n s += \",\";\n if (prettyIndent)\n s += \" \";\n }\n if (prettyIndent)\n s += \"\\n\";\n }\n\n if (prettyIndent)\n indentStr(prettyIndent, indentLevel - 1, s);\n s += \"]\";\n}\n\nvoid UniValue::writeObject(unsigned int prettyIndent, unsigned int indentLevel, string& s) const\n{\n s += \"{\";\n if (prettyIndent)\n s += \"\\n\";\n\n for (unsigned int i = 0; i < keys.size(); i++) {\n if (prettyIndent)\n indentStr(prettyIndent, indentLevel, s);\n s += \"\\\"\" + json_escape(keys[i]) + \"\\\":\";\n if (prettyIndent)\n s += \" \";\n s += values.at(i).write(prettyIndent, indentLevel + 1);\n if (i != (values.size() - 1))\n s += \",\";\n if (prettyIndent)\n s += \"\\n\";\n }\n\n if (prettyIndent)\n indentStr(prettyIndent, indentLevel - 1, s);\n s += \"}\";\n}\n\nRemove trailing whitespace from JSON export\/\/ Copyright 2014 BitPay Inc.\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \"univalue.h\"\n#include \"univalue_escapes.h\"\n\nusing namespace std;\n\nstatic string json_escape(const string& inS)\n{\n string outS;\n outS.reserve(inS.size() * 2);\n\n for (unsigned int i = 0; i < inS.size(); i++) {\n unsigned char ch = inS[i];\n const char *escStr = escapes[ch];\n\n if (escStr)\n outS += escStr;\n else\n outS += ch;\n }\n\n return outS;\n}\n\nstring UniValue::write(unsigned int prettyIndent,\n unsigned int indentLevel) const\n{\n string s;\n s.reserve(1024);\n\n unsigned int modIndent = indentLevel;\n if (modIndent == 0)\n modIndent = 1;\n\n switch (typ) {\n case VNULL:\n s += \"null\";\n break;\n case VOBJ:\n writeObject(prettyIndent, modIndent, s);\n break;\n case VARR:\n writeArray(prettyIndent, modIndent, s);\n break;\n case VSTR:\n s += \"\\\"\" + json_escape(val) + \"\\\"\";\n break;\n case VNUM:\n s += val;\n break;\n case VBOOL:\n s += (val == \"1\" ? \"true\" : \"false\");\n break;\n }\n\n return s;\n}\n\nstatic void indentStr(unsigned int prettyIndent, unsigned int indentLevel, string& s)\n{\n s.append(prettyIndent * indentLevel, ' ');\n}\n\nvoid UniValue::writeArray(unsigned int prettyIndent, unsigned int indentLevel, string& s) const\n{\n s += \"[\";\n if (prettyIndent)\n s += \"\\n\";\n\n for (unsigned int i = 0; i < values.size(); i++) {\n if (prettyIndent)\n indentStr(prettyIndent, indentLevel, s);\n s += values[i].write(prettyIndent, indentLevel + 1);\n if (i != (values.size() - 1)) {\n s += \",\";\n }\n if (prettyIndent)\n s += \"\\n\";\n }\n\n if (prettyIndent)\n indentStr(prettyIndent, indentLevel - 1, s);\n s += \"]\";\n}\n\nvoid UniValue::writeObject(unsigned int prettyIndent, unsigned int indentLevel, string& s) const\n{\n s += \"{\";\n if (prettyIndent)\n s += \"\\n\";\n\n for (unsigned int i = 0; i < keys.size(); i++) {\n if (prettyIndent)\n indentStr(prettyIndent, indentLevel, s);\n s += \"\\\"\" + json_escape(keys[i]) + \"\\\":\";\n if (prettyIndent)\n s += \" \";\n s += values.at(i).write(prettyIndent, indentLevel + 1);\n if (i != (values.size() - 1))\n s += \",\";\n if (prettyIndent)\n s += \"\\n\";\n }\n\n if (prettyIndent)\n indentStr(prettyIndent, indentLevel - 1, s);\n s += \"}\";\n}\n\n<|endoftext|>"} {"text":"\/*\n Copyright (c) 2006 Volker Krause \n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include \"monitor.h\"\n#include \"notificationmanagerinterface.h\"\n\n#include \n#include \n\n#include \n\nusing namespace PIM;\n\nclass PIM::MonitorPrivate\n{\n public:\n org::kde::Akonadi::NotificationManager *nm;\n QList collections;\n\n bool isCollectionMonitored( const QByteArray &path )\n {\n foreach ( const QByteArray ba, collections ) {\n if ( path.startsWith( ba ) )\n return true;\n }\n return false;\n }\n};\n\nPIM::Monitor::Monitor( QObject *parent ) :\n QObject( parent ),\n d( new MonitorPrivate() )\n{\n connectToNotificationManager();\n}\n\nPIM::Monitor::~Monitor()\n{\n delete d->nm;\n delete d;\n}\n\nvoid PIM::Monitor::monitorCollection( const QByteArray & path )\n{\n d->collections.append( path );\n if ( connectToNotificationManager() )\n d->nm->monitorCollection( path );\n}\n\nvoid PIM::Monitor::monitorItem( const DataReference & ref )\n{\n if ( connectToNotificationManager() )\n d->nm->monitorItem( ref.persistanceID().toLatin1() );\n}\n\nvoid PIM::Monitor::slotItemChanged( const QByteArray & uid, const QByteArray & collection )\n{\n if ( d->isCollectionMonitored( collection ) )\n emit itemChanged( DataReference( uid, QString() ) );\n}\n\nvoid PIM::Monitor::slotItemAdded( const QByteArray & uid, const QByteArray & collection )\n{\n if ( d->isCollectionMonitored( collection ) )\n emit itemAdded( DataReference( uid, QString() ) );\n}\n\nvoid PIM::Monitor::slotItemRemoved( const QByteArray & uid, const QByteArray & collection )\n{\n if ( d->isCollectionMonitored( collection ) )\n emit itemRemoved( DataReference( uid, QString() ) );\n}\n\nvoid PIM::Monitor::slotCollectionChanged( const QByteArray & path )\n{\n if ( d->isCollectionMonitored( path ) )\n emit collectionChanged( path );\n}\n\nvoid PIM::Monitor::slotCollectionAdded( const QByteArray & path )\n{\n if ( d->isCollectionMonitored( path ) )\n emit collectionAdded( path );\n}\n\nvoid PIM::Monitor::slotCollectionRemoved( const QByteArray & path )\n{\n if ( d->isCollectionMonitored( path ) )\n emit collectionRemoved( path );\n}\n\nbool PIM::Monitor::connectToNotificationManager( )\n{\n if ( !d->nm )\n d->nm = QDBus::sessionBus().findInterface(\"org.kde.pim.Akonadi.NotificationManager\", \"\/\");\n else\n return true;\n\n if ( !d->nm ) {\n qWarning() << \"Unable to connect to notification manager\";\n } else {\n connect( d->nm, SIGNAL(itemChanged(QByteArray,QByteArray)), SLOT(slotItemChanged(QByteArray,QByteArray)) );\n connect( d->nm, SIGNAL(itemAdded(QByteArray,QByteArray)), SLOT(slotItemAdded(QByteArray,QByteArray)) );\n connect( d->nm, SIGNAL(itemRemoved(QByteArray,QByteArray)), SLOT(slotItemRemoved(QByteArray,QByteArray)) );\n connect( d->nm, SIGNAL(collectionChanged(QByteArray)), SLOT(slotCollectionChanged(QByteArray)) );\n connect( d->nm, SIGNAL(collectionAdded(QByteArray)), SLOT(slotCollectionAdded(QByteArray)) );\n connect( d->nm, SIGNAL(collectionRemoved(QByteArray)), SLOT(slotCollectionRemoved(QByteArray)) );\n return true;\n }\n return false;\n}\n\n#include \"monitor.moc\"\nFix typo.\/*\n Copyright (c) 2006 Volker Krause \n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include \"monitor.h\"\n#include \"notificationmanagerinterface.h\"\n\n#include \n#include \n\n#include \n\nusing namespace PIM;\n\nclass PIM::MonitorPrivate\n{\n public:\n org::kde::Akonadi::NotificationManager *nm;\n QList collections;\n\n bool isCollectionMonitored( const QByteArray &path )\n {\n foreach ( const QByteArray ba, collections ) {\n if ( path.startsWith( ba ) )\n return true;\n }\n return false;\n }\n};\n\nPIM::Monitor::Monitor( QObject *parent ) :\n QObject( parent ),\n d( new MonitorPrivate() )\n{\n connectToNotificationManager();\n}\n\nPIM::Monitor::~Monitor()\n{\n delete d->nm;\n delete d;\n}\n\nvoid PIM::Monitor::monitorCollection( const QByteArray & path )\n{\n d->collections.append( path );\n if ( connectToNotificationManager() )\n d->nm->monitorCollection( path );\n}\n\nvoid PIM::Monitor::monitorItem( const DataReference & ref )\n{\n if ( connectToNotificationManager() )\n d->nm->monitorItem( ref.persistanceID().toLatin1() );\n}\n\nvoid PIM::Monitor::slotItemChanged( const QByteArray & uid, const QByteArray & collection )\n{\n if ( d->isCollectionMonitored( collection ) )\n emit itemChanged( DataReference( uid, QString() ) );\n}\n\nvoid PIM::Monitor::slotItemAdded( const QByteArray & uid, const QByteArray & collection )\n{\n if ( d->isCollectionMonitored( collection ) )\n emit itemAdded( DataReference( uid, QString() ) );\n}\n\nvoid PIM::Monitor::slotItemRemoved( const QByteArray & uid, const QByteArray & collection )\n{\n if ( d->isCollectionMonitored( collection ) )\n emit itemRemoved( DataReference( uid, QString() ) );\n}\n\nvoid PIM::Monitor::slotCollectionChanged( const QByteArray & path )\n{\n if ( d->isCollectionMonitored( path ) )\n emit collectionChanged( path );\n}\n\nvoid PIM::Monitor::slotCollectionAdded( const QByteArray & path )\n{\n if ( d->isCollectionMonitored( path ) )\n emit collectionAdded( path );\n}\n\nvoid PIM::Monitor::slotCollectionRemoved( const QByteArray & path )\n{\n if ( d->isCollectionMonitored( path ) )\n emit collectionRemoved( path );\n}\n\nbool PIM::Monitor::connectToNotificationManager( )\n{\n if ( !d->nm )\n d->nm = QDBus::sessionBus().findInterface(\"org.kde.Akonadi.NotificationManager\", \"\/\");\n else\n return true;\n\n if ( !d->nm ) {\n qWarning() << \"Unable to connect to notification manager\";\n } else {\n connect( d->nm, SIGNAL(itemChanged(QByteArray,QByteArray)), SLOT(slotItemChanged(QByteArray,QByteArray)) );\n connect( d->nm, SIGNAL(itemAdded(QByteArray,QByteArray)), SLOT(slotItemAdded(QByteArray,QByteArray)) );\n connect( d->nm, SIGNAL(itemRemoved(QByteArray,QByteArray)), SLOT(slotItemRemoved(QByteArray,QByteArray)) );\n connect( d->nm, SIGNAL(collectionChanged(QByteArray)), SLOT(slotCollectionChanged(QByteArray)) );\n connect( d->nm, SIGNAL(collectionAdded(QByteArray)), SLOT(slotCollectionAdded(QByteArray)) );\n connect( d->nm, SIGNAL(collectionRemoved(QByteArray)), SLOT(slotCollectionRemoved(QByteArray)) );\n return true;\n }\n return false;\n}\n\n#include \"monitor.moc\"\n<|endoftext|>"} {"text":"#include \"Precompiled.h\"\n#include \"Slider.h\"\n#include \"ElementManager.h\"\n\nnamespace libgui\n{\n\tvoid Slider::Init()\n\t{\n\t\tm_track = make_shared();\n\t\tthis->AddChild(m_track);\n\n\t\tm_thumb = make_shared(\n\t\t\tdynamic_pointer_cast(shared_from_this()),\n\t\t\tm_track);\n\t\tm_track->AddChild(m_thumb);\n\t}\n\n\tconst double& Slider::GetValue() const\n\t{\n\t\treturn m_value;\n\t}\n\n\tvoid Slider::SetValue(double value)\n\t{\n\t\tm_value = value;\n\t}\n\n\tconst double& Slider::GetThumbHeight() const\n\t{\n\t\treturn m_thumbHeight;\n\t}\n\n\tvoid Slider::SetThumbHeight(double thumbHeight)\n\t{\n\t\tm_thumbHeight = thumbHeight;\n\t}\n\n\tconst function)>& Slider::GetValueChangedCallback() const\n\t{\n\t\treturn m_valueChangedCallback;\n\t}\n\n\tvoid Slider::SetValueChangedCallback(const function)>& valueChangedCallback)\n\t{\n\t\tm_valueChangedCallback = valueChangedCallback;\n\t}\n\n\tconst shared_ptr& Slider::GetThumb() const\n\t{\n\t\treturn m_thumb;\n\t}\n\n\tconst shared_ptr& Slider::GetTrack() const\n\t{\n\t\treturn m_track;\n\t}\n\n\tSlider::Thumb::Thumb(weak_ptr slider, weak_ptr track)\n\t\t: m_slider(slider),\n\t\tm_track(track)\n\t{\n\t}\n\n\tvoid Slider::Thumb::Arrange()\n\t{\n\t\tif (auto slider = m_slider.lock())\n\t\t{\n\t\t\tauto p = GetParent();\n\t\t\tSetLeft(p->GetLeft()); SetRight(p->GetRight());\n\t\t\tauto thumbHeight = slider->GetThumbHeight();\n\t\t\tauto boundsTop = p->GetTop();\n\t\t\tauto boundsHeight = p->GetHeight() - thumbHeight;\n\t\t\tauto top = boundsTop + (slider->GetRawFromValue() * boundsHeight);\n\t\t\tSetTop(round(top)); SetBottom(round(top + thumbHeight));\n\t\t}\n\t}\n\n\tvoid Slider::Thumb::NotifyMouseEnter()\n\t{\n\t\tm_isOver = true;\n\n\t\tif (IsCapturing())\n\t\t{\n\t\t\tm_isPressed = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_isHot = true;\n\t\t}\n\t}\n\n\tvoid Slider::Thumb::NotifyMouseLeave()\n\t{\n\t\tm_isOver = false;\n\n\t\tif (IsCapturing())\n\t\t{\n\t\t\tm_isPressed = false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_isHot = false;\n\t\t}\n\t}\n\n\tvoid Slider::Thumb::NotifyMouseDown(Location location)\n\t{\n\t\tm_isHot = true;\n\t\tm_isPressed = true;\n\n\t\tm_anchorOffset = location.y - GetTop();\n\n\t\tGetElementManager()->RequestCapture(dynamic_pointer_cast(shared_from_this()));\n\t}\n\n\tvoid Slider::Thumb::NotifyMouseUp(Location location)\n\t{\n\t\tm_isPressed = false;\n\t\tif (IsCapturing())\n\t\t{\n\t\t\tif (!m_isOver)\n\t\t\t{\n\t\t\t\tm_isHot = false;\n\t\t\t}\n\n\t\t\tGetElementManager()->ReleaseCapture();\n\t\t}\n\t}\n\n\tvoid Slider::Thumb::NotifyMouseMove(Location location, bool& updateScreen)\n\t{\n\t\tif (IsCapturing())\n\t\t{\n\t\t\tauto slider = m_slider.lock();\n\t\t\tauto track = m_track.lock();\n\t\t\tif (slider && track)\n\t\t\t{\n\t\t\t\tauto offsetPercent = ((location.y - m_anchorOffset) - track->GetTop()) \/ \n\t\t\t\t\t(track->GetHeight() - slider->GetThumbHeight());\n\t\t\t\toffsetPercent = max(0.0, offsetPercent);\n\t\t\t\toffsetPercent = min(1.0, offsetPercent);\n\t\t\t\tif (slider->GetRawFromValue() != offsetPercent)\n\t\t\t\t{\n\t\t\t\t\tslider->SetValueFromRaw(offsetPercent);\n\t\t\t\t\tupdateScreen = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tupdateScreen = false;\n\t\treturn;\n\t}\n\n\tconst bool& Slider::Thumb::GetIsPressed() const\n\t{\n\t\treturn m_isPressed;\n\t}\n\n\tconst bool& Slider::Thumb::GetIsHot() const\n\t{\n\t\treturn m_isHot;\n\t}\n\n\tconst weak_ptr& Slider::Thumb::GetSlider() const\n\t{\n\t\treturn m_slider;\n\t}\n\n\tvoid Slider::OnValueChanged()\n\t{\n\t\tif (m_valueChangedCallback)\n\t\t{\n\t\t\tm_valueChangedCallback(dynamic_pointer_cast(shared_from_this()));\n\t\t}\n\t}\n\n\tdouble Slider::GetRawFromValue()\n\t{\n\t\treturn 1.0 - GetValue();\n\t}\n\n\tvoid Slider::SetValueFromRaw(double raw)\n\t{\n\t\tSetValue(1.0 - raw);\n\t}\n}Slider properly calls OnValueChanged()#include \"Precompiled.h\"\n#include \"Slider.h\"\n#include \"ElementManager.h\"\n\nnamespace libgui\n{\n\tvoid Slider::Init()\n\t{\n\t\tm_track = make_shared();\n\t\tthis->AddChild(m_track);\n\n\t\tm_thumb = make_shared(\n\t\t\tdynamic_pointer_cast(shared_from_this()),\n\t\t\tm_track);\n\t\tm_track->AddChild(m_thumb);\n\t}\n\n\tconst double& Slider::GetValue() const\n\t{\n\t\treturn m_value;\n\t}\n\n\tvoid Slider::SetValue(double value)\n\t{\n\t\tif (value != m_value)\n\t\t{\n\t\t\tOnValueChanged();\n\t\t}\n\n\t\tm_value = value;\n\t}\n\n\tconst double& Slider::GetThumbHeight() const\n\t{\n\t\treturn m_thumbHeight;\n\t}\n\n\tvoid Slider::SetThumbHeight(double thumbHeight)\n\t{\n\t\tm_thumbHeight = thumbHeight;\n\t}\n\n\tconst function)>& Slider::GetValueChangedCallback() const\n\t{\n\t\treturn m_valueChangedCallback;\n\t}\n\n\tvoid Slider::SetValueChangedCallback(const function)>& valueChangedCallback)\n\t{\n\t\tm_valueChangedCallback = valueChangedCallback;\n\t}\n\n\tconst shared_ptr& Slider::GetThumb() const\n\t{\n\t\treturn m_thumb;\n\t}\n\n\tconst shared_ptr& Slider::GetTrack() const\n\t{\n\t\treturn m_track;\n\t}\n\n\tSlider::Thumb::Thumb(weak_ptr slider, weak_ptr track)\n\t\t: m_slider(slider),\n\t\tm_track(track)\n\t{\n\t}\n\n\tvoid Slider::Thumb::Arrange()\n\t{\n\t\tif (auto slider = m_slider.lock())\n\t\t{\n\t\t\tauto p = GetParent();\n\t\t\tSetLeft(p->GetLeft()); SetRight(p->GetRight());\n\t\t\tauto thumbHeight = slider->GetThumbHeight();\n\t\t\tauto boundsTop = p->GetTop();\n\t\t\tauto boundsHeight = p->GetHeight() - thumbHeight;\n\t\t\tauto top = boundsTop + (slider->GetRawFromValue() * boundsHeight);\n\t\t\tSetTop(round(top)); SetBottom(round(top + thumbHeight));\n\t\t}\n\t}\n\n\tvoid Slider::Thumb::NotifyMouseEnter()\n\t{\n\t\tm_isOver = true;\n\n\t\tif (IsCapturing())\n\t\t{\n\t\t\tm_isPressed = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_isHot = true;\n\t\t}\n\t}\n\n\tvoid Slider::Thumb::NotifyMouseLeave()\n\t{\n\t\tm_isOver = false;\n\n\t\tif (IsCapturing())\n\t\t{\n\t\t\tm_isPressed = false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_isHot = false;\n\t\t}\n\t}\n\n\tvoid Slider::Thumb::NotifyMouseDown(Location location)\n\t{\n\t\tm_isHot = true;\n\t\tm_isPressed = true;\n\n\t\tm_anchorOffset = location.y - GetTop();\n\n\t\tGetElementManager()->RequestCapture(dynamic_pointer_cast(shared_from_this()));\n\t}\n\n\tvoid Slider::Thumb::NotifyMouseUp(Location location)\n\t{\n\t\tm_isPressed = false;\n\t\tif (IsCapturing())\n\t\t{\n\t\t\tif (!m_isOver)\n\t\t\t{\n\t\t\t\tm_isHot = false;\n\t\t\t}\n\n\t\t\tGetElementManager()->ReleaseCapture();\n\t\t}\n\t}\n\n\tvoid Slider::Thumb::NotifyMouseMove(Location location, bool& updateScreen)\n\t{\n\t\tif (IsCapturing())\n\t\t{\n\t\t\tauto slider = m_slider.lock();\n\t\t\tauto track = m_track.lock();\n\t\t\tif (slider && track)\n\t\t\t{\n\t\t\t\tauto offsetPercent = ((location.y - m_anchorOffset) - track->GetTop()) \/ \n\t\t\t\t\t(track->GetHeight() - slider->GetThumbHeight());\n\t\t\t\toffsetPercent = max(0.0, offsetPercent);\n\t\t\t\toffsetPercent = min(1.0, offsetPercent);\n\t\t\t\tif (slider->GetRawFromValue() != offsetPercent)\n\t\t\t\t{\n\t\t\t\t\tslider->SetValueFromRaw(offsetPercent);\n\t\t\t\t\tupdateScreen = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tupdateScreen = false;\n\t\treturn;\n\t}\n\n\tconst bool& Slider::Thumb::GetIsPressed() const\n\t{\n\t\treturn m_isPressed;\n\t}\n\n\tconst bool& Slider::Thumb::GetIsHot() const\n\t{\n\t\treturn m_isHot;\n\t}\n\n\tconst weak_ptr& Slider::Thumb::GetSlider() const\n\t{\n\t\treturn m_slider;\n\t}\n\n\tvoid Slider::OnValueChanged()\n\t{\n\t\tif (m_valueChangedCallback)\n\t\t{\n\t\t\tm_valueChangedCallback(dynamic_pointer_cast(shared_from_this()));\n\t\t}\n\t}\n\n\tdouble Slider::GetRawFromValue()\n\t{\n\t\treturn 1.0 - GetValue();\n\t}\n\n\tvoid Slider::SetValueFromRaw(double raw)\n\t{\n\t\tSetValue(1.0 - raw);\n\t}\n}<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ The DomAutocompleteTests in this file are responsible for ensuring the\n\/\/ abstract dom autocomplete framework is correctly responding to events and\n\/\/ delegating to appropriate places. This means concrete implementations should\n\/\/ focus only on testing the code actually written for that implementation and\n\/\/ those tests should be completely decoupled from WebCore::Event.\n\n#include \n\n#include \"config.h\"\n\n#include \"base\/compiler_specific.h\"\n\nMSVC_PUSH_WARNING_LEVEL(0);\n#include \"HTMLInputElement.h\"\n#include \"HTMLFormElement.h\"\n#include \"Document.h\"\n#include \"Frame.h\"\n#include \"Editor.h\"\n#include \"EventNames.h\"\n#include \"Event.h\"\n#include \"EventListener.h\"\n#include \nMSVC_POP_WARNING();\n\n#undef LOG\n\n#include \"webkit\/glue\/autocomplete_input_listener.h\"\n#include \"webkit\/glue\/webframe.h\"\n#include \"webkit\/glue\/webframe_impl.h\"\n#include \"webkit\/glue\/webview.h\"\n#include \"webkit\/tools\/test_shell\/test_shell_test.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nusing WebCore::Event;\n\nnamespace webkit_glue {\n\nclass TestAutocompleteBodyListener : public AutocompleteBodyListener {\n public:\n TestAutocompleteBodyListener() {\n }\n\n void SetCaretAtEnd(WebCore::HTMLInputElement* element, bool value) {\n std::vector::iterator iter =\n std::find(caret_at_end_elements_.begin(), caret_at_end_elements_.end(),\n element);\n if (value) {\n if (iter == caret_at_end_elements_.end())\n caret_at_end_elements_.push_back(element);\n } else {\n if (iter != caret_at_end_elements_.end())\n caret_at_end_elements_.erase(iter);\n }\n }\n\n void ResetTestState() {\n caret_at_end_elements_.clear();\n }\n\n protected:\n \/\/ AutocompleteBodyListener override.\n virtual bool IsCaretAtEndOfText(WebCore::HTMLInputElement* element,\n size_t input_length,\n size_t previous_length) const {\n return std::find(caret_at_end_elements_.begin(), \n caret_at_end_elements_.end(),\n element) != caret_at_end_elements_.end();\n }\n\n private:\n \/\/ List of elements for which the caret is at the end of the text.\n std::vector caret_at_end_elements_;\n};\n\nclass TestAutocompleteInputListener : public AutocompleteInputListener {\n public:\n TestAutocompleteInputListener()\n : blurred_(false),\n did_request_inline_autocomplete_(false) {\n }\n\n void ResetTestState() {\n blurred_ = false;\n did_request_inline_autocomplete_ = false;\n }\n\n bool blurred() const { return blurred_; }\n bool did_request_inline_autocomplete() const {\n return did_request_inline_autocomplete_;\n }\n\n virtual void OnBlur(WebCore::HTMLInputElement* element,\n const std::wstring& user_input) {\n blurred_ = true;\n }\n virtual void OnInlineAutocompleteNeeded(WebCore::HTMLInputElement* element,\n const std::wstring& user_input) {\n did_request_inline_autocomplete_ = true;\n }\n\n private:\n bool blurred_;\n bool did_request_inline_autocomplete_;\n};\n\nnamespace {\n\nclass DomAutocompleteTests : public TestShellTest {\n public:\n virtual void SetUp() {\n TestShellTest::SetUp();\n \/\/ We need a document in order to create HTMLInputElements.\n WebView* view = test_shell_->webView();\n WebFrameImpl* frame = static_cast(view->GetMainFrame());\n document_ = frame->frame()->document();\n }\n\n void FireAndHandleInputEvent(AutocompleteBodyListener* listener,\n WebCore::HTMLInputElement* element) {\n RefPtr event(Event::create(WebCore::eventNames().inputEvent,\n false, false));\n event->setTarget(element);\n listener->handleEvent(event.get(), false);\n }\n\n void SimulateTypedInput(TestAutocompleteBodyListener* listener,\n WebCore::HTMLInputElement* element,\n const std::wstring& new_input,\n bool caret_at_end) {\n element->setValue(StdWStringToString(new_input));\n listener->SetCaretAtEnd(element, caret_at_end);\n FireAndHandleInputEvent(listener, element);\n }\n\n WebCore::Document* document_;\n};\n} \/\/ namespace\n\nTEST_F(DomAutocompleteTests, OnBlur) {\n RefPtr ignored_element =\n new WebCore::HTMLInputElement(document_);\n RefPtr listened_element =\n new WebCore::HTMLInputElement(document_);\n RefPtr body_listener =\n new TestAutocompleteBodyListener;\n TestAutocompleteInputListener* listener = new TestAutocompleteInputListener();\n \/\/ body_listener takes ownership of the listener.\n body_listener->AddInputListener(listened_element.get(), listener);\n\n \/\/ Simulate a blur event to the element we are not listening to.\n \/\/ Our listener should not be notified.\n RefPtr event(Event::create(WebCore::eventNames().DOMFocusOutEvent,\n false, false));\n event->setTarget(ignored_element.get());\n body_listener->handleEvent(event.get(), false);\n EXPECT_FALSE(listener->blurred());\n \n \/\/ Now simulate the event on the input element we are listening to.\n event->setTarget(listened_element.get());\n body_listener->handleEvent(event.get(), false);\n EXPECT_TRUE(listener->blurred());\n}\n\nTEST_F(DomAutocompleteTests, InlineAutocompleteTriggeredByInputEvent) {\n RefPtr ignored_element =\n new WebCore::HTMLInputElement(document_);\n RefPtr listened_element =\n new WebCore::HTMLInputElement(document_);\n RefPtr body_listener =\n new TestAutocompleteBodyListener;\n\n TestAutocompleteInputListener* listener = new TestAutocompleteInputListener();\n body_listener->AddInputListener(listened_element.get(), listener);\n\n \/\/ Simulate an inputEvent by setting the value and artificially firing evt.\n \/\/ The user typed 'g'.\n SimulateTypedInput(body_listener.get(), ignored_element.get(), L\"g\", true);\n EXPECT_FALSE(listener->did_request_inline_autocomplete());\n SimulateTypedInput(body_listener.get(), listened_element.get(), L\"g\", true);\n EXPECT_TRUE(listener->did_request_inline_autocomplete());\n}\n\nTEST_F(DomAutocompleteTests, InlineAutocompleteHeuristics) {\n RefPtr input_element =\n new WebCore::HTMLInputElement(document_);\n RefPtr body_listener =\n new TestAutocompleteBodyListener();\n\n TestAutocompleteInputListener* listener = new TestAutocompleteInputListener();\n body_listener->AddInputListener(input_element.get(), listener);\n\n \/\/ Simulate a user entering some text, and then backspacing to remove\n \/\/ a character.\n SimulateTypedInput(body_listener.get(), input_element.get(), L\"g\", true);\n EXPECT_TRUE(listener->did_request_inline_autocomplete());\n listener->ResetTestState();\n body_listener->ResetTestState();\n\n SimulateTypedInput(body_listener.get(), input_element.get(), L\"go\", true);\n EXPECT_TRUE(listener->did_request_inline_autocomplete());\n listener->ResetTestState();\n body_listener->ResetTestState();\n\n SimulateTypedInput(body_listener.get(), input_element.get(), L\"g\", true);\n EXPECT_FALSE(listener->did_request_inline_autocomplete());\n listener->ResetTestState();\n body_listener->ResetTestState();\n\n \/\/ Now simulate the user moving the cursor to a position other than the end,\n \/\/ and adding text.\n SimulateTypedInput(body_listener.get(), input_element.get(), L\"og\", false);\n EXPECT_FALSE(listener->did_request_inline_autocomplete());\n listener->ResetTestState();\n body_listener->ResetTestState();\n\n \/\/ Test that same input doesn't trigger autocomplete.\n SimulateTypedInput(body_listener.get(), input_element.get(), L\"og\", true);\n EXPECT_FALSE(listener->did_request_inline_autocomplete());\n listener->ResetTestState();\n body_listener->ResetTestState();\n}\n\n} \/\/ webkit_glue\nAutocompleteBodyListener is created with a ref count of 1, so we need to do an adoptRef before assigning it to a RefPtr, otherwise it is leaked.\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ The DomAutocompleteTests in this file are responsible for ensuring the\n\/\/ abstract dom autocomplete framework is correctly responding to events and\n\/\/ delegating to appropriate places. This means concrete implementations should\n\/\/ focus only on testing the code actually written for that implementation and\n\/\/ those tests should be completely decoupled from WebCore::Event.\n\n#include \n\n#include \"config.h\"\n\n#include \"base\/compiler_specific.h\"\n\nMSVC_PUSH_WARNING_LEVEL(0);\n#include \"HTMLInputElement.h\"\n#include \"HTMLFormElement.h\"\n#include \"Document.h\"\n#include \"Frame.h\"\n#include \"Editor.h\"\n#include \"EventNames.h\"\n#include \"Event.h\"\n#include \"EventListener.h\"\n#include \nMSVC_POP_WARNING();\n\n#undef LOG\n\n#include \"webkit\/glue\/autocomplete_input_listener.h\"\n#include \"webkit\/glue\/webframe.h\"\n#include \"webkit\/glue\/webframe_impl.h\"\n#include \"webkit\/glue\/webview.h\"\n#include \"webkit\/tools\/test_shell\/test_shell_test.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nusing WebCore::Event;\n\nnamespace webkit_glue {\n\nclass TestAutocompleteBodyListener : public AutocompleteBodyListener {\n public:\n TestAutocompleteBodyListener() {\n }\n\n void SetCaretAtEnd(WebCore::HTMLInputElement* element, bool value) {\n std::vector::iterator iter =\n std::find(caret_at_end_elements_.begin(), caret_at_end_elements_.end(),\n element);\n if (value) {\n if (iter == caret_at_end_elements_.end())\n caret_at_end_elements_.push_back(element);\n } else {\n if (iter != caret_at_end_elements_.end())\n caret_at_end_elements_.erase(iter);\n }\n }\n\n void ResetTestState() {\n caret_at_end_elements_.clear();\n }\n\n protected:\n \/\/ AutocompleteBodyListener override.\n virtual bool IsCaretAtEndOfText(WebCore::HTMLInputElement* element,\n size_t input_length,\n size_t previous_length) const {\n return std::find(caret_at_end_elements_.begin(), \n caret_at_end_elements_.end(),\n element) != caret_at_end_elements_.end();\n }\n\n private:\n \/\/ List of elements for which the caret is at the end of the text.\n std::vector caret_at_end_elements_;\n};\n\nclass TestAutocompleteInputListener : public AutocompleteInputListener {\n public:\n TestAutocompleteInputListener()\n : blurred_(false),\n did_request_inline_autocomplete_(false) {\n }\n\n void ResetTestState() {\n blurred_ = false;\n did_request_inline_autocomplete_ = false;\n }\n\n bool blurred() const { return blurred_; }\n bool did_request_inline_autocomplete() const {\n return did_request_inline_autocomplete_;\n }\n\n virtual void OnBlur(WebCore::HTMLInputElement* element,\n const std::wstring& user_input) {\n blurred_ = true;\n }\n virtual void OnInlineAutocompleteNeeded(WebCore::HTMLInputElement* element,\n const std::wstring& user_input) {\n did_request_inline_autocomplete_ = true;\n }\n\n private:\n bool blurred_;\n bool did_request_inline_autocomplete_;\n};\n\nnamespace {\n\nclass DomAutocompleteTests : public TestShellTest {\n public:\n virtual void SetUp() {\n TestShellTest::SetUp();\n \/\/ We need a document in order to create HTMLInputElements.\n WebView* view = test_shell_->webView();\n WebFrameImpl* frame = static_cast(view->GetMainFrame());\n document_ = frame->frame()->document();\n }\n\n void FireAndHandleInputEvent(AutocompleteBodyListener* listener,\n WebCore::HTMLInputElement* element) {\n RefPtr event(Event::create(WebCore::eventNames().inputEvent,\n false, false));\n event->setTarget(element);\n listener->handleEvent(event.get(), false);\n }\n\n void SimulateTypedInput(TestAutocompleteBodyListener* listener,\n WebCore::HTMLInputElement* element,\n const std::wstring& new_input,\n bool caret_at_end) {\n element->setValue(StdWStringToString(new_input));\n listener->SetCaretAtEnd(element, caret_at_end);\n FireAndHandleInputEvent(listener, element);\n }\n\n WebCore::Document* document_;\n};\n} \/\/ namespace\n\nTEST_F(DomAutocompleteTests, OnBlur) {\n RefPtr ignored_element =\n new WebCore::HTMLInputElement(document_);\n RefPtr listened_element =\n new WebCore::HTMLInputElement(document_);\n RefPtr body_listener =\n adoptRef(new TestAutocompleteBodyListener);\n TestAutocompleteInputListener* listener = new TestAutocompleteInputListener();\n \/\/ body_listener takes ownership of the listener.\n body_listener->AddInputListener(listened_element.get(), listener);\n\n \/\/ Simulate a blur event to the element we are not listening to.\n \/\/ Our listener should not be notified.\n RefPtr event(Event::create(WebCore::eventNames().DOMFocusOutEvent,\n false, false));\n event->setTarget(ignored_element.get());\n body_listener->handleEvent(event.get(), false);\n EXPECT_FALSE(listener->blurred());\n \n \/\/ Now simulate the event on the input element we are listening to.\n event->setTarget(listened_element.get());\n body_listener->handleEvent(event.get(), false);\n EXPECT_TRUE(listener->blurred());\n}\n\nTEST_F(DomAutocompleteTests, InlineAutocompleteTriggeredByInputEvent) {\n RefPtr ignored_element =\n new WebCore::HTMLInputElement(document_);\n RefPtr listened_element =\n new WebCore::HTMLInputElement(document_);\n RefPtr body_listener =\n adoptRef(new TestAutocompleteBodyListener());\n\n TestAutocompleteInputListener* listener = new TestAutocompleteInputListener();\n body_listener->AddInputListener(listened_element.get(), listener);\n\n \/\/ Simulate an inputEvent by setting the value and artificially firing evt.\n \/\/ The user typed 'g'.\n SimulateTypedInput(body_listener.get(), ignored_element.get(), L\"g\", true);\n EXPECT_FALSE(listener->did_request_inline_autocomplete());\n SimulateTypedInput(body_listener.get(), listened_element.get(), L\"g\", true);\n EXPECT_TRUE(listener->did_request_inline_autocomplete());\n}\n\nTEST_F(DomAutocompleteTests, InlineAutocompleteHeuristics) {\n RefPtr input_element =\n new WebCore::HTMLInputElement(document_);\n RefPtr body_listener =\n adoptRef(new TestAutocompleteBodyListener());\n\n TestAutocompleteInputListener* listener = new TestAutocompleteInputListener();\n body_listener->AddInputListener(input_element.get(), listener);\n\n \/\/ Simulate a user entering some text, and then backspacing to remove\n \/\/ a character.\n SimulateTypedInput(body_listener.get(), input_element.get(), L\"g\", true);\n EXPECT_TRUE(listener->did_request_inline_autocomplete());\n listener->ResetTestState();\n body_listener->ResetTestState();\n\n SimulateTypedInput(body_listener.get(), input_element.get(), L\"go\", true);\n EXPECT_TRUE(listener->did_request_inline_autocomplete());\n listener->ResetTestState();\n body_listener->ResetTestState();\n\n SimulateTypedInput(body_listener.get(), input_element.get(), L\"g\", true);\n EXPECT_FALSE(listener->did_request_inline_autocomplete());\n listener->ResetTestState();\n body_listener->ResetTestState();\n\n \/\/ Now simulate the user moving the cursor to a position other than the end,\n \/\/ and adding text.\n SimulateTypedInput(body_listener.get(), input_element.get(), L\"og\", false);\n EXPECT_FALSE(listener->did_request_inline_autocomplete());\n listener->ResetTestState();\n body_listener->ResetTestState();\n\n \/\/ Test that same input doesn't trigger autocomplete.\n SimulateTypedInput(body_listener.get(), input_element.get(), L\"og\", true);\n EXPECT_FALSE(listener->did_request_inline_autocomplete());\n listener->ResetTestState();\n body_listener->ResetTestState();\n}\n\n} \/\/ webkit_glue\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"printing\/printing_context_cairo.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/values.h\"\n#include \"printing\/units.h\"\n#include \"printing\/print_settings_initializer_gtk.h\"\n\n#if defined(OS_CHROMEOS)\n#include \n#else\n#include \n#include \n#endif \/\/ defined(OS_CHROMEOS)\n\n#if !defined(OS_CHROMEOS)\nnamespace {\n \/\/ Function pointer for creating print dialogs.\n static void* (*create_dialog_func_)(\n printing::PrintingContext::PrintSettingsCallback* callback,\n printing::PrintingContextCairo* context) = NULL;\n \/\/ Function pointer for printing documents.\n static void (*print_document_func_)(\n void* print_dialog,\n const printing::NativeMetafile* metafile,\n const string16& document_name) = NULL;\n} \/\/ namespace\n#endif \/\/ !defined(OS_CHROMEOS)\n\nnamespace printing {\n\n\/\/ static\n PrintingContext* PrintingContext::Create(const std::string& app_locale) {\n return static_cast(new PrintingContextCairo(app_locale));\n}\n\nPrintingContextCairo::PrintingContextCairo(const std::string& app_locale)\n#if defined(OS_CHROMEOS)\n : PrintingContext(app_locale) {\n#else\n : PrintingContext(app_locale),\n print_dialog_(NULL) {\n#endif\n}\n\nPrintingContextCairo::~PrintingContextCairo() {\n ReleaseContext();\n}\n\n#if !defined(OS_CHROMEOS)\n\/\/ static\nvoid PrintingContextCairo::SetPrintingFunctions(\n void* (*create_dialog_func)(PrintSettingsCallback* callback,\n PrintingContextCairo* context),\n void (*print_document_func)(void* print_dialog,\n const NativeMetafile* metafile,\n const string16& document_name)) {\n DCHECK(create_dialog_func);\n DCHECK(print_document_func);\n DCHECK(!create_dialog_func_);\n DCHECK(!print_document_func_);\n create_dialog_func_ = create_dialog_func;\n print_document_func_ = print_document_func;\n}\n\nvoid PrintingContextCairo::PrintDocument(const NativeMetafile* metafile) {\n DCHECK(print_dialog_);\n DCHECK(metafile);\n print_document_func_(print_dialog_, metafile, document_name_);\n}\n#endif \/\/ !defined(OS_CHROMEOS)\n\nvoid PrintingContextCairo::AskUserForSettings(\n gfx::NativeView parent_view,\n int max_pages,\n bool has_selection,\n PrintSettingsCallback* callback) {\n#if defined(OS_CHROMEOS)\n callback->Run(OK);\n#else\n print_dialog_ = create_dialog_func_(callback, this);\n#endif \/\/ defined(OS_CHROMEOS)\n}\n\nPrintingContext::Result PrintingContextCairo::UseDefaultSettings() {\n DCHECK(!in_print_job_);\n\n ResetSettings();\n#if defined(OS_CHROMEOS)\n \/\/ For Chrome OS use default values based on the app locale rather than rely\n \/\/ on GTK. Note that relying on the app locale does not work well if it is\n \/\/ different from the system locale, e.g. a user using Chinese ChromeOS in the\n \/\/ US. Eventually we need to get the defaults from the printer.\n \/\/ TODO(sanjeevr): We need a better feedback loop between the cloud print\n \/\/ dialog and this code.\n int dpi = 300;\n gfx::Size physical_size_device_units;\n gfx::Rect printable_area_device_units;\n int32_t width = 0;\n int32_t height = 0;\n UErrorCode error = U_ZERO_ERROR;\n ulocdata_getPaperSize(app_locale_.c_str(), &height, &width, &error);\n if (error != U_ZERO_ERROR) {\n \/\/ If the call failed, assume a paper size of 8.5 x 11 inches.\n LOG(WARNING) << \"ulocdata_getPaperSize failed, using 8.5 x 11, error: \"\n << error;\n width = static_cast(8.5 * dpi);\n height = static_cast(11 * dpi);\n } else {\n \/\/ ulocdata_getPaperSize returns the width and height in mm.\n \/\/ Convert this to pixels based on the dpi.\n width = static_cast(ConvertUnitDouble(width, 25.4, 1.0) * dpi);\n height = static_cast(ConvertUnitDouble(height, 25.4, 1.0) * dpi);\n }\n\n physical_size_device_units.SetSize(width, height);\n printable_area_device_units.SetRect(\n static_cast(PrintSettingsInitializerGtk::kLeftMarginInInch * dpi),\n static_cast(PrintSettingsInitializerGtk::kTopMarginInInch * dpi),\n width - (PrintSettingsInitializerGtk::kLeftMarginInInch +\n PrintSettingsInitializerGtk::kRightMarginInInch) * dpi,\n height - (PrintSettingsInitializerGtk::kTopMarginInInch +\n PrintSettingsInitializerGtk::kBottomMarginInInch) * dpi);\n\n settings_.set_dpi(dpi);\n settings_.SetPrinterPrintableArea(physical_size_device_units,\n printable_area_device_units,\n dpi);\n#else \/\/ defined(OS_CHROMEOS)\n GtkWidget* dialog = gtk_print_unix_dialog_new(NULL, NULL);\n GtkPrintSettings* settings =\n gtk_print_unix_dialog_get_settings(GTK_PRINT_UNIX_DIALOG(dialog));\n GtkPageSetup* page_setup =\n gtk_print_unix_dialog_get_page_setup(GTK_PRINT_UNIX_DIALOG(dialog));\n\n PageRanges ranges_vector; \/\/ Nothing to initialize for default settings.\n PrintSettingsInitializerGtk::InitPrintSettings(\n settings, page_setup, ranges_vector, false, &settings_);\n\n g_object_unref(settings);\n \/\/ |page_setup| is owned by dialog, so it does not need to be unref'ed.\n gtk_widget_destroy(dialog);\n#endif \/\/ defined(OS_CHROMEOS)\n\n return OK;\n}\n\nPrintingContext::Result PrintingContextCairo::UpdatePrintSettings(\n const DictionaryValue& job_settings, const PageRanges& ranges) {\n DCHECK(!in_print_job_);\n\n settings_.ranges = ranges;\n\n NOTIMPLEMENTED();\n\n return FAILED;\n}\n\nPrintingContext::Result PrintingContextCairo::InitWithSettings(\n const PrintSettings& settings) {\n DCHECK(!in_print_job_);\n\n settings_ = settings;\n\n return OK;\n}\n\nPrintingContext::Result PrintingContextCairo::NewDocument(\n const string16& document_name) {\n DCHECK(!in_print_job_);\n in_print_job_ = true;\n\n#if !defined(OS_CHROMEOS)\n document_name_ = document_name;\n#endif \/\/ !defined(OS_CHROMEOS)\n\n return OK;\n}\n\nPrintingContext::Result PrintingContextCairo::NewPage() {\n if (abort_printing_)\n return CANCEL;\n DCHECK(in_print_job_);\n\n \/\/ Intentional No-op.\n\n return OK;\n}\n\nPrintingContext::Result PrintingContextCairo::PageDone() {\n if (abort_printing_)\n return CANCEL;\n DCHECK(in_print_job_);\n\n \/\/ Intentional No-op.\n\n return OK;\n}\n\nPrintingContext::Result PrintingContextCairo::DocumentDone() {\n if (abort_printing_)\n return CANCEL;\n DCHECK(in_print_job_);\n\n ResetSettings();\n return OK;\n}\n\nvoid PrintingContextCairo::Cancel() {\n abort_printing_ = true;\n in_print_job_ = false;\n}\n\nvoid PrintingContextCairo::ReleaseContext() {\n \/\/ Intentional No-op.\n}\n\ngfx::NativeDrawingContext PrintingContextCairo::context() const {\n \/\/ Intentional No-op.\n return NULL;\n}\n\n} \/\/ namespace printing\nPrintPreview: Remove NOTIMPLEMENTED() function call in PrintingContextCairo::UpdatePrintSettings().\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"printing\/printing_context_cairo.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/values.h\"\n#include \"printing\/units.h\"\n#include \"printing\/print_settings_initializer_gtk.h\"\n\n#if defined(OS_CHROMEOS)\n#include \n#else\n#include \n#include \n#endif \/\/ defined(OS_CHROMEOS)\n\n#if !defined(OS_CHROMEOS)\nnamespace {\n \/\/ Function pointer for creating print dialogs.\n static void* (*create_dialog_func_)(\n printing::PrintingContext::PrintSettingsCallback* callback,\n printing::PrintingContextCairo* context) = NULL;\n \/\/ Function pointer for printing documents.\n static void (*print_document_func_)(\n void* print_dialog,\n const printing::NativeMetafile* metafile,\n const string16& document_name) = NULL;\n} \/\/ namespace\n#endif \/\/ !defined(OS_CHROMEOS)\n\nnamespace printing {\n\n\/\/ static\n PrintingContext* PrintingContext::Create(const std::string& app_locale) {\n return static_cast(new PrintingContextCairo(app_locale));\n}\n\nPrintingContextCairo::PrintingContextCairo(const std::string& app_locale)\n#if defined(OS_CHROMEOS)\n : PrintingContext(app_locale) {\n#else\n : PrintingContext(app_locale),\n print_dialog_(NULL) {\n#endif\n}\n\nPrintingContextCairo::~PrintingContextCairo() {\n ReleaseContext();\n}\n\n#if !defined(OS_CHROMEOS)\n\/\/ static\nvoid PrintingContextCairo::SetPrintingFunctions(\n void* (*create_dialog_func)(PrintSettingsCallback* callback,\n PrintingContextCairo* context),\n void (*print_document_func)(void* print_dialog,\n const NativeMetafile* metafile,\n const string16& document_name)) {\n DCHECK(create_dialog_func);\n DCHECK(print_document_func);\n DCHECK(!create_dialog_func_);\n DCHECK(!print_document_func_);\n create_dialog_func_ = create_dialog_func;\n print_document_func_ = print_document_func;\n}\n\nvoid PrintingContextCairo::PrintDocument(const NativeMetafile* metafile) {\n DCHECK(print_dialog_);\n DCHECK(metafile);\n print_document_func_(print_dialog_, metafile, document_name_);\n}\n#endif \/\/ !defined(OS_CHROMEOS)\n\nvoid PrintingContextCairo::AskUserForSettings(\n gfx::NativeView parent_view,\n int max_pages,\n bool has_selection,\n PrintSettingsCallback* callback) {\n#if defined(OS_CHROMEOS)\n callback->Run(OK);\n#else\n print_dialog_ = create_dialog_func_(callback, this);\n#endif \/\/ defined(OS_CHROMEOS)\n}\n\nPrintingContext::Result PrintingContextCairo::UseDefaultSettings() {\n DCHECK(!in_print_job_);\n\n ResetSettings();\n#if defined(OS_CHROMEOS)\n \/\/ For Chrome OS use default values based on the app locale rather than rely\n \/\/ on GTK. Note that relying on the app locale does not work well if it is\n \/\/ different from the system locale, e.g. a user using Chinese ChromeOS in the\n \/\/ US. Eventually we need to get the defaults from the printer.\n \/\/ TODO(sanjeevr): We need a better feedback loop between the cloud print\n \/\/ dialog and this code.\n int dpi = 300;\n gfx::Size physical_size_device_units;\n gfx::Rect printable_area_device_units;\n int32_t width = 0;\n int32_t height = 0;\n UErrorCode error = U_ZERO_ERROR;\n ulocdata_getPaperSize(app_locale_.c_str(), &height, &width, &error);\n if (error != U_ZERO_ERROR) {\n \/\/ If the call failed, assume a paper size of 8.5 x 11 inches.\n LOG(WARNING) << \"ulocdata_getPaperSize failed, using 8.5 x 11, error: \"\n << error;\n width = static_cast(8.5 * dpi);\n height = static_cast(11 * dpi);\n } else {\n \/\/ ulocdata_getPaperSize returns the width and height in mm.\n \/\/ Convert this to pixels based on the dpi.\n width = static_cast(ConvertUnitDouble(width, 25.4, 1.0) * dpi);\n height = static_cast(ConvertUnitDouble(height, 25.4, 1.0) * dpi);\n }\n\n physical_size_device_units.SetSize(width, height);\n printable_area_device_units.SetRect(\n static_cast(PrintSettingsInitializerGtk::kLeftMarginInInch * dpi),\n static_cast(PrintSettingsInitializerGtk::kTopMarginInInch * dpi),\n width - (PrintSettingsInitializerGtk::kLeftMarginInInch +\n PrintSettingsInitializerGtk::kRightMarginInInch) * dpi,\n height - (PrintSettingsInitializerGtk::kTopMarginInInch +\n PrintSettingsInitializerGtk::kBottomMarginInInch) * dpi);\n\n settings_.set_dpi(dpi);\n settings_.SetPrinterPrintableArea(physical_size_device_units,\n printable_area_device_units,\n dpi);\n#else \/\/ defined(OS_CHROMEOS)\n GtkWidget* dialog = gtk_print_unix_dialog_new(NULL, NULL);\n GtkPrintSettings* settings =\n gtk_print_unix_dialog_get_settings(GTK_PRINT_UNIX_DIALOG(dialog));\n GtkPageSetup* page_setup =\n gtk_print_unix_dialog_get_page_setup(GTK_PRINT_UNIX_DIALOG(dialog));\n\n PageRanges ranges_vector; \/\/ Nothing to initialize for default settings.\n PrintSettingsInitializerGtk::InitPrintSettings(\n settings, page_setup, ranges_vector, false, &settings_);\n\n g_object_unref(settings);\n \/\/ |page_setup| is owned by dialog, so it does not need to be unref'ed.\n gtk_widget_destroy(dialog);\n#endif \/\/ defined(OS_CHROMEOS)\n\n return OK;\n}\n\nPrintingContext::Result PrintingContextCairo::UpdatePrintSettings(\n const DictionaryValue& job_settings, const PageRanges& ranges) {\n DCHECK(!in_print_job_);\n\n settings_.ranges = ranges;\n\n \/\/ TODO(kmadhusu): Update other print settings such as number of copies,\n \/\/ collate, duplex printing, etc.,\n\n return OK;\n}\n\nPrintingContext::Result PrintingContextCairo::InitWithSettings(\n const PrintSettings& settings) {\n DCHECK(!in_print_job_);\n\n settings_ = settings;\n\n return OK;\n}\n\nPrintingContext::Result PrintingContextCairo::NewDocument(\n const string16& document_name) {\n DCHECK(!in_print_job_);\n in_print_job_ = true;\n\n#if !defined(OS_CHROMEOS)\n document_name_ = document_name;\n#endif \/\/ !defined(OS_CHROMEOS)\n\n return OK;\n}\n\nPrintingContext::Result PrintingContextCairo::NewPage() {\n if (abort_printing_)\n return CANCEL;\n DCHECK(in_print_job_);\n\n \/\/ Intentional No-op.\n\n return OK;\n}\n\nPrintingContext::Result PrintingContextCairo::PageDone() {\n if (abort_printing_)\n return CANCEL;\n DCHECK(in_print_job_);\n\n \/\/ Intentional No-op.\n\n return OK;\n}\n\nPrintingContext::Result PrintingContextCairo::DocumentDone() {\n if (abort_printing_)\n return CANCEL;\n DCHECK(in_print_job_);\n\n ResetSettings();\n return OK;\n}\n\nvoid PrintingContextCairo::Cancel() {\n abort_printing_ = true;\n in_print_job_ = false;\n}\n\nvoid PrintingContextCairo::ReleaseContext() {\n \/\/ Intentional No-op.\n}\n\ngfx::NativeDrawingContext PrintingContextCairo::context() const {\n \/\/ Intentional No-op.\n return NULL;\n}\n\n} \/\/ namespace printing\n<|endoftext|>"} {"text":"\/* This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * Mapnik is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\/\n\n\/\/$Id$\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"mapwidget.hpp\"\n#include \"info_dialog.hpp\"\n\nusing mapnik::image_32;\nusing mapnik::Map;\nusing mapnik::layer;\nusing mapnik::box2d;\nusing mapnik::coord2d;\nusing mapnik::feature_ptr;\nusing mapnik::geometry_ptr;\nusing mapnik::CoordTransform;\nusing mapnik::projection;\nusing mapnik::scale_denominator;\nusing mapnik::feature_kv_iterator;\n\ndouble scales [] = {279541132.014,\n 139770566.007,\n 69885283.0036,\n 34942641.5018,\n 17471320.7509,\n 8735660.37545,\n 4367830.18772,\n 2183915.09386,\n 1091957.54693,\n 545978.773466,\n 272989.386733,\n 136494.693366,\n 68247.3466832,\n 34123.6733416,\n 17061.8366708,\n 8530.9183354,\n 4265.4591677,\n 2132.72958385,\n 1066.36479192,\n 533.182395962};\n\nMapWidget::MapWidget(QWidget *parent)\n : QWidget(parent),\n map_(),\n selected_(1),\n extent_(),\n cur_tool_(ZoomToBox),\n start_x_(0),\n start_y_(0),\n end_x_(0),\n end_y_(0),\n drag_(false),\n first_(true),\n pen_(QColor(0,0,255,96)),\n selectedLayer_(-1),\n scaling_factor_(1.0)\n{\n pen_.setWidth(3);\n pen_.setCapStyle(Qt::RoundCap);\n pen_.setJoinStyle(Qt::RoundJoin);\n}\n\nvoid MapWidget::setTool(eTool tool)\n{\n cur_tool_=tool;\n}\n\nvoid MapWidget::paintEvent(QPaintEvent*)\n{\n QPainter painter(this);\n\n if (drag_)\n {\n if (cur_tool_ == ZoomToBox)\n {\n unsigned width = end_x_-start_x_;\n unsigned height = end_y_-start_y_;\n painter.drawPixmap(QPoint(0, 0),pix_);\n painter.setPen(pen_);\n painter.setBrush(QColor(200,200,255,128));\n painter.drawRect(start_x_,start_y_,width,height);\n }\n else if (cur_tool_ == Pan)\n {\n int dx = end_x_-start_x_;\n int dy = end_y_-start_y_;\n painter.setBrush(QColor(200,200,200,128));\n painter.drawRect(0,0,width(),height());\n painter.drawPixmap(QPoint(dx,dy),pix_);\n }\n }\n else\n {\n painter.drawPixmap(QPoint(0, 0),pix_);\n }\n painter.end();\n}\n\nvoid MapWidget::resizeEvent(QResizeEvent * ev)\n{\n if (map_)\n {\n map_->resize(ev->size().width(),ev->size().height());\n updateMap();\n }\n}\n\nvoid MapWidget::mousePressEvent(QMouseEvent* e)\n{\n if (e->button()==Qt::LeftButton)\n {\n if (cur_tool_ == ZoomToBox || cur_tool_==Pan)\n {\n start_x_ = e->x();\n start_y_ = e->y();\n drag_=true;\n }\n else if (cur_tool_==Info)\n {\n if (map_)\n {\n QVector > info;\n\n projection map_proj(map_->srs()); \/\/ map projection\n double scale_denom = scale_denominator(*map_,map_proj.is_geographic());\n CoordTransform t(map_->width(),map_->height(),map_->get_current_extent());\n\n for (unsigned index = 0; index < map_->layer_count();++index)\n {\n if (int(index) != selectedLayer_) continue;\n\n layer & layer = map_->layers()[index];\n if (!layer.visible(scale_denom)) continue;\n std::string name = layer.name();\n double x = e->x();\n double y = e->y();\n std::cout << \"query at \" << x << \",\" << y << \"\\n\";\n projection layer_proj(layer.srs());\n mapnik::proj_transform prj_trans(map_proj,layer_proj);\n \/\/std::auto_ptr data(new mapnik::memory_datasource);\n mapnik::featureset_ptr fs = map_->query_map_point(index,x,y);\n\n if (fs)\n {\n feature_ptr feat = fs->next();\n if (feat)\n {\n \n feature_kv_iterator itr(*feat,true);\n feature_kv_iterator end(*feat);\n \n for ( ;itr!=end; ++itr)\n {\n info.push_back(QPair(QString(boost::get<0>(*itr).c_str()),\n boost::get<1>(*itr).to_string().c_str()));\n }\n \n typedef mapnik::coord_transform2 path_type;\n\n for (unsigned i=0; inum_geometries();++i)\n {\n mapnik::geometry_type & geom = feat->get_geometry(i);\n path_type path(t,geom,prj_trans);\n if (geom.num_points() > 0)\n {\n QPainterPath qpath;\n double x,y;\n path.vertex(&x,&y);\n qpath.moveTo(x,y);\n for (unsigned j = 1; j < geom.num_points(); ++j)\n {\n path.vertex(&x,&y);\n qpath.lineTo(x,y);\n }\n QPainter painter(&pix_);\n QPen pen(QColor(255,0,0,96));\n pen.setWidth(3);\n pen.setCapStyle(Qt::RoundCap);\n pen.setJoinStyle(Qt::RoundJoin);\n painter.setPen(pen);\n painter.drawPath(qpath);\n update();\n }\n }\n }\n }\n\n if (info.size() > 0)\n {\n info_dialog info_dlg(info,this);\n info_dlg.exec();\n break;\n }\n }\n\n \/\/ remove annotation layer\n map_->layers().erase(remove_if(map_->layers().begin(),\n map_->layers().end(),\n bind(&layer::name,_1) == \"*annotations*\")\n , map_->layers().end());\n }\n }\n }\n else if (e->button()==Qt::RightButton)\n {\n \/\/updateMap();\n }\n}\n\nvoid MapWidget::mouseMoveEvent(QMouseEvent* e)\n{\n if (cur_tool_ == ZoomToBox || cur_tool_==Pan)\n {\n end_x_ = e->x();\n end_y_ = e->y();\n update();\n }\n}\n\nvoid MapWidget::mouseReleaseEvent(QMouseEvent* e)\n{\n if (e->button()==Qt::LeftButton)\n {\n end_x_ = e->x();\n end_y_ = e->y();\n if (cur_tool_ == ZoomToBox)\n {\n drag_=false;\n if (map_)\n {\n CoordTransform t(map_->width(),map_->height(),map_->get_current_extent());\n box2d box = t.backward(box2d(start_x_,start_y_,end_x_,end_y_));\n map_->zoom_to_box(box);\n updateMap();\n }\n }\n else if (cur_tool_==Pan)\n {\n drag_=false;\n if (map_)\n {\n int cx = int(0.5 * map_->width());\n int cy = int(0.5 * map_->height());\n int dx = end_x_ - start_x_;\n int dy = end_y_ - start_y_;\n map_->pan(cx - dx ,cy - dy);\n updateMap();\n }\n }\n }\n}\n\n\nvoid MapWidget::keyPressEvent(QKeyEvent *e)\n{\n std::cout << \"key pressed:\"<< e->key()<<\"\\n\";\n switch (e->key()) {\n case Qt::Key_Minus:\n zoomOut();\n break;\n case Qt::Key_Plus:\n case 61:\n zoomIn();\n break;\n case 65:\n defaultView();\n break;\n case Qt::Key_Up:\n panUp();\n break;\n case Qt::Key_Down:\n panDown();\n break;\n case Qt::Key_Left:\n panLeft();\n break;\n case Qt::Key_Right:\n panRight();\n break;\n case 49:\n zoomToLevel(10);\n break;\n case 50:\n zoomToLevel(11);\n break;\n case 51:\n zoomToLevel(12);\n break;\n case 52:\n zoomToLevel(13);\n break;\n case 53:\n zoomToLevel(14);\n break;\n case 54:\n zoomToLevel(15);\n break;\n case 55:\n zoomToLevel(16);\n break;\n case 56:\n zoomToLevel(17);\n break;\n case 57:\n zoomToLevel(18);\n break;\n default:\n QWidget::keyPressEvent(e);\n }\n\n\n}\n\nvoid MapWidget::zoomToBox(mapnik::box2d const& bbox)\n{\n if (map_)\n {\n map_->zoom_to_box(bbox);\n updateMap();\n }\n}\n\nvoid MapWidget::defaultView()\n{\n if (map_)\n {\n map_->resize(width(),height());\n map_->zoom_all();\n updateMap();\n }\n}\n\nvoid MapWidget::zoomIn()\n{\n if (map_)\n {\n map_->zoom(0.5);\n updateMap();\n }\n}\n\nvoid MapWidget::zoomOut()\n{\n if (map_)\n {\n map_->zoom(2.0);\n updateMap();\n }\n}\n\nvoid MapWidget::panUp()\n{\n if (map_)\n {\n double cx = 0.5*map_->width();\n double cy = 0.5*map_->height();\n map_->pan(int(cx),int(cy - cy*0.25));\n updateMap();\n }\n}\n\nvoid MapWidget::panDown()\n{\n if (map_)\n {\n double cx = 0.5*map_->width();\n double cy = 0.5*map_->height();\n map_->pan(int(cx),int(cy + cy*0.25));\n updateMap();\n }\n}\n\nvoid MapWidget::panLeft()\n{\n if (map_)\n {\n double cx = 0.5*map_->width();\n double cy = 0.5*map_->height();\n map_->pan(int(cx - cx * 0.25),int(cy));\n updateMap();\n }\n}\n\nvoid MapWidget::panRight()\n{\n if (map_)\n {\n double cx = 0.5*map_->width();\n double cy = 0.5*map_->height();\n map_->pan(int(cx + cx * 0.25),int(cy));\n updateMap();\n }\n}\n\n\nvoid MapWidget::zoomToLevel(int level)\n{\n if ( map_ && level >= 0 && level < 19 )\n {\n double scale_denom = scales[level];\n std::cerr << \"scale denominator = \" << scale_denom << \"\\n\";\n mapnik::box2d ext = map_->get_current_extent();\n double width = static_cast(map_->width());\n double height= static_cast(map_->height());\n mapnik::coord2d pt = ext.center();\n\n double res = scale_denom * 0.00028;\n\n mapnik::box2d box(pt.x - 0.5 * width * res,\n pt.y - 0.5 * height*res,\n pt.x + 0.5 * width * res,\n pt.y + 0.5 * height*res);\n map_->zoom_to_box(box);\n updateMap();\n }\n}\n\nvoid MapWidget::export_to_file(unsigned ,unsigned ,std::string const&,std::string const&)\n{\n \/\/image_32 image(width,height);\n \/\/agg_renderer renderer(map,image);\n \/\/renderer.apply();\n \/\/image.saveToFile(filename,type);\n}\n\nvoid MapWidget::set_scaling_factor(double scaling_factor)\n{\n scaling_factor_ = scaling_factor;\n}\n\nvoid MapWidget::updateMap()\n{\n if (map_)\n {\n unsigned width=map_->width();\n unsigned height=map_->height();\n\n image_32 buf(width,height);\n\n try\n {\n mapnik::agg_renderer ren(*map_,buf,scaling_factor_);\n ren.apply();\n\n QImage image((uchar*)buf.raw_data(),width,height,QImage::Format_ARGB32);\n pix_=QPixmap::fromImage(image.rgbSwapped());\n projection prj(map_->srs()); \/\/ map projection\n\n box2d ext = map_->get_current_extent();\n double x0 = ext.minx();\n double y0 = ext.miny();\n double x1 = ext.maxx();\n double y1 = ext.maxy();\n prj.inverse(x0,y0);\n prj.inverse(x1,y1);\n std::cout << \"BBOX (WGS84): \" << x0 << \",\" << y0 << \",\" << x1 << \",\" << y1 << \"\\n\";\n update();\n \/\/ emit signal to interested widgets\n emit mapViewChanged();\n }\n catch (mapnik::config_error & ex)\n {\n std::cerr << ex.what() << std::endl;\n }\n catch (...)\n {\n std::cerr << \"Unknown exception caught!\\n\";\n }\n }\n}\n\nboost::shared_ptr MapWidget::getMap()\n{\n return map_;\n}\n\nvoid MapWidget::setMap(boost::shared_ptr map)\n{\n map_ = map;\n}\n\n\nvoid MapWidget::layerSelected(int index)\n{\n selectedLayer_ = index;\n}\n+ add: #include mapnik\/config_error.hpp\/* This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * Mapnik is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\/\n\n\/\/$Id$\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"mapwidget.hpp\"\n#include \"info_dialog.hpp\"\n\nusing mapnik::image_32;\nusing mapnik::Map;\nusing mapnik::layer;\nusing mapnik::box2d;\nusing mapnik::coord2d;\nusing mapnik::feature_ptr;\nusing mapnik::geometry_ptr;\nusing mapnik::CoordTransform;\nusing mapnik::projection;\nusing mapnik::scale_denominator;\nusing mapnik::feature_kv_iterator;\n\ndouble scales [] = {279541132.014,\n 139770566.007,\n 69885283.0036,\n 34942641.5018,\n 17471320.7509,\n 8735660.37545,\n 4367830.18772,\n 2183915.09386,\n 1091957.54693,\n 545978.773466,\n 272989.386733,\n 136494.693366,\n 68247.3466832,\n 34123.6733416,\n 17061.8366708,\n 8530.9183354,\n 4265.4591677,\n 2132.72958385,\n 1066.36479192,\n 533.182395962};\n\nMapWidget::MapWidget(QWidget *parent)\n : QWidget(parent),\n map_(),\n selected_(1),\n extent_(),\n cur_tool_(ZoomToBox),\n start_x_(0),\n start_y_(0),\n end_x_(0),\n end_y_(0),\n drag_(false),\n first_(true),\n pen_(QColor(0,0,255,96)),\n selectedLayer_(-1),\n scaling_factor_(1.0)\n{\n pen_.setWidth(3);\n pen_.setCapStyle(Qt::RoundCap);\n pen_.setJoinStyle(Qt::RoundJoin);\n}\n\nvoid MapWidget::setTool(eTool tool)\n{\n cur_tool_=tool;\n}\n\nvoid MapWidget::paintEvent(QPaintEvent*)\n{\n QPainter painter(this);\n\n if (drag_)\n {\n if (cur_tool_ == ZoomToBox)\n {\n unsigned width = end_x_-start_x_;\n unsigned height = end_y_-start_y_;\n painter.drawPixmap(QPoint(0, 0),pix_);\n painter.setPen(pen_);\n painter.setBrush(QColor(200,200,255,128));\n painter.drawRect(start_x_,start_y_,width,height);\n }\n else if (cur_tool_ == Pan)\n {\n int dx = end_x_-start_x_;\n int dy = end_y_-start_y_;\n painter.setBrush(QColor(200,200,200,128));\n painter.drawRect(0,0,width(),height());\n painter.drawPixmap(QPoint(dx,dy),pix_);\n }\n }\n else\n {\n painter.drawPixmap(QPoint(0, 0),pix_);\n }\n painter.end();\n}\n\nvoid MapWidget::resizeEvent(QResizeEvent * ev)\n{\n if (map_)\n {\n map_->resize(ev->size().width(),ev->size().height());\n updateMap();\n }\n}\n\nvoid MapWidget::mousePressEvent(QMouseEvent* e)\n{\n if (e->button()==Qt::LeftButton)\n {\n if (cur_tool_ == ZoomToBox || cur_tool_==Pan)\n {\n start_x_ = e->x();\n start_y_ = e->y();\n drag_=true;\n }\n else if (cur_tool_==Info)\n {\n if (map_)\n {\n QVector > info;\n\n projection map_proj(map_->srs()); \/\/ map projection\n double scale_denom = scale_denominator(*map_,map_proj.is_geographic());\n CoordTransform t(map_->width(),map_->height(),map_->get_current_extent());\n\n for (unsigned index = 0; index < map_->layer_count();++index)\n {\n if (int(index) != selectedLayer_) continue;\n\n layer & layer = map_->layers()[index];\n if (!layer.visible(scale_denom)) continue;\n std::string name = layer.name();\n double x = e->x();\n double y = e->y();\n std::cout << \"query at \" << x << \",\" << y << \"\\n\";\n projection layer_proj(layer.srs());\n mapnik::proj_transform prj_trans(map_proj,layer_proj);\n \/\/std::auto_ptr data(new mapnik::memory_datasource);\n mapnik::featureset_ptr fs = map_->query_map_point(index,x,y);\n\n if (fs)\n {\n feature_ptr feat = fs->next();\n if (feat)\n {\n \n feature_kv_iterator itr(*feat,true);\n feature_kv_iterator end(*feat);\n \n for ( ;itr!=end; ++itr)\n {\n info.push_back(QPair(QString(boost::get<0>(*itr).c_str()),\n boost::get<1>(*itr).to_string().c_str()));\n }\n \n typedef mapnik::coord_transform2 path_type;\n\n for (unsigned i=0; inum_geometries();++i)\n {\n mapnik::geometry_type & geom = feat->get_geometry(i);\n path_type path(t,geom,prj_trans);\n if (geom.num_points() > 0)\n {\n QPainterPath qpath;\n double x,y;\n path.vertex(&x,&y);\n qpath.moveTo(x,y);\n for (unsigned j = 1; j < geom.num_points(); ++j)\n {\n path.vertex(&x,&y);\n qpath.lineTo(x,y);\n }\n QPainter painter(&pix_);\n QPen pen(QColor(255,0,0,96));\n pen.setWidth(3);\n pen.setCapStyle(Qt::RoundCap);\n pen.setJoinStyle(Qt::RoundJoin);\n painter.setPen(pen);\n painter.drawPath(qpath);\n update();\n }\n }\n }\n }\n\n if (info.size() > 0)\n {\n info_dialog info_dlg(info,this);\n info_dlg.exec();\n break;\n }\n }\n\n \/\/ remove annotation layer\n map_->layers().erase(remove_if(map_->layers().begin(),\n map_->layers().end(),\n bind(&layer::name,_1) == \"*annotations*\")\n , map_->layers().end());\n }\n }\n }\n else if (e->button()==Qt::RightButton)\n {\n \/\/updateMap();\n }\n}\n\nvoid MapWidget::mouseMoveEvent(QMouseEvent* e)\n{\n if (cur_tool_ == ZoomToBox || cur_tool_==Pan)\n {\n end_x_ = e->x();\n end_y_ = e->y();\n update();\n }\n}\n\nvoid MapWidget::mouseReleaseEvent(QMouseEvent* e)\n{\n if (e->button()==Qt::LeftButton)\n {\n end_x_ = e->x();\n end_y_ = e->y();\n if (cur_tool_ == ZoomToBox)\n {\n drag_=false;\n if (map_)\n {\n CoordTransform t(map_->width(),map_->height(),map_->get_current_extent());\n box2d box = t.backward(box2d(start_x_,start_y_,end_x_,end_y_));\n map_->zoom_to_box(box);\n updateMap();\n }\n }\n else if (cur_tool_==Pan)\n {\n drag_=false;\n if (map_)\n {\n int cx = int(0.5 * map_->width());\n int cy = int(0.5 * map_->height());\n int dx = end_x_ - start_x_;\n int dy = end_y_ - start_y_;\n map_->pan(cx - dx ,cy - dy);\n updateMap();\n }\n }\n }\n}\n\n\nvoid MapWidget::keyPressEvent(QKeyEvent *e)\n{\n std::cout << \"key pressed:\"<< e->key()<<\"\\n\";\n switch (e->key()) {\n case Qt::Key_Minus:\n zoomOut();\n break;\n case Qt::Key_Plus:\n case 61:\n zoomIn();\n break;\n case 65:\n defaultView();\n break;\n case Qt::Key_Up:\n panUp();\n break;\n case Qt::Key_Down:\n panDown();\n break;\n case Qt::Key_Left:\n panLeft();\n break;\n case Qt::Key_Right:\n panRight();\n break;\n case 49:\n zoomToLevel(10);\n break;\n case 50:\n zoomToLevel(11);\n break;\n case 51:\n zoomToLevel(12);\n break;\n case 52:\n zoomToLevel(13);\n break;\n case 53:\n zoomToLevel(14);\n break;\n case 54:\n zoomToLevel(15);\n break;\n case 55:\n zoomToLevel(16);\n break;\n case 56:\n zoomToLevel(17);\n break;\n case 57:\n zoomToLevel(18);\n break;\n default:\n QWidget::keyPressEvent(e);\n }\n\n\n}\n\nvoid MapWidget::zoomToBox(mapnik::box2d const& bbox)\n{\n if (map_)\n {\n map_->zoom_to_box(bbox);\n updateMap();\n }\n}\n\nvoid MapWidget::defaultView()\n{\n if (map_)\n {\n map_->resize(width(),height());\n map_->zoom_all();\n updateMap();\n }\n}\n\nvoid MapWidget::zoomIn()\n{\n if (map_)\n {\n map_->zoom(0.5);\n updateMap();\n }\n}\n\nvoid MapWidget::zoomOut()\n{\n if (map_)\n {\n map_->zoom(2.0);\n updateMap();\n }\n}\n\nvoid MapWidget::panUp()\n{\n if (map_)\n {\n double cx = 0.5*map_->width();\n double cy = 0.5*map_->height();\n map_->pan(int(cx),int(cy - cy*0.25));\n updateMap();\n }\n}\n\nvoid MapWidget::panDown()\n{\n if (map_)\n {\n double cx = 0.5*map_->width();\n double cy = 0.5*map_->height();\n map_->pan(int(cx),int(cy + cy*0.25));\n updateMap();\n }\n}\n\nvoid MapWidget::panLeft()\n{\n if (map_)\n {\n double cx = 0.5*map_->width();\n double cy = 0.5*map_->height();\n map_->pan(int(cx - cx * 0.25),int(cy));\n updateMap();\n }\n}\n\nvoid MapWidget::panRight()\n{\n if (map_)\n {\n double cx = 0.5*map_->width();\n double cy = 0.5*map_->height();\n map_->pan(int(cx + cx * 0.25),int(cy));\n updateMap();\n }\n}\n\n\nvoid MapWidget::zoomToLevel(int level)\n{\n if ( map_ && level >= 0 && level < 19 )\n {\n double scale_denom = scales[level];\n std::cerr << \"scale denominator = \" << scale_denom << \"\\n\";\n mapnik::box2d ext = map_->get_current_extent();\n double width = static_cast(map_->width());\n double height= static_cast(map_->height());\n mapnik::coord2d pt = ext.center();\n\n double res = scale_denom * 0.00028;\n\n mapnik::box2d box(pt.x - 0.5 * width * res,\n pt.y - 0.5 * height*res,\n pt.x + 0.5 * width * res,\n pt.y + 0.5 * height*res);\n map_->zoom_to_box(box);\n updateMap();\n }\n}\n\nvoid MapWidget::export_to_file(unsigned ,unsigned ,std::string const&,std::string const&)\n{\n \/\/image_32 image(width,height);\n \/\/agg_renderer renderer(map,image);\n \/\/renderer.apply();\n \/\/image.saveToFile(filename,type);\n}\n\nvoid MapWidget::set_scaling_factor(double scaling_factor)\n{\n scaling_factor_ = scaling_factor;\n}\n\nvoid MapWidget::updateMap()\n{\n if (map_)\n {\n unsigned width=map_->width();\n unsigned height=map_->height();\n\n image_32 buf(width,height);\n\n try\n {\n mapnik::agg_renderer ren(*map_,buf,scaling_factor_);\n ren.apply();\n\n QImage image((uchar*)buf.raw_data(),width,height,QImage::Format_ARGB32);\n pix_=QPixmap::fromImage(image.rgbSwapped());\n projection prj(map_->srs()); \/\/ map projection\n\n box2d ext = map_->get_current_extent();\n double x0 = ext.minx();\n double y0 = ext.miny();\n double x1 = ext.maxx();\n double y1 = ext.maxy();\n prj.inverse(x0,y0);\n prj.inverse(x1,y1);\n std::cout << \"BBOX (WGS84): \" << x0 << \",\" << y0 << \",\" << x1 << \",\" << y1 << \"\\n\";\n update();\n \/\/ emit signal to interested widgets\n emit mapViewChanged();\n }\n catch (mapnik::config_error & ex)\n {\n std::cerr << ex.what() << std::endl;\n }\n catch (...)\n {\n std::cerr << \"Unknown exception caught!\\n\";\n }\n }\n}\n\nboost::shared_ptr MapWidget::getMap()\n{\n return map_;\n}\n\nvoid MapWidget::setMap(boost::shared_ptr map)\n{\n map_ = map;\n}\n\n\nvoid MapWidget::layerSelected(int index)\n{\n selectedLayer_ = index;\n}\n<|endoftext|>"} {"text":"\/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- *\/\n\/* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino=\"(0,W2s,i2s,t0,l1,:0\" *\/\n\n#include \"wallpaperbusinesslogic.h\"\n#include \"wallpaperdescriptor.h\"\n#include \"wallpapercurrentdescriptor.h\"\n#include \"wallpaperitrans.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#define DEBUG\n#include \"..\/debug.h\"\n\nstatic const QString PortraitKey = \n \"\/desktop\/meego\/background\/landscape\/picture_filename\";\nstatic const QString LandscapeKey = \n \"\/desktop\/meego\/background\/portrait\/picture_filename\";\n\nstatic const QString wallpaperDir = \".wallpapers\";\nstatic const QString destopFileName = \"wallpaper.desktop\";\nstatic const QString backupExtension = \".BAK\";\n\nWallpaperBusinessLogic::WallpaperBusinessLogic()\n{\n WallpaperCurrentDescriptor *currentDesc;\n \n m_LandscapeGConfItem = new MGConfItem (LandscapeKey);\n m_PortraitGConfItem = new MGConfItem (PortraitKey);\n m_EditedImage = 0;\n\n currentDesc = WallpaperCurrentDescriptor::instance ();\n currentDesc->setFromDestopFile (dirPath() + destopFileName);\n}\n\nWallpaperBusinessLogic::~WallpaperBusinessLogic()\n{\n delete m_LandscapeGConfItem;\n delete m_PortraitGConfItem;\n}\n\n\/*!\n * FIXME: This method is deprecated, should use the \n * WallpaperCurrentDescriptor::instance () instead.\n *\/\nWallpaperDescriptor *\nWallpaperBusinessLogic::Wallpaper (\n bool portrait)\n{\n Q_UNUSED (portrait);\n SYS_WARNING (\"Deprecated method.\");\n return WallpaperCurrentDescriptor::instance ();\n}\n\n\/*!\n * A high level method to set the current wallpaper.\n *\/\nvoid\nWallpaperBusinessLogic::setBackground (\n WallpaperITrans *landscapeITrans,\n WallpaperITrans *portraitITrans,\n WallpaperDescriptor *desc)\n{\n bool success;\n\n SYS_DEBUG (\"******** Saving background *********\");\n if (desc == 0)\n desc = m_EditedImage;\n\n Q_ASSERT (landscapeITrans);\n Q_ASSERT (portraitITrans);\n Q_ASSERT (desc);\n\n success = ensureHasDirectory ();\n if (!success)\n return;\n\n createBackupFiles ();\n\n success = writeFiles (landscapeITrans, portraitITrans, desc);\n if (!success) {\n \/\/ FIXME: Should restore backup files here.\n return;\n }\n \n deleteBackupFiles ();\n\n \/*\n *\n *\/\n WallpaperCurrentDescriptor *currentDesc;\n currentDesc = WallpaperCurrentDescriptor::instance ();\n currentDesc->setFromDestopFile (dirPath() + destopFileName);\n emit wallpaperChanged ();\n\n SYS_DEBUG (\"****** End saving backgroun ********\");\n}\n\n\/*!\n * This function does not support image manipulatios, it is deprecated.\n * FIXME: To remove this function.\n *\/\nvoid\nWallpaperBusinessLogic::setBackground (\n WallpaperDescriptor *desc)\n{\n if (desc == 0)\n desc = m_EditedImage;\n\n SYS_WARNING (\"Deprecated method.\");\n Q_ASSERT (m_PortraitGConfItem != 0);\n Q_ASSERT (m_LandscapeGConfItem != 0);\n\n SYS_DEBUG (\"*** filename = %s\", SYS_STR(desc->filename()));\n m_PortraitGConfItem->set (desc->filename());\n m_LandscapeGConfItem->set (desc->filename());\n}\n\n\n\n\/*!\n * Returns a list wallpaper descriptors with the available wallpapers. The\n * current wallpaper is the first element of the available wallpapers.\n *\n * FIXME: This function needs some polishing.\n *\/\nQList\nWallpaperBusinessLogic::availableWallpapers () const\n{\n QList list;\n const QString query = \n\"SELECT ?uri ?title ?mime ?height ?width WHERE { \"\n\" ?item nie:url ?uri.\" \n\n\" ?item nie:mimeType ?mime.\" \n\" FILTER regex(?mime, \\\"image\\\").\"\n\n\" ?item nfo:height ?height.\"\n\" ?item nfo:width ?width.\"\n\" FILTER ( ?height > \\\"300\\\" ).\"\n\" FILTER ( ?width > \\\"300\\\" ).\"\n\n\" OPTIONAL { ?item nie:title ?title }.\"\n\"}\"\n;\n\n WallpaperCurrentDescriptor *currentDesc;\n\n currentDesc = WallpaperCurrentDescriptor::instance ();\n list << WallpaperCurrentDescriptor::instance ();\n\n QVector result = ::tracker()->rawSparqlQuery(query);\n int x = 0;\n int y = 0;\n\n SYS_WARNING (\"*** result.size() = %d\", result.size());\n foreach (QStringList partlist, result) {\n WallpaperDescriptor *desc;\n\n SYS_DEBUG (\"*********************************\");\n SYS_DEBUG (\"*** url = %s\", SYS_STR(partlist[FieldUrl]));\n\n desc = new WallpaperDescriptor;\n desc->setUrl (partlist[FieldUrl]);\n desc->setTitle (partlist[FieldTitle]);\n desc->setMimeType (partlist[FieldMime]);\n list << desc;\n\n \/*\n * Just to see what we really get.\n *\/\n #if 1\n foreach (QString element, partlist) {\n SYS_DEBUG (\"*** element[%2d][%2d] = %s\", x, y, SYS_STR(element));\n x++;\n }\n x = 0;\n #endif\n \n y++;\n }\n\n return list;\n}\n\n\/*!\n * While a wallpaper image is edited the WallpaperBusinessLogic holds a\n * descriptor on it. This function is used to set this wallpaper descriptor.\n *\/\nvoid\nWallpaperBusinessLogic::setEditedImage (\n WallpaperDescriptor *desc)\n{\n SYS_DEBUG (\"*** desc = %s\", SYS_STR(desc->filename()));\n m_EditedImage = desc;\n}\n\n\/*!\n * Returns the wallpaper that is being edited.\n *\/\nWallpaperDescriptor *\nWallpaperBusinessLogic::editedImage ()\n{\n SYS_DEBUG (\"*** m_EditedImage = %s\", SYS_STR(m_EditedImage->filename()));\n return m_EditedImage;\n}\n\n\/*********************************************************************************\n * Low level file handling functions.\n *\/\n\n\/*!\n * Returns the directory path that is used to store the information about the\n * edited wallpaper. This is the data storing directory for the wallpaper\n * applet.\n *\/\nQString\nWallpaperBusinessLogic::dirPath () const\n{\n QString homeDir (getenv(\"HOME\"));\n QString dirPath = homeDir + \"\/\" + wallpaperDir + \"\/\";\n\n return dirPath;\n}\n\n\/*!\n * \\returns true if the directory exists or could be created\n *\n * If the data store directory does not exists this method will create it.\n *\/\nbool\nWallpaperBusinessLogic::ensureHasDirectory ()\n{\n QString path = dirPath();\n QDir dir (path);\n\n if (dir.exists()) {\n SYS_DEBUG (\"Directory %s already exists.\", SYS_STR(path));\n return true;\n }\n\n if (!dir.mkpath(path)) {\n SYS_WARNING (\"Unable to create %s directory.\", SYS_STR(path));\n return false;\n }\n\n return true;\n}\n\n\/*!\n * Takes the desktop file, the saved landscape image file and the saved portrait\n * file and moves\/renames them to create a backup version of each of them.\n *\/\nvoid\nWallpaperBusinessLogic::createBackupFiles ()\n{\n QString path = dirPath();\n QString desktopPath = path + destopFileName;\n QString filename;\n \n makeBackup (desktopPath);\n\n filename = WallpaperCurrentDescriptor::instance()->editedFilename (\n M::Portrait);\n if (!filename.isEmpty())\n makeBackup (filename);\n\n filename = WallpaperCurrentDescriptor::instance()->editedFilename (\n M::Landscape);\n if (!filename.isEmpty())\n makeBackup (filename);\n}\n\n\/*!\n * Removes all the files from the applet's data directory that has the file name\n * extension indicating that it is a backup file.\n *\/\nvoid\nWallpaperBusinessLogic::deleteBackupFiles ()\n{\n QString path = dirPath();\n QDir dir (path);\n QStringList nameFilters (\"*.BAK\");\n\n dir.setNameFilters (nameFilters);\n foreach (QString backupFileName, dir.entryList (QDir::Files)) {\n SYS_DEBUG (\"Removing backup file %s\", SYS_STR(backupFileName));\n QFile backupFile (path + backupFileName);\n\n if (!backupFile.remove()) {\n SYS_WARNING (\"Unable to remove %s backup file.\",\n SYS_STR((path + backupFileName)));\n }\n }\n}\n\n\/*!\n * \\returns true if the files could be created and saved.\n *\n * FIXME: This method should and will be moved to the WallpaperCurrentDescriptor\n * class.\n *\/\nbool\nWallpaperBusinessLogic::writeFiles (\n WallpaperITrans *landscapeITrans,\n WallpaperITrans *portraitITrans,\n WallpaperDescriptor *desc)\n{\n Q_ASSERT (landscapeITrans);\n Q_ASSERT (portraitITrans);\n Q_ASSERT (desc);\n \/*\n * These are pretty constants.\n *\/\n QString path = dirPath();\n QString desktopPath = path + destopFileName;\n QFile file (desktopPath);\n\n int version = desc->version () + 1;\n QString versionString = QString::number(version);\n QString portraitFilePath = path + \n desc->suggestedOutputFilename (M::Portrait);\n QString landscapeFilePath = path + \n desc->suggestedOutputFilename (M::Landscape);\n\n\n \/*\n * Opening the output file.\n *\/\n if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n SYS_DEBUG (\"Opening file %s for writing failed.\", SYS_STR(desktopPath));\n return false;\n }\n\n \/*\n * FIXME: This is the new stuff, but in order to use it the current\n * wallpaper descriptor has to be upgraded with from the arguments of this\n * method.\n *\/\n QTextStream out(&file);\n\n QString outString = \n WallpaperCurrentDescriptor::instance()->generateDesktopFile (path);\n SYS_DEBUG (\"outString = %s\", SYS_STR(outString));\n\n \/*\n * Then this is deprecated.\n *\/\n out << \"[Desktop Entry]\\n\";\n out << \"Type=WallpaperImage\\n\";\n out << \"Name=\" << desc->title() << \"\\n\";\n out << \"Version=\" << QString::number(version) << \"\\n\";\n out << \"\\n\";\n\n out << \"[DCP Landscape Wallpaper]\\n\";\n out << \"OriginalFile=\" << desc->originalImageFile(M::Landscape) << \"\\n\";\n out << \"EditedFile=\" << landscapeFilePath << \"\\n\";\n out << \"MimeType=\" << desc->mimeType() << \"\\n\";\n out << \"HorOffset=\" << landscapeITrans->x() << \"\\n\";\n out << \"VertOffset=\" << landscapeITrans->y() << \"\\n\";\n out << \"Scale=\" << landscapeITrans->scale() << \"\\n\";\n out << \"\\n\";\n\n out << \"[DCP Portrait Wallpaper]\\n\";\n out << \"OriginalFile=\" << desc->originalImageFile(M::Portrait) << \"\\n\";\n out << \"EditedFile=\" << portraitFilePath << \"\\n\";\n out << \"MimeType=\" << desc->mimeType() << \"\\n\";\n out << \"HorOffset=\" << portraitITrans->x() << \"\\n\";\n out << \"VertOffset=\" << portraitITrans->y() << \"\\n\";\n out << \"Scale=\" << portraitITrans->scale() << \"\\n\";\n out << \"\\n\";\n\n makeImageFile (portraitFilePath, desc, portraitITrans);\n makeImageFile (landscapeFilePath, desc, landscapeITrans);\n \n m_PortraitGConfItem->set (portraitFilePath);\n m_LandscapeGConfItem->set (landscapeFilePath);\n\n return true;\n}\n\n\/*!\n * \\param filePath The path of the file to save the image into.\n * \\param desc The image that should be saved.\n * \\param transformations The structure that descibes how to modify the image.\n *\n * This is a low level image manupilation method that takes a wallpaper and\n * saves it into a file with the given manupilations.\n * \n * FIXME: Maybe this method should be moved into some other class?\n *\/\nvoid\nWallpaperBusinessLogic::makeImageFile (\n const QString &filePath,\n WallpaperDescriptor *desc,\n WallpaperITrans *transformations)\n{\n QPixmap pixmap (transformations->expectedSize());\n QPainter painter (&pixmap);\n qreal scale = transformations->scale();\n QPixmap image;\n qreal ratio, ratio1;\n\n \/*\n * And this is exactly why we should move this kind of stuff into the image\n * descriptor classes.\n *\/\n if (desc->isCurrent()) {\n WallpaperCurrentDescriptor *cdesc;\n \n cdesc = qobject_cast (desc);\n image.load (cdesc->originalImageFile (transformations->orientation()));\n } else {\n image = desc->pixmap();\n }\n\n ratio = \n (qreal) transformations->expectedHeight () \/ \n (qreal) image.height();\n\n ratio1 = \n (qreal) transformations->expectedWidth () \/ \n (qreal) image.width();\n \n if (ratio1 > ratio)\n ratio = ratio1;\n\n \/*\n * Let's fill the pixmap with black, so the area not covered by the original\n * pixmap is initialized.\n *\/\n pixmap.fill (QColor(\"black\"));\n \n \/*\n * Then we draw the scaled image with the appropriate offset.\n *\/\n painter.drawPixmap (\n transformations->x(), transformations->y(),\n (scale * image.width ()) * ratio,\n (scale * image.height ()) * ratio,\n image);\n\n pixmap.save (filePath);\n}\n\n\/*!\n * Takes a full path file name, removes its backup file if there is one, renames\n * the file to create a backup file.\n *\/\nvoid \nWallpaperBusinessLogic::makeBackup (\n const QString &filePath)\n{\n QString backupFilePath = filePath + backupExtension;\n QFile file (filePath);\n QFile backupFile (backupFilePath);\n\n if (!file.exists())\n return;\n \n if (backupFile.exists()) {\n if (!backupFile.remove()) {\n SYS_WARNING (\"Unable to remove %s backup file.\", \n SYS_STR(backupFilePath));\n return;\n }\n }\n\n SYS_DEBUG (\"Moving %s -> %s\", SYS_STR(filePath), SYS_STR(backupFilePath));\n file.rename (backupFilePath);\n}\n\nGConf keys fixed.\/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- *\/\n\/* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino=\"(0,W2s,i2s,t0,l1,:0\" *\/\n\n#include \"wallpaperbusinesslogic.h\"\n#include \"wallpaperdescriptor.h\"\n#include \"wallpapercurrentdescriptor.h\"\n#include \"wallpaperitrans.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#define DEBUG\n#include \"..\/debug.h\"\n\nstatic const QString PortraitKey = \n \"\/desktop\/meego\/background\/portrait\/picture_filename\";\nstatic const QString LandscapeKey = \n \"\/desktop\/meego\/background\/landscape\/picture_filename\";\n\nstatic const QString wallpaperDir = \".wallpapers\";\nstatic const QString destopFileName = \"wallpaper.desktop\";\nstatic const QString backupExtension = \".BAK\";\n\nWallpaperBusinessLogic::WallpaperBusinessLogic()\n{\n WallpaperCurrentDescriptor *currentDesc;\n \n m_LandscapeGConfItem = new MGConfItem (LandscapeKey);\n m_PortraitGConfItem = new MGConfItem (PortraitKey);\n m_EditedImage = 0;\n\n currentDesc = WallpaperCurrentDescriptor::instance ();\n currentDesc->setFromDestopFile (dirPath() + destopFileName);\n}\n\nWallpaperBusinessLogic::~WallpaperBusinessLogic()\n{\n delete m_LandscapeGConfItem;\n delete m_PortraitGConfItem;\n}\n\n\/*!\n * FIXME: This method is deprecated, should use the \n * WallpaperCurrentDescriptor::instance () instead.\n *\/\nWallpaperDescriptor *\nWallpaperBusinessLogic::Wallpaper (\n bool portrait)\n{\n Q_UNUSED (portrait);\n SYS_WARNING (\"Deprecated method.\");\n return WallpaperCurrentDescriptor::instance ();\n}\n\n\/*!\n * A high level method to set the current wallpaper.\n *\/\nvoid\nWallpaperBusinessLogic::setBackground (\n WallpaperITrans *landscapeITrans,\n WallpaperITrans *portraitITrans,\n WallpaperDescriptor *desc)\n{\n bool success;\n\n SYS_DEBUG (\"******** Saving background *********\");\n if (desc == 0)\n desc = m_EditedImage;\n\n Q_ASSERT (landscapeITrans);\n Q_ASSERT (portraitITrans);\n Q_ASSERT (desc);\n\n success = ensureHasDirectory ();\n if (!success)\n return;\n\n createBackupFiles ();\n\n success = writeFiles (landscapeITrans, portraitITrans, desc);\n if (!success) {\n \/\/ FIXME: Should restore backup files here.\n return;\n }\n \n deleteBackupFiles ();\n\n \/*\n *\n *\/\n WallpaperCurrentDescriptor *currentDesc;\n currentDesc = WallpaperCurrentDescriptor::instance ();\n currentDesc->setFromDestopFile (dirPath() + destopFileName);\n emit wallpaperChanged ();\n\n SYS_DEBUG (\"****** End saving backgroun ********\");\n}\n\n\/*!\n * This function does not support image manipulatios, it is deprecated.\n * FIXME: To remove this function.\n *\/\nvoid\nWallpaperBusinessLogic::setBackground (\n WallpaperDescriptor *desc)\n{\n if (desc == 0)\n desc = m_EditedImage;\n\n SYS_WARNING (\"Deprecated method.\");\n Q_ASSERT (m_PortraitGConfItem != 0);\n Q_ASSERT (m_LandscapeGConfItem != 0);\n\n SYS_DEBUG (\"*** filename = %s\", SYS_STR(desc->filename()));\n m_PortraitGConfItem->set (desc->filename());\n m_LandscapeGConfItem->set (desc->filename());\n}\n\n\n\n\/*!\n * Returns a list wallpaper descriptors with the available wallpapers. The\n * current wallpaper is the first element of the available wallpapers.\n *\n * FIXME: This function needs some polishing.\n *\/\nQList\nWallpaperBusinessLogic::availableWallpapers () const\n{\n QList list;\n const QString query = \n\"SELECT ?uri ?title ?mime ?height ?width WHERE { \"\n\" ?item nie:url ?uri.\" \n\n\" ?item nie:mimeType ?mime.\" \n\" FILTER regex(?mime, \\\"image\\\").\"\n\n\" ?item nfo:height ?height.\"\n\" ?item nfo:width ?width.\"\n\" FILTER ( ?height > \\\"300\\\" ).\"\n\" FILTER ( ?width > \\\"300\\\" ).\"\n\n\" OPTIONAL { ?item nie:title ?title }.\"\n\"}\"\n;\n\n WallpaperCurrentDescriptor *currentDesc;\n\n currentDesc = WallpaperCurrentDescriptor::instance ();\n list << WallpaperCurrentDescriptor::instance ();\n\n QVector result = ::tracker()->rawSparqlQuery(query);\n int x = 0;\n int y = 0;\n\n SYS_WARNING (\"*** result.size() = %d\", result.size());\n foreach (QStringList partlist, result) {\n WallpaperDescriptor *desc;\n\n SYS_DEBUG (\"*********************************\");\n SYS_DEBUG (\"*** url = %s\", SYS_STR(partlist[FieldUrl]));\n\n desc = new WallpaperDescriptor;\n desc->setUrl (partlist[FieldUrl]);\n desc->setTitle (partlist[FieldTitle]);\n desc->setMimeType (partlist[FieldMime]);\n list << desc;\n\n \/*\n * Just to see what we really get.\n *\/\n #if 1\n foreach (QString element, partlist) {\n SYS_DEBUG (\"*** element[%2d][%2d] = %s\", x, y, SYS_STR(element));\n x++;\n }\n x = 0;\n #endif\n \n y++;\n }\n\n return list;\n}\n\n\/*!\n * While a wallpaper image is edited the WallpaperBusinessLogic holds a\n * descriptor on it. This function is used to set this wallpaper descriptor.\n *\/\nvoid\nWallpaperBusinessLogic::setEditedImage (\n WallpaperDescriptor *desc)\n{\n SYS_DEBUG (\"*** desc = %s\", SYS_STR(desc->filename()));\n m_EditedImage = desc;\n}\n\n\/*!\n * Returns the wallpaper that is being edited.\n *\/\nWallpaperDescriptor *\nWallpaperBusinessLogic::editedImage ()\n{\n SYS_DEBUG (\"*** m_EditedImage = %s\", SYS_STR(m_EditedImage->filename()));\n return m_EditedImage;\n}\n\n\/*********************************************************************************\n * Low level file handling functions.\n *\/\n\n\/*!\n * Returns the directory path that is used to store the information about the\n * edited wallpaper. This is the data storing directory for the wallpaper\n * applet.\n *\/\nQString\nWallpaperBusinessLogic::dirPath () const\n{\n QString homeDir (getenv(\"HOME\"));\n QString dirPath = homeDir + \"\/\" + wallpaperDir + \"\/\";\n\n return dirPath;\n}\n\n\/*!\n * \\returns true if the directory exists or could be created\n *\n * If the data store directory does not exists this method will create it.\n *\/\nbool\nWallpaperBusinessLogic::ensureHasDirectory ()\n{\n QString path = dirPath();\n QDir dir (path);\n\n if (dir.exists()) {\n SYS_DEBUG (\"Directory %s already exists.\", SYS_STR(path));\n return true;\n }\n\n if (!dir.mkpath(path)) {\n SYS_WARNING (\"Unable to create %s directory.\", SYS_STR(path));\n return false;\n }\n\n return true;\n}\n\n\/*!\n * Takes the desktop file, the saved landscape image file and the saved portrait\n * file and moves\/renames them to create a backup version of each of them.\n *\/\nvoid\nWallpaperBusinessLogic::createBackupFiles ()\n{\n QString path = dirPath();\n QString desktopPath = path + destopFileName;\n QString filename;\n \n makeBackup (desktopPath);\n\n filename = WallpaperCurrentDescriptor::instance()->editedFilename (\n M::Portrait);\n if (!filename.isEmpty())\n makeBackup (filename);\n\n filename = WallpaperCurrentDescriptor::instance()->editedFilename (\n M::Landscape);\n if (!filename.isEmpty())\n makeBackup (filename);\n}\n\n\/*!\n * Removes all the files from the applet's data directory that has the file name\n * extension indicating that it is a backup file.\n *\/\nvoid\nWallpaperBusinessLogic::deleteBackupFiles ()\n{\n QString path = dirPath();\n QDir dir (path);\n QStringList nameFilters (\"*.BAK\");\n\n dir.setNameFilters (nameFilters);\n foreach (QString backupFileName, dir.entryList (QDir::Files)) {\n SYS_DEBUG (\"Removing backup file %s\", SYS_STR(backupFileName));\n QFile backupFile (path + backupFileName);\n\n if (!backupFile.remove()) {\n SYS_WARNING (\"Unable to remove %s backup file.\",\n SYS_STR((path + backupFileName)));\n }\n }\n}\n\n\/*!\n * \\returns true if the files could be created and saved.\n *\n * FIXME: This method should and will be moved to the WallpaperCurrentDescriptor\n * class.\n *\/\nbool\nWallpaperBusinessLogic::writeFiles (\n WallpaperITrans *landscapeITrans,\n WallpaperITrans *portraitITrans,\n WallpaperDescriptor *desc)\n{\n Q_ASSERT (landscapeITrans);\n Q_ASSERT (portraitITrans);\n Q_ASSERT (desc);\n \/*\n * These are pretty constants.\n *\/\n QString path = dirPath();\n QString desktopPath = path + destopFileName;\n QFile file (desktopPath);\n\n int version = desc->version () + 1;\n QString versionString = QString::number(version);\n QString portraitFilePath = path + \n desc->suggestedOutputFilename (M::Portrait);\n QString landscapeFilePath = path + \n desc->suggestedOutputFilename (M::Landscape);\n\n\n \/*\n * Opening the output file.\n *\/\n if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n SYS_DEBUG (\"Opening file %s for writing failed.\", SYS_STR(desktopPath));\n return false;\n }\n\n \/*\n * FIXME: This is the new stuff, but in order to use it the current\n * wallpaper descriptor has to be upgraded with from the arguments of this\n * method.\n *\/\n QTextStream out(&file);\n\n QString outString = \n WallpaperCurrentDescriptor::instance()->generateDesktopFile (path);\n SYS_DEBUG (\"outString = %s\", SYS_STR(outString));\n\n \/*\n * Then this is deprecated.\n *\/\n out << \"[Desktop Entry]\\n\";\n out << \"Type=WallpaperImage\\n\";\n out << \"Name=\" << desc->title() << \"\\n\";\n out << \"Version=\" << QString::number(version) << \"\\n\";\n out << \"\\n\";\n\n out << \"[DCP Landscape Wallpaper]\\n\";\n out << \"OriginalFile=\" << desc->originalImageFile(M::Landscape) << \"\\n\";\n out << \"EditedFile=\" << landscapeFilePath << \"\\n\";\n out << \"MimeType=\" << desc->mimeType() << \"\\n\";\n out << \"HorOffset=\" << landscapeITrans->x() << \"\\n\";\n out << \"VertOffset=\" << landscapeITrans->y() << \"\\n\";\n out << \"Scale=\" << landscapeITrans->scale() << \"\\n\";\n out << \"\\n\";\n\n out << \"[DCP Portrait Wallpaper]\\n\";\n out << \"OriginalFile=\" << desc->originalImageFile(M::Portrait) << \"\\n\";\n out << \"EditedFile=\" << portraitFilePath << \"\\n\";\n out << \"MimeType=\" << desc->mimeType() << \"\\n\";\n out << \"HorOffset=\" << portraitITrans->x() << \"\\n\";\n out << \"VertOffset=\" << portraitITrans->y() << \"\\n\";\n out << \"Scale=\" << portraitITrans->scale() << \"\\n\";\n out << \"\\n\";\n\n makeImageFile (portraitFilePath, desc, portraitITrans);\n makeImageFile (landscapeFilePath, desc, landscapeITrans);\n \n m_PortraitGConfItem->set (portraitFilePath);\n m_LandscapeGConfItem->set (landscapeFilePath);\n\n return true;\n}\n\n\/*!\n * \\param filePath The path of the file to save the image into.\n * \\param desc The image that should be saved.\n * \\param transformations The structure that descibes how to modify the image.\n *\n * This is a low level image manupilation method that takes a wallpaper and\n * saves it into a file with the given manupilations.\n * \n * FIXME: Maybe this method should be moved into some other class?\n *\/\nvoid\nWallpaperBusinessLogic::makeImageFile (\n const QString &filePath,\n WallpaperDescriptor *desc,\n WallpaperITrans *transformations)\n{\n QPixmap pixmap (transformations->expectedSize());\n QPainter painter (&pixmap);\n qreal scale = transformations->scale();\n QPixmap image;\n qreal ratio, ratio1;\n\n \/*\n * And this is exactly why we should move this kind of stuff into the image\n * descriptor classes.\n *\/\n if (desc->isCurrent()) {\n WallpaperCurrentDescriptor *cdesc;\n \n cdesc = qobject_cast (desc);\n image.load (cdesc->originalImageFile (transformations->orientation()));\n } else {\n image = desc->pixmap();\n }\n\n ratio = \n (qreal) transformations->expectedHeight () \/ \n (qreal) image.height();\n\n ratio1 = \n (qreal) transformations->expectedWidth () \/ \n (qreal) image.width();\n \n if (ratio1 > ratio)\n ratio = ratio1;\n\n \/*\n * Let's fill the pixmap with black, so the area not covered by the original\n * pixmap is initialized.\n *\/\n pixmap.fill (QColor(\"black\"));\n \n \/*\n * Then we draw the scaled image with the appropriate offset.\n *\/\n painter.drawPixmap (\n transformations->x(), transformations->y(),\n (scale * image.width ()) * ratio,\n (scale * image.height ()) * ratio,\n image);\n\n pixmap.save (filePath);\n}\n\n\/*!\n * Takes a full path file name, removes its backup file if there is one, renames\n * the file to create a backup file.\n *\/\nvoid \nWallpaperBusinessLogic::makeBackup (\n const QString &filePath)\n{\n QString backupFilePath = filePath + backupExtension;\n QFile file (filePath);\n QFile backupFile (backupFilePath);\n\n if (!file.exists())\n return;\n \n if (backupFile.exists()) {\n if (!backupFile.remove()) {\n SYS_WARNING (\"Unable to remove %s backup file.\", \n SYS_STR(backupFilePath));\n return;\n }\n }\n\n SYS_DEBUG (\"Moving %s -> %s\", SYS_STR(filePath), SYS_STR(backupFilePath));\n file.rename (backupFilePath);\n}\n\n<|endoftext|>"} {"text":"\/\/===- DeadMachineInstructionElim.cpp - Remove dead machine instructions --===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This is an extremely simple MachineInstr-level dead-code-elimination pass.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\nusing namespace llvm;\n\nnamespace {\n class DeadMachineInstructionElim : public MachineFunctionPass {\n virtual bool runOnMachineFunction(MachineFunction &MF);\n \n const TargetRegisterInfo *TRI;\n const MachineRegisterInfo *MRI;\n const TargetInstrInfo *TII;\n BitVector LivePhysRegs;\n\n public:\n static char ID; \/\/ Pass identification, replacement for typeid\n DeadMachineInstructionElim() : MachineFunctionPass(&ID) {}\n\n private:\n bool isDead(const MachineInstr *MI) const;\n };\n}\nchar DeadMachineInstructionElim::ID = 0;\n\nstatic RegisterPass\nY(\"dead-mi-elimination\",\n \"Remove dead machine instructions\");\n\nFunctionPass *llvm::createDeadMachineInstructionElimPass() {\n return new DeadMachineInstructionElim();\n}\n\nbool DeadMachineInstructionElim::isDead(const MachineInstr *MI) const {\n \/\/ Don't delete instructions with side effects.\n bool SawStore = false;\n if (!MI->isSafeToMove(TII, SawStore, 0))\n return false;\n\n \/\/ Examine each operand.\n for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {\n const MachineOperand &MO = MI->getOperand(i);\n if (MO.isReg() && MO.isDef()) {\n unsigned Reg = MO.getReg();\n if (TargetRegisterInfo::isPhysicalRegister(Reg) ?\n LivePhysRegs[Reg] : !MRI->use_empty(Reg)) {\n \/\/ This def has a use. Don't delete the instruction!\n return false;\n }\n }\n }\n\n \/\/ If there are no defs with uses, the instruction is dead.\n return true;\n}\n\nbool DeadMachineInstructionElim::runOnMachineFunction(MachineFunction &MF) {\n bool AnyChanges = false;\n MRI = &MF.getRegInfo();\n TRI = MF.getTarget().getRegisterInfo();\n TII = MF.getTarget().getInstrInfo();\n\n \/\/ Compute a bitvector to represent all non-allocatable physregs.\n BitVector NonAllocatableRegs = TRI->getAllocatableSet(MF);\n NonAllocatableRegs.flip();\n\n \/\/ Loop over all instructions in all blocks, from bottom to top, so that it's\n \/\/ more likely that chains of dependent but ultimately dead instructions will\n \/\/ be cleaned up.\n for (MachineFunction::reverse_iterator I = MF.rbegin(), E = MF.rend();\n I != E; ++I) {\n MachineBasicBlock *MBB = &*I;\n\n \/\/ Start out assuming that all non-allocatable registers are live\n \/\/ out of this block.\n LivePhysRegs = NonAllocatableRegs;\n\n \/\/ Also add any explicit live-out physregs for this block.\n if (!MBB->empty() && MBB->back().getDesc().isReturn())\n for (MachineRegisterInfo::liveout_iterator LOI = MRI->liveout_begin(),\n LOE = MRI->liveout_end(); LOI != LOE; ++LOI) {\n unsigned Reg = *LOI;\n if (TargetRegisterInfo::isPhysicalRegister(Reg))\n LivePhysRegs.set(Reg);\n }\n\n \/\/ Now scan the instructions and delete dead ones, tracking physreg\n \/\/ liveness as we go.\n for (MachineBasicBlock::reverse_iterator MII = MBB->rbegin(),\n MIE = MBB->rend(); MII != MIE; ) {\n MachineInstr *MI = &*MII;\n\n \/\/ If the instruction is dead, delete it!\n if (isDead(MI)) {\n DEBUG(dbgs() << \"DeadMachineInstructionElim: DELETING: \" << *MI);\n AnyChanges = true;\n MI->eraseFromParent();\n MIE = MBB->rend();\n \/\/ MII is now pointing to the next instruction to process,\n \/\/ so don't increment it.\n continue;\n }\n\n \/\/ Record the physreg defs.\n for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {\n const MachineOperand &MO = MI->getOperand(i);\n if (MO.isReg() && MO.isDef()) {\n unsigned Reg = MO.getReg();\n if (Reg != 0 && TargetRegisterInfo::isPhysicalRegister(Reg)) {\n LivePhysRegs.reset(Reg);\n \/\/ Check the subreg set, not the alias set, because a def\n \/\/ of a super-register may still be partially live after\n \/\/ this def.\n for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);\n *SubRegs; ++SubRegs)\n LivePhysRegs.reset(*SubRegs);\n }\n }\n }\n \/\/ Record the physreg uses, after the defs, in case a physreg is\n \/\/ both defined and used in the same instruction.\n for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {\n const MachineOperand &MO = MI->getOperand(i);\n if (MO.isReg() && MO.isUse()) {\n unsigned Reg = MO.getReg();\n if (Reg != 0 && TargetRegisterInfo::isPhysicalRegister(Reg)) {\n LivePhysRegs.set(Reg);\n for (const unsigned *AliasSet = TRI->getAliasSet(Reg);\n *AliasSet; ++AliasSet)\n LivePhysRegs.set(*AliasSet);\n }\n }\n }\n\n \/\/ We didn't delete the current instruction, so increment MII to\n \/\/ the next one.\n ++MII;\n }\n }\n\n LivePhysRegs.clear();\n return AnyChanges;\n}\nIf the only use of something is a DEBUG_VALUE, don't let that stop it from being deleted, and change the DEBUG_VALUE value to undef.\/\/===- DeadMachineInstructionElim.cpp - Remove dead machine instructions --===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This is an extremely simple MachineInstr-level dead-code-elimination pass.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\nusing namespace llvm;\n\nnamespace {\n class DeadMachineInstructionElim : public MachineFunctionPass {\n virtual bool runOnMachineFunction(MachineFunction &MF);\n \n const TargetRegisterInfo *TRI;\n const MachineRegisterInfo *MRI;\n const TargetInstrInfo *TII;\n BitVector LivePhysRegs;\n\n public:\n static char ID; \/\/ Pass identification, replacement for typeid\n DeadMachineInstructionElim() : MachineFunctionPass(&ID) {}\n\n private:\n bool isDead(const MachineInstr *MI) const;\n };\n}\nchar DeadMachineInstructionElim::ID = 0;\n\nstatic RegisterPass\nY(\"dead-mi-elimination\",\n \"Remove dead machine instructions\");\n\nFunctionPass *llvm::createDeadMachineInstructionElimPass() {\n return new DeadMachineInstructionElim();\n}\n\nbool DeadMachineInstructionElim::isDead(const MachineInstr *MI) const {\n \/\/ Don't delete instructions with side effects.\n bool SawStore = false;\n if (!MI->isSafeToMove(TII, SawStore, 0))\n return false;\n\n \/\/ Examine each operand.\n for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {\n const MachineOperand &MO = MI->getOperand(i);\n if (MO.isReg() && MO.isDef()) {\n unsigned Reg = MO.getReg();\n if (TargetRegisterInfo::isPhysicalRegister(Reg) ?\n LivePhysRegs[Reg] : !MRI->use_empty(Reg)) {\n \/\/ This def has a use. Don't delete the instruction!\n return false;\n }\n }\n }\n\n \/\/ If there are no defs with uses, the instruction is dead.\n return true;\n}\n\nbool DeadMachineInstructionElim::runOnMachineFunction(MachineFunction &MF) {\n bool AnyChanges = false;\n MRI = &MF.getRegInfo();\n TRI = MF.getTarget().getRegisterInfo();\n TII = MF.getTarget().getInstrInfo();\n\n \/\/ Compute a bitvector to represent all non-allocatable physregs.\n BitVector NonAllocatableRegs = TRI->getAllocatableSet(MF);\n NonAllocatableRegs.flip();\n\n \/\/ Loop over all instructions in all blocks, from bottom to top, so that it's\n \/\/ more likely that chains of dependent but ultimately dead instructions will\n \/\/ be cleaned up.\n for (MachineFunction::reverse_iterator I = MF.rbegin(), E = MF.rend();\n I != E; ++I) {\n MachineBasicBlock *MBB = &*I;\n\n \/\/ Start out assuming that all non-allocatable registers are live\n \/\/ out of this block.\n LivePhysRegs = NonAllocatableRegs;\n\n \/\/ Also add any explicit live-out physregs for this block.\n if (!MBB->empty() && MBB->back().getDesc().isReturn())\n for (MachineRegisterInfo::liveout_iterator LOI = MRI->liveout_begin(),\n LOE = MRI->liveout_end(); LOI != LOE; ++LOI) {\n unsigned Reg = *LOI;\n if (TargetRegisterInfo::isPhysicalRegister(Reg))\n LivePhysRegs.set(Reg);\n }\n\n \/\/ Now scan the instructions and delete dead ones, tracking physreg\n \/\/ liveness as we go.\n for (MachineBasicBlock::reverse_iterator MII = MBB->rbegin(),\n MIE = MBB->rend(); MII != MIE; ) {\n MachineInstr *MI = &*MII;\n\n if (MI->getOpcode()==TargetInstrInfo::DEBUG_VALUE) {\n \/\/ Don't delete the DEBUG_VALUE itself, but if its Value operand is\n \/\/ a vreg and this is the only use, substitute an undef operand;\n \/\/ the former operand will then be deleted normally.\n if (MI->getNumOperands()==3 && MI->getOperand(0).isReg()) {\n unsigned Reg = MI->getOperand(0).getReg();\n MachineRegisterInfo::use_iterator I = MRI->use_begin(Reg);\n assert(I != MRI->use_end());\n if (++I == MRI->use_end())\n \/\/ only one use, which must be this DEBUG_VALUE.\n MI->getOperand(0).setReg(0U);\n }\n }\n\n \/\/ If the instruction is dead, delete it!\n if (isDead(MI)) {\n DEBUG(dbgs() << \"DeadMachineInstructionElim: DELETING: \" << *MI);\n AnyChanges = true;\n MI->eraseFromParent();\n MIE = MBB->rend();\n \/\/ MII is now pointing to the next instruction to process,\n \/\/ so don't increment it.\n continue;\n }\n\n \/\/ Record the physreg defs.\n for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {\n const MachineOperand &MO = MI->getOperand(i);\n if (MO.isReg() && MO.isDef()) {\n unsigned Reg = MO.getReg();\n if (Reg != 0 && TargetRegisterInfo::isPhysicalRegister(Reg)) {\n LivePhysRegs.reset(Reg);\n \/\/ Check the subreg set, not the alias set, because a def\n \/\/ of a super-register may still be partially live after\n \/\/ this def.\n for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);\n *SubRegs; ++SubRegs)\n LivePhysRegs.reset(*SubRegs);\n }\n }\n }\n \/\/ Record the physreg uses, after the defs, in case a physreg is\n \/\/ both defined and used in the same instruction.\n for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {\n const MachineOperand &MO = MI->getOperand(i);\n if (MO.isReg() && MO.isUse()) {\n unsigned Reg = MO.getReg();\n if (Reg != 0 && TargetRegisterInfo::isPhysicalRegister(Reg)) {\n LivePhysRegs.set(Reg);\n for (const unsigned *AliasSet = TRI->getAliasSet(Reg);\n *AliasSet; ++AliasSet)\n LivePhysRegs.set(*AliasSet);\n }\n }\n }\n\n \/\/ We didn't delete the current instruction, so increment MII to\n \/\/ the next one.\n ++MII;\n }\n }\n\n LivePhysRegs.clear();\n return AnyChanges;\n}\n<|endoftext|>"} {"text":"\/\/===- DependenceAnalysis.cpp - Dependence analysis on SSA views ----------===\/\/\n\/\/\n\/\/ Copyright 2019 The MLIR Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ =============================================================================\n\/\/\n\/\/ This file implements view-based alias and dependence analyses.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"mlir\/Linalg\/Analysis\/DependenceAnalysis.h\"\n#include \"mlir\/Linalg\/IR\/LinalgOps.h\"\n\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Debug.h\"\n\n#define DEBUG_TYPE \"linalg-dependence-analysis\"\n\nusing namespace mlir;\nusing namespace mlir::linalg;\n\nusing llvm::dbgs;\n\nValue *Aliases::find(Value *v) {\n if (v->getKind() == Value::Kind::BlockArgument)\n return v;\n\n auto it = aliases.find(v);\n if (it != aliases.end()) {\n assert((it->getSecond()->getKind() == Value::Kind::BlockArgument &&\n it->getSecond()->getType().isa()) ||\n it->getSecond()->getType().isa() &&\n \"Buffer or block argument expected\");\n return it->getSecond();\n }\n if (auto slice = dyn_cast_or_null(v->getDefiningOp())) {\n auto it = aliases.insert(std::make_pair(v, find(slice.getBaseView())));\n return it.first->second;\n }\n if (auto view = dyn_cast_or_null(v->getDefiningOp())) {\n auto it = aliases.insert(std::make_pair(v, view.getSupportingBuffer()));\n return it.first->second;\n }\n llvm_unreachable(\"unsupported view alias case\");\n}\n\nLinalgDependenceGraph::LinalgDependenceGraph(Aliases &aliases,\n ArrayRef ops)\n : aliases(aliases), linalgOps(ops.begin(), ops.end()) {\n for (auto en : llvm::enumerate(linalgOps)) {\n assert(isa(en.value()) && \"Expected value for LinalgOp\");\n linalgOpPositions.insert(make_pair(en.value(), en.index()));\n }\n for (unsigned i = 0, e = ops.size(); i < e; ++i) {\n for (unsigned j = i + 1; j < e; ++j) {\n addDependencesBetween(cast(ops[i]), cast(ops[j]));\n }\n }\n}\n\nvoid LinalgDependenceGraph::addDependenceElem(DependenceType dt,\n LinalgOpView indexingOpView,\n LinalgOpView dependentOpView) {\n LLVM_DEBUG(dbgs() << \"\\nAdd dep type \" << dt << \":\\t\" << *indexingOpView.op\n << \" -> \" << *dependentOpView.op);\n dependencesFromGraphs[dt][indexingOpView.op].push_back(\n LinalgDependenceGraphElem{dependentOpView, indexingOpView.view});\n dependencesIntoGraphs[dt][dependentOpView.op].push_back(\n LinalgDependenceGraphElem{indexingOpView, dependentOpView.view});\n}\n\nLinalgDependenceGraph::dependence_range\nLinalgDependenceGraph::getDependencesFrom(\n LinalgOp src, LinalgDependenceGraph::DependenceType dt) {\n return getDependencesFrom(src.getOperation(), dt);\n}\n\nLinalgDependenceGraph::dependence_range\nLinalgDependenceGraph::getDependencesFrom(\n Operation *src, LinalgDependenceGraph::DependenceType dt) {\n auto &vec = dependencesFromGraphs[dt][src];\n return llvm::make_range(vec.begin(), vec.end());\n}\n\nLinalgDependenceGraph::dependence_range\nLinalgDependenceGraph::getDependencesInto(\n LinalgOp dst, LinalgDependenceGraph::DependenceType dt) {\n return getDependencesInto(dst.getOperation(), dt);\n}\n\nLinalgDependenceGraph::dependence_range\nLinalgDependenceGraph::getDependencesInto(\n Operation *dst, LinalgDependenceGraph::DependenceType dt) {\n auto &vec = dependencesIntoGraphs[dt][dst];\n return llvm::make_range(vec.begin(), vec.end());\n}\n\nvoid LinalgDependenceGraph::addDependencesBetween(LinalgOp src, LinalgOp dst) {\n for (auto *srcView : src.getOutputs()) { \/\/ W\n \/\/ RAW graph\n for (auto *dstView : dst.getInputs()) { \/\/ R\n if (aliases.alias(srcView, dstView)) { \/\/ if alias, fill RAW\n addDependenceElem(DependenceType::RAW,\n LinalgOpView{src.getOperation(), srcView},\n LinalgOpView{dst.getOperation(), dstView});\n }\n }\n \/\/ WAW graph\n for (auto *dstView : dst.getOutputs()) { \/\/ W\n if (aliases.alias(srcView, dstView)) { \/\/ if alias, fill WAW\n addDependenceElem(DependenceType::WAW,\n LinalgOpView{src.getOperation(), srcView},\n LinalgOpView{dst.getOperation(), dstView});\n }\n }\n }\n for (auto *srcView : src.getInputs()) { \/\/ R\n \/\/ RAR graph\n for (auto *dstView : dst.getInputs()) { \/\/ R\n if (aliases.alias(srcView, dstView)) { \/\/ if alias, fill RAR\n addDependenceElem(DependenceType::RAR,\n LinalgOpView{src.getOperation(), srcView},\n LinalgOpView{dst.getOperation(), dstView});\n }\n }\n \/\/ WAR graph\n for (auto *dstView : dst.getOutputs()) { \/\/ W\n if (aliases.alias(srcView, dstView)) { \/\/ if alias, fill WAR\n addDependenceElem(DependenceType::WAR,\n LinalgOpView{src.getOperation(), srcView},\n LinalgOpView{dst.getOperation(), dstView});\n }\n }\n }\n}\n\nSmallVector\nLinalgDependenceGraph::findCoveringDependences(LinalgOp srcLinalgOp,\n LinalgOp dstLinalgOp) {\n return findOperationsWithCoveringDependences(\n srcLinalgOp, dstLinalgOp, nullptr,\n {DependenceType::WAW, DependenceType::WAR, DependenceType::RAW});\n}\n\nSmallVector\nLinalgDependenceGraph::findCoveringWrites(LinalgOp srcLinalgOp,\n LinalgOp dstLinalgOp, Value *view) {\n return findOperationsWithCoveringDependences(\n srcLinalgOp, dstLinalgOp, view,\n {DependenceType::WAW, DependenceType::WAR});\n}\n\nSmallVector\nLinalgDependenceGraph::findCoveringReads(LinalgOp srcLinalgOp,\n LinalgOp dstLinalgOp, Value *view) {\n return findOperationsWithCoveringDependences(\n srcLinalgOp, dstLinalgOp, view,\n {DependenceType::RAR, DependenceType::RAW});\n}\n\nSmallVector\nLinalgDependenceGraph::findOperationsWithCoveringDependences(\n LinalgOp srcLinalgOp, LinalgOp dstLinalgOp, Value *view,\n ArrayRef types) {\n auto *src = srcLinalgOp.getOperation();\n auto *dst = dstLinalgOp.getOperation();\n auto srcPos = linalgOpPositions[src];\n auto dstPos = linalgOpPositions[dst];\n assert(srcPos < dstPos && \"expected dst after src in IR traversal order\");\n\n SmallVector res;\n \/\/ Consider an intermediate interleaved `interim` op, look for any dependence\n \/\/ to an aliasing view on a src -> op -> dst path.\n \/\/ TODO(ntv) we are not considering paths yet, just interleaved positions.\n for (auto dt : types) {\n for (auto dependence : getDependencesFrom(src, dt)) {\n auto interimPos = linalgOpPositions[dependence.dependentOpView.op];\n \/\/ Skip if not interleaved.\n if (interimPos >= dstPos || interimPos <= srcPos)\n continue;\n if (view && !aliases.alias(view, dependence.indexingView))\n continue;\n auto *op = dependence.dependentOpView.op;\n LLVM_DEBUG(dbgs() << \"\\n***Found covering dependence of type \" << dt\n << \": \" << *src << \" -> \" << *op << \" on \"\n << *dependence.indexingView);\n res.push_back(op);\n }\n }\n return res;\n}\nFix OSS build\/\/===- DependenceAnalysis.cpp - Dependence analysis on SSA views ----------===\/\/\n\/\/\n\/\/ Copyright 2019 The MLIR Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ =============================================================================\n\/\/\n\/\/ This file implements view-based alias and dependence analyses.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"mlir\/Linalg\/Analysis\/DependenceAnalysis.h\"\n#include \"mlir\/Linalg\/IR\/LinalgOps.h\"\n\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Debug.h\"\n\n#define DEBUG_TYPE \"linalg-dependence-analysis\"\n\nusing namespace mlir;\nusing namespace mlir::linalg;\n\nusing llvm::dbgs;\n\nValue *Aliases::find(Value *v) {\n if (v->getKind() == Value::Kind::BlockArgument)\n return v;\n\n auto it = aliases.find(v);\n if (it != aliases.end()) {\n assert(((it->getSecond()->getKind() == Value::Kind::BlockArgument &&\n it->getSecond()->getType().isa()) ||\n it->getSecond()->getType().isa()) &&\n \"Buffer or block argument expected\");\n return it->getSecond();\n }\n if (auto slice = dyn_cast_or_null(v->getDefiningOp())) {\n auto it = aliases.insert(std::make_pair(v, find(slice.getBaseView())));\n return it.first->second;\n }\n if (auto view = dyn_cast_or_null(v->getDefiningOp())) {\n auto it = aliases.insert(std::make_pair(v, view.getSupportingBuffer()));\n return it.first->second;\n }\n llvm_unreachable(\"unsupported view alias case\");\n}\n\nLinalgDependenceGraph::LinalgDependenceGraph(Aliases &aliases,\n ArrayRef ops)\n : aliases(aliases), linalgOps(ops.begin(), ops.end()) {\n for (auto en : llvm::enumerate(linalgOps)) {\n assert(isa(en.value()) && \"Expected value for LinalgOp\");\n linalgOpPositions.insert(std::make_pair(en.value(), en.index()));\n }\n for (unsigned i = 0, e = ops.size(); i < e; ++i) {\n for (unsigned j = i + 1; j < e; ++j) {\n addDependencesBetween(cast(ops[i]), cast(ops[j]));\n }\n }\n}\n\nvoid LinalgDependenceGraph::addDependenceElem(DependenceType dt,\n LinalgOpView indexingOpView,\n LinalgOpView dependentOpView) {\n LLVM_DEBUG(dbgs() << \"\\nAdd dep type \" << dt << \":\\t\" << *indexingOpView.op\n << \" -> \" << *dependentOpView.op);\n dependencesFromGraphs[dt][indexingOpView.op].push_back(\n LinalgDependenceGraphElem{dependentOpView, indexingOpView.view});\n dependencesIntoGraphs[dt][dependentOpView.op].push_back(\n LinalgDependenceGraphElem{indexingOpView, dependentOpView.view});\n}\n\nLinalgDependenceGraph::dependence_range\nLinalgDependenceGraph::getDependencesFrom(\n LinalgOp src, LinalgDependenceGraph::DependenceType dt) {\n return getDependencesFrom(src.getOperation(), dt);\n}\n\nLinalgDependenceGraph::dependence_range\nLinalgDependenceGraph::getDependencesFrom(\n Operation *src, LinalgDependenceGraph::DependenceType dt) {\n auto &vec = dependencesFromGraphs[dt][src];\n return llvm::make_range(vec.begin(), vec.end());\n}\n\nLinalgDependenceGraph::dependence_range\nLinalgDependenceGraph::getDependencesInto(\n LinalgOp dst, LinalgDependenceGraph::DependenceType dt) {\n return getDependencesInto(dst.getOperation(), dt);\n}\n\nLinalgDependenceGraph::dependence_range\nLinalgDependenceGraph::getDependencesInto(\n Operation *dst, LinalgDependenceGraph::DependenceType dt) {\n auto &vec = dependencesIntoGraphs[dt][dst];\n return llvm::make_range(vec.begin(), vec.end());\n}\n\nvoid LinalgDependenceGraph::addDependencesBetween(LinalgOp src, LinalgOp dst) {\n for (auto *srcView : src.getOutputs()) { \/\/ W\n \/\/ RAW graph\n for (auto *dstView : dst.getInputs()) { \/\/ R\n if (aliases.alias(srcView, dstView)) { \/\/ if alias, fill RAW\n addDependenceElem(DependenceType::RAW,\n LinalgOpView{src.getOperation(), srcView},\n LinalgOpView{dst.getOperation(), dstView});\n }\n }\n \/\/ WAW graph\n for (auto *dstView : dst.getOutputs()) { \/\/ W\n if (aliases.alias(srcView, dstView)) { \/\/ if alias, fill WAW\n addDependenceElem(DependenceType::WAW,\n LinalgOpView{src.getOperation(), srcView},\n LinalgOpView{dst.getOperation(), dstView});\n }\n }\n }\n for (auto *srcView : src.getInputs()) { \/\/ R\n \/\/ RAR graph\n for (auto *dstView : dst.getInputs()) { \/\/ R\n if (aliases.alias(srcView, dstView)) { \/\/ if alias, fill RAR\n addDependenceElem(DependenceType::RAR,\n LinalgOpView{src.getOperation(), srcView},\n LinalgOpView{dst.getOperation(), dstView});\n }\n }\n \/\/ WAR graph\n for (auto *dstView : dst.getOutputs()) { \/\/ W\n if (aliases.alias(srcView, dstView)) { \/\/ if alias, fill WAR\n addDependenceElem(DependenceType::WAR,\n LinalgOpView{src.getOperation(), srcView},\n LinalgOpView{dst.getOperation(), dstView});\n }\n }\n }\n}\n\nSmallVector\nLinalgDependenceGraph::findCoveringDependences(LinalgOp srcLinalgOp,\n LinalgOp dstLinalgOp) {\n return findOperationsWithCoveringDependences(\n srcLinalgOp, dstLinalgOp, nullptr,\n {DependenceType::WAW, DependenceType::WAR, DependenceType::RAW});\n}\n\nSmallVector\nLinalgDependenceGraph::findCoveringWrites(LinalgOp srcLinalgOp,\n LinalgOp dstLinalgOp, Value *view) {\n return findOperationsWithCoveringDependences(\n srcLinalgOp, dstLinalgOp, view,\n {DependenceType::WAW, DependenceType::WAR});\n}\n\nSmallVector\nLinalgDependenceGraph::findCoveringReads(LinalgOp srcLinalgOp,\n LinalgOp dstLinalgOp, Value *view) {\n return findOperationsWithCoveringDependences(\n srcLinalgOp, dstLinalgOp, view,\n {DependenceType::RAR, DependenceType::RAW});\n}\n\nSmallVector\nLinalgDependenceGraph::findOperationsWithCoveringDependences(\n LinalgOp srcLinalgOp, LinalgOp dstLinalgOp, Value *view,\n ArrayRef types) {\n auto *src = srcLinalgOp.getOperation();\n auto *dst = dstLinalgOp.getOperation();\n auto srcPos = linalgOpPositions[src];\n auto dstPos = linalgOpPositions[dst];\n assert(srcPos < dstPos && \"expected dst after src in IR traversal order\");\n\n SmallVector res;\n \/\/ Consider an intermediate interleaved `interim` op, look for any dependence\n \/\/ to an aliasing view on a src -> op -> dst path.\n \/\/ TODO(ntv) we are not considering paths yet, just interleaved positions.\n for (auto dt : types) {\n for (auto dependence : getDependencesFrom(src, dt)) {\n auto interimPos = linalgOpPositions[dependence.dependentOpView.op];\n \/\/ Skip if not interleaved.\n if (interimPos >= dstPos || interimPos <= srcPos)\n continue;\n if (view && !aliases.alias(view, dependence.indexingView))\n continue;\n auto *op = dependence.dependentOpView.op;\n LLVM_DEBUG(dbgs() << \"\\n***Found covering dependence of type \" << dt\n << \": \" << *src << \" -> \" << *op << \" on \"\n << *dependence.indexingView);\n res.push_back(op);\n }\n }\n return res;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \"cppa\/cppa.hpp\"\n\nusing namespace cppa;\n\nvoid mirror() {\n \/\/ wait for messages\n become (\n \/\/ invoke this lambda expression if we receive a string\n on_arg_match >> [](const std::string& what) {\n \/\/ prints \"Hello World!\" via aout (thread-safe wrapper for cout)\n aout << what << std::endl;\n \/\/ replies \"!dlroW olleH\"\n reply(std::string(what.rbegin(), what.rend()));\n \/\/ terminates this actor\n self->quit();\n }\n );\n}\n\nvoid hello_world(const actor_ptr& buddy) {\n \/\/ send \"Hello World!\" to our buddy\n send(buddy, \"Hello World!\");\n \/\/ wait for messages\n become (\n on_arg_match >> [](const std::string& what) {\n \/\/ prints \"!dlroW olleH\"\n aout << what << std::endl;\n \/\/ terminate this actor\n self->quit();\n }\n );\n}\n\nint main() {\n \/\/ create a new actor that calls 'mirror()'\n auto mirror_actor = spawn(mirror);\n \/\/ create another actor that calls 'hello_world(mirror_actor)'\n spawn(hello_world, mirror_actor);\n \/\/ wait until all other actors we have spawned are done\n await_all_others_done();\n \/\/ run cleanup code before exiting main\n shutdown();\n}\nuse sync_send in hello world example#include \n#include \n#include \"cppa\/cppa.hpp\"\n\nusing namespace cppa;\n\nvoid mirror() {\n \/\/ wait for messages\n become (\n \/\/ invoke this lambda expression if we receive a string\n on_arg_match >> [](const std::string& what) {\n \/\/ prints \"Hello World!\" via aout (thread-safe cout wrapper)\n aout << what << std::endl;\n \/\/ replies \"!dlroW olleH\"\n reply(std::string(what.rbegin(), what.rend()));\n \/\/ terminates this actor (become otherwise 'loops' forever)\n self->quit();\n }\n );\n}\n\nvoid hello_world(const actor_ptr& buddy) {\n \/\/ send \"Hello World!\" to our buddy ...\n sync_send(buddy, \"Hello World!\").then(\n \/\/ ... and wait for a response\n on_arg_match >> [](const std::string& what) {\n \/\/ prints \"!dlroW olleH\"\n aout << what << std::endl;\n }\n );\n}\n\nint main() {\n \/\/ create a new actor that calls 'mirror()'\n auto mirror_actor = spawn(mirror);\n \/\/ create another actor that calls 'hello_world(mirror_actor)'\n spawn(hello_world, mirror_actor);\n \/\/ wait until all other actors we have spawned are done\n await_all_others_done();\n \/\/ run cleanup code before exiting main\n shutdown();\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2010-2013 Joshua Boyce.\r\n\/\/ See the file COPYING for copying permission.\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\/\/ TODO: Add support for for passing args, work dir, etc to CreateAndInject.\r\n\/\/ e.g. exe-arg0, exe-arg1, exe-arg2, ..., exe-argN?\r\n\r\nnamespace\r\n{\r\n\r\nstd::wstring PtrToString(void const* const ptr)\r\n{\r\n std::wostringstream str;\r\n str.imbue(std::locale::classic());\r\n str << std::hex << reinterpret_cast(ptr);\r\n return str.str();\r\n}\r\n\r\n}\r\n\r\nint main(int argc, char* \/*argv*\/[]) \r\n{\r\n try\r\n {\r\n hadesmem::detail::InitializeAll();\r\n\r\n std::cout << \"HadesMem Injector\\n\";\r\n\r\n boost::program_options::options_description opts_desc(\r\n \"General options\");\r\n opts_desc.add_options()\r\n (\"help\", \"produce help message\")\r\n (\"pid\", boost::program_options::value(), \"process id\")\r\n (\"module\", boost::program_options::wvalue(), \"module path\")\r\n (\"path-resolution\", \"perform path resolution\")\r\n (\"export\", boost::program_options::value(), \"export name\")\r\n (\"free\", \"unload module\")\r\n (\"add-path\", \"add module dir to serach order\")\r\n (\"run\", boost::program_options::wvalue(), \"process path\")\r\n ;\r\n\r\n std::vector const args = boost::program_options::\r\n split_winmain(GetCommandLine());\r\n boost::program_options::variables_map var_map;\r\n boost::program_options::store(boost::program_options::wcommand_line_parser(\r\n args).options(opts_desc).run(), var_map);\r\n boost::program_options::notify(var_map);\r\n\r\n if (var_map.count(\"help\") || argc == 1)\r\n {\r\n std::cout << '\\n' << opts_desc << '\\n';\r\n return 1;\r\n }\r\n\r\n if (!var_map.count(\"module\"))\r\n {\r\n std::cerr << \"\\nError! Module path must be specified.\\n\";\r\n return 1;\r\n }\r\n \r\n bool const has_pid = (var_map.count(\"pid\") != 0);\r\n bool const create_proc = (var_map.count(\"run\") != 0);\r\n if ((has_pid && create_proc) || (!has_pid && !create_proc))\r\n {\r\n std::cerr << \"\\nError! A process ID or an executable path must be \"\r\n \"specified.\\n\";\r\n return 1;\r\n }\r\n\r\n bool const inject = (var_map.count(\"free\") == 0);\r\n if (!inject && create_proc)\r\n {\r\n std::cerr << \"\\nError! Modules can only be unloaded from running \"\r\n \"targets.\\n\";\r\n return 1;\r\n }\r\n\r\n std::wstring const module_path = var_map[\"module\"].as();\r\n bool const path_resolution = var_map.count(\"path-resolution\") != 0;\r\n bool const add_path = var_map.count(\"add-path\") != 0;\r\n\r\n int flags = hadesmem::InjectFlags::kNone;\r\n if (path_resolution)\r\n {\r\n flags |= hadesmem::InjectFlags::kPathResolution;\r\n }\r\n if (add_path)\r\n {\r\n flags |= hadesmem::InjectFlags::kAddToSearchOrder;\r\n }\r\n\r\n if (has_pid)\r\n {\r\n try\r\n {\r\n hadesmem::GetSeDebugPrivilege();\r\n\r\n std::wcout << \"\\nAcquired SeDebugPrivilege.\\n\";\r\n }\r\n catch (std::exception const& \/*e*\/)\r\n {\r\n std::wcout << \"\\nFailed to acquire SeDebugPrivilege.\\n\";\r\n }\r\n\r\n DWORD const pid = var_map[\"pid\"].as();\r\n\r\n hadesmem::Process const process(pid);\r\n \r\n HMODULE module = nullptr;\r\n\r\n if (inject)\r\n {\r\n module = hadesmem::InjectDll(process, module_path, flags);\r\n\r\n std::wcout << \"\\nSuccessfully injected module at base address \" << \r\n PtrToString(module) << \".\\n\";\r\n }\r\n else\r\n {\r\n boost::filesystem::path path_real(module_path);\r\n if (path_resolution && path_real.is_relative())\r\n {\r\n path_real = boost::filesystem::absolute(path_real, \r\n hadesmem::detail::GetSelfDirPath());\r\n }\r\n path_real.make_preferred();\r\n\r\n hadesmem::Module const remote_module(process, path_real.native());\r\n module = remote_module.GetHandle();\r\n }\r\n\r\n if (var_map.count(\"export\"))\r\n {\r\n std::string const export_name = var_map[\"export\"].as();\r\n auto const export_ret = hadesmem::CallExport(process, module, \r\n export_name);\r\n\r\n std::wcout << \"\\nSuccessfully called module export.\\n\";\r\n std::wcout << \"Return: \" << export_ret.GetReturnValue() << \".\\n\";\r\n std::wcout << \"LastError: \" << export_ret.GetLastError() << \".\\n\";\r\n }\r\n\r\n if (!inject)\r\n {\r\n hadesmem::FreeDll(process, module);\r\n\r\n std::wcout << \"\\nSuccessfully freed module at base address \" << \r\n PtrToString(module) << \".\\n\";\r\n }\r\n }\r\n else\r\n {\r\n std::vector args;\r\n std::wstring const exe_path = var_map[\"run\"].as();\r\n std::string const export_name = var_map.count(\"export\") ? \r\n var_map[\"export\"].as() : \"\";\r\n hadesmem::CreateAndInjectData const inject_data = \r\n hadesmem::CreateAndInject(\r\n exe_path, \r\n L\"\", \r\n std::begin(args), \r\n std::end(args), \r\n module_path, \r\n export_name, \r\n flags);\r\n\r\n std::wcout << \"\\nSuccessfully created target.\\n\";\r\n std::wcout << \"Process ID: \" << inject_data.GetProcess() << \".\\n\";\r\n std::wcout << \"Module Base: \" << PtrToString(inject_data.GetModule()) \r\n << \".\\n\";\r\n std::wcout << \"Export Return: \" << inject_data.GetExportRet() << \".\\n\";\r\n std::wcout << \"Export LastError: \" << inject_data.GetExportLastError() \r\n << \".\\n\";\r\n }\r\n\r\n return 0;\r\n }\r\n catch (std::exception const& e)\r\n {\r\n std::cerr << \"\\nError!\\n\";\r\n std::cerr << boost::diagnostic_information(e) << '\\n';\r\n\r\n return 1;\r\n }\r\n}\r\n* Fix warning.\/\/ Copyright (C) 2010-2013 Joshua Boyce.\r\n\/\/ See the file COPYING for copying permission.\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\/\/ TODO: Add support for for passing args, work dir, etc to CreateAndInject.\r\n\/\/ e.g. exe-arg0, exe-arg1, exe-arg2, ..., exe-argN?\r\n\r\nnamespace\r\n{\r\n\r\nstd::wstring PtrToString(void const* const ptr)\r\n{\r\n std::wostringstream str;\r\n str.imbue(std::locale::classic());\r\n str << std::hex << reinterpret_cast(ptr);\r\n return str.str();\r\n}\r\n\r\n}\r\n\r\nint main(int argc, char* \/*argv*\/[]) \r\n{\r\n try\r\n {\r\n hadesmem::detail::InitializeAll();\r\n\r\n std::cout << \"HadesMem Injector\\n\";\r\n\r\n boost::program_options::options_description opts_desc(\r\n \"General options\");\r\n opts_desc.add_options()\r\n (\"help\", \"produce help message\")\r\n (\"pid\", boost::program_options::value(), \"process id\")\r\n (\"module\", boost::program_options::wvalue(), \"module path\")\r\n (\"path-resolution\", \"perform path resolution\")\r\n (\"export\", boost::program_options::value(), \"export name\")\r\n (\"free\", \"unload module\")\r\n (\"add-path\", \"add module dir to serach order\")\r\n (\"run\", boost::program_options::wvalue(), \"process path\")\r\n ;\r\n\r\n std::vector const args = boost::program_options::\r\n split_winmain(GetCommandLine());\r\n boost::program_options::variables_map var_map;\r\n boost::program_options::store(boost::program_options::wcommand_line_parser(\r\n args).options(opts_desc).run(), var_map);\r\n boost::program_options::notify(var_map);\r\n\r\n if (var_map.count(\"help\") || argc == 1)\r\n {\r\n std::cout << '\\n' << opts_desc << '\\n';\r\n return 1;\r\n }\r\n\r\n if (!var_map.count(\"module\"))\r\n {\r\n std::cerr << \"\\nError! Module path must be specified.\\n\";\r\n return 1;\r\n }\r\n \r\n bool const has_pid = (var_map.count(\"pid\") != 0);\r\n bool const create_proc = (var_map.count(\"run\") != 0);\r\n if ((has_pid && create_proc) || (!has_pid && !create_proc))\r\n {\r\n std::cerr << \"\\nError! A process ID or an executable path must be \"\r\n \"specified.\\n\";\r\n return 1;\r\n }\r\n\r\n bool const inject = (var_map.count(\"free\") == 0);\r\n if (!inject && create_proc)\r\n {\r\n std::cerr << \"\\nError! Modules can only be unloaded from running \"\r\n \"targets.\\n\";\r\n return 1;\r\n }\r\n\r\n std::wstring const module_path = var_map[\"module\"].as();\r\n bool const path_resolution = var_map.count(\"path-resolution\") != 0;\r\n bool const add_path = var_map.count(\"add-path\") != 0;\r\n\r\n int flags = hadesmem::InjectFlags::kNone;\r\n if (path_resolution)\r\n {\r\n flags |= hadesmem::InjectFlags::kPathResolution;\r\n }\r\n if (add_path)\r\n {\r\n flags |= hadesmem::InjectFlags::kAddToSearchOrder;\r\n }\r\n\r\n if (has_pid)\r\n {\r\n try\r\n {\r\n hadesmem::GetSeDebugPrivilege();\r\n\r\n std::wcout << \"\\nAcquired SeDebugPrivilege.\\n\";\r\n }\r\n catch (std::exception const& \/*e*\/)\r\n {\r\n std::wcout << \"\\nFailed to acquire SeDebugPrivilege.\\n\";\r\n }\r\n\r\n DWORD const pid = var_map[\"pid\"].as();\r\n\r\n hadesmem::Process const process(pid);\r\n \r\n HMODULE module = nullptr;\r\n\r\n if (inject)\r\n {\r\n module = hadesmem::InjectDll(process, module_path, flags);\r\n\r\n std::wcout << \"\\nSuccessfully injected module at base address \" << \r\n PtrToString(module) << \".\\n\";\r\n }\r\n else\r\n {\r\n boost::filesystem::path path_real(module_path);\r\n if (path_resolution && path_real.is_relative())\r\n {\r\n path_real = boost::filesystem::absolute(path_real, \r\n hadesmem::detail::GetSelfDirPath());\r\n }\r\n path_real.make_preferred();\r\n\r\n hadesmem::Module const remote_module(process, path_real.native());\r\n module = remote_module.GetHandle();\r\n }\r\n\r\n if (var_map.count(\"export\"))\r\n {\r\n std::string const export_name = var_map[\"export\"].as();\r\n auto const export_ret = hadesmem::CallExport(process, module, \r\n export_name);\r\n\r\n std::wcout << \"\\nSuccessfully called module export.\\n\";\r\n std::wcout << \"Return: \" << export_ret.GetReturnValue() << \".\\n\";\r\n std::wcout << \"LastError: \" << export_ret.GetLastError() << \".\\n\";\r\n }\r\n\r\n if (!inject)\r\n {\r\n hadesmem::FreeDll(process, module);\r\n\r\n std::wcout << \"\\nSuccessfully freed module at base address \" << \r\n PtrToString(module) << \".\\n\";\r\n }\r\n }\r\n else\r\n {\r\n std::vector create_args;\r\n std::wstring const exe_path = var_map[\"run\"].as();\r\n std::string const export_name = var_map.count(\"export\") ? \r\n var_map[\"export\"].as() : \"\";\r\n hadesmem::CreateAndInjectData const inject_data = \r\n hadesmem::CreateAndInject(\r\n exe_path, \r\n L\"\", \r\n std::begin(create_args), \r\n std::end(create_args), \r\n module_path, \r\n export_name, \r\n flags);\r\n\r\n std::wcout << \"\\nSuccessfully created target.\\n\";\r\n std::wcout << \"Process ID: \" << inject_data.GetProcess() << \".\\n\";\r\n std::wcout << \"Module Base: \" << PtrToString(inject_data.GetModule()) \r\n << \".\\n\";\r\n std::wcout << \"Export Return: \" << inject_data.GetExportRet() << \".\\n\";\r\n std::wcout << \"Export LastError: \" << inject_data.GetExportLastError() \r\n << \".\\n\";\r\n }\r\n\r\n return 0;\r\n }\r\n catch (std::exception const& e)\r\n {\r\n std::cerr << \"\\nError!\\n\";\r\n std::cerr << boost::diagnostic_information(e) << '\\n';\r\n\r\n return 1;\r\n }\r\n}\r\n<|endoftext|>"} {"text":"\/*\r\nMIT License\r\nCopyright (c) 2017 Arlen Keshabyan (arlen.albert@gmail.com)\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n*\/\r\n\r\n#include \r\n#include \r\n#include \"planar_movements_recognizer.hpp\"\r\n#include \"platform.hpp\"\r\n#include \"platform_utilities.hpp\"\r\n#include \"strings.hpp\"\r\n\r\nint main()\r\n{\r\n using namespace nstd::platform::utilities;\r\n\r\n auto res { shell_execute(\"gcc -E -Wp,-v -xc++ nul 2>&1\") };\r\n\r\n std::cout << \"shell_execute: \" << std::endl << res << std::endl;\r\n\r\n using namespace nstd::platform;\r\n\r\n std::cout << \"Is Little Endian: \" << nstd::str::boolalpha[is_little_endian] << std::endl;\r\n std::cout << \"Is 64 bit: \" << nstd::str::boolalpha[is_64bit] << std::endl;\r\n std::cout << \" OS: \" << get_current_os_type_name() << std::endl;\r\n std::cout << \"Platform: \" << get_current_os_family_name() << std::endl;\r\n std::cout << \"Compiler: \" << get_current_compiler_name() << std::endl << std::endl;\r\n\r\n using namespace std::string_literals;\r\n using namespace nstd::pmr;\r\n\r\n enum command : uint8_t\r\n {\r\n open_file = 100, close_file,\r\n go_back, go_forward,\r\n reload\r\n };\r\n\r\n std::map command_map\r\n {\r\n {0, \"Unknown\"s},\r\n {command::open_file, \"Open file\"s},\r\n {command::close_file, \"Close file\"s},\r\n {command::go_back, \"Go back\"s},\r\n {command::go_forward, \"Go forward\"s},\r\n {command::reload, \"Reload\"s}\r\n };\r\n\r\n using event = planar_movements_event_provider::event;\r\n\r\n planar_movements_event_provider pmep;\r\n command_recognizer cr;\r\n remove_noise_filter rnf;\r\n\r\n cr. add_command(command::open_file, { event::up }).\r\n add_command(command::close_file, { event::down }).\r\n add_command(command::go_back, { event::left }).\r\n add_command(command::go_forward, { event::right }).\r\n add_command(command::reload, { event::down, event::up })\r\n ;\r\n\r\n {\r\n std::vector coords { pmep(100., 100.), pmep(150., 105.), pmep(200., 103.), pmep(250., 102.), pmep(300., 95.) }; \/\/ moving right\r\n\r\n std::cout << command_map[cr(rnf(std::move(coords)))] << std::endl;\r\n }\r\n\r\n {\r\n event_filter ef(true);\r\n ef.set(event::right, event::left);\r\n\r\n \/\/ moving right, but mapping the right event to the left one using event_filter\r\n std::vector coords { ef(pmep(100., 100.)), ef(pmep(150., 105.)), ef(pmep(200., 103.)), ef(pmep(250., 102.)), ef(pmep(300., 95.)) }; \/\/ moving right\r\n\r\n std::cout << command_map[cr(rnf(std::move(coords)))] << std::endl;\r\n }\r\n\r\n {\r\n std::vector coords { pmep(295., 239.), pmep(310., 202.), pmep(300., 150.), pmep(300., 120.), pmep(300., 95.) }; \/\/ moving up\r\n\r\n std::cout << command_map[cr(rnf(std::move(coords)))] << std::endl;\r\n }\r\n\r\n {\r\n std::vector coords { pmep(300., 95.), pmep(300., 120.), pmep(300., 150.), pmep(310., 202.), pmep(295., 239.) }; \/\/ moving down\r\n\r\n std::cout << command_map[cr(rnf(std::move(coords)))] << std::endl;\r\n }\r\n\r\n {\r\n std::vector coords { pmep(300., 95.), pmep(300., 120.), pmep(300., 150.), pmep(310., 202.), pmep(295., 239.),\r\n pmep(295., 239.), pmep(310., 202.), pmep(300., 150.), pmep(300., 120.), pmep(300., 95.) }; \/\/ moving down & up\r\n\r\n std::cout << command_map[cr(rnf(std::move(coords)))] << std::endl;\r\n }\r\n\r\n std::cout << \"exiting...\" << std::endl;\r\n\r\n return 0;\r\n}\r\nsmall changes\/*\r\nMIT License\r\nCopyright (c) 2017 Arlen Keshabyan (arlen.albert@gmail.com)\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n*\/\r\n\r\n#include \r\n#include \r\n#include \"planar_movements_recognizer.hpp\"\r\n#include \"platform.hpp\"\r\n#include \"platform_utilities.hpp\"\r\n#include \"strings.hpp\"\r\n\r\nint main()\r\n{\r\n using namespace nstd::str;\r\n using namespace nstd::platform;\r\n using namespace nstd::platform::utilities;\r\n\r\n constexpr const bool if_windows { (current_os_family == os_family::Windows) };\r\n\r\n auto cmd { compose_string((if_windows ? \"where\" : \"which\"), \" gcc 2>&1\") };\r\n auto res { shell_execute(cmd) };\r\n\r\n std::cout << \"shell_execute: \" << std::endl << res << std::endl;\r\n\r\n std::cout << \"Is Little Endian: \" << boolalpha[is_little_endian] << std::endl;\r\n std::cout << \"Is 64 bit: \" << boolalpha[is_64bit] << std::endl;\r\n std::cout << \" OS: \" << get_current_os_type_name() << std::endl;\r\n std::cout << \"Platform: \" << get_current_os_family_name() << std::endl;\r\n std::cout << \"Compiler: \" << get_current_compiler_name() << std::endl << std::endl;\r\n\r\n using namespace std::string_literals;\r\n using namespace nstd::pmr;\r\n\r\n enum command : uint8_t\r\n {\r\n open_file = 100, close_file,\r\n go_back, go_forward,\r\n reload\r\n };\r\n\r\n std::map command_map\r\n {\r\n {0, \"Unknown\"s},\r\n {command::open_file, \"Open file\"s},\r\n {command::close_file, \"Close file\"s},\r\n {command::go_back, \"Go back\"s},\r\n {command::go_forward, \"Go forward\"s},\r\n {command::reload, \"Reload\"s}\r\n };\r\n\r\n using event = planar_movements_event_provider::event;\r\n\r\n planar_movements_event_provider pmep;\r\n command_recognizer cr;\r\n remove_noise_filter rnf;\r\n\r\n cr. add_command(command::open_file, { event::up }).\r\n add_command(command::close_file, { event::down }).\r\n add_command(command::go_back, { event::left }).\r\n add_command(command::go_forward, { event::right }).\r\n add_command(command::reload, { event::down, event::up })\r\n ;\r\n\r\n {\r\n std::vector coords { pmep(100., 100.), pmep(150., 105.), pmep(200., 103.), pmep(250., 102.), pmep(300., 95.) }; \/\/ moving right\r\n\r\n std::cout << command_map[cr(rnf(std::move(coords)))] << std::endl;\r\n }\r\n\r\n {\r\n event_filter ef(true);\r\n ef.set(event::right, event::left);\r\n\r\n \/\/ moving right, but mapping the right event to the left one using event_filter\r\n std::vector coords { ef(pmep(100., 100.)), ef(pmep(150., 105.)), ef(pmep(200., 103.)), ef(pmep(250., 102.)), ef(pmep(300., 95.)) }; \/\/ moving right\r\n\r\n std::cout << command_map[cr(rnf(std::move(coords)))] << std::endl;\r\n }\r\n\r\n {\r\n std::vector coords { pmep(295., 239.), pmep(310., 202.), pmep(300., 150.), pmep(300., 120.), pmep(300., 95.) }; \/\/ moving up\r\n\r\n std::cout << command_map[cr(rnf(std::move(coords)))] << std::endl;\r\n }\r\n\r\n {\r\n std::vector coords { pmep(300., 95.), pmep(300., 120.), pmep(300., 150.), pmep(310., 202.), pmep(295., 239.) }; \/\/ moving down\r\n\r\n std::cout << command_map[cr(rnf(std::move(coords)))] << std::endl;\r\n }\r\n\r\n {\r\n std::vector coords { pmep(300., 95.), pmep(300., 120.), pmep(300., 150.), pmep(310., 202.), pmep(295., 239.),\r\n pmep(295., 239.), pmep(310., 202.), pmep(300., 150.), pmep(300., 120.), pmep(300., 95.) }; \/\/ moving down & up\r\n\r\n std::cout << command_map[cr(rnf(std::move(coords)))] << std::endl;\r\n }\r\n\r\n std::cout << \"exiting...\" << std::endl;\r\n\r\n return 0;\r\n}\r\n<|endoftext|>"} {"text":"A quick fix for Issue 18353. This is my stupid mistake that I forgot removing the platform-dependent code in our renderer code. This change just add defined(OS_MACOSX) instead of removing #ifdef blocks since they are used by Chrome OS.<|endoftext|>"} {"text":"\n#include \"connection.h\"\n#include \"room.h\"\n#include \"user.h\"\n#include \"csapi\/room_send.h\"\n#include \"csapi\/joining.h\"\n#include \"csapi\/leaving.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace QMatrixClient;\nusing std::cout;\nusing std::endl;\nusing namespace std::placeholders;\n\nclass QMCTest : public QObject\n{\n public:\n QMCTest(Connection* conn, QString targetRoomName, QString source);\n\n private slots:\n void setupAndRun();\n void onNewRoom(Room* r);\n void run();\n void doTests();\n void loadMembers();\n void sendMessage();\n void addAndRemoveTag();\n void sendAndRedact();\n void checkRedactionOutcome(const QString& evtIdToRedact,\n RoomEventsRange events);\n void markDirectChat();\n void checkDirectChatOutcome(\n const Connection::DirectChatsMap& added);\n void leave();\n void finalize();\n\n private:\n QScopedPointer c;\n QStringList running;\n QStringList succeeded;\n QStringList failed;\n QString origin;\n QString targetRoomName;\n Room* targetRoom = nullptr;\n};\n\n#define QMC_CHECK(description, condition) \\\n{ \\\n Q_ASSERT(running.removeOne(description)); \\\n if (!!(condition)) \\\n { \\\n succeeded.push_back(description); \\\n cout << (description) << \" successful\" << endl; \\\n if (targetRoom) \\\n targetRoom->postMessage( \\\n origin % \": \" % (description) % \" successful\", \\\n MessageEventType::Notice); \\\n } else { \\\n failed.push_back(description); \\\n cout << (description) << \" FAILED\" << endl; \\\n if (targetRoom) \\\n targetRoom->postPlainText( \\\n origin % \": \" % (description) % \" FAILED\"); \\\n } \\\n}\n\nQMCTest::QMCTest(Connection* conn, QString testRoomName, QString source)\n : c(conn), origin(std::move(source)), targetRoomName(std::move(testRoomName))\n{\n if (!origin.isEmpty())\n cout << \"Origin for the test message: \" << origin.toStdString() << endl;\n if (!targetRoomName.isEmpty())\n cout << \"Test room name: \" << targetRoomName.toStdString() << endl;\n\n connect(c.data(), &Connection::connected, this, &QMCTest::setupAndRun);\n connect(c.data(), &Connection::loadedRoomState, this, &QMCTest::onNewRoom);\n \/\/ Big countdown watchdog\n QTimer::singleShot(180000, this, &QMCTest::leave);\n}\n\nvoid QMCTest::setupAndRun()\n{\n cout << \"Connected, server: \"\n << c->homeserver().toDisplayString().toStdString() << endl;\n cout << \"Access token: \" << c->accessToken().toStdString() << endl;\n\n if (!targetRoomName.isEmpty())\n {\n cout << \"Joining \" << targetRoomName.toStdString() << endl;\n running.push_back(\"Join room\");\n auto joinJob = c->joinRoom(targetRoomName);\n connect(joinJob, &BaseJob::failure, this,\n [this] { QMC_CHECK(\"Join room\", false); finalize(); });\n \/\/ Connection::joinRoom() creates a Room object upon JoinRoomJob::success\n \/\/ but this object is empty until the first sync is done.\n connect(joinJob, &BaseJob::success, this, [this,joinJob] {\n targetRoom = c->room(joinJob->roomId(), JoinState::Join);\n QMC_CHECK(\"Join room\", targetRoom != nullptr);\n\n run();\n });\n } else\n run();\n}\n\nvoid QMCTest::onNewRoom(Room* r)\n{\n cout << \"New room: \" << r->id().toStdString() << endl\n << \" Name: \" << r->name().toStdString() << endl\n << \" Canonical alias: \" << r->canonicalAlias().toStdString() << endl\n << endl;\n connect(r, &Room::aboutToAddNewMessages, r, [r] (RoomEventsRange timeline) {\n cout << timeline.size() << \" new event(s) in room \"\n << r->canonicalAlias().toStdString() << endl;\n\/\/ for (const auto& item: timeline)\n\/\/ {\n\/\/ cout << \"From: \"\n\/\/ << r->roomMembername(item->senderId()).toStdString()\n\/\/ << endl << \"Timestamp:\"\n\/\/ << item->timestamp().toString().toStdString() << endl\n\/\/ << \"JSON:\" << endl << item->originalJson().toStdString() << endl;\n\/\/ }\n });\n}\n\nvoid QMCTest::run()\n{\n c->setLazyLoading(true);\n c->sync();\n connectSingleShot(c.data(), &Connection::syncDone, this, &QMCTest::doTests);\n connect(c.data(), &Connection::syncDone, c.data(), [this] {\n cout << \"Sync complete, \"\n << running.size() << \" tests in the air\" << endl;\n if (!running.isEmpty())\n c->sync(10000);\n else if (targetRoom)\n {\n \/\/ TODO: Waiting for proper futures to come so that it could be:\n\/\/ targetRoom->postPlainText(origin % \": All tests finished\")\n\/\/ .then(this, &QMCTest::leave);\n auto txnId =\n targetRoom->postPlainText(origin % \": All tests finished\");\n connect(targetRoom, &Room::messageSent, this,\n [this,txnId] (QString serverTxnId) {\n if (txnId == serverTxnId)\n leave();\n });\n }\n else\n finalize();\n });\n}\n\nvoid QMCTest::doTests()\n{\n cout << \"Starting tests\" << endl;\n\n loadMembers();\n \/\/ Add here tests not requiring the test room\n if (targetRoomName.isEmpty())\n return;\n\n sendMessage();\n addAndRemoveTag();\n sendAndRedact();\n markDirectChat();\n \/\/ Add here tests with the test room\n}\n\nvoid QMCTest::loadMembers()\n{\n running.push_back(\"Loading members\");\n \/\/ The dedicated qmc-test room is too small to test\n \/\/ lazy-loading-then-full-loading; use #qmatrixclient:matrix.org instead.\n \/\/ TODO: #264\n auto* r = c->room(QStringLiteral(\"!PCzUtxtOjUySxSelof:matrix.org\"));\n if (!r)\n {\n cout << \"#test:matrix.org is not found in the test user's rooms\" << endl;\n QMC_CHECK(\"Loading members\", false);\n return;\n }\n \/\/ It's not exactly correct because an arbitrary server might not support\n \/\/ lazy loading; but in the absence of capabilities framework we assume\n \/\/ it does.\n if (r->memberNames().size() >= r->joinedCount())\n {\n cout << \"Lazy loading doesn't seem to be enabled\" << endl;\n QMC_CHECK(\"Loading members\", false);\n return;\n }\n r->setDisplayed();\n connect(r, &Room::allMembersLoaded, [this,r] {\n QMC_CHECK(\"Loading members\",\n r->memberNames().size() >= r->joinedCount());\n });\n}\n\nvoid QMCTest::sendMessage()\n{\n running.push_back(\"Message sending\");\n cout << \"Sending a message\" << endl;\n auto txnId = targetRoom->postPlainText(\"Hello, \" % origin % \" is here\");\n auto& pending = targetRoom->pendingEvents();\n if (pending.empty())\n {\n QMC_CHECK(\"Message sending\", false);\n return;\n }\n auto it = std::find_if(pending.begin(), pending.end(),\n [&txnId] (const auto& e) {\n return e->transactionId() == txnId;\n });\n QMC_CHECK(\"Message sending\", it != pending.end());\n \/\/ TODO: Wait when it actually gets sent; check that it obtained an id\n \/\/ Independently, check when it shows up in the timeline.\n}\n\nvoid QMCTest::addAndRemoveTag()\n{\n running.push_back(\"Tagging test\");\n static const auto TestTag = QStringLiteral(\"org.qmatrixclient.test\");\n \/\/ Pre-requisite\n if (targetRoom->tags().contains(TestTag))\n targetRoom->removeTag(TestTag);\n\n \/\/ Connect first because the signal is emitted synchronously.\n connect(targetRoom, &Room::tagsChanged, targetRoom, [=] {\n cout << \"Room \" << targetRoom->id().toStdString()\n << \", tag(s) changed:\" << endl\n << \" \" << targetRoom->tagNames().join(\", \").toStdString() << endl;\n if (targetRoom->tags().contains(TestTag))\n {\n cout << \"Test tag set, removing it now\" << endl;\n targetRoom->removeTag(TestTag);\n QMC_CHECK(\"Tagging test\", !targetRoom->tags().contains(TestTag));\n QObject::disconnect(targetRoom, &Room::tagsChanged, nullptr, nullptr);\n }\n });\n cout << \"Adding a tag\" << endl;\n targetRoom->addTag(TestTag);\n}\n\nvoid QMCTest::sendAndRedact()\n{\n running.push_back(\"Redaction\");\n cout << \"Sending a message to redact\" << endl;\n if (auto* job = targetRoom->connection()->sendMessage(targetRoom->id(),\n RoomMessageEvent(origin % \": message to redact\")))\n {\n connect(job, &BaseJob::success, targetRoom, [job,this] {\n cout << \"Redacting the message\" << endl;\n targetRoom->redactEvent(job->eventId(), origin);\n \/\/ Make sure to save the event id because the job is about to end.\n connect(targetRoom, &Room::aboutToAddNewMessages, this,\n std::bind(&QMCTest::checkRedactionOutcome,\n this, job->eventId(), _1));\n });\n } else\n QMC_CHECK(\"Redaction\", false);\n}\n\nvoid QMCTest::checkRedactionOutcome(const QString& evtIdToRedact,\n RoomEventsRange events)\n{\n static bool checkSucceeded = false;\n \/\/ There are two possible (correct) outcomes: either the event comes already\n \/\/ redacted at the next sync, or the nearest sync completes with\n \/\/ the unredacted event but the next one brings redaction.\n auto it = std::find_if(events.begin(), events.end(),\n [=] (const RoomEventPtr& e) {\n return e->id() == evtIdToRedact;\n });\n if (it == events.end())\n return; \/\/ Waiting for the next sync\n\n if ((*it)->isRedacted())\n {\n if (checkSucceeded)\n {\n const auto msg =\n \"The redacted event came in with the sync again, ignoring\";\n cout << msg << endl;\n targetRoom->postPlainText(msg);\n return;\n }\n cout << \"The sync brought already redacted message\" << endl;\n QMC_CHECK(\"Redaction\", true);\n \/\/ Not disconnecting because there are other connections from this class\n \/\/ to aboutToAddNewMessages\n checkSucceeded = true;\n return;\n }\n \/\/ The event is not redacted\n if (checkSucceeded)\n {\n const auto msg =\n \"Warning: the redacted event came non-redacted with the sync!\";\n cout << msg << endl;\n targetRoom->postPlainText(msg);\n }\n cout << \"Message came non-redacted with the sync, waiting for redaction\" << endl;\n connect(targetRoom, &Room::replacedEvent, targetRoom,\n [=] (const RoomEvent* newEvent, const RoomEvent* oldEvent) {\n QMC_CHECK(\"Redaction\", oldEvent->id() == evtIdToRedact &&\n newEvent->isRedacted() &&\n newEvent->redactionReason() == origin);\n checkSucceeded = true;\n disconnect(targetRoom, &Room::replacedEvent, nullptr, nullptr);\n });\n\n}\n\nvoid QMCTest::markDirectChat()\n{\n if (targetRoom->directChatUsers().contains(c->user()))\n {\n cout << \"Warning: the room is already a direct chat,\"\n \" only unmarking will be tested\" << endl;\n checkDirectChatOutcome({{ c->user(), targetRoom->id() }});\n return;\n }\n \/\/ Connect first because the signal is emitted synchronously.\n connect(c.data(), &Connection::directChatsListChanged,\n this, &QMCTest::checkDirectChatOutcome);\n cout << \"Marking the room as a direct chat\" << endl;\n c->addToDirectChats(targetRoom, c->user());\n}\n\nvoid QMCTest::checkDirectChatOutcome(const Connection::DirectChatsMap& added)\n{\n running.push_back(\"Direct chat test\");\n disconnect(c.data(), &Connection::directChatsListChanged, nullptr, nullptr);\n if (!targetRoom->isDirectChat())\n {\n cout << \"The room has not been marked as a direct chat\" << endl;\n QMC_CHECK(\"Direct chat test\", false);\n return;\n }\n if (!added.contains(c->user(), targetRoom->id()))\n {\n cout << \"The room has not been listed in new direct chats\" << endl;\n QMC_CHECK(\"Direct chat test\", false);\n return;\n }\n\n cout << \"Unmarking the direct chat\" << endl;\n c->removeFromDirectChats(targetRoom->id(), c->user());\n QMC_CHECK(\"Direct chat test\", !c->isDirectChat(targetRoom->id()));\n}\n\nvoid QMCTest::leave()\n{\n if (targetRoom)\n {\n cout << \"Leaving the room\" << endl;\n connect(targetRoom->leaveRoom(), &BaseJob::finished,\n this, &QMCTest::finalize);\n }\n else\n finalize();\n}\n\nvoid QMCTest::finalize()\n{\n cout << \"Logging out\" << endl;\n c->logout();\n connect(c.data(), &Connection::loggedOut, qApp,\n [this] {\n if (!failed.isEmpty())\n cout << \"FAILED: \" << failed.join(\", \").toStdString() << endl;\n if (!running.isEmpty())\n cout << \"DID NOT FINISH: \"\n << running.join(\", \").toStdString() << endl;\n QCoreApplication::processEvents();\n QCoreApplication::exit(failed.size() + running.size());\n });\n}\n\nint main(int argc, char* argv[])\n{\n QCoreApplication app(argc, argv);\n if (argc < 4)\n {\n cout << \"Usage: qmc-example [ [origin]]\" << endl;\n return -1;\n }\n\n cout << \"Connecting to the server as \" << argv[1] << endl;\n auto conn = new Connection;\n conn->connectToServer(argv[1], argv[2], argv[3]);\n QMCTest test { conn, argc >= 5 ? argv[4] : nullptr,\n argc >= 6 ? argv[5] : nullptr };\n return app.exec();\n}\nqmc-example: streamline redaction test\n#include \"connection.h\"\n#include \"room.h\"\n#include \"user.h\"\n#include \"csapi\/room_send.h\"\n#include \"csapi\/joining.h\"\n#include \"csapi\/leaving.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace QMatrixClient;\nusing std::cout;\nusing std::endl;\nusing namespace std::placeholders;\n\nclass QMCTest : public QObject\n{\n public:\n QMCTest(Connection* conn, QString targetRoomName, QString source);\n\n private slots:\n void setupAndRun();\n void onNewRoom(Room* r);\n void run();\n void doTests();\n void loadMembers();\n void sendMessage();\n void addAndRemoveTag();\n void sendAndRedact();\n void checkRedactionOutcome(const QString& evtIdToRedact,\n const QMetaObject::Connection& sc);\n void markDirectChat();\n void checkDirectChatOutcome(\n const Connection::DirectChatsMap& added);\n void leave();\n void finalize();\n\n private:\n QScopedPointer c;\n QStringList running;\n QStringList succeeded;\n QStringList failed;\n QString origin;\n QString targetRoomName;\n Room* targetRoom = nullptr;\n};\n\n#define QMC_CHECK(description, condition) \\\n{ \\\n Q_ASSERT(running.removeOne(description)); \\\n if (!!(condition)) \\\n { \\\n succeeded.push_back(description); \\\n cout << (description) << \" successful\" << endl; \\\n if (targetRoom) \\\n targetRoom->postMessage( \\\n origin % \": \" % (description) % \" successful\", \\\n MessageEventType::Notice); \\\n } else { \\\n failed.push_back(description); \\\n cout << (description) << \" FAILED\" << endl; \\\n if (targetRoom) \\\n targetRoom->postPlainText( \\\n origin % \": \" % (description) % \" FAILED\"); \\\n } \\\n}\n\nQMCTest::QMCTest(Connection* conn, QString testRoomName, QString source)\n : c(conn), origin(std::move(source)), targetRoomName(std::move(testRoomName))\n{\n if (!origin.isEmpty())\n cout << \"Origin for the test message: \" << origin.toStdString() << endl;\n if (!targetRoomName.isEmpty())\n cout << \"Test room name: \" << targetRoomName.toStdString() << endl;\n\n connect(c.data(), &Connection::connected, this, &QMCTest::setupAndRun);\n connect(c.data(), &Connection::loadedRoomState, this, &QMCTest::onNewRoom);\n \/\/ Big countdown watchdog\n QTimer::singleShot(180000, this, &QMCTest::leave);\n}\n\nvoid QMCTest::setupAndRun()\n{\n cout << \"Connected, server: \"\n << c->homeserver().toDisplayString().toStdString() << endl;\n cout << \"Access token: \" << c->accessToken().toStdString() << endl;\n\n if (!targetRoomName.isEmpty())\n {\n cout << \"Joining \" << targetRoomName.toStdString() << endl;\n running.push_back(\"Join room\");\n auto joinJob = c->joinRoom(targetRoomName);\n connect(joinJob, &BaseJob::failure, this,\n [this] { QMC_CHECK(\"Join room\", false); finalize(); });\n \/\/ Connection::joinRoom() creates a Room object upon JoinRoomJob::success\n \/\/ but this object is empty until the first sync is done.\n connect(joinJob, &BaseJob::success, this, [this,joinJob] {\n targetRoom = c->room(joinJob->roomId(), JoinState::Join);\n QMC_CHECK(\"Join room\", targetRoom != nullptr);\n\n run();\n });\n } else\n run();\n}\n\nvoid QMCTest::onNewRoom(Room* r)\n{\n cout << \"New room: \" << r->id().toStdString() << endl\n << \" Name: \" << r->name().toStdString() << endl\n << \" Canonical alias: \" << r->canonicalAlias().toStdString() << endl\n << endl;\n connect(r, &Room::aboutToAddNewMessages, r, [r] (RoomEventsRange timeline) {\n cout << timeline.size() << \" new event(s) in room \"\n << r->canonicalAlias().toStdString() << endl;\n\/\/ for (const auto& item: timeline)\n\/\/ {\n\/\/ cout << \"From: \"\n\/\/ << r->roomMembername(item->senderId()).toStdString()\n\/\/ << endl << \"Timestamp:\"\n\/\/ << item->timestamp().toString().toStdString() << endl\n\/\/ << \"JSON:\" << endl << item->originalJson().toStdString() << endl;\n\/\/ }\n });\n}\n\nvoid QMCTest::run()\n{\n c->setLazyLoading(true);\n c->sync();\n connectSingleShot(c.data(), &Connection::syncDone, this, &QMCTest::doTests);\n connect(c.data(), &Connection::syncDone, c.data(), [this] {\n cout << \"Sync complete, \"\n << running.size() << \" tests in the air\" << endl;\n if (!running.isEmpty())\n c->sync(10000);\n else if (targetRoom)\n {\n \/\/ TODO: Waiting for proper futures to come so that it could be:\n\/\/ targetRoom->postPlainText(origin % \": All tests finished\")\n\/\/ .then(this, &QMCTest::leave);\n auto txnId =\n targetRoom->postPlainText(origin % \": All tests finished\");\n connect(targetRoom, &Room::messageSent, this,\n [this,txnId] (QString serverTxnId) {\n if (txnId == serverTxnId)\n leave();\n });\n }\n else\n finalize();\n });\n}\n\nvoid QMCTest::doTests()\n{\n cout << \"Starting tests\" << endl;\n\n loadMembers();\n \/\/ Add here tests not requiring the test room\n if (targetRoomName.isEmpty())\n return;\n\n sendMessage();\n addAndRemoveTag();\n sendAndRedact();\n markDirectChat();\n \/\/ Add here tests with the test room\n}\n\nvoid QMCTest::loadMembers()\n{\n running.push_back(\"Loading members\");\n \/\/ The dedicated qmc-test room is too small to test\n \/\/ lazy-loading-then-full-loading; use #qmatrixclient:matrix.org instead.\n \/\/ TODO: #264\n auto* r = c->room(QStringLiteral(\"!PCzUtxtOjUySxSelof:matrix.org\"));\n if (!r)\n {\n cout << \"#test:matrix.org is not found in the test user's rooms\" << endl;\n QMC_CHECK(\"Loading members\", false);\n return;\n }\n \/\/ It's not exactly correct because an arbitrary server might not support\n \/\/ lazy loading; but in the absence of capabilities framework we assume\n \/\/ it does.\n if (r->memberNames().size() >= r->joinedCount())\n {\n cout << \"Lazy loading doesn't seem to be enabled\" << endl;\n QMC_CHECK(\"Loading members\", false);\n return;\n }\n r->setDisplayed();\n connect(r, &Room::allMembersLoaded, [this,r] {\n QMC_CHECK(\"Loading members\",\n r->memberNames().size() >= r->joinedCount());\n });\n}\n\nvoid QMCTest::sendMessage()\n{\n running.push_back(\"Message sending\");\n cout << \"Sending a message\" << endl;\n auto txnId = targetRoom->postPlainText(\"Hello, \" % origin % \" is here\");\n auto& pending = targetRoom->pendingEvents();\n if (pending.empty())\n {\n QMC_CHECK(\"Message sending\", false);\n return;\n }\n auto it = std::find_if(pending.begin(), pending.end(),\n [&txnId] (const auto& e) {\n return e->transactionId() == txnId;\n });\n QMC_CHECK(\"Message sending\", it != pending.end());\n \/\/ TODO: Wait when it actually gets sent; check that it obtained an id\n \/\/ Independently, check when it shows up in the timeline.\n}\n\nvoid QMCTest::addAndRemoveTag()\n{\n running.push_back(\"Tagging test\");\n static const auto TestTag = QStringLiteral(\"org.qmatrixclient.test\");\n \/\/ Pre-requisite\n if (targetRoom->tags().contains(TestTag))\n targetRoom->removeTag(TestTag);\n\n \/\/ Connect first because the signal is emitted synchronously.\n connect(targetRoom, &Room::tagsChanged, targetRoom, [=] {\n cout << \"Room \" << targetRoom->id().toStdString()\n << \", tag(s) changed:\" << endl\n << \" \" << targetRoom->tagNames().join(\", \").toStdString() << endl;\n if (targetRoom->tags().contains(TestTag))\n {\n cout << \"Test tag set, removing it now\" << endl;\n targetRoom->removeTag(TestTag);\n QMC_CHECK(\"Tagging test\", !targetRoom->tags().contains(TestTag));\n QObject::disconnect(targetRoom, &Room::tagsChanged, nullptr, nullptr);\n }\n });\n cout << \"Adding a tag\" << endl;\n targetRoom->addTag(TestTag);\n}\n\nvoid QMCTest::sendAndRedact()\n{\n running.push_back(\"Redaction\");\n cout << \"Sending a message to redact\" << endl;\n auto txnId = targetRoom->postPlainText(origin % \": message to redact\");\n if (txnId.isEmpty())\n {\n QMC_CHECK(\"Redaction\", false);\n return;\n }\n connect(targetRoom, &Room::messageSent, this,\n [this,txnId] (const QString& tId, const QString& evtId) {\n if (tId != txnId)\n return;\n\n cout << \"Redacting the message\" << endl;\n targetRoom->redactEvent(evtId, origin);\n QMetaObject::Connection sc;\n sc = connect(targetRoom, &Room::addedMessages, this,\n [this,sc,evtId] { checkRedactionOutcome(evtId, sc); });\n });\n}\n\nvoid QMCTest::checkRedactionOutcome(const QString& evtIdToRedact,\n const QMetaObject::Connection& sc)\n{\n \/\/ There are two possible (correct) outcomes: either the event comes already\n \/\/ redacted at the next sync, or the nearest sync completes with\n \/\/ the unredacted event but the next one brings redaction.\n auto it = targetRoom->findInTimeline(evtIdToRedact);\n if (it == targetRoom->timelineEdge())\n return; \/\/ Waiting for the next sync\n\n if ((*it)->isRedacted())\n {\n cout << \"The sync brought already redacted message\" << endl;\n QMC_CHECK(\"Redaction\", true);\n disconnect(sc);\n return;\n }\n cout << \"Message came non-redacted with the sync, waiting for redaction\"\n << endl;\n connect(targetRoom, &Room::replacedEvent, this,\n [this,evtIdToRedact]\n (const RoomEvent* newEvent, const RoomEvent* oldEvent) {\n if (oldEvent->id() == evtIdToRedact)\n {\n QMC_CHECK(\"Redaction\", newEvent->isRedacted() &&\n newEvent->redactionReason() == origin);\n disconnect(targetRoom, &Room::replacedEvent, nullptr, nullptr);\n }\n });\n}\n\nvoid QMCTest::markDirectChat()\n{\n if (targetRoom->directChatUsers().contains(c->user()))\n {\n cout << \"Warning: the room is already a direct chat,\"\n \" only unmarking will be tested\" << endl;\n checkDirectChatOutcome({{ c->user(), targetRoom->id() }});\n return;\n }\n \/\/ Connect first because the signal is emitted synchronously.\n connect(c.data(), &Connection::directChatsListChanged,\n this, &QMCTest::checkDirectChatOutcome);\n cout << \"Marking the room as a direct chat\" << endl;\n c->addToDirectChats(targetRoom, c->user());\n}\n\nvoid QMCTest::checkDirectChatOutcome(const Connection::DirectChatsMap& added)\n{\n running.push_back(\"Direct chat test\");\n disconnect(c.data(), &Connection::directChatsListChanged, nullptr, nullptr);\n if (!targetRoom->isDirectChat())\n {\n cout << \"The room has not been marked as a direct chat\" << endl;\n QMC_CHECK(\"Direct chat test\", false);\n return;\n }\n if (!added.contains(c->user(), targetRoom->id()))\n {\n cout << \"The room has not been listed in new direct chats\" << endl;\n QMC_CHECK(\"Direct chat test\", false);\n return;\n }\n\n cout << \"Unmarking the direct chat\" << endl;\n c->removeFromDirectChats(targetRoom->id(), c->user());\n QMC_CHECK(\"Direct chat test\", !c->isDirectChat(targetRoom->id()));\n}\n\nvoid QMCTest::leave()\n{\n if (targetRoom)\n {\n cout << \"Leaving the room\" << endl;\n connect(targetRoom->leaveRoom(), &BaseJob::finished,\n this, &QMCTest::finalize);\n }\n else\n finalize();\n}\n\nvoid QMCTest::finalize()\n{\n cout << \"Logging out\" << endl;\n c->logout();\n connect(c.data(), &Connection::loggedOut, qApp,\n [this] {\n if (!failed.isEmpty())\n cout << \"FAILED: \" << failed.join(\", \").toStdString() << endl;\n if (!running.isEmpty())\n cout << \"DID NOT FINISH: \"\n << running.join(\", \").toStdString() << endl;\n QCoreApplication::processEvents();\n QCoreApplication::exit(failed.size() + running.size());\n });\n}\n\nint main(int argc, char* argv[])\n{\n QCoreApplication app(argc, argv);\n if (argc < 4)\n {\n cout << \"Usage: qmc-example [ [origin]]\" << endl;\n return -1;\n }\n\n cout << \"Connecting to the server as \" << argv[1] << endl;\n auto conn = new Connection;\n conn->connectToServer(argv[1], argv[2], argv[3]);\n QMCTest test { conn, argc >= 5 ? argv[4] : nullptr,\n argc >= 6 ? argv[5] : nullptr };\n return app.exec();\n}\n<|endoftext|>"} {"text":"#include \r\n#include \r\n#include \r\n\/\/#include \r\n\r\nGtkWidget* window \t= nullptr;\r\nGtkWidget* toolbar \t= nullptr;\r\nGtkWidget* swin \t= nullptr;\r\nGtkWidget* source_view \t= nullptr;\r\nGtkWidget* hbox \t= nullptr;\r\nGtkSourceLanguageManager* language_manager = nullptr;\r\n\r\nstruct _Data\r\n{\r\n GtkTextBuffer *buffer;\r\n GtkWindow *parent;\r\n};\r\ntypedef struct _Data Data;\r\nstatic void new_file(GtkToolItem *button, Data *data)\r\n{\r\n\tdata->buffer = nullptr;\r\n}\r\nstatic void load_file(GtkToolItem *button, Data *data)\r\n{\r\n\tstatic GtkWidget *dialog = nullptr;\r\n\tif (dialog == nullptr)\r\n\t{\r\n\t\tdialog = gtk_file_chooser_dialog_new(\"Open File\",\r\n\t\t\tdata->parent, GTK_FILE_CHOOSER_ACTION_OPEN,\r\n\t\t\tGTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,\r\n\t\t\tGTK_STOCK_CANCEL, GTK_RESPONSE_REJECT, NULL);\r\n\t}\r\n\tif( gtk_dialog_run( GTK_DIALOG(dialog) ) == GTK_RESPONSE_ACCEPT )\r\n\t{\r\n\t\tgchar *filename = gtk_file_chooser_get_filename( GTK_FILE_CHOOSER( dialog ) );\r\n\t\tgchar *text_data;\r\n\t\tprintf(\"Open: %s\\n\", filename);\r\n\t\tg_file_get_contents( filename, &text_data, NULL, NULL );\r\n\t\tauto buff = gtk_text_view_get_buffer(GTK_TEXT_VIEW( source_view ));\r\n\t\tgtk_text_buffer_set_text( buff, text_data, -1 );\r\n\r\n\t\tauto s_lang = gtk_source_language_manager_guess_language(\r\n\t\t\tlanguage_manager,\r\n\t\t\tfilename,\r\n\t\t\tnullptr);\r\n\t\tgtk_source_buffer_set_language(\r\n\t\t\tGTK_SOURCE_BUFFER(buff), s_lang);\r\n\t\t\r\n\t\tg_free( filename );\r\n\t\tg_free( text_data );\r\n\t}\r\n\tgtk_widget_hide(dialog);\r\n}\r\nstatic void save_file(GtkToolItem *button, Data *data)\r\n{\r\n\tstatic GtkWidget *dialog = nullptr;\r\n\t\r\n\tif(dialog == nullptr)\r\n\t{\r\n\t\tdialog = gtk_file_chooser_dialog_new(\"Save file\",\r\n\t\t\tdata->parent, GTK_FILE_CHOOSER_ACTION_SAVE,\r\n\t\t\tGTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,\r\n\t\t\tGTK_STOCK_CANCEL, GTK_RESPONSE_REJECT, NULL);\r\n\t}\r\n\tif( gtk_dialog_run( GTK_DIALOG(dialog) ) == GTK_RESPONSE_ACCEPT )\r\n\t{\r\n\t\tgchar *filename;\r\n\t\tgchar *text_data;\r\n\t\t\r\n\t\tg_object_get( G_OBJECT( data->buffer ), \"text\",\r\n\t\t\t&text_data, NULL);\r\n\t\t\r\n\t\tfilename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER( dialog ));\r\n\t\t\r\n\t\tg_file_set_contents( filename, text_data, -1, NULL);\r\n\t\tg_free( filename );\r\n\t\tg_free( text_data );\r\n\t}\r\n\tgtk_widget_hide(dialog);\r\n}\r\nstatic void activate(GtkApplication* app, gpointer user_data)\r\n{\r\n\tGtkTextBuffer *buffer;\r\n\tData *data;\r\n\t\/\/ initialize\r\n\tdata = g_slice_new(Data);\r\n\twindow = gtk_application_window_new(app);\r\n\ttoolbar = gtk_toolbar_new();\r\n\thbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 1);\r\n\tsource_view = gtk_source_view_new();\r\n\tbuffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW( source_view ));\r\n\tswin = gtk_scrolled_window_new(NULL, NULL);\r\n\t\/\/\r\n\tlanguage_manager = gtk_source_language_manager_get_default ();\r\n\t\/\/\r\n\tGtkToolItem* new_button = gtk_tool_button_new(nullptr, nullptr);\r\n\tgtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(new_button), \"document-new\");\r\n\t\/\/\r\n\tGtkToolItem* open_button = gtk_tool_button_new(nullptr, nullptr);\r\n\tgtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(open_button), \"document-open\");\r\n\t\/\/\r\n\tGtkToolItem* save_button = gtk_tool_button_new(nullptr, nullptr);\r\n\tgtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(save_button), \"document-save\");\r\n\t\/\/\r\n\t\/\/ signal connect\r\n\tg_signal_connect(G_OBJECT(window), \"destroy\", G_CALLBACK( gtk_main_quit ), NULL);\r\n\tg_signal_connect (save_button, \"clicked\", G_CALLBACK(save_file), data);\r\n\tg_signal_connect (open_button, \"clicked\", G_CALLBACK(load_file), data);\r\n\t\/\/ position\r\n\tgtk_box_pack_start(GTK_BOX(hbox), toolbar, FALSE, FALSE, 0);\r\n\tgtk_box_pack_start( GTK_BOX( hbox ), swin, TRUE, TRUE, 0 );\r\n\t\/\/ insert toolbar items\r\n\tgtk_toolbar_insert(GTK_TOOLBAR(toolbar), new_button, -1);\r\n\tgtk_toolbar_insert(GTK_TOOLBAR(toolbar), open_button, -1);\r\n\tgtk_toolbar_insert(GTK_TOOLBAR(toolbar), save_button, -1);\r\n\t\/\/ window set\r\n\tgtk_window_set_title(GTK_WINDOW(window), \"Window\");\r\n\tgtk_window_set_default_size(GTK_WINDOW(window), 600, 500);\r\n\t\/\/ connections\r\n\tgtk_container_add(GTK_CONTAINER(window), hbox);\r\n\tgtk_container_add(GTK_CONTAINER(swin), source_view);\r\n\t\r\n\tdata->buffer = buffer;\r\n\tdata->parent = GTK_WINDOW(window);\r\n\tgtk_widget_show(toolbar);\r\n\tgtk_widget_show_all(window);\r\n}\r\n\r\nint main(int argc, char** argv)\r\n{\r\n\tGtkApplication* app;\r\n\t\r\n\tint status;\r\n\t\r\n\tapp = gtk_application_new(\"ca.chr.gtk.jazz\", G_APPLICATION_FLAGS_NONE);\r\n\tg_signal_connect(app, \"activate\", G_CALLBACK(activate), 0);\r\n\tstatus = g_application_run(G_APPLICATION(app), argc, argv);\r\n\tg_object_unref(app);\r\n\t\r\n\treturn status;\r\n}\r\nadded new_file function and integrating a tab feature#include \r\n#include \r\n#include \r\n\/\/#include \r\n\r\nGtkWidget* window \t= nullptr;\r\nGtkWidget* toolbar \t= nullptr;\r\nGtkWidget* swin \t= nullptr;\r\nGtkWidget* source_view \t= nullptr;\r\nGtkWidget* hbox \t= nullptr;\r\nGtkWidget* notebook = nullptr;\r\nGtkWidget* frame\t= nullptr;\r\nGtkWidget* label\t= nullptr;\r\nint frame_num = 1;\r\nchar bufferf[32];\r\nchar bufferl[32];\r\nGtkSourceLanguageManager* language_manager = nullptr;\r\n\r\nstruct _Data\r\n{\r\n GtkTextBuffer *buffer;\r\n GtkWindow *parent;\r\n};\r\ntypedef struct _Data Data;\r\nstatic void new_file(GtkToolItem *button, Data *data)\r\n{\r\n\tframe = gtk_frame_new(bufferf);\r\n\t\/\/gtk_container_set_border_width(GTK_CONTAINER(frame), 10);\r\n\t\/\/gtk_widget_set_size_request(frame, 400, 500);\r\n\tgtk_widget_show(frame);\r\n\t\r\n\t\/*label = gtk_label_new (bufferf);\r\n\tgtk_container_add(GTK_CONTAINER(frame), label);\r\n\tgtk_widget_show(label);*\/\r\n\t\r\n\tlabel = gtk_label_new(bufferl);\r\n\tgtk_notebook_prepend_page(GTK_NOTEBOOK(notebook), frame, label);\r\n}\r\nstatic void load_file(GtkToolItem *button, Data *data)\r\n{\r\n\tstatic GtkWidget *dialog = nullptr;\r\n\tif (dialog == nullptr)\r\n\t{\r\n\t\tdialog = gtk_file_chooser_dialog_new(\"Open File\",\r\n\t\t\tdata->parent, GTK_FILE_CHOOSER_ACTION_OPEN,\r\n\t\t\tGTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,\r\n\t\t\tGTK_STOCK_CANCEL, GTK_RESPONSE_REJECT, NULL);\r\n\t}\r\n\tif( gtk_dialog_run( GTK_DIALOG(dialog) ) == GTK_RESPONSE_ACCEPT )\r\n\t{\r\n\t\tgchar *filename = gtk_file_chooser_get_filename( GTK_FILE_CHOOSER( dialog ) );\r\n\t\tgchar *text_data;\r\n\t\tprintf(\"Open: %s\\n\", filename);\r\n\t\tg_file_get_contents( filename, &text_data, NULL, NULL );\r\n\t\tauto buff = gtk_text_view_get_buffer(GTK_TEXT_VIEW( source_view ));\r\n\t\tgtk_text_buffer_set_text( buff, text_data, -1 );\r\n\r\n\t\tauto s_lang = gtk_source_language_manager_guess_language(\r\n\t\t\tlanguage_manager,\r\n\t\t\tfilename,\r\n\t\t\tnullptr);\r\n\t\tgtk_source_buffer_set_language(\r\n\t\t\tGTK_SOURCE_BUFFER(buff), s_lang);\r\n\t\t\r\n\t\tg_free( filename );\r\n\t\tg_free( text_data );\r\n\t}\r\n\tgtk_widget_hide(dialog);\r\n}\r\nstatic void save_file(GtkToolItem *button, Data *data)\r\n{\r\n\tstatic GtkWidget *dialog = nullptr;\r\n\t\r\n\tif(dialog == nullptr)\r\n\t{\r\n\t\tdialog = gtk_file_chooser_dialog_new(\"Save file\",\r\n\t\t\tdata->parent, GTK_FILE_CHOOSER_ACTION_SAVE,\r\n\t\t\tGTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,\r\n\t\t\tGTK_STOCK_CANCEL, GTK_RESPONSE_REJECT, NULL);\r\n\t}\r\n\tif( gtk_dialog_run( GTK_DIALOG(dialog) ) == GTK_RESPONSE_ACCEPT )\r\n\t{\r\n\t\tgchar *filename;\r\n\t\tgchar *text_data;\r\n\t\t\r\n\t\tg_object_get( G_OBJECT( data->buffer ), \"text\",\r\n\t\t\t&text_data, NULL);\r\n\t\t\r\n\t\tfilename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER( dialog ));\r\n\t\t\r\n\t\tg_file_set_contents( filename, text_data, -1, NULL);\r\n\t\tg_free( filename );\r\n\t\tg_free( text_data );\r\n\t}\r\n\tgtk_widget_hide(dialog);\r\n}\r\nstatic void activate(GtkApplication* app, gpointer user_data)\r\n{\r\n\tGtkTextBuffer *buffer;\r\n\tData *data;\r\n\t\/\/ initialize\r\n\tnotebook = gtk_notebook_new();\r\n\tdata = g_slice_new(Data);\r\n\twindow = gtk_application_window_new(app);\r\n\ttoolbar = gtk_toolbar_new();\r\n\thbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 1);\r\n\tsource_view = gtk_source_view_new();\r\n\tbuffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW( source_view ));\r\n\tswin = gtk_scrolled_window_new(NULL, NULL);\r\n\t\/\/\r\n\tlanguage_manager = gtk_source_language_manager_get_default ();\r\n\t\/\/\r\n\tGtkToolItem* new_button = gtk_tool_button_new(nullptr, nullptr);\r\n\tgtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(new_button), \"document-new\");\r\n\t\/\/\r\n\tGtkToolItem* open_button = gtk_tool_button_new(nullptr, nullptr);\r\n\tgtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(open_button), \"document-open\");\r\n\t\/\/\r\n\tGtkToolItem* save_button = gtk_tool_button_new(nullptr, nullptr);\r\n\tgtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(save_button), \"document-save\");\r\n\t\/\/\r\n\t\/\/ signal connect\r\n\tg_signal_connect(G_OBJECT(window), \"destroy\", G_CALLBACK( gtk_main_quit ), NULL);\r\n\tg_signal_connect (save_button, \"clicked\", G_CALLBACK(save_file), data);\r\n\tg_signal_connect (open_button, \"clicked\", G_CALLBACK(load_file), data);\r\n\tg_signal_connect (new_button, \"clicked\", G_CALLBACK(new_file), data);\r\n\t\/\/ position\r\n\tgtk_box_pack_start(GTK_BOX(hbox), toolbar, FALSE, FALSE, 0);\r\n\tgtk_notebook_set_tab_pos (GTK_NOTEBOOK(notebook), GTK_POS_TOP);\r\n\tgtk_box_pack_start( GTK_BOX( hbox ), swin, TRUE, TRUE, 0 );\r\n\t\/\/ insert toolbar items\r\n\tgtk_toolbar_insert(GTK_TOOLBAR(toolbar), new_button, -1);\r\n\tgtk_toolbar_insert(GTK_TOOLBAR(toolbar), open_button, -1);\r\n\tgtk_toolbar_insert(GTK_TOOLBAR(toolbar), save_button, -1);\r\n\t\/\/ window set\r\n\tgtk_window_set_title(GTK_WINDOW(window), \"Window\");\r\n\tgtk_window_set_default_size(GTK_WINDOW(window), 600, 500);\r\n\t\/\/ connections\r\n\tgtk_container_add(GTK_CONTAINER(window), hbox);\r\n\t\/\/gtk_container_add(GTK_CONTAINER(hbox), notebook);\r\n\tgtk_container_add(GTK_CONTAINER(swin), notebook);\r\n\tgtk_container_add(GTK_CONTAINER(notebook), source_view);\r\n\t\r\n\tdata->buffer = buffer;\r\n\tdata->parent = GTK_WINDOW(window);\r\n\t\/\/gtk_widget_show(toolbar);\r\n\tgtk_widget_show_all(window);\r\n}\r\n\r\nint main(int argc, char** argv)\r\n{\r\n\tGtkApplication* app;\r\n\t\r\n\tint status;\r\n\t\r\n\tapp = gtk_application_new(\"ca.chr.gtk.jazz\", G_APPLICATION_FLAGS_NONE);\r\n\tg_signal_connect(app, \"activate\", G_CALLBACK(activate), 0);\r\n\tstatus = g_application_run(G_APPLICATION(app), argc, argv);\r\n\tg_object_unref(app);\r\n\t\r\n\treturn status;\r\n}\r\n<|endoftext|>"} {"text":"#include \n\n#include \"..\/chan.hh\"\n\nbool ok = false;\nbool sent = false;\n\nvoid producer(chan::write_chan* ch) {\n\tfor (int i = 2 ; ok ; i++) {\n\t\tprintf(\"w %d\\n\", i);\n\t\tsent = true;\n\t\tch->send(i);\n\t}\n}\n\nvoid consumer(chan::read_chan* ch) {\n\tfor (int i = 0 ; ok || sent ; i++) {\n\t\tint x = 0;\n\t\tch->recv(x);\n\t\tprintf(\"r %d\\n\", x);\n\t\tsent = false;\n\t}\n}\n\nint main() {\n\t\/\/ auto ch = new chan::unbuffered_chan();\n\tchan::unbuffered_chan ch;\n\n\tok = true;\n\n\tstd::thread t1(producer, &ch);\n\tstd::thread t2(consumer, &ch);\n\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(1));\n\n\tok = false;\n\n\tt1.join();\n\tt2.join();\n}\nexamples\/raw_pointers: remove races and segfaults#include \n\n#include \"..\/chan.hh\"\n\nvoid producer(chan::write_chan* ch) {\n\tfor (int i = 0 ; i < 100 ; i++) {\n\t\tprintf(\"w %d\\n\", i);\n\t\tch->send(i);\n\t}\n}\n\nvoid consumer(chan::read_chan* ch) {\n\tfor (int i = 0 ; i < 100 ; i++) {\n\t\tint x = 0;\n\t\tch->recv(x);\n\t\tprintf(\"r %d\\n\", x);\n\t}\n}\n\nint main() {\n\t\/\/ auto ch = new chan::unbuffered_chan();\n\tchan::unbuffered_chan ch;\n\n\tstd::thread t1(producer, &ch);\n\tstd::thread t2(consumer, &ch);\n\n\tt1.join();\n\tt2.join();\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ data_normalization.cpp\n\/\/ XAA1\n\/\/\n\/\/ Created by Michele Colombo on 16\/12\/2015.\n\/\/ Copyright (c) 2015 Michele Colombo. All rights reserved.\n\/\/\n\n#include \"data_normalization.h\"\n#include \n#include \n#include \n\nMinMaxNormalizer::MinMaxNormalizer(double min_target, double max_target){\n this->min_target = min_target;\n this->max_target = max_target;\n}\n\nvoid MinMaxNormalizer::setDataSource(const Doubles &values){\n auto mm = std::minmax_element(values.begin(), values.end());\n this->min_value = *mm.first;\n this->max_value = *mm.second;\n}\n\ndouble MinMaxNormalizer::normalize(double value){\n return min_target + (max_target - min_target) * (value - min_value) \/ (max_value - min_value);\n}\n\ndouble MinMaxNormalizer::denormalize(double value){\n return (value - min_target) * (max_value - min_value) \/ (max_target - min_target) + min_value;\n}\n\nvoid ZNormalizer::setDataSource(const Doubles &values){\n double sum = std::accumulate(values.begin(), values.end(), 0);\n mean = sum \/ (double)values.size();\n \n double accum = 0.0;\n std::for_each (std::begin(values), std::end(values), [&](const double d) {\n accum += (d - mean) * (d - mean);\n });\n sd = std::sqrt(accum\/(double)values.size());\n}\nFixed znorm implicit conversion issue\/\/\n\/\/ data_normalization.cpp\n\/\/ XAA1\n\/\/\n\/\/ Created by Michele Colombo on 16\/12\/2015.\n\/\/ Copyright (c) 2015 Michele Colombo. All rights reserved.\n\/\/\n\n#include \"data_normalization.h\"\n#include \n#include \n#include \n\nMinMaxNormalizer::MinMaxNormalizer(double min_target, double max_target){\n this->min_target = min_target;\n this->max_target = max_target;\n}\n\nvoid MinMaxNormalizer::setDataSource(const Doubles &values){\n auto mm = std::minmax_element(values.begin(), values.end());\n this->min_value = *mm.first;\n this->max_value = *mm.second;\n}\n\ndouble MinMaxNormalizer::normalize(double value){\n return min_target + (max_target - min_target) * (value - min_value) \/ (max_value - min_value);\n}\n\ndouble MinMaxNormalizer::denormalize(double value){\n return (value - min_target) * (max_value - min_value) \/ (max_target - min_target) + min_value;\n}\n\nvoid ZNormalizer::setDataSource(const Doubles &values){\n double sum = std::accumulate(values.begin(), values.end(), 0.0);\n mean = sum \/ (double)values.size();\n \n double accum = 0.0;\n std::for_each (std::begin(values), std::end(values), [&](const double d) {\n accum += (d - mean) * (d - mean);\n });\n sd = std::sqrt(accum\/(double)values.size());\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced\n\/\/ at the Lawrence Livermore National Laboratory. All Rights reserved. See files\n\/\/ LICENSE and NOTICE for details. LLNL-CODE-806117.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability visit https:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the BSD-3 license. We welcome feedback and contributions, see file\n\/\/ CONTRIBUTING.md for details.\n\n#ifndef MFEM_CONSTRAINED\n#define MFEM_CONSTRAINED\n\n#include \"solvers.hpp\"\n#include \"blockoperator.hpp\"\n#include \"sparsemat.hpp\"\n#include \"hypre.hpp\"\n\nnamespace mfem\n{\n\nclass ParFiniteElementSpace;\n\n\/** @brief An abstract class to solve the constrained system \\f$ Ax = f \\f$\n subject to the constraint \\f$ B x = r \\f$.\n\n Although implementations may not use the below formulation, for\n understanding some of its methods and notation you can think of\n it as solving the saddle-point system\n\n ( A B^T ) ( x ) ( f )\n ( B ) ( lambda ) = ( r )\n\n Do not confuse with ConstrainedOperator, which despite the similar name\n has very different functionality.\n\n The height and width of this object as an IterativeSolver are for\n the above saddle point system, but one can use its PrimalMult() method\n to solve just \\f$ Ax = f \\f$ subject to a constraint with \\f$ r \\f$\n defaulting to zero or set via SetConstraintRHS().\n\n This abstract object unifies handling of the \"dual\" rhs \\f$ r \\f$\n and the Lagrange multiplier solution \\f$ \\lambda \\f$, so that derived\n classses can reuse that code. *\/\nclass ConstrainedSolver : public IterativeSolver\n{\npublic:\n#ifdef MFEM_USE_MPI\n ConstrainedSolver(MPI_Comm comm, Operator& A_, Operator& B_);\n#endif\n ConstrainedSolver(Operator& A_, Operator& B_);\n\n virtual ~ConstrainedSolver() { }\n\n virtual void SetOperator(const Operator& op) override { }\n\n \/** @brief Set the right-hand side r for the constraint B x = r\n\n (r defaults to zero if you don't call this) *\/\n virtual void SetConstraintRHS(const Vector& r);\n\n \/** @brief Return the Lagrange multiplier solution in lambda\n\n PrimalMult() only gives you x, this provides access to lambda\n\n Does not make sense unless you've already solved the constrained\n system with Mult() or PrimalMult() *\/\n void GetMultiplierSolution(Vector& lambda) const { lambda = multiplier_sol; }\n\n \/** @brief Solve for \\f$ x \\f$ given \\f$ f \\f$.\n\n If you want to set \\f$ r \\f$, call SetConstraintRHS() before this.\n\n If you want to get \\f$ \\lambda \\f$, call GetMultiplierSolution() after\n this.\n\n The base class implementation calls Mult(), so derived classes must\n implement either this or Mult() *\/\n virtual void PrimalMult(const Vector& f, Vector& x) const;\n\n \/** @brief Solve for (x, lambda) given (f, r)\n\n The base class implementation calls PrimalMult(), so derived classes\n must implement either this or PrimalMult() *\/\n virtual void Mult(const Vector& f_and_r, Vector& x_and_lambda) const override;\n\nprotected:\n Operator& A;\n Operator& B;\n\n mutable Vector constraint_rhs;\n mutable Vector multiplier_sol;\n mutable Vector workb;\n mutable Vector workx;\n\nprivate:\n void Initialize();\n};\n\n\n\/** @brief Perform elimination of a single constraint.\n\n See EliminationProjection, EliminationCGSolver\n\n This keeps track of primary \/ secondary tdofs and does small dense block\n solves to eliminate constraints from a global system.\n\n \\f$ B_s^{-1} \\f$ maps the lagrange space into secondary dofs, while\n \\f$ -B_s^{-1} B_p \\f$ maps primary dofs to secondary dofs. *\/\nclass Eliminator\n{\npublic:\n Eliminator(const SparseMatrix& B, const Array& lagrange_dofs,\n const Array& primary_tdofs,\n const Array& secondary_tdofs);\n\n const Array& LagrangeDofs() const { return lagrange_tdofs; }\n const Array& PrimaryDofs() const { return primary_tdofs; }\n const Array& SecondaryDofs() const { return secondary_tdofs; }\n\n \/\/\/ Given primary displacements, return secondary displacements\n \/\/\/ This applies \\f$ -B_s^{-1} B_p \\f$.\n void Eliminate(const Vector& in, Vector& out) const;\n\n \/\/\/ Transpose of Eliminate(), applies \\f$ -B_p^T B_s^{-T} \\f$\n void EliminateTranspose(const Vector& in, Vector& out) const;\n\n \/\/\/ Maps Lagrange multipliers to secondary displacements,\n \/\/\/ applies \\f$ B_s^{-1} \\f$\n void LagrangeSecondary(const Vector& in, Vector& out) const;\n\n \/\/\/ Transpose of LagrangeSecondary()\n void LagrangeSecondaryTranspose(const Vector& in, Vector& out) const;\n\n \/\/\/ Return \\f$ -B_s^{-1} B_p \\f$ explicitly assembled in mat\n void ExplicitAssembly(DenseMatrix& mat) const;\n\nprivate:\n Array lagrange_tdofs;\n Array primary_tdofs;\n Array secondary_tdofs;\n\n DenseMatrix Bp;\n DenseMatrix Bs; \/\/ gets inverted in place\n LUFactors Bsinverse;\n DenseMatrix BsT; \/\/ gets inverted in place\n LUFactors BsTinverse;\n Array ipiv;\n Array ipivT;\n};\n\n\n\/** Collects action of several Eliminator objects to perform elimination of\n constraints.\n\n Works in parallel, but each Eliminator must be processor local, and must\n operate on disjoint degrees of freedom (ie, the primary and secondary dofs\n for one Eliminator must have no overlap with any dofs from a different\n Eliminator). *\/\nclass EliminationProjection : public Operator\n{\npublic:\n EliminationProjection(const Operator& A, Array& eliminators);\n\n void Mult(const Vector& x, Vector& y) const override;\n\n void MultTranspose(const Vector& x, Vector& y) const override;\n\n \/** @brief Assemble this projector as a (processor-local) SparseMatrix.\n\n Some day we may also want to try approximate variants. *\/\n SparseMatrix * AssembleExact() const;\n\n \/** Given Lagrange multiplier right-hand-side \\f$ g \\f$, return\n \\f$ \\tilde{g} \\f$ *\/\n void BuildGTilde(const Vector& g, Vector& gtilde) const;\n\n \/** After a solve, recover the Lagrange multiplier. *\/\n void RecoverMultiplier(const Vector& disprhs,\n const Vector& disp, Vector& lm) const;\n\nprivate:\n const Operator& Aop;\n Array eliminators;\n};\n\n\n#ifdef MFEM_USE_MPI\n\/** @brief Solve constrained system by eliminating the constraint; see\n ConstrainedSolver\n\n Solves the system with the operator \\f$ P^T A P + Z_P \\f$, where P is\n EliminationProjection and Z_P is the identity on the eliminated dofs. *\/\nclass EliminationSolver : public ConstrainedSolver\n{\npublic:\n \/** @brief Constructor, with explicit splitting into primary\/secondary dofs.\n\n This constructor uses a single elimination block (per processor), which\n provides the most general algorithm but is also not scalable\n\n The secondary_dofs are eliminated from the system in this algorithm,\n as they can be written in terms of the primary_dofs. *\/\n EliminationSolver(HypreParMatrix& A, SparseMatrix& B,\n Array& primary_dofs,\n Array& secondary_dofs);\n\n \/** @brief Constructor, elimination is by blocks.\n\n The nonzeros in B are assumed to be in disjoint rows and columns; the\n rows are identified with the constraint_rowstarts array, the secondary\n dofs are assumed to be the first nonzeros in the rows. *\/\n EliminationSolver(HypreParMatrix& A, SparseMatrix& B,\n Array& constraint_rowstarts);\n\n ~EliminationSolver();\n\n void PrimalMult(const Vector& x, Vector& y) const override;\n\nprotected:\n \/\/\/ Internal utility routine; assembles eliminated matrix explicitly\n void BuildExplicitOperator();\n\n \/\/\/ Build preconditioner for eliminated system\n virtual Solver* BuildPreconditioner() const = 0;\n \/\/\/ Select krylov solver for eliminated system\n virtual IterativeSolver* BuildKrylov() const = 0;\n\n HypreParMatrix& hA;\n Array eliminators;\n EliminationProjection * projector;\n HypreParMatrix * h_explicit_operator;\n mutable Solver* prec;\n};\n\n\n\/** EliminationSolver using CG and HypreBoomerAMG *\/\nclass EliminationCGSolver : public EliminationSolver\n{\npublic:\n EliminationCGSolver(HypreParMatrix& A, SparseMatrix& B,\n Array& constraint_rowstarts,\n int dimension_=0, bool reorder_=false) :\n EliminationSolver(A, B, constraint_rowstarts),\n dimension(dimension_), reorder(reorder_)\n { BuildExplicitOperator(); }\n\nprotected:\n virtual Solver* BuildPreconditioner() const override\n {\n HypreBoomerAMG * h_prec = new HypreBoomerAMG(*h_explicit_operator);\n h_prec->SetPrintLevel(0);\n if (dimension > 0) { h_prec->SetSystemsOptions(dimension, reorder); }\n return h_prec;\n }\n\n virtual IterativeSolver* BuildKrylov() const override\n { return new CGSolver(GetComm()); }\n\nprivate:\n int dimension;\n bool reorder;\n};\n\n\n\/** @brief Solve constrained system with penalty method; see ConstrainedSolver.\n\n Only approximates the solution, better approximation with higher penalty,\n but with higher penalty the preconditioner is less effective. *\/\nclass PenaltyConstrainedSolver : public ConstrainedSolver\n{\npublic:\n PenaltyConstrainedSolver(HypreParMatrix& A, SparseMatrix& B,\n double penalty_);\n\n PenaltyConstrainedSolver(HypreParMatrix& A, HypreParMatrix& B,\n double penalty_);\n\n ~PenaltyConstrainedSolver();\n\n void PrimalMult(const Vector& x, Vector& y) const override;\n\nprotected:\n void Initialize(HypreParMatrix& A, HypreParMatrix& B);\n\n \/\/\/ Build preconditioner for penalized system\n virtual Solver* BuildPreconditioner() const = 0;\n \/\/\/ Select krylov solver for penalized system\n virtual IterativeSolver* BuildKrylov() const = 0;\n\n double penalty;\n Operator& constraintB;\n HypreParMatrix * penalized_mat;\n mutable Solver * prec;\n};\n\n\n\/** Uses CG and a HypreBoomerAMG preconditioner for the penalized system. *\/\nclass PenaltyPCGSolver : public PenaltyConstrainedSolver\n{\npublic:\n PenaltyPCGSolver(HypreParMatrix& A, SparseMatrix& B, double penalty_,\n int dimension=0, bool reorder=false) :\n PenaltyConstrainedSolver(A, B, penalty_),\n dimension_(dimension), reorder_(reorder)\n { }\n\n PenaltyPCGSolver(HypreParMatrix& A, HypreParMatrix& B, double penalty_,\n int dimension=0, bool reorder=false) :\n PenaltyConstrainedSolver(A, B, penalty_),\n dimension_(dimension), reorder_(reorder)\n { }\n\nprotected:\n virtual Solver* BuildPreconditioner() const override\n {\n HypreBoomerAMG* h_prec = new HypreBoomerAMG(*penalized_mat);\n h_prec->SetPrintLevel(0);\n if (dimension_ > 0) { h_prec->SetSystemsOptions(dimension_, reorder_); }\n return h_prec;\n }\n\n virtual IterativeSolver* BuildKrylov() const override\n { return new CGSolver(GetComm()); }\n\nprivate:\n int dimension_;\n bool reorder_;\n};\n\n#endif\n\n\/** @brief Solve constrained system by solving original mixed sysetm;\n see ConstrainedSolver.\n\n Solves the saddle-point problem with a block-diagonal preconditioner, with\n user-provided preconditioner in the top-left block and (by default) an\n identity matrix in the bottom-right.\n\n This is the most general ConstrainedSolver, needing only Operator objects\n to function. But in general it is not very efficient or scalable. *\/\nclass SchurConstrainedSolver : public ConstrainedSolver\n{\npublic:\n \/\/\/ Setup constrained system, with primal_pc a user-provided preconditioner\n \/\/\/ for the top-left block.\n#ifdef MFEM_USE_MPI\n SchurConstrainedSolver(MPI_Comm comm, Operator& A_, Operator& B_,\n Solver& primal_pc_);\n#endif\n SchurConstrainedSolver(Operator& A_, Operator& B_, Solver& primal_pc_);\n virtual ~SchurConstrainedSolver();\n\n virtual void Mult(const Vector& x, Vector& y) const override;\n\nprotected:\n#ifdef MFEM_USE_MPI\n SchurConstrainedSolver(MPI_Comm comm, Operator& A_, Operator& B_);\n#endif\n SchurConstrainedSolver(Operator& A_, Operator& B_);\n\n Array offsets;\n BlockOperator * block_op; \/\/ owned\n TransposeOperator * tr_B; \/\/ owned\n Solver * primal_pc; \/\/ NOT owned\n BlockDiagonalPreconditioner * block_pc; \/\/ owned\n Solver * dual_pc; \/\/ owned\n\nprivate:\n void Initialize();\n};\n\n\n#ifdef MFEM_USE_MPI\n\/** @brief Basic saddle-point solver with assembled blocks (ie, the\n operators are assembled HypreParMatrix objects.)\n\n This uses a block-diagonal preconditioner that approximates\n \\f$ [ A^{-1} 0; 0 (B A^{-1} B^T)^{-1} ] \\f$.\n\n In the top-left block, we approximate \\f$ A^{-1} \\f$ with HypreBoomerAMG.\n In the bottom-right, we approximate \\f$ A^{-1} \\f$ with the inverse of the\n diagonal of \\f$ A \\f$, assemble \\f$ B D^{-1} B^T \\f$, and use\n HypreBoomerAMG on that assembled matrix. *\/\nclass SchurConstrainedHypreSolver : public SchurConstrainedSolver\n{\npublic:\n SchurConstrainedHypreSolver(MPI_Comm comm, HypreParMatrix& hA_,\n HypreParMatrix& hB_, int dimension=0,\n bool reorder=false);\n virtual ~SchurConstrainedHypreSolver();\n\nprivate:\n HypreParMatrix& hA;\n HypreParMatrix& hB;\n HypreParMatrix * schur_mat;\n};\n#endif\n\n}\n\n#endif\nEven clearer differentiation of ConstrainedSolver from ConstrainedOperator in documenation.\/\/ Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced\n\/\/ at the Lawrence Livermore National Laboratory. All Rights reserved. See files\n\/\/ LICENSE and NOTICE for details. LLNL-CODE-806117.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability visit https:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the BSD-3 license. We welcome feedback and contributions, see file\n\/\/ CONTRIBUTING.md for details.\n\n#ifndef MFEM_CONSTRAINED\n#define MFEM_CONSTRAINED\n\n#include \"solvers.hpp\"\n#include \"blockoperator.hpp\"\n#include \"sparsemat.hpp\"\n#include \"hypre.hpp\"\n\nnamespace mfem\n{\n\nclass ParFiniteElementSpace;\n\n\/** @brief An abstract class to solve the constrained system \\f$ Ax = f \\f$\n subject to the constraint \\f$ B x = r \\f$.\n\n Although implementations may not use the below formulation, for\n understanding some of its methods and notation you can think of\n it as solving the saddle-point system\n\n ( A B^T ) ( x ) ( f )\n ( B ) ( lambda ) = ( r )\n\n Do not confuse with ConstrainedOperator, which handles only simple\n pointwise constraints and is not a Solver.\n\n The height and width of this object as an IterativeSolver are for\n the above saddle point system, but one can use its PrimalMult() method\n to solve just \\f$ Ax = f \\f$ subject to a constraint with \\f$ r \\f$\n defaulting to zero or set via SetConstraintRHS().\n\n This abstract object unifies handling of the \"dual\" rhs \\f$ r \\f$\n and the Lagrange multiplier solution \\f$ \\lambda \\f$, so that derived\n classses can reuse that code. *\/\nclass ConstrainedSolver : public IterativeSolver\n{\npublic:\n#ifdef MFEM_USE_MPI\n ConstrainedSolver(MPI_Comm comm, Operator& A_, Operator& B_);\n#endif\n ConstrainedSolver(Operator& A_, Operator& B_);\n\n virtual ~ConstrainedSolver() { }\n\n virtual void SetOperator(const Operator& op) override { }\n\n \/** @brief Set the right-hand side r for the constraint B x = r\n\n (r defaults to zero if you don't call this) *\/\n virtual void SetConstraintRHS(const Vector& r);\n\n \/** @brief Return the Lagrange multiplier solution in lambda\n\n PrimalMult() only gives you x, this provides access to lambda\n\n Does not make sense unless you've already solved the constrained\n system with Mult() or PrimalMult() *\/\n void GetMultiplierSolution(Vector& lambda) const { lambda = multiplier_sol; }\n\n \/** @brief Solve for \\f$ x \\f$ given \\f$ f \\f$.\n\n If you want to set \\f$ r \\f$, call SetConstraintRHS() before this.\n\n If you want to get \\f$ \\lambda \\f$, call GetMultiplierSolution() after\n this.\n\n The base class implementation calls Mult(), so derived classes must\n implement either this or Mult() *\/\n virtual void PrimalMult(const Vector& f, Vector& x) const;\n\n \/** @brief Solve for (x, lambda) given (f, r)\n\n The base class implementation calls PrimalMult(), so derived classes\n must implement either this or PrimalMult() *\/\n virtual void Mult(const Vector& f_and_r, Vector& x_and_lambda) const override;\n\nprotected:\n Operator& A;\n Operator& B;\n\n mutable Vector constraint_rhs;\n mutable Vector multiplier_sol;\n mutable Vector workb;\n mutable Vector workx;\n\nprivate:\n void Initialize();\n};\n\n\n\/** @brief Perform elimination of a single constraint.\n\n See EliminationProjection, EliminationCGSolver\n\n This keeps track of primary \/ secondary tdofs and does small dense block\n solves to eliminate constraints from a global system.\n\n \\f$ B_s^{-1} \\f$ maps the lagrange space into secondary dofs, while\n \\f$ -B_s^{-1} B_p \\f$ maps primary dofs to secondary dofs. *\/\nclass Eliminator\n{\npublic:\n Eliminator(const SparseMatrix& B, const Array& lagrange_dofs,\n const Array& primary_tdofs,\n const Array& secondary_tdofs);\n\n const Array& LagrangeDofs() const { return lagrange_tdofs; }\n const Array& PrimaryDofs() const { return primary_tdofs; }\n const Array& SecondaryDofs() const { return secondary_tdofs; }\n\n \/\/\/ Given primary displacements, return secondary displacements\n \/\/\/ This applies \\f$ -B_s^{-1} B_p \\f$.\n void Eliminate(const Vector& in, Vector& out) const;\n\n \/\/\/ Transpose of Eliminate(), applies \\f$ -B_p^T B_s^{-T} \\f$\n void EliminateTranspose(const Vector& in, Vector& out) const;\n\n \/\/\/ Maps Lagrange multipliers to secondary displacements,\n \/\/\/ applies \\f$ B_s^{-1} \\f$\n void LagrangeSecondary(const Vector& in, Vector& out) const;\n\n \/\/\/ Transpose of LagrangeSecondary()\n void LagrangeSecondaryTranspose(const Vector& in, Vector& out) const;\n\n \/\/\/ Return \\f$ -B_s^{-1} B_p \\f$ explicitly assembled in mat\n void ExplicitAssembly(DenseMatrix& mat) const;\n\nprivate:\n Array lagrange_tdofs;\n Array primary_tdofs;\n Array secondary_tdofs;\n\n DenseMatrix Bp;\n DenseMatrix Bs; \/\/ gets inverted in place\n LUFactors Bsinverse;\n DenseMatrix BsT; \/\/ gets inverted in place\n LUFactors BsTinverse;\n Array ipiv;\n Array ipivT;\n};\n\n\n\/** Collects action of several Eliminator objects to perform elimination of\n constraints.\n\n Works in parallel, but each Eliminator must be processor local, and must\n operate on disjoint degrees of freedom (ie, the primary and secondary dofs\n for one Eliminator must have no overlap with any dofs from a different\n Eliminator). *\/\nclass EliminationProjection : public Operator\n{\npublic:\n EliminationProjection(const Operator& A, Array& eliminators);\n\n void Mult(const Vector& x, Vector& y) const override;\n\n void MultTranspose(const Vector& x, Vector& y) const override;\n\n \/** @brief Assemble this projector as a (processor-local) SparseMatrix.\n\n Some day we may also want to try approximate variants. *\/\n SparseMatrix * AssembleExact() const;\n\n \/** Given Lagrange multiplier right-hand-side \\f$ g \\f$, return\n \\f$ \\tilde{g} \\f$ *\/\n void BuildGTilde(const Vector& g, Vector& gtilde) const;\n\n \/** After a solve, recover the Lagrange multiplier. *\/\n void RecoverMultiplier(const Vector& disprhs,\n const Vector& disp, Vector& lm) const;\n\nprivate:\n const Operator& Aop;\n Array eliminators;\n};\n\n\n#ifdef MFEM_USE_MPI\n\/** @brief Solve constrained system by eliminating the constraint; see\n ConstrainedSolver\n\n Solves the system with the operator \\f$ P^T A P + Z_P \\f$, where P is\n EliminationProjection and Z_P is the identity on the eliminated dofs. *\/\nclass EliminationSolver : public ConstrainedSolver\n{\npublic:\n \/** @brief Constructor, with explicit splitting into primary\/secondary dofs.\n\n This constructor uses a single elimination block (per processor), which\n provides the most general algorithm but is also not scalable\n\n The secondary_dofs are eliminated from the system in this algorithm,\n as they can be written in terms of the primary_dofs. *\/\n EliminationSolver(HypreParMatrix& A, SparseMatrix& B,\n Array& primary_dofs,\n Array& secondary_dofs);\n\n \/** @brief Constructor, elimination is by blocks.\n\n The nonzeros in B are assumed to be in disjoint rows and columns; the\n rows are identified with the constraint_rowstarts array, the secondary\n dofs are assumed to be the first nonzeros in the rows. *\/\n EliminationSolver(HypreParMatrix& A, SparseMatrix& B,\n Array& constraint_rowstarts);\n\n ~EliminationSolver();\n\n void PrimalMult(const Vector& x, Vector& y) const override;\n\nprotected:\n \/\/\/ Internal utility routine; assembles eliminated matrix explicitly\n void BuildExplicitOperator();\n\n \/\/\/ Build preconditioner for eliminated system\n virtual Solver* BuildPreconditioner() const = 0;\n \/\/\/ Select krylov solver for eliminated system\n virtual IterativeSolver* BuildKrylov() const = 0;\n\n HypreParMatrix& hA;\n Array eliminators;\n EliminationProjection * projector;\n HypreParMatrix * h_explicit_operator;\n mutable Solver* prec;\n};\n\n\n\/** EliminationSolver using CG and HypreBoomerAMG *\/\nclass EliminationCGSolver : public EliminationSolver\n{\npublic:\n EliminationCGSolver(HypreParMatrix& A, SparseMatrix& B,\n Array& constraint_rowstarts,\n int dimension_=0, bool reorder_=false) :\n EliminationSolver(A, B, constraint_rowstarts),\n dimension(dimension_), reorder(reorder_)\n { BuildExplicitOperator(); }\n\nprotected:\n virtual Solver* BuildPreconditioner() const override\n {\n HypreBoomerAMG * h_prec = new HypreBoomerAMG(*h_explicit_operator);\n h_prec->SetPrintLevel(0);\n if (dimension > 0) { h_prec->SetSystemsOptions(dimension, reorder); }\n return h_prec;\n }\n\n virtual IterativeSolver* BuildKrylov() const override\n { return new CGSolver(GetComm()); }\n\nprivate:\n int dimension;\n bool reorder;\n};\n\n\n\/** @brief Solve constrained system with penalty method; see ConstrainedSolver.\n\n Only approximates the solution, better approximation with higher penalty,\n but with higher penalty the preconditioner is less effective. *\/\nclass PenaltyConstrainedSolver : public ConstrainedSolver\n{\npublic:\n PenaltyConstrainedSolver(HypreParMatrix& A, SparseMatrix& B,\n double penalty_);\n\n PenaltyConstrainedSolver(HypreParMatrix& A, HypreParMatrix& B,\n double penalty_);\n\n ~PenaltyConstrainedSolver();\n\n void PrimalMult(const Vector& x, Vector& y) const override;\n\nprotected:\n void Initialize(HypreParMatrix& A, HypreParMatrix& B);\n\n \/\/\/ Build preconditioner for penalized system\n virtual Solver* BuildPreconditioner() const = 0;\n \/\/\/ Select krylov solver for penalized system\n virtual IterativeSolver* BuildKrylov() const = 0;\n\n double penalty;\n Operator& constraintB;\n HypreParMatrix * penalized_mat;\n mutable Solver * prec;\n};\n\n\n\/** Uses CG and a HypreBoomerAMG preconditioner for the penalized system. *\/\nclass PenaltyPCGSolver : public PenaltyConstrainedSolver\n{\npublic:\n PenaltyPCGSolver(HypreParMatrix& A, SparseMatrix& B, double penalty_,\n int dimension=0, bool reorder=false) :\n PenaltyConstrainedSolver(A, B, penalty_),\n dimension_(dimension), reorder_(reorder)\n { }\n\n PenaltyPCGSolver(HypreParMatrix& A, HypreParMatrix& B, double penalty_,\n int dimension=0, bool reorder=false) :\n PenaltyConstrainedSolver(A, B, penalty_),\n dimension_(dimension), reorder_(reorder)\n { }\n\nprotected:\n virtual Solver* BuildPreconditioner() const override\n {\n HypreBoomerAMG* h_prec = new HypreBoomerAMG(*penalized_mat);\n h_prec->SetPrintLevel(0);\n if (dimension_ > 0) { h_prec->SetSystemsOptions(dimension_, reorder_); }\n return h_prec;\n }\n\n virtual IterativeSolver* BuildKrylov() const override\n { return new CGSolver(GetComm()); }\n\nprivate:\n int dimension_;\n bool reorder_;\n};\n\n#endif\n\n\/** @brief Solve constrained system by solving original mixed sysetm;\n see ConstrainedSolver.\n\n Solves the saddle-point problem with a block-diagonal preconditioner, with\n user-provided preconditioner in the top-left block and (by default) an\n identity matrix in the bottom-right.\n\n This is the most general ConstrainedSolver, needing only Operator objects\n to function. But in general it is not very efficient or scalable. *\/\nclass SchurConstrainedSolver : public ConstrainedSolver\n{\npublic:\n \/\/\/ Setup constrained system, with primal_pc a user-provided preconditioner\n \/\/\/ for the top-left block.\n#ifdef MFEM_USE_MPI\n SchurConstrainedSolver(MPI_Comm comm, Operator& A_, Operator& B_,\n Solver& primal_pc_);\n#endif\n SchurConstrainedSolver(Operator& A_, Operator& B_, Solver& primal_pc_);\n virtual ~SchurConstrainedSolver();\n\n virtual void Mult(const Vector& x, Vector& y) const override;\n\nprotected:\n#ifdef MFEM_USE_MPI\n SchurConstrainedSolver(MPI_Comm comm, Operator& A_, Operator& B_);\n#endif\n SchurConstrainedSolver(Operator& A_, Operator& B_);\n\n Array offsets;\n BlockOperator * block_op; \/\/ owned\n TransposeOperator * tr_B; \/\/ owned\n Solver * primal_pc; \/\/ NOT owned\n BlockDiagonalPreconditioner * block_pc; \/\/ owned\n Solver * dual_pc; \/\/ owned\n\nprivate:\n void Initialize();\n};\n\n\n#ifdef MFEM_USE_MPI\n\/** @brief Basic saddle-point solver with assembled blocks (ie, the\n operators are assembled HypreParMatrix objects.)\n\n This uses a block-diagonal preconditioner that approximates\n \\f$ [ A^{-1} 0; 0 (B A^{-1} B^T)^{-1} ] \\f$.\n\n In the top-left block, we approximate \\f$ A^{-1} \\f$ with HypreBoomerAMG.\n In the bottom-right, we approximate \\f$ A^{-1} \\f$ with the inverse of the\n diagonal of \\f$ A \\f$, assemble \\f$ B D^{-1} B^T \\f$, and use\n HypreBoomerAMG on that assembled matrix. *\/\nclass SchurConstrainedHypreSolver : public SchurConstrainedSolver\n{\npublic:\n SchurConstrainedHypreSolver(MPI_Comm comm, HypreParMatrix& hA_,\n HypreParMatrix& hB_, int dimension=0,\n bool reorder=false);\n virtual ~SchurConstrainedHypreSolver();\n\nprivate:\n HypreParMatrix& hA;\n HypreParMatrix& hB;\n HypreParMatrix * schur_mat;\n};\n#endif\n\n}\n\n#endif\n<|endoftext|>"} {"text":"\/** Copyright (C) 2016, 2017 European Spallation Source ERIC *\/\n\n#include \n#include \n\nclass EFUArgsTest : public TestBase {};\n\nTEST_F(EFUArgsTest, Constructor) {\n EFUArgs efu_args;\n auto settings = efu_args.GetBaseSettings();\n\n \/\/ ASSERT_EQ(12, settings.cpustart); \/**< todo fixme *\/\n ASSERT_EQ(\"0.0.0.0\", settings.DetectorAddress);\n ASSERT_EQ(9000, settings.DetectorPort);\n ASSERT_EQ(\"localhost:9092\", settings.KafkaBroker);\n ASSERT_EQ(\"127.0.0.1\", settings.GraphiteAddress);\n ASSERT_EQ(2003, settings.GraphitePort);\n ASSERT_EQ(0xffffffffU, settings.StopAfterSec);\n}\n\nTEST_F(EFUArgsTest, VerifyCommandLineOptions) {\n\n \/\/ clang-format off\n const char *myargv[] = {\"progname\",\n \"-b\", \"mybroker:9091\",\n \"-c\" , \"99\",\n \"-d\", \"myinst\",\n \"-i\", \"1.2.3.4\",\n \"-p\", \"9876\",\n \"-g\", \"4.3.2.1\",\n \"-o\", \"2323\",\n \"-s\", \"5\",\n \"-a\", \"10.0.0.1\",\n \"-m\", \"8989\" };\n \/\/ clang-format on\n int myargc = 21;\n EFUArgs efu_args;\n auto ret = efu_args.parseAndProceed(myargc, (char **)myargv);\n ASSERT_EQ(ret, true); \/\/ has detector\n auto settings = efu_args.GetBaseSettings();\n auto glsettings = efu_args.getGraylogSettings();\n\n ASSERT_EQ(\"mybroker:9091\", settings.KafkaBroker);\n \/\/ ASSERT_EQ(99, opts.cpustart); \/**< todo fixme *\/\n ASSERT_EQ(\"myinst\", settings.DetectorPluginName);\n ASSERT_EQ(\"1.2.3.4\", settings.DetectorAddress);\n ASSERT_EQ(9876, settings.DetectorPort);\n ASSERT_EQ(\"4.3.2.1\", settings.GraphiteAddress);\n ASSERT_EQ(2323, settings.GraphitePort);\n ASSERT_EQ(5, settings.StopAfterSec);\n ASSERT_EQ(\"10.0.0.1\", glsettings.address);\n ASSERT_EQ(8989, settings.CommandServerPort);\n}\n\nTEST_F(EFUArgsTest, HelpText) {\n int myargc = 2;\n const char *myargv[] = {\"progname\", \"-h\"};\n\n EFUArgs efu_args;\n auto ret = efu_args.parseAndProceed(myargc, (char **)myargv);\n ASSERT_EQ(ret, false); \/\/ has detector\n\n ASSERT_EQ(myargc, 2);\n ASSERT_TRUE(myargv != NULL);\n}\n\nTEST_F(EFUArgsTest, XTRACE_Text) {\n EFUArgs efu_args;\n MESSAGE() << \"This is not a test, just ensuring printout is done once\\n\" ;\n efu_args.printSettings();\n}\n\nint main(int argc, char **argv) {\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\npre merge commit - working on EFUArgsTest\/** Copyright (C) 2016, 2017 European Spallation Source ERIC *\/\n\n#include \n#include \n\nclass EFUArgsTest : public TestBase {};\n\nTEST_F(EFUArgsTest, Constructor) {\n EFUArgs efu_args;\n auto settings = efu_args.GetBaseSettings();\n\n \/\/ ASSERT_EQ(12, settings.cpustart); \/**< todo fixme *\/\n ASSERT_EQ(\"0.0.0.0\", settings.DetectorAddress);\n ASSERT_EQ(9000, settings.DetectorPort);\n ASSERT_EQ(\"localhost:9092\", settings.KafkaBroker);\n ASSERT_EQ(\"127.0.0.1\", settings.GraphiteAddress);\n ASSERT_EQ(2003, settings.GraphitePort);\n ASSERT_EQ(0xffffffffU, settings.StopAfterSec);\n}\n\nTEST_F(EFUArgsTest, VerifyCommandLineOptions) {\n\n \/\/ clang-format off\n const char *myargv[] = {\"progname\",\n \"-b\", \"mybroker:9091\",\n \"-c\" , \"99\",\n \"-d\", \"myinst\",\n \"-i\", \"1.2.3.4\",\n \"-p\", \"9876\",\n \"-g\", \"4.3.2.1\",\n \"-o\", \"2323\",\n \"-s\", \"5\",\n \"-a\", \"10.0.0.1\",\n \"-m\", \"8989\" };\n \/\/ clang-format on\n int myargc = 21;\n EFUArgs efu_args;\n auto ret = efu_args.parseAndProceed(myargc, (char **)myargv);\n ASSERT_EQ(ret, true); \/\/ has detector\n auto settings = efu_args.GetBaseSettings();\n auto glsettings = efu_args.getGraylogSettings();\n\n ASSERT_EQ(\"mybroker:9091\", settings.KafkaBroker);\n \/\/ ASSERT_EQ(99, opts.cpustart); \/**< todo fixme *\/\n ASSERT_EQ(\"myinst\", settings.DetectorPluginName);\n ASSERT_EQ(\"1.2.3.4\", settings.DetectorAddress);\n ASSERT_EQ(9876, settings.DetectorPort);\n ASSERT_EQ(\"4.3.2.1\", settings.GraphiteAddress);\n ASSERT_EQ(2323, settings.GraphitePort);\n ASSERT_EQ(5, settings.StopAfterSec);\n ASSERT_EQ(\"10.0.0.1\", glsettings.address);\n ASSERT_EQ(8989, settings.CommandServerPort);\n}\n\nTEST_F(EFUArgsTest, HelpText) {\n int myargc = 2;\n const char *myargv[] = {\"progname\", \"-h\"};\n\n EFUArgs efu_args;\n auto ret = efu_args.parseAndProceed(myargc, (char **)myargv);\n ASSERT_EQ(ret, false); \/\/ has detector\n\n ASSERT_EQ(myargc, 2);\n ASSERT_TRUE(myargv != NULL);\n}\n\nTEST_F(EFUArgsTest, CoreAffinityOption) {\n int myargc = 5;\n const char *myargv[] = {\"progname\", \"-d\", \"dummydetector\", \"-c\", \"thread1:5\"};\n\n EFUArgs efu_args;\n auto ret = efu_args.parseAndProceed(myargc, (char **)myargv);\n ASSERT_EQ(ret, false); \/\/ has detector\n\n ASSERT_EQ(myargc, 5);\n ASSERT_TRUE(myargv != NULL);\n}\n\nTEST_F(EFUArgsTest, PrintHelpText) {\n EFUArgs efu_args;\n MESSAGE() << \"This is not a test, just ensuring printout is done once\\n\" ;\n efu_args.printHelp();\n}\n\nTEST_F(EFUArgsTest, XTRACE_Text) {\n EFUArgs efu_args;\n MESSAGE() << \"This is not a test, just ensuring printout is done once\\n\" ;\n efu_args.printSettings();\n}\n\nint main(int argc, char **argv) {\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"#include \"kugouwindow.h\"\n\n#ifdef MUSIC_WEBKIT\n# if QT_VERSION >= QT_VERSION_CHECK(5,0,0)\n# include \n# include \n# else\n# include \n# include \n# endif\n#endif\n#include \n#include \n#include \n#include \n\nKugouWindow::KugouWindow(QWidget *parent)\n : QWidget(parent)\n{\n QVBoxLayout *layout = new QVBoxLayout(this);\n layout->setSpacing(0);\n layout->setContentsMargins(0, 0, 0, 0);\n#ifdef MUSIC_WEBKIT\n const QString radioStyle = \"QPushButton{ border:none; color:rgb(135, 135, 135);} \\\n QPushButton:hover{ color:rgb(104, 169, 236);} \\\n QPushButton:checked{ color:rgb(40, 143, 231);} \\\n QWidget{background: white;}\";\n QWidget *top = new QWidget(this);\n top->setFixedHeight(25);\n top->setStyleSheet( radioStyle );\n QHBoxLayout *topLayout = new QHBoxLayout(top);\n topLayout->setContentsMargins(0, 0, 0, 0);\n\n QButtonGroup *buttonGroup = new QButtonGroup(this);\n QPushButton *bt = new QPushButton(tr(\" Recommend \"), top);\n bt->setCursor(QCursor(Qt::PointingHandCursor));\n buttonGroup->addButton(bt, 0);\n bt = new QPushButton(tr(\" Radio \"), top);\n bt->setCursor(QCursor(Qt::PointingHandCursor));\n buttonGroup->addButton(bt, 1);\n bt = new QPushButton(tr(\" Rank \"), top);\n bt->setCursor(QCursor(Qt::PointingHandCursor));\n buttonGroup->addButton(bt, 2);\n bt = new QPushButton(tr(\" Singer \"), top);\n bt->setCursor(QCursor(Qt::PointingHandCursor));\n buttonGroup->addButton(bt, 3);\n bt = new QPushButton(tr(\" Category \"), top);\n bt->setCursor(QCursor(Qt::PointingHandCursor));\n buttonGroup->addButton(bt, 4);\n bt = new QPushButton(tr(\" Show \"), top);\n bt->setCursor(QCursor(Qt::PointingHandCursor));\n buttonGroup->addButton(bt, 5);\n bt = new QPushButton(tr(\" CCTV \"), top);\n bt->setCursor(QCursor(Qt::PointingHandCursor));\n buttonGroup->addButton(bt, 6);\n connect(buttonGroup, SIGNAL(buttonClicked(int)), SLOT(differButtonIndexChanged(int)));\n\n topLayout->addStretch(1);\n topLayout->addWidget(buttonGroup->button(0));\n topLayout->addWidget(buttonGroup->button(1));\n topLayout->addWidget(buttonGroup->button(2));\n topLayout->addWidget(buttonGroup->button(3));\n topLayout->addWidget(buttonGroup->button(4));\n topLayout->addWidget(buttonGroup->button(5));\n topLayout->addWidget(buttonGroup->button(6));\n topLayout->addStretch(1);\n\n QWebView *view = new QWebView(this);\n view->page()->mainFrame()->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff);\n view->setUrl(QUrl( KugouUrl::getRecommendUrl() ));\n\n layout->addWidget(top);\n layout->addWidget(m_webView = view);\n#else\n QLabel *pix = new QLabel(this);\n pix->setPixmap(QPixmap(\":\/image\/nowebkit\"));\n layout->addWidget(pix);\n#endif\n setLayout(layout);\n}\n\nKugouWindow::~KugouWindow()\n{\n delete m_webView;\n}\n\nQString KugouWindow::getClassName()\n{\n return staticMetaObject.className();\n}\n\nvoid KugouWindow::differButtonIndexChanged(int index)\n{\n QString url = KugouUrl::getRecommendUrl();\n switch(index)\n {\n case 0: url = KugouUrl::getRecommendUrl(); break;\n case 1: url = KugouUrl::getRadioUrl(); break;\n case 2: url = KugouUrl::getRankUrl(); break;\n case 3: url = KugouUrl::getSingerUrl(); break;\n case 4: url = KugouUrl::getCategoryUrl(); break;\n case 5: url = KugouUrl::getShowUrl(); break;\n case 6: url = KugouUrl::getCCTVUrl(); break;\n }\n#ifdef MUSIC_WEBKIT\n static_cast(m_webView)->setUrl(QUrl( url ));\n#endif\n}\nset pointer to null while no macro effected[741258]#include \"kugouwindow.h\"\n\n#ifdef MUSIC_WEBKIT\n# if QT_VERSION >= QT_VERSION_CHECK(5,0,0)\n# include \n# include \n# else\n# include \n# include \n# endif\n#endif\n#include \n#include \n#include \n#include \n\nKugouWindow::KugouWindow(QWidget *parent)\n : QWidget(parent)\n{\n QVBoxLayout *layout = new QVBoxLayout(this);\n layout->setSpacing(0);\n layout->setContentsMargins(0, 0, 0, 0);\n#ifdef MUSIC_WEBKIT\n const QString radioStyle = \"QPushButton{ border:none; color:rgb(135, 135, 135);} \\\n QPushButton:hover{ color:rgb(104, 169, 236);} \\\n QPushButton:checked{ color:rgb(40, 143, 231);} \\\n QWidget{background: white;}\";\n QWidget *top = new QWidget(this);\n top->setFixedHeight(25);\n top->setStyleSheet( radioStyle );\n QHBoxLayout *topLayout = new QHBoxLayout(top);\n topLayout->setContentsMargins(0, 0, 0, 0);\n\n QButtonGroup *buttonGroup = new QButtonGroup(this);\n QPushButton *bt = new QPushButton(tr(\" Recommend \"), top);\n bt->setCursor(QCursor(Qt::PointingHandCursor));\n buttonGroup->addButton(bt, 0);\n bt = new QPushButton(tr(\" Radio \"), top);\n bt->setCursor(QCursor(Qt::PointingHandCursor));\n buttonGroup->addButton(bt, 1);\n bt = new QPushButton(tr(\" Rank \"), top);\n bt->setCursor(QCursor(Qt::PointingHandCursor));\n buttonGroup->addButton(bt, 2);\n bt = new QPushButton(tr(\" Singer \"), top);\n bt->setCursor(QCursor(Qt::PointingHandCursor));\n buttonGroup->addButton(bt, 3);\n bt = new QPushButton(tr(\" Category \"), top);\n bt->setCursor(QCursor(Qt::PointingHandCursor));\n buttonGroup->addButton(bt, 4);\n bt = new QPushButton(tr(\" Show \"), top);\n bt->setCursor(QCursor(Qt::PointingHandCursor));\n buttonGroup->addButton(bt, 5);\n bt = new QPushButton(tr(\" CCTV \"), top);\n bt->setCursor(QCursor(Qt::PointingHandCursor));\n buttonGroup->addButton(bt, 6);\n connect(buttonGroup, SIGNAL(buttonClicked(int)), SLOT(differButtonIndexChanged(int)));\n\n topLayout->addStretch(1);\n topLayout->addWidget(buttonGroup->button(0));\n topLayout->addWidget(buttonGroup->button(1));\n topLayout->addWidget(buttonGroup->button(2));\n topLayout->addWidget(buttonGroup->button(3));\n topLayout->addWidget(buttonGroup->button(4));\n topLayout->addWidget(buttonGroup->button(5));\n topLayout->addWidget(buttonGroup->button(6));\n topLayout->addStretch(1);\n\n QWebView *view = new QWebView(this);\n view->page()->mainFrame()->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff);\n view->setUrl(QUrl( KugouUrl::getRecommendUrl() ));\n\n layout->addWidget(top);\n layout->addWidget(m_webView = view);\n#else\n m_webView = nullptr;\n QLabel *pix = new QLabel(this);\n pix->setPixmap(QPixmap(\":\/image\/nowebkit\"));\n layout->addWidget(pix);\n#endif\n setLayout(layout);\n}\n\nKugouWindow::~KugouWindow()\n{\n delete m_webView;\n}\n\nQString KugouWindow::getClassName()\n{\n return staticMetaObject.className();\n}\n\nvoid KugouWindow::differButtonIndexChanged(int index)\n{\n QString url = KugouUrl::getRecommendUrl();\n switch(index)\n {\n case 0: url = KugouUrl::getRecommendUrl(); break;\n case 1: url = KugouUrl::getRadioUrl(); break;\n case 2: url = KugouUrl::getRankUrl(); break;\n case 3: url = KugouUrl::getSingerUrl(); break;\n case 4: url = KugouUrl::getCategoryUrl(); break;\n case 5: url = KugouUrl::getShowUrl(); break;\n case 6: url = KugouUrl::getCCTVUrl(); break;\n }\n#ifdef MUSIC_WEBKIT\n static_cast(m_webView)->setUrl(QUrl( url ));\n#endif\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2010 Jens-Michael Hoffmann \n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library. If not, see .\n\n#include \"BlendingAlgorithms.h\"\n\n#include \"TextureTile.h\"\n\n#include \n\n#include \n#include \n\nnamespace Marble\n{\n\nvoid OverpaintBlending::blend( QImage * const bottom, TextureTile const * const top ) const\n{\n Q_ASSERT( bottom );\n Q_ASSERT( top );\n Q_ASSERT( top->image() );\n Q_ASSERT( bottom->size() == top->image()->size() );\n Q_ASSERT( bottom->format() == QImage::Format_ARGB32_Premultiplied );\n\n QPainter painter( bottom );\n\n painter.drawImage( 0, 0, *top->image() );\n}\n\n\/\/ pre-conditions:\n\/\/ - bottom and top image have the same size\n\/\/ - bottom image format is ARGB32_Premultiplied\nvoid IndependentChannelBlending::blend( QImage * const bottom,\n TextureTile const * const top ) const\n{\n QImage const * const topImage = top->image();\n Q_ASSERT( topImage );\n Q_ASSERT( bottom->size() == topImage->size() );\n Q_ASSERT( bottom->format() == QImage::Format_ARGB32_Premultiplied );\n\n int const width = bottom->width();\n int const height = bottom->height();\n QImage const topImagePremult = topImage->convertToFormat( QImage::Format_ARGB32_Premultiplied );\n for ( int y = 0; y < height; ++y ) {\n for ( int x = 0; x < width; ++x ) {\n QRgb const bottomPixel = bottom->pixel( x, y );\n QRgb const topPixel = topImagePremult.pixel( x, y );\n qreal const resultRed = blendChannel( qRed( bottomPixel ) \/ 255.0,\n qRed( topPixel ) \/ 255.0 );\n qreal const resultGreen = blendChannel( qGreen( bottomPixel ) \/ 255.0,\n qGreen( topPixel ) \/ 255.0 );\n qreal const resultBlue = blendChannel( qBlue( bottomPixel ) \/ 255.0,\n qBlue( topPixel ) \/ 255.0 );\n bottom->setPixel( x, y, qRgb( resultRed * 255.0,\n resultGreen * 255.0,\n resultBlue * 255.0 ));\n }\n }\n}\n\n\n\/\/ Neutral blendings\n\nqreal AllanonBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return ( bottomColorIntensity + topColorIntensity ) \/ 2.0;\n}\n\nqreal ArcusTangentBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return 2.0 * atan( topColorIntensity \/ bottomColorIntensity ) \/ M_PI;\n}\n\nqreal GeometricMeanBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return sqrt( bottomColorIntensity * topColorIntensity );\n}\n\nqreal LinearLightBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return qMin( qreal( 1.0 ),\n qMax( qreal( 0.0 ), qreal( bottomColorIntensity + 2.0 * topColorIntensity - 1.0 )));\n}\n\nqreal OverlayBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n if ( bottomColorIntensity < 0.5 )\n return 2.0 * bottomColorIntensity * topColorIntensity;\n else\n return 1.0 - 2.0 * ( 1.0 - bottomColorIntensity ) * ( 1.0 - topColorIntensity );\n}\n\nqreal ParallelBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n Q_UNUSED(bottomColorIntensity);\n Q_UNUSED(topColorIntensity);\n \/\/ FIXME: return qMin( qMax( 2.0 \/ ( 1.0 \/ bottomColorIntensity + 1.0 \/ topColorIntensity )), 0.0, 1.0 );\n return 0.0;\n}\n\nqreal TextureBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n Q_UNUSED(bottomColorIntensity);\n Q_UNUSED(topColorIntensity);\n \/\/ FIXME: return qMax( qMin( topColorIntensity + bottomColorIntensity ) - 0.5 ), 1.0 ), 0.0 );\n return 0.0;\n}\n\n\n\/\/ Darkening blendings\n\nqreal ColorBurnBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n Q_UNUSED(bottomColorIntensity);\n Q_UNUSED(topColorIntensity);\n \/\/ FIXME: check if this formula makes sense\n return qMin( qreal( 1.0 ),\n qMax( qreal( 0.0 ), qreal( 1.0 - ( 1.0 - bottomColorIntensity ) \/ topColorIntensity )));\n}\n\nqreal DarkBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return ( bottomColorIntensity + 1.0 - topColorIntensity ) * topColorIntensity;\n}\n\nqreal DarkenBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n \/\/ FIXME: is this really ok? not vice versa?\n return bottomColorIntensity > topColorIntensity ? topColorIntensity : bottomColorIntensity;\n}\n\nqreal DivideBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return log( 1.0 + bottomColorIntensity \/ ( 1.0 - topColorIntensity ) \/ 8.0) \/ log(2.0);\n}\n\nqreal GammaDarkBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return pow( bottomColorIntensity, 1.0 \/ topColorIntensity );\n}\n\nqreal LinearBurnBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return qMax( 0.0, bottomColorIntensity + topColorIntensity - 1.0 );\n}\n\nqreal MultiplyBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return bottomColorIntensity * topColorIntensity;\n}\n\nqreal SubtractiveBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return qMax( bottomColorIntensity - topColorIntensity, qreal(0.0) );\n}\n\n\n\/\/ Lightening blendings\n\nqreal AdditiveBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return qMin( topColorIntensity + bottomColorIntensity, qreal(1.0) );\n}\n\nqreal ColorDodgeBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return qMin( qreal( 1.0 ),\n qMax( qreal( 0.0 ), qreal( bottomColorIntensity \/ ( 1.0 - topColorIntensity ))));\n}\n\nqreal GammaLightBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return pow( bottomColorIntensity, topColorIntensity );\n}\n\nqreal HardLightBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return topColorIntensity < 0.5\n ? 2.0 * bottomColorIntensity * topColorIntensity\n : 1.0 - 2.0 * ( 1.0 - bottomColorIntensity ) * ( 1.0 - topColorIntensity );\n}\n\nqreal LightBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return bottomColorIntensity * ( 1.0 - topColorIntensity ) + pow( topColorIntensity, 2 );\n}\n\nqreal LightenBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n \/\/ is this ok?\n return bottomColorIntensity < topColorIntensity ? topColorIntensity : bottomColorIntensity;\n}\n\nqreal PinLightBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return qMax( qreal(0.0), qMax( qreal(2.0 + topColorIntensity - 1.0),\n qMin( bottomColorIntensity, qreal(2.0 * topColorIntensity ))));\n}\n\nqreal ScreenBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return 1.0 - ( 1.0 - bottomColorIntensity ) * ( 1.0 - topColorIntensity );\n}\n\nqreal SoftLightBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return pow( bottomColorIntensity, pow( 2.0, ( 2.0 * ( 0.5 - topColorIntensity ))));\n}\n\nqreal VividLightBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return topColorIntensity < 0.5\n ? qMin( qreal( 1.0 ),\n qMax( qreal( 0.0 ), qreal( 1.0 - ( 1.0 - bottomColorIntensity ) \/ ( 2.0 * topColorIntensity ))))\n : qMin( qreal( 1.0 ),\n qMax( qreal( 0.0 ), qreal( bottomColorIntensity \/ ( 2.0 * ( 1.0 - topColorIntensity )))));\n}\n\n\n\/\/ Inverter blendings\n\nqreal AdditiveSubtractiveBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n Q_UNUSED(bottomColorIntensity);\n Q_UNUSED(topColorIntensity);\n \/\/ FIXME:\n \/\/ return qMin( 1.0, qMax( 0.0, abs( bottomColorIntensity * bottomColorIntensity\n \/\/ - topColorIntensity * topColorIntensity )));\n return 0.0;\n}\n\nqreal BleachBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n \/\/ FIXME: \"why this is the same formula as Screen Blending? Please correct.)\"\n return 1.0 - ( 1.0 - bottomColorIntensity ) * ( 1.0 - topColorIntensity );\n}\n\nqreal DifferenceBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return qMax( qMin( qreal( 1.0 ), qreal( bottomColorIntensity - topColorIntensity + 0.5 )),\n qreal( 0.0 ));\n}\n\nqreal EquivalenceBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return 1.0 - abs( bottomColorIntensity - topColorIntensity );\n}\n\nqreal HalfDifferenceBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return bottomColorIntensity + topColorIntensity\n - 2.0 * ( bottomColorIntensity * topColorIntensity );\n}\n\n\n\/\/ Special purpose blendings\n\nvoid CloudsBlending::blend( QImage * const bottom, TextureTile const * const top ) const\n{\n QImage const * const topImage = top->image();\n Q_ASSERT( topImage );\n Q_ASSERT( bottom->size() == topImage->size() );\n int const width = bottom->width();\n int const height = bottom->height();\n for ( int y = 0; y < height; ++y ) {\n for ( int x = 0; x < width; ++x ) {\n qreal const c = qRed( topImage->pixel( x, y )) \/ 255.0;\n QRgb const bottomPixel = bottom->pixel( x, y );\n int const bottomRed = qRed( bottomPixel );\n int const bottomGreen = qGreen( bottomPixel );\n int const bottomBlue = qBlue( bottomPixel );\n bottom->setPixel( x, y, qRgb(( int )( bottomRed + ( 255 - bottomRed ) * c ),\n ( int )( bottomGreen + ( 255 - bottomGreen ) * c ),\n ( int )( bottomBlue + ( 255 - bottomBlue ) * c )));\n }\n }\n}\n\n\n}\nCast to qreal\/\/ Copyright 2010 Jens-Michael Hoffmann \n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library. If not, see .\n\n#include \"BlendingAlgorithms.h\"\n\n#include \"TextureTile.h\"\n\n#include \n\n#include \n#include \n\nnamespace Marble\n{\n\nvoid OverpaintBlending::blend( QImage * const bottom, TextureTile const * const top ) const\n{\n Q_ASSERT( bottom );\n Q_ASSERT( top );\n Q_ASSERT( top->image() );\n Q_ASSERT( bottom->size() == top->image()->size() );\n Q_ASSERT( bottom->format() == QImage::Format_ARGB32_Premultiplied );\n\n QPainter painter( bottom );\n\n painter.drawImage( 0, 0, *top->image() );\n}\n\n\/\/ pre-conditions:\n\/\/ - bottom and top image have the same size\n\/\/ - bottom image format is ARGB32_Premultiplied\nvoid IndependentChannelBlending::blend( QImage * const bottom,\n TextureTile const * const top ) const\n{\n QImage const * const topImage = top->image();\n Q_ASSERT( topImage );\n Q_ASSERT( bottom->size() == topImage->size() );\n Q_ASSERT( bottom->format() == QImage::Format_ARGB32_Premultiplied );\n\n int const width = bottom->width();\n int const height = bottom->height();\n QImage const topImagePremult = topImage->convertToFormat( QImage::Format_ARGB32_Premultiplied );\n for ( int y = 0; y < height; ++y ) {\n for ( int x = 0; x < width; ++x ) {\n QRgb const bottomPixel = bottom->pixel( x, y );\n QRgb const topPixel = topImagePremult.pixel( x, y );\n qreal const resultRed = blendChannel( qRed( bottomPixel ) \/ 255.0,\n qRed( topPixel ) \/ 255.0 );\n qreal const resultGreen = blendChannel( qGreen( bottomPixel ) \/ 255.0,\n qGreen( topPixel ) \/ 255.0 );\n qreal const resultBlue = blendChannel( qBlue( bottomPixel ) \/ 255.0,\n qBlue( topPixel ) \/ 255.0 );\n bottom->setPixel( x, y, qRgb( resultRed * 255.0,\n resultGreen * 255.0,\n resultBlue * 255.0 ));\n }\n }\n}\n\n\n\/\/ Neutral blendings\n\nqreal AllanonBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return ( bottomColorIntensity + topColorIntensity ) \/ 2.0;\n}\n\nqreal ArcusTangentBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return 2.0 * atan( topColorIntensity \/ bottomColorIntensity ) \/ M_PI;\n}\n\nqreal GeometricMeanBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return sqrt( bottomColorIntensity * topColorIntensity );\n}\n\nqreal LinearLightBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return qMin( qreal( 1.0 ),\n qMax( qreal( 0.0 ), qreal( bottomColorIntensity + 2.0 * topColorIntensity - 1.0 )));\n}\n\nqreal OverlayBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n if ( bottomColorIntensity < 0.5 )\n return 2.0 * bottomColorIntensity * topColorIntensity;\n else\n return 1.0 - 2.0 * ( 1.0 - bottomColorIntensity ) * ( 1.0 - topColorIntensity );\n}\n\nqreal ParallelBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n Q_UNUSED(bottomColorIntensity);\n Q_UNUSED(topColorIntensity);\n \/\/ FIXME: return qMin( qMax( 2.0 \/ ( 1.0 \/ bottomColorIntensity + 1.0 \/ topColorIntensity )), 0.0, 1.0 );\n return 0.0;\n}\n\nqreal TextureBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n Q_UNUSED(bottomColorIntensity);\n Q_UNUSED(topColorIntensity);\n \/\/ FIXME: return qMax( qMin( topColorIntensity + bottomColorIntensity ) - 0.5 ), 1.0 ), 0.0 );\n return 0.0;\n}\n\n\n\/\/ Darkening blendings\n\nqreal ColorBurnBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n Q_UNUSED(bottomColorIntensity);\n Q_UNUSED(topColorIntensity);\n \/\/ FIXME: check if this formula makes sense\n return qMin( qreal( 1.0 ),\n qMax( qreal( 0.0 ), qreal( 1.0 - ( 1.0 - bottomColorIntensity ) \/ topColorIntensity )));\n}\n\nqreal DarkBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return ( bottomColorIntensity + 1.0 - topColorIntensity ) * topColorIntensity;\n}\n\nqreal DarkenBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n \/\/ FIXME: is this really ok? not vice versa?\n return bottomColorIntensity > topColorIntensity ? topColorIntensity : bottomColorIntensity;\n}\n\nqreal DivideBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return log( 1.0 + bottomColorIntensity \/ ( 1.0 - topColorIntensity ) \/ 8.0) \/ log(2.0);\n}\n\nqreal GammaDarkBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return pow( bottomColorIntensity, 1.0 \/ topColorIntensity );\n}\n\nqreal LinearBurnBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return qMax( qreal(0.0), bottomColorIntensity + topColorIntensity - 1.0 );\n}\n\nqreal MultiplyBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return bottomColorIntensity * topColorIntensity;\n}\n\nqreal SubtractiveBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return qMax( bottomColorIntensity - topColorIntensity, qreal(0.0) );\n}\n\n\n\/\/ Lightening blendings\n\nqreal AdditiveBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return qMin( topColorIntensity + bottomColorIntensity, qreal(1.0) );\n}\n\nqreal ColorDodgeBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return qMin( qreal( 1.0 ),\n qMax( qreal( 0.0 ), qreal( bottomColorIntensity \/ ( 1.0 - topColorIntensity ))));\n}\n\nqreal GammaLightBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return pow( bottomColorIntensity, topColorIntensity );\n}\n\nqreal HardLightBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return topColorIntensity < 0.5\n ? 2.0 * bottomColorIntensity * topColorIntensity\n : 1.0 - 2.0 * ( 1.0 - bottomColorIntensity ) * ( 1.0 - topColorIntensity );\n}\n\nqreal LightBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return bottomColorIntensity * ( 1.0 - topColorIntensity ) + pow( topColorIntensity, 2 );\n}\n\nqreal LightenBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n \/\/ is this ok?\n return bottomColorIntensity < topColorIntensity ? topColorIntensity : bottomColorIntensity;\n}\n\nqreal PinLightBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return qMax( qreal(0.0), qMax( qreal(2.0 + topColorIntensity - 1.0),\n qMin( bottomColorIntensity, qreal(2.0 * topColorIntensity ))));\n}\n\nqreal ScreenBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return 1.0 - ( 1.0 - bottomColorIntensity ) * ( 1.0 - topColorIntensity );\n}\n\nqreal SoftLightBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return pow( bottomColorIntensity, pow( 2.0, ( 2.0 * ( 0.5 - topColorIntensity ))));\n}\n\nqreal VividLightBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return topColorIntensity < 0.5\n ? qMin( qreal( 1.0 ),\n qMax( qreal( 0.0 ), qreal( 1.0 - ( 1.0 - bottomColorIntensity ) \/ ( 2.0 * topColorIntensity ))))\n : qMin( qreal( 1.0 ),\n qMax( qreal( 0.0 ), qreal( bottomColorIntensity \/ ( 2.0 * ( 1.0 - topColorIntensity )))));\n}\n\n\n\/\/ Inverter blendings\n\nqreal AdditiveSubtractiveBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n Q_UNUSED(bottomColorIntensity);\n Q_UNUSED(topColorIntensity);\n \/\/ FIXME:\n \/\/ return qMin( 1.0, qMax( 0.0, abs( bottomColorIntensity * bottomColorIntensity\n \/\/ - topColorIntensity * topColorIntensity )));\n return 0.0;\n}\n\nqreal BleachBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n \/\/ FIXME: \"why this is the same formula as Screen Blending? Please correct.)\"\n return 1.0 - ( 1.0 - bottomColorIntensity ) * ( 1.0 - topColorIntensity );\n}\n\nqreal DifferenceBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return qMax( qMin( qreal( 1.0 ), qreal( bottomColorIntensity - topColorIntensity + 0.5 )),\n qreal( 0.0 ));\n}\n\nqreal EquivalenceBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return 1.0 - abs( bottomColorIntensity - topColorIntensity );\n}\n\nqreal HalfDifferenceBlending::blendChannel( qreal const bottomColorIntensity,\n qreal const topColorIntensity ) const\n{\n return bottomColorIntensity + topColorIntensity\n - 2.0 * ( bottomColorIntensity * topColorIntensity );\n}\n\n\n\/\/ Special purpose blendings\n\nvoid CloudsBlending::blend( QImage * const bottom, TextureTile const * const top ) const\n{\n QImage const * const topImage = top->image();\n Q_ASSERT( topImage );\n Q_ASSERT( bottom->size() == topImage->size() );\n int const width = bottom->width();\n int const height = bottom->height();\n for ( int y = 0; y < height; ++y ) {\n for ( int x = 0; x < width; ++x ) {\n qreal const c = qRed( topImage->pixel( x, y )) \/ 255.0;\n QRgb const bottomPixel = bottom->pixel( x, y );\n int const bottomRed = qRed( bottomPixel );\n int const bottomGreen = qGreen( bottomPixel );\n int const bottomBlue = qBlue( bottomPixel );\n bottom->setPixel( x, y, qRgb(( int )( bottomRed + ( 255 - bottomRed ) * c ),\n ( int )( bottomGreen + ( 255 - bottomGreen ) * c ),\n ( int )( bottomBlue + ( 255 - bottomBlue ) * c )));\n }\n }\n}\n\n\n}\n<|endoftext|>"} {"text":"\/*\n RecognitionKernel.cpp\n\n Copyright (c) 2011 AIST All Rights Reserved.\n Eclipse Public License v1.0 (http:\/\/www.eclipse.org\/legal\/epl-v10.html)\n\n $Date:: $\n*\/\n#include \n\n#include \n#include \"recogImage.h\"\n#include \"stereo.h\"\n#include \"circle.h\"\n#include \"vertex.h\"\n#include \"extractEdge.h\"\n#include \"extractFeature_old.h\"\n#include \"extractFeature.hpp\"\n#include \"visionErrorCode.h\"\n\n#include \n\nstatic unsigned long\nGetTickCount()\n{\n struct timeval t;\n double msec;\n gettimeofday(&t, NULL);\n msec = (double) (t.tv_sec * 1.0E3 + t.tv_usec * 1.0E-3);\n return (unsigned long) msec;\n}\n\nstatic void\nfreeEdgeMemory(uchar* edgL, uchar* edgR, uchar* edgV)\n{\n free(edgL);\n free(edgR);\n free(edgV);\n}\n\nstatic void\nfreeFeatures2D(Features2D_old* L, Features2D_old* R, Features2D_old* V)\n{\n destructFeatures(L);\n destructFeatures(R);\n destructFeatures(V);\n}\n\n\/\/\n\/\/! 三次元物体認識の実行\n\/\/\n\/\/! 画像データから 三次元特徴を抽出し、モデルとマッチングを行い、\n\/\/! 結果を返す。\n\/\/\n\/\/! 引数:\n\/\/! RecogImage** image : カメラ画像\n\/\/! CalibParam& calib : カメラキャリブレーションデータ\n\/\/! Features3D& model : 対象物体モデル\n\/\/! Parameters& param : 認識パラメータ\n\/\/\nMatch3Dresults\nRecognitionKernel(RecogImage** image,\n CalibParam& calib,\n Features3D& model,\n Parameters& param)\n{\n Match3Dresults Match = {0};\n int imageNum = calib.numOfCameras;\n int colsize = image[0]->colsize;\n int rowsize = image[0]->rowsize;\n\n param.colsize = colsize;\n param.rowsize = rowsize;\n param.imgsize = colsize * rowsize;\n\n \/\/ 画像の歪みを補正する\n undistortImage(image[0], &calib.CameraL, image[0], &calib.CameraL);\n undistortImage(image[1], &calib.CameraR, image[1], &calib.CameraR);\n if (imageNum > 2)\n {\n undistortImage(image[2], &calib.CameraV, image[2], &calib.CameraV);\n }\n\n unsigned char* edgeL = (unsigned char*) calloc(colsize * rowsize, sizeof(unsigned char));\n unsigned char* edgeR = (unsigned char*) calloc(colsize * rowsize, sizeof(unsigned char));\n if (edgeL == NULL || edgeR == NULL)\n {\n freeEdgeMemory(edgeL, edgeR, NULL);\n Match.error = VISION_MALLOC_ERROR;\n return Match;\n }\n\n unsigned char* edgeV = NULL;\n if (imageNum > 2)\n {\n edgeV = (unsigned char*) calloc(colsize * rowsize, sizeof(unsigned char));\n if (edgeV == NULL)\n {\n freeEdgeMemory(edgeL, edgeR, NULL);\n Match.error = VISION_MALLOC_ERROR;\n return Match;\n }\n }\n\n model.calib = &calib;\n model.edge[0] = edgeL;\n model.edge[1] = edgeR;\n if (imageNum > 2)\n {\n model.edge[2] = edgeV;\n }\n\n \/\/ 処理時間計測\n unsigned long stime, etime, dtime1, dtime2, dtime3;\n\n stime = GetTickCount();\n\n Features2D_old* features0 = NULL;\n Features2D_old* features1 = NULL;\n Features2D_old* features2 = NULL;\n\n ovgr::Features2D f0, f1, f2;\n ovgr::CorrespondingPair cp_bi, cp_LR, cp_RV, cp_VL;\n std::vector cps(1);\n ovgr::CorrespondingSet cs;\n ovgr::CorrespondenceThresholds cpThs;\n\n const uchar* edges[3] = {0};\n const CameraParam* camParam[3] = {0};\n std::vector features(2);\n\n StereoPairing pairing = param.pairing;\n\n \/\/ 画像が 2 枚の時は、強制的に DBL_LR にする。\n if (imageNum == 2)\n {\n pairing = DBL_LR;\n }\n\n \/\/ 特徴データ識別 ID 番号\n param.feature2D.id = 0;\n\n \/\/ 二次元特徴の抽出\n switch (pairing)\n {\n case DBL_LR:\n features0 = ImageToFeature2D_old(image[0]->pixel, edgeL, param, model);\n f0 = ovgr::create_new_features_from_old_one(features0, image[0]->pixel, ¶m);\n param.feature2D.id = 1;\n features1 = ImageToFeature2D_old(image[1]->pixel, edgeR, param, model);\n f1 = ovgr::create_new_features_from_old_one(features1, image[1]->pixel, ¶m);\n camParam[0] = &calib.CameraL;\n camParam[1] = &calib.CameraR;\n edges[0] = edgeL;\n edges[1] = edgeR;\n break;\n\n case DBL_LV:\n features0 = ImageToFeature2D_old(image[2]->pixel, edgeV, param, model);\n f0 = ovgr::create_new_features_from_old_one(features0, image[2]->pixel, ¶m);\n param.feature2D.id = 1;\n features1 = ImageToFeature2D_old(image[0]->pixel, edgeL, param, model);\n f1 = ovgr::create_new_features_from_old_one(features1, image[0]->pixel, ¶m);\n camParam[0] = &calib.CameraV;\n camParam[1] = &calib.CameraL;\n edges[0] = edgeV;\n edges[1] = edgeL;\n break;\n\n case DBL_RV:\n features0 = ImageToFeature2D_old(image[1]->pixel, edgeR, param, model);\n f0 = ovgr::create_new_features_from_old_one(features0, image[1]->pixel, ¶m);\n param.feature2D.id = 1;\n features1 = ImageToFeature2D_old(image[2]->pixel, edgeV, param, model);\n f1 = ovgr::create_new_features_from_old_one(features1, image[2]->pixel, ¶m);\n camParam[0] = &calib.CameraR;\n camParam[1] = &calib.CameraV;\n edges[0] = edgeR;\n edges[1] = edgeV;\n break;\n\n case TBL_OR:\n case TBL_AND:\n features0 = ImageToFeature2D_old(image[0]->pixel, edgeL, param, model);\n f0 = ovgr::create_new_features_from_old_one(features0, image[0]->pixel, ¶m);\n param.feature2D.id = 1;\n features1 = ImageToFeature2D_old(image[1]->pixel, edgeR, param, model);\n f1 = ovgr::create_new_features_from_old_one(features1, image[1]->pixel, ¶m);\n param.feature2D.id = 2;\n features2 = ImageToFeature2D_old(image[2]->pixel, edgeV, param, model);\n f2 = ovgr::create_new_features_from_old_one(features2, image[2]->pixel, ¶m);\n camParam[0] = &calib.CameraL; \n camParam[1] = &calib.CameraR;\n camParam[2] = &calib.CameraV;\n edges[0] = edgeL;\n edges[1] = edgeR;\n edges[2] = edgeV;\n break;\n\n default:\n freeEdgeMemory(edgeL, edgeR, edgeV);\n Match.error = VISION_PARAM_ERROR;\n return Match;\n }\n\n#ifdef RECOGNITION_TEST\n printf( \"RecognitionKernel:RECOGNITION_TEST:StereoPair=%d\\n\", pairing);\n fflush(stdout);\n#endif\n\n \/\/ 2D 処理時間計測\n etime = GetTickCount();\n dtime1 = etime - stime;\n stime = etime;\n\n if (features0 == NULL || features1 == NULL)\n {\n freeFeatures2D(features0, features1, features2);\n freeEdgeMemory(edgeL, edgeR, edgeV);\n Match.error = VISION_MALLOC_ERROR;\n return Match;\n }\n else if (pairing == TBL_OR || pairing == TBL_AND)\n {\n if (features2 == NULL)\n {\n freeFeatures2D(features0, features1, features2);\n freeEdgeMemory(edgeL, edgeR, edgeV);\n Match.error = VISION_MALLOC_ERROR;\n return Match;\n }\n }\n\n \/\/ 各ペアで、二次元特徴のすべての組み合わせでステレオ対応を試みる。\n\n if (pairing != TBL_OR && pairing != TBL_AND)\n {\n cp_bi = make_corresponding_pairs(f0, *camParam[0], f1, *camParam[1], cpThs);\n cps[0] = &cp_bi;\n features[0] = &f0;\n features[1] = &f1;\n }\n else\n {\n cp_LR = make_corresponding_pairs(f0, calib.CameraL, f1, calib.CameraR, cpThs);\n cp_RV = make_corresponding_pairs(f1, calib.CameraR, f2, calib.CameraV, cpThs);\n cp_VL = make_corresponding_pairs(f2, calib.CameraV, f0, calib.CameraL, cpThs);\n cps.resize(3);\n cps[0] = &cp_LR;\n cps[1] = &cp_RV;\n cps[2] = &cp_VL;\n features.resize(3);\n features[0] = &f0;\n features[1] = &f1;\n features[2] = &f2;\n }\n\n if (pairing != TBL_AND)\n {\n \/\/ 2眼と3眼OR\n cs = ovgr::filter_corresponding_set(cps, ovgr::CorresOr);\n }\n else\n {\n \/\/ 3眼AND\n cs = ovgr::filter_corresponding_set(cps, ovgr::CorresAnd);\n }\n\n printf(\"# vertex: %d, ellipse: %d\\n\", cs.vertex.size(), cs.ellipse.size());\n\n Features3D scene = { 0 };\n\n \/\/ 二次元頂点のステレオデータから三次元頂点情報の復元\n if (model.numOfVertices > 0 && !(param.feature2D.no_search_features & NO_SEARCH_VERTEX))\n {\n reconstruct_hyperbola_to_vertex3D(features, cs, camParam, edges, &scene, param);\n }\n\n \/\/ 二次元楕円のステレオデータから三次元真円情報の復元\n if (model.numOfCircles > 0 && !(param.feature2D.no_search_features & NO_SEARCH_ELLIPSE))\n {\n reconstruct_ellipse2D_to_circle3D(features, cs, camParam, edges, &scene, param);\n }\n\n \/\/ 3D 処理時間計測\n etime = GetTickCount();\n dtime2 = etime - stime;\n\n \/\/ 二次元特徴メモリ解放\n freeFeatures2D(features0, features1, features2);\n\n \/\/ 三次元特徴とモデルデータのマッチングを行う。\n stime = GetTickCount();\n\n \/\/ シーンとモデルデータを照合して認識を実行する。\n Match = matchFeatures3D(scene, model, param);\n\n etime = GetTickCount();\n dtime3 = etime - stime;\n\n \/\/ 認識時間計測\n printf(\"認識時間: %lu msec. (2D: %lu + 3D: %lu + 認識: %lu)\\n\",\n\t dtime1 + dtime2 + dtime3, dtime1, dtime2, dtime3);\n fflush(stdout);\n\n freeEdgeMemory(edgeL, edgeR, edgeV);\n freeFeatures3D(&scene);\n\n return Match;\n}\nadded OpenMP directives.\/*\n RecognitionKernel.cpp\n\n Copyright (c) 2011 AIST All Rights Reserved.\n Eclipse Public License v1.0 (http:\/\/www.eclipse.org\/legal\/epl-v10.html)\n\n $Date:: $\n*\/\n#include \n\n#include \n#include \"recogImage.h\"\n#include \"stereo.h\"\n#include \"circle.h\"\n#include \"vertex.h\"\n#include \"extractEdge.h\"\n#include \"extractFeature_old.h\"\n#include \"extractFeature.hpp\"\n#include \"visionErrorCode.h\"\n\n#include \n\nstatic unsigned long\nGetTickCount()\n{\n struct timeval t;\n double msec;\n gettimeofday(&t, NULL);\n msec = (double) (t.tv_sec * 1.0E3 + t.tv_usec * 1.0E-3);\n return (unsigned long) msec;\n}\n\nstatic void\nfreeEdgeMemory(uchar* edgL, uchar* edgR, uchar* edgV)\n{\n free(edgL);\n free(edgR);\n free(edgV);\n}\n\nstatic void\nfreeFeatures2D(Features2D_old* L, Features2D_old* R, Features2D_old* V)\n{\n destructFeatures(L);\n destructFeatures(R);\n destructFeatures(V);\n}\n\n\/\/\n\/\/! 三次元物体認識の実行\n\/\/\n\/\/! 画像データから 三次元特徴を抽出し、モデルとマッチングを行い、\n\/\/! 結果を返す。\n\/\/\n\/\/! 引数:\n\/\/! RecogImage** image : カメラ画像\n\/\/! CalibParam& calib : カメラキャリブレーションデータ\n\/\/! Features3D& model : 対象物体モデル\n\/\/! Parameters& param : 認識パラメータ\n\/\/\nMatch3Dresults\nRecognitionKernel(RecogImage** image,\n CalibParam& calib,\n Features3D& model,\n Parameters& param)\n{\n Match3Dresults Match = {0};\n int imageNum = calib.numOfCameras;\n int colsize = image[0]->colsize;\n int rowsize = image[0]->rowsize;\n\n param.colsize = colsize;\n param.rowsize = rowsize;\n param.imgsize = colsize * rowsize;\n\n \/\/ 画像の歪みを補正する\n undistortImage(image[0], &calib.CameraL, image[0], &calib.CameraL);\n undistortImage(image[1], &calib.CameraR, image[1], &calib.CameraR);\n if (imageNum > 2)\n {\n undistortImage(image[2], &calib.CameraV, image[2], &calib.CameraV);\n }\n\n unsigned char* edgeL = (unsigned char*) calloc(colsize * rowsize, sizeof(unsigned char));\n unsigned char* edgeR = (unsigned char*) calloc(colsize * rowsize, sizeof(unsigned char));\n if (edgeL == NULL || edgeR == NULL)\n {\n freeEdgeMemory(edgeL, edgeR, NULL);\n Match.error = VISION_MALLOC_ERROR;\n return Match;\n }\n\n unsigned char* edgeV = NULL;\n if (imageNum > 2)\n {\n edgeV = (unsigned char*) calloc(colsize * rowsize, sizeof(unsigned char));\n if (edgeV == NULL)\n {\n freeEdgeMemory(edgeL, edgeR, NULL);\n Match.error = VISION_MALLOC_ERROR;\n return Match;\n }\n }\n\n model.calib = &calib;\n model.edge[0] = edgeL;\n model.edge[1] = edgeR;\n if (imageNum > 2)\n {\n model.edge[2] = edgeV;\n }\n\n \/\/ 処理時間計測\n unsigned long stime, etime, dtime1, dtime2, dtime3;\n\n stime = GetTickCount();\n\n Features2D_old* features0 = NULL;\n Features2D_old* features1 = NULL;\n Features2D_old* features2 = NULL;\n\n ovgr::Features2D f0, f1, f2;\n ovgr::CorrespondingPair cp_bi, cp_LR, cp_RV, cp_VL;\n std::vector cps(1);\n ovgr::CorrespondingSet cs;\n ovgr::CorrespondenceThresholds cpThs;\n\n const uchar* edges[3] = {0};\n const CameraParam* camParam[3] = {0};\n std::vector features(2);\n\n StereoPairing pairing = param.pairing;\n\n \/\/ 画像が 2 枚の時は、強制的に DBL_LR にする。\n if (imageNum == 2)\n {\n pairing = DBL_LR;\n }\n\n \/\/ 特徴データ識別 ID 番号\n param.feature2D.id = 0;\n\n \/\/ 二次元特徴の抽出\n#ifdef _OPENMP\n#pragma omp parallel\n#endif\n switch (pairing)\n {\n case DBL_LR:\n#ifdef _OPENMP\n#pragma omp sections\n#endif\n {\n#ifdef _OPENMP\n#pragma omp section\n#endif\n {\n features0 = ImageToFeature2D_old(image[0]->pixel, edgeL, param, model);\n f0 = ovgr::create_new_features_from_old_one(features0, image[0]->pixel, ¶m);\n }\n#ifdef _OPENMP\n#pragma omp section\n#endif\n {\n features1 = ImageToFeature2D_old(image[1]->pixel, edgeR, param, model);\n f1 = ovgr::create_new_features_from_old_one(features1, image[1]->pixel, ¶m);\n }\n }\n param.feature2D.id = 1;\n camParam[0] = &calib.CameraL;\n camParam[1] = &calib.CameraR;\n edges[0] = edgeL;\n edges[1] = edgeR;\n break;\n\n case DBL_LV:\n#ifdef _OPENMP\n#pragma omp sections\n#endif\n {\n#ifdef _OPENMP\n#pragma omp section\n#endif\n {\n features0 = ImageToFeature2D_old(image[2]->pixel, edgeV, param, model);\n f0 = ovgr::create_new_features_from_old_one(features0, image[2]->pixel, ¶m);\n }\n#ifdef _OPENMP\n#pragma omp section\n#endif\n {\n features1 = ImageToFeature2D_old(image[0]->pixel, edgeL, param, model);\n f1 = ovgr::create_new_features_from_old_one(features1, image[0]->pixel, ¶m);\n }\n }\n param.feature2D.id = 1;\n camParam[0] = &calib.CameraV;\n camParam[1] = &calib.CameraL;\n edges[0] = edgeV;\n edges[1] = edgeL;\n break;\n\n case DBL_RV:\n#ifdef _OPENMP\n#pragma omp sections\n#endif\n {\n#ifdef _OPENMP\n#pragma omp section\n#endif\n {\n features0 = ImageToFeature2D_old(image[1]->pixel, edgeR, param, model);\n f0 = ovgr::create_new_features_from_old_one(features0, image[1]->pixel, ¶m);\n }\n#ifdef _OPENMP\n#pragma omp section\n#endif\n {\n features1 = ImageToFeature2D_old(image[2]->pixel, edgeV, param, model);\n f1 = ovgr::create_new_features_from_old_one(features1, image[2]->pixel, ¶m);\n }\n }\n param.feature2D.id = 1;\n camParam[0] = &calib.CameraR;\n camParam[1] = &calib.CameraV;\n edges[0] = edgeR;\n edges[1] = edgeV;\n break;\n\n case TBL_OR:\n case TBL_AND:\n#ifdef _OPENMP\n#pragma omp sections\n#endif\n {\n#ifdef _OPENMP\n#pragma omp section\n#endif\n {\n features0 = ImageToFeature2D_old(image[0]->pixel, edgeL, param, model);\n f0 = ovgr::create_new_features_from_old_one(features0, image[0]->pixel, ¶m);\n }\n#ifdef _OPENMP\n#pragma omp section\n#endif\n {\n features1 = ImageToFeature2D_old(image[1]->pixel, edgeR, param, model);\n f1 = ovgr::create_new_features_from_old_one(features1, image[1]->pixel, ¶m);\n }\n#ifdef _OPENMP\n#pragma omp section\n#endif\n {\n features2 = ImageToFeature2D_old(image[2]->pixel, edgeV, param, model);\n f2 = ovgr::create_new_features_from_old_one(features2, image[2]->pixel, ¶m);\n }\n }\n \/\/param.feature2D.id = 1;\n param.feature2D.id = 2;\n camParam[0] = &calib.CameraL; \n camParam[1] = &calib.CameraR;\n camParam[2] = &calib.CameraV;\n edges[0] = edgeL;\n edges[1] = edgeR;\n edges[2] = edgeV;\n break;\n\n default:\n freeEdgeMemory(edgeL, edgeR, edgeV);\n Match.error = VISION_PARAM_ERROR;\n }\n\n if (Match.error == VISION_PARAM_ERROR)\n {\n return Match;\n }\n\n#ifdef RECOGNITION_TEST\n printf( \"RecognitionKernel:RECOGNITION_TEST:StereoPair=%d\\n\", pairing);\n fflush(stdout);\n#endif\n\n \/\/ 2D 処理時間計測\n etime = GetTickCount();\n dtime1 = etime - stime;\n stime = etime;\n\n if (features0 == NULL || features1 == NULL)\n {\n freeFeatures2D(features0, features1, features2);\n freeEdgeMemory(edgeL, edgeR, edgeV);\n Match.error = VISION_MALLOC_ERROR;\n return Match;\n }\n else if (pairing == TBL_OR || pairing == TBL_AND)\n {\n if (features2 == NULL)\n {\n freeFeatures2D(features0, features1, features2);\n freeEdgeMemory(edgeL, edgeR, edgeV);\n Match.error = VISION_MALLOC_ERROR;\n return Match;\n }\n }\n\n \/\/ 各ペアで、二次元特徴のすべての組み合わせでステレオ対応を試みる。\n\n if (pairing != TBL_OR && pairing != TBL_AND)\n {\n cp_bi = make_corresponding_pairs(f0, *camParam[0], f1, *camParam[1], cpThs);\n cps[0] = &cp_bi;\n features[0] = &f0;\n features[1] = &f1;\n }\n else\n {\n cp_LR = make_corresponding_pairs(f0, calib.CameraL, f1, calib.CameraR, cpThs);\n cp_RV = make_corresponding_pairs(f1, calib.CameraR, f2, calib.CameraV, cpThs);\n cp_VL = make_corresponding_pairs(f2, calib.CameraV, f0, calib.CameraL, cpThs);\n cps.resize(3);\n cps[0] = &cp_LR;\n cps[1] = &cp_RV;\n cps[2] = &cp_VL;\n features.resize(3);\n features[0] = &f0;\n features[1] = &f1;\n features[2] = &f2;\n }\n\n if (pairing != TBL_AND)\n {\n \/\/ 2眼と3眼OR\n cs = ovgr::filter_corresponding_set(cps, ovgr::CorresOr);\n }\n else\n {\n \/\/ 3眼AND\n cs = ovgr::filter_corresponding_set(cps, ovgr::CorresAnd);\n }\n\n printf(\"# vertex: %d, ellipse: %d\\n\", cs.vertex.size(), cs.ellipse.size());\n\n Features3D scene = { 0 };\n\n \/\/ 二次元頂点のステレオデータから三次元頂点情報の復元\n if (model.numOfVertices > 0 && !(param.feature2D.no_search_features & NO_SEARCH_VERTEX))\n {\n reconstruct_hyperbola_to_vertex3D(features, cs, camParam, edges, &scene, param);\n }\n\n \/\/ 二次元楕円のステレオデータから三次元真円情報の復元\n if (model.numOfCircles > 0 && !(param.feature2D.no_search_features & NO_SEARCH_ELLIPSE))\n {\n reconstruct_ellipse2D_to_circle3D(features, cs, camParam, edges, &scene, param);\n }\n\n \/\/ 3D 処理時間計測\n etime = GetTickCount();\n dtime2 = etime - stime;\n\n \/\/ 二次元特徴メモリ解放\n freeFeatures2D(features0, features1, features2);\n\n \/\/ 三次元特徴とモデルデータのマッチングを行う。\n stime = GetTickCount();\n\n \/\/ シーンとモデルデータを照合して認識を実行する。\n Match = matchFeatures3D(scene, model, param);\n\n etime = GetTickCount();\n dtime3 = etime - stime;\n\n \/\/ 認識時間計測\n printf(\"認識時間: %lu msec. (2D: %lu + 3D: %lu + 認識: %lu)\\n\",\n\t dtime1 + dtime2 + dtime3, dtime1, dtime2, dtime3);\n fflush(stdout);\n\n freeEdgeMemory(edgeL, edgeR, edgeV);\n freeFeatures3D(&scene);\n\n return Match;\n}\n<|endoftext|>"} {"text":"\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2011 Alesis Novik\n * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society\n *\/\n#include \"lib\/config.h\"\n\n#ifdef HAVE_LAPACK\n\n#include \"distributions\/Gaussian.h\"\n#include \"lib\/Mathematics.h\"\n#include \"base\/Parameter.h\"\n\nusing namespace shogun;\n\nCGaussian::CGaussian() : CDistribution(), m_constant(0),\nm_cov(NULL), m_cov_rows(0), m_cov_cols(0), m_cov_inverse(NULL),\nm_cov_inverse_rows(0), m_cov_inverse_cols(0), m_mean(NULL),\nm_mean_length(0)\n{\n}\n\nCGaussian::CGaussian(float64_t* mean, int32_t mean_length,\n\t\t\t\t\tfloat64_t* cov, int32_t cov_rows, int32_t cov_cols) : CDistribution(),\n\t\t\t\t\tm_cov_inverse(NULL)\n{\n\tASSERT(mean_length == cov_rows);\n\tASSERT(cov_rows == cov_cols);\n\tm_mean = new float64_t[mean_length];\n\tmemcpy(m_mean, mean, sizeof(float64_t)*mean_length);\n\tm_cov = new float64_t[cov_rows*cov_cols];\n\tmemcpy(m_cov, cov, sizeof(float64_t)*cov_rows*cov_cols);\n\tm_mean_length = mean_length;\n\tm_cov_rows = cov_rows;\n\tm_cov_cols = cov_cols;\n\tinit();\n\tregister_params();\n}\n\nvoid CGaussian::init()\n{\n\tdelete[] m_cov_inverse;\n\n\tm_cov_inverse_rows = m_cov_cols;\n\tm_cov_inverse_cols = m_cov_rows;\n\n\tm_cov_inverse = new float64_t[m_cov_rows*m_cov_cols];\n\tmemcpy(m_cov_inverse, m_cov, sizeof(float64_t)*m_cov_rows*m_cov_cols);\n\tint32_t result = clapack_dpotrf(CblasRowMajor, CblasLower, m_cov_rows, m_cov_inverse, m_cov_rows);\n\tm_constant = 1;\n\n\tfor (int i = 0; i < m_cov_rows; i++)\n\t\tm_constant *= m_cov_inverse[i*m_cov_rows+i];\n\tm_constant = 1\/m_constant;\n\tm_constant *= pow(2*M_PI, (float64_t) -m_cov_rows\/2);\n\n\tresult = clapack_dpotri(CblasRowMajor, CblasLower, m_cov_rows, m_cov_inverse, m_cov_rows);\n}\n\nCGaussian::~CGaussian()\n{\n\tdelete[] m_cov_inverse;\n\tdelete[] m_cov;\n\tdelete[] m_mean;\n}\n\nbool CGaussian::train(CFeatures* data)\n{\n\t\/\/ init features with data if necessary and assure type is correct\n\tif (data)\n\t{\n\t\tif (!data->has_property(FP_DOT))\n\t\t\t\tSG_ERROR(\"Specified features are not of type CDotFeatures\\n\");\t\t\n\t\tset_features(data);\n\t}\n\tCDotFeatures* dotdata = (CDotFeatures *) data;\n\n\tdelete[] m_mean;\n\tdelete[] m_cov;\n\n\tdotdata->get_mean(&m_mean, &m_mean_length);\n\tdotdata->get_cov(&m_cov, &m_cov_rows, &m_cov_cols);\n\n\tinit();\n\n\treturn true;\n}\n\nint32_t CGaussian::get_num_model_parameters()\n{\n\treturn m_cov_rows*m_cov_cols+m_mean_length;\n}\n\nfloat64_t CGaussian::get_log_model_parameter(int32_t num_param)\n{\n\tif (num_paramhas_property(FP_DOT));\n\tfloat64_t* point;\n\tint32_t point_len;\n\t((CDotFeatures *)features)->get_feature_vector(&point, &point_len, num_example);\n\tfloat64_t answer = compute_PDF(point, point_len);\n\tdelete[] point;\n\treturn answer;\n}\n\nfloat64_t CGaussian::compute_PDF(float64_t* point, int32_t point_len)\n{\n\tASSERT(m_mean && m_cov);\n\tASSERT(point_len == m_mean_length);\n\tfloat64_t* difference = new float64_t[m_mean_length];\n\tmemcpy(difference, point, sizeof(float64_t)*m_mean_length);\n\tfloat64_t* result = new float64_t[m_mean_length];\n\n\tfor (int i = 0; i < m_mean_length; i++)\n\t\tdifference[i] -= m_mean[i];\n\n\tcblas_dsymv(CblasRowMajor, CblasLower, m_mean_length, -1.0\/2.0, m_cov_inverse, m_mean_length,\n\t\t\t\tdifference, 1, 0, result, 1);\n\n\tfloat64_t answer = m_constant * exp(cblas_ddot(m_mean_length, difference, 1, result, 1));\n\n\tdelete[] difference;\n\tdelete[] result;\n\n\treturn answer;\n}\n\nvoid CGaussian::register_params()\n{\n\tm_parameters->add_matrix(&m_cov, &m_cov_rows, &m_cov_cols, \"m_cov\", \"Covariance.\");\n\tm_parameters->add_matrix(&m_cov_inverse, &m_cov_inverse_rows, &m_cov_inverse_cols, \"m_cov_inverse\", \"Covariance inverse.\");\n\tm_parameters->add_vector(&m_mean, &m_mean_length, \"m_mean\", \"Mean.\");\n\tm_parameters->add(&m_constant, \"m_constant\", \"Constant part.\");\n}\n#endif\nImproved readability of Gaussian.cpp\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2011 Alesis Novik\n * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society\n *\/\n#include \"lib\/config.h\"\n\n#ifdef HAVE_LAPACK\n\n#include \"distributions\/Gaussian.h\"\n#include \"lib\/Mathematics.h\"\n#include \"base\/Parameter.h\"\n\nusing namespace shogun;\n\nCGaussian::CGaussian() : CDistribution(), m_constant(0),\nm_cov(NULL), m_cov_rows(0), m_cov_cols(0), m_cov_inverse(NULL),\nm_cov_inverse_rows(0), m_cov_inverse_cols(0), m_mean(NULL),\nm_mean_length(0)\n{\n}\n\nCGaussian::CGaussian(float64_t* mean, int32_t mean_length,\n\t\t\t\t\tfloat64_t* cov, int32_t cov_rows, int32_t cov_cols) : CDistribution(),\n\t\t\t\t\tm_cov_inverse(NULL)\n{\n\tASSERT(mean_length == cov_rows);\n\tASSERT(cov_rows == cov_cols);\n\tm_mean = new float64_t[mean_length];\n\tmemcpy(m_mean, mean, sizeof(float64_t)*mean_length);\n\tm_cov = new float64_t[cov_rows*cov_cols];\n\tmemcpy(m_cov, cov, sizeof(float64_t)*cov_rows*cov_cols);\n\tm_mean_length = mean_length;\n\tm_cov_rows = cov_rows;\n\tm_cov_cols = cov_cols;\n\tinit();\n\tregister_params();\n}\n\nvoid CGaussian::init()\n{\n\tdelete[] m_cov_inverse;\n\n\tm_cov_inverse_rows = m_cov_cols;\n\tm_cov_inverse_cols = m_cov_rows;\n\n\tm_cov_inverse = new float64_t[m_cov_rows*m_cov_cols];\n\tmemcpy(m_cov_inverse, m_cov, sizeof(float64_t)*m_cov_rows*m_cov_cols);\n\tint32_t result = clapack_dpotrf(CblasRowMajor, CblasLower, m_cov_rows, m_cov_inverse, m_cov_rows);\n\tm_constant = 1;\n\n\tfor (int i = 0; i < m_cov_rows; i++)\n\t\tm_constant *= m_cov_inverse[i*m_cov_rows+i];\n\n\tm_constant = 1\/m_constant;\n\tm_constant *= pow(2*M_PI, (float64_t) -m_cov_rows\/2);\n\n\tresult = clapack_dpotri(CblasRowMajor, CblasLower, m_cov_rows, m_cov_inverse, m_cov_rows);\n}\n\nCGaussian::~CGaussian()\n{\n\tdelete[] m_cov_inverse;\n\tdelete[] m_cov;\n\tdelete[] m_mean;\n}\n\nbool CGaussian::train(CFeatures* data)\n{\n\t\/\/ init features with data if necessary and assure type is correct\n\tif (data)\n\t{\n\t\tif (!data->has_property(FP_DOT))\n\t\t\t\tSG_ERROR(\"Specified features are not of type CDotFeatures\\n\");\t\t\n\t\tset_features(data);\n\t}\n\tCDotFeatures* dotdata = (CDotFeatures *) data;\n\n\tdelete[] m_mean;\n\tdelete[] m_cov;\n\n\tdotdata->get_mean(&m_mean, &m_mean_length);\n\tdotdata->get_cov(&m_cov, &m_cov_rows, &m_cov_cols);\n\n\tinit();\n\n\treturn true;\n}\n\nint32_t CGaussian::get_num_model_parameters()\n{\n\treturn m_cov_rows*m_cov_cols+m_mean_length;\n}\n\nfloat64_t CGaussian::get_log_model_parameter(int32_t num_param)\n{\n\tif (num_paramhas_property(FP_DOT));\n\tfloat64_t* point;\n\tint32_t point_len;\n\t((CDotFeatures *)features)->get_feature_vector(&point, &point_len, num_example);\n\tfloat64_t answer = compute_PDF(point, point_len);\n\tdelete[] point;\n\treturn answer;\n}\n\nfloat64_t CGaussian::compute_PDF(float64_t* point, int32_t point_len)\n{\n\tASSERT(m_mean && m_cov);\n\tASSERT(point_len == m_mean_length);\n\tfloat64_t* difference = new float64_t[m_mean_length];\n\tmemcpy(difference, point, sizeof(float64_t)*m_mean_length);\n\tfloat64_t* result = new float64_t[m_mean_length];\n\n\tfor (int i = 0; i < m_mean_length; i++)\n\t\tdifference[i] -= m_mean[i];\n\n\tcblas_dsymv(CblasRowMajor, CblasLower, m_mean_length, -1.0\/2.0, m_cov_inverse, m_mean_length,\n\t\t\t\tdifference, 1, 0, result, 1);\n\n\tfloat64_t answer = m_constant * exp(cblas_ddot(m_mean_length, difference, 1, result, 1));\n\n\tdelete[] difference;\n\tdelete[] result;\n\n\treturn answer;\n}\n\nvoid CGaussian::register_params()\n{\n\tm_parameters->add_matrix(&m_cov, &m_cov_rows, &m_cov_cols, \"m_cov\", \"Covariance.\");\n\tm_parameters->add_matrix(&m_cov_inverse, &m_cov_inverse_rows, &m_cov_inverse_cols, \"m_cov_inverse\", \"Covariance inverse.\");\n\tm_parameters->add_vector(&m_mean, &m_mean_length, \"m_mean\", \"Mean.\");\n\tm_parameters->add(&m_constant, \"m_constant\", \"Constant part.\");\n}\n#endif\n<|endoftext|>"} {"text":"#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tethernet_base クラス @n\r\n\t\t\tCopyright 2017 Kunihito Hiramatsu\r\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"ethernet.hpp\"\r\n\r\nnamespace net {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief ethernet_base\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\tclass ethernet_base {\r\n\r\n\t\tethernet&\tethernet_;\r\n\r\n\t\tuint16_t\tport_;\r\n\t\tuint32_t\tcepid_;\r\n\r\n\t\tint16_t set_tcp_crep_(ID repid, UH portno) {\r\n\t\t\tif (repid == 0 || repid > __tcprepn) {\r\n\t\t\t\treturn -1;\r\n\t\t\t}\r\n\t\t\ttcp_crep[repid - 1].myaddr.portno = portno;\r\n\t\t\treturn 0;\r\n\t\t}\r\n\r\n\t\tint16_t set_tcp_ccep_(ID cepid, UB ch, int rbufsz) {\r\n\t\t\tif (cepid == 0 || cepid > __tcpcepn){\r\n\t\t\t\treturn -1;\r\n\t\t\t}\r\n\t\t\ttcp_ccep[cepid - 1].cepatr = ch;\r\n\t\t\ttcp_ccep[cepid - 1].rbufsz = rbufsz;\r\n\t\t\treturn 0;\r\n\t\t}\r\n\r\n\tpublic:\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief コンストラクター\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tethernet_base(ethernet& e) : ethernet_(e), port_(0), cepid_(0) { }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief ethernet を参照\r\n\t\t\t@return ethernet\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tethernet& at_ethernet() { return ethernet_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief ポート番号を取得\r\n\t\t\t@return ポート番号\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tuint16_t get_port() const { return port_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief CEP ID を取得\r\n\t\t\t@return CEP ID\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tuint32_t get_cepid() const { return cepid_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 開始\r\n\t\t\t@param[in]\tport\tポート番号\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid begin(uint16_t port)\r\n\t\t{\r\n\t\t\tport_ = port;\r\n\r\n#ifdef ETHER_DEBUG\r\n\t\t\tutils::format(\"ethernet_server: begin: %d\") % static_cast(port);\r\n#endif\r\n\t\t\tif(port_ > 0) {\r\n\t\t\t\tcepid_ = ethernet_.new_connection();\r\n\t\t\t\tif(cepid_ == 0) {\r\n\t\t\t\t\tutils::format(\"New connection fail\\n\");\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t\/* initialize cep status *\/\r\n\t\t\t\tethernet_.at_cep(cepid_).status = T4_CLOSED;\r\n\t\t\t\t\/* Initialize TCP reception point *\/\r\n#ifdef ETHER_DEBUG\r\n\t\t\t\tutils::format(\"set_tcp_crep_(): %d\") % cepid_;\r\n#endif\r\n\t\t\t\tif(set_tcp_crep_(cepid_, port_) != E_OK) {\r\n\t\t\t\t\tutils::format(\"set_tcp_crep() fail: %d\\n\") % cepid_;\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t\/* Initialize TCP communication end point *\/\r\n#ifdef ETHER_DEBUG\r\n\t\t\t\tutils::format(\"set_tcp_ccep(): %d\\n\") % cepid_;\r\n#endif\r\n\t\t\t\tif(set_tcp_ccep_(cepid_, 0, ethernet::TCP_MSS) != E_OK) {\r\n\t\t\t\t\tutils::format(\"set_tcp_ccep_() fail: %d\\n\") % cepid_;\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tutils::format(\"port == 0\\n\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 終了\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid end()\r\n\t\t{\r\n\t\t\tethernet_.end_connection(cepid_);\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 接続確認\r\n\t\t\t@return 接続中なら「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool connected()\r\n\t\t{\r\n\t\t\tint ercd = tcp_read_stat(cepid_);\r\n\t\t\tbool res;\r\n\t\t\tif(ercd == T4_TCPS_ESTABLISHED || ercd == T4_TCPS_CLOSE_WAIT) {\r\n\t\t\t\tres = true;\r\n\t\t\t} else {\r\n\t\t\t\tres = false;\r\n\t\t\t}\r\n\t\t\treturn res;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 書き込み\r\n\t\t\t@param[in]\tbyte\tデータ\r\n\t\t\t@return 書き込み成功なら「1」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tint32_t write(uint8_t data)\r\n\t\t{\r\n\t\t\tint32_t ercd = tcp_send_data(cepid_, &data, 1, TMO_FEVR);\r\n\t\t\treturn ercd;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 1バイト書き込み\r\n\t\t\t@return 書き込み成功なら「1」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tint32_t write(const void* buffer, uint32_t size)\r\n\t\t{\r\n\t\t\tint32_t ercd;\r\n\t\t\tuint32_t current_send_size = 0;\r\n\r\n\t\t\tconst uint8_t* p = static_cast(buffer);\r\n\t\t\tif (size <= 0x7fff) {\r\n\t\t\t\tercd = tcp_send_data(cepid_, p, size, TMO_FEVR);\r\n\t\t\t} else {\r\n\t\t\t\twhile (size > current_send_size) {\r\n\t\t\t\t\tif((size - current_send_size) > 0x7fff) {\r\n\t\t\t\t\t\tercd = tcp_send_data(cepid_, (p + current_send_size), 0x7fff, TMO_FEVR);\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tercd = tcp_send_data(cepid_, (p + current_send_size),\r\n\t\t\t\t\t\t\t\t\t(size - current_send_size), TMO_FEVR);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif(ercd < 0) {\r\n\t\t\t\t\t\tbreak; \/\/ error\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcurrent_send_size += static_cast(ercd);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn current_send_size;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 1バイト読み込み\r\n\t\t\t@return 読み込みデータ\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tint read()\r\n\t\t{\r\n#if defined(ETHER_DEBUG)\r\n\t\t\tutils::format(\"EthernetClinet::read()\");\r\n\t\t\tutils::format(\"%u : \") % static_cast(millis());\r\n#endif\r\n\t\t\tethernet::CEP& cep = ethernet_.at_cep(cepid_);\r\n\t\t\tint32_t ercd = tcp_recv_data(cepid_, cep.recv_buf, 1, TMO_FEVR);\r\n#if defined(ETHER_DEBUG)\r\n\t\t\tutils::format(\"%u\\n\") % static_cast(millis());\r\n#endif\r\n\t\t\tint recv_data;\r\n\t\t\tif(ercd <= 0) {\r\n\t\t\t\trecv_data = -1;\r\n\t\t\t} else {\r\n\t\t\t\trecv_data = static_cast(cep.recv_buf[0]);\r\n\t\t\t}\r\n\t\t\treturn recv_data;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 読み込み\r\n\t\t\t@param[out]\tbuf\t\t読み込み先\r\n\t\t\t@param[in]\tsize\t読み込みサイズ\r\n\t\t\t@return 読み込みサイズ\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tint read(void* buf, size_t size)\r\n\t\t{\r\n\t\t\tint32_t ercd = tcp_recv_data(cepid_, buf, size, TMO_FEVR);\r\n\t\t\tif(ercd <= 0) {\r\n\t\t\t\tercd = -1;\r\n\t\t\t}\r\n\t\t\treturn ercd;\r\n\t\t}\r\n\r\n\r\n\t\tint print(const char* t) {\r\n\t\t\tif(t == nullptr) return 0;\r\n\t\t\tsize_t l = strlen(t);\r\n\t\t\treturn write(t, l);\r\n\t\t}\r\n\r\n\r\n\t\tint print(int value) {\r\n\t\t\tchar tmp[16];\r\n\t\t\tutils::format(\"%d\", tmp, sizeof(tmp)) % value;\r\n\t\t\treturn print(tmp);\r\n\t\t}\r\n\r\n\r\n\t\t\/* get the length of the string * s return. '\\ 0' is not included in length. *\/\r\n\t\tint println(const char* t = nullptr)\r\n\t\t{\r\n\t\t\tif(t == nullptr) {\r\n\t\t\t\treturn write(\"\\r\\n\", 2);\r\n\t\t\t}\r\n\r\n\t\t\tsize_t l = strlen(t);\r\n\t\t\tchar tmp[l + 2];\r\n\t\t\tstrcpy(tmp, t);\r\n\t\t\ttmp[l + 0] = '\\r';\r\n\t\t\ttmp[l + 1] = '\\n';\r\n\t\t\treturn write(tmp, l + 2);\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 有効なデータがあるか\r\n\t\t\t@return 有効なデータ数\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tint available()\r\n\t\t{\r\n\t\t\tint res = 0;\r\n\t\t\tif(connected()) {\r\n\t\t\t\tres = head_tcb[cepid_ - 1].rdsize;\r\n\t\t\t\tint ercd = tcp_read_stat(cepid_);\r\n\r\n\t\t\t\tif(res == 0 && ercd == T4_TCPS_CLOSE_WAIT) {\r\n\t\t\t\t\ttcp_sht_cep(cepid_, TMO_FEVR);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn res;\r\n\t\t}\r\n\t};\r\n}\r\ncleanup timeout handling#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tethernet_base クラス @n\r\n\t\t\tCopyright 2017 Kunihito Hiramatsu\r\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"ethernet.hpp\"\r\n\r\nnamespace net {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief ethernet_base\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\tclass ethernet_base {\r\n\r\n\t\tethernet&\tethernet_;\r\n\r\n\t\tuint16_t\tport_;\r\n\t\tuint32_t\tcepid_;\r\n\r\n\t\tint16_t set_tcp_crep_(ID repid, UH portno) {\r\n\t\t\tif (repid == 0 || repid > __tcprepn) {\r\n\t\t\t\treturn -1;\r\n\t\t\t}\r\n\t\t\ttcp_crep[repid - 1].myaddr.portno = portno;\r\n\t\t\treturn 0;\r\n\t\t}\r\n\r\n\t\tint16_t set_tcp_ccep_(ID cepid, UB ch, int rbufsz) {\r\n\t\t\tif (cepid == 0 || cepid > __tcpcepn){\r\n\t\t\t\treturn -1;\r\n\t\t\t}\r\n\t\t\ttcp_ccep[cepid - 1].cepatr = ch;\r\n\t\t\ttcp_ccep[cepid - 1].rbufsz = rbufsz;\r\n\t\t\treturn 0;\r\n\t\t}\r\n\r\n\tpublic:\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief コンストラクター\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tethernet_base(ethernet& e) : ethernet_(e), port_(0), cepid_(0) { }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief ethernet を参照\r\n\t\t\t@return ethernet\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tethernet& at_ethernet() { return ethernet_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief ポート番号を取得\r\n\t\t\t@return ポート番号\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tuint16_t get_port() const { return port_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief CEP ID を取得\r\n\t\t\t@return CEP ID\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tuint32_t get_cepid() const { return cepid_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 開始\r\n\t\t\t@param[in]\tport\tポート番号\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid begin(uint16_t port)\r\n\t\t{\r\n\t\t\tport_ = port;\r\n\r\n#ifdef ETHER_DEBUG\r\n\t\t\tutils::format(\"ethernet_server: begin: %d\") % static_cast(port);\r\n#endif\r\n\t\t\tif(port_ > 0) {\r\n\t\t\t\tcepid_ = ethernet_.new_connection();\r\n\t\t\t\tif(cepid_ == 0) {\r\n\t\t\t\t\tutils::format(\"New connection fail\\n\");\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t\/* initialize cep status *\/\r\n\t\t\t\tethernet_.at_cep(cepid_).status = T4_CLOSED;\r\n\t\t\t\t\/* Initialize TCP reception point *\/\r\n#ifdef ETHER_DEBUG\r\n\t\t\t\tutils::format(\"set_tcp_crep_(): %d\") % cepid_;\r\n#endif\r\n\t\t\t\tif(set_tcp_crep_(cepid_, port_) != E_OK) {\r\n\t\t\t\t\tutils::format(\"set_tcp_crep() fail: %d\\n\") % cepid_;\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t\/* Initialize TCP communication end point *\/\r\n#ifdef ETHER_DEBUG\r\n\t\t\t\tutils::format(\"set_tcp_ccep(): %d\\n\") % cepid_;\r\n#endif\r\n\t\t\t\tif(set_tcp_ccep_(cepid_, 0, ethernet::TCP_MSS) != E_OK) {\r\n\t\t\t\t\tutils::format(\"set_tcp_ccep_() fail: %d\\n\") % cepid_;\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tutils::format(\"port == 0\\n\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 終了\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid end()\r\n\t\t{\r\n\t\t\tethernet_.end_connection(cepid_);\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 接続確認\r\n\t\t\t@return 接続中なら「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool connected()\r\n\t\t{\r\n\t\t\tbool ret = false;\r\n\t\t\tint ercd = tcp_read_stat(cepid_);\r\n\t\t\tif(ercd == T4_TCPS_ESTABLISHED || ercd == T4_TCPS_CLOSE_WAIT) {\r\n\t\t\t\tret = true;\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 書き込み\r\n\t\t\t@param[in]\tbyte\tデータ\r\n\t\t\t@return 書き込み成功なら「1」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tint32_t write(uint8_t data)\r\n\t\t{\r\n\t\t\tint32_t ercd = tcp_send_data(cepid_, &data, 1, TMO_FEVR);\r\n\t\t\treturn ercd;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 1バイト書き込み\r\n\t\t\t@return 書き込み成功なら「1」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tint32_t write(const void* buffer, uint32_t size)\r\n\t\t{\r\n\t\t\tint32_t ercd;\r\n\t\t\tuint32_t current_send_size = 0;\r\n\r\n\t\t\tconst uint8_t* p = static_cast(buffer);\r\n\t\t\tif (size <= 0x7fff) {\r\n\t\t\t\tercd = tcp_send_data(cepid_, p, size, TMO_FEVR);\r\n\t\t\t} else {\r\n\t\t\t\twhile (size > current_send_size) {\r\n\t\t\t\t\tif((size - current_send_size) > 0x7fff) {\r\n\t\t\t\t\t\tercd = tcp_send_data(cepid_, (p + current_send_size), 0x7fff, TMO_FEVR);\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tercd = tcp_send_data(cepid_, (p + current_send_size),\r\n\t\t\t\t\t\t\t\t\t(size - current_send_size), TMO_FEVR);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif(ercd < 0) {\r\n\t\t\t\t\t\tbreak; \/\/ error\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcurrent_send_size += static_cast(ercd);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn current_send_size;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 1バイト読み込み\r\n\t\t\t@return 読み込みデータ\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tint read()\r\n\t\t{\r\n#if defined(ETHER_DEBUG)\r\n\t\t\tutils::format(\"EthernetClinet::read()\");\r\n\t\t\tutils::format(\"%u : \") % static_cast(millis());\r\n#endif\r\n\t\t\tethernet::CEP& cep = ethernet_.at_cep(cepid_);\r\n\t\t\tint32_t ercd = tcp_recv_data(cepid_, cep.recv_buf, 1, TMO_FEVR);\r\n#if defined(ETHER_DEBUG)\r\n\t\t\tutils::format(\"%u\\n\") % static_cast(millis());\r\n#endif\r\n\t\t\tint recv_data;\r\n\t\t\tif(ercd <= 0) {\r\n\t\t\t\trecv_data = -1;\r\n\t\t\t} else {\r\n\t\t\t\trecv_data = static_cast(cep.recv_buf[0]);\r\n\t\t\t}\r\n\t\t\treturn recv_data;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 読み込み\r\n\t\t\t@param[out]\tbuf\t\t読み込み先\r\n\t\t\t@param[in]\tsize\t読み込みサイズ\r\n\t\t\t@return 読み込みサイズ\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tint read(void* buf, size_t size)\r\n\t\t{\r\n\t\t\tint32_t ercd = tcp_recv_data(cepid_, buf, size, TMO_FEVR);\r\n\t\t\tif(ercd <= 0) {\r\n\t\t\t\tercd = -1;\r\n\t\t\t}\r\n\t\t\treturn ercd;\r\n\t\t}\r\n\r\n\r\n\t\tint print(const char* t) {\r\n\t\t\tif(t == nullptr) return 0;\r\n\t\t\tsize_t l = strlen(t);\r\n\t\t\treturn write(t, l);\r\n\t\t}\r\n\r\n\r\n\t\tint print(int value) {\r\n\t\t\tchar tmp[16];\r\n\t\t\tutils::format(\"%d\", tmp, sizeof(tmp)) % value;\r\n\t\t\treturn print(tmp);\r\n\t\t}\r\n\r\n\r\n\t\t\/* get the length of the string * s return. '\\ 0' is not included in length. *\/\r\n\t\tint println(const char* t = nullptr)\r\n\t\t{\r\n\t\t\tif(t == nullptr) {\r\n\t\t\t\treturn write(\"\\r\\n\", 2);\r\n\t\t\t}\r\n\r\n\t\t\tsize_t l = strlen(t);\r\n\t\t\tchar tmp[l + 2];\r\n\t\t\tstrcpy(tmp, t);\r\n\t\t\ttmp[l + 0] = '\\r';\r\n\t\t\ttmp[l + 1] = '\\n';\r\n\t\t\treturn write(tmp, l + 2);\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 有効なデータがあるか\r\n\t\t\t@return 有効なデータ数\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tint available()\r\n\t\t{\r\n\t\t\tint ret = 0;\r\n\t\t\tif(connected()) {\r\n\t\t\t\tret = head_tcb[cepid_ - 1].rdsize;\r\n\t\t\t\tint ercd = tcp_read_stat(cepid_);\r\n\r\n\t\t\t\tif(ret == 0 && ercd == T4_TCPS_CLOSE_WAIT) {\r\n\t\t\t\t\ttcp_sht_cep(cepid_, TMO_FEVR);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\t};\r\n}\r\n<|endoftext|>"} {"text":"\/\/-----------------------------------------------------------------------------\n\/\/ Copyright (c) 2014 Michael G. Brehm\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/ \n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/ \n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/-----------------------------------------------------------------------------\n\n#include \"stdafx.h\"\t\t\t\t\t\t\/\/ Include project pre-compiled headers\n#include \"ElfImage.h\"\t\t\t\t\t\/\/ Include ELFImage declarations\n\n#pragma warning(push, 4)\t\t\t\t\/\/ Enable maximum compiler warnings\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Explicit Instantiations\n\n#ifdef _M_X64\ntemplate ElfImageT;\n#else\ntemplate ElfImageT;\n#endif\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ElfImageT Constructor (private)\n\/\/\n\/\/ Arguments:\n\/\/\n\/\/\tmapping\t\t- Memory-mapped ELF image file to load\n\/\/\tlength\t\t- Optional length to use from mapping\n\ntemplate \nElfImageT::ElfImageT(std::shared_ptr& mapping, size_t length)\n{\n\t\/\/ Create a read-only view of the memory-mapped ELF image\n\tstd::unique_ptr view(MappedFileView::Create(mapping, FILE_MAP_READ, 0, length));\n\tintptr_t viewptr = intptr_t(view->Pointer);\n\n\t\/\/ Validate the ELF header that should be at the start of the view\n\tValidateHeader(view->Pointer, view->Length);\n\tehdr_t*\telfheader = reinterpret_cast(view->Pointer);\n\n\t\/\/ Create a collection of all the ELF program headers\n\tstd::vector\tprogheaders;\n\tfor(int index = 0; index < elfheader->e_phnum; index++) {\n\n\t\t\/\/ Get the offset into the file for the next program header and check it\n\t\tintptr_t offset = elfheader->e_phoff + (index * elfheader->e_phentsize);\n\t\tif(view->Length < (offset + sizeof(phdr_t))) throw Exception(E_ELF_TRUNCATED);\n\n\t\t\/\/ Insert the program header into the collection\n\t\tprogheaders.push_back(*reinterpret_cast(viewptr + offset));\n\t}\n\n\t\/\/ Determine the memory requirements of the loaded image\n\tintptr_t minpaddr = 0, maxpaddr = 0;\n\tfor_each(progheaders.begin(), progheaders.end(), [&](phdr_t& phdr) {\n\n\t\tif(phdr.p_type == PT_LOAD) {\n\n\t\t\t\/\/ Calculate the minimum and maximum physical addresses of the segment\n\t\t\t\/\/ and adjust the overall minimum and maximums accordingly\n\t\t\tintptr_t minsegaddr(phdr.p_paddr);\n\t\t\tintptr_t maxsegaddr(phdr.p_paddr + phdr.p_memsz);\n\n\t\t\tminpaddr = (minpaddr == 0) ? minsegaddr : min(minsegaddr, minpaddr);\n\t\t\tmaxpaddr = (maxpaddr == 0) ? maxsegaddr : max(maxsegaddr, maxpaddr);\n\t\t}\n\t});\n\n\t\/\/ Attempt to reserve the virtual memory for the image. First try to use the physical address specified\n\t\/\/ by the image to avoid relocations, but go ahead and put it anywhere if that doesn't work\n\ttry { m_region.reset(MemoryRegion::Reserve(reinterpret_cast(minpaddr), maxpaddr - minpaddr)); }\n\tcatch(Exception&) { m_region.reset(MemoryRegion::Reserve(maxpaddr - minpaddr, MEM_TOP_DOWN)); }\n\n\t\/\/ Determine the delta between the allocated region and the original base physical address\n\tintptr_t regionbase = intptr_t(m_region->Pointer);\n\tintptr_t paddrdelta = minpaddr - regionbase; \n\n\t\/\/ Load the PT_LOAD segments into virtual memory\n\tfor_each(progheaders.begin(), progheaders.end(), [&](phdr_t& phdr) {\n\n\t\tif((phdr.p_type == PT_LOAD) && (phdr.p_memsz)) {\n\n\t\t\t\/\/ Get the base address of the loadable segment and commit the virtual memory\n\t\t\tintptr_t segbase = phdr.p_paddr - paddrdelta;\n\t\t\tm_region->Commit(reinterpret_cast(segbase), phdr.p_memsz, PAGE_READWRITE);\n\n\t\t\t\/\/ Not all segments contain data that needs to be copied from the source image\n\t\t\tif(phdr.p_filesz) {\n\n\t\t\t\t\/\/ Ensure that there is enough source data to copy and copy it into the segment region\n\t\t\t\tif(view->Length < (phdr.p_offset + phdr.p_filesz)) throw Exception(E_ELF_TRUNCATED);\n\t\t\t\tmemcpy(reinterpret_cast(segbase), reinterpret_cast(viewptr + phdr.p_offset), phdr.p_filesz);\n\t\t\t}\n\n\t\t\t\/\/ Memory that was not loaded from the ELF image must be initialized to zero\n\t\t\tmemset(reinterpret_cast(segbase + phdr.p_filesz), 0, phdr.p_memsz - phdr.p_filesz);\n\n\t\t\t\/\/ Attempt to apply the proper virtual memory protection flags to the segment\n\t\t\ttry { m_region->Protect(reinterpret_cast(segbase), phdr.p_memsz, FlagsToProtection(phdr.p_flags)); }\n\t\t\tcatch(Exception& ex) { throw Exception(ex, E_ELFSEGMENTPROTECTION); }\n\t\t}\n\t});\n\n\t\/\/ Calculate the address of the image entry point, if one has been specified in the header\n\tm_entry = (elfheader->e_entry) ? reinterpret_cast(elfheader->e_entry - paddrdelta) : nullptr;\n}\n\n\/\/---------------------------------------------------------------------------\n\/\/ ElfImageT::AlignDown (private, static)\n\/\/\n\/\/ Aligns an offset down to the specified alignment\n\/\/\n\/\/ Arguments:\n\/\/\n\/\/\taddress\t\t- Address to be aligned\n\/\/\talignment\t- Alignment\n\ntemplate \nuintptr_t ElfImageT::AlignDown(uintptr_t address, size_t alignment)\n{\n\tif(alignment < 1) throw Exception(E_ARGUMENTOUTOFRANGE, _T(\"alignment\"));\n\n\tif(address < alignment) return 0;\n\telse return AlignUp(address - (alignment - 1), alignment);\n}\n\n\/\/---------------------------------------------------------------------------\n\/\/ ElfImageT::AlignUp (private, static)\n\/\/\n\/\/ Aligns an offset up to the specified alignment\n\/\/\n\/\/ Arguments:\n\/\/\n\/\/\taddress\t\t- Address to be aligned\n\/\/\talignment\t- Alignment\n\ntemplate \nuintptr_t ElfImageT::AlignUp(uintptr_t address, size_t alignment)\n{\n\tif(alignment < 1) throw Exception(E_ARGUMENTOUTOFRANGE, _T(\"alignment\"));\n\n\tif(address == 0) return 0;\n\telse return address + ((alignment - (address % alignment)) % alignment);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ElfImageT::FlagsToProtection (private, static)\n\/\/\n\/\/ Converts an ELF program header p_flags into VirtualAlloc() protection flags\n\/\/\n\/\/ Arguments:\n\/\/\n\/\/\tflags\t\t- ELF program header p_flags value\n\ntemplate \nDWORD ElfImageT::FlagsToProtection(uint32_t flags)\n{\n\tswitch(flags) {\n\n\t\tcase PF_X:\t\t\t\t\treturn PAGE_EXECUTE;\n\t\tcase PF_W :\t\t\t\t\treturn PAGE_READWRITE;\n\t\tcase PF_R :\t\t\t\t\treturn PAGE_READONLY;\n\t\tcase PF_X | PF_W :\t\t\treturn PAGE_EXECUTE_READWRITE;\n\t\tcase PF_X | PF_R :\t\t\treturn PAGE_EXECUTE_READ;\n\t\tcase PF_W | PF_R :\t\t\treturn PAGE_READWRITE;\n\t\tcase PF_X | PF_W | PF_R :\treturn PAGE_EXECUTE_READWRITE;\n\t}\n\n\treturn PAGE_NOACCESS;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ElfImageT::Load (static)\n\/\/\n\/\/ Parses and loads the specified ELF image into virtual memory\n\/\/\n\/\/ Arguments:\n\/\/\n\/\/\tmapping\t\t\t- Memory-mapped image file\n\/\/\tlength\t\t\t- Optional length of mapping to use\n\ntemplate \nElfImageT* ElfImageT::Load(std::shared_ptr& mapping, size_t length)\n{\n\t\/\/ All the validation code has been moved into the constructor\n\treturn new ElfImageT(mapping, length);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ElfImageT::TryValidateHeader (static)\n\/\/\n\/\/ Validates that the provided pointer points to a 64-bit ELF binary header --\n\/\/ returns a boolean flag rather than throwing an exception\n\/\/\n\/\/ Arguments:\n\/\/\n\/\/\tbase\t\t- Base address of the ELF binary to test\n\/\/\tlength\t\t- Length of the buffer pointed to by base\n\ntemplate \nbool ElfImageT::TryValidateHeader(const void* base, size_t length)\n{\n\t\/\/ Invoke the version that throws exceptions and just eat them\n\ttry { ValidateHeader(base, length); return true; }\n\tcatch(Exception&) { return false; }\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ElfImageT::ValidateHeader (static)\n\/\/\n\/\/ Validates that the provided pointer points to a 64-bit ELF binary header\n\/\/\n\/\/ Arguments:\n\/\/\n\/\/\tbase\t\t- Base address of the ELF binary to test\n\/\/\tlength\t\t- Length of the buffer pointed to by base\n\ntemplate \nvoid ElfImageT::ValidateHeader(const void* base, size_t length)\n{\n\tconst ehdr_t*\t\t\t\theader;\t\t\t\t\t\/\/ ELF header structure\n\n\t\/\/ Check the length and cast out a pointer to the header structure\n\tif(length < sizeof(ehdr_t)) throw Exception(E_TRUNCATEDELFHEADER);\n\theader = reinterpret_cast(base);\n\n\t\/\/ Check the ELF header magic number\n\tif(memcmp(&header->e_ident[EI_MAG0], ELFMAG, SELFMAG) != 0) throw Exception(E_INVALIDELFMAGIC);\n\n\t\/\/ Verify the ELF class matches the build configuration (32-bit vs. 64-bit)\n\tint elfclass = (sizeof(ehdr_t) == sizeof(Elf32_Ehdr)) ? ELFCLASS32 : ELFCLASS64;\n\tif(header->e_ident[EI_CLASS] != elfclass) throw Exception(E_UNEXPECTEDELFCLASS, header->e_ident[EI_CLASS]);\n\n\t\/\/ Verify the endianness and version of the ELF binary\n\tif(header->e_ident[EI_DATA] != ELFDATA2LSB) throw Exception(E_UNEXPECTEDELFENCODING);\n\tif(header->e_ident[EI_VERSION] != EV_CURRENT) throw Exception(E_UNKNOWNELFVERSION);\n\n\t\/\/ TODO: Verify x86 \/ x86_64 machine - check size of ehdr_t to know which\n\t\/\/ TODO: Verify object file type\n\n\t\/\/ Verify that the length of the header is the same size as the Elfxx_Ehdr struct\n\t\/\/ and that the header entries are at least as big as the known structures\n\tif(header->e_ehsize != sizeof(ehdr_t)) throw Exception(E_UNKNOWNELFVERSION);\n\tif((header->e_phentsize) && (header->e_phentsize < sizeof(phdr_t))) throw Exception(E_INVALIDELFPROGRAMTABLE);\n\tif((header->e_shentsize) && (header->e_shentsize < sizeof(shdr_t))) throw Exception(E_INVALIDELFSECTIONTABLE);\n}\n\n\/\/-----------------------------------------------------------------------------\n\n#pragma warning(pop)\nAllow for binaries that have a load address of zero to support position-independent executables\/\/-----------------------------------------------------------------------------\n\/\/ Copyright (c) 2014 Michael G. Brehm\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/ \n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/ \n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/-----------------------------------------------------------------------------\n\n#include \"stdafx.h\"\t\t\t\t\t\t\/\/ Include project pre-compiled headers\n#include \"ElfImage.h\"\t\t\t\t\t\/\/ Include ELFImage declarations\n\n#pragma warning(push, 4)\t\t\t\t\/\/ Enable maximum compiler warnings\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Explicit Instantiations\n\n#ifdef _M_X64\ntemplate ElfImageT;\n#else\ntemplate ElfImageT;\n#endif\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ElfImageT Constructor (private)\n\/\/\n\/\/ Arguments:\n\/\/\n\/\/\tmapping\t\t- Memory-mapped ELF image file to load\n\/\/\tlength\t\t- Optional length to use from mapping\n\ntemplate \nElfImageT::ElfImageT(std::shared_ptr& mapping, size_t length)\n{\n\t\/\/ Create a read-only view of the memory-mapped ELF image\n\tstd::unique_ptr view(MappedFileView::Create(mapping, FILE_MAP_READ, 0, length));\n\tintptr_t viewptr = intptr_t(view->Pointer);\n\n\t\/\/ Validate the ELF header that should be at the start of the view\n\tValidateHeader(view->Pointer, view->Length);\n\tehdr_t*\telfheader = reinterpret_cast(view->Pointer);\n\n\t\/\/ Create a collection of all the ELF program headers\n\tstd::vector\tprogheaders;\n\tfor(int index = 0; index < elfheader->e_phnum; index++) {\n\n\t\t\/\/ Get the offset into the file for the next program header and check it\n\t\tintptr_t offset = elfheader->e_phoff + (index * elfheader->e_phentsize);\n\t\tif(view->Length < (offset + sizeof(phdr_t))) throw Exception(E_ELF_TRUNCATED);\n\n\t\t\/\/ Insert the program header into the collection\n\t\tprogheaders.push_back(*reinterpret_cast(viewptr + offset));\n\t}\n\n\t\/\/ Determine the memory requirements of the loaded image\n\tintptr_t minpaddr = 0, maxpaddr = 0;\n\tfor_each(progheaders.begin(), progheaders.end(), [&](phdr_t& phdr) {\n\n\t\tif(phdr.p_type == PT_LOAD) {\n\n\t\t\t\/\/ Calculate the minimum and maximum physical addresses of the segment\n\t\t\t\/\/ and adjust the overall minimum and maximums accordingly\n\t\t\tminpaddr = min(intptr_t(phdr.p_paddr), minpaddr);\n\t\t\tmaxpaddr = max(intptr_t(phdr.p_paddr + phdr.p_memsz), maxpaddr);\n\t\t}\n\t});\n\n\t\/\/ Attempt to reserve the virtual memory for the image. First try to use the physical address specified\n\t\/\/ by the image to avoid relocations, but go ahead and put it anywhere if that doesn't work\n\ttry { m_region.reset(MemoryRegion::Reserve(reinterpret_cast(minpaddr), maxpaddr - minpaddr)); }\n\tcatch(Exception&) { m_region.reset(MemoryRegion::Reserve(maxpaddr - minpaddr, MEM_TOP_DOWN)); }\n\n\t\/\/ Determine the delta between the allocated region and the original base physical address\n\tintptr_t regionbase = intptr_t(m_region->Pointer);\n\tintptr_t paddrdelta = minpaddr - regionbase; \n\n\t\/\/ Load the PT_LOAD segments into virtual memory\n\tfor_each(progheaders.begin(), progheaders.end(), [&](phdr_t& phdr) {\n\n\t\tif((phdr.p_type == PT_LOAD) && (phdr.p_memsz)) {\n\n\t\t\t\/\/ Get the base address of the loadable segment and commit the virtual memory\n\t\t\tintptr_t segbase = phdr.p_paddr - paddrdelta;\n\t\t\tm_region->Commit(reinterpret_cast(segbase), phdr.p_memsz, PAGE_READWRITE);\n\n\t\t\t\/\/ Not all segments contain data that needs to be copied from the source image\n\t\t\tif(phdr.p_filesz) {\n\n\t\t\t\t\/\/ Ensure that there is enough source data to copy and copy it into the segment region\n\t\t\t\tif(view->Length < (phdr.p_offset + phdr.p_filesz)) throw Exception(E_ELF_TRUNCATED);\n\t\t\t\tmemcpy(reinterpret_cast(segbase), reinterpret_cast(viewptr + phdr.p_offset), phdr.p_filesz);\n\t\t\t}\n\n\t\t\t\/\/ Memory that was not loaded from the ELF image must be initialized to zero\n\t\t\tmemset(reinterpret_cast(segbase + phdr.p_filesz), 0, phdr.p_memsz - phdr.p_filesz);\n\n\t\t\t\/\/ Attempt to apply the proper virtual memory protection flags to the segment\n\t\t\ttry { m_region->Protect(reinterpret_cast(segbase), phdr.p_memsz, FlagsToProtection(phdr.p_flags)); }\n\t\t\tcatch(Exception& ex) { throw Exception(ex, E_ELFSEGMENTPROTECTION); }\n\t\t}\n\t});\n\n\t\/\/ Calculate the address of the image entry point, if one has been specified in the header\n\tm_entry = (elfheader->e_entry) ? reinterpret_cast(elfheader->e_entry - paddrdelta) : nullptr;\n}\n\n\/\/---------------------------------------------------------------------------\n\/\/ ElfImageT::AlignDown (private, static)\n\/\/\n\/\/ Aligns an offset down to the specified alignment\n\/\/\n\/\/ Arguments:\n\/\/\n\/\/\taddress\t\t- Address to be aligned\n\/\/\talignment\t- Alignment\n\ntemplate \nuintptr_t ElfImageT::AlignDown(uintptr_t address, size_t alignment)\n{\n\tif(alignment < 1) throw Exception(E_ARGUMENTOUTOFRANGE, _T(\"alignment\"));\n\n\tif(address < alignment) return 0;\n\telse return AlignUp(address - (alignment - 1), alignment);\n}\n\n\/\/---------------------------------------------------------------------------\n\/\/ ElfImageT::AlignUp (private, static)\n\/\/\n\/\/ Aligns an offset up to the specified alignment\n\/\/\n\/\/ Arguments:\n\/\/\n\/\/\taddress\t\t- Address to be aligned\n\/\/\talignment\t- Alignment\n\ntemplate \nuintptr_t ElfImageT::AlignUp(uintptr_t address, size_t alignment)\n{\n\tif(alignment < 1) throw Exception(E_ARGUMENTOUTOFRANGE, _T(\"alignment\"));\n\n\tif(address == 0) return 0;\n\telse return address + ((alignment - (address % alignment)) % alignment);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ElfImageT::FlagsToProtection (private, static)\n\/\/\n\/\/ Converts an ELF program header p_flags into VirtualAlloc() protection flags\n\/\/\n\/\/ Arguments:\n\/\/\n\/\/\tflags\t\t- ELF program header p_flags value\n\ntemplate \nDWORD ElfImageT::FlagsToProtection(uint32_t flags)\n{\n\tswitch(flags) {\n\n\t\tcase PF_X:\t\t\t\t\treturn PAGE_EXECUTE;\n\t\tcase PF_W :\t\t\t\t\treturn PAGE_READWRITE;\n\t\tcase PF_R :\t\t\t\t\treturn PAGE_READONLY;\n\t\tcase PF_X | PF_W :\t\t\treturn PAGE_EXECUTE_READWRITE;\n\t\tcase PF_X | PF_R :\t\t\treturn PAGE_EXECUTE_READ;\n\t\tcase PF_W | PF_R :\t\t\treturn PAGE_READWRITE;\n\t\tcase PF_X | PF_W | PF_R :\treturn PAGE_EXECUTE_READWRITE;\n\t}\n\n\treturn PAGE_NOACCESS;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ElfImageT::Load (static)\n\/\/\n\/\/ Parses and loads the specified ELF image into virtual memory\n\/\/\n\/\/ Arguments:\n\/\/\n\/\/\tmapping\t\t\t- Memory-mapped image file\n\/\/\tlength\t\t\t- Optional length of mapping to use\n\ntemplate \nElfImageT* ElfImageT::Load(std::shared_ptr& mapping, size_t length)\n{\n\t\/\/ All the validation code has been moved into the constructor\n\treturn new ElfImageT(mapping, length);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ElfImageT::TryValidateHeader (static)\n\/\/\n\/\/ Validates that the provided pointer points to a 64-bit ELF binary header --\n\/\/ returns a boolean flag rather than throwing an exception\n\/\/\n\/\/ Arguments:\n\/\/\n\/\/\tbase\t\t- Base address of the ELF binary to test\n\/\/\tlength\t\t- Length of the buffer pointed to by base\n\ntemplate \nbool ElfImageT::TryValidateHeader(const void* base, size_t length)\n{\n\t\/\/ Invoke the version that throws exceptions and just eat them\n\ttry { ValidateHeader(base, length); return true; }\n\tcatch(Exception&) { return false; }\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ElfImageT::ValidateHeader (static)\n\/\/\n\/\/ Validates that the provided pointer points to a 64-bit ELF binary header\n\/\/\n\/\/ Arguments:\n\/\/\n\/\/\tbase\t\t- Base address of the ELF binary to test\n\/\/\tlength\t\t- Length of the buffer pointed to by base\n\ntemplate \nvoid ElfImageT::ValidateHeader(const void* base, size_t length)\n{\n\tconst ehdr_t*\t\t\t\theader;\t\t\t\t\t\/\/ ELF header structure\n\n\t\/\/ Check the length and cast out a pointer to the header structure\n\tif(length < sizeof(ehdr_t)) throw Exception(E_TRUNCATEDELFHEADER);\n\theader = reinterpret_cast(base);\n\n\t\/\/ Check the ELF header magic number\n\tif(memcmp(&header->e_ident[EI_MAG0], ELFMAG, SELFMAG) != 0) throw Exception(E_INVALIDELFMAGIC);\n\n\t\/\/ Verify the ELF class matches the build configuration (32-bit vs. 64-bit)\n\tint elfclass = (sizeof(ehdr_t) == sizeof(Elf32_Ehdr)) ? ELFCLASS32 : ELFCLASS64;\n\tif(header->e_ident[EI_CLASS] != elfclass) throw Exception(E_UNEXPECTEDELFCLASS, header->e_ident[EI_CLASS]);\n\n\t\/\/ Verify the endianness and version of the ELF binary\n\tif(header->e_ident[EI_DATA] != ELFDATA2LSB) throw Exception(E_UNEXPECTEDELFENCODING);\n\tif(header->e_ident[EI_VERSION] != EV_CURRENT) throw Exception(E_UNKNOWNELFVERSION);\n\n\t\/\/ TODO: Verify x86 \/ x86_64 machine - check size of ehdr_t to know which\n\t\/\/ TODO: Verify object file type\n\n\t\/\/ Verify that the length of the header is the same size as the Elfxx_Ehdr struct\n\t\/\/ and that the header entries are at least as big as the known structures\n\tif(header->e_ehsize != sizeof(ehdr_t)) throw Exception(E_UNKNOWNELFVERSION);\n\tif((header->e_phentsize) && (header->e_phentsize < sizeof(phdr_t))) throw Exception(E_INVALIDELFPROGRAMTABLE);\n\tif((header->e_shentsize) && (header->e_shentsize < sizeof(shdr_t))) throw Exception(E_INVALIDELFSECTIONTABLE);\n}\n\n\/\/-----------------------------------------------------------------------------\n\n#pragma warning(pop)\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace AGE\n{\n\tclass Engine;\n\tclass RenderScene;\n\tclass EntityFilter;\n\tclass System;\n\tclass SceneManager;\n\n\tclass AScene : public DependenciesInjector, public EntityIdRegistrationManager, public ComponentManager\n\t{\n\tprivate:\n\t\tstd::multimap > _systems;\n\t\tstd::array, MAX_CPT_NUMBER + MAX_TAG_NUMBER> _filters;\n\t\tstd::list _allFilters;\n\t\tAGE::ObjectPool _entityPool;\n\t\tAGE::Queue _freeEntityId;\n\t\tstd::unordered_set _entities;\n\t\tENTITY_ID _entityNumber;\n\t\tAGE::RenderScene *_renderScene;\n\t\tbool _active;\n\t\tfriend EntityFilter;\n\t\tfriend class AGE::RenderScene;\n\t\tfriend class AGE::SceneManager;\n\tprotected:\n\t\tAGE::Engine * _engine;\n\t\tinline void setActive(bool tof) { _active = tof; }\n\tpublic:\n\t\tAScene(AGE::Engine *engine);\n\t\tvirtual ~AScene();\n\t\tinline std::size_t getNumberOfEntities() const { return _entities.size(); }\n\t\tvirtual bool \t\t\tuserStart() = 0;\n\t\tvirtual bool \t\t\tuserUpdateBegin(float time) = 0;\n\t\tvirtual bool userUpdateEnd(float time) = 0;\n\t\tvoid \t\t\t\t\tupdate(float time);\n\t\tbool start();\n\t\tinline AGE::Engine *getEngine() { return _engine; }\n\t\tinline void setRenderScene(AGE::RenderScene *renderScene) { _renderScene = renderScene; }\n\t\tinline bool isActive() const { return _active; }\n\n\t\tvoid registerFilter(EntityFilter *filter);\n\t\tvoid filterSubscribe(ComponentType id, EntityFilter* filter);\n\t\tvoid filterUnsubscribe(ComponentType id, EntityFilter* filter);\n\n\t\tvoid informFiltersTagAddition(TAG_ID id, const EntityData &entity);\n\t\tvoid informFiltersTagDeletion(TAG_ID id, const EntityData &entity);\n\t\tvoid informFiltersComponentAddition(ComponentType id, const EntityData &entity);\n\t\tvoid informFiltersComponentDeletion(ComponentType id, const EntityData &entity);\n\t\tvoid informFiltersEntityCreation(const EntityData &entity);\n\t\tvoid informFiltersEntityDeletion(const EntityData &entity);\n\n\t\tEntity &createEntity();\n\t\tvoid destroy(const Entity &e);\n\t\tvoid clearAllEntities();\n\n\t\ttemplate \n\t\tstd::shared_ptr addSystem(std::size_t priority)\n\t\t{\n\t\t\tauto tmp = std::make_shared((AScene*)(this));\n\t\t\tif (!tmp->init())\n\t\t\t\treturn nullptr;\n\t\t\t_systems.insert(std::make_pair(priority, tmp));\n\t\t\treturn tmp;\n\t\t}\n\n\t\ttemplate \n\t\tstd::shared_ptr getSystem()\n\t\t{\n\t\t\tfor (auto &e : _systems)\n\t\t\t{\n\t\t\t\tif (typeid(*e.second.get()).name() == typeid(T).name())\n\t\t\t\t\treturn std::static_pointer_cast(e.second);\n\t\t\t}\n\t\t\treturn nullptr;\n\t\t}\n\n\t\ttemplate \n\t\tvoid deleteSystem()\n\t\t{\n\t\t\tfor (auto &e : _systems)\n\t\t\t{\n\t\t\t\tif (typeid(*e.second.get()).name() == typeid(T).name())\n\t\t\t\t{\n\t\t\t\t\tdelete e.second;\n\t\t\t\t\t_systems.erase(e);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ttemplate \n\t\tbool activateSystem()\n\t\t{\n\t\t\tfor (auto &e : _systems)\n\t\t\t{\n\t\t\t\tif (typeid(*e.second.get()).name() == typeid(T).name())\n\t\t\t\t\treturn e.second->setActivation(true);\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\ttemplate \n\t\tbool deactivateSystem()\n\t\t{\n\t\t\tfor (auto &e : _systems)\n\t\t\t{\n\t\t\t\tif (typeid(*e.second.get()).name() == typeid(T).name())\n\t\t\t\t\treturn e.second->setActivation(false);\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tvoid saveToJson(const std::string &fileName);\n\t\tvoid loadFromJson(const std::string &fileName);\n\t\tvoid saveToBinary(const std::string &fileName);\n\t\tvoid loadFromBinary(const std::string &fileName);\n\n\t\ttemplate \n\t\tvoid saveSelectionToJson(const std::string &fileName, Container &selection)\n\t\t{\n\t\t\tstd::ofstream file(fileName.c_str(), std::ios::binary);\n\t\t\tAGE_ASSERT(file.is_open());\n\t\t\t{\n\t\t\t\tauto ar = cereal::JSONOutputArchive(file);\n\n\t\t\t\tstd::size_t entityNbr = selection.size();\n\n\t\t\t\tar(cereal::make_nvp(\"Number_of_serialized_entities\", entityNbr));\n\n\t\t\t\tauto &typesMap = ComponentRegistrationManager::getInstance().getAgeIdToSystemIdMap();\n\t\t\t\tar(cereal::make_nvp(\"Component type map\", typesMap));\n\n\t\t\t\tfor (auto &e : selection)\n\t\t\t\t{\n\t\t\t\t\tEntitySerializationInfos es(e.ptr);\n\t\t\t\t\tfor (auto &c : e.ptr->components)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (c)\n\t\t\t\t\t\t{\n#ifdef EDITOR_ENABLED\n\t\t\t\t\t\t\tif (WESerialization::SerializeForEditor() == false && !c->serializeInExport())\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n#endif\n\t\t\t\t\t\t\tes.componentTypes.push_back(c->getType());\n\t\t\t\t\t\t\tes.components.push_back(c);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tar(cereal::make_nvp(\"Entity_\" + std::to_string(e.ptr->getEntity().getId()), es));\n\t\t\t\t}\n\t\t\t}\n\t\t\tfile.close();\n\t\t}\n\n\t\ttemplate \n\t\tvoid load(std::ifstream &s)\n\t\t{\n\t\t\t\/\/ @ECS TODO\n\t\t\t\n\t\t\t\/\/Archive ar(s);\n\n\t\t\t\/\/std::uint16_t size = 0;\n\t\t\t\/\/ar(size);\n\t\t\t\/\/for (unsigned int i = 0; i < size; ++i)\n\t\t\t\/\/{\n\t\t\t\/\/\tauto &e = createEntity();\n\t\t\t\/\/\tauto &ed = *e.ptr;\n\n\t\t\t\/\/\tEntitySerializationInfos infos(ed);\n\t\t\t\/\/\tar(infos);\n\t\t\t\/\/\te.flags = infos.flags;\n\t\t\t\/\/\ted.link.setPosition(infos.link.getPosition());\n\t\t\t\/\/\ted.link.setOrientation(infos.link.getOrientation());\n\t\t\t\/\/\ted.link.setScale(infos.link.getScale());\n\n\t\t\t\/\/\tfor (auto &hash : infos.componentsHash)\n\t\t\t\/\/\t{\n\t\t\t\/\/\t\tstd::size_t componentTypeId;\n\t\t\t\/\/\t\tauto ptr = ComponentRegistrar::getInstance().createComponentFromType(hash, ar, componentTypeId, this);\n\t\t\t\/\/\t\ted.barcode.setComponent(componentTypeId);\n\t\t\t\/\/\t\tassert(_componentsManagers[componentTypeId] != nullptr);\n\t\t\t\/\/\t\t_componentsManagers[componentTypeId]->addComponentPtr(e, ptr);\n\t\t\t\/\/\t\tinformFiltersComponentAddition(componentTypeId, ed);\n\t\t\t\/\/\t}\n\t\t\t\/\/\t\/\/\tar(*e.get());\n\t\t\t\/\/}\n\t\t\t\/\/\/\/updateEntityHandles();\n\t\t}\n\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/\/\/\/\/\/\n\t\t\/\/ Component Manager Get \/ Set\n\n\t\ttemplate \n\t\tvoid clearComponentsType()\n\t\t{\n\t\t\t\/\/TODO\n\t\t\tauto id = Component::getTypeId();\n\t\t\tif (_componentsManagers[id] == nullptr)\n\t\t\t\treturn;\n\t\t\tauto &manager = *static_cast*>(_componentsManagers[id]);\n\t\t\tauto &col = manager.getComponents();\n\t\t\tfor (std::size_t i = 0; i < manager.getSize(); ++i)\n\t\t\t{\n\t\t\t\t_entityPool[col[i].entityId].barcode.unsetComponent(ComponentType(id));\n\t\t\t}\n\t\t\tmanager.clearComponents();\n\t\t\tfor (auto filter : _filters[id])\n\t\t\t{\n\t\t\t\tfilter->clearCollection();\n\t\t\t}\n\t\t}\n\n\t\tvoid addTag(Entity &e, TAG_ID tag);\n\t\tvoid removeTag(Entity &e, TAG_ID tag);\n\t\tbool isTagged(Entity &e, TAG_ID tag);\n\t};\n}\nMissing include#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef EDITOR_ENABLED\n#include \n#endif\n\nnamespace AGE\n{\n\tclass Engine;\n\tclass RenderScene;\n\tclass EntityFilter;\n\tclass System;\n\tclass SceneManager;\n\n\tclass AScene : public DependenciesInjector, public EntityIdRegistrationManager, public ComponentManager\n\t{\n\tprivate:\n\t\tstd::multimap > _systems;\n\t\tstd::array, MAX_CPT_NUMBER + MAX_TAG_NUMBER> _filters;\n\t\tstd::list _allFilters;\n\t\tAGE::ObjectPool _entityPool;\n\t\tAGE::Queue _freeEntityId;\n\t\tstd::unordered_set _entities;\n\t\tENTITY_ID _entityNumber;\n\t\tAGE::RenderScene *_renderScene;\n\t\tbool _active;\n\t\tfriend EntityFilter;\n\t\tfriend class AGE::RenderScene;\n\t\tfriend class AGE::SceneManager;\n\tprotected:\n\t\tAGE::Engine * _engine;\n\t\tinline void setActive(bool tof) { _active = tof; }\n\tpublic:\n\t\tAScene(AGE::Engine *engine);\n\t\tvirtual ~AScene();\n\t\tinline std::size_t getNumberOfEntities() const { return _entities.size(); }\n\t\tvirtual bool \t\t\tuserStart() = 0;\n\t\tvirtual bool \t\t\tuserUpdateBegin(float time) = 0;\n\t\tvirtual bool userUpdateEnd(float time) = 0;\n\t\tvoid \t\t\t\t\tupdate(float time);\n\t\tbool start();\n\t\tinline AGE::Engine *getEngine() { return _engine; }\n\t\tinline void setRenderScene(AGE::RenderScene *renderScene) { _renderScene = renderScene; }\n\t\tinline bool isActive() const { return _active; }\n\n\t\tvoid registerFilter(EntityFilter *filter);\n\t\tvoid filterSubscribe(ComponentType id, EntityFilter* filter);\n\t\tvoid filterUnsubscribe(ComponentType id, EntityFilter* filter);\n\n\t\tvoid informFiltersTagAddition(TAG_ID id, const EntityData &entity);\n\t\tvoid informFiltersTagDeletion(TAG_ID id, const EntityData &entity);\n\t\tvoid informFiltersComponentAddition(ComponentType id, const EntityData &entity);\n\t\tvoid informFiltersComponentDeletion(ComponentType id, const EntityData &entity);\n\t\tvoid informFiltersEntityCreation(const EntityData &entity);\n\t\tvoid informFiltersEntityDeletion(const EntityData &entity);\n\n\t\tEntity &createEntity();\n\t\tvoid destroy(const Entity &e);\n\t\tvoid clearAllEntities();\n\n\t\ttemplate \n\t\tstd::shared_ptr addSystem(std::size_t priority)\n\t\t{\n\t\t\tauto tmp = std::make_shared((AScene*)(this));\n\t\t\tif (!tmp->init())\n\t\t\t\treturn nullptr;\n\t\t\t_systems.insert(std::make_pair(priority, tmp));\n\t\t\treturn tmp;\n\t\t}\n\n\t\ttemplate \n\t\tstd::shared_ptr getSystem()\n\t\t{\n\t\t\tfor (auto &e : _systems)\n\t\t\t{\n\t\t\t\tif (typeid(*e.second.get()).name() == typeid(T).name())\n\t\t\t\t\treturn std::static_pointer_cast(e.second);\n\t\t\t}\n\t\t\treturn nullptr;\n\t\t}\n\n\t\ttemplate \n\t\tvoid deleteSystem()\n\t\t{\n\t\t\tfor (auto &e : _systems)\n\t\t\t{\n\t\t\t\tif (typeid(*e.second.get()).name() == typeid(T).name())\n\t\t\t\t{\n\t\t\t\t\tdelete e.second;\n\t\t\t\t\t_systems.erase(e);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ttemplate \n\t\tbool activateSystem()\n\t\t{\n\t\t\tfor (auto &e : _systems)\n\t\t\t{\n\t\t\t\tif (typeid(*e.second.get()).name() == typeid(T).name())\n\t\t\t\t\treturn e.second->setActivation(true);\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\ttemplate \n\t\tbool deactivateSystem()\n\t\t{\n\t\t\tfor (auto &e : _systems)\n\t\t\t{\n\t\t\t\tif (typeid(*e.second.get()).name() == typeid(T).name())\n\t\t\t\t\treturn e.second->setActivation(false);\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tvoid saveToJson(const std::string &fileName);\n\t\tvoid loadFromJson(const std::string &fileName);\n\t\tvoid saveToBinary(const std::string &fileName);\n\t\tvoid loadFromBinary(const std::string &fileName);\n\n\t\ttemplate \n\t\tvoid saveSelectionToJson(const std::string &fileName, Container &selection)\n\t\t{\n\t\t\tstd::ofstream file(fileName.c_str(), std::ios::binary);\n\t\t\tAGE_ASSERT(file.is_open());\n\t\t\t{\n\t\t\t\tauto ar = cereal::JSONOutputArchive(file);\n\n\t\t\t\tstd::size_t entityNbr = selection.size();\n\n\t\t\t\tar(cereal::make_nvp(\"Number_of_serialized_entities\", entityNbr));\n\n\t\t\t\tauto &typesMap = ComponentRegistrationManager::getInstance().getAgeIdToSystemIdMap();\n\t\t\t\tar(cereal::make_nvp(\"Component type map\", typesMap));\n\n\t\t\t\tfor (auto &e : selection)\n\t\t\t\t{\n\t\t\t\t\tEntitySerializationInfos es(e.ptr);\n\t\t\t\t\tfor (auto &c : e.ptr->components)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (c)\n\t\t\t\t\t\t{\n#ifdef EDITOR_ENABLED\n\t\t\t\t\t\t\tif (WESerialization::SerializeForEditor() == false && !c->serializeInExport())\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n#endif\n\t\t\t\t\t\t\tes.componentTypes.push_back(c->getType());\n\t\t\t\t\t\t\tes.components.push_back(c);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tar(cereal::make_nvp(\"Entity_\" + std::to_string(e.ptr->getEntity().getId()), es));\n\t\t\t\t}\n\t\t\t}\n\t\t\tfile.close();\n\t\t}\n\n\t\ttemplate \n\t\tvoid load(std::ifstream &s)\n\t\t{\n\t\t\t\/\/ @ECS TODO\n\t\t\t\n\t\t\t\/\/Archive ar(s);\n\n\t\t\t\/\/std::uint16_t size = 0;\n\t\t\t\/\/ar(size);\n\t\t\t\/\/for (unsigned int i = 0; i < size; ++i)\n\t\t\t\/\/{\n\t\t\t\/\/\tauto &e = createEntity();\n\t\t\t\/\/\tauto &ed = *e.ptr;\n\n\t\t\t\/\/\tEntitySerializationInfos infos(ed);\n\t\t\t\/\/\tar(infos);\n\t\t\t\/\/\te.flags = infos.flags;\n\t\t\t\/\/\ted.link.setPosition(infos.link.getPosition());\n\t\t\t\/\/\ted.link.setOrientation(infos.link.getOrientation());\n\t\t\t\/\/\ted.link.setScale(infos.link.getScale());\n\n\t\t\t\/\/\tfor (auto &hash : infos.componentsHash)\n\t\t\t\/\/\t{\n\t\t\t\/\/\t\tstd::size_t componentTypeId;\n\t\t\t\/\/\t\tauto ptr = ComponentRegistrar::getInstance().createComponentFromType(hash, ar, componentTypeId, this);\n\t\t\t\/\/\t\ted.barcode.setComponent(componentTypeId);\n\t\t\t\/\/\t\tassert(_componentsManagers[componentTypeId] != nullptr);\n\t\t\t\/\/\t\t_componentsManagers[componentTypeId]->addComponentPtr(e, ptr);\n\t\t\t\/\/\t\tinformFiltersComponentAddition(componentTypeId, ed);\n\t\t\t\/\/\t}\n\t\t\t\/\/\t\/\/\tar(*e.get());\n\t\t\t\/\/}\n\t\t\t\/\/\/\/updateEntityHandles();\n\t\t}\n\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/\/\/\/\/\/\n\t\t\/\/ Component Manager Get \/ Set\n\n\t\ttemplate \n\t\tvoid clearComponentsType()\n\t\t{\n\t\t\t\/\/TODO\n\t\t\tauto id = Component::getTypeId();\n\t\t\tif (_componentsManagers[id] == nullptr)\n\t\t\t\treturn;\n\t\t\tauto &manager = *static_cast*>(_componentsManagers[id]);\n\t\t\tauto &col = manager.getComponents();\n\t\t\tfor (std::size_t i = 0; i < manager.getSize(); ++i)\n\t\t\t{\n\t\t\t\t_entityPool[col[i].entityId].barcode.unsetComponent(ComponentType(id));\n\t\t\t}\n\t\t\tmanager.clearComponents();\n\t\t\tfor (auto filter : _filters[id])\n\t\t\t{\n\t\t\t\tfilter->clearCollection();\n\t\t\t}\n\t\t}\n\n\t\tvoid addTag(Entity &e, TAG_ID tag);\n\t\tvoid removeTag(Entity &e, TAG_ID tag);\n\t\tbool isTagged(Entity &e, TAG_ID tag);\n\t};\n}\n<|endoftext|>"} {"text":"Fixed multiple duplicate lights in mesh lightsources vector<|endoftext|>"} {"text":"#include \"ComponentBone.h\"\n#include \"Application.h\"\n\n#include \"imgui\/imgui.h\"\n#include \"mmgr\\mmgr.h\"\n\nComponentBone::ComponentBone() : Component(componentType_Bone)\n{\n\ttypeName = \"Skeleton\";\n\tname = \"Bone\";\n}\n\nComponentBone::ComponentBone(GameObject * argparent) : Component(componentType_Bone, argparent)\n{\n\ttypeName = \"Skeleton\";\n\tname = \"Bone\";\n}\n \nComponentBone::ComponentBone(componentType argtype, GameObject * argparent) : Component(componentType_Bone, argparent)\n{\n\ttypeName = \"Skeleton\";\n\tname = \"Bone\";\n}\n\nComponentBone::~ComponentBone()\n{\n\ttypeName = \"Skeleton\";\n}\n\nvoid ComponentBone::Start()\n{\n}\n\nvoid ComponentBone::Update(float dt)\n{\n\t\/\/for (uint i = 0; i < skeleton.size(); ++i)\n\t\/\/{\n\t\/\/\tfloat3 position, scale;\n\t\/\/\tfloat4x4 rot;\n\t\/\/\tskeleton[i]->offsetMat.Decompose(position, rot, scale);\n\t\/\/\tApp->renderer3D->debugger->DrawAABB(position, scale);\n\t\/\/}\n}\n\nvoid ComponentBone::CleanUp()\n{\n\tfor (int i = 0; i < skeleton.size(); i++) {\n\t\tif (skeleton[i] != nullptr) {\n\t\t\tskeleton[i]->CleanUp();\n\t\t\tmdelete skeleton[i];\n\t\t}\n\t}\n}\n\nvoid ComponentBone::Enable()\n{\n\tisActive = true;\n}\n\nvoid ComponentBone::Disable()\n{\n\tisActive = false;\n}\n\nvoid ComponentBone::OnEditor()\n{\n\tint num_bones = skeleton.size();\n\tImGui::TextColored(COLOR_YELLOW, \"Num Bones:\");\n\tImGui::InputInt(\"const\", &num_bones);\n\tImGui::TextColored(COLOR_YELLOW, \"Bones:\");\n\tif (ImGui::CollapsingHeader(\"Bones:\")) {\n\t\tfor (int i = 0; i < skeleton.size(); i++) {\n\t\t\tImGui::TextColored(COLOR_YELLOW, \"%i: \", i);\n\t\t\tImGui::SameLine();\n\t\t\tImGui::Text(skeleton[i]->name.c_str());\n\t\t}\n\t}\n}\n\nComponentMesh * ComponentBone::GetMesh() const\n{\n\treturn mesh;\n}\n\nvoid ComponentBone::SetMesh(ComponentMesh * m)\n{\n\tmesh = m;\n}\nvoid ComponentBone::CollectGOs(GameObject * go)\n{\n\tPairedGOToBones tmp;\n\ttmp.object = go;\n\ttmp.name = go->GetName();\n\tpairedgotobones.push_back(tmp);\n\n\tfor (uint i = 0; i < go->children.size(); ++i)\n\t\tCollectGOs(go->children[i]);\n}\nbool ComponentBone::insert_BoneToIterate(ResourceBone * bone)\n{\n\tif (bone == nullptr || gos_filled == false)\n\t\treturn false;\n\n\tfor (uint i = 0; i < pairedgotobones.size(); ++i) {\n\t\tif (pairedgotobones[i].name == bone->name)\n\t\t{\n\t\t\tpairedgotobones[i].bones.push_back(bone);\n\t\t\tbone->object = pairedgotobones[i].object;\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nResourceBone * ComponentBone::GetRootBone()\n{\n\treturn skeleton.empty() ? nullptr : skeleton[0];\n}\n\nGameObject * ComponentBone::GetRootBoneGO()\n{\n\n\tif (rootBoneGO != nullptr)\n\t\treturn rootBoneGO;\n\n\tfor (int i = 0; i < GetParent()->children.size(); i++) {\n\t\tGameObject* child = GetParent()->children[i];\n\t\tif (child->GetName() == GetRootBone()->name) {\n\t\t\trootBoneGO = child;\n\t\t\treturn rootBoneGO;\n\t\t}\n\t}\n\n\treturn nullptr;\n}\n\nvoid ComponentBone::GetGOFromBones()\n{\n\tif (gos_filled == false)\n\t{\n\t\tCollectGOs(App->scene->GetRoot());\n\t\tgos_filled = true;\n\t}\n\n\tif (pairs_filled == false)\n\t{\n\t\tfor (uint i = 0; i < skeleton.size(); ++i)\n\t\t{\n\t\t\tinsert_BoneToIterate(skeleton[i]);\n\t\t}\n\n\t\t\/*for (vector::iterator it = pairedgotobones.begin(); it != pairedgotobones.end();)\n\t\t{\n\t\t\tif ((*it).bones.empty() == true)\n\t\t\t\tit = pairedgotobones.erase(it);\n\n\t\t\t++it;\n\t\t}*\/\n\t\tpairs_filled = true;\n\t}\n}\n\nadded security :police_car:#include \"ComponentBone.h\"\n#include \"Application.h\"\n\n#include \"imgui\/imgui.h\"\n#include \"mmgr\\mmgr.h\"\n\nComponentBone::ComponentBone() : Component(componentType_Bone)\n{\n\ttypeName = \"Skeleton\";\n\tname = \"Bone\";\n}\n\nComponentBone::ComponentBone(GameObject * argparent) : Component(componentType_Bone, argparent)\n{\n\ttypeName = \"Skeleton\";\n\tname = \"Bone\";\n}\n \nComponentBone::ComponentBone(componentType argtype, GameObject * argparent) : Component(componentType_Bone, argparent)\n{\n\ttypeName = \"Skeleton\";\n\tname = \"Bone\";\n}\n\nComponentBone::~ComponentBone()\n{\n\ttypeName = \"Skeleton\";\n}\n\nvoid ComponentBone::Start()\n{\n}\n\nvoid ComponentBone::Update(float dt)\n{\n\t\/\/for (uint i = 0; i < skeleton.size(); ++i)\n\t\/\/{\n\t\/\/\tfloat3 position, scale;\n\t\/\/\tfloat4x4 rot;\n\t\/\/\tskeleton[i]->offsetMat.Decompose(position, rot, scale);\n\t\/\/\tApp->renderer3D->debugger->DrawAABB(position, scale);\n\t\/\/}\n}\n\nvoid ComponentBone::CleanUp()\n{\n\tfor (int i = 0; i < skeleton.size(); i++) {\n\t\tif (skeleton[i] != nullptr) {\n\t\t\tskeleton[i]->CleanUp();\n\t\t\tmdelete skeleton[i];\n\t\t}\n\t}\n}\n\nvoid ComponentBone::Enable()\n{\n\tisActive = true;\n}\n\nvoid ComponentBone::Disable()\n{\n\tisActive = false;\n}\n\nvoid ComponentBone::OnEditor()\n{\n\tint num_bones = skeleton.size();\n\tImGui::TextColored(COLOR_YELLOW, \"Num Bones:\");\n\tImGui::InputInt(\"const\", &num_bones);\n\tImGui::TextColored(COLOR_YELLOW, \"Bones:\");\n\tif (ImGui::CollapsingHeader(\"Bones:\")) {\n\t\tfor (int i = 0; i < skeleton.size(); i++) {\n\t\t\tImGui::TextColored(COLOR_YELLOW, \"%i: \", i);\n\t\t\tImGui::SameLine();\n\t\t\tImGui::Text(skeleton[i]->name.c_str());\n\t\t}\n\t}\n}\n\nComponentMesh * ComponentBone::GetMesh() const\n{\n\treturn mesh;\n}\n\nvoid ComponentBone::SetMesh(ComponentMesh * m)\n{\n\tmesh = m;\n}\nvoid ComponentBone::CollectGOs(GameObject * go)\n{\n\tPairedGOToBones tmp;\n\ttmp.object = go;\n\ttmp.name = go->GetName();\n\tpairedgotobones.push_back(tmp);\n\n\tfor (uint i = 0; i < go->children.size(); ++i)\n\t\tCollectGOs(go->children[i]);\n}\nbool ComponentBone::insert_BoneToIterate(ResourceBone * bone)\n{\n\tif (bone == nullptr || gos_filled == false)\n\t\treturn false;\n\n\tfor (uint i = 0; i < pairedgotobones.size(); ++i) {\n\t\tif (pairedgotobones[i].name == bone->name)\n\t\t{\n\t\t\tpairedgotobones[i].bones.push_back(bone);\n\t\t\tbone->object = pairedgotobones[i].object;\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nResourceBone * ComponentBone::GetRootBone()\n{\n\treturn skeleton.empty() ? nullptr : skeleton[0];\n}\n\nGameObject * ComponentBone::GetRootBoneGO()\n{\n\n\tif (rootBoneGO != nullptr)\n\t\treturn rootBoneGO;\n\tif (GetRootBone() == nullptr)\n\t\treturn nullptr;\n\n\tfor (int i = 0; i < GetParent()->children.size(); i++) {\n\t\tGameObject* child = GetParent()->children[i];\n\t\tif (child->GetName() == GetRootBone()->name) {\n\t\t\trootBoneGO = child;\n\t\t\treturn rootBoneGO;\n\t\t}\n\t}\n\n\treturn nullptr;\n}\n\nvoid ComponentBone::GetGOFromBones()\n{\n\tif (gos_filled == false)\n\t{\n\t\tCollectGOs(App->scene->GetRoot());\n\t\tgos_filled = true;\n\t}\n\n\tif (pairs_filled == false)\n\t{\n\t\tfor (uint i = 0; i < skeleton.size(); ++i)\n\t\t{\n\t\t\tinsert_BoneToIterate(skeleton[i]);\n\t\t}\n\n\t\t\/*for (vector::iterator it = pairedgotobones.begin(); it != pairedgotobones.end();)\n\t\t{\n\t\t\tif ((*it).bones.empty() == true)\n\t\t\t\tit = pairedgotobones.erase(it);\n\n\t\t\t++it;\n\t\t}*\/\n\t\tpairs_filled = true;\n\t}\n}\n\n<|endoftext|>"} {"text":"#include \"Expression.hpp\"\n\n#include \n#include \n\n#include \n\nnamespace lm\n{\nExpression::Expression(const std::string& inputInit) : input{inputInit}\n{\n std::cout << \"contructor\" << std::endl;\n}\n\ndouble Expression::getResult()\n{ std::cout << \"get result\" << std::endl;\n std::istringstream istr(input);\n std::cout << \"after istr\" << std::endl;\n\n std::cout << \"val init\" << std::endl;\n double val1 = 0.0;\n double val2 = 0.0;\n char op = '\\0';\n std::cout << \"before >> \" << istr.str() << std::endl;\n istr >> val1;\n std::cout << \"after val1 >> \" << val1 << std::endl;\n istr >> op;\n std::cout << \"after op >> \" << op << std::endl;\n istr >> val2;\n std::cout << \"after val2 >> \" << val2 << std::endl;\n switch (op)\n {\n case '+': std::cout << \"1\" << std::endl; return val1 + val2;\n case '-': std::cout << \"2\" << std::endl; return val1 - val2;\n case '*': std::cout << \"3\" << std::endl; return val1 * val2;\n case '\/':\n\n std::cout << \"4\" << std::endl;\n if (std::fabs(val2) < epsilon)\n {\n std::cout << \"5\" << std::endl;\n throw std::runtime_error(\"division by zero\");\n }\n\n std::cout << \"6\" << std::endl;\n return val1 \/ val2;\n default:\n std::cout << \"7\" << std::endl;\n throw std::runtime_error(\"unknown operation\");\n }\n}\n}\ntravis test#include \"Expression.hpp\"\n\n#include \n#include \n\n#include \n\nnamespace lm\n{\nExpression::Expression(const std::string& inputInit) : input{inputInit}\n{\n std::cout << \"contructor\" << std::endl;\n}\n\ndouble Expression::getResult()\n{ std::cout << \"get result \" << input << std::endl;\n std::istringstream istr(input);\n std::cout << \"after istr\" << std::endl;\n\n std::cout << \"val init\" << std::endl;\n double val1 = 0.0;\n double val2 = 0.0;\n char op = '\\0';\n std::cout << \"before >> \" << istr.str() << std::endl;\n istr >> val1;\n std::cout << \"after val1 >> \" << val1 << std::endl;\n istr >> op;\n std::cout << \"after op >> \" << op << std::endl;\n istr >> val2;\n std::cout << \"after val2 >> \" << val2 << std::endl;\n switch (op)\n {\n case '+': std::cout << \"1\" << std::endl; return val1 + val2;\n case '-': std::cout << \"2\" << std::endl; return val1 - val2;\n case '*': std::cout << \"3\" << std::endl; return val1 * val2;\n case '\/':\n\n std::cout << \"4\" << std::endl;\n if (std::fabs(val2) < epsilon)\n {\n std::cout << \"5\" << std::endl;\n throw std::runtime_error(\"division by zero\");\n }\n\n std::cout << \"6\" << std::endl;\n return val1 \/ val2;\n default:\n std::cout << \"7\" << std::endl;\n throw std::runtime_error(\"unknown operation\");\n }\n}\n}\n<|endoftext|>"} {"text":"\/\/\/\n\/\/\/ @file S2_easy.cpp\n\/\/\/ @brief Calculate the contribution of the clustered easy leaves\n\/\/\/ and the sparse easy leaves in parallel using OpenMP\n\/\/\/ (Deleglise-Rivat algorithm).\n\/\/\/\n\/\/\/ Copyright (C) 2017 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#ifdef _OPENMP\n #include \n#endif\n\nusing namespace std;\nusing namespace primecount;\n\nnamespace {\n\n\/\/\/ backup to file every 60 seconds\nbool is_backup(double time)\n{\n double seconds = get_wtime() - time;\n return seconds > 60;\n}\n\ntemplate \nvoid print_resume(double percent, T x)\n{\n print_log(\"Resume from \" + backup_file());\n print_status(percent, x);\n}\n\n\/\/\/ backup to file\ntemplate \nvoid backup(J& json,\n T x,\n int64_t y,\n int64_t z,\n int threads,\n double percent,\n double time)\n{\n json[\"S2_easy\"][\"x\"] = to_string(x);\n json[\"S2_easy\"][\"y\"] = y;\n json[\"S2_easy\"][\"z\"] = z;\n json[\"S2_easy\"][\"threads\"] = threads;\n json[\"S2_easy\"][\"percent\"] = percent;\n json[\"S2_easy\"][\"seconds\"] = get_wtime() - time;\n\n store_backup(json);\n}\n\n\/\/\/ backup thread\ntemplate \nvoid backup(J& json,\n int64_t start,\n int64_t b,\n int64_t thread_id,\n T s2_easy)\n{\n string tid = \"thread\" + to_string(thread_id);\n\n json[\"S2_easy\"][\"start\"] = start;\n json[\"S2_easy\"][tid][\"b\"] = b;\n json[\"S2_easy\"][tid][\"s2_easy\"] = to_string(s2_easy);\n}\n\n\/\/\/ backup result\ntemplate \nvoid backup(J& json,\n T x,\n int64_t y,\n int64_t z,\n T s2_easy,\n double time)\n{\n json.erase(\"S2_easy\");\n\n json[\"S2_easy\"][\"x\"] = to_string(x);\n json[\"S2_easy\"][\"y\"] = y;\n json[\"S2_easy\"][\"z\"] = z;\n json[\"S2_easy\"][\"s2_easy\"] = to_string(s2_easy);\n json[\"S2_easy\"][\"percent\"] = 100;\n json[\"S2_easy\"][\"seconds\"] = get_wtime() - time;\n\n store_backup(json);\n}\n\ntemplate \nint64_t get_start(J& json,\n T x,\n int64_t y,\n int64_t z,\n int64_t start)\n{\n if (is_resume(json, \"S2_easy\", x, y, z) &&\n json[\"S2_easy\"].count(\"start\"))\n {\n start = json[\"S2_easy\"][\"start\"];\n }\n\n return start;\n}\n\ntemplate \nint get_threads(J& json,\n T x,\n int64_t y,\n int64_t z,\n int threads)\n{\n if (is_resume(json, \"S2_easy\", x, y, z) &&\n json[\"S2_easy\"].count(\"threads\"))\n {\n double percent = json[\"S2_easy\"][\"percent\"];\n int backup_threads = json[\"S2_easy\"][\"threads\"];\n threads = max(threads, backup_threads);\n print_resume(percent, x);\n }\n\n return threads;\n}\n\ntemplate \ndouble get_time(J& json,\n T x,\n int64_t y,\n int64_t z,\n double time)\n{\n if (is_resume(json, \"S2_easy\", x, y, z))\n {\n double seconds = json[\"S2_easy\"][\"seconds\"];\n time = get_wtime() - seconds;\n }\n\n return time;\n}\n\n\/\/\/ resume result\ntemplate \nbool resume(J& json,\n T x,\n int64_t y,\n int64_t z,\n T& s2_easy,\n double& time)\n{\n if (is_resume(json, \"S2_easy\", x, y, z) &&\n json[\"S2_easy\"].count(\"s2_easy\"))\n {\n double percent = json[\"S2_easy\"][\"percent\"];\n double seconds = json[\"S2_easy\"][\"seconds\"];\n\n s2_easy = calculator::eval(json[\"S2_easy\"][\"s2_easy\"]);\n time = get_wtime() - seconds;\n print_resume(percent, x);\n return true;\n }\n\n return false;\n}\n\n\/\/\/ resume thread\ntemplate \nbool resume(J& json,\n T x,\n int64_t y,\n int64_t z,\n int64_t& b,\n int thread_id,\n T& s2_easy)\n{\n bool resumed = false;\n\n #pragma omp critical (s2_easy_resume)\n if (is_resume(json, \"S2_easy\", thread_id, x, y, z))\n {\n resumed = true;\n string tid = \"thread\" + to_string(thread_id);\n b = json[\"S2_easy\"][tid][\"b\"];\n s2_easy = calculator::eval(json[\"S2_easy\"][tid][\"s2_easy\"]);\n }\n\n return resumed;\n}\n\ntemplate \nT S2_easy(T x,\n int64_t y,\n int64_t z,\n int64_t b,\n Primes& primes,\n PiTable& pi)\n{\n int64_t prime = primes[b];\n T x2 = x \/ prime;\n int64_t min_trivial = min(x2 \/ prime, y);\n int64_t min_clustered = (int64_t) isqrt(x2);\n int64_t min_sparse = z \/ prime;\n\n min_clustered = in_between(prime, min_clustered, y);\n min_sparse = in_between(prime, min_sparse, y);\n\n int64_t l = pi[min_trivial];\n int64_t pi_min_clustered = pi[min_clustered];\n int64_t pi_min_sparse = pi[min_sparse];\n T s2_easy = 0;\n\n \/\/ Find all clustered easy leaves:\n \/\/ n = primes[b] * primes[l]\n \/\/ x \/ n <= y && phi(x \/ n, b - 1) == phi(x \/ m, b - 1)\n \/\/ where phi(x \/ n, b - 1) = pi(x \/ n) - b + 2\n while (l > pi_min_clustered)\n {\n int64_t xn = (int64_t) fast_div(x2, primes[l]);\n int64_t phi_xn = pi[xn] - b + 2;\n int64_t xm = (int64_t) fast_div(x2, primes[b + phi_xn - 1]);\n int64_t l2 = pi[xm];\n s2_easy += phi_xn * (l - l2);\n l = l2;\n }\n\n \/\/ Find all sparse easy leaves:\n \/\/ n = primes[b] * primes[l]\n \/\/ x \/ n <= y && phi(x \/ n, b - 1) = pi(x \/ n) - b + 2\n for (; l > pi_min_sparse; l--)\n {\n int64_t xn = (int64_t) fast_div(x2, primes[l]);\n s2_easy += pi[xn] - b + 2;\n }\n\n return s2_easy;\n}\n\n\/\/\/ Calculate the contribution of the clustered easy leaves\n\/\/\/ and the sparse easy leaves.\n\/\/\/ @param T either int64_t or uint128_t.\n\/\/\/\ntemplate \nT S2_easy_OpenMP(T x,\n int64_t y,\n int64_t z,\n int64_t c,\n Primes& primes,\n int threads,\n double& time)\n{\n T s2 = 0;\n auto json = load_backup();\n auto copy = json;\n\n if (resume(json, x, y, z, s2, time))\n return s2;\n\n if (!is_resume(json, \"S2_easy\", x, y, z))\n json.erase(\"S2_easy\");\n\n PiTable pi(y);\n S2Status status(x);\n double backup_time = get_wtime();\n time = get_time(json, x, y, z, time);\n\n int64_t x13 = iroot<3>(x);\n int64_t pi_x13 = pi[x13];\n int64_t pi_sqrty = pi[isqrt(y)];\n int64_t start = max(c, pi_sqrty) + 1;\n start = get_start(json, x, y, z, start);\n\n int64_t thread_threshold = 1000;\n threads = ideal_num_threads(threads, x13, thread_threshold);\n threads = get_threads(json, x, y, z, threads);\n\n #pragma omp parallel for \\\n num_threads(threads) reduction(+: s2)\n for (int i = 0; i < threads; i++)\n {\n T s2_easy = 0;\n int64_t b = 0;\n\n if (resume(copy, x, y, z, b, i, s2_easy))\n s2_easy += S2_easy(x, y, z, b, primes, pi);\n\n while (true)\n {\n if (is_print())\n status.print(b, pi_x13);\n\n #pragma omp critical (s2_easy_backup)\n {\n b = start++;\n\n backup(json, start, b, i, s2_easy);\n\n if (is_backup(backup_time))\n {\n double percent = status.getPercent(start, pi_x13, start, pi_x13);\n backup(json, x, y, z, threads, percent, time);\n backup_time = get_wtime();\n }\n }\n\n if (b > pi_x13)\n break;\n\n s2_easy += S2_easy(x, y, z, b, primes, pi);\n }\n\n s2 += s2_easy;\n }\n\n backup(json, x, y, z, s2, time);\n\n return s2;\n}\n\n} \/\/ namespace\n\nnamespace primecount {\n\nint64_t S2_easy(int64_t x,\n int64_t y,\n int64_t z,\n int64_t c,\n int threads)\n{\n#ifdef HAVE_MPI\n if (mpi_num_procs() > 1)\n return S2_easy_mpi(x, y, z, c, threads);\n#endif\n\n print_log(\"\");\n print_log(\"=== S2_easy(x, y) ===\");\n print_log(\"Computation of the easy special leaves\");\n print_log(x, y, c, threads);\n\n double time = get_wtime();\n auto primes = generate_primes(y);\n int64_t s2_easy = S2_easy_OpenMP((intfast64_t) x, y, z, c, primes, threads, time);\n\n print_log(\"S2_easy\", s2_easy, time);\n return s2_easy;\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t S2_easy(int128_t x,\n int64_t y,\n int64_t z,\n int64_t c,\n int threads)\n{\n#ifdef HAVE_MPI\n if (mpi_num_procs() > 1)\n return S2_easy_mpi(x, y, z, c, threads);\n#endif\n\n print_log(\"\");\n print_log(\"=== S2_easy(x, y) ===\");\n print_log(\"Computation of the easy special leaves\");\n print_log(x, y, c, threads);\n\n int128_t s2_easy;\n double time = get_wtime();\n\n \/\/ uses less memory\n if (y <= numeric_limits::max())\n {\n auto primes = generate_primes(y);\n s2_easy = S2_easy_OpenMP((intfast128_t) x, y, z, c, primes, threads, time);\n }\n else\n {\n auto primes = generate_primes(y);\n s2_easy = S2_easy_OpenMP((intfast128_t) x, y, z, c, primes, threads, time);\n }\n\n print_log(\"S2_easy\", s2_easy, time);\n return s2_easy;\n}\n\n#endif\n\n} \/\/ namespace\nRemove critical section\/\/\/\n\/\/\/ @file S2_easy.cpp\n\/\/\/ @brief Calculate the contribution of the clustered easy leaves\n\/\/\/ and the sparse easy leaves in parallel using OpenMP\n\/\/\/ (Deleglise-Rivat algorithm).\n\/\/\/\n\/\/\/ Copyright (C) 2017 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#ifdef _OPENMP\n #include \n#endif\n\nusing namespace std;\nusing namespace primecount;\n\nnamespace {\n\n\/\/\/ backup to file every 60 seconds\nbool is_backup(double time)\n{\n double seconds = get_wtime() - time;\n return seconds > 60;\n}\n\ntemplate \nvoid print_resume(double percent, T x)\n{\n print_log(\"Resume from \" + backup_file());\n print_status(percent, x);\n}\n\n\/\/\/ backup to file\ntemplate \nvoid backup(J& json,\n T x,\n int64_t y,\n int64_t z,\n int threads,\n double percent,\n double time)\n{\n json[\"S2_easy\"][\"x\"] = to_string(x);\n json[\"S2_easy\"][\"y\"] = y;\n json[\"S2_easy\"][\"z\"] = z;\n json[\"S2_easy\"][\"threads\"] = threads;\n json[\"S2_easy\"][\"percent\"] = percent;\n json[\"S2_easy\"][\"seconds\"] = get_wtime() - time;\n\n store_backup(json);\n}\n\n\/\/\/ backup thread\ntemplate \nvoid backup(J& json,\n int64_t start,\n int64_t b,\n int64_t thread_id,\n T s2_easy)\n{\n string tid = \"thread\" + to_string(thread_id);\n\n json[\"S2_easy\"][\"start\"] = start;\n json[\"S2_easy\"][tid][\"b\"] = b;\n json[\"S2_easy\"][tid][\"s2_easy\"] = to_string(s2_easy);\n}\n\n\/\/\/ backup result\ntemplate \nvoid backup(J& json,\n T x,\n int64_t y,\n int64_t z,\n T s2_easy,\n double time)\n{\n json.erase(\"S2_easy\");\n\n json[\"S2_easy\"][\"x\"] = to_string(x);\n json[\"S2_easy\"][\"y\"] = y;\n json[\"S2_easy\"][\"z\"] = z;\n json[\"S2_easy\"][\"s2_easy\"] = to_string(s2_easy);\n json[\"S2_easy\"][\"percent\"] = 100;\n json[\"S2_easy\"][\"seconds\"] = get_wtime() - time;\n\n store_backup(json);\n}\n\ntemplate \nint64_t get_start(J& json,\n T x,\n int64_t y,\n int64_t z,\n int64_t start)\n{\n if (is_resume(json, \"S2_easy\", x, y, z) &&\n json[\"S2_easy\"].count(\"start\"))\n {\n start = json[\"S2_easy\"][\"start\"];\n }\n\n return start;\n}\n\ntemplate \nint get_threads(J& json,\n T x,\n int64_t y,\n int64_t z,\n int threads)\n{\n if (is_resume(json, \"S2_easy\", x, y, z) &&\n json[\"S2_easy\"].count(\"threads\"))\n {\n double percent = json[\"S2_easy\"][\"percent\"];\n int backup_threads = json[\"S2_easy\"][\"threads\"];\n threads = max(threads, backup_threads);\n print_resume(percent, x);\n }\n\n return threads;\n}\n\ntemplate \ndouble get_time(J& json,\n T x,\n int64_t y,\n int64_t z,\n double time)\n{\n if (is_resume(json, \"S2_easy\", x, y, z))\n {\n double seconds = json[\"S2_easy\"][\"seconds\"];\n time = get_wtime() - seconds;\n }\n\n return time;\n}\n\n\/\/\/ resume result\ntemplate \nbool resume(J& json,\n T x,\n int64_t y,\n int64_t z,\n T& s2_easy,\n double& time)\n{\n if (is_resume(json, \"S2_easy\", x, y, z) &&\n json[\"S2_easy\"].count(\"s2_easy\"))\n {\n double percent = json[\"S2_easy\"][\"percent\"];\n double seconds = json[\"S2_easy\"][\"seconds\"];\n\n s2_easy = calculator::eval(json[\"S2_easy\"][\"s2_easy\"]);\n time = get_wtime() - seconds;\n print_resume(percent, x);\n return true;\n }\n\n return false;\n}\n\n\/\/\/ resume thread\ntemplate \nbool resume(J& json,\n T x,\n int64_t y,\n int64_t z,\n int64_t& b,\n int thread_id,\n T& s2_easy)\n{\n bool resumed = false;\n\n if (is_resume(json, \"S2_easy\", thread_id, x, y, z))\n {\n resumed = true;\n string tid = \"thread\" + to_string(thread_id);\n b = json[\"S2_easy\"][tid][\"b\"];\n s2_easy = calculator::eval(json[\"S2_easy\"][tid][\"s2_easy\"]);\n }\n\n return resumed;\n}\n\ntemplate \nT S2_easy(T x,\n int64_t y,\n int64_t z,\n int64_t b,\n Primes& primes,\n PiTable& pi)\n{\n int64_t prime = primes[b];\n T x2 = x \/ prime;\n int64_t min_trivial = min(x2 \/ prime, y);\n int64_t min_clustered = (int64_t) isqrt(x2);\n int64_t min_sparse = z \/ prime;\n\n min_clustered = in_between(prime, min_clustered, y);\n min_sparse = in_between(prime, min_sparse, y);\n\n int64_t l = pi[min_trivial];\n int64_t pi_min_clustered = pi[min_clustered];\n int64_t pi_min_sparse = pi[min_sparse];\n T s2_easy = 0;\n\n \/\/ Find all clustered easy leaves:\n \/\/ n = primes[b] * primes[l]\n \/\/ x \/ n <= y && phi(x \/ n, b - 1) == phi(x \/ m, b - 1)\n \/\/ where phi(x \/ n, b - 1) = pi(x \/ n) - b + 2\n while (l > pi_min_clustered)\n {\n int64_t xn = (int64_t) fast_div(x2, primes[l]);\n int64_t phi_xn = pi[xn] - b + 2;\n int64_t xm = (int64_t) fast_div(x2, primes[b + phi_xn - 1]);\n int64_t l2 = pi[xm];\n s2_easy += phi_xn * (l - l2);\n l = l2;\n }\n\n \/\/ Find all sparse easy leaves:\n \/\/ n = primes[b] * primes[l]\n \/\/ x \/ n <= y && phi(x \/ n, b - 1) = pi(x \/ n) - b + 2\n for (; l > pi_min_sparse; l--)\n {\n int64_t xn = (int64_t) fast_div(x2, primes[l]);\n s2_easy += pi[xn] - b + 2;\n }\n\n return s2_easy;\n}\n\n\/\/\/ Calculate the contribution of the clustered easy leaves\n\/\/\/ and the sparse easy leaves.\n\/\/\/ @param T either int64_t or uint128_t.\n\/\/\/\ntemplate \nT S2_easy_OpenMP(T x,\n int64_t y,\n int64_t z,\n int64_t c,\n Primes& primes,\n int threads,\n double& time)\n{\n T s2 = 0;\n auto json = load_backup();\n auto copy = json;\n\n if (resume(json, x, y, z, s2, time))\n return s2;\n\n if (!is_resume(json, \"S2_easy\", x, y, z))\n json.erase(\"S2_easy\");\n\n PiTable pi(y);\n S2Status status(x);\n double backup_time = get_wtime();\n time = get_time(json, x, y, z, time);\n\n int64_t x13 = iroot<3>(x);\n int64_t pi_x13 = pi[x13];\n int64_t pi_sqrty = pi[isqrt(y)];\n int64_t start = max(c, pi_sqrty) + 1;\n start = get_start(json, x, y, z, start);\n\n int64_t thread_threshold = 1000;\n threads = ideal_num_threads(threads, x13, thread_threshold);\n threads = get_threads(json, x, y, z, threads);\n\n #pragma omp parallel for \\\n num_threads(threads) reduction(+: s2)\n for (int i = 0; i < threads; i++)\n {\n T s2_easy = 0;\n int64_t b = 0;\n\n if (resume(copy, x, y, z, b, i, s2_easy))\n s2_easy += S2_easy(x, y, z, b, primes, pi);\n\n while (true)\n {\n if (is_print())\n status.print(b, pi_x13);\n\n #pragma omp critical (s2_easy)\n {\n b = start++;\n\n backup(json, start, b, i, s2_easy);\n\n if (is_backup(backup_time))\n {\n double percent = status.getPercent(start, pi_x13, start, pi_x13);\n backup(json, x, y, z, threads, percent, time);\n backup_time = get_wtime();\n }\n }\n\n if (b > pi_x13)\n break;\n\n s2_easy += S2_easy(x, y, z, b, primes, pi);\n }\n\n s2 += s2_easy;\n }\n\n backup(json, x, y, z, s2, time);\n\n return s2;\n}\n\n} \/\/ namespace\n\nnamespace primecount {\n\nint64_t S2_easy(int64_t x,\n int64_t y,\n int64_t z,\n int64_t c,\n int threads)\n{\n#ifdef HAVE_MPI\n if (mpi_num_procs() > 1)\n return S2_easy_mpi(x, y, z, c, threads);\n#endif\n\n print_log(\"\");\n print_log(\"=== S2_easy(x, y) ===\");\n print_log(\"Computation of the easy special leaves\");\n print_log(x, y, c, threads);\n\n double time = get_wtime();\n auto primes = generate_primes(y);\n int64_t s2_easy = S2_easy_OpenMP((intfast64_t) x, y, z, c, primes, threads, time);\n\n print_log(\"S2_easy\", s2_easy, time);\n return s2_easy;\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t S2_easy(int128_t x,\n int64_t y,\n int64_t z,\n int64_t c,\n int threads)\n{\n#ifdef HAVE_MPI\n if (mpi_num_procs() > 1)\n return S2_easy_mpi(x, y, z, c, threads);\n#endif\n\n print_log(\"\");\n print_log(\"=== S2_easy(x, y) ===\");\n print_log(\"Computation of the easy special leaves\");\n print_log(x, y, c, threads);\n\n int128_t s2_easy;\n double time = get_wtime();\n\n \/\/ uses less memory\n if (y <= numeric_limits::max())\n {\n auto primes = generate_primes(y);\n s2_easy = S2_easy_OpenMP((intfast128_t) x, y, z, c, primes, threads, time);\n }\n else\n {\n auto primes = generate_primes(y);\n s2_easy = S2_easy_OpenMP((intfast128_t) x, y, z, c, primes, threads, time);\n }\n\n print_log(\"S2_easy\", s2_easy, time);\n return s2_easy;\n}\n\n#endif\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: worksheetbuffer.cxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \"oox\/xls\/worksheetbuffer.hxx\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"oox\/helper\/attributelist.hxx\"\n#include \"oox\/helper\/containerhelper.hxx\"\n#include \"oox\/helper\/propertyset.hxx\"\n#include \"oox\/helper\/recordinputstream.hxx\"\n#include \"oox\/core\/filterbase.hxx\"\n#include \"oox\/xls\/biffinputstream.hxx\"\n#include \"oox\/xls\/excelhandlers.hxx\"\n\nusing ::rtl::OUString;\nusing ::rtl::OUStringBuffer;\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::uno::Exception;\nusing ::com::sun::star::uno::UNO_QUERY;\nusing ::com::sun::star::uno::UNO_QUERY_THROW;\nusing ::com::sun::star::container::XIndexAccess;\nusing ::com::sun::star::container::XNameAccess;\nusing ::com::sun::star::container::XNamed;\nusing ::com::sun::star::lang::Locale;\nusing ::com::sun::star::lang::XMultiServiceFactory;\nusing ::com::sun::star::i18n::ParseResult;\nusing ::com::sun::star::sheet::XSpreadsheetDocument;\nusing ::com::sun::star::sheet::XSpreadsheets;\nusing ::com::sun::star::sheet::XSpreadsheet;\nusing ::com::sun::star::sheet::XExternalSheetName;\nusing ::com::sun::star::sheet::XSheetLinkable;\n\nnamespace oox {\nnamespace xls {\n\n\/\/ ============================================================================\n\nnamespace {\n\n\/** Returns the base file name without path and extension. *\/\nOUString lclGetBaseFileName( const OUString& rUrl )\n{\n sal_Int32 nFileNamePos = ::std::max< sal_Int32 >( rUrl.lastIndexOf( '\/' ) + 1, 0 );\n sal_Int32 nExtPos = rUrl.lastIndexOf( '.' );\n if( nExtPos <= nFileNamePos ) nExtPos = rUrl.getLength();\n return rUrl.copy( nFileNamePos, nExtPos - nFileNamePos );\n}\n\n} \/\/ namespace\n\n\/\/ ============================================================================\n\nOoxSheetInfo::OoxSheetInfo() :\n mnSheetId( -1 ),\n mnState( XML_visible )\n{\n}\n\n\/\/ ============================================================================\n\nWorksheetBuffer::WorksheetBuffer( const WorkbookHelper& rHelper ) :\n WorkbookHelper( rHelper ),\n maIsVisibleProp( CREATE_OUSTRING( \"IsVisible\" ) )\n{\n \/\/ character classification service for conversion to valid sheet names\n Reference< XMultiServiceFactory > xFactory = ::comphelper::getProcessServiceFactory();\n mxCharClass.set( xFactory->createInstance( CREATE_OUSTRING( \"com.sun.star.i18n.CharacterClassification\" ) ), UNO_QUERY );\n OSL_ENSURE( mxCharClass.is(), \"WorksheetBuffer::WorksheetBuffer - no character classification service\" );\n}\n\nvoid WorksheetBuffer::initializeSingleSheet()\n{\n OSL_ENSURE( maSheetInfos.empty(), \"WorksheetBuffer::initializeSingleSheet - invalid call\" );\n OoxSheetInfo aSheetInfo;\n aSheetInfo.maName = lclGetBaseFileName( getBaseFilter().getFileUrl() );\n insertSheet( aSheetInfo );\n}\n\nvoid WorksheetBuffer::importSheet( const AttributeList& rAttribs )\n{\n OoxSheetInfo aSheetInfo;\n aSheetInfo.maId = rAttribs.getString( R_TOKEN( id ) );\n aSheetInfo.maName = rAttribs.getString( XML_name );\n aSheetInfo.mnSheetId = rAttribs.getInteger( XML_sheetId, -1 );\n aSheetInfo.mnState = rAttribs.getToken( XML_state, XML_visible );\n insertSheet( aSheetInfo );\n}\n\nvoid WorksheetBuffer::importSheet( RecordInputStream& rStrm )\n{\n sal_Int32 nState;\n OoxSheetInfo aSheetInfo;\n rStrm >> nState >> aSheetInfo.mnSheetId >> aSheetInfo.maId >> aSheetInfo.maName;\n static const sal_Int32 spnStates[] = { XML_visible, XML_hidden, XML_veryHidden };\n aSheetInfo.mnState = STATIC_ARRAY_SELECT( spnStates, nState, XML_visible );\n insertSheet( aSheetInfo );\n}\n\nvoid WorksheetBuffer::importSheet( BiffInputStream& rStrm )\n{\n sal_uInt16 nState = 0;\n if( getBiff() >= BIFF5 )\n {\n rStrm.skip( 4 );\n rStrm >> nState;\n }\n\n OoxSheetInfo aSheetInfo;\n aSheetInfo.maName = (getBiff() == BIFF8) ?\n rStrm.readUniString( rStrm.readuInt8() ) :\n rStrm.readByteString( false, getTextEncoding() );\n static const sal_Int32 spnStates[] = { XML_visible, XML_hidden, XML_veryHidden };\n aSheetInfo.mnState = STATIC_ARRAY_SELECT( spnStates, nState, XML_visible );\n insertSheet( aSheetInfo );\n}\n\nsal_Int32 WorksheetBuffer::insertExternalSheet( const OUString& rTargetUrl, const OUString& rSheetName )\n{\n \/\/ try to find existing external sheet (needed for BIFF4W and BIFF5)\n ExternalSheetName aExtSheet( rTargetUrl, rSheetName );\n ExternalSheetMap::iterator aIt = maExternalSheets.find( aExtSheet );\n if( aIt != maExternalSheets.end() )\n return aIt->second;\n\n \/\/ create a new external sheet\n sal_Int16& rnSheet = maExternalSheets[ aExtSheet ];\n rnSheet = getTotalSheetCount();\n insertSheet( OUString(), rnSheet, false );\n\n try\n {\n Reference< XSpreadsheet > xSheet = getSheet( rnSheet );\n \/\/ use base file name as sheet name, if sheet name is missing (e.g. links to BIFF2-BIFF4 files)\n OUString aSheetName = rSheetName;\n if( aSheetName.getLength() == 0 )\n aSheetName = lclGetBaseFileName( rTargetUrl );\n \/\/ link the sheet\n Reference< XSheetLinkable > xLinkable( xSheet, UNO_QUERY_THROW );\n xLinkable->link( rTargetUrl, aSheetName, OUString(), OUString(), ::com::sun::star::sheet::SheetLinkMode_VALUE );\n \/\/ set the special external sheet name\n Reference< XExternalSheetName > xSheetName( xSheet, UNO_QUERY_THROW );\n xSheetName->setExternalName( xLinkable->getLinkUrl(), xLinkable->getLinkSheetName() );\n }\n catch( Exception& )\n {\n }\n\n \/\/ return sheet index\n return rnSheet;\n}\n\nsal_Int32 WorksheetBuffer::getInternalSheetCount() const\n{\n return static_cast< sal_Int32 >( maSheetInfos.size() );\n}\n\nOUString WorksheetBuffer::getSheetRelId( sal_Int32 nSheet ) const\n{\n OUString aRelId;\n if( const OoxSheetInfo* pInfo = getSheetInfo( nSheet ) )\n aRelId = pInfo->maId;\n return aRelId;\n}\n\nOUString WorksheetBuffer::getFinalSheetName( sal_Int32 nSheet ) const\n{\n OUString aName;\n if( const OoxSheetInfo* pInfo = getSheetInfo( nSheet ) )\n aName = pInfo->maFinalName;\n return aName;\n}\n\nOUString WorksheetBuffer::getFinalSheetName( const OUString& rName ) const\n{\n for( SheetInfoVec::const_iterator aIt = maSheetInfos.begin(), aEnd = maSheetInfos.end(); aIt != aEnd; ++aIt )\n \/\/ TODO: handle encoded characters\n if( aIt->maName.equalsIgnoreAsciiCase( rName ) )\n return aIt->maFinalName;\n return OUString();\n}\n\nsal_Int32 WorksheetBuffer::getFinalSheetIndex( const OUString& rName ) const\n{\n for( SheetInfoVec::const_iterator aIt = maSheetInfos.begin(), aEnd = maSheetInfos.end(); aIt != aEnd; ++aIt )\n \/\/ TODO: handle encoded characters\n if( aIt->maName.equalsIgnoreAsciiCase( rName ) )\n return static_cast< sal_Int32 >( aIt - maSheetInfos.begin() );\n return -1;\n}\n\n\/\/ private --------------------------------------------------------------------\n\nsal_Int16 WorksheetBuffer::getTotalSheetCount() const\n{\n try\n {\n Reference< XIndexAccess > xSheetsIA( getDocument()->getSheets(), UNO_QUERY_THROW );\n return static_cast< sal_Int16 >( xSheetsIA->getCount() );\n }\n catch( Exception& )\n {\n OSL_ENSURE( false, \"WorksheetBuffer::getTotalSheetCount - cannot get sheet count\" );\n }\n return 1;\n}\n\nconst OoxSheetInfo* WorksheetBuffer::getSheetInfo( sal_Int32 nSheet ) const\n{\n return ((0 <= nSheet) && (static_cast< size_t >( nSheet ) < maSheetInfos.size())) ?\n &maSheetInfos[ static_cast< size_t >( nSheet ) ] : 0;\n}\n\nOUString WorksheetBuffer::convertToValidSheetName( const OUString& rName, sal_Unicode cReplaceChar ) const\n{\n if( !mxCharClass.is() ) return rName;\n\n using namespace ::com::sun::star::i18n::KParseTokens;\n using namespace ::com::sun::star::i18n::KParseType;\n\n OUStringBuffer aFinalName( rName );\n Locale aLocale( CREATE_OUSTRING( \"en\" ), CREATE_OUSTRING( \"US\" ), OUString() );\n sal_Int32 nStartFlags = ANY_LETTER_OR_NUMBER | ASC_UNDERSCORE;\n sal_Int32 nContFlags = nStartFlags;\n OUString aStartChars;\n OUString aContChars( sal_Unicode( ' ' ) );\n sal_Int32 nStartPos = 0;\n while( nStartPos < aFinalName.getLength() )\n {\n ParseResult aRes = mxCharClass->parsePredefinedToken(\n IDENTNAME, rName, nStartPos, aLocale, nStartFlags, aStartChars, nContFlags, aContChars );\n if( aRes.EndPos < aFinalName.getLength() )\n {\n aFinalName.setCharAt( aRes.EndPos, cReplaceChar );\n nStartFlags = nContFlags;\n aStartChars = aContChars;\n }\n nStartPos = aRes.EndPos + 1;\n }\n return aFinalName.makeStringAndClear();\n}\n\nOUString WorksheetBuffer::insertSheet( const OUString& rName, sal_Int16 nSheet, bool bVisible )\n{\n OUString aFinalName = (rName.getLength() == 0) ? CREATE_OUSTRING( \"Sheet\" ) : convertToValidSheetName( rName, '_' );\n try\n {\n Reference< XSpreadsheets > xSheets( getDocument()->getSheets(), UNO_QUERY_THROW );\n Reference< XIndexAccess > xSheetsIA( xSheets, UNO_QUERY_THROW );\n Reference< XNameAccess > xSheetsNA( xSheets, UNO_QUERY_THROW );\n PropertySet aPropSet;\n if( nSheet < xSheetsIA->getCount() )\n {\n \/\/ existing sheet - try to rename\n Reference< XNamed > xSheetName( xSheetsIA->getByIndex( nSheet ), UNO_QUERY_THROW );\n if( xSheetName->getName() != aFinalName )\n {\n aFinalName = ContainerHelper::getUnusedName( xSheetsNA, aFinalName, ' ' );\n xSheetName->setName( aFinalName );\n }\n aPropSet.set( xSheetName );\n }\n else\n {\n \/\/ new sheet - insert with unused name\n aFinalName = ContainerHelper::getUnusedName( xSheetsNA, aFinalName, ' ' );\n xSheets->insertNewByName( aFinalName, nSheet );\n aPropSet.set( xSheetsIA->getByIndex( nSheet ) );\n }\n\n \/\/ sheet properties\n aPropSet.setProperty( maIsVisibleProp, bVisible );\n }\n catch( Exception& )\n {\n OSL_ENSURE( false, \"WorksheetBuffer::insertSheet - cannot insert or rename worksheet\" );\n }\n return aFinalName;\n}\n\nvoid WorksheetBuffer::insertSheet( const OoxSheetInfo& rSheetInfo )\n{\n OSL_ENSURE( maExternalSheets.empty(), \"WorksheetBuffer::insertSheet - external sheets exist already\" );\n sal_Int16 nSheet = static_cast< sal_Int16 >( maSheetInfos.size() );\n maSheetInfos.push_back( rSheetInfo );\n maSheetInfos.back().maFinalName = insertSheet( rSheetInfo.maName, nSheet, rSheetInfo.mnState == XML_visible );\n}\n\n\/\/ ============================================================================\n\n} \/\/ namespace xls\n} \/\/ namespace oox\n\nINTEGRATION: CWS xmlfilter05 (1.3.4); FILE MERGED 2008\/05\/02 11:19:28 hbrinkm 1.3.4.4: RESYNC: (1.3-1.4); FILE MERGED 2008\/04\/16 13:10:12 dr 1.3.4.3: new optional token handling, fix default rotation in 3d charts 2008\/04\/02 12:42:04 hbrinkm 1.3.4.2: merged changes from xmlfilter04 to xmlfilter05 2008\/04\/01 15:38:48 hbrinkm 1.3.4.1: 'Merged xmlfilter04'\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: worksheetbuffer.cxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \"oox\/xls\/worksheetbuffer.hxx\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"oox\/helper\/attributelist.hxx\"\n#include \"oox\/helper\/containerhelper.hxx\"\n#include \"oox\/helper\/propertyset.hxx\"\n#include \"oox\/helper\/recordinputstream.hxx\"\n#include \"oox\/core\/filterbase.hxx\"\n#include \"oox\/xls\/biffinputstream.hxx\"\n#include \"oox\/xls\/excelhandlers.hxx\"\n\nusing ::rtl::OUString;\nusing ::rtl::OUStringBuffer;\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::uno::Exception;\nusing ::com::sun::star::uno::UNO_QUERY;\nusing ::com::sun::star::uno::UNO_QUERY_THROW;\nusing ::com::sun::star::container::XIndexAccess;\nusing ::com::sun::star::container::XNameAccess;\nusing ::com::sun::star::container::XNamed;\nusing ::com::sun::star::lang::Locale;\nusing ::com::sun::star::lang::XMultiServiceFactory;\nusing ::com::sun::star::i18n::ParseResult;\nusing ::com::sun::star::sheet::XSpreadsheetDocument;\nusing ::com::sun::star::sheet::XSpreadsheets;\nusing ::com::sun::star::sheet::XSpreadsheet;\nusing ::com::sun::star::sheet::XExternalSheetName;\nusing ::com::sun::star::sheet::XSheetLinkable;\n\nnamespace oox {\nnamespace xls {\n\n\/\/ ============================================================================\n\nnamespace {\n\n\/** Returns the base file name without path and extension. *\/\nOUString lclGetBaseFileName( const OUString& rUrl )\n{\n sal_Int32 nFileNamePos = ::std::max< sal_Int32 >( rUrl.lastIndexOf( '\/' ) + 1, 0 );\n sal_Int32 nExtPos = rUrl.lastIndexOf( '.' );\n if( nExtPos <= nFileNamePos ) nExtPos = rUrl.getLength();\n return rUrl.copy( nFileNamePos, nExtPos - nFileNamePos );\n}\n\n} \/\/ namespace\n\n\/\/ ============================================================================\n\nOoxSheetInfo::OoxSheetInfo() :\n mnSheetId( -1 ),\n mnState( XML_visible )\n{\n}\n\n\/\/ ============================================================================\n\nWorksheetBuffer::WorksheetBuffer( const WorkbookHelper& rHelper ) :\n WorkbookHelper( rHelper ),\n maIsVisibleProp( CREATE_OUSTRING( \"IsVisible\" ) )\n{\n \/\/ character classification service for conversion to valid sheet names\n Reference< XMultiServiceFactory > xFactory = ::comphelper::getProcessServiceFactory();\n mxCharClass.set( xFactory->createInstance( CREATE_OUSTRING( \"com.sun.star.i18n.CharacterClassification\" ) ), UNO_QUERY );\n OSL_ENSURE( mxCharClass.is(), \"WorksheetBuffer::WorksheetBuffer - no character classification service\" );\n}\n\nvoid WorksheetBuffer::initializeSingleSheet()\n{\n OSL_ENSURE( maSheetInfos.empty(), \"WorksheetBuffer::initializeSingleSheet - invalid call\" );\n OoxSheetInfo aSheetInfo;\n aSheetInfo.maName = lclGetBaseFileName( getBaseFilter().getFileUrl() );\n insertSheet( aSheetInfo );\n}\n\nvoid WorksheetBuffer::importSheet( const AttributeList& rAttribs )\n{\n OoxSheetInfo aSheetInfo;\n aSheetInfo.maId = rAttribs.getString( R_TOKEN( id ), OUString() );\n aSheetInfo.maName = rAttribs.getString( XML_name, OUString() );\n aSheetInfo.mnSheetId = rAttribs.getInteger( XML_sheetId, -1 );\n aSheetInfo.mnState = rAttribs.getToken( XML_state, XML_visible );\n insertSheet( aSheetInfo );\n}\n\nvoid WorksheetBuffer::importSheet( RecordInputStream& rStrm )\n{\n sal_Int32 nState;\n OoxSheetInfo aSheetInfo;\n rStrm >> nState >> aSheetInfo.mnSheetId >> aSheetInfo.maId >> aSheetInfo.maName;\n static const sal_Int32 spnStates[] = { XML_visible, XML_hidden, XML_veryHidden };\n aSheetInfo.mnState = STATIC_ARRAY_SELECT( spnStates, nState, XML_visible );\n insertSheet( aSheetInfo );\n}\n\nvoid WorksheetBuffer::importSheet( BiffInputStream& rStrm )\n{\n sal_uInt16 nState = 0;\n if( getBiff() >= BIFF5 )\n {\n rStrm.skip( 4 );\n rStrm >> nState;\n }\n\n OoxSheetInfo aSheetInfo;\n aSheetInfo.maName = (getBiff() == BIFF8) ?\n rStrm.readUniString( rStrm.readuInt8() ) :\n rStrm.readByteString( false, getTextEncoding() );\n static const sal_Int32 spnStates[] = { XML_visible, XML_hidden, XML_veryHidden };\n aSheetInfo.mnState = STATIC_ARRAY_SELECT( spnStates, nState, XML_visible );\n insertSheet( aSheetInfo );\n}\n\nsal_Int32 WorksheetBuffer::insertExternalSheet( const OUString& rTargetUrl, const OUString& rSheetName )\n{\n \/\/ try to find existing external sheet (needed for BIFF4W and BIFF5)\n ExternalSheetName aExtSheet( rTargetUrl, rSheetName );\n ExternalSheetMap::iterator aIt = maExternalSheets.find( aExtSheet );\n if( aIt != maExternalSheets.end() )\n return aIt->second;\n\n \/\/ create a new external sheet\n sal_Int16& rnSheet = maExternalSheets[ aExtSheet ];\n rnSheet = getTotalSheetCount();\n insertSheet( OUString(), rnSheet, false );\n\n try\n {\n Reference< XSpreadsheet > xSheet = getSheet( rnSheet );\n \/\/ use base file name as sheet name, if sheet name is missing (e.g. links to BIFF2-BIFF4 files)\n OUString aSheetName = rSheetName;\n if( aSheetName.getLength() == 0 )\n aSheetName = lclGetBaseFileName( rTargetUrl );\n \/\/ link the sheet\n Reference< XSheetLinkable > xLinkable( xSheet, UNO_QUERY_THROW );\n xLinkable->link( rTargetUrl, aSheetName, OUString(), OUString(), ::com::sun::star::sheet::SheetLinkMode_VALUE );\n \/\/ set the special external sheet name\n Reference< XExternalSheetName > xSheetName( xSheet, UNO_QUERY_THROW );\n xSheetName->setExternalName( xLinkable->getLinkUrl(), xLinkable->getLinkSheetName() );\n }\n catch( Exception& )\n {\n }\n\n \/\/ return sheet index\n return rnSheet;\n}\n\nsal_Int32 WorksheetBuffer::getInternalSheetCount() const\n{\n return static_cast< sal_Int32 >( maSheetInfos.size() );\n}\n\nOUString WorksheetBuffer::getSheetRelId( sal_Int32 nSheet ) const\n{\n OUString aRelId;\n if( const OoxSheetInfo* pInfo = getSheetInfo( nSheet ) )\n aRelId = pInfo->maId;\n return aRelId;\n}\n\nOUString WorksheetBuffer::getFinalSheetName( sal_Int32 nSheet ) const\n{\n OUString aName;\n if( const OoxSheetInfo* pInfo = getSheetInfo( nSheet ) )\n aName = pInfo->maFinalName;\n return aName;\n}\n\nOUString WorksheetBuffer::getFinalSheetName( const OUString& rName ) const\n{\n for( SheetInfoVec::const_iterator aIt = maSheetInfos.begin(), aEnd = maSheetInfos.end(); aIt != aEnd; ++aIt )\n \/\/ TODO: handle encoded characters\n if( aIt->maName.equalsIgnoreAsciiCase( rName ) )\n return aIt->maFinalName;\n return OUString();\n}\n\nsal_Int32 WorksheetBuffer::getFinalSheetIndex( const OUString& rName ) const\n{\n for( SheetInfoVec::const_iterator aIt = maSheetInfos.begin(), aEnd = maSheetInfos.end(); aIt != aEnd; ++aIt )\n \/\/ TODO: handle encoded characters\n if( aIt->maName.equalsIgnoreAsciiCase( rName ) )\n return static_cast< sal_Int32 >( aIt - maSheetInfos.begin() );\n return -1;\n}\n\n\/\/ private --------------------------------------------------------------------\n\nsal_Int16 WorksheetBuffer::getTotalSheetCount() const\n{\n try\n {\n Reference< XIndexAccess > xSheetsIA( getDocument()->getSheets(), UNO_QUERY_THROW );\n return static_cast< sal_Int16 >( xSheetsIA->getCount() );\n }\n catch( Exception& )\n {\n OSL_ENSURE( false, \"WorksheetBuffer::getTotalSheetCount - cannot get sheet count\" );\n }\n return 1;\n}\n\nconst OoxSheetInfo* WorksheetBuffer::getSheetInfo( sal_Int32 nSheet ) const\n{\n return ((0 <= nSheet) && (static_cast< size_t >( nSheet ) < maSheetInfos.size())) ?\n &maSheetInfos[ static_cast< size_t >( nSheet ) ] : 0;\n}\n\nOUString WorksheetBuffer::convertToValidSheetName( const OUString& rName, sal_Unicode cReplaceChar ) const\n{\n if( !mxCharClass.is() ) return rName;\n\n using namespace ::com::sun::star::i18n::KParseTokens;\n using namespace ::com::sun::star::i18n::KParseType;\n\n OUStringBuffer aFinalName( rName );\n Locale aLocale( CREATE_OUSTRING( \"en\" ), CREATE_OUSTRING( \"US\" ), OUString() );\n sal_Int32 nStartFlags = ANY_LETTER_OR_NUMBER | ASC_UNDERSCORE;\n sal_Int32 nContFlags = nStartFlags;\n OUString aStartChars;\n OUString aContChars( sal_Unicode( ' ' ) );\n sal_Int32 nStartPos = 0;\n while( nStartPos < aFinalName.getLength() )\n {\n ParseResult aRes = mxCharClass->parsePredefinedToken(\n IDENTNAME, rName, nStartPos, aLocale, nStartFlags, aStartChars, nContFlags, aContChars );\n if( aRes.EndPos < aFinalName.getLength() )\n {\n aFinalName.setCharAt( aRes.EndPos, cReplaceChar );\n nStartFlags = nContFlags;\n aStartChars = aContChars;\n }\n nStartPos = aRes.EndPos + 1;\n }\n return aFinalName.makeStringAndClear();\n}\n\nOUString WorksheetBuffer::insertSheet( const OUString& rName, sal_Int16 nSheet, bool bVisible )\n{\n OUString aFinalName = (rName.getLength() == 0) ? CREATE_OUSTRING( \"Sheet\" ) : convertToValidSheetName( rName, '_' );\n try\n {\n Reference< XSpreadsheets > xSheets( getDocument()->getSheets(), UNO_QUERY_THROW );\n Reference< XIndexAccess > xSheetsIA( xSheets, UNO_QUERY_THROW );\n Reference< XNameAccess > xSheetsNA( xSheets, UNO_QUERY_THROW );\n PropertySet aPropSet;\n if( nSheet < xSheetsIA->getCount() )\n {\n \/\/ existing sheet - try to rename\n Reference< XNamed > xSheetName( xSheetsIA->getByIndex( nSheet ), UNO_QUERY_THROW );\n if( xSheetName->getName() != aFinalName )\n {\n aFinalName = ContainerHelper::getUnusedName( xSheetsNA, aFinalName, ' ' );\n xSheetName->setName( aFinalName );\n }\n aPropSet.set( xSheetName );\n }\n else\n {\n \/\/ new sheet - insert with unused name\n aFinalName = ContainerHelper::getUnusedName( xSheetsNA, aFinalName, ' ' );\n xSheets->insertNewByName( aFinalName, nSheet );\n aPropSet.set( xSheetsIA->getByIndex( nSheet ) );\n }\n\n \/\/ sheet properties\n aPropSet.setProperty( maIsVisibleProp, bVisible );\n }\n catch( Exception& )\n {\n OSL_ENSURE( false, \"WorksheetBuffer::insertSheet - cannot insert or rename worksheet\" );\n }\n return aFinalName;\n}\n\nvoid WorksheetBuffer::insertSheet( const OoxSheetInfo& rSheetInfo )\n{\n OSL_ENSURE( maExternalSheets.empty(), \"WorksheetBuffer::insertSheet - external sheets exist already\" );\n sal_Int16 nSheet = static_cast< sal_Int16 >( maSheetInfos.size() );\n maSheetInfos.push_back( rSheetInfo );\n maSheetInfos.back().maFinalName = insertSheet( rSheetInfo.maName, nSheet, rSheetInfo.mnState == XML_visible );\n}\n\n\/\/ ============================================================================\n\n} \/\/ namespace xls\n} \/\/ namespace oox\n\n<|endoftext|>"} {"text":"\/**\n * @file WebotsController.cpp\n *\n * @author Schlotter, Benjamin<\/a>\n * @brief Interface for the Webots simulator\n *\n *\/\n\n#include \"WebotsController.h\"\n\n#include \n#include \n\n#include \"PlatformInterface\/Platform.h\"\n#include \"Tools\/Communication\/MessageQueue\/MessageQueue4Threads.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n WebotsController::WebotsController(const std::string& name)\n : \n thePlatformName(name),\n theSyncMode(false),\n theSenseTime(0),\n theStepTime(0),\n exiting(false)\n{\n \/\/ register input\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n\n \/\/ register output\n registerOutput(*this);\n registerOutput(*this);\n\n \/\/ debug\n registerInput(*this);\n registerInput(*this);\n registerOutput(*this);\n\n\n GError *err = NULL;\n socket = g_socket_new(G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_TCP, &err);\n if (err)\n {\n socket = NULL;\n std::cout << \"[WARN] Could not create a socket. This is a fatal error and communication is available. Error message:\"\n << std::endl << err->message << std::endl;\n g_error_free (err);\n }\n}\n\nWebotsController::~WebotsController()\n{\n if (socket != NULL) {\n g_socket_close(socket, NULL);\n }\n}\n\nbool WebotsController::connect(const std::string& host, int port)\n{\n if(socket == NULL) {\n return false;\n }\n\n cout << \"[WebotsController] connecting to \" << host << \":\" << port << endl;\n\n gboolean conn = false;\n GCancellable* cancellable = NULL;\n GSocketAddress* sockaddr = NULL;\n GError* conn_error = NULL;\n GError* error = NULL;\n\n GSocketConnectable* addr = g_network_address_new(host.c_str(),static_cast (port));\n GSocketAddressEnumerator* enumerator = g_socket_connectable_enumerate(addr);\n g_object_unref(addr);\n\n \/**\n * Try each sockaddr until we succeed. Record the first\n * connection error, but not any further ones (since they'll probably\n * be basically the same as the first).\n *\/\n while (!conn && (sockaddr = g_socket_address_enumerator_next(enumerator, cancellable, &error)))\n {\n conn = g_socket_connect(socket, sockaddr, NULL, conn_error ? NULL : &conn_error);\n g_object_unref(sockaddr);\n }\n g_object_unref(enumerator);\n if (conn)\n {\n \/**\n * We couldn't connect to the first address, but we succeeded\n * in connecting to a later address.\n *\/\n if (conn_error) {\n g_error_free (conn_error);\n }\n return true;\n }\n\n if(error) {\n std::cout << \"[WARN] Could not connect:\" << std::endl << error->message << std::endl;\n g_error_free(error);\n }\n\n if (conn_error) {\n std::cout << \"[WARN] Could not connect:\" << std::endl << conn_error->message << std::endl;\n g_error_free(conn_error);\n }\n\n return false;\n}\/\/end connect\n\n\nbool WebotsController::init(\n const std::string& modelPath, \n const std::string& parameterTeamName, \n unsigned int parameterTeamNumber, \n unsigned int parameterPlayerNumber, \n const std::string& server, \n unsigned int port, \n bool sync)\n{\n Platform::getInstance().init(this);\n\n Configuration& config = Platform::getInstance().theConfiguration;\n\n \/\/ set the team number first\n unsigned int teamNumber;\n if (parameterTeamNumber != 0) {\n teamNumber = parameterTeamNumber;\n } else if (config.hasKey(\"player\", \"TeamNumber\")) {\n teamNumber = config.getInt(\"player\", \"TeamNumber\");\n } else {\n teamNumber = 4;\n }\n\n \/\/ use the player number if one is given, otherwise use the number from the simulation\n unsigned int playerNumber;\n if(parameterPlayerNumber != 0) {\n playerNumber = parameterPlayerNumber;\n } else if(config.hasKey(\"player\", \"PlayerNumber\") && config.getInt(\"player\", \"PlayerNumber\") != 0) {\n playerNumber = config.getInt(\"player\", \"PlayerNumber\");\n } else {\n playerNumber = 0;\n }\n\n \/\/ use the team name if one is given, otherwise generate a name\n string teamName;\n if (!parameterTeamName.empty()) {\n teamName = parameterTeamName;\n } else if (config.hasKey(\"player\", \"TeamName\")) {\n teamName = config.getString(\"player\", \"TeamName\");\n } else {\n teamName = \"NaoTH-\" + std::to_string(teamNumber);\n }\n\n theSyncMode = sync;\n\n \/\/ connect to the simulator\n if(!connect(server, port)) {\n std::cerr << \"WebotsController could not connect\" << std::endl;\n return false;\n }\n theSocket.init(socket);\n\n \/\/ TODO: send create command to simulator\n \/\/\"rsg\/agent\/naov4\/nao.rsg\";\n theSocket << \"(scene \" << modelPath << \")\" << send;\n\n \/\/ wait the response\n getSensorData(theSensorData);\n\n std::cout << \"Sensordata: \" << theSensorData << std::endl;\n\n \/\/ initialize the teamname and number\n \/\/theSocket << \"(init (teamname \" << theGameInfo.teamName << \")(unum \" << theGameInfo.playerNumber << \"))\" << theSync << send;\n\n \n cout << \"NaoTH Simpark initialization successful: \" << teamName << \" \" << playerNumber << endl;\n\n \/\/DEBUG_REQUEST_REGISTER(\"SimSparkController:beam\", \"beam to start pose\", false);\n \/\/REGISTER_DEBUG_COMMAND(\"beam\", \"beam to given pose\", this);\n\n \/\/ hack?\n config.setInt(\"player\", \"TeamNumber\", teamNumber);\n config.setInt(\"player\", \"PlayerNumber\", playerNumber);\n config.setString(\"player\", \"TeamName\", teamName);\n\n#ifdef DEBUG\n \/\/ calculate debug communicaiton port\n unsigned short debugPort = static_cast (5000 + (teamNumber*100) + playerNumber);\n theDebugServer.start(debugPort);\n#endif\n\n theLastSenseTime = NaoTime::getNaoTimeInMilliSeconds();\n theLastActTime = theLastSenseTime;\n calculateNextActTime();\n\n return true;\n}\n\nvoid WebotsController::main()\n{\n if ( theSyncMode ) {\n singleThreadMain();\n } else {\n multiThreadsMain();\n }\n}\n\nvoid WebotsController::singleThreadMain()\n{\n cout << \"SimSpark Controller runs in single thread\" << endl;\n while ( getSensorData(theSensorData) )\n {\n \/*\n updateSensors(theSensorData);\n if ( isNewImage || isNewVirtualVision )\n {\n callCognition();\n }\n *\/\n PlatformInterface::runMotion();\n act();\n }\/\/end while\n}\/\/end main\n\n\nvoid WebotsController::motionLoop()\n{\n while ( !exiting )\n {\n std::string data;\n {\n std::unique_lock lock(theSensorDataMutex);\n theSensorDataCond.wait(lock);\n data = theSensorData;\n theSensorData = \"\";\n }\n PlatformInterface::runMotion();\n }\n}\/\/end motionLoop\n\nvoid WebotsController::cognitionLoop()\n{\n while (!exiting)\n {\n callCognition();\n }\n}\/\/end cognitionLoop\n\nvoid WebotsController::callCognition()\n{\n if(cognitionRegistered())\n {\n getCognitionInput();\n if ( !exiting )\n {\n PlatformInterface::callCognition();\n setCognitionOutput();\n }\n }\n}\/\/end callCognition\n\nvoid WebotsController::senseLoop()\n{\n while( true )\n {\n string data;\n if ( !getSensorData(data) )\n {\n break;\n }\n\n {\n std::unique_lock lock(theSensorDataMutex);\n if ( !theSensorData.empty() )\n {\n cerr<<\"[Warning] the sensor data @ \" << theLastSenseTime << \" is dropped!\"< lock(theTimeMutex);\n theTimeCond.wait(lock);\n calculateNextActTime();\n }\n\n unsigned int now = NaoTime::getNaoTimeInMilliSeconds();\n if ( theNextActTime > now )\n {\n ThreadUtil::sleep(theNextActTime - now);\n }\n\n act();\n }\n}\n\nvoid WebotsController::act()\n{\n \/\/ send command\n std::unique_lock lock(theActDataMutex);\n try {\n \/\/theSocket << theActData.str() << theSync << send;\n }\n catch(std::runtime_error& exp)\n {\n cerr<<\"can not send data to server, because of \"<senseLoop();});\n std::thread actThread = std::thread([this]{this->actLoop();});\n std::thread motionThread = std::thread([this]{this->motionLoop();});\n\n cognitionLoop();\n\n if(motionThread.joinable()) {\n motionThread.join();\n }\n if(actThread.joinable()) {\n actThread.join();\n }\n if(senseThread.joinable()) {\n senseThread.join();\n }\n}\/\/end multiThreadsMain\n\nvoid WebotsController::getMotionInput()\n{\n PlatformInterface::getMotionInput();\n\n \/*\n for (int i = 0; i < JointData::numOfJoint; i++) {\n theSensorJointData.stiffness[i] = theLastSensorJointData.stiffness[i];\n }\n theLastSensorJointData = theSensorJointData;\n *\/\n}\n\nvoid WebotsController::setMotionOutput()\n{\n PlatformInterface::setMotionOutput();\n\n \/*\n {\n std::unique_lock lock(theActDataMutex);\n say();\n autoBeam();\n jointControl();\n theActData << theSync;\n }\n *\/\n}\n\nvoid WebotsController::getCognitionInput()\n{\n \/*\n std::unique_lock lock(theCognitionInputMutex);\n while (!isNewImage && !isNewVirtualVision && !exiting )\n {\n theCognitionInputCond.wait(lock);\n }\n\n PlatformInterface::getCognitionInput();\n isNewVirtualVision = false;\n isNewImage = false;\n *\/\n}\n\nvoid WebotsController::setCognitionOutput()\n{\n std::unique_lock lock(theCognitionOutputMutex);\n PlatformInterface::setCognitionOutput();\n}\n\nbool WebotsController::getSensorData(std::string& data)\n{\n try {\n theSocket >> data;\n\n \/\/ Test the message pack parsing\n msgpack::object_handle oh = msgpack::unpack(data.data(), data.size());\n\n \/\/ deserialized object is valid during the msgpack::object_handle instance is alive.\n msgpack::object deserialized = oh.get();\n\n \/\/ msgpack::object supports ostream.\n std::cout << deserialized << std::endl;\n\n theLastSenseTime = NaoTime::getNaoTimeInMilliSeconds();\n }\n catch (std::runtime_error& exp)\n {\n cerr<<\"can not get data from server, because of \"< theNextActTime)\n {\n theNextActTime += getBasicTimeStep();\n }\n}\ncomment\/**\n * @file WebotsController.cpp\n *\n * @author Schlotter, Benjamin<\/a>\n * @brief Interface for the Webots simulator\n *\n *\/\n\n#include \"WebotsController.h\"\n\n#include \n#include \n\n#include \"PlatformInterface\/Platform.h\"\n#include \"Tools\/Communication\/MessageQueue\/MessageQueue4Threads.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n WebotsController::WebotsController(const std::string& name)\n : \n thePlatformName(name),\n theSyncMode(false),\n theSenseTime(0),\n theStepTime(0),\n exiting(false)\n{\n \/\/ register input\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n\n \/\/ register output\n registerOutput(*this);\n registerOutput(*this);\n\n \/\/ debug\n registerInput(*this);\n registerInput(*this);\n registerOutput(*this);\n\n\n GError *err = NULL;\n socket = g_socket_new(G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_TCP, &err);\n if (err)\n {\n socket = NULL;\n std::cout << \"[WARN] Could not create a socket. This is a fatal error and communication is available. Error message:\"\n << std::endl << err->message << std::endl;\n g_error_free (err);\n }\n}\n\nWebotsController::~WebotsController()\n{\n if (socket != NULL) {\n g_socket_close(socket, NULL);\n }\n}\n\nbool WebotsController::connect(const std::string& host, int port)\n{\n if(socket == NULL) {\n return false;\n }\n\n cout << \"[WebotsController] connecting to \" << host << \":\" << port << endl;\n\n gboolean conn = false;\n GCancellable* cancellable = NULL;\n GSocketAddress* sockaddr = NULL;\n GError* conn_error = NULL;\n GError* error = NULL;\n\n GSocketConnectable* addr = g_network_address_new(host.c_str(),static_cast (port));\n GSocketAddressEnumerator* enumerator = g_socket_connectable_enumerate(addr);\n g_object_unref(addr);\n\n \/**\n * Try each sockaddr until we succeed. Record the first\n * connection error, but not any further ones (since they'll probably\n * be basically the same as the first).\n *\/\n while (!conn && (sockaddr = g_socket_address_enumerator_next(enumerator, cancellable, &error)))\n {\n conn = g_socket_connect(socket, sockaddr, NULL, conn_error ? NULL : &conn_error);\n g_object_unref(sockaddr);\n }\n g_object_unref(enumerator);\n if (conn)\n {\n \/**\n * We couldn't connect to the first address, but we succeeded\n * in connecting to a later address.\n *\/\n if (conn_error) {\n g_error_free (conn_error);\n }\n return true;\n }\n\n if(error) {\n std::cout << \"[WARN] Could not connect:\" << std::endl << error->message << std::endl;\n g_error_free(error);\n }\n\n if (conn_error) {\n std::cout << \"[WARN] Could not connect:\" << std::endl << conn_error->message << std::endl;\n g_error_free(conn_error);\n }\n\n return false;\n}\/\/end connect\n\n\nbool WebotsController::init(\n const std::string& modelPath, \n const std::string& parameterTeamName, \n unsigned int parameterTeamNumber, \n unsigned int parameterPlayerNumber, \n const std::string& server, \n unsigned int port, \n bool sync)\n{\n \/\/ IMPORTANT: initialize the platform\n Platform::getInstance().init(this);\n\n\n Configuration& config = Platform::getInstance().theConfiguration;\n\n \/\/ set the team number first\n unsigned int teamNumber;\n if (parameterTeamNumber != 0) {\n teamNumber = parameterTeamNumber;\n } else if (config.hasKey(\"player\", \"TeamNumber\")) {\n teamNumber = config.getInt(\"player\", \"TeamNumber\");\n } else {\n teamNumber = 4;\n }\n\n \/\/ use the player number if one is given, otherwise use the number from the simulation\n unsigned int playerNumber;\n if(parameterPlayerNumber != 0) {\n playerNumber = parameterPlayerNumber;\n } else if(config.hasKey(\"player\", \"PlayerNumber\") && config.getInt(\"player\", \"PlayerNumber\") != 0) {\n playerNumber = config.getInt(\"player\", \"PlayerNumber\");\n } else {\n playerNumber = 0;\n }\n\n \/\/ use the team name if one is given, otherwise generate a name\n string teamName;\n if (!parameterTeamName.empty()) {\n teamName = parameterTeamName;\n } else if (config.hasKey(\"player\", \"TeamName\")) {\n teamName = config.getString(\"player\", \"TeamName\");\n } else {\n teamName = \"NaoTH-\" + std::to_string(teamNumber);\n }\n\n theSyncMode = sync;\n\n \/\/ connect to the simulator\n if(!connect(server, port)) {\n std::cerr << \"WebotsController could not connect\" << std::endl;\n return false;\n }\n theSocket.init(socket);\n\n \/\/ TODO: send create command to simulator\n \/\/\"rsg\/agent\/naov4\/nao.rsg\";\n theSocket << \"(scene \" << modelPath << \")\" << send;\n\n \/\/ wait the response\n getSensorData(theSensorData);\n\n std::cout << \"Sensordata: \" << theSensorData << std::endl;\n\n \/\/ initialize the teamname and number\n \/\/theSocket << \"(init (teamname \" << theGameInfo.teamName << \")(unum \" << theGameInfo.playerNumber << \"))\" << theSync << send;\n\n cout << \"NaoTH Simpark initialization successful: \" << teamName << \" \" << playerNumber << endl;\n\n \/\/DEBUG_REQUEST_REGISTER(\"SimSparkController:beam\", \"beam to start pose\", false);\n \/\/REGISTER_DEBUG_COMMAND(\"beam\", \"beam to given pose\", this);\n\n \/\/ hack?\n config.setInt(\"player\", \"TeamNumber\", teamNumber);\n config.setInt(\"player\", \"PlayerNumber\", playerNumber);\n config.setString(\"player\", \"TeamName\", teamName);\n\n#ifdef DEBUG\n \/\/ calculate debug communicaiton port\n unsigned short debugPort = static_cast (5000 + (teamNumber*100) + playerNumber);\n theDebugServer.start(debugPort);\n#endif\n\n theLastSenseTime = NaoTime::getNaoTimeInMilliSeconds();\n theLastActTime = theLastSenseTime;\n calculateNextActTime();\n\n return true;\n}\n\nvoid WebotsController::main()\n{\n if ( theSyncMode ) {\n singleThreadMain();\n } else {\n multiThreadsMain();\n }\n}\n\nvoid WebotsController::singleThreadMain()\n{\n cout << \"SimSpark Controller runs in single thread\" << endl;\n while ( getSensorData(theSensorData) )\n {\n \/*\n updateSensors(theSensorData);\n if ( isNewImage || isNewVirtualVision )\n {\n callCognition();\n }\n *\/\n PlatformInterface::runMotion();\n act();\n }\/\/end while\n}\/\/end main\n\n\nvoid WebotsController::motionLoop()\n{\n while ( !exiting )\n {\n std::string data;\n {\n std::unique_lock lock(theSensorDataMutex);\n theSensorDataCond.wait(lock);\n data = theSensorData;\n theSensorData = \"\";\n }\n PlatformInterface::runMotion();\n }\n}\/\/end motionLoop\n\nvoid WebotsController::cognitionLoop()\n{\n while (!exiting)\n {\n callCognition();\n }\n}\/\/end cognitionLoop\n\nvoid WebotsController::callCognition()\n{\n if(cognitionRegistered())\n {\n getCognitionInput();\n if ( !exiting )\n {\n PlatformInterface::callCognition();\n setCognitionOutput();\n }\n }\n}\/\/end callCognition\n\nvoid WebotsController::senseLoop()\n{\n while( true )\n {\n string data;\n if ( !getSensorData(data) )\n {\n break;\n }\n\n {\n std::unique_lock lock(theSensorDataMutex);\n if ( !theSensorData.empty() )\n {\n cerr<<\"[Warning] the sensor data @ \" << theLastSenseTime << \" is dropped!\"< lock(theTimeMutex);\n theTimeCond.wait(lock);\n calculateNextActTime();\n }\n\n unsigned int now = NaoTime::getNaoTimeInMilliSeconds();\n if ( theNextActTime > now )\n {\n ThreadUtil::sleep(theNextActTime - now);\n }\n\n act();\n }\n}\n\nvoid WebotsController::act()\n{\n \/\/ send command\n std::unique_lock lock(theActDataMutex);\n try {\n \/\/theSocket << theActData.str() << theSync << send;\n }\n catch(std::runtime_error& exp)\n {\n cerr<<\"can not send data to server, because of \"<senseLoop();});\n std::thread actThread = std::thread([this]{this->actLoop();});\n std::thread motionThread = std::thread([this]{this->motionLoop();});\n\n cognitionLoop();\n\n if(motionThread.joinable()) {\n motionThread.join();\n }\n if(actThread.joinable()) {\n actThread.join();\n }\n if(senseThread.joinable()) {\n senseThread.join();\n }\n}\/\/end multiThreadsMain\n\nvoid WebotsController::getMotionInput()\n{\n PlatformInterface::getMotionInput();\n\n \/*\n for (int i = 0; i < JointData::numOfJoint; i++) {\n theSensorJointData.stiffness[i] = theLastSensorJointData.stiffness[i];\n }\n theLastSensorJointData = theSensorJointData;\n *\/\n}\n\nvoid WebotsController::setMotionOutput()\n{\n PlatformInterface::setMotionOutput();\n\n \/*\n {\n std::unique_lock lock(theActDataMutex);\n say();\n autoBeam();\n jointControl();\n theActData << theSync;\n }\n *\/\n}\n\nvoid WebotsController::getCognitionInput()\n{\n \/*\n std::unique_lock lock(theCognitionInputMutex);\n while (!isNewImage && !isNewVirtualVision && !exiting )\n {\n theCognitionInputCond.wait(lock);\n }\n\n PlatformInterface::getCognitionInput();\n isNewVirtualVision = false;\n isNewImage = false;\n *\/\n}\n\nvoid WebotsController::setCognitionOutput()\n{\n std::unique_lock lock(theCognitionOutputMutex);\n PlatformInterface::setCognitionOutput();\n}\n\nbool WebotsController::getSensorData(std::string& data)\n{\n try {\n theSocket >> data;\n\n \/\/ Test the message pack parsing\n msgpack::object_handle oh = msgpack::unpack(data.data(), data.size());\n\n \/\/ deserialized object is valid during the msgpack::object_handle instance is alive.\n msgpack::object deserialized = oh.get();\n\n \/\/ msgpack::object supports ostream.\n std::cout << deserialized << std::endl;\n\n theLastSenseTime = NaoTime::getNaoTimeInMilliSeconds();\n }\n catch (std::runtime_error& exp)\n {\n cerr<<\"can not get data from server, because of \"< theNextActTime)\n {\n theNextActTime += getBasicTimeStep();\n }\n}\n<|endoftext|>"} {"text":"#include \"..\/include\/InputParams.h\"\n\n\/\/ array of all parameters\nnamespace {\n\tconst char* parameter_list[] = {\n\t\t\/\/ General\n\t\t\"outputfile\",\n\t\t\"deflection_off\",\n\t\t\"read_redshift_planes\",\n\t\t\"redshift_planes_fil\",\n\t\t\"z_lens\",\n\t\t\"z_source\",\n\t\t\n\t\t\/\/ Cosmology\n\t\t\"Omega_matter\",\n\t\t\"Omega_lambda\",\n\t\t\"Omega_baryon\",\n\t\t\"Omega_neutrino\",\n\t\t\"hubble\",\n\t\t\"sigm_8\",\n\n\t\t\/\/ Main halos type\n\t\t\"main_halo_on\",\n\t\t\"main_DM_halo_type\",\n\t\t\"main_galaxy_halo_type\",\n\n\t\t\/\/ Field halos\n\t\t\"field_off\",\n\t\t\"field_Nplanes\",\n\n\t\t\/\/ Field halos type\n\t\t\"field_internal_profile\",\n\t\t\"field_internal_profile_galaxy\",\n\t\t\"field_prof_internal_slope_pnfw\",\n\t\t\"field_prof_internal_slope_pl\",\n\n\t\t\/\/ Field halos from a mass function\n\t\t\"field_mass_func_type\",\n\t\t\"field_fov\",\n\t\t\"field_buffer\",\n\t\t\"field_min_mass\",\n\t\t\n\t\t\/\/ Field halos from an input file\n\t\t\"field_input_simulation_file\",\n\t\t\n\t\t\/\/ AnaNSIE lens halo model\n\t\t\"main_sigma\",\n\t\t\"main_core\",\n\t\t\"main_axis_ratio\",\n\t\t\"main_pos_angle\",\n\t\t\"main_NDistortionModes\",\n\t\t\"main_perturb_beta\",\n\t\t\"main_perturb_kappa\",\n\t\t\"main_perturb_gamma\",\n\t\t\"main_perturb_monopole\",\n\t\t\"main_perturb_quadrapole\",\n\t\t\"main_perturb_hexopole\",\n\t\t\"main_perturb_octopole\",\n\t\t\"main_sub_Ndensity\",\n\t\t\"main_sub_beta\",\n\t\t\"main_sub_alpha\",\n\t\t\"main_sub_Rmax\",\n\t\t\"main_sub_mass_max\",\n\t\t\"main_sub_mass_min\",\n\t\t\"main_sub_type\",\n\t\t\"main_stars_N\",\n\t\t\"main_stars_fraction\",\n\t\t\"main_stars_mass\",\n\t\t\n\t\t\/\/ MOKA lens halo model\n\t\t\"MOKA_input_file\",\n\t\t\"MOKA_input_params\",\n\t\t\"MOKA_analyze\",\n\t\t\"background_field\",\n\n\t\t\/\/ NFW lens halo model\n\t\t\"mass_nfw\"\n\t\t\"Rmax_nfw\"\n\t\t\"zlens_nfw\"\n\t\t\"concentration_nfw\"\n\n\t\t\/\/ Pseudo NFW lens halo model\n\t\t\"mass_pnfw\"\n\t\t\"Rmax_pnfw\"\n\t\t\"zlens_pnfw\"\n\t\t\"concentration_pnfw\"\n\t\t\"slope_pnfw\"\n\n\t\t\/\/ Power law lens halo model\n\t\t\"mass_pl\"\n\t\t\"Rmax_pl\"\n\t\t\"zlens_pl\"\n\t\t\"slope_pl\"\n\n\t\t\/\/ Simple NSIE lens halo model\n\t\t\"mass_nsie\"\n\n\t\t\/\/ Hernquist lens halo model\n\t\t\"mass_hernquist\"\n\t\t\"Rmax_hernquist\"\n\t\t\"zlens_hernquist\"\n\t\t\"rscale_hernquist\"\n\t\t\n\t\t\/\/ Jaffe lens halo model\n\t\t\"mass_jaffe\"\n\t\t\"Rmax_jaffe\"\n\t\t\"zlens_jaffe\"\n\t\t\"rscale_jaffe\"\n\n\t\t\/\/ MultiDark lenses\n\t\t\"MultiDark_input_file\",\n\t\t\n\t\t\/\/ Type of source SB model\n\t\t\"SourceSBType\",\n\t\t\n\t\t\/\/ Gaussian source model\n\t\t\"gauss_r2\",\n\t\t\n\t\t\/\/ BLR source model\n\t\t\"BHmass\",\n\t\t\"gamma\",\n\t\t\"inclin\",\n\t\t\"opening_ang\",\n\t\t\"r_in\",\n\t\t\"r_out\",\n\t\t\"nuo\",\n\t\t\"source_sigma\"\n\t};\n}\n\n\/\/ initialize the static set of all known labels\nconst std::set InputParams::known_labels(parameter_list, parameter_list + sizeof(parameter_list)\/sizeof(parameter_list[0]));\nAdded Uniform halo and stars parameters to input_params_list.cpp#include \"..\/include\/InputParams.h\"\n\n\/\/ array of all parameters\nnamespace {\n\tconst char* parameter_list[] = {\n\t\t\/\/ General\n\t\t\"outputfile\",\n\t\t\"deflection_off\",\n\t\t\"read_redshift_planes\",\n\t\t\"redshift_planes_fil\",\n\t\t\"z_lens\",\n\t\t\"z_source\",\n\t\t\n\t\t\/\/ Cosmology\n\t\t\"Omega_matter\",\n\t\t\"Omega_lambda\",\n\t\t\"Omega_baryon\",\n\t\t\"Omega_neutrino\",\n\t\t\"hubble\",\n\t\t\"sigm_8\",\n\n\t\t\/\/ Main halos type\n\t\t\"main_halo_on\",\n\t\t\"main_DM_halo_type\",\n\t\t\"main_galaxy_halo_type\",\n\n\t\t\/\/ Field halos\n\t\t\"field_off\",\n\t\t\"field_Nplanes\",\n\n\t\t\/\/ Field halos type\n\t\t\"field_internal_profile\",\n\t\t\"field_internal_profile_galaxy\",\n\t\t\"field_prof_internal_slope_pnfw\",\n\t\t\"field_prof_internal_slope_pl\",\n\n\t\t\/\/ Field halos from a mass function\n\t\t\"field_mass_func_type\",\n\t\t\"field_fov\",\n\t\t\"field_buffer\",\n\t\t\"field_min_mass\",\n\t\t\n\t\t\/\/ Field halos from an input file\n\t\t\"field_input_simulation_file\",\n\t\t\n\t\t\/\/ AnaNSIE lens halo model\n\t\t\"main_sigma\",\n\t\t\"main_core\",\n\t\t\"main_axis_ratio\",\n\t\t\"main_pos_angle\",\n\t\t\"main_NDistortionModes\",\n\t\t\"main_perturb_beta\",\n\t\t\"main_perturb_kappa\",\n\t\t\"main_perturb_gamma\",\n\t\t\"main_perturb_monopole\",\n\t\t\"main_perturb_quadrapole\",\n\t\t\"main_perturb_hexopole\",\n\t\t\"main_perturb_octopole\",\n\t\t\"main_sub_Ndensity\",\n\t\t\"main_sub_beta\",\n\t\t\"main_sub_alpha\",\n\t\t\"main_sub_Rmax\",\n\t\t\"main_sub_mass_max\",\n\t\t\"main_sub_mass_min\",\n\t\t\"main_sub_type\",\n\t\t\n\t\t\/\/ MOKA lens halo model\n\t\t\"MOKA_input_file\",\n\t\t\"MOKA_input_params\",\n\t\t\"MOKA_analyze\",\n\t\t\"background_field\",\n\n\t\t\/\/ NFW lens halo model\n\t\t\"mass_nfw\",\n\t\t\"Rmax_nfw\",\n\t\t\"zlens_nfw\",\n\t\t\"concentration_nfw\",\n\n\t\t\/\/ Pseudo NFW lens halo model\n\t\t\"mass_pnfw\",\n\t\t\"Rmax_pnfw\",\n\t\t\"zlens_pnfw\",\n\t\t\"concentration_pnfw\",\n\t\t\"slope_pnfw\",\n\n\t\t\/\/ Power law lens halo model\n\t\t\"mass_pl\",\n\t\t\"Rmax_pl\",\n\t\t\"zlens_pl\",\n\t\t\"slope_pl\",\n\n\t\t\/\/ Simple NSIE lens halo model\n\t\t\"mass_nsie\",\n\n\t\t\/\/ Hernquist lens halo model\n\t\t\"mass_hernquist\",\n\t\t\"Rmax_hernquist\",\n\t\t\"zlens_hernquist\",\n\t\t\"rscale_hernquist\",\n\t\t\n\t\t\/\/ Jaffe lens halo model\n\t\t\"mass_jaffe\",\n\t\t\"Rmax_jaffe\",\n\t\t\"zlens_jaffe\",\n\t\t\"rscale_jaffe\",\n\n\t\t\/\/ Uniform lens halo model\n\t\t\"zlens_uniform\",\n\t\t\"kappa_uniform\",\n\t\t\"gamma_uniform_1\",\n\t\t\"gamma_uniform_2\",\n\t\t\"zsource_reference\",\n\n\t\t\/\/ Stars\n\t\t\"main_stars_N\",\n\t\t\"main_stars_fraction\",\n\t\t\"main_stars_mass\",\n\t\t\"main_stars_mass_function\",\n\t\t\"main_stars_min_mass\",\n\t\t\"main_stars_max_mass\",\n\t\t\"main_stars_bending_point\",\n\t\t\"main_stars_lo_mass_slope\",\n\t\t\"main_stars_hi_mass_slope\",\n\n\t\t\/\/ MultiDark lenses\n\t\t\"MultiDark_input_file\",\n\t\t\n\t\t\/\/ Type of source SB model\n\t\t\"SourceSBType\",\n\t\t\n\t\t\/\/ Gaussian source model\n\t\t\"gauss_r2\",\n\t\t\n\t\t\/\/ BLR source model\n\t\t\"BHmass\",\n\t\t\"gamma\",\n\t\t\"inclin\",\n\t\t\"opening_ang\",\n\t\t\"r_in\",\n\t\t\"r_out\",\n\t\t\"nuo\",\n\t\t\"source_sigma\"\n\t};\n}\n\n\/\/ initialize the static set of all known labels\nconst std::set InputParams::known_labels(parameter_list, parameter_list + sizeof(parameter_list)\/sizeof(parameter_list[0]));\n<|endoftext|>"} {"text":"#include \n\nusing namespace std;\n\nint main()\n{\n\tcout << \"TODO\" << endl;\n\n\treturn -1;\n}\nImplement ranking system based on web, title, and pageindex.#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"IndexHelper.hpp\"\n\nusing namespace std;\n\nconst array, 3> INDEXWEIGHTS {{\n\t{16, \"titleindex\"},\n\t{4, \"webindex\"},\n\t{1, \"pageindex\"}\n}};\n\nstring getQueryString()\n{\n\tifstream input(\"query.txt\");\n\tstring query;\n\tgetline(input, query);\n\n\treturn query;\n}\n\nmap getWeightedResults(const string& query)\n{\n\tmap results;\n\tIndexHelper helper;\n\n\t\/\/ Add the base score from the index\n\tfor (const auto index : INDEXWEIGHTS) {\n\t\tfor (auto link : helper.getLinksFromIndex(query, index.second)) {\n\t\t\tresults[link] += index.first;\n\t\t}\n\t}\n\n\t\/\/ TODO: Add the link score\n\n\treturn results;\n}\n\nvector getResults(string query)\n{\n\tvector> orderedResults;\n\tfor (auto entry : getWeightedResults(query)) {\n\t\torderedResults.emplace_back(entry.second, entry.first);\n\t}\n\n\tsort(orderedResults.begin(), orderedResults.end(), greater>());\n\n\tvector results;\n\tfor (auto result : orderedResults) {\n\t\tresults.emplace_back(result.second);\n\t}\n\n\treturn results;\n\n}\n\nint main()\n{\n\tstring query = \"liacs\";\n\tfor (auto result : getResults(query)) {\n\t\tcout << result << endl;\n\t}\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkPostgreSQLQuery.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/*-------------------------------------------------------------------------\n Copyright 2008 Sandia Corporation.\n Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n the U.S. Government retains certain rights in this software.\n-------------------------------------------------------------------------*\/\n#include \"vtkPostgreSQLQuery.h\"\n\n#include \"vtkObjectFactory.h\"\n#include \"vtkPostgreSQLDatabase.h\"\n#include \"vtkStringArray.h\"\n#include \"vtkVariant.h\"\n#include \"vtkVariantArray.h\"\n#include \"vtkPostgreSQLDatabasePrivate.h\"\n\n#include \n\n#include \n\n#define BEGIN_TRANSACTION \"BEGIN TRANSACTION\"\n#define COMMIT_TRANSACTION \"COMMIT\"\n#define ROLLBACK_TRANSACTION \"ROLLBACK\"\n\nvtkCxxRevisionMacro(vtkPostgreSQLQuery, \"1.8\");\nvtkStandardNewMacro(vtkPostgreSQLQuery);\n\nclass vtkPostgreSQLQueryPrivate : public vtkObject\n{\npublic:\n static vtkPostgreSQLQueryPrivate* New();\n static vtkPostgreSQLQueryPrivate* NewForDatabase( vtkPostgreSQLDatabase* db )\n {\n vtkPostgreSQLQueryPrivate* p = vtkPostgreSQLQueryPrivate::New();\n p->SetDatabase( db );\n return p;\n }\n vtkTypeRevisionMacro(vtkPostgreSQLQueryPrivate,vtkObject);\n vtkPostgreSQLQueryPrivate()\n { \/\/ For StandardNewMacro. Do not use the default constructor!\n this->Database = 0;\n this->LastErrorText = 0;\n }\n vtkPostgreSQLQueryPrivate( vtkPostgreSQLDatabase* db )\n {\n this->Database = 0;\n this->LastErrorText = 0;\n\n assert( db );\n this->SetDatabase( db );\n }\n ~vtkPostgreSQLQueryPrivate()\n {\n this->SetDatabase( 0 );\n this->SetLastErrorText( 0 );\n }\n bool Execute( bool& active, const char* query )\n {\n if ( ! this->Database || ! this->Database->IsOpen() )\n {\n bool err = true;\n if ( this->Database )\n { \/\/ Perhaps the connection parameters were modified since the last open?\n err = this->Database->Open() ? false : true;\n }\n if ( err )\n {\n vtkErrorMacro( \"Need a valid database connection to execute query \\\"\" << query << \"\\\"\" );\n return false;\n }\n }\n\n pqxx::transaction<>* work = this->Database->Connection->Work;\n bool localWork = false; \/\/ automatically commit when done?\n try\n {\n if ( ! work )\n {\n work = new pqxx::transaction<>( this->Database->Connection->Connection, \"LocalWork\" );\n localWork = true;\n }\n this->Result = work->exec( query );\n this->NextIterator = this->Result.begin();\n this->Iterator = NextIterator;\n if ( localWork )\n {\n work->commit();\n delete work;\n }\n active = 1;\n }\n catch ( vtkstd::exception& e )\n {\n active = 0;\n this->SetLastErrorText( e.what() );\n return false;\n }\n this->SetLastErrorText( 0 );\n return true;\n }\n\n bool BeginTransaction()\n {\n if ( ! this->Database || ! this->Database->IsOpen() )\n {\n vtkErrorMacro( \"Need a valid database connection to open a transaction\" );\n return false;\n }\n return this->Database->Connection->BeginTransaction();\n }\n\n bool CommitTransaction()\n {\n if ( ! this->Database || ! this->Database->IsOpen() )\n {\n vtkErrorMacro( \"Need a valid database connection to commit a transaction\" );\n return false;\n }\n return this->Database->Connection->CommitTransaction();\n }\n\n bool RollbackTransaction()\n {\n if ( ! this->Database || ! this->Database->IsOpen() )\n {\n vtkErrorMacro( \"Need a valid database connection to rollback a transaction\" );\n return false;\n }\n return this->Database->Connection->RollbackTransaction();\n }\n\n int GetNumberOfFields()\n {\n return this->Result.columns();\n }\n\n const char* GetFieldName( int column )\n {\n return this->Result.column_name( column );\n }\n\n int GetFieldType( int column )\n {\n pqxx::oid ctyp = this->Result.column_type( column );\n return this->Database->Connection->GetVTKTypeFromOID( ctyp );\n }\n\n bool NextRow()\n {\n this->Iterator = this->NextIterator;\n ++ this->NextIterator;\n return this->Iterator != this->Result.end();\n }\n\n vtkVariant DataValue( int column )\n {\n int colType = this->GetFieldType( column );\n switch ( colType )\n {\n case VTK_VOID:\n return vtkVariant();\n case VTK_BIT:\n {\n bool val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n case VTK_CHAR:\n case VTK_SIGNED_CHAR:\n {\n int val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( (char)val );\n }\n case VTK_UNSIGNED_CHAR:\n {\n int val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( (unsigned char)val );\n }\n case VTK_SHORT:\n {\n short val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n case VTK_UNSIGNED_SHORT:\n {\n unsigned short val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n case VTK_INT:\n {\n int val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n case VTK_UNSIGNED_INT:\n {\n unsigned int val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n case VTK_LONG:\n {\n long val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n case VTK_UNSIGNED_LONG:\n {\n unsigned long val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n#ifdef VTK_TYPE_USE_LONG_LONG\n case VTK_LONG_LONG:\n {\n long long val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n case VTK_UNSIGNED_LONG_LONG:\n {\n unsigned long long val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n#endif \/\/ VTK_TYPE_USE_LONG_LONG\n case VTK_FLOAT:\n {\n float val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n case VTK_DOUBLE:\n {\n double val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n case VTK_ID_TYPE:\n {\n vtkIdType val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n case VTK_STRING:\n {\n vtkstd::string val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n }\n return vtkVariant();\n }\n\n\n vtkSetObjectMacro(Database,vtkPostgreSQLDatabase);\n vtkSetStringMacro(LastErrorText);\n\n vtkPostgreSQLDatabase* Database;\n pqxx::result Result;\n pqxx::result::const_iterator Iterator;\n pqxx::result::const_iterator NextIterator;\n char* LastErrorText;\n};\n\nvtkStandardNewMacro(vtkPostgreSQLQueryPrivate);\nvtkCxxRevisionMacro(vtkPostgreSQLQueryPrivate, \"1.8\");\n\n\/\/ ----------------------------------------------------------------------\nvtkPostgreSQLQuery::vtkPostgreSQLQuery() \n{\n this->Transactor = 0;\n}\n\n\/\/ ----------------------------------------------------------------------\nvtkPostgreSQLQuery::~vtkPostgreSQLQuery()\n{\n if ( this->Transactor )\n {\n this->Transactor->Delete();\n }\n}\n\n\/\/ ----------------------------------------------------------------------\nvoid vtkPostgreSQLQuery::PrintSelf( ostream& os, vtkIndent indent )\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"Transactor: \";\n if ( this->Transactor )\n {\n os << this->Transactor << \"\\n\";\n }\n else\n {\n os << \"(null)\\n\";\n }\n}\n\n\/\/ ----------------------------------------------------------------------\nbool vtkPostgreSQLQuery::Execute()\n{\n if ( this->Query == 0 )\n {\n vtkErrorMacro( \"Cannot execute before a query has been set.\" );\n return false;\n }\n\n vtkPostgreSQLDatabase* db = vtkPostgreSQLDatabase::SafeDownCast( this->Database );\n assert( db );\n\n if ( this->Transactor && this->Transactor->Database != db )\n {\n this->Active = 0;\n \/\/ Delete any transactor not attached to the current database.\n this->Transactor->Delete();\n this->Transactor = 0;\n }\n\n if ( ! this->Transactor )\n {\n if ( ! db )\n {\n vtkErrorMacro( \"No database on which to execute the query.\" );\n return false;\n }\n this->Transactor = vtkPostgreSQLQueryPrivate::NewForDatabase( db );\n }\n\n return this->Transactor->Execute( this->Active, this->Query );\n}\n\n\/\/ ----------------------------------------------------------------------\nint vtkPostgreSQLQuery::GetNumberOfFields()\n{\n if ( ! this->Active || ! this->Transactor )\n {\n vtkErrorMacro( \"Query is not active!\" );\n return 0;\n }\n\n return this->Transactor->GetNumberOfFields();\n}\n\n\/\/ ----------------------------------------------------------------------\nconst char* vtkPostgreSQLQuery::GetFieldName( int column )\n{\n if ( ! this->Active || ! this->Transactor )\n {\n vtkErrorMacro( \"Query is not active!\" );\n return 0;\n }\n else if ( column < 0 || column >= this->Transactor->GetNumberOfFields() )\n {\n vtkErrorMacro( \"Illegal field index \" << column );\n return 0;\n }\n return this->Transactor->GetFieldName( column );\n}\n\n\/\/ ----------------------------------------------------------------------\nint vtkPostgreSQLQuery::GetFieldType( int column )\n{\n if ( ! this->Active || ! this->Transactor )\n {\n vtkErrorMacro( \"Query is not active!\" );\n return -1;\n }\n else if ( column < 0 || column >= this->Transactor->GetNumberOfFields() )\n {\n vtkErrorMacro( \"Illegal field index \" << column );\n return -1;\n }\n return this->Transactor->GetFieldType( column );\n}\n\n\/\/ ----------------------------------------------------------------------\nbool vtkPostgreSQLQuery::NextRow()\n{\n if ( ! this->IsActive() || ! this->Transactor )\n {\n vtkErrorMacro( \"Query is not active!\" );\n return false;\n }\n\n return this->Transactor->NextRow();\n}\n\n\/\/ ----------------------------------------------------------------------\nvtkVariant vtkPostgreSQLQuery::DataValue( vtkIdType column )\n{\n if ( this->IsActive() == false )\n {\n vtkWarningMacro( \"DataValue() called on inactive query\" );\n return vtkVariant();\n }\n else if ( column < 0 || column >= this->GetNumberOfFields() )\n {\n vtkWarningMacro( \"DataValue() called with out-of-range column index \" << column );\n return vtkVariant();\n }\n\n return this->Transactor->DataValue( column );\n}\n\n\/\/ ----------------------------------------------------------------------\nconst char * vtkPostgreSQLQuery::GetLastErrorText()\n{\n if ( ! this->Database )\n {\n return \"No database\";\n }\n if ( ! this->Transactor )\n {\n return \"No active query\";\n }\n return this->Transactor->LastErrorText;\n}\n\nvtkStdString vtkPostgreSQLQuery::EscapeString( vtkStdString s, bool addSurroundingQuotes )\n{\n vtkStdString retval;\n if ( addSurroundingQuotes )\n {\n retval = \"'\";\n }\n\n vtkPostgreSQLDatabase* db = static_cast( this->Database );\n if ( db->Connection )\n {\n if ( db->Connection->Work )\n {\n retval.append( db->Connection->Work->esc( s ) );\n }\n else \n {\n pqxx::transaction<> ework( db->Connection->Connection, \"EscapeWork\" );\n retval.append( ework.esc( s ) );\n }\n }\n else\n {\n this->Superclass::EscapeString( s, false );\n }\n\n if ( addSurroundingQuotes )\n {\n retval.append( \"'\" );\n }\n return retval;\n}\n\n\/\/ ----------------------------------------------------------------------\nbool vtkPostgreSQLQuery::HasError()\n{\n if ( ! this->Database )\n {\n return false;\n }\n if ( ! this->Transactor )\n {\n return false;\n }\n return ( this->Transactor->LastErrorText != 0 );\n}\n\n\/\/ ----------------------------------------------------------------------\nbool vtkPostgreSQLQuery::BeginTransaction()\n{\n if ( this->Transactor )\n {\n vtkErrorMacro(<<\"Cannot start a transaction. One is already in progress.\");\n return false;\n }\n\n vtkPostgreSQLDatabase* db = vtkPostgreSQLDatabase::SafeDownCast( this->Database );\n assert( db );\n\n this->Transactor = vtkPostgreSQLQueryPrivate::NewForDatabase( db );\n if ( ! this->Transactor )\n {\n vtkErrorMacro(<<\"Cannot create a new transaction.\");\n return false;\n }\n\n return this->Transactor->BeginTransaction();\n}\n \n\/\/ ----------------------------------------------------------------------\nbool vtkPostgreSQLQuery::CommitTransaction()\n{\n if ( this->Transactor )\n {\n if ( this->Transactor->CommitTransaction() )\n {\n this->Transactor->Delete();\n this->Transactor = 0;\n this->Active = false;\n return true;\n }\n \/\/ don't delete the transactor on failure... we want the error message!\n return false;\n }\n vtkErrorMacro( \"Cannot commit. There is no transaction in progress.\");\n return false;\n}\n\n\/\/ ----------------------------------------------------------------------\nbool vtkPostgreSQLQuery::RollbackTransaction()\n{\n if ( ! this->Transactor )\n {\n vtkErrorMacro(\"Cannot rollback. There is no transaction in progress.\");\n return false;\n }\n\n return this->Transactor->RollbackTransaction();\n}\n\n\/\/ ----------------------------------------------------------------------\nvoid vtkPostgreSQLQuery::SetLastErrorText( const char* msg )\n{\n if ( this->Transactor )\n {\n this->Transactor->SetLastErrorText( msg );\n }\n}\n\nBUG: in EscapeString(), append to the return value (and not only calculate) the string that is calculated by the method of the superclass.\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkPostgreSQLQuery.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/*-------------------------------------------------------------------------\n Copyright 2008 Sandia Corporation.\n Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n the U.S. Government retains certain rights in this software.\n-------------------------------------------------------------------------*\/\n#include \"vtkPostgreSQLQuery.h\"\n\n#include \"vtkObjectFactory.h\"\n#include \"vtkPostgreSQLDatabase.h\"\n#include \"vtkStringArray.h\"\n#include \"vtkVariant.h\"\n#include \"vtkVariantArray.h\"\n#include \"vtkPostgreSQLDatabasePrivate.h\"\n\n#include \n\n#include \n\n#define BEGIN_TRANSACTION \"BEGIN TRANSACTION\"\n#define COMMIT_TRANSACTION \"COMMIT\"\n#define ROLLBACK_TRANSACTION \"ROLLBACK\"\n\nvtkCxxRevisionMacro(vtkPostgreSQLQuery, \"1.9\");\nvtkStandardNewMacro(vtkPostgreSQLQuery);\n\nclass vtkPostgreSQLQueryPrivate : public vtkObject\n{\npublic:\n static vtkPostgreSQLQueryPrivate* New();\n static vtkPostgreSQLQueryPrivate* NewForDatabase( vtkPostgreSQLDatabase* db )\n {\n vtkPostgreSQLQueryPrivate* p = vtkPostgreSQLQueryPrivate::New();\n p->SetDatabase( db );\n return p;\n }\n vtkTypeRevisionMacro(vtkPostgreSQLQueryPrivate,vtkObject);\n vtkPostgreSQLQueryPrivate()\n { \/\/ For StandardNewMacro. Do not use the default constructor!\n this->Database = 0;\n this->LastErrorText = 0;\n }\n vtkPostgreSQLQueryPrivate( vtkPostgreSQLDatabase* db )\n {\n this->Database = 0;\n this->LastErrorText = 0;\n\n assert( db );\n this->SetDatabase( db );\n }\n ~vtkPostgreSQLQueryPrivate()\n {\n this->SetDatabase( 0 );\n this->SetLastErrorText( 0 );\n }\n bool Execute( bool& active, const char* query )\n {\n if ( ! this->Database || ! this->Database->IsOpen() )\n {\n bool err = true;\n if ( this->Database )\n { \/\/ Perhaps the connection parameters were modified since the last open?\n err = this->Database->Open() ? false : true;\n }\n if ( err )\n {\n vtkErrorMacro( \"Need a valid database connection to execute query \\\"\" << query << \"\\\"\" );\n return false;\n }\n }\n\n pqxx::transaction<>* work = this->Database->Connection->Work;\n bool localWork = false; \/\/ automatically commit when done?\n try\n {\n if ( ! work )\n {\n work = new pqxx::transaction<>( this->Database->Connection->Connection, \"LocalWork\" );\n localWork = true;\n }\n this->Result = work->exec( query );\n this->NextIterator = this->Result.begin();\n this->Iterator = NextIterator;\n if ( localWork )\n {\n work->commit();\n delete work;\n }\n active = 1;\n }\n catch ( vtkstd::exception& e )\n {\n active = 0;\n this->SetLastErrorText( e.what() );\n return false;\n }\n this->SetLastErrorText( 0 );\n return true;\n }\n\n bool BeginTransaction()\n {\n if ( ! this->Database || ! this->Database->IsOpen() )\n {\n vtkErrorMacro( \"Need a valid database connection to open a transaction\" );\n return false;\n }\n return this->Database->Connection->BeginTransaction();\n }\n\n bool CommitTransaction()\n {\n if ( ! this->Database || ! this->Database->IsOpen() )\n {\n vtkErrorMacro( \"Need a valid database connection to commit a transaction\" );\n return false;\n }\n return this->Database->Connection->CommitTransaction();\n }\n\n bool RollbackTransaction()\n {\n if ( ! this->Database || ! this->Database->IsOpen() )\n {\n vtkErrorMacro( \"Need a valid database connection to rollback a transaction\" );\n return false;\n }\n return this->Database->Connection->RollbackTransaction();\n }\n\n int GetNumberOfFields()\n {\n return this->Result.columns();\n }\n\n const char* GetFieldName( int column )\n {\n return this->Result.column_name( column );\n }\n\n int GetFieldType( int column )\n {\n pqxx::oid ctyp = this->Result.column_type( column );\n return this->Database->Connection->GetVTKTypeFromOID( ctyp );\n }\n\n bool NextRow()\n {\n this->Iterator = this->NextIterator;\n ++ this->NextIterator;\n return this->Iterator != this->Result.end();\n }\n\n vtkVariant DataValue( int column )\n {\n int colType = this->GetFieldType( column );\n switch ( colType )\n {\n case VTK_VOID:\n return vtkVariant();\n case VTK_BIT:\n {\n bool val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n case VTK_CHAR:\n case VTK_SIGNED_CHAR:\n {\n int val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( (char)val );\n }\n case VTK_UNSIGNED_CHAR:\n {\n int val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( (unsigned char)val );\n }\n case VTK_SHORT:\n {\n short val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n case VTK_UNSIGNED_SHORT:\n {\n unsigned short val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n case VTK_INT:\n {\n int val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n case VTK_UNSIGNED_INT:\n {\n unsigned int val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n case VTK_LONG:\n {\n long val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n case VTK_UNSIGNED_LONG:\n {\n unsigned long val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n#ifdef VTK_TYPE_USE_LONG_LONG\n case VTK_LONG_LONG:\n {\n long long val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n case VTK_UNSIGNED_LONG_LONG:\n {\n unsigned long long val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n#endif \/\/ VTK_TYPE_USE_LONG_LONG\n case VTK_FLOAT:\n {\n float val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n case VTK_DOUBLE:\n {\n double val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n case VTK_ID_TYPE:\n {\n vtkIdType val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n case VTK_STRING:\n {\n vtkstd::string val;\n if ( ! this->Iterator[column].to( val ) )\n {\n return vtkVariant();\n }\n return vtkVariant( val );\n }\n }\n return vtkVariant();\n }\n\n\n vtkSetObjectMacro(Database,vtkPostgreSQLDatabase);\n vtkSetStringMacro(LastErrorText);\n\n vtkPostgreSQLDatabase* Database;\n pqxx::result Result;\n pqxx::result::const_iterator Iterator;\n pqxx::result::const_iterator NextIterator;\n char* LastErrorText;\n};\n\nvtkStandardNewMacro(vtkPostgreSQLQueryPrivate);\nvtkCxxRevisionMacro(vtkPostgreSQLQueryPrivate, \"1.9\");\n\n\/\/ ----------------------------------------------------------------------\nvtkPostgreSQLQuery::vtkPostgreSQLQuery() \n{\n this->Transactor = 0;\n}\n\n\/\/ ----------------------------------------------------------------------\nvtkPostgreSQLQuery::~vtkPostgreSQLQuery()\n{\n if ( this->Transactor )\n {\n this->Transactor->Delete();\n }\n}\n\n\/\/ ----------------------------------------------------------------------\nvoid vtkPostgreSQLQuery::PrintSelf( ostream& os, vtkIndent indent )\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"Transactor: \";\n if ( this->Transactor )\n {\n os << this->Transactor << \"\\n\";\n }\n else\n {\n os << \"(null)\\n\";\n }\n}\n\n\/\/ ----------------------------------------------------------------------\nbool vtkPostgreSQLQuery::Execute()\n{\n if ( this->Query == 0 )\n {\n vtkErrorMacro( \"Cannot execute before a query has been set.\" );\n return false;\n }\n\n vtkPostgreSQLDatabase* db = vtkPostgreSQLDatabase::SafeDownCast( this->Database );\n assert( db );\n\n if ( this->Transactor && this->Transactor->Database != db )\n {\n this->Active = 0;\n \/\/ Delete any transactor not attached to the current database.\n this->Transactor->Delete();\n this->Transactor = 0;\n }\n\n if ( ! this->Transactor )\n {\n if ( ! db )\n {\n vtkErrorMacro( \"No database on which to execute the query.\" );\n return false;\n }\n this->Transactor = vtkPostgreSQLQueryPrivate::NewForDatabase( db );\n }\n\n return this->Transactor->Execute( this->Active, this->Query );\n}\n\n\/\/ ----------------------------------------------------------------------\nint vtkPostgreSQLQuery::GetNumberOfFields()\n{\n if ( ! this->Active || ! this->Transactor )\n {\n vtkErrorMacro( \"Query is not active!\" );\n return 0;\n }\n\n return this->Transactor->GetNumberOfFields();\n}\n\n\/\/ ----------------------------------------------------------------------\nconst char* vtkPostgreSQLQuery::GetFieldName( int column )\n{\n if ( ! this->Active || ! this->Transactor )\n {\n vtkErrorMacro( \"Query is not active!\" );\n return 0;\n }\n else if ( column < 0 || column >= this->Transactor->GetNumberOfFields() )\n {\n vtkErrorMacro( \"Illegal field index \" << column );\n return 0;\n }\n return this->Transactor->GetFieldName( column );\n}\n\n\/\/ ----------------------------------------------------------------------\nint vtkPostgreSQLQuery::GetFieldType( int column )\n{\n if ( ! this->Active || ! this->Transactor )\n {\n vtkErrorMacro( \"Query is not active!\" );\n return -1;\n }\n else if ( column < 0 || column >= this->Transactor->GetNumberOfFields() )\n {\n vtkErrorMacro( \"Illegal field index \" << column );\n return -1;\n }\n return this->Transactor->GetFieldType( column );\n}\n\n\/\/ ----------------------------------------------------------------------\nbool vtkPostgreSQLQuery::NextRow()\n{\n if ( ! this->IsActive() || ! this->Transactor )\n {\n vtkErrorMacro( \"Query is not active!\" );\n return false;\n }\n\n return this->Transactor->NextRow();\n}\n\n\/\/ ----------------------------------------------------------------------\nvtkVariant vtkPostgreSQLQuery::DataValue( vtkIdType column )\n{\n if ( this->IsActive() == false )\n {\n vtkWarningMacro( \"DataValue() called on inactive query\" );\n return vtkVariant();\n }\n else if ( column < 0 || column >= this->GetNumberOfFields() )\n {\n vtkWarningMacro( \"DataValue() called with out-of-range column index \" << column );\n return vtkVariant();\n }\n\n return this->Transactor->DataValue( column );\n}\n\n\/\/ ----------------------------------------------------------------------\nconst char * vtkPostgreSQLQuery::GetLastErrorText()\n{\n if ( ! this->Database )\n {\n return \"No database\";\n }\n if ( ! this->Transactor )\n {\n return \"No active query\";\n }\n return this->Transactor->LastErrorText;\n}\n\nvtkStdString vtkPostgreSQLQuery::EscapeString( vtkStdString s, bool addSurroundingQuotes )\n{\n vtkStdString retval;\n if ( addSurroundingQuotes )\n {\n retval = \"'\";\n }\n\n vtkPostgreSQLDatabase* db = static_cast( this->Database );\n if ( db->Connection )\n {\n if ( db->Connection->Work )\n {\n retval.append( db->Connection->Work->esc( s ) );\n }\n else \n {\n pqxx::transaction<> ework( db->Connection->Connection, \"EscapeWork\" );\n retval.append( ework.esc( s ) );\n }\n }\n else\n {\n retval.append( this->Superclass::EscapeString( s, false ) );\n }\n\n if ( addSurroundingQuotes )\n {\n retval.append( \"'\" );\n }\n\n return retval;\n}\n\n\/\/ ----------------------------------------------------------------------\nbool vtkPostgreSQLQuery::HasError()\n{\n if ( ! this->Database )\n {\n return false;\n }\n if ( ! this->Transactor )\n {\n return false;\n }\n return ( this->Transactor->LastErrorText != 0 );\n}\n\n\/\/ ----------------------------------------------------------------------\nbool vtkPostgreSQLQuery::BeginTransaction()\n{\n if ( this->Transactor )\n {\n vtkErrorMacro(<<\"Cannot start a transaction. One is already in progress.\");\n return false;\n }\n\n vtkPostgreSQLDatabase* db = vtkPostgreSQLDatabase::SafeDownCast( this->Database );\n assert( db );\n\n this->Transactor = vtkPostgreSQLQueryPrivate::NewForDatabase( db );\n if ( ! this->Transactor )\n {\n vtkErrorMacro(<<\"Cannot create a new transaction.\");\n return false;\n }\n\n return this->Transactor->BeginTransaction();\n}\n \n\/\/ ----------------------------------------------------------------------\nbool vtkPostgreSQLQuery::CommitTransaction()\n{\n if ( this->Transactor )\n {\n if ( this->Transactor->CommitTransaction() )\n {\n this->Transactor->Delete();\n this->Transactor = 0;\n this->Active = false;\n return true;\n }\n \/\/ don't delete the transactor on failure... we want the error message!\n return false;\n }\n vtkErrorMacro( \"Cannot commit. There is no transaction in progress.\");\n return false;\n}\n\n\/\/ ----------------------------------------------------------------------\nbool vtkPostgreSQLQuery::RollbackTransaction()\n{\n if ( ! this->Transactor )\n {\n vtkErrorMacro(\"Cannot rollback. There is no transaction in progress.\");\n return false;\n }\n\n return this->Transactor->RollbackTransaction();\n}\n\n\/\/ ----------------------------------------------------------------------\nvoid vtkPostgreSQLQuery::SetLastErrorText( const char* msg )\n{\n if ( this->Transactor )\n {\n this->Transactor->SetLastErrorText( msg );\n }\n}\n\n<|endoftext|>"} {"text":"\/*\n###############################################################################\n#\n# EGSnrc gui compile page\n# Copyright (C) 2015 National Research Council Canada\n#\n# This file is part of EGSnrc.\n#\n# EGSnrc is free software: you can redistribute it and\/or modify it under\n# the terms of the GNU Affero General Public License as published by the\n# Free Software Foundation, either version 3 of the License, or (at your\n# option) any later version.\n#\n# EGSnrc is distributed in the hope that it will be useful, but WITHOUT ANY\n# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for\n# more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with EGSnrc. If not, see .\n#\n###############################################################################\n#\n# Author: Iwan Kawrakow, 2003\n#\n# Contributors: Ernesto Mainegra-Hing\n#\n###############################################################################\n*\/\n\n\n#include \"egs_compile_page.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/#include \n\n#include \n\nconst QSizePolicy ignored(QSizePolicy::Ignored,QSizePolicy::Ignored);\nconst QSizePolicy preferred(QSizePolicy::Preferred,QSizePolicy::Preferred);\n\nusing namespace Qt;\n\nEGS_CompilePage::EGS_CompilePage(QWidget *parent, const char *name,\n WFlags f) : EGS_GUI_Widget(parent,name,f) { make(); }\n\nEGS_CompilePage::EGS_CompilePage(EGS_ConfigReader *cr, QWidget *parent,\n const char *name, WFlags f) : EGS_GUI_Widget(cr,parent,name,f) { make(); }\n\nvoid EGS_CompilePage::make() {\n\n \/\/ The layout of the compile widget\n QVBoxLayout *topl = new QVBoxLayout(this);\n topl->setSpacing(6); topl->setMargin(11);\n\n bg_coption = new QButtonGroup(this);\n c_option = new QGroupBox(\"coption box\",this);\n QVBoxLayout *bgl = new QVBoxLayout(c_option);bgl->setSpacing(6); bgl->setMargin(11);\n c_option->setTitle( tr(\"Target\") );\n\n QRadioButton *rb = new QRadioButton(\"opt\",c_option);\n rb->setChecked(true); bgl->addWidget(rb); the_target = 0; bg_coption->addButton(rb);\n rb = new QRadioButton(\"noopt\",c_option); bgl->addWidget(rb); bg_coption->addButton(rb);\n rb = new QRadioButton(\"debug\",c_option); bgl->addWidget(rb); bg_coption->addButton(rb);\n rb = new QRadioButton(\"clean\",c_option); bgl->addWidget(rb); bg_coption->addButton(rb);\n \/\/connect(bg_coption,SIGNAL(clicked(int)),this,SLOT(changeTarget(int)));\n\n QHBoxLayout *hl1 = new QHBoxLayout;\n hl1->addWidget(c_option);\n\n QVBoxLayout *vl1 = new QVBoxLayout;\n\n \/\/ Fortran options\n QVBoxLayout *gbl = new QVBoxLayout();gbl->setSpacing(6); gbl->setMargin(11);\n QGroupBox *gb = new QGroupBox(this); gb->setTitle( tr(\"Extra Fortran options\") );\n QHBoxLayout *hbl = new QHBoxLayout(gb);hbl->setAlignment( Qt::AlignCenter );\n extra_f_options = new QLineEdit(gb);\n hbl->addWidget(extra_f_options);\n vl1->addWidget(gb);\n \/\/ C Options\n gb = new QGroupBox(\"Extra C options\",this); gb->setTitle( tr(\"Extra C options\") );\n hbl = new QHBoxLayout(gb);hbl->setAlignment( Qt::AlignCenter );\n extra_c_options = new QLineEdit(gb);\n hbl->addWidget(extra_c_options);\n\n vl1->addWidget(gb);\n\n hl1->addLayout(vl1);\n topl->addLayout(hl1,1);\n\n hl1 = new QHBoxLayout;\n QPushButton *b = new QPushButton(\"&Go\",this);\n connect(b,SIGNAL(clicked()),this,SLOT(startCompilation()));\n hl1->addWidget(b); is_running = false; start_c = b;\n\n QSpacerItem *spacer = new QSpacerItem(20,20,QSizePolicy::Expanding,\n QSizePolicy::Minimum);\n hl1->addItem(spacer);\n \/\/b = new QPushButton(\"&Cancel\",this,\"cancel button\");\n b = new QPushButton(\"&Cancel\",this);\n connect(b,SIGNAL(clicked()),this,SLOT(stopCompilation()));\n b->setEnabled(false); hl1->addWidget(b); stop_c = b;\n\n topl->addLayout(hl1,1);\n\n \/\/c_text = new QTextEdit(this,\"compilation output\");\n c_text = new QTextEdit(this);\n QFont ctext_font( c_text->font() );\n ctext_font.setFamily( \"Courier [Adobe]\" );\n ctext_font.setPointSize( 9 );\n c_text->setFont( ctext_font );\n\n c_text->setReadOnly(true);\n \/\/c_text->hide(); d_hidden = true;\n topl->addWidget(c_text,100);\n\n c_process = new QProcess;\n connect(c_process,SIGNAL(readyReadStandardOutput()),this,SLOT(readProcessOut()));\n connect(c_process,SIGNAL(readyReadStandardError()),this,SLOT(readProcessErr()));\n connect(c_process,SIGNAL(finished(int, QProcess::ExitStatus)),\n this, SLOT(compilationFinished(int, QProcess::ExitStatus)));\n}\n\nbool EGS_CompilePage::checkExeDir() {\n QString exe_dir = egsHome() + \"bin\" + QDir::separator();\n QDir dexe(exe_dir);\n if( !dexe.exists() ) {\n#ifdef IK_DEBUG\n qDebug(\"Creating directory %s\",exe_dir.latin1());\n#endif\n if( !dexe.mkdir(exe_dir) ) return false;\n }\n exe_dir += myMachine();\n dexe.setPath(exe_dir);\n if( !dexe.exists() ) {\n#ifdef IK_DEBUG\n qDebug(\"Creating directory %s\",exe_dir.latin1());\n#endif\n if( !dexe.mkdir(exe_dir) ) return false;\n }\n return true;\n}\n\nvoid EGS_CompilePage::startCompilation() {\n#ifdef IK_DEBUG\n qDebug(\"In EGS_CompilePage::startCompilation()\\n\");\n#endif\n if ( !checkVars() ) return;\n start_c->setEnabled(false); stop_c->setEnabled(true);\n c_option->setEnabled(false);\n\n if( !checkExeDir() )\n qFatal(\"Failed to create executable directory for %s\",myMachine().toLatin1().data());\n\n QStringList args;\n \/\/c_process->clearArguments();\n \/\/c_process->addArgument(makeProgram());\n#ifdef IK_DEBUG\n qDebug(\"user code: %s\",the_user_code.toLatin1().data());\n#endif\n QString ucode = the_user_code;\n QString udir = egsHome() + ucode;\n QDir::setCurrent(udir);\n#ifdef IK_DEBUG\n qDebug(\"udir: %s\",udir.toLatin1().data());\n#endif\n \/\/QButton *b = c_option->selected();\n QAbstractButton *b = bg_coption->checkedButton();\/\/c_option->selected();\n QString bname = b->text();\/\/b->name();\n#ifdef IK_DEBUG\n qDebug(\"selected button: %s\",bname.toLatin1().data());\n#endif\n if( bname != \"opt\" ) args << bname;\/\/c_process->addArgument(bname);\n QString conf = \"EGS_CONFIG=\"; conf += egsConfiguration();\n args <addArgument(conf);\n QString ehome = \"EGS_HOME=\"; ehome += egsHome();\n args << ehome; \/\/c_process->addArgument(ehome);\n if( bname != \"clean\" ) {\n QString fopt = extra_f_options->text();\n if( !fopt.isEmpty() ) {\n \/\/QString aux=\"FCFLAGS=\\\"\";\n \/\/aux += fFlags() + \" \" + fopt + \"\\\"\";\n QString aux=\"FCFLAGS=\";\n aux += fFlags() + \" \" + fopt;\n args << aux; \/\/c_process->addArgument(aux);\n }\n QString copt = extra_c_options->text();\n if( !copt.isEmpty() ) {\n QString aux=\"C_FLAGS=\\\"\";\n aux += cFlags() + \" \" + copt + \"\\\"\";\n args << aux; \/\/c_process->addArgument(aux);\n }\n }\n#ifdef IK_DEBUG\n qDebug(\"Current directory: %s\",QDir::currentDirPath().toLatin1().data());\n#endif\n \/\/qWarning(\"Executing: <%s>\",args.join(\" \").toLatin1().data());\n c_text->setText(\"\");\n\n \/\/c_process->start();\n c_process->start(makeProgram(),args);\n if(c_process->error()==QProcess::FailedToStart) {\n c_text->insertPlainText(tr(\"Failed to execute: \")+ makeProgram() + args.join(\" \") + tr(\"!!!\"));\n }\n else{\n is_running = true; killed = false;\n }\n}\n\nvoid EGS_CompilePage::stopCompilation() {\n#ifdef IK_DEBUG\n qDebug(\"In EGS_CompilePage::stopCompilation()\\n\");\n#endif\n \/\/c_process->tryTerminate();\n c_process->kill(); killed = true;\n}\n\nvoid EGS_CompilePage::readProcessOut() {\n \/\/QByteArray a = c_process->readStdout();\n QByteArray a = c_process->readAllStandardOutput();\n c_text->insertPlainText(a);\/\/c_text->insert(a); \/\/c_text->append(a);\n}\n\nvoid EGS_CompilePage::readProcessErr() {\n \/\/QByteArray a = c_process->readStderr();\n QByteArray a = c_process->readAllStandardError();\n c_text->insertPlainText(a);\/\/c_text->insert(a); \/\/c_text->append(a);\n}\n\nvoid EGS_CompilePage::setUserCode(const QString &new_user_code) {\n#ifdef IK_DEBUG\n qDebug(\"In EGS_CompilePage::setUserCode: %s\",new_user_code.latin1());\n#endif\n the_user_code = new_user_code;\n}\n\nvoid EGS_CompilePage::sendSignals() {\n \/\/QButton *b = c_option->selected();\n \/\/QString bname = b->name();\n QAbstractButton *b = bg_coption->checkedButton();\n QString bname = b->text();\n emit targetChanged(bname);\n}\n\nvoid EGS_CompilePage::changeTarget(int id) {\n if( id == the_target ) return;\n the_target = id;\n \/\/QButton *b = c_option->selected(); QString bname = b->name();\n QAbstractButton *b = bg_coption->checkedButton();\n QString bname = b->text();\n emit targetChanged(bname);\n}\n\nvoid EGS_CompilePage::compilationFinished(int exitCode, QProcess::ExitStatus exitStatus) {\n#ifdef IK_DEBUG\n qDebug(\"In EGS_CompilePage::compilationFinished()\\n\");\n#endif\n start_c->setEnabled(true); stop_c->setEnabled(false);\n c_option->setEnabled(true);\n is_running = false;\n\n QString bname = bg_coption->checkedButton()->text();\n QString exit_code = tr(\"ExitCode = \") + QString::number(exitCode);\n c_text->append(exit_code);\n if( bname != QString(\"clean\") ) {\n if (killed)\n c_text->append(\n \"\\n\\n************************* killed *****************************\\n\\n\");\n else{\n if( exitStatus != QProcess::NormalExit)\n c_text->append(\n \"\\n\\n************************* failed *****************************\\n\\n\");\n else\n c_text->append(\n \"\\n\\n************************* finished *****************************\\n\\n\");\n }\n }\n}\nSet egs_gui compilation flags properly (#340)\/*\n###############################################################################\n#\n# EGSnrc gui compile page\n# Copyright (C) 2015 National Research Council Canada\n#\n# This file is part of EGSnrc.\n#\n# EGSnrc is free software: you can redistribute it and\/or modify it under\n# the terms of the GNU Affero General Public License as published by the\n# Free Software Foundation, either version 3 of the License, or (at your\n# option) any later version.\n#\n# EGSnrc is distributed in the hope that it will be useful, but WITHOUT ANY\n# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for\n# more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with EGSnrc. If not, see .\n#\n###############################################################################\n#\n# Author: Iwan Kawrakow, 2003\n#\n# Contributors: Ernesto Mainegra-Hing\n#\n###############################################################################\n*\/\n\n\n#include \"egs_compile_page.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/#include \n\n#include \n\nconst QSizePolicy ignored(QSizePolicy::Ignored,QSizePolicy::Ignored);\nconst QSizePolicy preferred(QSizePolicy::Preferred,QSizePolicy::Preferred);\n\nusing namespace Qt;\n\nEGS_CompilePage::EGS_CompilePage(QWidget *parent, const char *name,\n WFlags f) : EGS_GUI_Widget(parent,name,f) { make(); }\n\nEGS_CompilePage::EGS_CompilePage(EGS_ConfigReader *cr, QWidget *parent,\n const char *name, WFlags f) : EGS_GUI_Widget(cr,parent,name,f) { make(); }\n\nvoid EGS_CompilePage::make() {\n\n \/\/ The layout of the compile widget\n QVBoxLayout *topl = new QVBoxLayout(this);\n topl->setSpacing(6); topl->setMargin(11);\n\n bg_coption = new QButtonGroup(this);\n c_option = new QGroupBox(\"coption box\",this);\n QVBoxLayout *bgl = new QVBoxLayout(c_option);bgl->setSpacing(6); bgl->setMargin(11);\n c_option->setTitle( tr(\"Target\") );\n\n QRadioButton *rb = new QRadioButton(\"opt\",c_option);\n rb->setChecked(true); bgl->addWidget(rb); the_target = 0; bg_coption->addButton(rb);\n rb = new QRadioButton(\"noopt\",c_option); bgl->addWidget(rb); bg_coption->addButton(rb);\n rb = new QRadioButton(\"debug\",c_option); bgl->addWidget(rb); bg_coption->addButton(rb);\n rb = new QRadioButton(\"clean\",c_option); bgl->addWidget(rb); bg_coption->addButton(rb);\n \/\/connect(bg_coption,SIGNAL(clicked(int)),this,SLOT(changeTarget(int)));\n\n QHBoxLayout *hl1 = new QHBoxLayout;\n hl1->addWidget(c_option);\n\n QVBoxLayout *vl1 = new QVBoxLayout;\n\n \/\/ Fortran options\n QVBoxLayout *gbl = new QVBoxLayout();gbl->setSpacing(6); gbl->setMargin(11);\n QGroupBox *gb = new QGroupBox(this); gb->setTitle( tr(\"Extra Fortran options\") );\n QHBoxLayout *hbl = new QHBoxLayout(gb);hbl->setAlignment( Qt::AlignCenter );\n extra_f_options = new QLineEdit(gb);\n hbl->addWidget(extra_f_options);\n vl1->addWidget(gb);\n \/\/ C Options\n gb = new QGroupBox(\"Extra C options\",this); gb->setTitle( tr(\"Extra C options\") );\n hbl = new QHBoxLayout(gb);hbl->setAlignment( Qt::AlignCenter );\n extra_c_options = new QLineEdit(gb);\n hbl->addWidget(extra_c_options);\n\n vl1->addWidget(gb);\n\n hl1->addLayout(vl1);\n topl->addLayout(hl1,1);\n\n hl1 = new QHBoxLayout;\n QPushButton *b = new QPushButton(\"&Go\",this);\n connect(b,SIGNAL(clicked()),this,SLOT(startCompilation()));\n hl1->addWidget(b); is_running = false; start_c = b;\n\n QSpacerItem *spacer = new QSpacerItem(20,20,QSizePolicy::Expanding,\n QSizePolicy::Minimum);\n hl1->addItem(spacer);\n \/\/b = new QPushButton(\"&Cancel\",this,\"cancel button\");\n b = new QPushButton(\"&Cancel\",this);\n connect(b,SIGNAL(clicked()),this,SLOT(stopCompilation()));\n b->setEnabled(false); hl1->addWidget(b); stop_c = b;\n\n topl->addLayout(hl1,1);\n\n \/\/c_text = new QTextEdit(this,\"compilation output\");\n c_text = new QTextEdit(this);\n QFont ctext_font( c_text->font() );\n ctext_font.setFamily( \"Courier [Adobe]\" );\n ctext_font.setPointSize( 9 );\n c_text->setFont( ctext_font );\n\n c_text->setReadOnly(true);\n \/\/c_text->hide(); d_hidden = true;\n topl->addWidget(c_text,100);\n\n c_process = new QProcess;\n connect(c_process,SIGNAL(readyReadStandardOutput()),this,SLOT(readProcessOut()));\n connect(c_process,SIGNAL(readyReadStandardError()),this,SLOT(readProcessErr()));\n connect(c_process,SIGNAL(finished(int, QProcess::ExitStatus)),\n this, SLOT(compilationFinished(int, QProcess::ExitStatus)));\n}\n\nbool EGS_CompilePage::checkExeDir() {\n QString exe_dir = egsHome() + \"bin\" + QDir::separator();\n QDir dexe(exe_dir);\n if( !dexe.exists() ) {\n#ifdef IK_DEBUG\n qDebug(\"Creating directory %s\",exe_dir.latin1());\n#endif\n if( !dexe.mkdir(exe_dir) ) return false;\n }\n exe_dir += myMachine();\n dexe.setPath(exe_dir);\n if( !dexe.exists() ) {\n#ifdef IK_DEBUG\n qDebug(\"Creating directory %s\",exe_dir.latin1());\n#endif\n if( !dexe.mkdir(exe_dir) ) return false;\n }\n return true;\n}\n\nvoid EGS_CompilePage::startCompilation() {\n#ifdef IK_DEBUG\n qDebug(\"In EGS_CompilePage::startCompilation()\\n\");\n#endif\n if ( !checkVars() ) return;\n start_c->setEnabled(false); stop_c->setEnabled(true);\n c_option->setEnabled(false);\n\n if( !checkExeDir() )\n qFatal(\"Failed to create executable directory for %s\",myMachine().toLatin1().data());\n\n QStringList args;\n \/\/c_process->clearArguments();\n \/\/c_process->addArgument(makeProgram());\n#ifdef IK_DEBUG\n qDebug(\"user code: %s\",the_user_code.toLatin1().data());\n#endif\n QString ucode = the_user_code;\n QString udir = egsHome() + ucode;\n QDir::setCurrent(udir);\n#ifdef IK_DEBUG\n qDebug(\"udir: %s\",udir.toLatin1().data());\n#endif\n \/\/QButton *b = c_option->selected();\n QAbstractButton *b = bg_coption->checkedButton();\/\/c_option->selected();\n QString bname = b->text();\/\/b->name();\n#ifdef IK_DEBUG\n qDebug(\"selected button: %s\",bname.toLatin1().data());\n#endif\n if( bname != \"opt\" ){\n if( bname == \"noopt\" )\n args << \"FOPT= \" << \"opt= \";\n else if ( bname == \"debug\" )\n args << \"FOPT=-g\" << \"opt=-g\";\n else\n args << bname;\n }\n QString conf = \"EGS_CONFIG=\"; conf += egsConfiguration();\n args <addArgument(conf);\n QString ehome = \"EGS_HOME=\"; ehome += egsHome();\n args << ehome; \/\/c_process->addArgument(ehome);\n if( bname != \"clean\" ) {\n QString fopt = extra_f_options->text();\n if( !fopt.isEmpty() ) {\n \/\/QString aux=\"FCFLAGS=\\\"\";\n \/\/aux += fFlags() + \" \" + fopt + \"\\\"\";\n QString aux=\"FCFLAGS=\";\n aux += fFlags() + \" \" + fopt;\n args << aux; \/\/c_process->addArgument(aux);\n }\n QString copt = extra_c_options->text();\n if( !copt.isEmpty() ) {\n QString aux=\"C_FLAGS=\\\"\";\n aux += cFlags() + \" \" + copt + \"\\\"\";\n args << aux; \/\/c_process->addArgument(aux);\n }\n }\n#ifdef IK_DEBUG\n qDebug(\"Current directory: %s\",QDir::currentDirPath().toLatin1().data());\n#endif\n \/\/qWarning(\"Executing: <%s>\",args.join(\" \").toLatin1().data());\n c_text->setText(\"\");\n\n \/\/c_process->start();\n c_process->start(makeProgram(),args);\n if(c_process->error()==QProcess::FailedToStart) {\n c_text->insertPlainText(tr(\"Failed to execute: \")+ makeProgram() + args.join(\" \") + tr(\"!!!\"));\n }\n else{\n is_running = true; killed = false;\n }\n}\n\nvoid EGS_CompilePage::stopCompilation() {\n#ifdef IK_DEBUG\n qDebug(\"In EGS_CompilePage::stopCompilation()\\n\");\n#endif\n \/\/c_process->tryTerminate();\n c_process->kill(); killed = true;\n}\n\nvoid EGS_CompilePage::readProcessOut() {\n \/\/QByteArray a = c_process->readStdout();\n QByteArray a = c_process->readAllStandardOutput();\n c_text->insertPlainText(a);\/\/c_text->insert(a); \/\/c_text->append(a);\n}\n\nvoid EGS_CompilePage::readProcessErr() {\n \/\/QByteArray a = c_process->readStderr();\n QByteArray a = c_process->readAllStandardError();\n c_text->insertPlainText(a);\/\/c_text->insert(a); \/\/c_text->append(a);\n}\n\nvoid EGS_CompilePage::setUserCode(const QString &new_user_code) {\n#ifdef IK_DEBUG\n qDebug(\"In EGS_CompilePage::setUserCode: %s\",new_user_code.latin1());\n#endif\n the_user_code = new_user_code;\n}\n\nvoid EGS_CompilePage::sendSignals() {\n \/\/QButton *b = c_option->selected();\n \/\/QString bname = b->name();\n QAbstractButton *b = bg_coption->checkedButton();\n QString bname = b->text();\n emit targetChanged(bname);\n}\n\nvoid EGS_CompilePage::changeTarget(int id) {\n if( id == the_target ) return;\n the_target = id;\n \/\/QButton *b = c_option->selected(); QString bname = b->name();\n QAbstractButton *b = bg_coption->checkedButton();\n QString bname = b->text();\n emit targetChanged(bname);\n}\n\nvoid EGS_CompilePage::compilationFinished(int exitCode, QProcess::ExitStatus exitStatus) {\n#ifdef IK_DEBUG\n qDebug(\"In EGS_CompilePage::compilationFinished()\\n\");\n#endif\n start_c->setEnabled(true); stop_c->setEnabled(false);\n c_option->setEnabled(true);\n is_running = false;\n\n QString bname = bg_coption->checkedButton()->text();\n QString exit_code = tr(\"ExitCode = \") + QString::number(exitCode);\n c_text->append(exit_code);\n if( bname != QString(\"clean\") ) {\n if (killed)\n c_text->append(\n \"\\n\\n************************* killed *****************************\\n\\n\");\n else{\n if( exitStatus != QProcess::NormalExit)\n c_text->append(\n \"\\n\\n************************* failed *****************************\\n\\n\");\n else\n c_text->append(\n \"\\n\\n************************* finished *****************************\\n\\n\");\n }\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \"immintrin.h\"\n\n#include \"\/home\/christoph\/intel\/iaca\/include\/iacaMarks.h\"\n\n#if 0\n__m512i _mm512_mulhi_epi32(__m512i a, __m512i b) {\n auto a_lo = _mm512_srli_epi64(a, 32);\n auto b_lo = _mm512_srli_epi64(b, 32);\n auto c_lo = _mm512_mul_epi32(a_lo, b_lo);\n auto c_hi = _mm512_mul_epi32(a , b );\n return _mm512_mask_blend_epi32(0x5555, c_lo, _mm512_srli_epi64(c_hi, 32));\n}\n#endif\n\n\/\/ constants\nconstexpr std::size_t m512i_size = sizeof(__m512i);\nconstexpr std::size_t small_bits = 23;\nconstexpr std::size_t small_shft = 8;\nconstexpr std::size_t large_bits = 52;\nconstexpr std::size_t large_shft = 32;\nconstexpr std::size_t small_smin = 1 << (small_bits - small_shft);\nconstexpr std::size_t large_smin = 1 << (large_bits - large_shft);\n\ntemplate\ninline T* _addr(T* base, std::size_t byte_step) {\n return reinterpret_cast(\n reinterpret_cast(base) + byte_step\n );\n}\n\nstd::uint8_t* encode_ans(\n std::uint32_t* coder_iter, \/\/ where the stream starts\n std::uint32_t* coder_last, \/\/ where the stream ends\n \/\/ note that we encode from the end to the front!\n std::uint8_t* stream_out \/\/ target to write the stream out to\n) {\n \/\/ small states, 3 for pipelining\n auto state_sml0 = _mm512_set1_epi32(small_smin);\n auto state_sml1 = _mm512_set1_epi32(small_smin);\n auto state_sml2 = _mm512_set1_epi32(small_smin);\n \/\/ large states, 3 for pipelining (might not be worth it)\n \/\/auto state_lrg0 = _mm512_set1_epi64(large_smin);\n \/\/auto state_lrg1 = _mm512_set1_epi64(large_smin);\n \/\/auto state_lrg2 = _mm512_set1_epi64(large_smin);\n\n \/\/ we write from a high adress to a low so we need to\n __m128i stream_buf;\n __m128i shuffle_mk[] = {\n \/\/ shuffle masks that move each element left by 1 and clear the low bytes\n _mm_set_epi8(0x0F,0x0E,0x0D,0x0C,0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00),\n _mm_set_epi8(0x0E,0x0D,0x0C,0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF),\n _mm_set_epi8(0x0D,0x0C,0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF),\n _mm_set_epi8(0x0C,0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF)\n };\n\n while (coder_iter < coder_last) {\n IACA_START\n \/\/ load data\n coder_last = _addr(coder_last, -2 * m512i_size);\n auto digit = _mm512_loadu_si512(_addr(coder_last, 0 * m512i_size));\n auto base = _mm512_loadu_si512(_addr(coder_last, 1 * m512i_size));\n\n \/\/ check if there are small codings\n auto small_mask = _mm512_cmpgt_epi32_mask(_mm512_set1_epi32(32), base);\n\n \/\/ check for overflow\n auto oflow_test = _mm512_mullo_epi32(state_sml0, base);\n auto oflow_mask = _mm512_mask_cmpgt_epi32_mask(small_mask, oflow_test, _mm512_set1_epi32((1 << small_bits) - 1));\n\n \/\/ shift out\n auto state_shft = _mm512_cvtepi32_epi8(_mm512_maskz_compress_epi32(oflow_mask, state_sml0));\n auto oflow_n = _mm_popcnt_u64(oflow_mask);\n stream_buf = _mm_shuffle_epi8(stream_buf, _mm_load_si128(shuffle_mk + oflow_n));\n stream_buf = _mm_or_si128(stream_buf, state_shft); \/\/ @todo if vpermi2b has a low latency then this might be improved\n stream_out -= oflow_n;\n _mm_storeu_si128(reinterpret_cast<__m128i*>(stream_out), stream_buf); \/\/ partially overrides\n\n \/\/ rescale\n state_sml0 = _mm512_mask_srli_epi32(state_sml0, oflow_mask, state_sml0, small_shft);\n\n \/\/ actual encoding\n state_sml0 = _mm512_mask_mullo_epi32(state_sml0, small_mask, state_sml0, base );\n state_sml0 = _mm512_mask_add_epi32 (state_sml0, small_mask, state_sml0, digit);\n\n \/\/ rotate the states to reduce dependency\n auto tmp = state_sml0;\n state_sml0 = state_sml1;\n state_sml1 = state_sml2;\n state_sml2 = tmp;\n\n if (!_mm512_kortestc(small_mask, small_mask)) {\n \/\/ @todo Add fallback for large bases\n _mm512_storeu_si512(reinterpret_cast<__m512i*>(stream_out), tmp); \/\/ just to keep the branch\n }\n }\n IACA_END\n\n \/\/ store small states\n _mm512_storeu_si512(_addr(stream_out, 0 * m512i_size), state_sml0);\n _mm512_storeu_si512(_addr(stream_out, 1 * m512i_size), state_sml1);\n _mm512_storeu_si512(_addr(stream_out, 2 * m512i_size), state_sml2);\n stream_out = _addr(stream_out, 3 * m512i_size);\n\n \/\/ store large states\n \/\/_mm512_storeu_si512(_addr(stream_out, 0 * m512i_size), state_lrg0);\n \/\/_mm512_storeu_si512(_addr(stream_out, 1 * m512i_size), state_lrg1);\n \/\/_mm512_storeu_si512(_addr(stream_out, 2 * m512i_size), state_lrg2);\n \/\/stream_out = _addr(stream_out, 3 * m512i_size);\n\n \/\/ return a pointer to the end\n return stream_out;\n}\n\nint main() {}\nImproved latency#include \n#include \"immintrin.h\"\n\n#include \"\/home\/christoph\/intel\/iaca\/include\/iacaMarks.h\"\n\n#if 0\n__m512i _mm512_mulhi_epi32(__m512i a, __m512i b) {\n auto a_lo = _mm512_srli_epi64(a, 32);\n auto b_lo = _mm512_srli_epi64(b, 32);\n auto c_lo = _mm512_mul_epi32(a_lo, b_lo);\n auto c_hi = _mm512_mul_epi32(a , b );\n return _mm512_mask_blend_epi32(0x5555, c_lo, _mm512_srli_epi64(c_hi, 32));\n}\n#endif\n\n\/\/ constants\nconstexpr std::size_t m512i_size = sizeof(__m512i);\nconstexpr std::size_t small_bits = 23;\nconstexpr std::size_t small_shft = 8;\nconstexpr std::size_t large_bits = 52;\nconstexpr std::size_t large_shft = 32;\nconstexpr std::size_t small_smin = 1 << (small_bits - small_shft);\nconstexpr std::size_t large_smin = 1 << (large_bits - large_shft);\n\ntemplate\ninline T* _addr(T* base, std::size_t byte_step) {\n return reinterpret_cast(\n reinterpret_cast(base) + byte_step\n );\n}\n\nstd::uint8_t* encode_ans(\n std::uint32_t* coder_iter, \/\/ where the stream starts\n std::uint32_t* coder_last, \/\/ where the stream ends\n \/\/ note that we encode from the end to the front!\n std::uint8_t* stream_out \/\/ target to write the stream out to\n) {\n \/\/ small states, 3 for pipelining\n auto state_sml0 = _mm512_set1_epi32(small_smin);\n auto state_sml1 = _mm512_set1_epi32(small_smin);\n auto state_sml2 = _mm512_set1_epi32(small_smin);\n \/\/ large states, 3 for pipelining (might not be worth it)\n \/\/auto state_lrg0 = _mm512_set1_epi64(large_smin);\n \/\/auto state_lrg1 = _mm512_set1_epi64(large_smin);\n \/\/auto state_lrg2 = _mm512_set1_epi64(large_smin);\n\n \/\/ we write from a high adress to a low so we need to\n __m128i stream_buf;\n#if 0\n __m128i shuffle_mk[] = {\n \/\/ shuffle masks that move each element left by 1 and clear the low bytes\n _mm_set_epi8(0x0F,0x0E,0x0D,0x0C,0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00),\n _mm_set_epi8(0x0E,0x0D,0x0C,0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF),\n _mm_set_epi8(0x0D,0x0C,0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF),\n _mm_set_epi8(0x0C,0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),\n _mm_set_epi8(0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF)\n };\n#else\n __m128i shuffle_mk = _mm_set_epi8(0x0F,0x0E,0x0D,0x0C,0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00);\n#endif\n\n while (coder_iter < coder_last) {\n IACA_START\n \/\/ load data\n coder_last = _addr(coder_last, -2 * m512i_size);\n auto digit = _mm512_loadu_si512(_addr(coder_last, 0 * m512i_size));\n auto base = _mm512_loadu_si512(_addr(coder_last, 1 * m512i_size));\n\n \/\/ check if there are small codings\n auto small_mask = _mm512_cmpgt_epi32_mask(_mm512_set1_epi32(32), base);\n\n \/\/ check for overflow\n auto oflow_test = _mm512_mullo_epi32(state_sml0, base);\n auto oflow_mask = _mm512_mask_cmpgt_epi32_mask(small_mask, oflow_test, _mm512_set1_epi32((1 << small_bits) - 1));\n\n \/\/ shift out\n auto state_shft = _mm512_cvtepi32_epi8(_mm512_maskz_compress_epi32(oflow_mask, state_sml0));\n#if 1\n auto oflow_n = _mm_popcnt_u64(oflow_mask);\n auto oflow_bc = _mm_broadcastb_epi8(_mm_cvtsi128_si64x(oflow_n));\n stream_buf = _mm_shuffle_epi8(stream_buf, _mm_sub_si128(shuffle_mk, oflow_bc));\n#else\n stream_buf = _mm_shuffle_epi8(stream_buf, _mm_load_si128(shuffle_mk + oflow_n));\n#endif\n stream_buf = _mm_or_si128(stream_buf, state_shft); \/\/ @todo if vpermi2b has a low latency then this might be improved\n stream_out -= oflow_n;\n _mm_storeu_si128(reinterpret_cast<__m128i*>(stream_out), stream_buf); \/\/ partially overrides\n\n \/\/ rescale\n state_sml0 = _mm512_mask_srli_epi32(state_sml0, oflow_mask, state_sml0, small_shft);\n\n \/\/ actual encoding\n state_sml0 = _mm512_mask_mullo_epi32(state_sml0, small_mask, state_sml0, base );\n state_sml0 = _mm512_mask_add_epi32 (state_sml0, small_mask, state_sml0, digit);\n\n \/\/ rotate the states to reduce dependency\n auto tmp = state_sml0;\n state_sml0 = state_sml1;\n state_sml1 = state_sml2;\n state_sml2 = tmp;\n\n if (!_mm512_kortestc(small_mask, small_mask)) {\n \/\/ @todo Add fallback for large bases\n _mm512_storeu_si512(reinterpret_cast<__m512i*>(stream_out), tmp); \/\/ just to keep the branch\n }\n }\n IACA_END\n\n \/\/ store small states\n _mm512_storeu_si512(_addr(stream_out, 0 * m512i_size), state_sml0);\n _mm512_storeu_si512(_addr(stream_out, 1 * m512i_size), state_sml1);\n _mm512_storeu_si512(_addr(stream_out, 2 * m512i_size), state_sml2);\n stream_out = _addr(stream_out, 3 * m512i_size);\n\n \/\/ store large states\n \/\/_mm512_storeu_si512(_addr(stream_out, 0 * m512i_size), state_lrg0);\n \/\/_mm512_storeu_si512(_addr(stream_out, 1 * m512i_size), state_lrg1);\n \/\/_mm512_storeu_si512(_addr(stream_out, 2 * m512i_size), state_lrg2);\n \/\/stream_out = _addr(stream_out, 3 * m512i_size);\n\n \/\/ return a pointer to the end\n return stream_out;\n}\n\nint main() {}\n<|endoftext|>"} {"text":"\/*\r\n* This file is part of `et engine`\r\n* Copyright 2009-2012 by Sergey Reznik\r\n* Please, do not modify contents without approval.\r\n*\r\n*\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace et;\r\n\r\nstd::string Locale::time()\r\n{\r\n\treturn std::string();\r\n}\r\n\r\nstd::string Locale::date()\r\n{\r\n\treturn std::string();\r\n}\r\n\r\nsize_t Locale::currentLocale()\r\n{\r\n\tstd::string mbcs(\"en_US\");\r\n\tlowercase(mbcs);\r\n\t\r\n\tsize_t result = 0;\r\n\r\n\tif (mbcs.size() > 0)\r\n\t\tresult |= mbcs[0];\r\n\t\r\n\tif (mbcs.size() > 1)\r\n\t\tresult |= mbcs[1] << 8;\r\n\t\r\n\tif ((mbcs.size() >= 5) && ((mbcs[2] == '-') || (mbcs[2] == '_')))\r\n\t\tresult |= (mbcs[3] << 16) | (mbcs[4] << 24);\r\n\telse\r\n\t\tresult |= (result & 0xffff) << 16;\r\n\r\n\treturn result;\r\n}\r\nandroid locale\/*\r\n* This file is part of `et engine`\r\n* Copyright 2009-2012 by Sergey Reznik\r\n* Please, do not modify contents without approval.\r\n*\r\n*\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace et;\r\n\r\nstd::string locale::time()\r\n{\r\n\treturn std::string();\r\n}\r\n\r\nstd::string locale::date()\r\n{\r\n\treturn std::string();\r\n}\r\n\r\nsize_t locale::currentLocale()\r\n{\r\n\tstd::string mbcs(\"en_US\");\r\n\tlowercase(mbcs);\r\n\t\r\n\tsize_t result = 0;\r\n\r\n\tif (mbcs.size() > 0)\r\n\t\tresult |= mbcs[0];\r\n\t\r\n\tif (mbcs.size() > 1)\r\n\t\tresult |= mbcs[1] << 8;\r\n\t\r\n\tif ((mbcs.size() >= 5) && ((mbcs[2] == '-') || (mbcs[2] == '_')))\r\n\t\tresult |= (mbcs[3] << 16) | (mbcs[4] << 24);\r\n\telse\r\n\t\tresult |= (result & 0xffff) << 16;\r\n\r\n\treturn result;\r\n}\r\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\nnamespace smartview\n{\n\tvoid ExtendedFlags::Parse()\n\t{\n\t\t\/\/ Run through the parser once to count the number of flag structs\n\t\tfor (;;)\n\t\t{\n\t\t\t\/\/ Must have at least 2 bytes left to have another flag\n\t\t\tif (m_Parser.RemainingBytes() < 2) break;\n\t\t\t(void) m_Parser.Get();\n\t\t\tconst auto cbData = m_Parser.Get();\n\t\t\t\/\/ Must have at least cbData bytes left to be a valid flag\n\t\t\tif (m_Parser.RemainingBytes() < cbData) break;\n\n\t\t\tm_Parser.advance(cbData);\n\t\t\tm_ulNumFlags++;\n\t\t}\n\n\t\t\/\/ Now we parse for real\n\t\tm_Parser.rewind();\n\n\t\tif (m_ulNumFlags && m_ulNumFlags < _MaxEntriesSmall)\n\t\t{\n\t\t\tauto bBadData = false;\n\n\t\t\tm_pefExtendedFlags.reserve(m_ulNumFlags);\n\t\t\tfor (ULONG i = 0; i < m_ulNumFlags; i++)\n\t\t\t{\n\t\t\t\tExtendedFlag extendedFlag;\n\n\t\t\t\textendedFlag.Id = m_Parser.Get();\n\t\t\t\textendedFlag.Cb = m_Parser.Get();\n\n\t\t\t\t\/\/ If the structure says there's more bytes than remaining buffer, we're done parsing.\n\t\t\t\tif (m_Parser.RemainingBytes() < extendedFlag.Cb)\n\t\t\t\t{\n\t\t\t\t\tm_ulNumFlags = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tswitch (extendedFlag.Id)\n\t\t\t\t{\n\t\t\t\tcase EFPB_FLAGS:\n\t\t\t\t\tif (extendedFlag.Cb == sizeof(DWORD))\n\t\t\t\t\t\textendedFlag.Data.ExtendedFlags = m_Parser.Get();\n\t\t\t\t\telse\n\t\t\t\t\t\tbBadData = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase EFPB_CLSIDID:\n\t\t\t\t\tif (extendedFlag.Cb == sizeof(GUID))\n\t\t\t\t\t\textendedFlag.Data.SearchFolderID = m_Parser.Get();\n\t\t\t\t\telse\n\t\t\t\t\t\tbBadData = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase EFPB_SFTAG:\n\t\t\t\t\tif (extendedFlag.Cb == sizeof(DWORD))\n\t\t\t\t\t\textendedFlag.Data.SearchFolderTag = m_Parser.Get();\n\t\t\t\t\telse\n\t\t\t\t\t\tbBadData = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase EFPB_TODO_VERSION:\n\t\t\t\t\tif (extendedFlag.Cb == sizeof(DWORD))\n\t\t\t\t\t\textendedFlag.Data.ToDoFolderVersion = m_Parser.Get();\n\t\t\t\t\telse\n\t\t\t\t\t\tbBadData = true;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\textendedFlag.lpUnknownData = m_Parser.GetBYTES(extendedFlag.Cb, _MaxBytes);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t\/\/ If we encountered a bad flag, stop parsing\n\t\t\t\tif (bBadData)\n\t\t\t\t{\n\t\t\t\t\tm_ulNumFlags = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tm_pefExtendedFlags.push_back(extendedFlag);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid ExtendedFlags::ParseBlocks()\n\t{\n\t\tsetRoot(L\"Extended Flags:\");\n\t\taddHeader(L\"\\r\\nNumber of flags = %1!d!\", m_ulNumFlags);\n\n\t\tif (m_pefExtendedFlags.size())\n\t\t{\n\t\t\tfor (const auto& extendedFlag : m_pefExtendedFlags)\n\t\t\t{\n\t\t\t\tauto szFlags = interpretprop::InterpretFlags(flagExtendedFolderFlagType, extendedFlag.Id);\n\t\t\t\taddBlock(extendedFlag.Id, L\"\\r\\nId = 0x%1!02X! = %2!ws!\", extendedFlag.Id.getData(), szFlags.c_str());\n\t\t\t\taddBlock(extendedFlag.Cb, L\"\\r\\nCb = 0x%1!02X! = %1!d!\", extendedFlag.Cb.getData());\n\n\t\t\t\tswitch (extendedFlag.Id)\n\t\t\t\t{\n\t\t\t\tcase EFPB_FLAGS:\n\t\t\t\t\taddBlock(\n\t\t\t\t\t\textendedFlag.Data.ExtendedFlags,\n\t\t\t\t\t\tL\"\\r\\n\\tExtended Flags = 0x%1!08X! = %2!ws!\",\n\t\t\t\t\t\textendedFlag.Data.ExtendedFlags.getData(),\n\t\t\t\t\t\tinterpretprop::InterpretFlags(flagExtendedFolderFlag, extendedFlag.Data.ExtendedFlags).c_str());\n\t\t\t\t\tbreak;\n\t\t\t\tcase EFPB_CLSIDID:\n\t\t\t\t\taddBlock(\n\t\t\t\t\t\textendedFlag.Data.SearchFolderID,\n\t\t\t\t\t\tL\"\\r\\n\\tSearchFolderID = %1!ws!\",\n\t\t\t\t\t\tguid::GUIDToString(extendedFlag.Data.SearchFolderID).c_str());\n\t\t\t\t\tbreak;\n\t\t\t\tcase EFPB_SFTAG:\n\t\t\t\t\taddBlock(\n\t\t\t\t\t\textendedFlag.Data.SearchFolderTag,\n\t\t\t\t\t\tL\"\\r\\n\\tSearchFolderTag = 0x%1!08X!\",\n\t\t\t\t\t\textendedFlag.Data.SearchFolderTag.getData());\n\t\t\t\t\tbreak;\n\t\t\t\tcase EFPB_TODO_VERSION:\n\t\t\t\t\taddBlock(\n\t\t\t\t\t\textendedFlag.Data.ToDoFolderVersion,\n\t\t\t\t\t\tL\"\\r\\n\\tToDoFolderVersion = 0x%1!08X!\",\n\t\t\t\t\t\textendedFlag.Data.ToDoFolderVersion.getData());\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (extendedFlag.lpUnknownData.size())\n\t\t\t\t{\n\t\t\t\t\taddBlankLine();\n\t\t\t\t\taddHeader(L\"\\tUnknown Data = \");\n\t\t\t\t\taddBlock(extendedFlag.lpUnknownData);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n} \/\/ namespace smartviewFix Extended Flags#include \n#include \n#include \n#include \n#include \n\nnamespace smartview\n{\n\tvoid ExtendedFlags::Parse()\n\t{\n\t\t\/\/ Run through the parser once to count the number of flag structs\n\t\tfor (;;)\n\t\t{\n\t\t\t\/\/ Must have at least 2 bytes left to have another flag\n\t\t\tif (m_Parser.RemainingBytes() < 2) break;\n\t\t\t(void) m_Parser.Get();\n\t\t\tconst auto cbData = m_Parser.Get();\n\t\t\t\/\/ Must have at least cbData bytes left to be a valid flag\n\t\t\tif (m_Parser.RemainingBytes() < cbData) break;\n\n\t\t\tm_Parser.advance(cbData);\n\t\t\tm_ulNumFlags++;\n\t\t}\n\n\t\t\/\/ Now we parse for real\n\t\tm_Parser.rewind();\n\n\t\tif (m_ulNumFlags && m_ulNumFlags < _MaxEntriesSmall)\n\t\t{\n\t\t\tauto bBadData = false;\n\n\t\t\tm_pefExtendedFlags.reserve(m_ulNumFlags);\n\t\t\tfor (ULONG i = 0; i < m_ulNumFlags; i++)\n\t\t\t{\n\t\t\t\tExtendedFlag extendedFlag;\n\n\t\t\t\textendedFlag.Id = m_Parser.Get();\n\t\t\t\textendedFlag.Cb = m_Parser.Get();\n\n\t\t\t\t\/\/ If the structure says there's more bytes than remaining buffer, we're done parsing.\n\t\t\t\tif (m_Parser.RemainingBytes() < extendedFlag.Cb)\n\t\t\t\t{\n\t\t\t\t\tm_pefExtendedFlags.push_back(extendedFlag);\n\t\t\t\t\tm_ulNumFlags = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tswitch (extendedFlag.Id)\n\t\t\t\t{\n\t\t\t\tcase EFPB_FLAGS:\n\t\t\t\t\tif (extendedFlag.Cb == sizeof(DWORD))\n\t\t\t\t\t\textendedFlag.Data.ExtendedFlags = m_Parser.Get();\n\t\t\t\t\telse\n\t\t\t\t\t\tbBadData = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase EFPB_CLSIDID:\n\t\t\t\t\tif (extendedFlag.Cb == sizeof(GUID))\n\t\t\t\t\t\textendedFlag.Data.SearchFolderID = m_Parser.Get();\n\t\t\t\t\telse\n\t\t\t\t\t\tbBadData = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase EFPB_SFTAG:\n\t\t\t\t\tif (extendedFlag.Cb == sizeof(DWORD))\n\t\t\t\t\t\textendedFlag.Data.SearchFolderTag = m_Parser.Get();\n\t\t\t\t\telse\n\t\t\t\t\t\tbBadData = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase EFPB_TODO_VERSION:\n\t\t\t\t\tif (extendedFlag.Cb == sizeof(DWORD))\n\t\t\t\t\t\textendedFlag.Data.ToDoFolderVersion = m_Parser.Get();\n\t\t\t\t\telse\n\t\t\t\t\t\tbBadData = true;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\textendedFlag.lpUnknownData = m_Parser.GetBYTES(extendedFlag.Cb, _MaxBytes);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t\/\/ If we encountered a bad flag, stop parsing\n\t\t\t\tif (bBadData)\n\t\t\t\t{\n\t\t\t\t\tm_pefExtendedFlags.push_back(extendedFlag);\n\t\t\t\t\tm_ulNumFlags = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tm_pefExtendedFlags.push_back(extendedFlag);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid ExtendedFlags::ParseBlocks()\n\t{\n\t\tsetRoot(L\"Extended Flags:\");\n\t\taddHeader(L\"\\r\\nNumber of flags = %1!d!\", m_ulNumFlags);\n\n\t\tif (m_pefExtendedFlags.size())\n\t\t{\n\t\t\tfor (const auto& extendedFlag : m_pefExtendedFlags)\n\t\t\t{\n\t\t\t\tauto szFlags = interpretprop::InterpretFlags(flagExtendedFolderFlagType, extendedFlag.Id);\n\t\t\t\taddBlock(extendedFlag.Id, L\"\\r\\nId = 0x%1!02X! = %2!ws!\", extendedFlag.Id.getData(), szFlags.c_str());\n\t\t\t\taddBlock(extendedFlag.Cb, L\"\\r\\nCb = 0x%1!02X! = %1!d!\", extendedFlag.Cb.getData());\n\n\t\t\t\tswitch (extendedFlag.Id)\n\t\t\t\t{\n\t\t\t\tcase EFPB_FLAGS:\n\t\t\t\t\taddBlock(\n\t\t\t\t\t\textendedFlag.Data.ExtendedFlags,\n\t\t\t\t\t\tL\"\\r\\n\\tExtended Flags = 0x%1!08X! = %2!ws!\",\n\t\t\t\t\t\textendedFlag.Data.ExtendedFlags.getData(),\n\t\t\t\t\t\tinterpretprop::InterpretFlags(flagExtendedFolderFlag, extendedFlag.Data.ExtendedFlags).c_str());\n\t\t\t\t\tbreak;\n\t\t\t\tcase EFPB_CLSIDID:\n\t\t\t\t\taddBlock(\n\t\t\t\t\t\textendedFlag.Data.SearchFolderID,\n\t\t\t\t\t\tL\"\\r\\n\\tSearchFolderID = %1!ws!\",\n\t\t\t\t\t\tguid::GUIDToString(extendedFlag.Data.SearchFolderID).c_str());\n\t\t\t\t\tbreak;\n\t\t\t\tcase EFPB_SFTAG:\n\t\t\t\t\taddBlock(\n\t\t\t\t\t\textendedFlag.Data.SearchFolderTag,\n\t\t\t\t\t\tL\"\\r\\n\\tSearchFolderTag = 0x%1!08X!\",\n\t\t\t\t\t\textendedFlag.Data.SearchFolderTag.getData());\n\t\t\t\t\tbreak;\n\t\t\t\tcase EFPB_TODO_VERSION:\n\t\t\t\t\taddBlock(\n\t\t\t\t\t\textendedFlag.Data.ToDoFolderVersion,\n\t\t\t\t\t\tL\"\\r\\n\\tToDoFolderVersion = 0x%1!08X!\",\n\t\t\t\t\t\textendedFlag.Data.ToDoFolderVersion.getData());\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (extendedFlag.lpUnknownData.size())\n\t\t\t\t{\n\t\t\t\t\taddBlankLine();\n\t\t\t\t\taddHeader(L\"\\tUnknown Data = \");\n\t\t\t\t\taddBlock(extendedFlag.lpUnknownData);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n} \/\/ namespace smartview<|endoftext|>"} {"text":"\/*******************************************************************************\n* ALMA - Atacama Large Millimiter Array\n* (c) Associated Universities Inc., 2007 \n* \n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n* \n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n* \n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n* \"@(#) $Id: RepeatGuard.cpp,v 1.2 2007\/03\/02 13:45:29 nbarriga Exp $\"\n*\n* who when what\n* -------- -------- ----------------------------------------------\n* nbarriga 2007-02-20 created \n*\/\n\n#include \"vltPort.h\"\n\nstatic char *rcsId=\"@(#) $Id: RepeatGuard.cpp,v 1.2 2007\/03\/02 13:45:29 nbarriga Exp $\"; \nstatic void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);\n\n\n#include \"RepeatGuard.h\"\n\nRepeatGuard::RepeatGuard(unsigned int interval, unsigned int maxRepetitions, bool or_or_and){\n method=or_or_and;\n if(interval==0)method=COUNTER;\n if(maxRepetitions==0)method=TIMER;\n\n\tthis->maxRepetitions=maxRepetitions;\n\tthis->interval=interval*10000000;\n\tcounter=0;\n\tcounterAtLastCheck=0;\n\tlastTime=0;\n}\n\nRepeatGuard::~RepeatGuard(){\n\n}\n\nbool RepeatGuard::check(){\n switch(method){\n case AND:\n if(lastTime+interval<=getTimeStamp()&&counter>=maxRepetitions){\n counterAtLastCheck=counter;\n counter=0;\n lastTime=getTimeStamp();\n return true;\n }\n return false;\n break;\n case OR:\n if(lastTime+interval<=getTimeStamp()||counter>=maxRepetitions){\n counterAtLastCheck=counter;\n counter=0;\n lastTime=getTimeStamp();\n return true;\n }\n return false;\n break;\n case TIMER:\n if(lastTime+interval<=getTimeStamp()){\n counterAtLastCheck=counter;\n counter=0;\n lastTime=getTimeStamp();\n return true;\n }\n return false;\n break;\n case COUNTER:\n if(counter>=maxRepetitions){\n counterAtLastCheck=counter;\n counter=0;\n lastTime=getTimeStamp();\n return true;\n }\n return false;\n break;\n }\n}\n\nbool RepeatGuard::checkAndIncrement(){\n\n counter++;\n return check();\n}\n\nvoid RepeatGuard::increment(){\n\tcounter++;\n}\n\nunsigned int RepeatGuard::count(){\n\treturn counterAtLastCheck;\n}\n\nvoid RepeatGuard::reset(){\n\tcounter=0;\n\tcounterAtLastCheck=0;\n\tlastTime=0;\n}\n\nvoid RepeatGuard::reset(unsigned int interval, unsigned int maxRepetitions, bool or_or_and){\n method=OR;\n if(interval==0)method=COUNTER;\n if(maxRepetitions==0)method=TIMER;\n\n\tthis->maxRepetitions=maxRepetitions;\n\tthis->interval=interval*10000000;\n\tcounter=0;\n\tcounterAtLastCheck=0;\n\tlastTime=0;\n}\n\/*___oOo___*\/\nRemoved a warning in check(). It returns false if no case in the switch is selected. In practice, this cannot happen anyway, but the compiler was complaining because it was detecting a method without value for the return.\/*******************************************************************************\n* ALMA - Atacama Large Millimiter Array\n* (c) Associated Universities Inc., 2007 \n* \n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n* \n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n* \n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n* \"@(#) $Id: RepeatGuard.cpp,v 1.3 2007\/03\/22 10:55:29 gchiozzi Exp $\"\n*\n* who when what\n* -------- -------- ----------------------------------------------\n* nbarriga 2007-02-20 created \n*\/\n\n#include \"vltPort.h\"\n\nstatic char *rcsId=\"@(#) $Id: RepeatGuard.cpp,v 1.3 2007\/03\/22 10:55:29 gchiozzi Exp $\"; \nstatic void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);\n\n\n#include \"RepeatGuard.h\"\n\nRepeatGuard::RepeatGuard(unsigned int interval, unsigned int maxRepetitions, bool or_or_and){\n method=or_or_and;\n if(interval==0)method=COUNTER;\n if(maxRepetitions==0)method=TIMER;\n\n\tthis->maxRepetitions=maxRepetitions;\n\tthis->interval=interval*10000000;\n\tcounter=0;\n\tcounterAtLastCheck=0;\n\tlastTime=0;\n}\n\nRepeatGuard::~RepeatGuard(){\n\n}\n\nbool RepeatGuard::check(){\n switch(method){\n case AND:\n if(lastTime+interval<=getTimeStamp()&&counter>=maxRepetitions){\n counterAtLastCheck=counter;\n counter=0;\n lastTime=getTimeStamp();\n return true;\n }\n return false;\n break;\n case OR:\n if(lastTime+interval<=getTimeStamp()||counter>=maxRepetitions){\n counterAtLastCheck=counter;\n counter=0;\n lastTime=getTimeStamp();\n return true;\n }\n return false;\n break;\n case TIMER:\n if(lastTime+interval<=getTimeStamp()){\n counterAtLastCheck=counter;\n counter=0;\n lastTime=getTimeStamp();\n return true;\n }\n return false;\n break;\n case COUNTER:\n if(counter>=maxRepetitions){\n counterAtLastCheck=counter;\n counter=0;\n lastTime=getTimeStamp();\n return true;\n }\n return false;\n break;\n }\n\treturn false;\n}\n\nbool RepeatGuard::checkAndIncrement(){\n\n counter++;\n return check();\n}\n\nvoid RepeatGuard::increment(){\n\tcounter++;\n}\n\nunsigned int RepeatGuard::count(){\n\treturn counterAtLastCheck;\n}\n\nvoid RepeatGuard::reset(){\n\tcounter=0;\n\tcounterAtLastCheck=0;\n\tlastTime=0;\n}\n\nvoid RepeatGuard::reset(unsigned int interval, unsigned int maxRepetitions, bool or_or_and){\n method=OR;\n if(interval==0)method=COUNTER;\n if(maxRepetitions==0)method=TIMER;\n\n\tthis->maxRepetitions=maxRepetitions;\n\tthis->interval=interval*10000000;\n\tcounter=0;\n\tcounterAtLastCheck=0;\n\tlastTime=0;\n}\n\/*___oOo___*\/\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n\nextern \"C\" {\n#include \n}\n\nextern void __platform_init();\nextern void default_stdout_handlers();\n\nchar cmdline[256];\nuintptr_t mem_size;\n\nextern \"C\" {\n void __init_sanity_checks();\n void kernel_sanity_checks();\n uintptr_t _move_symbols(uintptr_t loc);\n void _init_bss();\n void _init_heap(uintptr_t);\n void _init_c_runtime();\n void _init_syscalls();\n void __libc_init_array();\n uintptr_t _end;\n void set_stack();\n void* get_cpu_ebp();\n\n \/\/ Set to NULL. There are no interrupts in ukvm\n void (*current_eoi_mechanism)();\n void (*current_intr_handler)();\n void (*cpu_sampling_irq_handler)();\n\n\n void kernel_start()\n {\n\n \/\/ generate checksums of read-only areas etc.\n __init_sanity_checks();\n\n \/\/ Determine where free memory starts\n uintptr_t free_mem_begin = reinterpret_cast(&_end);\n\n \/\/ Preserve symbols from the ELF binary\n free_mem_begin += _move_symbols(free_mem_begin);\n\n \/\/ Do not zero out all solo5 global variables!! == don't touch the BSS\n \/\/_init_bss();\n\n \/\/ Initialize heap\n \/\/ XXX: this is dangerous as solo5 might be doing malloc()'s using it's own\n \/\/ idea of a heap. Luckily there is no malloc instance at solo5\/kernel\/[ukvm|virtio|muen],\n \/\/ so might be OK (for now).\n _init_heap(free_mem_begin);\n\n \/\/Initialize stack-unwinder, call global constructors etc.\n _init_c_runtime();\n\n \/\/ Initialize system calls\n _init_syscalls();\n\n \/\/Initialize stdout handlers\n default_stdout_handlers();\n\n \/\/ Call global ctors\n __libc_init_array();\n\n \/\/ interrupts.asm uses these symbols. This is just to make the compiler happy.\n \/\/ These won't ever be called.\n current_eoi_mechanism = NULL;\n current_intr_handler = NULL;\n cpu_sampling_irq_handler = NULL;\n\n \/\/ Initialize OS including devices\n OS::start(cmdline, mem_size);\n\n \/\/ Starting event loop from here allows us to profile OS::start\n OS::event_loop();\n }\n\n int solo5_app_main(char *_cmdline)\n {\n \/\/ cmdline is stored at 0x6000 by ukvm which is used by includeos. Move it fast.\n strncpy(cmdline, _cmdline, 256);\n\n \/\/ solo5 sets the stack to be at the end of memory, so let's use that as\n \/\/ our memory size (before we change).\n mem_size = (uintptr_t)get_cpu_ebp();\n\n \/\/ set the stack location to its new includeos location, and call kernel_start\n set_stack();\n }\n}\nsolo5: Update kernel_start stubs needed for linking#include \n#include \n#include \n#include \n#include \n#include \n\nextern \"C\" {\n#include \n}\n\nextern void __platform_init();\nextern void default_stdout_handlers();\nvoid __arch_subscribe_irq(unsigned char) {} \/\/ for now\n\nchar cmdline[256];\nuintptr_t mem_size;\n\nextern \"C\" {\n void __init_sanity_checks();\n void kernel_sanity_checks();\n uintptr_t _move_symbols(uintptr_t loc);\n void _init_bss();\n void _init_heap(uintptr_t);\n void _init_c_runtime();\n void _init_syscalls();\n void __libc_init_array();\n uintptr_t _end;\n void set_stack();\n void* get_cpu_ebp();\n\n void kernel_start()\n {\n\n \/\/ generate checksums of read-only areas etc.\n __init_sanity_checks();\n\n \/\/ Determine where free memory starts\n uintptr_t free_mem_begin = reinterpret_cast(&_end);\n\n \/\/ Preserve symbols from the ELF binary\n free_mem_begin += _move_symbols(free_mem_begin);\n\n \/\/ Do not zero out all solo5 global variables!! == don't touch the BSS\n \/\/_init_bss();\n\n \/\/ Initialize heap\n \/\/ XXX: this is dangerous as solo5 might be doing malloc()'s using it's own\n \/\/ idea of a heap. Luckily there is no malloc instance at solo5\/kernel\/[ukvm|virtio|muen],\n \/\/ so might be OK (for now).\n _init_heap(free_mem_begin);\n\n \/\/Initialize stack-unwinder, call global constructors etc.\n _init_c_runtime();\n\n \/\/ Initialize system calls\n _init_syscalls();\n\n \/\/Initialize stdout handlers\n default_stdout_handlers();\n\n \/\/ Call global ctors\n __libc_init_array();\n\n \/\/ Initialize OS including devices\n OS::start(cmdline, mem_size);\n\n \/\/ Starting event loop from here allows us to profile OS::start\n OS::event_loop();\n }\n\n int solo5_app_main(char *_cmdline)\n {\n \/\/ cmdline is stored at 0x6000 by ukvm which is used by includeos. Move it fast.\n strncpy(cmdline, _cmdline, 256);\n\n \/\/ solo5 sets the stack to be at the end of memory, so let's use that as\n \/\/ our memory size (before we change).\n mem_size = (uintptr_t)get_cpu_ebp();\n\n \/\/ set the stack location to its new includeos location, and call kernel_start\n set_stack();\n return 0;\n }\n}\n<|endoftext|>"} {"text":"\/**\n * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may find a copy of the License in the LICENCE file.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @file JPetTaskExecutor.cpp\n *\/\n\n#include \"JPetTaskExecutor.h\"\n#include \n#include \n#include \"..\/JPetTaskInterface\/JPetTaskInterface.h\"\n#include \"..\/JPetScopeLoader\/JPetScopeLoader.h\"\n#include \"..\/JPetTaskLoader\/JPetTaskLoader.h\"\n#include \"..\/JPetParamGetterAscii\/JPetParamGetterAscii.h\"\n#include \"..\/JPetParamGetterAscii\/JPetParamSaverAscii.h\"\n#include \"..\/JPetLoggerInclude.h\"\n\n\nJPetTaskExecutor::JPetTaskExecutor(TaskGeneratorChain* taskGeneratorChain, int processedFileId, JPetOptions opt) :\n fProcessedFile(processedFileId),\n ftaskGeneratorChain(taskGeneratorChain),\n fOptions(opt)\n{\n if (fOptions.isLocalDB()) {\n fParamManager = new JPetParamManager(new JPetParamGetterAscii(fOptions.getLocalDB()));\n } else {\n fParamManager = new JPetParamManager();\n }\n if (taskGeneratorChain) {\n for (auto taskGenerator : *ftaskGeneratorChain) {\n auto task = taskGenerator();\n task->setParamManager(fParamManager); \/\/ maybe that should not be here\n fTasks.push_back(task);\n }\n } else {\n ERROR(\"taskGeneratorChain is null while constructing JPetTaskExecutor\");\n }\n}\n\nbool JPetTaskExecutor::process()\n{\n if(!processFromCmdLineArgs(fProcessedFile)) {\n ERROR(\"Error in processFromCmdLineArgs\");\n return false;\n }\n for (auto currentTask = fTasks.begin(); currentTask != fTasks.end(); currentTask++) {\n JPetOptions::Options currOpts = fOptions.getOptions();\n if (currentTask != fTasks.begin()) {\n \/\/\/ Ignore the event range options for all but the first task.\n currOpts = JPetOptions::resetEventRange(currOpts);\n \/\/\/ For all but the first task, \n \/\/\/ the input path must be changed if \n \/\/\/ the output path argument -o was given, because the input\n \/\/\/ data for them will lay in the location defined by -o.\n auto outPath = currOpts.at(\"outputPath\");\n if (!outPath.empty()) {\n currOpts.at(\"inputFile\") = outPath + JPetCommonTools::extractPathFromFile(currOpts.at(\"inputFile\")) + JPetCommonTools::extractFileNameFromFullPath(currOpts.at(\"inputFile\"));\n }\n }\n\n INFO(Form(\"Starting task: %s\", dynamic_cast(*currentTask)->getSubTask()->GetName()));\n (*currentTask)->init(currOpts);\n (*currentTask)->exec();\n (*currentTask)->terminate();\n INFO(Form(\"Finished task: %s\", dynamic_cast(*currentTask)->getSubTask()->GetName()));\n }\n return true;\n}\n\nvoid* JPetTaskExecutor::processProxy(void* runner)\n{\n assert(runner);\n static_cast(runner)->process();\n return 0;\n}\n\nTThread* JPetTaskExecutor::run()\n{\n TThread* thread = new TThread(to_string(fProcessedFile).c_str(), processProxy, (void*)this);\n assert(thread);\n thread->Run();\n return thread;\n}\n\nbool JPetTaskExecutor::processFromCmdLineArgs(int)\n{\n auto runNum = fOptions.getRunNumber();\n if (runNum >= 0) {\n try {\n fParamManager->fillParameterBank(runNum);\n } catch (...) {\n ERROR(\"Param bank was not generated correctly.\\n The run number used:\" + JPetCommonTools::intToString(runNum));\n return false;\n }\n if (fOptions.isLocalDBCreate()) {\n JPetParamSaverAscii saver;\n saver.saveParamBank(fParamManager->getParamBank(), runNum, fOptions.getLocalDBCreate());\n }\n }\n \n auto inputFileType = fOptions.getInputFileType();\n auto inputFile = fOptions.getInputFile();\n if (inputFileType == JPetOptions::kScope) {\n createScopeTaskAndAddToTaskList();\n } else if (inputFileType == JPetOptions::kHld) {\n long long nevents = fOptions.getTotalEvents();\n if (nevents > 0) {\n fUnpacker.setParams(fOptions.getInputFile(), nevents);\n WARNING(std::string(\"Even though the range of events was set, only the first \") + JPetCommonTools::intToString(nevents) + std::string(\" will be unpacked by the unpacker. \\n The unpacker always starts from the beginning of the file.\"));\n } else {\n fUnpacker.setParams(fOptions.getInputFile());\n }\n unpackFile();\n }\n else if( inputFileType == JPetOptions::kZip){\n INFO( std::string(\"Unzipping file before unpacking\") );\n unzipFile();\n \n }\n \n if(fOptions.getInputFileType() == JPetOptions::kUndefinedFileType)\n ERROR( Form(\"Unknown file type provided for file: %s\", fOptions.getInputFile()) );\n \n return true;\n}\n\nvoid JPetTaskExecutor::createScopeTaskAndAddToTaskList()\n{\n JPetScopeLoader* module = new JPetScopeLoader(new JPetScopeTask(\"JPetScopeReader\", \"Process Oscilloscope ASCII data into JPetRecoSignal structures.\"));\n assert(module);\n module->setParamManager(fParamManager);\n auto scopeFile = fOptions.getScopeConfigFile();\n if (!fParamManager->getParametersFromScopeConfig(scopeFile)) {\n ERROR(\"Unable to generate Param Bank from Scope Config\");\n }\n fTasks.push_front(module);\n}\n\nvoid JPetTaskExecutor::unpackFile()\n{\n if (fOptions.getInputFileType() == JPetOptions::kHld) {\n fUnpacker.exec();\n } else {\n WARNING(\"Input file is not hld and unpacker was supposed to be called!\");\n }\n}\n\nvoid JPetTaskExecutor::unzipFile()\n{\n \n if( (fOptions.getInputFileType() == JPetOptions::kZip) ) {\n system(Form(\"gzip -d %s\", fOptions.getInputFile() ) );\n \n }\n else {\n WARNING(\"Input file is not zip and cannot be unzipped\");\n }\n}\n\n\nJPetTaskExecutor::~JPetTaskExecutor()\n{\n for (auto & task : fTasks) {\n if (task) {\n delete task;\n task = 0;\n }\n }\n}\nAdded unzipping, after the unzipping unpacking is done automatically\/**\n * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may find a copy of the License in the LICENCE file.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @file JPetTaskExecutor.cpp\n *\/\n\n#include \"JPetTaskExecutor.h\"\n#include \n#include \n#include \"..\/JPetTaskInterface\/JPetTaskInterface.h\"\n#include \"..\/JPetScopeLoader\/JPetScopeLoader.h\"\n#include \"..\/JPetTaskLoader\/JPetTaskLoader.h\"\n#include \"..\/JPetParamGetterAscii\/JPetParamGetterAscii.h\"\n#include \"..\/JPetParamGetterAscii\/JPetParamSaverAscii.h\"\n#include \"..\/JPetLoggerInclude.h\"\n\n\nJPetTaskExecutor::JPetTaskExecutor(TaskGeneratorChain* taskGeneratorChain, int processedFileId, JPetOptions opt) :\n fProcessedFile(processedFileId),\n ftaskGeneratorChain(taskGeneratorChain),\n fOptions(opt)\n{\n if (fOptions.isLocalDB()) {\n fParamManager = new JPetParamManager(new JPetParamGetterAscii(fOptions.getLocalDB()));\n } else {\n fParamManager = new JPetParamManager();\n }\n if (taskGeneratorChain) {\n for (auto taskGenerator : *ftaskGeneratorChain) {\n auto task = taskGenerator();\n task->setParamManager(fParamManager); \/\/ maybe that should not be here\n fTasks.push_back(task);\n }\n } else {\n ERROR(\"taskGeneratorChain is null while constructing JPetTaskExecutor\");\n }\n}\n\nbool JPetTaskExecutor::process()\n{\n if(!processFromCmdLineArgs(fProcessedFile)) {\n ERROR(\"Error in processFromCmdLineArgs\");\n return false;\n }\n for (auto currentTask = fTasks.begin(); currentTask != fTasks.end(); currentTask++) {\n JPetOptions::Options currOpts = fOptions.getOptions();\n if (currentTask != fTasks.begin()) {\n \/\/\/ Ignore the event range options for all but the first task.\n currOpts = JPetOptions::resetEventRange(currOpts);\n \/\/\/ For all but the first task, \n \/\/\/ the input path must be changed if \n \/\/\/ the output path argument -o was given, because the input\n \/\/\/ data for them will lay in the location defined by -o.\n auto outPath = currOpts.at(\"outputPath\");\n if (!outPath.empty()) {\n currOpts.at(\"inputFile\") = outPath + JPetCommonTools::extractPathFromFile(currOpts.at(\"inputFile\")) + JPetCommonTools::extractFileNameFromFullPath(currOpts.at(\"inputFile\"));\n }\n }\n\n INFO(Form(\"Starting task: %s\", dynamic_cast(*currentTask)->getSubTask()->GetName()));\n (*currentTask)->init(currOpts);\n (*currentTask)->exec();\n (*currentTask)->terminate();\n INFO(Form(\"Finished task: %s\", dynamic_cast(*currentTask)->getSubTask()->GetName()));\n }\n return true;\n}\n\nvoid* JPetTaskExecutor::processProxy(void* runner)\n{\n assert(runner);\n static_cast(runner)->process();\n return 0;\n}\n\nTThread* JPetTaskExecutor::run()\n{\n TThread* thread = new TThread(to_string(fProcessedFile).c_str(), processProxy, (void*)this);\n assert(thread);\n thread->Run();\n return thread;\n}\n\nbool JPetTaskExecutor::processFromCmdLineArgs(int)\n{\n auto runNum = fOptions.getRunNumber();\n if (runNum >= 0) {\n try {\n fParamManager->fillParameterBank(runNum);\n } catch (...) {\n ERROR(\"Param bank was not generated correctly.\\n The run number used:\" + JPetCommonTools::intToString(runNum));\n return false;\n }\n if (fOptions.isLocalDBCreate()) {\n JPetParamSaverAscii saver;\n saver.saveParamBank(fParamManager->getParamBank(), runNum, fOptions.getLocalDBCreate());\n }\n }\n \n auto inputFileType = fOptions.getInputFileType();\n auto inputFile = fOptions.getInputFile();\n if (inputFileType == JPetOptions::kScope) {\n createScopeTaskAndAddToTaskList();\n } else if (inputFileType == JPetOptions::kHld) {\n long long nevents = fOptions.getTotalEvents();\n if (nevents > 0) {\n fUnpacker.setParams(fOptions.getInputFile(), nevents);\n WARNING(std::string(\"Even though the range of events was set, only the first \") + JPetCommonTools::intToString(nevents) + std::string(\" will be unpacked by the unpacker. \\n The unpacker always starts from the beginning of the file.\"));\n } else {\n fUnpacker.setParams(fOptions.getInputFile());\n }\n unpackFile();\n }\n else if( inputFileType == JPetOptions::kZip){\n INFO( std::string(\"Unzipping file before unpacking\") );\n unzipFile();\n \/\/Changing file name to proper one after unzipping\n std::string sInputFile = inputFile;\n sInputFile = sInputFile.substr(0, sInputFile.find(\".gz\"));\n \n inputFile = sInputFile.c_str();\n \/\/ copied from above, since one cannot \n long long nevents = fOptions.getTotalEvents();\n if (nevents > 0) {\n fUnpacker.setParams( inputFile, nevents);\n WARNING(std::string(\"Even though the range of events was set, only the first \") + JPetCommonTools::intToString(nevents) + std::string(\" will be unpacked by the unpacker. \\n The unpacker always starts from the beginning of the file.\"));\n } else {\n fUnpacker.setParams(inputFile);\n }\n fUnpacker.exec();\n }\n \n if(fOptions.getInputFileType() == JPetOptions::kUndefinedFileType)\n ERROR( Form(\"Unknown file type provided for file: %s\", fOptions.getInputFile()) );\n \n return true;\n}\n\nvoid JPetTaskExecutor::createScopeTaskAndAddToTaskList()\n{\n JPetScopeLoader* module = new JPetScopeLoader(new JPetScopeTask(\"JPetScopeReader\", \"Process Oscilloscope ASCII data into JPetRecoSignal structures.\"));\n assert(module);\n module->setParamManager(fParamManager);\n auto scopeFile = fOptions.getScopeConfigFile();\n if (!fParamManager->getParametersFromScopeConfig(scopeFile)) {\n ERROR(\"Unable to generate Param Bank from Scope Config\");\n }\n fTasks.push_front(module);\n}\n\nvoid JPetTaskExecutor::unpackFile()\n{\n if (fOptions.getInputFileType() == JPetOptions::kHld) {\n fUnpacker.exec();\n } else {\n WARNING(\"Input file is not hld and unpacker was supposed to be called!\");\n }\n}\n\nvoid JPetTaskExecutor::unzipFile()\n{ \n if( (fOptions.getInputFileType() == JPetOptions::kZip) ) {\n system(Form(\"gzip -d %s\", fOptions.getInputFile() ) ); \n }\n else {\n WARNING(\"Input file is not zip and cannot be unzipped\");\n }\n}\n\n\nJPetTaskExecutor::~JPetTaskExecutor()\n{\n for (auto & task : fTasks) {\n if (task) {\n delete task;\n task = 0;\n }\n }\n}\n<|endoftext|>"} {"text":"#include \"carbon_user.h\"\n#include \n#include \n#include \n\n\/\/ Suggested DVFS domain configuration:\n\/\/ <1.0, CORE, L1_ICACHE, L1_DCACHE> <1.0, L2_CACHE, DIRECTORY> <1.0, NETWORK_MEMORY, NETWORK_USER>\n\nvoid doMemoryWork()\n{\n \/\/int ARRAY_SIZE = 8192*64;\n int ARRAY_SIZE = 512*64;\n int NUM_ITERATIONS = 100;\n int8_t array [ARRAY_SIZE];\n for (int i=0; i[dvfs][tests] Better error statements for dvfs unit tests#include \"carbon_user.h\"\n#include \n#include \n#include \n\n\/\/ Suggested DVFS domain configuration:\n\/\/ <1.0, CORE, L1_ICACHE, L1_DCACHE> <1.0, L2_CACHE, DIRECTORY> <1.0, NETWORK_MEMORY, NETWORK_USER>\n\nvoid doMemoryWork()\n{\n \/\/int ARRAY_SIZE = 8192*64;\n int ARRAY_SIZE = 512*64;\n int NUM_ITERATIONS = 100;\n int8_t array [ARRAY_SIZE];\n for (int i=0; i"} {"text":"\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2017 Couchbase, Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"config.h\"\n#include \"memcached.h\"\n#include \"mcaudit.h\"\n#include \"memcached_audit_events.h\"\n#include \"buckets.h\"\n#include \"debug_helpers.h\"\n#include \"runtime.h\"\n\n#include \n#include \n#include \n\nstatic std::atomic_bool audit_enabled{false};\n\nstatic const int First = MEMCACHED_AUDIT_OPENED_DCP_CONNECTION;\nstatic const int Last = MEMCACHED_AUDIT_DOCUMENT_DELETE;\n\nstatic std::array events;\n\nstatic bool isEnabled(uint32_t id) {\n if (!audit_enabled.load(std::memory_order_consume)) {\n \/\/ Global switch is off.. All events are disabled\n return false;\n }\n\n if (id >= First && id <= Last) {\n \/\/ This is one of ours\n return events[id - First].load(std::memory_order_consume);\n }\n\n \/\/ we don't have information about this id... let the underlying event\n \/\/ framework deal with it\n return true;\n}\n\nvoid setEnabled(uint32_t id, bool enable) {\n bool expected = !enable;\n\n if (id == 0) {\n if (audit_enabled.compare_exchange_strong(expected, enable)) {\n LOG_INFO(\"Audit changed from: {} to: {}\",\n !enable ? \"enabled\" : \"disabled\",\n enable ? \"enabled\" : \"disabled\");\n }\n }\n\n if (id >= First && id <= Last) {\n if (events[id - First].compare_exchange_strong(expected, enable)) {\n LOG_INFO(\"Audit descriptor {} changed from: {} to: {}\",\n id,\n expected ? \"enabled\" : \"disabled\",\n enable ? \"enabled\" : \"disabled\");\n }\n }\n}\n\n\/**\n * Create the typical memcached audit object. It constists of a\n * timestamp, the socket endpoints and the creds. Then each audit event\n * may add event-specific content.\n *\n * @param c the connection object\n * @return the cJSON object containing the basic information\n *\/\nstatic unique_cJSON_ptr create_memcached_audit_object(const Connection* c) {\n cJSON *root = cJSON_CreateObject();\n\n std::string timestamp = ISOTime::generatetimestamp();\n cJSON_AddStringToObject(root, \"timestamp\", timestamp.c_str());\n\n cJSON_AddStringToObject(root, \"peername\", c->getPeername().c_str());\n cJSON_AddStringToObject(root, \"sockname\", c->getSockname().c_str());\n cJSON *source = cJSON_CreateObject();\n cJSON_AddStringToObject(source, \"source\", \"memcached\");\n cJSON_AddStringToObject(source, \"user\", c->getUsername());\n cJSON_AddItemToObject(root, \"real_userid\", source);\n\n return unique_cJSON_ptr(root);\n}\n\n\/**\n * Convert the JSON object to text and send it to the audit framework\n *\n * @param c the connection object requesting the call\n * @param id the audit identifier\n * @param event the payload of the audit description\n * @param warn what to log if we're failing to put the audit event\n *\/\nstatic void do_audit(const Connection* c,\n uint32_t id,\n unique_cJSON_ptr& event,\n const char* warn) {\n auto text = to_string(event, false);\n auto status = put_audit_event(get_audit_handle(), id, text.data(),\n text.length());\n\n if (status != AUDIT_SUCCESS) {\n LOG_WARNING(\"{}: {}\", warn, text);\n }\n}\n\nvoid audit_auth_failure(const Connection* c, const char* reason) {\n if (!isEnabled(MEMCACHED_AUDIT_AUTHENTICATION_FAILED)) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n cJSON_AddStringToObject(root.get(), \"reason\", reason);\n\n do_audit(c, MEMCACHED_AUDIT_AUTHENTICATION_FAILED, root,\n \"Failed to send AUTH FAILED audit event\");\n}\n\nvoid audit_auth_success(const Connection* c) {\n if (!isEnabled(MEMCACHED_AUDIT_AUTHENTICATION_SUCCEEDED)) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n do_audit(c, MEMCACHED_AUDIT_AUTHENTICATION_SUCCEEDED, root,\n \"Failed to send AUTH SUCCESS audit event\");\n}\n\nvoid audit_bucket_flush(const Connection* c, const char* bucket) {\n if (!isEnabled(MEMCACHED_AUDIT_BUCKET_FLUSH)) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n cJSON_AddStringToObject(root.get(), \"bucket\", bucket);\n\n do_audit(c, MEMCACHED_AUDIT_BUCKET_FLUSH, root,\n \"Failed to send BUCKET_FLUSH audit event\");\n}\n\nvoid audit_dcp_open(const Connection* c) {\n if (!isEnabled(MEMCACHED_AUDIT_OPENED_DCP_CONNECTION)) {\n return;\n }\n if (c->isInternal()) {\n LOG_INFO(\"Open DCP stream with admin credentials\");\n } else {\n auto root = create_memcached_audit_object(c);\n cJSON_AddStringToObject(root.get(), \"bucket\", getBucketName(c));\n\n do_audit(c, MEMCACHED_AUDIT_OPENED_DCP_CONNECTION, root,\n \"Failed to send DCP open connection \"\n \"audit event to audit daemon\");\n }\n}\n\nvoid audit_set_privilege_debug_mode(const Connection* c, bool enable) {\n if (!isEnabled(MEMCACHED_AUDIT_PRIVILEGE_DEBUG_CONFIGURED)) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n cJSON_AddBoolToObject(root.get(), \"enable\", enable);\n do_audit(c, MEMCACHED_AUDIT_PRIVILEGE_DEBUG_CONFIGURED, root,\n \"Failed to send modifications in privilege debug state \"\n \"audit event to audit daemon\");\n}\n\nvoid audit_privilege_debug(const Connection* c,\n const std::string& command,\n const std::string& bucket,\n const std::string& privilege,\n const std::string& context) {\n if (!isEnabled(MEMCACHED_AUDIT_PRIVILEGE_DEBUG)) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n cJSON_AddStringToObject(root.get(), \"command\", command.c_str());\n cJSON_AddStringToObject(root.get(), \"bucket\", bucket.c_str());\n cJSON_AddStringToObject(root.get(), \"privilege\", privilege.c_str());\n cJSON_AddStringToObject(root.get(), \"context\", context.c_str());\n\n do_audit(c, MEMCACHED_AUDIT_PRIVILEGE_DEBUG, root,\n \"Failed to send privilege debug audit event to audit daemon\");\n}\n\nvoid audit_command_access_failed(const Cookie& cookie) {\n if (!isEnabled(MEMCACHED_AUDIT_COMMAND_ACCESS_FAILURE)) {\n return;\n }\n const auto& connection = cookie.getConnection();\n auto root = create_memcached_audit_object(&connection);\n char buffer[256];\n memset(buffer, 0, sizeof(buffer));\n const auto packet = cookie.getPacket();\n \/\/ Deliberately ignore failure of bytes_to_output_string\n \/\/ We'll either have a partial string or no string.\n bytes_to_output_string(buffer,\n sizeof(buffer),\n connection.getId(),\n true,\n \"Access to command is not allowed:\",\n reinterpret_cast(packet.data()),\n packet.size());\n cJSON_AddStringToObject(root.get(), \"packet\", buffer);\n do_audit(&connection, MEMCACHED_AUDIT_COMMAND_ACCESS_FAILURE, root, buffer);\n}\n\nvoid audit_invalid_packet(const Cookie& cookie) {\n if (!isEnabled(MEMCACHED_AUDIT_INVALID_PACKET)) {\n return;\n }\n const auto& connection = cookie.getConnection();\n auto root = create_memcached_audit_object(&connection);\n char buffer[256];\n memset(buffer, 0, sizeof(buffer));\n const auto packet = cookie.getPacket();\n \/\/ Deliberately ignore failure of bytes_to_output_string\n \/\/ We'll either have a partial string or no string.\n bytes_to_output_string(buffer,\n sizeof(buffer),\n connection.getId(),\n true,\n \"Invalid Packet:\",\n reinterpret_cast(packet.data()),\n packet.size());\n cJSON_AddStringToObject(root.get(), \"packet\", buffer);\n do_audit(&connection, MEMCACHED_AUDIT_INVALID_PACKET, root, buffer);\n}\n\nbool mc_audit_event(uint32_t audit_eventid, cb::const_byte_buffer payload) {\n if (!audit_enabled) {\n return true;\n }\n\n return put_audit_event(get_audit_handle(),\n audit_eventid,\n payload.data(),\n payload.size()) == AUDIT_SUCCESS;\n}\n\nnamespace cb {\nnamespace audit {\nnamespace document {\n\nvoid add(const Cookie& cookie, Operation operation) {\n uint32_t id = 0;\n switch (operation) {\n case Operation::Read:\n id = MEMCACHED_AUDIT_DOCUMENT_READ;\n break;\n case Operation::Lock:\n id = MEMCACHED_AUDIT_DOCUMENT_LOCKED;\n break;\n case Operation::Modify:\n id = MEMCACHED_AUDIT_DOCUMENT_MODIFY;\n break;\n case Operation::Delete:\n id = MEMCACHED_AUDIT_DOCUMENT_DELETE;\n break;\n }\n\n if (id == 0) {\n throw std::invalid_argument(\n \"cb::audit::document::add: Invalid operation\");\n }\n\n if (!isEnabled(id)) {\n return;\n }\n\n const auto& connection = cookie.getConnection();\n auto root = create_memcached_audit_object(&connection);\n cJSON_AddStringToObject(root.get(), \"bucket\", connection.getBucket().name);\n cJSON_AddStringToObject(\n root.get(), \"key\", cookie.getPrintableRequestKey().c_str());\n\n switch (operation) {\n case Operation::Read:\n do_audit(&connection,\n MEMCACHED_AUDIT_DOCUMENT_READ,\n root,\n \"Failed to send document read audit event to audit daemon\");\n break;\n case Operation::Lock:\n do_audit(&connection,\n MEMCACHED_AUDIT_DOCUMENT_LOCKED,\n root,\n \"Failed to send document locked audit event to audit daemon\");\n break;\n case Operation::Modify:\n do_audit(&connection,\n MEMCACHED_AUDIT_DOCUMENT_MODIFY,\n root,\n \"Failed to send document modify audit event to audit daemon\");\n break;\n case Operation::Delete:\n do_audit(&connection,\n MEMCACHED_AUDIT_DOCUMENT_DELETE,\n root,\n \"Failed to send document delete audit event to audit daemon\");\n break;\n }\n}\n\n} \/\/ namespace documnent\n} \/\/ namespace audit\n} \/\/ namespace cb\n\n\n\nstatic void event_state_listener(uint32_t id, bool enabled) {\n setEnabled(id, enabled);\n}\n\nvoid initialize_audit() {\n\/* Start the audit daemon *\/\n AUDIT_EXTENSION_DATA audit_extension_data;\n memset(&audit_extension_data, 0, sizeof(audit_extension_data));\n audit_extension_data.notify_io_complete = notify_io_complete;\n audit_extension_data.configfile = settings.getAuditFile().c_str();\n Audit* handle = nullptr;\n if (start_auditdaemon(&audit_extension_data, &handle) != AUDIT_SUCCESS) {\n FATAL_ERROR(EXIT_FAILURE, \"FATAL: Failed to start audit daemon\");\n }\n set_audit_handle(handle);\n cb::audit::add_event_state_listener(handle, event_state_listener);\n cb::audit::notify_all_event_states(handle);\n}\nMB-29238: Use domain instead of source for memcached audit events\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2017 Couchbase, Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"config.h\"\n#include \"memcached.h\"\n#include \"mcaudit.h\"\n#include \"memcached_audit_events.h\"\n#include \"buckets.h\"\n#include \"debug_helpers.h\"\n#include \"runtime.h\"\n\n#include \n#include \n#include \n\nstatic std::atomic_bool audit_enabled{false};\n\nstatic const int First = MEMCACHED_AUDIT_OPENED_DCP_CONNECTION;\nstatic const int Last = MEMCACHED_AUDIT_DOCUMENT_DELETE;\n\nstatic std::array events;\n\nstatic bool isEnabled(uint32_t id) {\n if (!audit_enabled.load(std::memory_order_consume)) {\n \/\/ Global switch is off.. All events are disabled\n return false;\n }\n\n if (id >= First && id <= Last) {\n \/\/ This is one of ours\n return events[id - First].load(std::memory_order_consume);\n }\n\n \/\/ we don't have information about this id... let the underlying event\n \/\/ framework deal with it\n return true;\n}\n\nvoid setEnabled(uint32_t id, bool enable) {\n bool expected = !enable;\n\n if (id == 0) {\n if (audit_enabled.compare_exchange_strong(expected, enable)) {\n LOG_INFO(\"Audit changed from: {} to: {}\",\n !enable ? \"enabled\" : \"disabled\",\n enable ? \"enabled\" : \"disabled\");\n }\n }\n\n if (id >= First && id <= Last) {\n if (events[id - First].compare_exchange_strong(expected, enable)) {\n LOG_INFO(\"Audit descriptor {} changed from: {} to: {}\",\n id,\n expected ? \"enabled\" : \"disabled\",\n enable ? \"enabled\" : \"disabled\");\n }\n }\n}\n\n\/**\n * Create the typical memcached audit object. It constists of a\n * timestamp, the socket endpoints and the creds. Then each audit event\n * may add event-specific content.\n *\n * @param c the connection object\n * @return the cJSON object containing the basic information\n *\/\nstatic unique_cJSON_ptr create_memcached_audit_object(const Connection* c) {\n cJSON *root = cJSON_CreateObject();\n\n std::string timestamp = ISOTime::generatetimestamp();\n cJSON_AddStringToObject(root, \"timestamp\", timestamp.c_str());\n\n cJSON_AddStringToObject(root, \"peername\", c->getPeername().c_str());\n cJSON_AddStringToObject(root, \"sockname\", c->getSockname().c_str());\n cJSON *domain = cJSON_CreateObject();\n cJSON_AddStringToObject(domain, \"domain\", \"memcached\");\n cJSON_AddStringToObject(domain, \"user\", c->getUsername());\n cJSON_AddItemToObject(root, \"real_userid\", domain);\n\n return unique_cJSON_ptr(root);\n}\n\n\/**\n * Convert the JSON object to text and send it to the audit framework\n *\n * @param c the connection object requesting the call\n * @param id the audit identifier\n * @param event the payload of the audit description\n * @param warn what to log if we're failing to put the audit event\n *\/\nstatic void do_audit(const Connection* c,\n uint32_t id,\n unique_cJSON_ptr& event,\n const char* warn) {\n auto text = to_string(event, false);\n auto status = put_audit_event(get_audit_handle(), id, text.data(),\n text.length());\n\n if (status != AUDIT_SUCCESS) {\n LOG_WARNING(\"{}: {}\", warn, text);\n }\n}\n\nvoid audit_auth_failure(const Connection* c, const char* reason) {\n if (!isEnabled(MEMCACHED_AUDIT_AUTHENTICATION_FAILED)) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n cJSON_AddStringToObject(root.get(), \"reason\", reason);\n\n do_audit(c, MEMCACHED_AUDIT_AUTHENTICATION_FAILED, root,\n \"Failed to send AUTH FAILED audit event\");\n}\n\nvoid audit_auth_success(const Connection* c) {\n if (!isEnabled(MEMCACHED_AUDIT_AUTHENTICATION_SUCCEEDED)) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n do_audit(c, MEMCACHED_AUDIT_AUTHENTICATION_SUCCEEDED, root,\n \"Failed to send AUTH SUCCESS audit event\");\n}\n\nvoid audit_bucket_flush(const Connection* c, const char* bucket) {\n if (!isEnabled(MEMCACHED_AUDIT_BUCKET_FLUSH)) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n cJSON_AddStringToObject(root.get(), \"bucket\", bucket);\n\n do_audit(c, MEMCACHED_AUDIT_BUCKET_FLUSH, root,\n \"Failed to send BUCKET_FLUSH audit event\");\n}\n\nvoid audit_dcp_open(const Connection* c) {\n if (!isEnabled(MEMCACHED_AUDIT_OPENED_DCP_CONNECTION)) {\n return;\n }\n if (c->isInternal()) {\n LOG_INFO(\"Open DCP stream with admin credentials\");\n } else {\n auto root = create_memcached_audit_object(c);\n cJSON_AddStringToObject(root.get(), \"bucket\", getBucketName(c));\n\n do_audit(c, MEMCACHED_AUDIT_OPENED_DCP_CONNECTION, root,\n \"Failed to send DCP open connection \"\n \"audit event to audit daemon\");\n }\n}\n\nvoid audit_set_privilege_debug_mode(const Connection* c, bool enable) {\n if (!isEnabled(MEMCACHED_AUDIT_PRIVILEGE_DEBUG_CONFIGURED)) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n cJSON_AddBoolToObject(root.get(), \"enable\", enable);\n do_audit(c, MEMCACHED_AUDIT_PRIVILEGE_DEBUG_CONFIGURED, root,\n \"Failed to send modifications in privilege debug state \"\n \"audit event to audit daemon\");\n}\n\nvoid audit_privilege_debug(const Connection* c,\n const std::string& command,\n const std::string& bucket,\n const std::string& privilege,\n const std::string& context) {\n if (!isEnabled(MEMCACHED_AUDIT_PRIVILEGE_DEBUG)) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n cJSON_AddStringToObject(root.get(), \"command\", command.c_str());\n cJSON_AddStringToObject(root.get(), \"bucket\", bucket.c_str());\n cJSON_AddStringToObject(root.get(), \"privilege\", privilege.c_str());\n cJSON_AddStringToObject(root.get(), \"context\", context.c_str());\n\n do_audit(c, MEMCACHED_AUDIT_PRIVILEGE_DEBUG, root,\n \"Failed to send privilege debug audit event to audit daemon\");\n}\n\nvoid audit_command_access_failed(const Cookie& cookie) {\n if (!isEnabled(MEMCACHED_AUDIT_COMMAND_ACCESS_FAILURE)) {\n return;\n }\n const auto& connection = cookie.getConnection();\n auto root = create_memcached_audit_object(&connection);\n char buffer[256];\n memset(buffer, 0, sizeof(buffer));\n const auto packet = cookie.getPacket();\n \/\/ Deliberately ignore failure of bytes_to_output_string\n \/\/ We'll either have a partial string or no string.\n bytes_to_output_string(buffer,\n sizeof(buffer),\n connection.getId(),\n true,\n \"Access to command is not allowed:\",\n reinterpret_cast(packet.data()),\n packet.size());\n cJSON_AddStringToObject(root.get(), \"packet\", buffer);\n do_audit(&connection, MEMCACHED_AUDIT_COMMAND_ACCESS_FAILURE, root, buffer);\n}\n\nvoid audit_invalid_packet(const Cookie& cookie) {\n if (!isEnabled(MEMCACHED_AUDIT_INVALID_PACKET)) {\n return;\n }\n const auto& connection = cookie.getConnection();\n auto root = create_memcached_audit_object(&connection);\n char buffer[256];\n memset(buffer, 0, sizeof(buffer));\n const auto packet = cookie.getPacket();\n \/\/ Deliberately ignore failure of bytes_to_output_string\n \/\/ We'll either have a partial string or no string.\n bytes_to_output_string(buffer,\n sizeof(buffer),\n connection.getId(),\n true,\n \"Invalid Packet:\",\n reinterpret_cast(packet.data()),\n packet.size());\n cJSON_AddStringToObject(root.get(), \"packet\", buffer);\n do_audit(&connection, MEMCACHED_AUDIT_INVALID_PACKET, root, buffer);\n}\n\nbool mc_audit_event(uint32_t audit_eventid, cb::const_byte_buffer payload) {\n if (!audit_enabled) {\n return true;\n }\n\n return put_audit_event(get_audit_handle(),\n audit_eventid,\n payload.data(),\n payload.size()) == AUDIT_SUCCESS;\n}\n\nnamespace cb {\nnamespace audit {\nnamespace document {\n\nvoid add(const Cookie& cookie, Operation operation) {\n uint32_t id = 0;\n switch (operation) {\n case Operation::Read:\n id = MEMCACHED_AUDIT_DOCUMENT_READ;\n break;\n case Operation::Lock:\n id = MEMCACHED_AUDIT_DOCUMENT_LOCKED;\n break;\n case Operation::Modify:\n id = MEMCACHED_AUDIT_DOCUMENT_MODIFY;\n break;\n case Operation::Delete:\n id = MEMCACHED_AUDIT_DOCUMENT_DELETE;\n break;\n }\n\n if (id == 0) {\n throw std::invalid_argument(\n \"cb::audit::document::add: Invalid operation\");\n }\n\n if (!isEnabled(id)) {\n return;\n }\n\n const auto& connection = cookie.getConnection();\n auto root = create_memcached_audit_object(&connection);\n cJSON_AddStringToObject(root.get(), \"bucket\", connection.getBucket().name);\n cJSON_AddStringToObject(\n root.get(), \"key\", cookie.getPrintableRequestKey().c_str());\n\n switch (operation) {\n case Operation::Read:\n do_audit(&connection,\n MEMCACHED_AUDIT_DOCUMENT_READ,\n root,\n \"Failed to send document read audit event to audit daemon\");\n break;\n case Operation::Lock:\n do_audit(&connection,\n MEMCACHED_AUDIT_DOCUMENT_LOCKED,\n root,\n \"Failed to send document locked audit event to audit daemon\");\n break;\n case Operation::Modify:\n do_audit(&connection,\n MEMCACHED_AUDIT_DOCUMENT_MODIFY,\n root,\n \"Failed to send document modify audit event to audit daemon\");\n break;\n case Operation::Delete:\n do_audit(&connection,\n MEMCACHED_AUDIT_DOCUMENT_DELETE,\n root,\n \"Failed to send document delete audit event to audit daemon\");\n break;\n }\n}\n\n} \/\/ namespace documnent\n} \/\/ namespace audit\n} \/\/ namespace cb\n\n\n\nstatic void event_state_listener(uint32_t id, bool enabled) {\n setEnabled(id, enabled);\n}\n\nvoid initialize_audit() {\n\/* Start the audit daemon *\/\n AUDIT_EXTENSION_DATA audit_extension_data;\n memset(&audit_extension_data, 0, sizeof(audit_extension_data));\n audit_extension_data.notify_io_complete = notify_io_complete;\n audit_extension_data.configfile = settings.getAuditFile().c_str();\n Audit* handle = nullptr;\n if (start_auditdaemon(&audit_extension_data, &handle) != AUDIT_SUCCESS) {\n FATAL_ERROR(EXIT_FAILURE, \"FATAL: Failed to start audit daemon\");\n }\n set_audit_handle(handle);\n cb::audit::add_event_state_listener(handle, event_state_listener);\n cb::audit::notify_all_event_states(handle);\n}\n<|endoftext|>"} {"text":"\/*\n incomingtransfer.cpp - msn p2p protocol\n\n Copyright (c) 2003-2005 by Olivier Goffart \n Copyright (c) 2005 by Gregg Edghill \n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include \"incomingtransfer.h\"\nusing P2P::TransferContext;\nusing P2P::IncomingTransfer;\nusing P2P::Message;\n\n\/\/ Kde includes\n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace KNetwork;\n\n\/\/ Qt includes\n#include \n#include \n\n\/\/ Kopete includes\n#include \n\nIncomingTransfer::IncomingTransfer(const QString& from, P2P::Dispatcher *dispatcher, Q_UINT32 sessionId)\n: TransferContext(from,dispatcher,sessionId)\n{\n\tm_direction = P2P::Incoming;\n\tm_listener = 0l;\n}\n\nIncomingTransfer::~IncomingTransfer()\n{\n\tkdDebug(14140) << k_funcinfo << endl;\n\tif(m_listener)\n\t{\n\t\tdelete m_listener;\n\t\tm_listener = 0l;\n\t}\n\n\tif(m_socket)\n\t{\n\t\tdelete m_socket;\n\t\tm_socket = 0l;\n\t}\n}\n\n\nvoid IncomingTransfer::slotTransferAccepted(Kopete::Transfer* transfer, const QString& \/*fileName*\/)\n{\n\tQ_UINT32 sessionId = transfer->info().internalId().toUInt();\n\tif(sessionId!=m_sessionId)\n\t\treturn;\n\t\n\tQObject::connect(transfer , SIGNAL(transferCanceled()), this, SLOT(abort()));\n\tm_transfer = transfer;\n\t\t\n\tQString content = QString(\"SessionID: %1\\r\\n\\r\\n\").arg(sessionId);\n\tsendMessage(OK, content);\n\t\n\tQObject::disconnect(Kopete::TransferManager::transferManager(), 0l, this, 0l);\n}\n\nvoid IncomingTransfer::slotTransferRefused(const Kopete::FileTransferInfo& info)\n{\n\tQ_UINT32 sessionId = info.internalId().toUInt();\n\tif(sessionId!=m_sessionId)\n\t\treturn;\n\t\n\tQString content = QString(\"SessionID: %1\\r\\n\\r\\n\").arg(sessionId);\n\t\/\/ Send the sending client a cancelation message.\n\tsendMessage(DECLINE, content);\n\tm_state=Finished;\n\t\n\tQObject::disconnect(Kopete::TransferManager::transferManager(), 0l, this, 0l);\n}\n\n\n\nvoid IncomingTransfer::acknowledged()\n{\n\tkdDebug(14140) << k_funcinfo << endl;\n\t\n\tswitch(m_state)\n\t{\n\t\tcase Invitation:\n\t\t\t\t\/\/ NOTE UDI: base identifier acknowledge message, ignore.\n\t\t\t\t\/\/ UDI: 200 OK message should follow.\n\t\t\t\tif(m_type == File){\n\t\t\t\t\t\/\/ FT: 200 OK acknowledged message.\n\t\t\t\t\t\/\/ Direct connection invitation should follow.\n\t\t\t\t\tm_state = Negotiation;\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\tcase Negotiation:\n\t\t\t\t\/\/ 200 OK acknowledge message.\n\t\t\tbreak;\n\n\t\tcase DataTransfer:\n\t\t\tbreak;\n\t\t\t\n\t\tcase Finished:\n\t\t\t\/\/ UDI: Bye acknowledge message.\n\t\t\tm_dispatcher->detach(this);\n\t\t\tbreak;\n\t}\n}\n\nvoid IncomingTransfer::processMessage(const Message& message)\n{\n\tif(m_file && (message.header.flag == 0x20 || message.header.flag == 0x01000030))\n\t{\n\t\t\/\/ UserDisplayIcon data or File data is in this message.\n\t\t\/\/ Write the recieved data to the file.\n\t\tkdDebug(14140) << k_funcinfo << QString(\"Received, %1 bytes\").arg(message.header.dataSize) << endl;\n\t\t\n\t\tm_file->writeBlock(message.body.data(), message.header.dataSize);\n\t\tif(m_transfer){\n\t\t\tm_transfer->slotProcessed(message.header.dataOffset + message.header.dataSize);\n\t\t}\n\t\t\n\t\tif((message.header.dataOffset + message.header.dataSize) == message.header.totalDataSize)\n\t\t{\n\t\t\t\/\/ Transfer is complete.\n\t\t\tif(m_type == UserDisplayIcon){\n\t\t\t\tm_tempFile->close();\n\t\t\t\tm_dispatcher->displayIconReceived(m_tempFile, m_object);\n\t\t\t\tm_tempFile = 0l;\n\t\t\t\tm_file = 0l;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_file->close();\n\t\t\t}\n\n\t\t\tm_isComplete = true;\n\t\t\t\/\/ Send data acknowledge message.\n\t\t\tacknowledge(message);\n\n\t\t\tif(m_type == UserDisplayIcon)\n\t\t\t{\n\t\t\t\tm_state = Finished;\n\t\t\t\t\/\/ Send BYE message.\n\t\t\t\tsendMessage(BYE, \"\\r\\n\");\n\t\t\t}\n\t\t}\n\t}\n\telse if(message.header.dataSize == 4 && message.applicationIdentifier == 1)\n\t{\n\t\t\/\/ Data preparation message.\n\t\tm_tempFile = new KTempFile(locateLocal(\"tmp\", \"msnpicture--\"), \".png\");\n\t\tm_tempFile->setAutoDelete(true);\n\t\tm_file = m_tempFile->file();\n\t\tm_state = DataTransfer;\n\t\t\/\/ Send data preparation acknowledge message.\n\t\tacknowledge(message);\n\t}\n\telse\n\t{\n\t\tQString body =\n\t\t\tQCString(message.body.data(), message.header.dataSize);\n\/\/\t\tkdDebug(14140) << k_funcinfo << \"received, \" << body << endl;\n\n\t\tif(body.startsWith(\"INVITE\"))\n\t\t{\n\t\t\t\/\/ Retrieve some MSNSLP headers used when\n\t\t\t\/\/ replying to this INVITE message.\n\t\t\tQRegExp regex(\";branch=\\\\{([0-9A-F\\\\-]*)\\\\}\\r\\n\");\n\t\t\tregex.search(body);\n\t\t\tm_branch = regex.cap(1);\n\t\t\t\/\/ NOTE Call-ID never changes.\n\t\t\tregex = QRegExp(\"Call-ID: \\\\{([0-9A-F\\\\-]*)\\\\}\\r\\n\");\n\t\t\tregex.search(body);\n\t\t\tm_callId = regex.cap(1);\n\t\t\tregex = QRegExp(\"Bridges: ([^\\r\\n]*)\\r\\n\");\n\t\t\tregex.search(body);\n\t\t\tQString bridges = regex.cap(1);\n\t\t\t\/\/ The NetID field is 0 if the Conn-Type is\n\t\t\t\/\/ Direct-Connect or Firewall, otherwise, it is\n\t\t\t\/\/ a randomly generated number.\n\t\t\tregex = QRegExp(\"NetID: (\\\\-?\\\\d+)\\r\\n\");\n\t\t\tregex.search(body);\n\t\t\tQString netId = regex.cap(1);\n\t\t\tkdDebug(14140) << \"net id, \" << netId << endl;\n\t\t\t\/\/ Connection Types\n\t\t\t\/\/ - Direct-Connect\n\t\t\t\/\/ - Port-Restrict-NAT\n\t\t\t\/\/ - IP-Restrict-NAT\n\t\t\t\/\/ - Symmetric-NAT\n\t\t\t\/\/ - Firewall\n\t\t\tregex = QRegExp(\"Conn-Type: ([^\\r\\n]+)\\r\\n\");\n\t\t\tregex.search(body);\n\t\t\tQString connType = regex.cap(1);\n\n\t\t\tbool wouldListen = false;\n\t\t\tif(netId.toUInt() == 0 && connType == \"Direct-Connect\"){\n\t\t\t\twouldListen = true;\n\n\t\t\t}\n\t\t\telse if(connType == \"IP-Restrict-NAT\"){\n\t\t\t\twouldListen = true;\n\t\t\t}\n#if 1\n\t\t\twouldListen = false; \/\/ TODO Direct connection support\n#endif\t\t\t\n\t\t\tQString content;\n\t\t\t\n\t\t\tif(wouldListen)\n\t\t\t{\n\t\t\t\t\/\/ Create a listening socket for direct file transfer.\n\t\t\t\tm_listener = new KServerSocket(\"\", \"\");\n\t\t\t\tm_listener->setResolutionEnabled(true);\n\t\t\t\t\/\/ Create the callback that will try to accept incoming connections.\n\t\t\t\tQObject::connect(m_listener, SIGNAL(readyAccept()), SLOT(slotAccept()));\n\t\t\t\tQObject::connect(m_listener, SIGNAL(gotError(int)), this, SLOT(slotListenError(int)));\n\t\t\t\t\/\/ Listen for incoming connections.\n\t\t\t\tbool isListening = m_listener->listen(1);\n\t\t\t\tkdDebug(14140) << k_funcinfo << (isListening ? \"listening\" : \"not listening\") << endl;\n\t\t\t\tkdDebug(14140) << k_funcinfo\n\t\t\t\t\t<< \"local endpoint, \" << m_listener->localAddress().nodeName()\n\t\t\t\t\t<< endl;\n\t\t\t\t\n\t\t\t\tcontent = \"Bridge: TCPv1\\r\\n\"\n\t\t\t\t\t\"Listening: true\\r\\n\" +\n\t\t\t\t\tQString(\"Hashed-Nonce: {%1}\\r\\n\").arg(P2P::Uid::createUid()) +\n\t\t\t\t\tQString(\"IPv4Internal-Addrs: %1\\r\\n\").arg(m_listener->localAddress().nodeName()) +\n\t\t\t\t\tQString(\"IPv4Internal-Port: %1\\r\\n\").arg(m_listener->localAddress().serviceName()) +\n\t\t\t\t\t\"\\r\\n\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcontent =\n\t\t\t\t\t\"Bridge: TCPv1\\r\\n\"\n\t\t\t\t\t\"Listening: false\\r\\n\"\n\t\t\t\t\t\"Hashed-Nonce: {00000000-0000-0000-0000-000000000000}\\r\\n\"\n\t\t\t\t\t\"\\r\\n\";\n\t\t\t}\n\n\t\t\tacknowledge(message);\n\n\t\t\tif(m_transfer)\n\t\t\t{\n\t\t\t\t\/\/ NOTE The sending client can ask for a direct connections\n\t\t\t\t\/\/ if one was established before.\n\t\t\t\tQFile *destionation = new QFile(m_transfer->destinationURL().path());\n\t\t\t\tif(!destionation->open(IO_WriteOnly))\n\t\t\t\t{\n\t\t\t\t\tif(m_transfer){\n\t\t\t\t\t\tm_transfer->slotError(KIO::ERR_CANNOT_OPEN_FOR_WRITING, i18n(\"Cannot open file for writing\"));\n\t\t\t\t\t\tm_transfer = 0l;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\terror();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\n\t\t\t\tm_file = destionation;\n\t\t\t}\n\t\t\t\n\t\t\tm_state = DataTransfer;\n\t\t\t\/\/ Send 200 OK message to the sending client.\n\t\t\tsendMessage(OK, content);\n\t\t}\n\t\telse if(body.startsWith(\"BYE\"))\n\t\t{\n\t\t\tm_state = Finished;\n\t\t\t\/\/ Send the sending client an acknowledge message.\n\t\t\tacknowledge(message);\n\n\t\t\tif(m_file && m_transfer)\n\t\t\t{\n\t\t\t\tif(m_isComplete){\n\t\t\t\t\t\/\/ The transfer is complete.\n\t\t\t\t\tm_transfer->slotComplete();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ The transfer has been canceled remotely.\n\t\t\t\t\tif(m_transfer){\n\t\t\t\t\t\t\/\/ Inform the user of the file transfer cancelation.\n\t\t\t\t\t\tm_transfer->slotError(KIO::ERR_ABORTED, i18n(\"File transfer canceled.\"));\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ Remove the partially received file.\n\t\t\t\t\tm_file->remove();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Dispose of this transfer context.\n\t\t\tm_dispatcher->detach(this);\n\t\t}\n\t\telse if(body.startsWith(\"MSNSLP\/1.0 200 OK\"))\n\t\t{\n\t\t\tif(m_type == UserDisplayIcon){\n\t\t\t\tm_state = Negotiation;\n\t\t\t\t\/\/ Acknowledge the 200 OK message.\n\t\t\t\tacknowledge(message);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid IncomingTransfer::slotListenError(int \/*errorCode*\/)\n{\n\tkdDebug(14140) << k_funcinfo << m_listener->errorString() << endl;\n}\n\nvoid IncomingTransfer::slotAccept()\n{\n\t\/\/ Try to accept an incoming connection from the sending client.\n\tm_socket = static_cast(m_listener->accept());\n\tif(!m_socket)\n\t{\n\t\t\/\/ NOTE If direct connection fails, the sending\n\t\t\/\/ client wil transfer the file data through the\n\t\t\/\/ existing session.\n\t\tkdDebug(14140) << k_funcinfo << \"Direct connection failed.\" << endl;\n\t\t\/\/ Close the listening endpoint.\n\t\tm_listener->close();\n\t\treturn;\n\t}\n\n\tkdDebug(14140) << k_funcinfo << \"Direct connection established.\" << endl;\n\n\t\/\/ Set the socket to non blocking,\n\t\/\/ enable the ready read signal and disable\n\t\/\/ ready write signal.\n\t\/\/ NOTE readyWrite consumes too much cpu usage.\n\tm_socket->setBlocking(false);\n\tm_socket->enableRead(true);\n\tm_socket->enableWrite(false);\n\n\t\/\/ Create the callback that will try to read bytes from the accepted socket.\n\tQObject::connect(m_socket, SIGNAL(readyRead()), this, SLOT(slotSocketRead()));\n\t\/\/ Create the callback that will try to handle the socket close event.\n\tQObject::connect(m_socket, SIGNAL(closed()), this, SLOT(slotSocketClosed()));\n\t\/\/ Create the callback that will try to handle the socket error event.\n\tQObject::connect(m_socket, SIGNAL(gotError(int)), this, SLOT(slotSocketError(int)));\n}\n\nvoid IncomingTransfer::slotSocketRead()\n{\n\tint available = m_socket->bytesAvailable();\n\tkdDebug(14140) << k_funcinfo << available << \", bytes available.\" << endl;\n\tif(available > 0)\n\t{\n\t\tQByteArray buffer(available);\n\t\tm_socket->readBlock(buffer.data(), buffer.size());\n\n\t\tif(QString(buffer) == \"foo\"){\n\t\t\tkdDebug(14140) << \"Connection Check.\" << endl;\n\t\t}\n\t}\n}\n\nvoid IncomingTransfer::slotSocketClosed()\n{\n\tkdDebug(14140) << k_funcinfo << endl;\n}\n\nvoid IncomingTransfer::slotSocketError(int errorCode)\n{\n\tkdDebug(14140) << k_funcinfo << errorCode << endl;\n}\n\n#include \"incomingtransfer.moc\"\nBUG: 113525\/*\n incomingtransfer.cpp - msn p2p protocol\n\n Copyright (c) 2003-2005 by Olivier Goffart \n Copyright (c) 2005 by Gregg Edghill \n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include \"incomingtransfer.h\"\nusing P2P::TransferContext;\nusing P2P::IncomingTransfer;\nusing P2P::Message;\n\n\/\/ Kde includes\n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace KNetwork;\n\n\/\/ Qt includes\n#include \n#include \n\n\/\/ Kopete includes\n#include \n\nIncomingTransfer::IncomingTransfer(const QString& from, P2P::Dispatcher *dispatcher, Q_UINT32 sessionId)\n: TransferContext(from,dispatcher,sessionId)\n{\n\tm_direction = P2P::Incoming;\n\tm_listener = 0l;\n}\n\nIncomingTransfer::~IncomingTransfer()\n{\n\tkdDebug(14140) << k_funcinfo << endl;\n\tif(m_listener)\n\t{\n\t\tdelete m_listener;\n\t\tm_listener = 0l;\n\t}\n\n\tif(m_socket)\n\t{\n\t\tdelete m_socket;\n\t\tm_socket = 0l;\n\t}\n}\n\n\nvoid IncomingTransfer::slotTransferAccepted(Kopete::Transfer* transfer, const QString& \/*fileName*\/)\n{\n\tQ_UINT32 sessionId = transfer->info().internalId().toUInt();\n\tif(sessionId!=m_sessionId)\n\t\treturn;\n\t\n\tQObject::connect(transfer , SIGNAL(transferCanceled()), this, SLOT(abort()));\n\tm_transfer = transfer;\n\t\t\n\tQString content = QString(\"SessionID: %1\\r\\n\\r\\n\").arg(sessionId);\n\tsendMessage(OK, content);\n\t\n\tQObject::disconnect(Kopete::TransferManager::transferManager(), 0l, this, 0l);\n}\n\nvoid IncomingTransfer::slotTransferRefused(const Kopete::FileTransferInfo& info)\n{\n\tQ_UINT32 sessionId = info.internalId().toUInt();\n\tif(sessionId!=m_sessionId)\n\t\treturn;\n\t\n\tQString content = QString(\"SessionID: %1\\r\\n\\r\\n\").arg(sessionId);\n\t\/\/ Send the sending client a cancelation message.\n\tsendMessage(DECLINE, content);\n\tm_state=Finished;\n\t\n\tQObject::disconnect(Kopete::TransferManager::transferManager(), 0l, this, 0l);\n}\n\n\n\nvoid IncomingTransfer::acknowledged()\n{\n\tkdDebug(14140) << k_funcinfo << endl;\n\t\n\tswitch(m_state)\n\t{\n\t\tcase Invitation:\n\t\t\t\t\/\/ NOTE UDI: base identifier acknowledge message, ignore.\n\t\t\t\t\/\/ UDI: 200 OK message should follow.\n\t\t\t\tif(m_type == File){\n\t\t\t\t\t\/\/ FT: 200 OK acknowledged message.\n\t\t\t\t\t\/\/ Direct connection invitation should follow.\n\t\t\t\t\tm_state = Negotiation;\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\tcase Negotiation:\n\t\t\t\t\/\/ 200 OK acknowledge message.\n\t\t\tbreak;\n\n\t\tcase DataTransfer:\n\t\t\tbreak;\n\t\t\t\n\t\tcase Finished:\n\t\t\t\/\/ UDI: Bye acknowledge message.\n\t\t\tm_dispatcher->detach(this);\n\t\t\tbreak;\n\t}\n}\n\nvoid IncomingTransfer::processMessage(const Message& message)\n{\n\tif(m_file && (message.header.flag == 0x20 || message.header.flag == 0x01000030))\n\t{\n\t\t\/\/ UserDisplayIcon data or File data is in this message.\n\t\t\/\/ Write the recieved data to the file.\n\t\tkdDebug(14140) << k_funcinfo << QString(\"Received, %1 bytes\").arg(message.header.dataSize) << endl;\n\t\t\n\t\tm_file->writeBlock(message.body.data(), message.header.dataSize);\n\t\tif(m_transfer){\n\t\t\tm_transfer->slotProcessed(message.header.dataOffset + message.header.dataSize);\n\t\t}\n\t\t\n\t\tif((message.header.dataOffset + message.header.dataSize) == message.header.totalDataSize)\n\t\t{\n\t\t\t\/\/ Transfer is complete.\n\t\t\tif(m_type == UserDisplayIcon){\n\t\t\t\tm_tempFile->close();\n\t\t\t\tm_dispatcher->displayIconReceived(m_tempFile, m_object);\n\t\t\t\tm_tempFile = 0l;\n\t\t\t\tm_file = 0l;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_file->close();\n\t\t\t}\n\n\t\t\tm_isComplete = true;\n\t\t\t\/\/ Send data acknowledge message.\n\t\t\tacknowledge(message);\n\n\t\t\tif(m_type == UserDisplayIcon)\n\t\t\t{\n\t\t\t\tm_state = Finished;\n\t\t\t\t\/\/ Send BYE message.\n\t\t\t\tsendMessage(BYE, \"\\r\\n\");\n\t\t\t}\n\t\t}\n\t}\n\telse if(message.header.dataSize == 4 && message.applicationIdentifier == 1)\n\t{\n\t\t\/\/ Data preparation message.\n\t\tm_tempFile = new KTempFile(locateLocal(\"tmp\", \"msnpicture--\"), \".png\");\n\t\tm_tempFile->setAutoDelete(true);\n\t\tm_file = m_tempFile->file();\n\t\tm_state = DataTransfer;\n\t\t\/\/ Send data preparation acknowledge message.\n\t\tacknowledge(message);\n\t}\n\telse\n\t{\n\t\tQString body =\n\t\t\tQCString(message.body.data(), message.header.dataSize);\n\/\/\t\tkdDebug(14140) << k_funcinfo << \"received, \" << body << endl;\n\n\t\tif(body.startsWith(\"INVITE\"))\n\t\t{\n\t\t\t\/\/ Retrieve some MSNSLP headers used when\n\t\t\t\/\/ replying to this INVITE message.\n\t\t\tQRegExp regex(\";branch=\\\\{([0-9A-F\\\\-]*)\\\\}\\r\\n\");\n\t\t\tregex.search(body);\n\t\t\tm_branch = regex.cap(1);\n\t\t\t\/\/ NOTE Call-ID never changes.\n\t\t\tregex = QRegExp(\"Call-ID: \\\\{([0-9A-F\\\\-]*)\\\\}\\r\\n\");\n\t\t\tregex.search(body);\n\t\t\tm_callId = regex.cap(1);\n\t\t\tregex = QRegExp(\"Bridges: ([^\\r\\n]*)\\r\\n\");\n\t\t\tregex.search(body);\n\t\t\tQString bridges = regex.cap(1);\n\t\t\t\/\/ The NetID field is 0 if the Conn-Type is\n\t\t\t\/\/ Direct-Connect or Firewall, otherwise, it is\n\t\t\t\/\/ a randomly generated number.\n\t\t\tregex = QRegExp(\"NetID: (\\\\-?\\\\d+)\\r\\n\");\n\t\t\tregex.search(body);\n\t\t\tQString netId = regex.cap(1);\n\t\t\tkdDebug(14140) << \"net id, \" << netId << endl;\n\t\t\t\/\/ Connection Types\n\t\t\t\/\/ - Direct-Connect\n\t\t\t\/\/ - Port-Restrict-NAT\n\t\t\t\/\/ - IP-Restrict-NAT\n\t\t\t\/\/ - Symmetric-NAT\n\t\t\t\/\/ - Firewall\n\t\t\tregex = QRegExp(\"Conn-Type: ([^\\r\\n]+)\\r\\n\");\n\t\t\tregex.search(body);\n\t\t\tQString connType = regex.cap(1);\n\n\t\t\tbool wouldListen = false;\n\t\t\tif(netId.toUInt() == 0 && connType == \"Direct-Connect\"){\n\t\t\t\twouldListen = true;\n\n\t\t\t}\n\t\t\telse if(connType == \"IP-Restrict-NAT\"){\n\t\t\t\twouldListen = true;\n\t\t\t}\n#if 1\n\t\t\twouldListen = false; \/\/ TODO Direct connection support\n#endif\t\t\t\n\t\t\tQString content;\n\t\t\t\n\t\t\tif(wouldListen)\n\t\t\t{\n\t\t\t\t\/\/ Create a listening socket for direct file transfer.\n\t\t\t\tm_listener = new KServerSocket(\"\", \"\");\n\t\t\t\tm_listener->setResolutionEnabled(true);\n\t\t\t\t\/\/ Create the callback that will try to accept incoming connections.\n\t\t\t\tQObject::connect(m_listener, SIGNAL(readyAccept()), SLOT(slotAccept()));\n\t\t\t\tQObject::connect(m_listener, SIGNAL(gotError(int)), this, SLOT(slotListenError(int)));\n\t\t\t\t\/\/ Listen for incoming connections.\n\t\t\t\tbool isListening = m_listener->listen(1);\n\t\t\t\tkdDebug(14140) << k_funcinfo << (isListening ? \"listening\" : \"not listening\") << endl;\n\t\t\t\tkdDebug(14140) << k_funcinfo\n\t\t\t\t\t<< \"local endpoint, \" << m_listener->localAddress().nodeName()\n\t\t\t\t\t<< endl;\n\t\t\t\t\n\t\t\t\tcontent = \"Bridge: TCPv1\\r\\n\"\n\t\t\t\t\t\"Listening: true\\r\\n\" +\n\t\t\t\t\tQString(\"Hashed-Nonce: {%1}\\r\\n\").arg(P2P::Uid::createUid()) +\n\t\t\t\t\tQString(\"IPv4Internal-Addrs: %1\\r\\n\").arg(m_listener->localAddress().nodeName()) +\n\t\t\t\t\tQString(\"IPv4Internal-Port: %1\\r\\n\").arg(m_listener->localAddress().serviceName()) +\n\t\t\t\t\t\"\\r\\n\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcontent =\n\t\t\t\t\t\"Bridge: TCPv1\\r\\n\"\n\t\t\t\t\t\"Listening: false\\r\\n\"\n\t\t\t\t\t\"Hashed-Nonce: {00000000-0000-0000-0000-000000000000}\\r\\n\"\n\t\t\t\t\t\"\\r\\n\";\n\t\t\t}\n\n\t\t\tacknowledge(message);\n\n\t\t\tif(m_transfer)\n\t\t\t{\n\t\t\t\t\/\/ NOTE The sending client can ask for a direct connections\n\t\t\t\t\/\/ if one was established before.\n\t\t\t\tif(!m_file)\n\t\t\t\t{\n\t\t\t\t\tQFile *destionation = new QFile(m_transfer->destinationURL().path());\n\t\t\t\t\tif(!destionation->open(IO_WriteOnly))\n\t\t\t\t\t{\n\t\t\t\t\t\tif(m_transfer){\n\t\t\t\t\t\t\tm_transfer->slotError(KIO::ERR_CANNOT_OPEN_FOR_WRITING, i18n(\"Cannot open file for writing\"));\n\t\t\t\t\t\t\tm_transfer = 0l;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\terror();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\tm_file = destionation;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ TODO\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tm_state = DataTransfer;\n\t\t\t\/\/ Send 200 OK message to the sending client.\n\t\t\tsendMessage(OK, content);\n\t\t}\n\t\telse if(body.startsWith(\"BYE\"))\n\t\t{\n\t\t\tm_state = Finished;\n\t\t\t\/\/ Send the sending client an acknowledge message.\n\t\t\tacknowledge(message);\n\n\t\t\tif(m_file && m_transfer)\n\t\t\t{\n\t\t\t\tif(m_isComplete){\n\t\t\t\t\t\/\/ The transfer is complete.\n\t\t\t\t\tm_transfer->slotComplete();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ The transfer has been canceled remotely.\n\t\t\t\t\tif(m_transfer){\n\t\t\t\t\t\t\/\/ Inform the user of the file transfer cancelation.\n\t\t\t\t\t\tm_transfer->slotError(KIO::ERR_ABORTED, i18n(\"File transfer canceled.\"));\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ Remove the partially received file.\n\t\t\t\t\tm_file->remove();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Dispose of this transfer context.\n\t\t\tm_dispatcher->detach(this);\n\t\t}\n\t\telse if(body.startsWith(\"MSNSLP\/1.0 200 OK\"))\n\t\t{\n\t\t\tif(m_type == UserDisplayIcon){\n\t\t\t\tm_state = Negotiation;\n\t\t\t\t\/\/ Acknowledge the 200 OK message.\n\t\t\t\tacknowledge(message);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid IncomingTransfer::slotListenError(int \/*errorCode*\/)\n{\n\tkdDebug(14140) << k_funcinfo << m_listener->errorString() << endl;\n}\n\nvoid IncomingTransfer::slotAccept()\n{\n\t\/\/ Try to accept an incoming connection from the sending client.\n\tm_socket = static_cast(m_listener->accept());\n\tif(!m_socket)\n\t{\n\t\t\/\/ NOTE If direct connection fails, the sending\n\t\t\/\/ client wil transfer the file data through the\n\t\t\/\/ existing session.\n\t\tkdDebug(14140) << k_funcinfo << \"Direct connection failed.\" << endl;\n\t\t\/\/ Close the listening endpoint.\n\t\tm_listener->close();\n\t\treturn;\n\t}\n\n\tkdDebug(14140) << k_funcinfo << \"Direct connection established.\" << endl;\n\n\t\/\/ Set the socket to non blocking,\n\t\/\/ enable the ready read signal and disable\n\t\/\/ ready write signal.\n\t\/\/ NOTE readyWrite consumes too much cpu usage.\n\tm_socket->setBlocking(false);\n\tm_socket->enableRead(true);\n\tm_socket->enableWrite(false);\n\n\t\/\/ Create the callback that will try to read bytes from the accepted socket.\n\tQObject::connect(m_socket, SIGNAL(readyRead()), this, SLOT(slotSocketRead()));\n\t\/\/ Create the callback that will try to handle the socket close event.\n\tQObject::connect(m_socket, SIGNAL(closed()), this, SLOT(slotSocketClosed()));\n\t\/\/ Create the callback that will try to handle the socket error event.\n\tQObject::connect(m_socket, SIGNAL(gotError(int)), this, SLOT(slotSocketError(int)));\n}\n\nvoid IncomingTransfer::slotSocketRead()\n{\n\tint available = m_socket->bytesAvailable();\n\tkdDebug(14140) << k_funcinfo << available << \", bytes available.\" << endl;\n\tif(available > 0)\n\t{\n\t\tQByteArray buffer(available);\n\t\tm_socket->readBlock(buffer.data(), buffer.size());\n\n\t\tif(QString(buffer) == \"foo\"){\n\t\t\tkdDebug(14140) << \"Connection Check.\" << endl;\n\t\t}\n\t}\n}\n\nvoid IncomingTransfer::slotSocketClosed()\n{\n\tkdDebug(14140) << k_funcinfo << endl;\n}\n\nvoid IncomingTransfer::slotSocketError(int errorCode)\n{\n\tkdDebug(14140) << k_funcinfo << errorCode << endl;\n}\n\n#include \"incomingtransfer.moc\"\n<|endoftext|>"} {"text":"{\n \/\/\n gROOT->Reset();\n c1 = new TCanvas(\"c1\",\"Help to run demos\",200,10,700,500);\n\n welcome = new TPaveText(.1,.8,.9,.97);\n welcome->AddText(\"Welcome to the ROOT demos\");\n welcome->SetTextColor(4);\n welcome->SetFillColor(24);\n welcome->Draw();\n\n hdemo = new TPaveText(.05,.05,.95,.7);\n hdemo->SetTextAlign(12);\n hdemo->SetTextFont(61);\n hdemo->AddText(\"- Run demo Hsimple first. Then in any order\");\n hdemo->AddText(\"- Click left mouse button to execute one demo\");\n hdemo->AddText(\"- Click right mouse button to see the title of the demo\");\n hdemo->AddText(\"- Click on 'Close Bar' to exit from the demo menu\");\n hdemo->AddText(\"- Select 'File\/Print' to print a Postscript view of the canvas\");\n hdemo->AddText(\"- You can execute a demo with the mouse or type commands\");\n hdemo->AddText(\"- During the demo (try on this canvas) you can :\");\n hdemo->AddText(\".... Use left button to move\/grow\/etc objects\");\n hdemo->AddText(\".... Use middle button to pop overlapping objects\");\n hdemo->AddText(\" (with 2-buttons mouse just use left and right buttons simultaneously)\");\n hdemo->AddText(\".... Use right button to get an object sensitive pop-up\");\n hdemo->SetAllWith(\"....\",\"color\",2);\n hdemo->SetAllWith(\"....\",\"font\",72);\n hdemo->SetAllWith(\"(with\",\"color\",4);\n hdemo->SetAllWith(\"(with\",\"font\",8);\n\n hdemo->Draw();\n}\nModify the help demo: -change the name of the canvas from c1 to chelp -change the font and colors{\n \/\/\n gROOT->Reset();\n new TCanvas(\"chelp\",\"Help to run demos\",200,10,700,500);\n\n welcome = new TPaveText(.1,.8,.9,.97);\n welcome->AddText(\"Welcome to the ROOT demos\");\n welcome->SetTextFont(32);\n welcome->SetTextColor(4);\n welcome->SetFillColor(24);\n welcome->Draw();\n\n hdemo = new TPaveText(.05,.05,.95,.7);\n hdemo->SetTextAlign(12);\n hdemo->SetTextFont(52);\n hdemo->AddText(\"- Run demo hsimple.C first. Then in any order\");\n hdemo->AddText(\"- Click left mouse button to execute one demo\");\n hdemo->AddText(\"- Click right mouse button to see the title of the demo\");\n hdemo->AddText(\"- Click on 'Close Bar' to exit from the demo menu\");\n hdemo->AddText(\"- Select 'File\/Print' to print a Postscript view of the canvas\");\n hdemo->AddText(\"- You can execute a demo with the mouse or type commands\");\n hdemo->AddText(\"- During the demo (try on this canvas) you can :\");\n hdemo->AddText(\" .... Use left button to move\/grow\/etc objects\");\n hdemo->AddText(\" .... Use middle button to pop overlapping objects\");\n hdemo->AddText(\" .... Use right button to get an object sensitive pop-up\");\n hdemo->AddText(\" \");\n hdemo->SetAllWith(\"....\",\"color\",2);\n hdemo->SetAllWith(\"....\",\"font\",72);\n hdemo->SetAllWith(\"....\",\"size\",0.04);\n\n hdemo->Draw();\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#if qPlatform_Linux\n#include \n#include \n#elif qPlatform_Windows\n#include \n#endif\n\n#include \"..\/Characters\/LineEndings.h\"\n#include \"..\/Characters\/StringBuilder.h\"\n#include \"..\/Execution\/Finally.h\"\n\n#include \"BackTrace.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\n\n\n\n\n\/*\n ********************************************************************************\n ********************************* Debug::BackTrace *****************************\n ********************************************************************************\n *\/\nString Debug::BackTrace ()\n{\n#if qPlatform_Linux\n \/\/ @see http:\/\/man7.org\/linux\/man-pages\/man3\/backtrace.3.html\n constexpr size_t kMaxStackSize_ = 100; \/\/ could look at return size and re-run if equals exactly...\n void* stackTraceBuf[kMaxStackSize_] {};\n int nptrs = ::backtrace (buffer, NEltsOf (stackTraceBuf));\n DbgTrace (\"backtrace() returned %d addresses\\n\", nptrs);\n char** syms = ::backtrace_symbols (stackTraceBuf, nptrs);\n if (syms == NULL) {\n DbgTrace (\"%d errno\", errno); \/\/ perror(\"backtrace_symbols\");\n return String {};\n }\n Execution::Finally cleanup ([syms] () { if (syms != nullptr) ::free (syms); });\n Characters::StringBuilder out;\n for (int j = 0; j < nptrs; j++) {\n out.Append (String::FromNarrowSDKString (syms[j]) + Characters::GetEOL ());\n }\n return out.str ();\n}\n#else\n return Characters::String {};\n#endif\n}\nminor cleanups for Debug::BackTrace ()\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#if qPlatform_Linux\n#include \n#include \n#elif qPlatform_Windows\n#include \n#endif\n\n#include \"..\/Characters\/LineEndings.h\"\n#include \"..\/Characters\/StringBuilder.h\"\n#include \"..\/Execution\/Finally.h\"\n\n#include \"BackTrace.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\n\n\n\n\n\/*\n ********************************************************************************\n ********************************* Debug::BackTrace *****************************\n ********************************************************************************\n *\/\nString Debug::BackTrace ()\n{\n#if qPlatform_Linux\n \/\/ @see http:\/\/man7.org\/linux\/man-pages\/man3\/backtrace.3.html\n constexpr size_t kMaxStackSize_ = 100; \/\/ could look at return size and re-run if equals exactly...\n void* stackTraceBuf[kMaxStackSize_] {};\n int nptrs = ::backtrace (stackTraceBuf, NEltsOf (stackTraceBuf));\n DbgTrace (\"backtrace() returned %d addresses\\n\", nptrs);\n char** syms = ::backtrace_symbols (stackTraceBuf, nptrs);\n if (syms == NULL) {\n DbgTrace (\"%d errno\", errno); \/\/ perror(\"backtrace_symbols\");\n return String {};\n }\n Execution::Finally cleanup ([syms] () { if (syms != nullptr) ::free (syms); });\n StringBuilder out;\n for (int j = 0; j < nptrs; j++) {\n out.Append (String::FromNarrowSDKString (syms[j]) + Characters::GetEOL ());\n }\n return out.str ();\n}\n#else\n return Characters::String {};\n#endif\n}\n<|endoftext|>"} {"text":"\n\/*\n icqaccount.cpp - ICQ Account Class\n\n Copyright (c) 2003 by Stefan Gehn\n Kopete (c) 2003 by the Kopete developers \n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n *\/\n\n#include \"icqaccount.h\"\n#include \"icqcontact.h\"\n#include \"icqprotocol.h\"\n#include \"icqchangestatus.h\"\n\n#include \n#include \n#include \n\n#include \"kopetestdaction.h\"\n\n#include \n\nICQAccount::ICQAccount(KopeteProtocol *parent, QString accountID, const char *name)\n\t: OscarAccount(parent, accountID, name, true)\n{\n\tmMyself = 0;\n\tmAwayDialog = new ICQChangeStatus(getEngine());\n}\n\nvoid ICQAccount::loaded()\n{\n\t\/\/ needs to be here because pluginData() does not work in constructor\n\tmMyself = new ICQContact(accountId(), pluginData(protocol(), \"NickName\"), this, 0L);\n}\n\nICQAccount::~ICQAccount()\n{\n\/\/\tkdDebug(14200) << k_funcinfo << \"[\" << accountId() << \"] deleted\" << endl;\n\tdelete mAwayDialog;\n}\n\nKActionMenu* ICQAccount::actionMenu()\n{\n\t\/\/ mActionMenu is managed by KopeteAccount. It is deleted when\n\t\/\/ it is no longer shown, so we can (safely) just make a new one here.\n\n\tKActionMenu* mActionMenu = new KActionMenu(accountId(),\n\t\t\"icq_protocol\", this, \"ICQAccount::mActionMenu\");\n\n\tICQProtocol *p = ICQProtocol::protocol();\n\n\tKAction* mActionOnline = new KAction(p->statusOnline.caption(),\n\t\tp->statusOnline.iconFor(this), 0,\n\t\tthis, SLOT(slotGoOnline()), this, \"ICQAccount::mActionOnline\");\n\n\tKAction* mActionOffline = new KAction(p->statusOffline.caption(),\n\t\tp->statusOffline.iconFor(this), 0,\n\t\tthis, SLOT(slotGoOffline()), this, \"ICQAccount::mActionOffline\");\n\n\tKAction* mActionAway\t\t= new KAction(p->statusAway.caption(),\n\t\tp->statusAway.iconFor(this), 0,\n\t\tthis, SLOT(slotGoAway()), this, \"ICQAccount::mActionAway\");\n\n\tKAction* mActionNA = new KAction(p->statusNA.caption(),\n\t\tp->statusNA.iconFor(this), 0,\n\t\tthis, SLOT(slotGoNA()), this, \"ICQAccount::mActionNA\");\n\n\tKAction* mActionDND = new KAction(p->statusDND.caption(),\n\t\tp->statusDND.iconFor(this), 0,\n\t\tthis, SLOT(slotGoDND()), this, \"ICQAccount::mActionDND\");\n\n\tKAction* mActionOccupied = new KAction(p->statusOCC.caption(),\n\t\tp->statusOCC.iconFor(this), 0,\n\t\tthis, SLOT(slotGoOCC()), this, \"ICQAccount::mActionOccupied\");\n\n\tKAction* mActionFFC = new KAction(p->statusFFC.caption(),\n\t\tp->statusFFC.iconFor(this), 0,\n\t\tthis, SLOT(slotGoFFC()), this, \"ICQAccount::mActionFFC\");\n\n\tmActionMenu->popupMenu()->insertTitle(\n\t\tmMyself->onlineStatus().iconFor(mMyself),\n\t\ti18n(\"%2 <%1>\").arg(accountId()).arg(mMyself->displayName()));\n\n\tmActionMenu->insert(mActionOnline); \/\/ always first\n\tmActionMenu->insert(mActionFFC);\n\tmActionMenu->insert(mActionAway);\n\tmActionMenu->insert(mActionNA);\n\tmActionMenu->insert(mActionDND);\n\tmActionMenu->insert(mActionOccupied);\n\tmActionMenu->insert(mActionOffline);\n\tmActionMenu->popupMenu()->insertSeparator();\n\tmActionMenu->insert(\n\t\tKopeteStdAction::contactInfo(myself(), SLOT(slotUserInfo()),\n\t\t\tmActionMenu, \"ICQAccount::mActionEditInfo\"));\n\n\treturn mActionMenu;\n}\n\nvoid ICQAccount::slotGoNA()\n{\n\tkdDebug(14200) << k_funcinfo << \"Called\" << endl;\n\t\/\/ Away could also be a different AWAY mode (like NA or OCC)\n\tif(\n\t\t(myself()->onlineStatus().status() == KopeteOnlineStatus::Online) ||\n\t\t(myself()->onlineStatus().status() == KopeteOnlineStatus::Away)\n\t\t)\n\t{\n\t\tmAwayDialog->show(OSCAR_NA);\n\t}\n}\n\nvoid ICQAccount::slotGoOCC()\n{\n\tkdDebug(14200) << k_funcinfo << \"Called\" << endl;\n\t\/\/ Away could also be a different AWAY mode (like NA or OCC)\n\tif(\n\t\t(myself()->onlineStatus().status() == KopeteOnlineStatus::Online) ||\n\t\t(myself()->onlineStatus().status() == KopeteOnlineStatus::Away)\n\t\t)\n\t{\n\t\tmAwayDialog->show(OSCAR_OCC);\n\t}\n}\n\nvoid ICQAccount::slotGoFFC()\n{\n\tkdDebug(14200) << k_funcinfo << \"Called\" << endl;\n\t\/\/ Away could also be a different AWAY mode (like NA or OCC)\n\tif(\n\t\t(myself()->onlineStatus().status() == KopeteOnlineStatus::Online) ||\n\t\t(myself()->onlineStatus().status() == KopeteOnlineStatus::Away)\n\t\t)\n\t\tmEngine->sendStatus(ICQ_STATUS_FFC);\n}\n\nvoid ICQAccount::slotGoDND()\n{\n\tkdDebug(14200) << k_funcinfo << \"Called\" << endl;\n\t\/\/ Away could also be a different AWAY mode (like NA or OCC)\n\tif(\n\t\t(myself()->onlineStatus().status() == KopeteOnlineStatus::Online) ||\n\t\t(myself()->onlineStatus().status() == KopeteOnlineStatus::Away)\n\t\t)\n\t\tmEngine->sendStatus(ICQ_STATUS_DND);\n}\n\nvoid ICQAccount::setAway(bool away, const QString &awayReason)\n{\n\tkdDebug(14200) << k_funcinfo << \" \" << accountId() << endl;\n\/\/ TODO: Make use of away message as well\n\tif(away)\n\t{\n\t\tif((myself()->onlineStatus().status() == KopeteOnlineStatus::Online) ||\n\t\t\t(myself()->onlineStatus().status() == KopeteOnlineStatus::Away))\n\t\t{\n\t\t\tmEngine->sendStatus(ICQ_STATUS_AWAY);\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(myself()->onlineStatus().status() == KopeteOnlineStatus::Away)\n\t\t\tmEngine->sendStatus(ICQ_STATUS_ONLINE);\n\t}\n}\n\nOscarContact *ICQAccount::createNewContact(\n\tconst QString &contactId,\n\tconst QString &displayName,\n\tKopeteMetaContact *parentContact)\n{\n\tkdDebug(14200) << k_funcinfo << \"contactId='\" << contactId << \"', displayName='\" <<\n\t\tdisplayName << \"', ptr parentContact=\" << parentContact << endl;\n\treturn new ICQContact(contactId,displayName,this,parentContact);\n}\n\n#include \"icqaccount.moc\"\n\/\/ vim: set noet ts=4 sts=4 sw=4:\nThe myself contact has to be created in the constructor, like the doc say\n\/*\n icqaccount.cpp - ICQ Account Class\n\n Copyright (c) 2003 by Stefan Gehn\n Kopete (c) 2003 by the Kopete developers \n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n *\/\n\n#include \"icqaccount.h\"\n#include \"icqcontact.h\"\n#include \"icqprotocol.h\"\n#include \"icqchangestatus.h\"\n\n#include \n#include \n#include \n\n#include \"kopetestdaction.h\"\n\n#include \n\nICQAccount::ICQAccount(KopeteProtocol *parent, QString accountID, const char *name)\n\t: OscarAccount(parent, accountID, name, true)\n{\n\t\/\/myself has to be created in constructor\n\tmMyself = new ICQContact(accountId(), accountId(), this, 0L);\n\tmAwayDialog = new ICQChangeStatus(getEngine());\n}\n\nvoid ICQAccount::loaded()\n{\n\t\/\/ needs to be here because pluginData() does not work in constructor\n\tmMyself->rename(pluginData(protocol(), \"NickName\"));\n}\n\nICQAccount::~ICQAccount()\n{\n\/\/\tkdDebug(14200) << k_funcinfo << \"[\" << accountId() << \"] deleted\" << endl;\n\tdelete mAwayDialog;\n}\n\nKActionMenu* ICQAccount::actionMenu()\n{\n\t\/\/ mActionMenu is managed by KopeteAccount. It is deleted when\n\t\/\/ it is no longer shown, so we can (safely) just make a new one here.\n\n\tKActionMenu* mActionMenu = new KActionMenu(accountId(),\n\t\t\"icq_protocol\", this, \"ICQAccount::mActionMenu\");\n\n\tICQProtocol *p = ICQProtocol::protocol();\n\n\tKAction* mActionOnline = new KAction(p->statusOnline.caption(),\n\t\tp->statusOnline.iconFor(this), 0,\n\t\tthis, SLOT(slotGoOnline()), this, \"ICQAccount::mActionOnline\");\n\n\tKAction* mActionOffline = new KAction(p->statusOffline.caption(),\n\t\tp->statusOffline.iconFor(this), 0,\n\t\tthis, SLOT(slotGoOffline()), this, \"ICQAccount::mActionOffline\");\n\n\tKAction* mActionAway\t\t= new KAction(p->statusAway.caption(),\n\t\tp->statusAway.iconFor(this), 0,\n\t\tthis, SLOT(slotGoAway()), this, \"ICQAccount::mActionAway\");\n\n\tKAction* mActionNA = new KAction(p->statusNA.caption(),\n\t\tp->statusNA.iconFor(this), 0,\n\t\tthis, SLOT(slotGoNA()), this, \"ICQAccount::mActionNA\");\n\n\tKAction* mActionDND = new KAction(p->statusDND.caption(),\n\t\tp->statusDND.iconFor(this), 0,\n\t\tthis, SLOT(slotGoDND()), this, \"ICQAccount::mActionDND\");\n\n\tKAction* mActionOccupied = new KAction(p->statusOCC.caption(),\n\t\tp->statusOCC.iconFor(this), 0,\n\t\tthis, SLOT(slotGoOCC()), this, \"ICQAccount::mActionOccupied\");\n\n\tKAction* mActionFFC = new KAction(p->statusFFC.caption(),\n\t\tp->statusFFC.iconFor(this), 0,\n\t\tthis, SLOT(slotGoFFC()), this, \"ICQAccount::mActionFFC\");\n\n\tmActionMenu->popupMenu()->insertTitle(\n\t\tmMyself->onlineStatus().iconFor(mMyself),\n\t\ti18n(\"%2 <%1>\").arg(accountId()).arg(mMyself->displayName()));\n\n\tmActionMenu->insert(mActionOnline); \/\/ always first\n\tmActionMenu->insert(mActionFFC);\n\tmActionMenu->insert(mActionAway);\n\tmActionMenu->insert(mActionNA);\n\tmActionMenu->insert(mActionDND);\n\tmActionMenu->insert(mActionOccupied);\n\tmActionMenu->insert(mActionOffline);\n\tmActionMenu->popupMenu()->insertSeparator();\n\tmActionMenu->insert(\n\t\tKopeteStdAction::contactInfo(myself(), SLOT(slotUserInfo()),\n\t\t\tmActionMenu, \"ICQAccount::mActionEditInfo\"));\n\n\treturn mActionMenu;\n}\n\nvoid ICQAccount::slotGoNA()\n{\n\tkdDebug(14200) << k_funcinfo << \"Called\" << endl;\n\t\/\/ Away could also be a different AWAY mode (like NA or OCC)\n\tif(\n\t\t(myself()->onlineStatus().status() == KopeteOnlineStatus::Online) ||\n\t\t(myself()->onlineStatus().status() == KopeteOnlineStatus::Away)\n\t\t)\n\t{\n\t\tmAwayDialog->show(OSCAR_NA);\n\t}\n}\n\nvoid ICQAccount::slotGoOCC()\n{\n\tkdDebug(14200) << k_funcinfo << \"Called\" << endl;\n\t\/\/ Away could also be a different AWAY mode (like NA or OCC)\n\tif(\n\t\t(myself()->onlineStatus().status() == KopeteOnlineStatus::Online) ||\n\t\t(myself()->onlineStatus().status() == KopeteOnlineStatus::Away)\n\t\t)\n\t{\n\t\tmAwayDialog->show(OSCAR_OCC);\n\t}\n}\n\nvoid ICQAccount::slotGoFFC()\n{\n\tkdDebug(14200) << k_funcinfo << \"Called\" << endl;\n\t\/\/ Away could also be a different AWAY mode (like NA or OCC)\n\tif(\n\t\t(myself()->onlineStatus().status() == KopeteOnlineStatus::Online) ||\n\t\t(myself()->onlineStatus().status() == KopeteOnlineStatus::Away)\n\t\t)\n\t\tmEngine->sendStatus(ICQ_STATUS_FFC);\n}\n\nvoid ICQAccount::slotGoDND()\n{\n\tkdDebug(14200) << k_funcinfo << \"Called\" << endl;\n\t\/\/ Away could also be a different AWAY mode (like NA or OCC)\n\tif(\n\t\t(myself()->onlineStatus().status() == KopeteOnlineStatus::Online) ||\n\t\t(myself()->onlineStatus().status() == KopeteOnlineStatus::Away)\n\t\t)\n\t\tmEngine->sendStatus(ICQ_STATUS_DND);\n}\n\nvoid ICQAccount::setAway(bool away, const QString &awayReason)\n{\n\tkdDebug(14200) << k_funcinfo << \" \" << accountId() << endl;\n\/\/ TODO: Make use of away message as well\n\tif(away)\n\t{\n\t\tif((myself()->onlineStatus().status() == KopeteOnlineStatus::Online) ||\n\t\t\t(myself()->onlineStatus().status() == KopeteOnlineStatus::Away))\n\t\t{\n\t\t\tmEngine->sendStatus(ICQ_STATUS_AWAY);\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(myself()->onlineStatus().status() == KopeteOnlineStatus::Away)\n\t\t\tmEngine->sendStatus(ICQ_STATUS_ONLINE);\n\t}\n}\n\nOscarContact *ICQAccount::createNewContact(\n\tconst QString &contactId,\n\tconst QString &displayName,\n\tKopeteMetaContact *parentContact)\n{\n\tkdDebug(14200) << k_funcinfo << \"contactId='\" << contactId << \"', displayName='\" <<\n\t\tdisplayName << \"', ptr parentContact=\" << parentContact << endl;\n\treturn new ICQContact(contactId,displayName,this,parentContact);\n}\n\n#include \"icqaccount.moc\"\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (C) 2013-2018 University of Amsterdam\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 2 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program. If not, see .\n\/\/\n\n#include \"labels.h\"\n#include \"iostream\"\n\n\nusing namespace std;\n\nmap > Labels::_orgStringValues;\nint Labels::_counter = 0;\n\nLabels::Labels(boost::interprocess::managed_shared_memory *mem)\n\t: _labels(mem->get_segment_manager())\n{\n\t _id = ++Labels::_counter;\n\t_mem = mem;\n}\n\nLabels::~Labels()\n{\n}\n\nvoid Labels::clear()\n{\n\t_labels.clear();\n}\n\nint Labels::add(int display)\n{\n\tLabel label(display);\n\t_labels.push_back(label);\n\n\treturn display;\n}\n\nint Labels::add(const std::string &display)\n{\n\treturn add(_labels.size(), display, true);\n}\n\nint Labels::add(int key, const std::string &display, bool filterAllows)\n{\n\tLabel label(display, key, filterAllows);\n\t_labels.push_back(label);\n\n\treturn key;\n}\n\nvoid Labels::removeValues(std::set valuesToRemove)\n{\n\t_labels.erase(\n\t\tstd::remove_if(\n\t\t\t_labels.begin(),\n\t\t\t_labels.end(),\n\t\t\t[&valuesToRemove](const Label& label) {\n\t\t\t\treturn std::find(valuesToRemove.begin(), valuesToRemove.end(), label.value()) != valuesToRemove.end();\n\t\t\t}),\n\t\t_labels.end());\n}\n\nbool Labels::syncInts(map &values)\n{\n\tstd::set keys;\n\tfor (const auto &value : values)\n\t\tkeys.insert(value.first);\n\n\tbool changed = syncInts(keys);\n\n\tfor (Label& label : _labels)\n\t{\n\t\tint value = label.value();\n\t\tstring &new_string_label = values[value];\n\t\tstring old_string_label = label.text();\n\t\tif (new_string_label != old_string_label)\n\t\t{\n\t\t\t_setNewStringForLabel(label, new_string_label);\n\t\t\tchanged = true;\n\t\t}\n\t}\n\n\treturn changed;\n}\n\nbool Labels::syncInts(const std::set &values)\n{\n\tstd::set valuesToAdd = values;\n\tstd::set valuesToRemove;\n\n\tfor (const Label& label : _labels)\n\t{\n\t\tint value = label.value();\n\t\tif (std::find(values.begin(), values.end(), value) != values.end())\n\t\t{\n\t\t\tstd::set::iterator value_it = std::find(valuesToAdd.begin(), valuesToAdd.end(), value);\n\t\t\tif (value_it != valuesToAdd.end())\n\t\t\t\tvaluesToAdd.erase(value_it);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"Remove label \" << label.text() << std::endl;\n\t\t\tstd::cout.flush();\n\t\t\tvaluesToRemove.insert(value);\n\t\t}\n\t}\n\n\n\tremoveValues(valuesToRemove);\t\n\n\tfor (int value : valuesToAdd)\n\t\tadd(value);\n\n\treturn valuesToAdd.size() + valuesToRemove.size() > 0;\n}\n\nstd::map Labels::syncStrings(const std::vector &new_values, const std::map &new_labels, bool *changedSomething)\n{\n\tstd::vector > valuesToAdd;\n\tstd::map > mapValuesToAdd;\n\tuint valuesToAddIndex = 0;\n\n\tfor (const std::string& newValue : new_values)\n\t{\n\t\tstd::string shortValue\t= newValue.length() > Label::MAX_LABEL_LENGTH ? newValue.substr(0, Label::MAX_LABEL_LENGTH) : newValue;\n\t\tvaluesToAdd.push_back(make_pair(newValue, shortValue));\n\t\tauto elt = mapValuesToAdd.find(shortValue);\n\t\tif (elt != mapValuesToAdd.end())\n\t\t\telt->second.push_back(valuesToAddIndex);\n\t\telse\n\t\t\tmapValuesToAdd[shortValue] = { valuesToAddIndex };\n\t\tvaluesToAddIndex++;\n\t}\n\t\n\tstd::set\t\t\t\tvaluesToRemove;\n\tstd::map\tresult;\n\tint\t\t\t\t\t\t\tmaxLabelKey = 0;\n\n\tfor (const Label &label : _labels)\n\t{\n\t\tstd::string labelText\t= _getOrgValueFromLabel(label);\n\t\tint labelValue\t\t\t= label.value();\n\t\t\n\t\tif (labelValue > maxLabelKey)\n\t\t\tmaxLabelKey = labelValue;\n\n\t\tauto elt = mapValuesToAdd.find(labelText);\n\t\tif (elt != mapValuesToAdd.end())\n\t\t{\n\t\t\tfor (uint i : elt->second)\n\t\t\t\tresult[valuesToAdd[i].first] = labelValue;\n\t\t\tmapValuesToAdd.erase(elt);\n\t\t}\n\t\telse\n\t\t\tvaluesToRemove.insert(labelValue);\n\t}\n\n\tif(changedSomething != nullptr && (valuesToRemove.size() > 0 || mapValuesToAdd.size() > 0))\n\t\t*changedSomething = true;\n\n\tremoveValues(valuesToRemove);\n\t\n\tfor (auto elt : valuesToAdd)\n\t{\n\t\tmaxLabelKey++;\n\t\tadd(maxLabelKey, elt.second, true);\n\t\tresult[elt.first] = maxLabelKey;\n\t}\n\n\tfor (Label& label : _labels)\n\t{\n\t\tstd::string labelText = _getOrgValueFromLabel(label);\n\t\tauto newLabelIt = new_labels.find(labelText);\n\t\tif (newLabelIt != new_labels.end())\n\t\t{\n\t\t\tstd::string newStringLabel = newLabelIt->second;\n\t\t\tif (labelText != newStringLabel)\n\t\t\t{\n\t\t\t\t_setNewStringForLabel(label, newStringLabel);\n\n\t\t\t\tif(changedSomething != nullptr)\n\t\t\t\t\t*changedSomething = true;\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nstd::set Labels::getIntValues()\n{\n\tstd::set result;\n\tfor (const Label& label : _labels)\n\t\tresult.insert(label.value());\n\t\n\treturn result;\n}\n\nmap &Labels::getOrgStringValues() const\n{\n\treturn Labels::_orgStringValues[_id];\n}\n\nvoid Labels::setOrgStringValues(int key, std::string value)\n{\n\tmap &orgStringValues = getOrgStringValues();\n\torgStringValues[key] = value;\n}\n\nconst Label &Labels::getLabelObjectFromKey(int index) const\n\n{\n\tfor (const Label &label: _labels)\n\t{\n\t\tif (label.value() == index)\n\t\t\treturn label;\n\t}\n\n\tstd::cout << \"Cannot find entry \" << index << std::endl;\n\tfor(const Label &label: _labels)\n\t{\n\t\tstd::cout << \"Label Value: \" << label.value() << \", Text: \" << label.text() << std::endl;\n\t}\n\tstd::cout.flush();\n\tthrow runtime_error(\"Cannot find this entry\");\n}\n\nbool Labels::setLabelFromRow(int row, const string &display)\n{\n\tif (row >= (int)_labels.size() || row < 0)\n\t{\n\t\tstd::cout << \"Set label with wrong row: \" << row << \", size: \" << _labels.size() << std::endl;\n\t\tstd::cout.flush();\n\t\treturn false;\n\t}\n\n\ttry\n\t{\n\t\tLabel &label = _labels.at(row);\n\t\tif (label.text() == display)\n\t\t\treturn false;\n\n\t\t_setNewStringForLabel(label, display);\n\t}\n\tcatch(...)\n\t{\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nvoid Labels::_setNewStringForLabel(Label &label, const string &display)\n{\n\tint label_value = label.value();\n\tstring label_string = label.text();\n\tmap &orgStringValues = getOrgStringValues();\n\tif (orgStringValues.find(label_value) == orgStringValues.end())\n\t\torgStringValues[label_value] = label_string;\n\tlabel.setLabel(display);\n}\n\nstring Labels::_getValueFromLabel(const Label &label) const\n{\n\tif (label.hasIntValue())\n\t{\n\t\tstd::ostringstream ss;\n\t\tss << label.value();\n\t\treturn ss.str();\n\t}\n\telse\n\t{\n\t\treturn _getOrgValueFromLabel(label);\n\t}\n}\n\nstring Labels::_getOrgValueFromLabel(const Label &label) const\n{\n\tmap &orgStringValues = getOrgStringValues();\n\tmap::const_iterator it = orgStringValues.find(label.value());\n\tif (it == orgStringValues.end())\n\t\treturn label.text();\n\telse\n\t\treturn it->second;\t\n}\n\nstring Labels::getValueFromKey(int key) const\n{\n\tconst Label &label = getLabelObjectFromKey(key);\n\treturn _getValueFromLabel(label);\n}\n\nstring Labels::getValueFromRow(int row)\n{\n\tif (row >= (int)_labels.size())\n\t{\n\t\tstd::cout << \"Get value with wrong row: \" << row << \", size: \" << _labels.size() << std::endl;\n\t\tstd::cout.flush();\n\t\treturn \"\";\n\t}\n\tconst Label &label = _labels.at(row);\n\treturn _getValueFromLabel(label);\n}\n\nLabel& Labels::operator[](size_t index)\n{\n\treturn _labels.at(index);\n}\n\nstd::string Labels::getLabelFromRow(int row)\n{\n\tif (row >= (int)_labels.size())\n\t{\n\t\tstd::cout << \"Get label with wrong row: \" << row << \", size: \" << _labels.size() << std::endl;\n\t\tstd::cout.flush();\n\t\treturn \"\";\n\t}\n\tLabel &label = _labels.at(row);\n\treturn label.text();\n}\n\nvoid Labels::set(vector