commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
c7f18da6b04bb757bace18f22542c8078ba1b7b2
src/arch/x86/cpuid.cc
src/arch/x86/cpuid.cc
/* * Copyright (c) 2008 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black */ #include "arch/x86/cpuid.hh" #include "base/bitfield.hh" #include "cpu/thread_context.hh" namespace X86ISA { enum StandardCpuidFunction { VendorAndLargestStdFunc, FamilyModelStepping, CacheAndTLB, SerialNumber, CacheParams, MonitorMwait, ThermalPowerMgmt, ExtendedFeatures, NumStandardCpuidFuncs }; enum ExtendedCpuidFunctions { VendorAndLargestExtFunc, FamilyModelSteppingBrandFeatures, NameString1, NameString2, NameString3, L1CacheAndTLB, L2L3CacheAndL2TLB, APMInfo, LongModeAddressSize, /* * The following are defined by the spec but not yet implemented */ /* // Function 9 is reserved SVMInfo = 10, // Functions 11-24 are reserved TLB1GBPageInfo = 25, PerformanceInfo,*/ NumExtendedCpuidFuncs }; static const int vendorStringSize = 13; static const char vendorString[vendorStringSize] = "M5 Simulator"; static const int nameStringSize = 48; static const char nameString[nameStringSize] = "Fake M5 x86_64 CPU"; uint64_t stringToRegister(const char *str) { uint64_t reg = 0; for (int pos = 3; pos >=0; pos--) { reg <<= 8; reg |= str[pos]; } return reg; } bool doCpuid(ThreadContext * tc, uint32_t function, uint32_t index, CpuidResult &result) { uint16_t family = bits(function, 31, 16); uint16_t funcNum = bits(function, 15, 0); if (family == 0x8000) { // The extended functions switch (funcNum) { case VendorAndLargestExtFunc: assert(vendorStringSize >= 12); result = CpuidResult( 0x80000000 + NumExtendedCpuidFuncs - 1, stringToRegister(vendorString), stringToRegister(vendorString + 4), stringToRegister(vendorString + 8)); break; case FamilyModelSteppingBrandFeatures: result = CpuidResult(0x00020f51, 0x00000405, 0xe3d3fbff, 0x00000001); break; case NameString1: case NameString2: case NameString3: { // Zero fill anything beyond the end of the string. This // should go away once the string is a vetted parameter. char cleanName[nameStringSize]; memset(cleanName, '\0', nameStringSize); strncpy(cleanName, nameString, nameStringSize); int offset = (funcNum - NameString1) * 16; assert(nameStringSize >= offset + 16); result = CpuidResult( stringToRegister(cleanName + offset + 0), stringToRegister(cleanName + offset + 4), stringToRegister(cleanName + offset + 12), stringToRegister(cleanName + offset + 8)); } break; case L1CacheAndTLB: result = CpuidResult(0xff08ff08, 0xff20ff20, 0x40020140, 0x40020140); break; case L2L3CacheAndL2TLB: result = CpuidResult(0x00000000, 0x42004200, 0x00000000, 0x04008140); break; case APMInfo: result = CpuidResult(0x80000018, 0x68747541, 0x69746e65, 0x444d4163); break; case LongModeAddressSize: result = CpuidResult(0x00003030, 0x00000000, 0x00000000, 0x00000000); break; /* case SVMInfo: case TLB1GBPageInfo: case PerformanceInfo:*/ default: warn("x86 cpuid family 0x8000: unimplemented function %u", funcNum); return false; } } else if (family == 0x0000) { // The standard functions switch (funcNum) { case VendorAndLargestStdFunc: assert(vendorStringSize >= 12); result = CpuidResult( NumStandardCpuidFuncs - 1, stringToRegister(vendorString), stringToRegister(vendorString + 4), stringToRegister(vendorString + 8)); break; case FamilyModelStepping: result = CpuidResult(0x00020f51, 0x00000805, 0xe7dbfbff, 0x04000209); break; case ExtendedFeatures: result = CpuidResult(0x00000000, 0x01800000, 0x00000000, 0x00000000); break; default: warn("x86 cpuid family 0x0000: unimplemented function %u", funcNum); return false; } } else { warn("x86 cpuid: unknown family %#x", family); return false; } return true; } } // namespace X86ISA
/* * Copyright (c) 2008 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black */ #include "arch/x86/cpuid.hh" #include "base/bitfield.hh" #include "cpu/thread_context.hh" namespace X86ISA { enum StandardCpuidFunction { VendorAndLargestStdFunc, FamilyModelStepping, CacheAndTLB, SerialNumber, CacheParams, MonitorMwait, ThermalPowerMgmt, ExtendedFeatures, NumStandardCpuidFuncs }; enum ExtendedCpuidFunctions { VendorAndLargestExtFunc, FamilyModelSteppingBrandFeatures, NameString1, NameString2, NameString3, L1CacheAndTLB, L2L3CacheAndL2TLB, APMInfo, LongModeAddressSize, /* * The following are defined by the spec but not yet implemented */ /* // Function 9 is reserved SVMInfo = 10, // Functions 11-24 are reserved TLB1GBPageInfo = 25, PerformanceInfo,*/ NumExtendedCpuidFuncs }; static const int vendorStringSize = 13; static const char vendorString[vendorStringSize] = "M5 Simulator"; static const int nameStringSize = 48; static const char nameString[nameStringSize] = "Fake M5 x86_64 CPU"; uint64_t stringToRegister(const char *str) { uint64_t reg = 0; for (int pos = 3; pos >=0; pos--) { reg <<= 8; reg |= str[pos]; } return reg; } bool doCpuid(ThreadContext * tc, uint32_t function, uint32_t index, CpuidResult &result) { uint16_t family = bits(function, 31, 16); uint16_t funcNum = bits(function, 15, 0); if (family == 0x8000) { // The extended functions switch (funcNum) { case VendorAndLargestExtFunc: assert(vendorStringSize >= 12); result = CpuidResult( 0x80000000 + NumExtendedCpuidFuncs - 1, stringToRegister(vendorString), stringToRegister(vendorString + 4), stringToRegister(vendorString + 8)); break; case FamilyModelSteppingBrandFeatures: result = CpuidResult(0x00020f51, 0x00000405, 0xe3d3fbff, 0x00000001); break; case NameString1: case NameString2: case NameString3: { // Zero fill anything beyond the end of the string. This // should go away once the string is a vetted parameter. char cleanName[nameStringSize]; memset(cleanName, '\0', nameStringSize); strncpy(cleanName, nameString, nameStringSize); int offset = (funcNum - NameString1) * 16; assert(nameStringSize >= offset + 16); result = CpuidResult( stringToRegister(cleanName + offset + 0), stringToRegister(cleanName + offset + 4), stringToRegister(cleanName + offset + 12), stringToRegister(cleanName + offset + 8)); } break; case L1CacheAndTLB: result = CpuidResult(0xff08ff08, 0xff20ff20, 0x40020140, 0x40020140); break; case L2L3CacheAndL2TLB: result = CpuidResult(0x00000000, 0x42004200, 0x00000000, 0x04008140); break; case APMInfo: result = CpuidResult(0x80000018, 0x68747541, 0x69746e65, 0x444d4163); break; case LongModeAddressSize: result = CpuidResult(0x00003030, 0x00000000, 0x00000000, 0x00000000); break; /* case SVMInfo: case TLB1GBPageInfo: case PerformanceInfo:*/ default: warn("x86 cpuid family 0x8000: unimplemented function %u", funcNum); return false; } } else if (family == 0x0000) { // The standard functions switch (funcNum) { case VendorAndLargestStdFunc: assert(vendorStringSize >= 12); result = CpuidResult( NumStandardCpuidFuncs - 1, stringToRegister(vendorString), stringToRegister(vendorString + 4), stringToRegister(vendorString + 8)); break; case FamilyModelStepping: result = CpuidResult(0x00020f51, 0x00000805, 0xe7dbfbff, 0x00000209); break; case ExtendedFeatures: result = CpuidResult(0x00000000, 0x01800000, 0x00000000, 0x00000000); break; default: warn("x86 cpuid family 0x0000: unimplemented function %u", funcNum); return false; } } else { warn("x86 cpuid: unknown family %#x", family); return false; } return true; } } // namespace X86ISA
Stop CPUID from claiming we support xsave.
x86: Stop CPUID from claiming we support xsave. xsave is a fairly complex feature which we don't support in gem5, but we do report that we support it through CPUID. It looks like I confused it with FXSAVE which is an instruction related to SSE. This change turns that bit back off again. Change-Id: I00fc79168c5f7095b5241e870a4c8782e4385425 Reviewed-on: https://gem5-review.googlesource.com/c/public/gem5/+/20169 Reviewed-by: Jason Lowe-Power <[email protected]> Reviewed-by: Pouya Fotouhi <[email protected]> Maintainer: Gabe Black <[email protected]> Tested-by: kokoro <[email protected]>
C++
bsd-3-clause
gem5/gem5,gem5/gem5,gem5/gem5,gem5/gem5,gem5/gem5,gem5/gem5,gem5/gem5
5009f2cd111987e37ff5a1ba73391c4b544db15d
cpp-port/fileseq.cpp
cpp-port/fileseq.cpp
#include "fileseq.h" #include "private/frameset_p.h" #include <algorithm> #include <iterator> #include <string> #include <sstream> namespace fileseq { std::string framesToFrameRange(const Frames &frames, bool sorted, int zfill) { size_t count = frames.size(); if (count == 0) { return ""; } if (count == 1) { return internal::zfill(frames[0], zfill); } const Frames* framesPtr = &frames; if (sorted) { Frames sortedFrames = frames; std::sort(sortedFrames.begin(), sortedFrames.end()); framesPtr = &sortedFrames; } size_t i = 0; long step = 0; bool hasWritten = false; std::string start, end; std::stringstream buf; Frames::const_iterator framesIt = framesPtr->begin(); Frames::const_iterator framesEnd = framesPtr->end(); while (framesIt < framesEnd) { // Items left count = std::distance(framesIt, framesEnd); // If we get to the last element, just write it and end if (count <= 2) { for (i = 0; i < count; ++i) { if (hasWritten) { buf << ","; } buf << internal::zfill(framesIt[i], zfill); } hasWritten = true; break; } // At this point, we have 3 or more frames to check. // Scan the current window of the slice to see how // many frames we can consume into a group step = framesIt[1] - framesIt[0]; for (i = 0; i < (count-1); ++i) { // We have scanned as many frames as we can // for this group. Now write them and stop // looping on this window if ((framesIt[i+1] - framesIt[i]) != step) { break; } } // Subsequent groups are comma-separated if (hasWritten) { buf << ","; hasWritten = true; } // We only have a single frame to write for this group if (i == 0) { buf << internal::zfill(framesIt[0], zfill); framesIt++; hasWritten = true; continue; } // First do a check to see if we could have gotten a larger range // out of subsequent values with a different step size if (i == 1 && count > 3) { // Check if the next two pairwise frames have the same step. // If so, then it is better than our current grouping. if ((framesIt[2] - framesIt[1]) == (framesIt[3] - framesIt[2])) { // Just consume the first frame, and allow the next // loop to scan the new stepping buf << internal::zfill(framesIt[0], zfill); framesIt++; hasWritten = true; continue; } } // Otherwise write out this step range start = internal::zfill(framesIt[0], zfill); end = internal::zfill(framesIt[i], zfill); buf << start << "-" << end; if (step > 1) { buf << "x" << step; } framesIt++; hasWritten = true; } return buf.str(); } bool isFrameRange(const std::string &frange) { internal::RangeMatches matches; return frameRangeMatches(matches, frange); } FileSequence findSequenceOnDisk(const std::string &pattern, Status* ok) { return findSequenceOnDisk(pattern, PadStyleDefault, ok); } FileSequence findSequenceOnDisk(const std::string &pattern, PadStyle style, Status* ok) { return FileSequence(""); } Status findSequencesOnDisk(FileSequences &seqs, const std::string &path, bool hiddenFiles, bool singleFiles, PadStyle style) { Status stat; stat.setError("Not implemented"); return stat; } } // fileseq
#include "fileseq.h" #include "private/frameset_p.h" #include <algorithm> #include <iterator> #include <string> #include <sstream> namespace fileseq { std::string framesToFrameRange(const Frames &frames, bool sorted, int zfill) { Frames::size_type count = frames.size(); if (count == 0) { return ""; } if (count == 1) { return internal::zfill(frames[0], zfill); } Frames::const_iterator framesIt = frames.begin(); Frames::const_iterator framesEnd = frames.end(); Frames sortedFrames; if (sorted) { // Copy sortedFrames = frames; // Sort std::sort(sortedFrames.begin(), sortedFrames.end()); framesIt = sortedFrames.begin(); framesEnd = sortedFrames.end(); } long step = 0; bool hasWritten = false; Frames::size_type i = 0; std::string start, end; std::stringstream buf; while (framesIt != framesEnd) { // Items left count = std::distance(framesIt, framesEnd); // If we get to the last element, just write it and end if (count <= 2) { for (i = 0; i < count; ++i) { if (hasWritten) { buf << ","; } buf << internal::zfill(framesIt[i], zfill); } hasWritten = true; break; } // At this point, we have 3 or more frames to check. // Scan the current window of the slice to see how // many frames we can consume into a group step = framesIt[1] - framesIt[0]; // Scan and update the pointer index until we get // to a point where the step changes for (i = 0; i < (count-1); ++i) { if ((framesIt[i+1] - framesIt[i]) != step) { // We have scanned as many frames as we can // for this group. Now write them and stop // looping on this window, because the step // has changed. break; } } // Subsequent groups are comma-separated if (hasWritten) { buf << ","; hasWritten = true; } // We only have a single frame to write for this group if (i == 0) { buf << internal::zfill(framesIt[0], zfill); framesIt++; hasWritten = true; continue; } // First do a check to see if we could have gotten a larger range // out of subsequent values with a different step size if (i == 1 && count > 3) { // Check if the next two pairwise frames have the same step. // If so, then it is better than our current grouping. if ((framesIt[2] - framesIt[1]) == (framesIt[3] - framesIt[2])) { // Just consume the first frame, and allow the next // loop to scan the new stepping buf << internal::zfill(framesIt[0], zfill); framesIt++; hasWritten = true; continue; } } // Otherwise write out this step range start = internal::zfill(framesIt[0], zfill); end = internal::zfill(framesIt[i], zfill); buf << start << "-" << end; if (step > 1) { buf << "x" << step; } hasWritten = true; // Advance our iterator to the end of the current window // so that we can test the next available number framesIt += (i+1); } return buf.str(); } bool isFrameRange(const std::string &frange) { internal::RangeMatches matches; return frameRangeMatches(matches, frange); } FileSequence findSequenceOnDisk(const std::string &pattern, Status* ok) { return findSequenceOnDisk(pattern, PadStyleDefault, ok); } FileSequence findSequenceOnDisk(const std::string &pattern, PadStyle style, Status* ok) { return FileSequence(""); } Status findSequencesOnDisk(FileSequences &seqs, const std::string &path, bool hiddenFiles, bool singleFiles, PadStyle style) { Status stat; stat.setError("Not implemented"); return stat; } } // fileseq
Fix bug in framesToFrameRange() iteration
Fix bug in framesToFrameRange() iteration
C++
mit
justinfx/gofileseq,justinfx/gofileseq,justinfx/gofileseq,justinfx/gofileseq
877e3bdc4f841a3845ed02fa25abafe152d00232
scientistservice.cpp
scientistservice.cpp
#include "scientistservice.h" #include <algorithm> #include <iostream> using namespace std; ScientistService::ScientistService() { } //compares names of scientists in alphabetical order struct ScientistComparisonNameForward { bool operator() (Scientist i, Scientist j) {return (i.getName()<j.getName());} }; //compares year of birth between scientists in ascending order bool ScientistComparisonYearOfBirthForward (Scientist i, Scientist j) { return (i.getYearOfBirth()<j.getYearOfBirth()); } //compares year of death between scientists in ascending order bool ScientistComparisonYearOfDeathForward (Scientist i, Scientist j) { return (i.getYearOfDeath()<j.getYearOfDeath()); } //compares age between scientists in ascending order bool ScientistComparisonAgeForward (Scientist i, Scientist j) { return (i.getAge()<j.getAge()); } //NEED TO USE OR TERMINATE /* struct ScientistComparisonGenderForward { bool operator() (Scientist i, Scientist j) {return (i.getGender()<j.getGender());} }; */ //sorts scientist by aplhabetical order, by year of birth, by year of death and by age vector<Scientist> ScientistService::sortScientists(vector<Scientist> _listOfScientists, string sort) { if (sort == "name" || sort == "Name" || sort == "n") { ScientistComparisonNameForward cmp; std::sort(_scientists.begin(), _scientists.end(), cmp); } else if (sort == "birth" || sort == "Birth" || sort == "b") { std::sort(_scientists.begin(), _scientists.end(), ScientistComparisonYearOfBirthForward); } else if (sort == "death" || sort == "Death" || sort == "d") { std::sort(_scientists.begin(), _scientists.end(), ScientistComparisonYearOfDeathForward); } else if (sort == "age" || sort == "Age" || sort == "a") { std::sort(_scientists.begin(), _scientists.end(), ScientistComparisonAgeForward); } else { //default is to sort by name ScientistComparisonNameForward cmp; std::sort(_scientists.begin(), _scientists.end(), cmp); } return _listOfScientists; } //search for scientist by name vector<int> ScientistService::searchScientists(string& searchData) { vector<int> foundScientists; for(unsigned long i = 0; i < _scientists.size(); i++) { string name = _scientists[i].getName(); if(name.substr(0,searchData.size()) == searchData) { //If we find the scientist then we... foundScientists.push_back(i); } } return foundScientists; //remeber to change } // adds an registered scientist to vector void ScientistService::addScientist(Scientist scientist) { bool isin = ifExist(scientist.getName()); if (isin == false) { _scientists.push_back(scientist); _data.writeNewScientist(scientist); } } //get functions Scientist ScientistService::getScientist(int index) const { return _scientists[index]; } //get vector size int ScientistService::getSize() const { return _scientists.size(); } //validation - registering a scientist that is already registered is not allowed bool ScientistService::ifExist(string name) { for (size_t i = 0; i < _scientists.size(); i++) { if (_scientists[i].getName() == name) { return true; } } return false; } //get scientist vector vector<Scientist> ScientistService::getScientistVector() { return _scientists; } //loads from file to vector bool ScientistService::load() { _data.getData(_scientists); return DataAccessWorks(); } //validates if DataAccess works bool ScientistService::DataAccessWorks() { if (_data.DataOk && _data.FileOpen) { return true; } return false; } //user can change characteristic of scientist void ScientistService::editScientist(int index, string change, string input) { if (change == "name") { _scientists[index].setName(input); } else if (change == "gender") { _scientists[index].setGender(input); } else if (change == "birth") { _scientists[index].setYearOfBirth(stoi(input, 0)); } else if (change == "death") { _scientists[index].setYearOfDeath(stoi(input, 0)); } } //user can delete scientist void ScientistService::deleteScientist(int index) { _scientists.erase(_scientists.begin()+index); _data.writeData(_scientists); }
#include "scientistservice.h" #include <algorithm> #include <iostream> using namespace std; ScientistService::ScientistService() { } //compares names of scientists in alphabetical order struct ScientistComparisonNameForward { bool operator() (Scientist i, Scientist j) {return (i.getName()<j.getName());} }; //compares year of birth between scientists in ascending order bool ScientistComparisonYearOfBirthForward (Scientist i, Scientist j) { return (i.getYearOfBirth()<j.getYearOfBirth()); } //compares year of death between scientists in ascending order bool ScientistComparisonYearOfDeathForward (Scientist i, Scientist j) { return (i.getYearOfDeath()<j.getYearOfDeath()); } //compares age between scientists in ascending order bool ScientistComparisonAgeForward (Scientist i, Scientist j) { return (i.getAge()<j.getAge()); } //sorts scientist by aplhabetical order, by year of birth, by year of death and by age vector<Scientist> ScientistService::sortScientists(vector<Scientist> _listOfScientists, string sort) { if (sort == "name" || sort == "Name" || sort == "n") { ScientistComparisonNameForward cmp; std::sort(_scientists.begin(), _scientists.end(), cmp); } else if (sort == "birth" || sort == "Birth" || sort == "b") { std::sort(_scientists.begin(), _scientists.end(), ScientistComparisonYearOfBirthForward); } else if (sort == "death" || sort == "Death" || sort == "d") { std::sort(_scientists.begin(), _scientists.end(), ScientistComparisonYearOfDeathForward); } else if (sort == "age" || sort == "Age" || sort == "a") { std::sort(_scientists.begin(), _scientists.end(), ScientistComparisonAgeForward); } else { //default is to sort by name ScientistComparisonNameForward cmp; std::sort(_scientists.begin(), _scientists.end(), cmp); } return _listOfScientists; } //search for scientist by name vector<int> ScientistService::searchScientists(string& searchData) { vector<int> foundScientists; for(unsigned long i = 0; i < _scientists.size(); i++) { string name = _scientists[i].getName(); if(name.substr(0,searchData.size()) == searchData) { //If we find the scientist then we... foundScientists.push_back(i); } } return foundScientists; //remeber to change } // adds an registered scientist to vector void ScientistService::addScientist(Scientist scientist) { bool isin = ifExist(scientist.getName()); if (isin == false) { _scientists.push_back(scientist); _data.writeNewScientist(scientist); } } //get functions Scientist ScientistService::getScientist(int index) const { return _scientists[index]; } //get vector size int ScientistService::getSize() const { return _scientists.size(); } //validation - registering a scientist that is already registered is not allowed bool ScientistService::ifExist(string name) { for (size_t i = 0; i < _scientists.size(); i++) { if (_scientists[i].getName() == name) { return true; } } return false; } //get scientist vector vector<Scientist> ScientistService::getScientistVector() { return _scientists; } //loads from file to vector bool ScientistService::load() { _data.getData(_scientists); return DataAccessWorks(); } //validates if DataAccess works bool ScientistService::DataAccessWorks() { if (_data.DataOk && _data.FileOpen) { return true; } return false; } //user can change characteristic of scientist void ScientistService::editScientist(int index, string change, string input) { if (change == "name") { _scientists[index].setName(input); } else if (change == "gender") { _scientists[index].setGender(input); } else if (change == "birth") { _scientists[index].setYearOfBirth(stoi(input, 0)); } else if (change == "death") { _scientists[index].setYearOfDeath(stoi(input, 0)); } } //user can delete scientist void ScientistService::deleteScientist(int index) { _scientists.erase(_scientists.begin()+index); _data.writeData(_scientists); }
terminate useless function
terminate useless function
C++
mit
VLN1-Hopur23/VLN1-Hopur23
b4f6d79f4e81448c742a5f63f6c33cb5833ec647
rss/parser.cpp
rss/parser.cpp
/* rsspp - Copyright (C) 2008-2012 Andreas Krennmair <[email protected]> * Licensed under the MIT/X Consortium License. See file LICENSE * for more information. */ #include <config.h> #include <rsspp.h> #include <rsspp_internal.h> #include <libxml/parser.h> #include <libxml/tree.h> #include <curl/curl.h> #include <logger.h> #include <utils.h> #include <cstring> #include <utils.h> #include <remote_api.h> using namespace newsbeuter; static size_t my_write_data(void *buffer, size_t size, size_t nmemb, void *userp) { std::string * pbuf = static_cast<std::string *>(userp); pbuf->append(static_cast<const char *>(buffer), size * nmemb); return size * nmemb; } namespace rsspp { parser::parser(unsigned int timeout, const char * user_agent, const char * proxy, const char * proxy_auth, curl_proxytype proxy_type, const bool ssl_verify) : to(timeout), ua(user_agent), prx(proxy), prxauth(proxy_auth), prxtype(proxy_type), verify_ssl(ssl_verify), doc(0), lm(0) { } parser::~parser() { if (doc) xmlFreeDoc(doc); } struct header_values { time_t lastmodified; std::string etag; header_values() : lastmodified(0) { } }; static size_t handle_headers(void * ptr, size_t size, size_t nmemb, void * data) { char * header = new char[size*nmemb + 1]; header_values * values = (header_values *)data; memcpy(header, ptr, size*nmemb); header[size*nmemb] = '\0'; if (!strncasecmp("Last-Modified:", header, 14)) { time_t r = curl_getdate(header+14, nullptr); if (r == -1) { LOG(LOG_DEBUG, "handle_headers: last-modified %s (curl_getdate FAILED)", header+14); } else { values->lastmodified = curl_getdate(header+14, nullptr); LOG(LOG_DEBUG, "handle_headers: got last-modified %s (%d)", header+14, values->lastmodified); } } else if (!strncasecmp("ETag:",header, 5)) { values->etag = std::string(header+5); utils::trim(values->etag); LOG(LOG_DEBUG, "handle_headers: got etag %s", values->etag.c_str()); } delete[] header; return size * nmemb; } feed parser::parse_url(const std::string& url, time_t lastmodified, const std::string& etag, newsbeuter::remote_api * api, const std::string& cookie_cache, CURL *ehandle) { std::string buf; CURLcode ret; curl_slist* custom_headers {}; CURL * easyhandle = ehandle; if (!easyhandle) { easyhandle = curl_easy_init(); if (!easyhandle) { throw exception(_("couldn't initialize libcurl")); } } if (ua) { curl_easy_setopt(easyhandle, CURLOPT_USERAGENT, ua); } if (api) { api->add_custom_headers(&custom_headers); } curl_easy_setopt(easyhandle, CURLOPT_URL, url.c_str()); curl_easy_setopt(easyhandle, CURLOPT_SSL_VERIFYPEER, verify_ssl); curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, my_write_data); curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &buf); curl_easy_setopt(easyhandle, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(easyhandle, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(easyhandle, CURLOPT_MAXREDIRS, 10); curl_easy_setopt(easyhandle, CURLOPT_FAILONERROR, 1); curl_easy_setopt(easyhandle, CURLOPT_ENCODING, "gzip, deflate"); if (cookie_cache != "") { curl_easy_setopt(easyhandle, CURLOPT_COOKIEFILE, cookie_cache.c_str()); curl_easy_setopt(easyhandle, CURLOPT_COOKIEJAR, cookie_cache.c_str()); } if (to != 0) curl_easy_setopt(easyhandle, CURLOPT_TIMEOUT, to); if (prx) curl_easy_setopt(easyhandle, CURLOPT_PROXY, prx); if (prxauth) { curl_easy_setopt(easyhandle, CURLOPT_PROXYAUTH, CURLAUTH_ANY); curl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, prxauth); } curl_easy_setopt(easyhandle, CURLOPT_PROXYTYPE, prxtype); header_values hdrs; curl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &hdrs); curl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, handle_headers); if (lastmodified != 0) { curl_easy_setopt(easyhandle, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE); curl_easy_setopt(easyhandle, CURLOPT_TIMEVALUE, lastmodified); } if (etag.length() > 0) { auto header = utils::strprintf("If-None-Match: %s", etag.c_str()); custom_headers = curl_slist_append(custom_headers, header.c_str()); } if (custom_headers) { curl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, custom_headers); } ret = curl_easy_perform(easyhandle); lm = hdrs.lastmodified; et = hdrs.etag; if (custom_headers) { curl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, 0); curl_slist_free_all(custom_headers); } LOG(LOG_DEBUG, "rsspp::parser::parse_url: ret = %d", ret); long status; curl_easy_getinfo(easyhandle, CURLINFO_HTTP_CONNECTCODE, &status); if (status >= 400) { LOG(LOG_USERERROR, _("Error: trying to download feed `%s' returned HTTP status code %ld."), url.c_str(), status); } curl_easy_reset(easyhandle); if (!ehandle) curl_easy_cleanup(easyhandle); if (ret != 0) { LOG(LOG_ERROR, "rsspp::parser::parse_url: curl_easy_perform returned err %d: %s", ret, curl_easy_strerror(ret)); throw exception(curl_easy_strerror(ret)); } LOG(LOG_INFO, "parser::parse_url: retrieved data for %s: %s", url.c_str(), buf.c_str()); if (buf.length() > 0) { LOG(LOG_DEBUG, "parser::parse_url: handing over data to parse_buffer()"); return parse_buffer(buf.c_str(), buf.length(), url.c_str()); } return feed(); } feed parser::parse_buffer(const char * buffer, size_t size, const char * url) { doc = xmlReadMemory(buffer, size, url, nullptr, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING); if (doc == nullptr) { throw exception(_("could not parse buffer")); } xmlNode* root_element = xmlDocGetRootElement(doc); feed f = parse_xmlnode(root_element); if (doc->encoding) { f.encoding = (const char *)doc->encoding; } LOG(LOG_INFO, "parser::parse_buffer: encoding = %s", f.encoding.c_str()); return f; } feed parser::parse_file(const std::string& filename) { doc = xmlReadFile(filename.c_str(), nullptr, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING); xmlNode* root_element = xmlDocGetRootElement(doc); if (root_element == nullptr) { throw exception(_("could not parse file")); } feed f = parse_xmlnode(root_element); if (doc->encoding) { f.encoding = (const char *)doc->encoding; } LOG(LOG_INFO, "parser::parse_file: encoding = %s", f.encoding.c_str()); return f; } feed parser::parse_xmlnode(xmlNode* node) { feed f; if (node) { if (node->name && node->type == XML_ELEMENT_NODE) { if (strcmp((const char *)node->name, "rss")==0) { const char * version = (const char *)xmlGetProp(node, (const xmlChar *)"version"); if (!version) { xmlFree((void *)version); throw exception(_("no RSS version")); } if (strcmp(version, "0.91")==0) f.rss_version = RSS_0_91; else if (strcmp(version, "0.92")==0) f.rss_version = RSS_0_92; else if (strcmp(version, "0.94")==0) f.rss_version = RSS_0_94; else if (strcmp(version, "2.0")==0 || strcmp(version, "2")==0) f.rss_version = RSS_2_0; else if (strcmp(version, "1.0")==0) f.rss_version = RSS_0_91; else { xmlFree((void *)version); throw exception(_("invalid RSS version")); } xmlFree((void *)version); } else if (strcmp((const char *)node->name, "RDF")==0) { f.rss_version = RSS_1_0; } else if (strcmp((const char *)node->name, "feed")==0) { if (node->ns && node->ns->href) { if (strcmp((const char *)node->ns->href, ATOM_0_3_URI)==0) { f.rss_version = ATOM_0_3; } else if (strcmp((const char *)node->ns->href, ATOM_1_0_URI)==0) { f.rss_version = ATOM_1_0; } else { const char * version = (const char *)xmlGetProp(node, (const xmlChar *)"version"); if (!version) { xmlFree((void *)version); throw exception(_("invalid Atom version")); } if (strcmp(version, "0.3")==0) { xmlFree((void *)version); f.rss_version = ATOM_0_3_NONS; } else { xmlFree((void *)version); throw exception(_("invalid Atom version")); } } } else { throw exception(_("no Atom version")); } } std::shared_ptr<rss_parser> parser = rss_parser_factory::get_object(f, doc); try { parser->parse_feed(f, node); } catch (exception& e) { throw; } } } else { throw exception(_("XML root node is nullptr")); } return f; } void parser::global_init() { LIBXML_TEST_VERSION curl_global_init(CURL_GLOBAL_ALL); } void parser::global_cleanup() { xmlCleanupParser(); curl_global_cleanup(); } }
/* rsspp - Copyright (C) 2008-2012 Andreas Krennmair <[email protected]> * Licensed under the MIT/X Consortium License. See file LICENSE * for more information. */ #include <config.h> #include <rsspp.h> #include <rsspp_internal.h> #include <libxml/parser.h> #include <libxml/tree.h> #include <curl/curl.h> #include <logger.h> #include <utils.h> #include <cstring> #include <utils.h> #include <remote_api.h> using namespace newsbeuter; static size_t my_write_data(void *buffer, size_t size, size_t nmemb, void *userp) { std::string * pbuf = static_cast<std::string *>(userp); pbuf->append(static_cast<const char *>(buffer), size * nmemb); return size * nmemb; } namespace rsspp { parser::parser(unsigned int timeout, const char * user_agent, const char * proxy, const char * proxy_auth, curl_proxytype proxy_type, const bool ssl_verify) : to(timeout), ua(user_agent), prx(proxy), prxauth(proxy_auth), prxtype(proxy_type), verify_ssl(ssl_verify), doc(0), lm(0) { } parser::~parser() { if (doc) xmlFreeDoc(doc); } struct header_values { time_t lastmodified; std::string etag; header_values() : lastmodified(0) { } }; static size_t handle_headers(void * ptr, size_t size, size_t nmemb, void * data) { char * header = new char[size*nmemb + 1]; header_values * values = (header_values *)data; memcpy(header, ptr, size*nmemb); header[size*nmemb] = '\0'; if (!strncasecmp("Last-Modified:", header, 14)) { time_t r = curl_getdate(header+14, nullptr); if (r == -1) { LOG(LOG_DEBUG, "handle_headers: last-modified %s (curl_getdate FAILED)", header+14); } else { values->lastmodified = curl_getdate(header+14, nullptr); LOG(LOG_DEBUG, "handle_headers: got last-modified %s (%d)", header+14, values->lastmodified); } } else if (!strncasecmp("ETag:",header, 5)) { values->etag = std::string(header+5); utils::trim(values->etag); LOG(LOG_DEBUG, "handle_headers: got etag %s", values->etag.c_str()); } delete[] header; return size * nmemb; } feed parser::parse_url(const std::string& url, time_t lastmodified, const std::string& etag, newsbeuter::remote_api * api, const std::string& cookie_cache, CURL *ehandle) { std::string buf; CURLcode ret; curl_slist* custom_headers {}; CURL * easyhandle = ehandle; if (!easyhandle) { easyhandle = curl_easy_init(); if (!easyhandle) { throw exception(_("couldn't initialize libcurl")); } } if (ua) { curl_easy_setopt(easyhandle, CURLOPT_USERAGENT, ua); } if (api) { api->add_custom_headers(&custom_headers); } curl_easy_setopt(easyhandle, CURLOPT_URL, url.c_str()); curl_easy_setopt(easyhandle, CURLOPT_SSL_VERIFYPEER, verify_ssl); curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, my_write_data); curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &buf); curl_easy_setopt(easyhandle, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(easyhandle, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(easyhandle, CURLOPT_MAXREDIRS, 10); curl_easy_setopt(easyhandle, CURLOPT_FAILONERROR, 1); curl_easy_setopt(easyhandle, CURLOPT_ENCODING, "gzip, deflate"); if (cookie_cache != "") { curl_easy_setopt(easyhandle, CURLOPT_COOKIEFILE, cookie_cache.c_str()); curl_easy_setopt(easyhandle, CURLOPT_COOKIEJAR, cookie_cache.c_str()); } if (to != 0) curl_easy_setopt(easyhandle, CURLOPT_TIMEOUT, to); if (prx) curl_easy_setopt(easyhandle, CURLOPT_PROXY, prx); if (prxauth) { curl_easy_setopt(easyhandle, CURLOPT_PROXYAUTH, CURLAUTH_ANY); curl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, prxauth); } curl_easy_setopt(easyhandle, CURLOPT_PROXYTYPE, prxtype); header_values hdrs; curl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &hdrs); curl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, handle_headers); if (lastmodified != 0) { curl_easy_setopt(easyhandle, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE); curl_easy_setopt(easyhandle, CURLOPT_TIMEVALUE, lastmodified); } if (etag.length() > 0) { auto header = utils::strprintf("If-None-Match: %s", etag.c_str()); custom_headers = curl_slist_append(custom_headers, header.c_str()); custom_headers = curl_slist_append(custom_headers, "A-IM: feed"); } if (custom_headers) { curl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, custom_headers); } ret = curl_easy_perform(easyhandle); lm = hdrs.lastmodified; et = hdrs.etag; if (custom_headers) { curl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, 0); curl_slist_free_all(custom_headers); } LOG(LOG_DEBUG, "rsspp::parser::parse_url: ret = %d", ret); long status; curl_easy_getinfo(easyhandle, CURLINFO_HTTP_CONNECTCODE, &status); if (status >= 400) { LOG(LOG_USERERROR, _("Error: trying to download feed `%s' returned HTTP status code %ld."), url.c_str(), status); } curl_easy_reset(easyhandle); if (!ehandle) curl_easy_cleanup(easyhandle); if (ret != 0) { LOG(LOG_ERROR, "rsspp::parser::parse_url: curl_easy_perform returned err %d: %s", ret, curl_easy_strerror(ret)); throw exception(curl_easy_strerror(ret)); } LOG(LOG_INFO, "parser::parse_url: retrieved data for %s: %s", url.c_str(), buf.c_str()); if (buf.length() > 0) { LOG(LOG_DEBUG, "parser::parse_url: handing over data to parse_buffer()"); return parse_buffer(buf.c_str(), buf.length(), url.c_str()); } return feed(); } feed parser::parse_buffer(const char * buffer, size_t size, const char * url) { doc = xmlReadMemory(buffer, size, url, nullptr, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING); if (doc == nullptr) { throw exception(_("could not parse buffer")); } xmlNode* root_element = xmlDocGetRootElement(doc); feed f = parse_xmlnode(root_element); if (doc->encoding) { f.encoding = (const char *)doc->encoding; } LOG(LOG_INFO, "parser::parse_buffer: encoding = %s", f.encoding.c_str()); return f; } feed parser::parse_file(const std::string& filename) { doc = xmlReadFile(filename.c_str(), nullptr, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING); xmlNode* root_element = xmlDocGetRootElement(doc); if (root_element == nullptr) { throw exception(_("could not parse file")); } feed f = parse_xmlnode(root_element); if (doc->encoding) { f.encoding = (const char *)doc->encoding; } LOG(LOG_INFO, "parser::parse_file: encoding = %s", f.encoding.c_str()); return f; } feed parser::parse_xmlnode(xmlNode* node) { feed f; if (node) { if (node->name && node->type == XML_ELEMENT_NODE) { if (strcmp((const char *)node->name, "rss")==0) { const char * version = (const char *)xmlGetProp(node, (const xmlChar *)"version"); if (!version) { xmlFree((void *)version); throw exception(_("no RSS version")); } if (strcmp(version, "0.91")==0) f.rss_version = RSS_0_91; else if (strcmp(version, "0.92")==0) f.rss_version = RSS_0_92; else if (strcmp(version, "0.94")==0) f.rss_version = RSS_0_94; else if (strcmp(version, "2.0")==0 || strcmp(version, "2")==0) f.rss_version = RSS_2_0; else if (strcmp(version, "1.0")==0) f.rss_version = RSS_0_91; else { xmlFree((void *)version); throw exception(_("invalid RSS version")); } xmlFree((void *)version); } else if (strcmp((const char *)node->name, "RDF")==0) { f.rss_version = RSS_1_0; } else if (strcmp((const char *)node->name, "feed")==0) { if (node->ns && node->ns->href) { if (strcmp((const char *)node->ns->href, ATOM_0_3_URI)==0) { f.rss_version = ATOM_0_3; } else if (strcmp((const char *)node->ns->href, ATOM_1_0_URI)==0) { f.rss_version = ATOM_1_0; } else { const char * version = (const char *)xmlGetProp(node, (const xmlChar *)"version"); if (!version) { xmlFree((void *)version); throw exception(_("invalid Atom version")); } if (strcmp(version, "0.3")==0) { xmlFree((void *)version); f.rss_version = ATOM_0_3_NONS; } else { xmlFree((void *)version); throw exception(_("invalid Atom version")); } } } else { throw exception(_("no Atom version")); } } std::shared_ptr<rss_parser> parser = rss_parser_factory::get_object(f, doc); try { parser->parse_feed(f, node); } catch (exception& e) { throw; } } } else { throw exception(_("XML root node is nullptr")); } return f; } void parser::global_init() { LIBXML_TEST_VERSION curl_global_init(CURL_GLOBAL_ALL); } void parser::global_cleanup() { xmlCleanupParser(); curl_global_cleanup(); } }
Support for delta feeds (RFC3229+feed)
Support for delta feeds (RFC3229+feed) The `If-None-Match` header combined with the `A-IM: feed` header instructs compatible servers to only send the feed entries that have been added or changed since the feed was last updated. (As determined using the ETag sent by the server which is later returned by the If-None-Match header.)
C++
mit
der-lyse/newsboat,der-lyse/newsboat,der-lyse/newsboat,newsboat/newsboat,x4121/newsbeuter,x4121/newsbeuter,newsboat/newsboat,newsboat/newsboat,der-lyse/newsboat,newsboat/newsboat,der-lyse/newsboat,newsboat/newsboat,newsboat/newsboat,newsboat/newsboat,x4121/newsbeuter,newsboat/newsboat,x4121/newsbeuter,der-lyse/newsboat,der-lyse/newsboat,der-lyse/newsboat
ebe9c045924ec730ea8d2077b4d90d588195885c
demo/oxygenlistdemowidget.cpp
demo/oxygenlistdemowidget.cpp
/* * this file is part of the oxygen gtk engine * Copyright (c) 2010 Hugo Pereira Da Costa <[email protected]> * * based on the Null Theme Engine for Gtk+. * Copyright (c) 2008 Robert Staudinger <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or( at your option ) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "oxygenlistdemowidget.h" #include <iostream> #include <string> namespace Oxygen { //____________________________________________________ ListDemoWidget::ListDemoWidget( void ) { // main widget GtkWidget* mainWidget( gtk_vbox_new( false, 0 ) ); gtk_box_set_spacing( GTK_BOX( mainWidget ), 5 ); setWidget( mainWidget ); // setup setName( "Lists" ); setComments( "Shows the appearance of lists and trees" ); setIconName( "view-list-tree" ); realize(); // vertical pane GtkWidget* vpaned( gtk_vpaned_new() ); gtk_widget_show( vpaned ); gtk_box_pack_start( GTK_BOX( mainWidget ), vpaned, true, true, 0 ); // simple list { GtkListStore* model( gtk_list_store_new( 1, G_TYPE_STRING ) ); const char* columns[] = { "First Item", "Second Item", "Third Item" }; for( unsigned int i=0; i<3; i++ ) { GtkTreeIter iter; gtk_list_store_append( model, &iter ); gtk_list_store_set( model, &iter, 0, columns[i], -1 ); } GtkWidget* treeView( gtk_tree_view_new_with_model( GTK_TREE_MODEL( model ) ) ); gtk_tree_view_set_headers_visible( GTK_TREE_VIEW( treeView ), false ); gtk_widget_show( treeView ); // renderer GtkCellRenderer *renderer( gtk_cell_renderer_text_new() ); GtkTreeViewColumn *column( gtk_tree_view_column_new_with_attributes( "", renderer, "text", 0, NULL ) ); gtk_tree_view_append_column( GTK_TREE_VIEW( treeView ), column ); // scrolled window GtkWidget* scrolledWindow( gtk_scrolled_window_new( 0L, 0L ) ); gtk_scrolled_window_set_shadow_type( GTK_SCROLLED_WINDOW( scrolledWindow ), GTK_SHADOW_IN ); gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolledWindow ), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC ); gtk_container_add( GTK_CONTAINER( scrolledWindow ), treeView ); gtk_container_set_border_width( GTK_CONTAINER( scrolledWindow ), 2 ); gtk_widget_show( scrolledWindow ); gtk_paned_pack1( GTK_PANED( vpaned ), scrolledWindow, true, true ); } // tree { GtkTreeStore* model( gtk_tree_store_new ( 2, G_TYPE_STRING, G_TYPE_STRING ) ); const char* titleColumns[] = { "First Item", "Second Item", "Third Item" }; const char* descriptionColumns[] = { "First Description", "Second Description", "Third Description" }; const char* subTitleColumns[] = { "First Subitem", "Second Subitem", "Third Subitem" }; const char* subDescriptionColumns[] = { "First Subitem Description", "Second Subitem Description", "Third Subitem Description" }; for( unsigned int i=0; i<3; i++ ) { GtkTreeIter iter; gtk_tree_store_append( model, &iter, 0L ); gtk_tree_store_set( model, &iter, 0, titleColumns[i], 1, descriptionColumns[i], -1 ); // append children if( i == 1 ) { for( unsigned int i=0; i<2; i++ ) { GtkTreeIter subiter; gtk_tree_store_append( model, &subiter, &iter ); gtk_tree_store_set( model, &subiter, 0, subTitleColumns[i], 1, subDescriptionColumns[i], -1 ); } } else if( i == 2 ) { GtkTreeIter subiter; gtk_tree_store_append( model, &subiter, &iter ); gtk_tree_store_set( model, &subiter, 0, subTitleColumns[2], 1, subDescriptionColumns[2], -1 ); } } GtkWidget* treeView( gtk_tree_view_new_with_model( GTK_TREE_MODEL( model ) ) ); gtk_tree_view_set_headers_visible( GTK_TREE_VIEW( treeView ), true ); gtk_widget_show( treeView ); // renderers { GtkCellRenderer *renderer( gtk_cell_renderer_text_new() ); GtkTreeViewColumn *column( gtk_tree_view_column_new_with_attributes( "Title", renderer, "text", 0, NULL ) ); gtk_tree_view_append_column( GTK_TREE_VIEW( treeView ), column ); } { GtkCellRenderer *renderer( gtk_cell_renderer_text_new() ); GtkTreeViewColumn *column( gtk_tree_view_column_new_with_attributes( "Description", renderer, "text", 1, NULL ) ); gtk_tree_view_append_column( GTK_TREE_VIEW( treeView ), column ); } // scrolled window GtkWidget* scrolledWindow( gtk_scrolled_window_new( 0L, 0L ) ); gtk_scrolled_window_set_shadow_type( GTK_SCROLLED_WINDOW( scrolledWindow ), GTK_SHADOW_IN ); gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolledWindow ), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC ); gtk_container_add( GTK_CONTAINER( scrolledWindow ), treeView ); gtk_container_set_border_width( GTK_CONTAINER( scrolledWindow ), 2 ); gtk_widget_show( scrolledWindow ); gtk_paned_pack2( GTK_PANED( vpaned ), scrolledWindow, true, true ); } } }
/* * this file is part of the oxygen gtk engine * Copyright (c) 2010 Hugo Pereira Da Costa <[email protected]> * * based on the Null Theme Engine for Gtk+. * Copyright (c) 2008 Robert Staudinger <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or( at your option ) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "oxygenlistdemowidget.h" #include <iostream> #include <string> namespace Oxygen { //____________________________________________________ ListDemoWidget::ListDemoWidget( void ) { // main widget GtkWidget* mainWidget( gtk_vbox_new( false, 0 ) ); gtk_box_set_spacing( GTK_BOX( mainWidget ), 5 ); setWidget( mainWidget ); // setup setName( "Lists" ); setComments( "Shows the appearance of lists and trees" ); setIconName( "view-list-tree" ); realize(); // vertical pane GtkWidget* vpaned( gtk_vpaned_new() ); gtk_widget_show( vpaned ); gtk_box_pack_start( GTK_BOX( mainWidget ), vpaned, true, true, 0 ); // simple list { GtkListStore* model( gtk_list_store_new( 1, G_TYPE_STRING ) ); const char* columns[] = { "First Item", "Second Item", "Third Item" }; for( unsigned int i=0; i<3; i++ ) { GtkTreeIter iter; gtk_list_store_append( model, &iter ); gtk_list_store_set( model, &iter, 0, columns[i], -1 ); } GtkWidget* treeView( gtk_tree_view_new_with_model( GTK_TREE_MODEL( model ) ) ); gtk_tree_view_set_headers_visible( GTK_TREE_VIEW( treeView ), false ); gtk_widget_show( treeView ); // renderer GtkCellRenderer *renderer( gtk_cell_renderer_text_new() ); GtkTreeViewColumn *column( gtk_tree_view_column_new_with_attributes( "", renderer, "text", 0, NULL ) ); gtk_tree_view_append_column( GTK_TREE_VIEW( treeView ), column ); // scrolled window GtkWidget* scrolledWindow( gtk_scrolled_window_new( 0L, 0L ) ); gtk_scrolled_window_set_shadow_type( GTK_SCROLLED_WINDOW( scrolledWindow ), GTK_SHADOW_IN ); gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolledWindow ), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC ); gtk_container_add( GTK_CONTAINER( scrolledWindow ), treeView ); gtk_container_set_border_width( GTK_CONTAINER( scrolledWindow ), 2 ); gtk_widget_show( scrolledWindow ); gtk_paned_pack1( GTK_PANED( vpaned ), scrolledWindow, true, true ); } // tree { GtkTreeStore* model( gtk_tree_store_new ( 2, G_TYPE_STRING, G_TYPE_STRING ) ); const char* titleColumns[] = { "First Item", "Second Item", "Third Item" }; const char* descriptionColumns[] = { "First Description", "Second Description", "Third Description" }; const char* subTitleColumns[] = { "First Subitem", "Second Subitem", "Third Subitem" }; const char* subDescriptionColumns[] = { "First Subitem Description", "Second Subitem Description", "Third Subitem Description" }; for( unsigned int i=0; i<3; i++ ) { GtkTreeIter iter; gtk_tree_store_append( model, &iter, 0L ); gtk_tree_store_set( model, &iter, 0, titleColumns[i], 1, descriptionColumns[i], -1 ); // append children if( i == 1 ) { for( unsigned int i=0; i<2; i++ ) { GtkTreeIter subiter; gtk_tree_store_append( model, &subiter, &iter ); gtk_tree_store_set( model, &subiter, 0, subTitleColumns[i], 1, subDescriptionColumns[i], -1 ); } } else if( i == 2 ) { GtkTreeIter subiter; gtk_tree_store_append( model, &subiter, &iter ); gtk_tree_store_set( model, &subiter, 0, subTitleColumns[2], 1, subDescriptionColumns[2], -1 ); } } GtkWidget* treeView( gtk_tree_view_new_with_model( GTK_TREE_MODEL( model ) ) ); gtk_tree_view_set_headers_visible( GTK_TREE_VIEW( treeView ), true ); gtk_widget_show( treeView ); // renderers { GtkCellRenderer *renderer( gtk_cell_renderer_text_new() ); GtkTreeViewColumn *column( gtk_tree_view_column_new_with_attributes( "Title", renderer, "text", 0, NULL ) ); gtk_tree_view_column_set_resizable(column, TRUE); gtk_tree_view_append_column( GTK_TREE_VIEW( treeView ), column ); } { GtkCellRenderer *renderer( gtk_cell_renderer_text_new() ); GtkTreeViewColumn *column( gtk_tree_view_column_new_with_attributes( "Description", renderer, "text", 1, NULL ) ); gtk_tree_view_column_set_resizable(column, TRUE); gtk_tree_view_append_column( GTK_TREE_VIEW( treeView ), column ); } // scrolled window GtkWidget* scrolledWindow( gtk_scrolled_window_new( 0L, 0L ) ); gtk_scrolled_window_set_shadow_type( GTK_SCROLLED_WINDOW( scrolledWindow ), GTK_SHADOW_IN ); gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolledWindow ), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC ); gtk_container_add( GTK_CONTAINER( scrolledWindow ), treeView ); gtk_container_set_border_width( GTK_CONTAINER( scrolledWindow ), 2 ); gtk_widget_show( scrolledWindow ); gtk_paned_pack2( GTK_PANED( vpaned ), scrolledWindow, true, true ); } } }
Make treeview columns resizable in oxygen-gtk-demo
Make treeview columns resizable in oxygen-gtk-demo
C++
lgpl-2.1
KDE/oxygen-gtk,blue-shell/carbon-gtk,blueshell-next/carbon-gtk,blueshell-next/carbon-gtk,KDE/oxygen-gtk,blue-shell/carbon-gtk
becbfeda4793992cbb35588cd9db87be41bef620
common/engine/keyboardprocessor/tests/unit/kmx/kmx.cpp
common/engine/keyboardprocessor/tests/unit/kmx/kmx.cpp
/* Copyright: © 2018 SIL International. Description: Tests for kmx integration Create Date: 30 Oct 2018 Authors: Marc Durdin (MD), Tim Eves (TSE) */ #include <string> #include <fstream> #include <sstream> #include <cctype> #include <keyman/keyboardprocessor.h> #include "state.hpp" #define try_status(expr) \ {auto __s = (expr); if (__s != KM_KBP_STATUS_OK) std::exit(100*__LINE__+__s);} #ifdef assert #undef assert #endif #define assert(expr) {if (!(expr)) std::exit(100*__LINE__); } std::string utf16_to_utf8(std::u16string utf16_string); namespace { const std::string base = "tests/unit/kmx/"; int run_test(const std::string & file); int load_source(const std::string & file, std::string & keys, std::u16string & expected, std::u16string & context); struct key_event { km_kbp_virtual_key vk; uint16_t modifier_state; }; km_kbp_option_item test_env_opts[] = { KM_KBP_OPTIONS_END }; // String trim functions from https://stackoverflow.com/a/217605/1836776 // trim from start (in place) static inline void ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { return !std::isspace(ch); })); } // trim from end (in place) static inline void rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return !std::isspace(ch); }).base(), s.end()); } // trim from both ends (in place) static inline void trim(std::string &s) { ltrim(s); rtrim(s); } // trim from start (copying) static inline std::string ltrim_copy(std::string s) { ltrim(s); return s; } // trim from end (copying) static inline std::string rtrim_copy(std::string s) { rtrim(s); return s; } // trim from both ends (copying) static inline std::string trim_copy(std::string s) { trim(s); return s; } key_event char_to_event(char ch) { assert(ch >= 32 && ch < 128); return { s_char_to_vkey[(int)ch - 32].vk, (uint16_t)(s_char_to_vkey[(int)ch - 32].shifted ? KM_KBP_MODIFIER_SHIFT : 0) }; } uint16_t const get_modifier(std::string const m) { for (int i = 0; s_modifier_names[i].name; i++) { if (m == s_modifier_names[i].name) { return s_modifier_names[i].modifier; } } return 0; } km_kbp_virtual_key const get_vk(std::string const & vk) { for (int i = 1; i < 256; i++) { if (vk == s_key_names[i]) { return i; } } return 0; } key_event const vkey_to_event(std::string const & vk_event) { // vkey format is MODIFIER MODIFIER K_NAME //std::cout << "VK=" << vk_event << std::endl; std::stringstream f(vk_event); std::string s; uint16_t modifier_state = 0; km_kbp_virtual_key vk; while(std::getline(f, s, ' ')) { uint16_t modifier = get_modifier(s); if (modifier != 0) { modifier_state |= modifier; } else { vk = get_vk(s); assert(vk != 0); break; } } // The string should be empty at this point assert(!std::getline(f, s, ' ')); return { vk, modifier_state }; } key_event next_key(std::string &keys) { // Parse the next element of the string, chop it off, and return it if (keys.length() == 0) return { 0 }; char ch = keys[0]; if (ch == '[') { if (keys.length() > 1 && keys[1] == '[') { keys.erase(0, 2); return char_to_event(ch); } auto n = keys.find(']'); assert(n != std::string::npos); auto vkey = keys.substr(1, n - 1); keys.erase(0, n+1); return vkey_to_event(vkey); } else { keys.erase(0, 1); return char_to_event(ch); } } void apply_action(km_kbp_state const * state, km_kbp_action_item const & act) { switch (act.type) { case KM_KBP_IT_END: assert(false); break; case KM_KBP_IT_ALERT: //std::cout << "beep" << std::endl; break; case KM_KBP_IT_CHAR: //std::cout << "char(" << act.character << ") size=" << cp->size() << std::endl; break; case KM_KBP_IT_MARKER: //std::cout << "deadkey(" << act.marker << ")" << std::endl; break; case KM_KBP_IT_BACK: break; case KM_KBP_IT_PERSIST_OPT: case KM_KBP_IT_RESET_OPT: assert(false); // TODO break; case KM_KBP_IT_VKEYDOWN: case KM_KBP_IT_VKEYUP: case KM_KBP_IT_VSHIFTDOWN: case KM_KBP_IT_VSHIFTUP: assert(false); // NOT SUPPORTED break; default: assert(false); // NOT SUPPORTED break; } } int run_test(const std::string & file) { std::string keys = ""; std::u16string expected = u"", context = u""; int result = load_source(file, keys, expected, context); if (result != 0) return result; //std::cout << "keys = " << keys << std::endl; //std::cout << "expected = " << utf16_to_utf8(expected) << std::endl; //std::cout << "context = " << utf16_to_utf8(context) << std::endl; // TODO: compile the keyboard using kmcomp km_kbp_keyboard * test_kb = nullptr; km_kbp_state * test_state = nullptr; try_status(km_kbp_keyboard_load(std::filesystem::path(base + file + ".kmx").c_str(), &test_kb)); // Setup state, environment, options try_status(km_kbp_state_create(test_kb, test_env_opts, &test_state)); // Setup context km_kbp_context_item *citems = nullptr; try_status(km_kbp_context_items_from_utf16(context.c_str(), &citems)); try_status(km_kbp_context_set(km_kbp_state_context(test_state), citems)); km_kbp_context_items_dispose(citems); // Run through key events, applying output for each event for (auto p = next_key(keys); p.vk != 0; p = next_key(keys)) { try_status(km_kbp_process_event(test_state, p.vk, p.modifier_state)); for (auto act = km_kbp_state_action_items(test_state, nullptr); act->type != KM_KBP_IT_END; act++) { apply_action(test_state, *act); } } // Compare final output { TODO: don't use the inbuilt context, instead use the actions, starting with context } size_t n = 0; try_status(km_kbp_context_get(km_kbp_state_context(test_state), &citems)); try_status(km_kbp_context_items_to_utf16(citems, nullptr, &n)); km_kbp_cp *buf = new km_kbp_cp[n]; try_status(km_kbp_context_items_to_utf16(citems, buf, &n)); km_kbp_context_items_dispose(citems); //std::cout << "result = " << utf16_to_utf8(buf) << std::endl; // Destroy them km_kbp_state_dispose(test_state); km_kbp_keyboard_dispose(test_kb); return (buf == expected) ? 0 : __LINE__; } std::u16string parse_source_string(std::string const & s) { std::u16string t; for (auto p = s.begin(); p != s.end(); p++) { if (*p == '\\') { p++; km_kbp_usv v; assert(p != s.end()); if (*p == 'u') { // Unicode value p++; size_t n; std::string s1 = s.substr(p - s.begin(), 6); v = std::stoul(s1, &n, 16); assert(v >= 0x20 && v <= 0x10FFFF); p += n-1; if (v < 0x10000) { t += km_kbp_cp(v); } else { t += km_kbp_cp(Uni_UTF32ToSurrogate1(v)) + km_kbp_cp(Uni_UTF32ToSurrogate2(v)); } } else if (*p == 'd') { // Deadkey // TODO, not yet supported assert(false); } } else { t += *p; } } return t; } int load_source(const std::string & file, std::string & keys, std::u16string & expected, std::u16string & context) { const std::string s_keys = "c keys: ", s_expected = "c expected: ", s_context = "c context: "; //std::cout << "load_source " << base + file + ".kmn" << std::endl; // Parse out the header statements in file.kmn that tell us (a) environment, (b) key sequence, (c) start context, (d) expected result std::ifstream kmn(base + file + ".kmn"); std::string line; while (std::getline(kmn, line)) { trim(line); if (!line.length()) continue; if (line.compare(0, s_keys.length(), s_keys) == 0) { keys = line.substr(s_keys.length()); trim(keys); } else if (line.compare(0, s_expected.length(), s_expected) == 0) { line = line.substr(s_expected.length()); trim(line); expected = parse_source_string(line); } else if (line.compare(0, s_context.length(), s_context) == 0) { line = line.substr(s_context.length()); trim(line); context = parse_source_string(line); } } if (keys == "") { // We must at least have a key sequence to run the test return __LINE__; } return 0; } } // namespace int main(int, char *[]) { int result; if ((result = run_test("000 - null keyboard")) != 0) return result; if ((result = run_test("001 - basic input UnicodeI")) != 0) return result; if ((result = run_test("002 - basic input Unicode")) != 0) return result; if ((result = run_test("004 - basic input (shift 2)")) != 0) return result; if ((result = run_test("006 - vkey input (shift ctrl)")) != 0) return result; if ((result = run_test("007 - vkey input (ctrl alt)")) != 0) return result; if ((result = run_test("008 - vkey input (ctrl alt 2)")) != 0) return result; if ((result = run_test("012 - ralt")) != 0) return result; if ((result = run_test("013 - deadkeys")) != 0) return result; if ((result = run_test("014 - groups and virtual keys")) != 0) return result; if ((result = run_test("015 - ralt 2")) != 0) return result; if ((result = run_test("017 - space mnemonic kbd")) != 0) return result; if ((result = run_test("018 - nul testing")) != 0) return result; if ((result = run_test("019 - multiple deadkeys")) != 0) return result; if ((result = run_test("020 - deadkeys and backspace")) != 0) return result; return result; }
/* Copyright: © 2018 SIL International. Description: Tests for kmx integration Create Date: 30 Oct 2018 Authors: Marc Durdin (MD), Tim Eves (TSE) */ #include <string> #include <fstream> #include <sstream> #include <cctype> #include <algorithm> #include <keyman/keyboardprocessor.h> #include "state.hpp" #define try_status(expr) \ {auto __s = (expr); if (__s != KM_KBP_STATUS_OK) std::exit(100*__LINE__+__s);} #ifdef assert #undef assert #endif #define assert(expr) {if (!(expr)) std::exit(100*__LINE__); } std::string utf16_to_utf8(std::u16string utf16_string); namespace { const std::string base = "tests/unit/kmx/"; int run_test(const std::string & file); int load_source(const std::string & file, std::string & keys, std::u16string & expected, std::u16string & context); struct key_event { km_kbp_virtual_key vk; uint16_t modifier_state; }; km_kbp_option_item test_env_opts[] = { KM_KBP_OPTIONS_END }; // String trim functions from https://stackoverflow.com/a/217605/1836776 // trim from start (in place) static inline void ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { return !std::isspace(ch); })); } // trim from end (in place) static inline void rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return !std::isspace(ch); }).base(), s.end()); } // trim from both ends (in place) static inline void trim(std::string &s) { ltrim(s); rtrim(s); } // trim from start (copying) static inline std::string ltrim_copy(std::string s) { ltrim(s); return s; } // trim from end (copying) static inline std::string rtrim_copy(std::string s) { rtrim(s); return s; } // trim from both ends (copying) static inline std::string trim_copy(std::string s) { trim(s); return s; } key_event char_to_event(char ch) { assert(ch >= 32 && ch < 128); return { s_char_to_vkey[(int)ch - 32].vk, (uint16_t)(s_char_to_vkey[(int)ch - 32].shifted ? KM_KBP_MODIFIER_SHIFT : 0) }; } uint16_t const get_modifier(std::string const m) { for (int i = 0; s_modifier_names[i].name; i++) { if (m == s_modifier_names[i].name) { return s_modifier_names[i].modifier; } } return 0; } km_kbp_virtual_key const get_vk(std::string const & vk) { for (int i = 1; i < 256; i++) { if (vk == s_key_names[i]) { return i; } } return 0; } key_event const vkey_to_event(std::string const & vk_event) { // vkey format is MODIFIER MODIFIER K_NAME //std::cout << "VK=" << vk_event << std::endl; std::stringstream f(vk_event); std::string s; uint16_t modifier_state = 0; km_kbp_virtual_key vk; while(std::getline(f, s, ' ')) { uint16_t modifier = get_modifier(s); if (modifier != 0) { modifier_state |= modifier; } else { vk = get_vk(s); assert(vk != 0); break; } } // The string should be empty at this point assert(!std::getline(f, s, ' ')); return { vk, modifier_state }; } key_event next_key(std::string &keys) { // Parse the next element of the string, chop it off, and return it if (keys.length() == 0) return { 0 }; char ch = keys[0]; if (ch == '[') { if (keys.length() > 1 && keys[1] == '[') { keys.erase(0, 2); return char_to_event(ch); } auto n = keys.find(']'); assert(n != std::string::npos); auto vkey = keys.substr(1, n - 1); keys.erase(0, n+1); return vkey_to_event(vkey); } else { keys.erase(0, 1); return char_to_event(ch); } } void apply_action(km_kbp_state const * state, km_kbp_action_item const & act) { switch (act.type) { case KM_KBP_IT_END: assert(false); break; case KM_KBP_IT_ALERT: //std::cout << "beep" << std::endl; break; case KM_KBP_IT_CHAR: //std::cout << "char(" << act.character << ") size=" << cp->size() << std::endl; break; case KM_KBP_IT_MARKER: //std::cout << "deadkey(" << act.marker << ")" << std::endl; break; case KM_KBP_IT_BACK: break; case KM_KBP_IT_PERSIST_OPT: case KM_KBP_IT_RESET_OPT: assert(false); // TODO break; case KM_KBP_IT_VKEYDOWN: case KM_KBP_IT_VKEYUP: case KM_KBP_IT_VSHIFTDOWN: case KM_KBP_IT_VSHIFTUP: assert(false); // NOT SUPPORTED break; default: assert(false); // NOT SUPPORTED break; } } int run_test(const std::string & file) { std::string keys = ""; std::u16string expected = u"", context = u""; int result = load_source(file, keys, expected, context); if (result != 0) return result; //std::cout << "keys = " << keys << std::endl; //std::cout << "expected = " << utf16_to_utf8(expected) << std::endl; //std::cout << "context = " << utf16_to_utf8(context) << std::endl; // TODO: compile the keyboard using kmcomp km_kbp_keyboard * test_kb = nullptr; km_kbp_state * test_state = nullptr; try_status(km_kbp_keyboard_load(std::filesystem::path(base + file + ".kmx").c_str(), &test_kb)); // Setup state, environment, options try_status(km_kbp_state_create(test_kb, test_env_opts, &test_state)); // Setup context km_kbp_context_item *citems = nullptr; try_status(km_kbp_context_items_from_utf16(context.c_str(), &citems)); try_status(km_kbp_context_set(km_kbp_state_context(test_state), citems)); km_kbp_context_items_dispose(citems); // Run through key events, applying output for each event for (auto p = next_key(keys); p.vk != 0; p = next_key(keys)) { try_status(km_kbp_process_event(test_state, p.vk, p.modifier_state)); for (auto act = km_kbp_state_action_items(test_state, nullptr); act->type != KM_KBP_IT_END; act++) { apply_action(test_state, *act); } } // Compare final output { TODO: don't use the inbuilt context, instead use the actions, starting with context } size_t n = 0; try_status(km_kbp_context_get(km_kbp_state_context(test_state), &citems)); try_status(km_kbp_context_items_to_utf16(citems, nullptr, &n)); km_kbp_cp *buf = new km_kbp_cp[n]; try_status(km_kbp_context_items_to_utf16(citems, buf, &n)); km_kbp_context_items_dispose(citems); //std::cout << "result = " << utf16_to_utf8(buf) << std::endl; // Destroy them km_kbp_state_dispose(test_state); km_kbp_keyboard_dispose(test_kb); return (buf == expected) ? 0 : __LINE__; } std::u16string parse_source_string(std::string const & s) { std::u16string t; for (auto p = s.begin(); p != s.end(); p++) { if (*p == '\\') { p++; km_kbp_usv v; assert(p != s.end()); if (*p == 'u') { // Unicode value p++; size_t n; std::string s1 = s.substr(p - s.begin(), 6); v = std::stoul(s1, &n, 16); assert(v >= 0x20 && v <= 0x10FFFF); p += n-1; if (v < 0x10000) { t += km_kbp_cp(v); } else { t += km_kbp_cp(Uni_UTF32ToSurrogate1(v)) + km_kbp_cp(Uni_UTF32ToSurrogate2(v)); } } else if (*p == 'd') { // Deadkey // TODO, not yet supported assert(false); } } else { t += *p; } } return t; } int load_source(const std::string & file, std::string & keys, std::u16string & expected, std::u16string & context) { const std::string s_keys = "c keys: ", s_expected = "c expected: ", s_context = "c context: "; //std::cout << "load_source " << base + file + ".kmn" << std::endl; // Parse out the header statements in file.kmn that tell us (a) environment, (b) key sequence, (c) start context, (d) expected result std::ifstream kmn(base + file + ".kmn"); std::string line; while (std::getline(kmn, line)) { trim(line); if (!line.length()) continue; if (line.compare(0, s_keys.length(), s_keys) == 0) { keys = line.substr(s_keys.length()); trim(keys); } else if (line.compare(0, s_expected.length(), s_expected) == 0) { line = line.substr(s_expected.length()); trim(line); expected = parse_source_string(line); } else if (line.compare(0, s_context.length(), s_context) == 0) { line = line.substr(s_context.length()); trim(line); context = parse_source_string(line); } } if (keys == "") { // We must at least have a key sequence to run the test return __LINE__; } return 0; } } // namespace int main(int, char *[]) { int result; if ((result = run_test("000 - null keyboard")) != 0) return result; if ((result = run_test("001 - basic input UnicodeI")) != 0) return result; if ((result = run_test("002 - basic input Unicode")) != 0) return result; if ((result = run_test("004 - basic input (shift 2)")) != 0) return result; if ((result = run_test("006 - vkey input (shift ctrl)")) != 0) return result; if ((result = run_test("007 - vkey input (ctrl alt)")) != 0) return result; if ((result = run_test("008 - vkey input (ctrl alt 2)")) != 0) return result; if ((result = run_test("012 - ralt")) != 0) return result; if ((result = run_test("013 - deadkeys")) != 0) return result; if ((result = run_test("014 - groups and virtual keys")) != 0) return result; if ((result = run_test("015 - ralt 2")) != 0) return result; if ((result = run_test("017 - space mnemonic kbd")) != 0) return result; if ((result = run_test("018 - nul testing")) != 0) return result; if ((result = run_test("019 - multiple deadkeys")) != 0) return result; if ((result = run_test("020 - deadkeys and backspace")) != 0) return result; return result; }
Add <algorithm> for kmx.cpp
[common] Add <algorithm> for kmx.cpp
C++
apache-2.0
tavultesoft/keymanweb,tavultesoft/keymanweb
6af2e09d7d6172b772ef427b8af2521f3ce4d634
src/block_manager.cpp
src/block_manager.cpp
/* Copyright 2016 Nervana Systems Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <iomanip> #include <fstream> #include <exception> #include "block_manager.hpp" #include "file_util.hpp" #include "cpio.hpp" using namespace std; using namespace nervana; const std::string block_manager::m_owner_lock_filename = "caching_in_progress"; const std::string block_manager::m_cache_complete_filename = "cache_complete"; nervana::block_manager::block_manager(block_loader_source* file_loader, size_t block_size, const string& cache_root, bool enable_shuffle) : async_manager<encoded_record_list, encoded_record_list>{file_loader, "block_manager"} , m_file_loader{*file_loader} , m_block_size{m_file_loader.block_size()} , m_block_count{m_file_loader.block_count()} , m_record_count{m_file_loader.record_count()} , m_current_block_number{0} , m_elements_per_record{m_file_loader.elements_per_record()} , m_cache_root{cache_root} , m_cache_enabled{m_cache_root.empty() == false} , m_shuffle_enabled{enable_shuffle} , m_block_load_sequence{} , m_rnd{get_global_random_seed()} { m_block_load_sequence.reserve(m_block_count); m_block_load_sequence.resize(m_block_count); iota(m_block_load_sequence.begin(), m_block_load_sequence.end(), 0); if (m_cache_enabled) { m_source_uid = file_loader->get_uid(); stringstream ss; ss << "aeon_cache_"; ss << hex << setw(8) << setfill('0') << m_source_uid; m_cache_dir = file_util::path_join(m_cache_root, ss.str()); if (file_util::exists(m_cache_dir) == false) { file_util::make_directory(m_cache_dir); } if (!check_if_complete(m_cache_dir)) { if (!take_ownership(m_cache_dir, m_cache_lock)) { throw runtime_error("dataset cache in process, try later"); } } } } nervana::encoded_record_list* block_manager::filler() { m_state = async_state::wait_for_buffer; encoded_record_list* rc = get_pending_buffer(); m_state = async_state::processing; encoded_record_list* input = nullptr; rc->clear(); if (m_cache_enabled) { // cache path string block_name = create_cache_block_name(m_block_load_sequence[m_current_block_number]); string block_file_path = file_util::path_join(m_cache_dir, block_name); if (file_util::exists(block_file_path)) { m_cache_hit++; ifstream f(block_file_path); if (f) { cpio::reader reader(f); for (size_t record_number = 0; record_number < reader.record_count(); record_number++) { encoded_record record; for (size_t element = 0; element < m_elements_per_record; element++) { vector<char> e; reader.read(e); record.add_element(e); } rc->add_record(record); } } } else { m_cache_miss++; m_state = async_state::fetching_data; input = m_source->next(); m_state = async_state::processing; if (input == nullptr) { rc = nullptr; } else { ofstream f(block_file_path); if (f) { cpio::writer writer(f); writer.write_all_records(*input); } input->swap(*rc); } } if (++m_current_block_number == m_block_count) { m_current_block_number = 0; // Done writing cache so unlock it mark_cache_complete(m_cache_dir); release_ownership(m_cache_dir, m_cache_lock); } } else { // The non-cache path m_state = async_state::fetching_data; input = m_source->next(); m_state = async_state::processing; if (input != nullptr) { rc->swap(*input); if (++m_current_block_number == m_block_count) { m_current_block_number = 0; m_file_loader.reset(); } } } if (m_shuffle_enabled && m_current_block_number == 0) { // This will not trigger on the first pass through the dataset shuffle(m_block_load_sequence.begin(), m_block_load_sequence.end(), m_rnd); } if (rc && rc->size() == 0) { rc = nullptr; } m_state = async_state::idle; return rc; } string block_manager::create_cache_name(source_uid_t uid) { stringstream ss; ss << "aeon_cache_"; ss << hex << setw(8) << setfill('0') << uid; return ss.str(); } string block_manager::create_cache_block_name(size_t block_number) { stringstream ss; ss << "block_" << block_number << ".cpio"; return ss.str(); } bool block_manager::check_if_complete(const std::string& cache_dir) { string file = file_util::path_join(cache_dir, m_cache_complete_filename); return file_util::exists(file); } void block_manager::mark_cache_complete(const std::string& cache_dir) { string file = file_util::path_join(cache_dir, m_cache_complete_filename); ofstream f{file}; } bool block_manager::take_ownership(const std::string& cache_dir, int& lock) { string file = file_util::path_join(cache_dir, m_owner_lock_filename); lock = file_util::try_get_lock(file); return lock != -1; } void block_manager::release_ownership(const std::string& cache_dir, int lock) { string file = file_util::path_join(cache_dir, m_owner_lock_filename); file_util::release_lock(lock, file); }
/* Copyright 2016 Nervana Systems Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <iomanip> #include <fstream> #include <exception> #include <random> #include "block_manager.hpp" #include "file_util.hpp" #include "cpio.hpp" using namespace std; using namespace nervana; const std::string block_manager::m_owner_lock_filename = "caching_in_progress"; const std::string block_manager::m_cache_complete_filename = "cache_complete"; nervana::block_manager::block_manager(block_loader_source* file_loader, size_t block_size, const string& cache_root, bool enable_shuffle) : async_manager<encoded_record_list, encoded_record_list>{file_loader, "block_manager"} , m_file_loader{*file_loader} , m_block_size{m_file_loader.block_size()} , m_block_count{m_file_loader.block_count()} , m_record_count{m_file_loader.record_count()} , m_current_block_number{0} , m_elements_per_record{m_file_loader.elements_per_record()} , m_cache_root{cache_root} , m_cache_enabled{m_cache_root.empty() == false} , m_shuffle_enabled{enable_shuffle} , m_block_load_sequence{} , m_rnd{get_global_random_seed()} { m_block_load_sequence.reserve(m_block_count); m_block_load_sequence.resize(m_block_count); iota(m_block_load_sequence.begin(), m_block_load_sequence.end(), 0); if (m_cache_enabled) { m_source_uid = file_loader->get_uid(); stringstream ss; ss << "aeon_cache_"; ss << hex << setw(8) << setfill('0') << m_source_uid; m_cache_dir = file_util::path_join(m_cache_root, ss.str()); if (file_util::exists(m_cache_dir) == false) { file_util::make_directory(m_cache_dir); } if (!check_if_complete(m_cache_dir)) { if (!take_ownership(m_cache_dir, m_cache_lock)) { throw runtime_error("dataset cache in process, try later"); } } } } nervana::encoded_record_list* block_manager::filler() { m_state = async_state::wait_for_buffer; encoded_record_list* rc = get_pending_buffer(); m_state = async_state::processing; encoded_record_list* input = nullptr; rc->clear(); if (m_cache_enabled) { // cache path string block_name = create_cache_block_name(m_block_load_sequence[m_current_block_number]); string block_file_path = file_util::path_join(m_cache_dir, block_name); if (file_util::exists(block_file_path)) { m_cache_hit++; ifstream f(block_file_path); if (f) { cpio::reader reader(f); for (size_t record_number = 0; record_number < reader.record_count(); record_number++) { encoded_record record; for (size_t element = 0; element < m_elements_per_record; element++) { vector<char> e; reader.read(e); record.add_element(e); } rc->add_record(record); } if (m_shuffle_enabled) { std::random_device rd; rc->shuffle(rd()); } } } else { m_cache_miss++; m_state = async_state::fetching_data; input = m_source->next(); m_state = async_state::processing; if (input == nullptr) { rc = nullptr; } else { ofstream f(block_file_path); if (f) { cpio::writer writer(f); writer.write_all_records(*input); } input->swap(*rc); } } if (++m_current_block_number == m_block_count) { m_current_block_number = 0; // Done writing cache so unlock it mark_cache_complete(m_cache_dir); release_ownership(m_cache_dir, m_cache_lock); } } else { // The non-cache path m_state = async_state::fetching_data; input = m_source->next(); m_state = async_state::processing; if (input != nullptr) { rc->swap(*input); if (++m_current_block_number == m_block_count) { m_current_block_number = 0; m_file_loader.reset(); } } } if (m_shuffle_enabled && m_current_block_number == 0) { // This will not trigger on the first pass through the dataset shuffle(m_block_load_sequence.begin(), m_block_load_sequence.end(), m_rnd); } if (rc && rc->size() == 0) { rc = nullptr; } m_state = async_state::idle; return rc; } string block_manager::create_cache_name(source_uid_t uid) { stringstream ss; ss << "aeon_cache_"; ss << hex << setw(8) << setfill('0') << uid; return ss.str(); } string block_manager::create_cache_block_name(size_t block_number) { stringstream ss; ss << "block_" << block_number << ".cpio"; return ss.str(); } bool block_manager::check_if_complete(const std::string& cache_dir) { string file = file_util::path_join(cache_dir, m_cache_complete_filename); return file_util::exists(file); } void block_manager::mark_cache_complete(const std::string& cache_dir) { string file = file_util::path_join(cache_dir, m_cache_complete_filename); ofstream f{file}; } bool block_manager::take_ownership(const std::string& cache_dir, int& lock) { string file = file_util::path_join(cache_dir, m_owner_lock_filename); lock = file_util::try_get_lock(file); return lock != -1; } void block_manager::release_ownership(const std::string& cache_dir, int lock) { string file = file_util::path_join(cache_dir, m_owner_lock_filename); file_util::release_lock(lock, file); }
enable shuffle inside block
enable shuffle inside block
C++
apache-2.0
NervanaSystems/aeon,NervanaSystems/aeon,NervanaSystems/aeon,NervanaSystems/aeon
60fa188ee32c6bc9be6f854c34889591f59236c3
tests/executor/tile_group_layout_test.cpp
tests/executor/tile_group_layout_test.cpp
//===----------------------------------------------------------------------===// // // PelotonDB // // materialization_test.cpp // // Identification: tests/executor/materialization_test.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <memory> #include <string> #include <unordered_map> #include <vector> #include <chrono> #include <iostream> #include <ctime> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "backend/planner/abstract_plan.h" #include "backend/planner/materialization_plan.h" #include "backend/planner/seq_scan_plan.h" #include "backend/catalog/manager.h" #include "backend/catalog/schema.h" #include "backend/common/types.h" #include "backend/common/value.h" #include "backend/common/value_factory.h" #include "backend/executor/logical_tile.h" #include "backend/executor/logical_tile_factory.h" #include "backend/executor/materialization_executor.h" #include "backend/storage/backend_vm.h" #include "backend/storage/tile.h" #include "backend/storage/tile_group.h" #include "backend/storage/data_table.h" #include "backend/concurrency/transaction.h" #include "backend/executor/abstract_executor.h" #include "backend/executor/seq_scan_executor.h" #include "backend/expression/abstract_expression.h" #include "backend/expression/expression_util.h" #include "backend/storage/table_factory.h" #include "backend/index/index_factory.h" #include "executor/executor_tests_util.h" #include "executor/mock_executor.h" using ::testing::NotNull; namespace peloton { namespace test { //===--------------------------------------------------------------------===// // Tile Group Layout Tests //===--------------------------------------------------------------------===// void RunTest() { std::chrono::time_point<std::chrono::system_clock> start, end; const int tuples_per_tilegroup_count = 10; const int tile_group_count = 5; const int tuple_count = tuples_per_tilegroup_count * tile_group_count; const oid_t col_count = 250; const bool is_inlined = true; const bool indexes = false; std::vector<catalog::Column> columns; for(oid_t col_itr = 0 ; col_itr <= col_count; col_itr++) { auto column = catalog::Column(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER), "FIELD" + std::to_string(col_itr), is_inlined); columns.push_back(column); } catalog::Schema *table_schema = new catalog::Schema(columns); std::string table_name("TEST_TABLE"); ///////////////////////////////////////////////////////// // Create table. ///////////////////////////////////////////////////////// bool own_schema = true; bool adapt_table = true; std::unique_ptr<storage::DataTable> table(storage::TableFactory::GetDataTable( INVALID_OID, INVALID_OID, table_schema, table_name, tuples_per_tilegroup_count, own_schema, adapt_table)); // PRIMARY INDEX if (indexes == true) { std::vector<oid_t> key_attrs; auto tuple_schema = table->GetSchema(); catalog::Schema *key_schema; index::IndexMetadata *index_metadata; bool unique; key_attrs = {0}; key_schema = catalog::Schema::CopySchema(tuple_schema, key_attrs); key_schema->SetIndexedColumns(key_attrs); unique = true; index_metadata = new index::IndexMetadata( "primary_index", 123, INDEX_TYPE_BTREE, INDEX_CONSTRAINT_TYPE_PRIMARY_KEY, tuple_schema, key_schema, unique); index::Index *pkey_index = index::IndexFactory::GetInstance(index_metadata); table->AddIndex(pkey_index); } ///////////////////////////////////////////////////////// // Load in the data ///////////////////////////////////////////////////////// // Insert tuples into tile_group. auto &txn_manager = concurrency::TransactionManager::GetInstance(); const bool allocate = true; auto txn = txn_manager.BeginTransaction(); for (int rowid = 0; rowid < tuple_count; rowid++) { int populate_value = rowid; storage::Tuple tuple(table_schema, allocate); for(oid_t col_itr = 0 ; col_itr <= col_count; col_itr++) { auto value = ValueFactory::GetIntegerValue(populate_value + col_itr); tuple.SetValue(col_itr, value); } ItemPointer tuple_slot_id = table->InsertTuple(txn, &tuple); EXPECT_TRUE(tuple_slot_id.block != INVALID_OID); EXPECT_TRUE(tuple_slot_id.offset != INVALID_OID); txn->RecordInsert(tuple_slot_id); } txn_manager.CommitTransaction(txn); ///////////////////////////////////////////////////////// // Do a seq scan with predicate on top of the table ///////////////////////////////////////////////////////// start = std::chrono::system_clock::now(); txn = txn_manager.BeginTransaction(); std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); // Column ids to be added to logical tile after scan. //std::vector<oid_t> column_ids; //for(oid_t col_itr = 0 ; col_itr <= 200; col_itr++) { // column_ids.push_back(col_itr); //} std::vector<oid_t> column_ids({198, 206}); // Create and set up seq scan executor planner::SeqScanPlan seq_scan_node(table.get(), nullptr, column_ids); int expected_num_tiles = tile_group_count; executor::SeqScanExecutor seq_scan_executor(&seq_scan_node, context.get()); // Create and set up materialization executor std::vector<catalog::Column> output_columns; std::unordered_map<oid_t, oid_t> old_to_new_cols; oid_t col_itr = 0; for(auto column_id : column_ids) { auto column = catalog::Column(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER), "FIELD" + std::to_string(column_id), is_inlined); output_columns.push_back(column); old_to_new_cols[col_itr] = col_itr; col_itr++; } std::unique_ptr<catalog::Schema> output_schema( new catalog::Schema(output_columns)); bool physify_flag = true; // is going to create a physical tile planner::MaterializationPlan mat_node(old_to_new_cols, output_schema.release(), physify_flag); executor::MaterializationExecutor mat_executor(&mat_node, nullptr); mat_executor.AddChild(&seq_scan_executor); EXPECT_TRUE(mat_executor.Init()); std::vector<std::unique_ptr<executor::LogicalTile>> result_tiles; for (int i = 0; i < expected_num_tiles; i++) { EXPECT_TRUE(mat_executor.Execute()); std::unique_ptr<executor::LogicalTile> result_tile(mat_executor.GetOutput()); EXPECT_THAT(result_tile, NotNull()); result_tiles.emplace_back(result_tile.release()); } EXPECT_FALSE(mat_executor.Execute()); txn_manager.CommitTransaction(txn); end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end-start; std::cout << "duration :: " << elapsed_seconds.count() << "s\n"; } TEST(TileGroupLayoutTest, RowLayout) { peloton_layout = LAYOUT_ROW; RunTest(); } TEST(TileGroupLayoutTest, ColumnLayout) { peloton_layout = LAYOUT_COLUMN; RunTest(); } TEST(TileGroupLayoutTest, HybridLayout) { peloton_layout = LAYOUT_HYBRID; RunTest(); } } // namespace test } // namespace peloton
//===----------------------------------------------------------------------===// // // PelotonDB // // materialization_test.cpp // // Identification: tests/executor/materialization_test.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <memory> #include <string> #include <unordered_map> #include <vector> #include <chrono> #include <iostream> #include <ctime> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "backend/planner/abstract_plan.h" #include "backend/planner/materialization_plan.h" #include "backend/planner/seq_scan_plan.h" #include "backend/catalog/manager.h" #include "backend/catalog/schema.h" #include "backend/common/types.h" #include "backend/common/value.h" #include "backend/common/value_factory.h" #include "backend/executor/logical_tile.h" #include "backend/executor/logical_tile_factory.h" #include "backend/executor/materialization_executor.h" #include "backend/storage/backend_vm.h" #include "backend/storage/tile.h" #include "backend/storage/tile_group.h" #include "backend/storage/data_table.h" #include "backend/concurrency/transaction.h" #include "backend/executor/abstract_executor.h" #include "backend/executor/seq_scan_executor.h" #include "backend/expression/abstract_expression.h" #include "backend/expression/expression_util.h" #include "backend/storage/table_factory.h" #include "backend/index/index_factory.h" #include "executor/executor_tests_util.h" #include "executor/mock_executor.h" using ::testing::NotNull; namespace peloton { namespace test { //===--------------------------------------------------------------------===// // Tile Group Layout Tests //===--------------------------------------------------------------------===// void RunTest() { std::chrono::time_point<std::chrono::system_clock> start, end; const int tuples_per_tilegroup_count = 10; const int tile_group_count = 5; const int tuple_count = tuples_per_tilegroup_count * tile_group_count; const oid_t col_count = 250; const bool is_inlined = true; const bool indexes = false; std::vector<catalog::Column> columns; for(oid_t col_itr = 0 ; col_itr <= col_count; col_itr++) { auto column = catalog::Column(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER), "FIELD" + std::to_string(col_itr), is_inlined); columns.push_back(column); } catalog::Schema *table_schema = new catalog::Schema(columns); std::string table_name("TEST_TABLE"); ///////////////////////////////////////////////////////// // Create table. ///////////////////////////////////////////////////////// bool own_schema = true; bool adapt_table = true; std::unique_ptr<storage::DataTable> table(storage::TableFactory::GetDataTable( INVALID_OID, INVALID_OID, table_schema, table_name, tuples_per_tilegroup_count, own_schema, adapt_table)); // PRIMARY INDEX if (indexes == true) { std::vector<oid_t> key_attrs; auto tuple_schema = table->GetSchema(); catalog::Schema *key_schema; index::IndexMetadata *index_metadata; bool unique; key_attrs = {0}; key_schema = catalog::Schema::CopySchema(tuple_schema, key_attrs); key_schema->SetIndexedColumns(key_attrs); unique = true; index_metadata = new index::IndexMetadata( "primary_index", 123, INDEX_TYPE_BTREE, INDEX_CONSTRAINT_TYPE_PRIMARY_KEY, tuple_schema, key_schema, unique); index::Index *pkey_index = index::IndexFactory::GetInstance(index_metadata); table->AddIndex(pkey_index); } ///////////////////////////////////////////////////////// // Load in the data ///////////////////////////////////////////////////////// // Insert tuples into tile_group. auto &txn_manager = concurrency::TransactionManager::GetInstance(); const bool allocate = true; auto txn = txn_manager.BeginTransaction(); for (int rowid = 0; rowid < tuple_count; rowid++) { int populate_value = rowid; storage::Tuple tuple(table_schema, allocate); for(oid_t col_itr = 0 ; col_itr <= col_count; col_itr++) { auto value = ValueFactory::GetIntegerValue(populate_value + col_itr); tuple.SetValue(col_itr, value); } ItemPointer tuple_slot_id = table->InsertTuple(txn, &tuple); EXPECT_TRUE(tuple_slot_id.block != INVALID_OID); EXPECT_TRUE(tuple_slot_id.offset != INVALID_OID); txn->RecordInsert(tuple_slot_id); } txn_manager.CommitTransaction(txn); ///////////////////////////////////////////////////////// // Do a seq scan with predicate on top of the table ///////////////////////////////////////////////////////// start = std::chrono::system_clock::now(); txn = txn_manager.BeginTransaction(); std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); // Column ids to be added to logical tile after scan. //std::vector<oid_t> column_ids; //for(oid_t col_itr = 0 ; col_itr <= 200; col_itr++) { // column_ids.push_back(col_itr); //} std::vector<oid_t> column_ids({198, 206}); // Create and set up seq scan executor planner::SeqScanPlan seq_scan_node(table.get(), nullptr, column_ids); int expected_num_tiles = tile_group_count; executor::SeqScanExecutor seq_scan_executor(&seq_scan_node, context.get()); // Create and set up materialization executor std::vector<catalog::Column> output_columns; std::unordered_map<oid_t, oid_t> old_to_new_cols; oid_t col_itr = 0; for(auto column_id : column_ids) { auto column = catalog::Column(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER), "FIELD" + std::to_string(column_id), is_inlined); output_columns.push_back(column); old_to_new_cols[col_itr] = col_itr; col_itr++; } std::unique_ptr<catalog::Schema> output_schema( new catalog::Schema(output_columns)); bool physify_flag = true; // is going to create a physical tile planner::MaterializationPlan mat_node(old_to_new_cols, output_schema.release(), physify_flag); executor::MaterializationExecutor mat_executor(&mat_node, nullptr); mat_executor.AddChild(&seq_scan_executor); EXPECT_TRUE(mat_executor.Init()); std::vector<std::unique_ptr<executor::LogicalTile>> result_tiles; for (int i = 0; i < expected_num_tiles; i++) { EXPECT_TRUE(mat_executor.Execute()); std::unique_ptr<executor::LogicalTile> result_tile(mat_executor.GetOutput()); EXPECT_THAT(result_tile, NotNull()); result_tiles.emplace_back(result_tile.release()); } EXPECT_FALSE(mat_executor.Execute()); txn_manager.CommitTransaction(txn); end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end-start; std::cout << "duration :: " << elapsed_seconds.count() << "s\n"; } TEST(TileGroupLayoutTest, RowLayout) { peloton_layout = LAYOUT_ROW; RunTest(); } TEST(TileGroupLayoutTest, ColumnLayout) { peloton_layout = LAYOUT_COLUMN; RunTest(); } } // namespace test } // namespace peloton
Fix tile group layout test
Fix tile group layout test Former-commit-id: 3ed3a831bf72305d8bebb281a1343d81378f9b43
C++
apache-2.0
amaliujia/CMUDB-peloton,larryxiao/peloton,larryxiao/peloton,larryxiao/peloton-1,larryxiao/peloton-1,omegaga/peloton,amaliujia/CMUDB-peloton,amaliujia/CMUDB-peloton,larryxiao/peloton,larryxiao/peloton,ranxian/peloton,ranxian/peloton,omegaga/peloton,amaliujia/CMUDB-peloton,omegaga/peloton,larryxiao/peloton-1,omegaga/peloton,larryxiao/peloton-1,larryxiao/peloton-1,larryxiao/peloton-1,amaliujia/CMUDB-peloton,larryxiao/peloton,amaliujia/CMUDB-peloton,ranxian/peloton,larryxiao/peloton-1,ranxian/peloton,omegaga/peloton,omegaga/peloton,ranxian/peloton,omegaga/peloton,ranxian/peloton,amaliujia/CMUDB-peloton,larryxiao/peloton,larryxiao/peloton
c92396049efffe46dd5d48de34fde60d8c47b5ee
src/classes/Field.cxx
src/classes/Field.cxx
// Field // Author: Matthew Raso-Barnett 30/09/2009 #include "Field.h" #include "FieldVertex.h" //______________________________________________________________________________ // Field - ABC for magnetic field. // //______________________________________________________________________________ ClassImp(Field) //_____________________________________________________________________________ Field::Field() :TNamed(), fFieldShape(NULL), fFieldMatrix(NULL) { // Default constructor. Info("Field", "Default Constructor"); } //_____________________________________________________________________________ Field::Field(const std::string& name, const TGeoShape* shape, const TGeoMatrix* matrix) :TNamed(name, ""), fFieldShape(shape), fFieldMatrix(matrix) { // Default constructor. Info("Field", "Constructor"); } //_____________________________________________________________________________ Field::Field(const Field& other) :TNamed(other), fFieldShape(other.fFieldShape), fFieldMatrix(other.fFieldMatrix) { // Copy constructor. } //______________________________________________________________________________ Field::~Field() { // Destructor. Info("Field", "Destructor"); if(fFieldShape) delete fFieldShape; if(fFieldMatrix) delete fFieldMatrix; } //______________________________________________________________________________ Bool_t Field::Contains(const TVector3& point) const { // -- Check whether supplied point is contained by Field-shape // First convert point to local coordinates Double_t masterPoint[3] = {point[0], point[1], point[2]}; Double_t localPoint[3] = {0.,0.,0.}; fFieldMatrix->MasterToLocal(masterPoint, localPoint); // Check and return whether its contained return fFieldShape->Contains(localPoint); } //______________________________________________________________________________ FieldVertex Field::ConvertToGlobalFrame(const FieldVertex& point) const { // -- Convert supplied point to global frame FieldVertex globalPoint; Double_t localPoint[3] = {point.X(), point.Y(), point.Z()}; Double_t masterPoint[3] = {0.,0.,0.}; Double_t localField[3] = {point.Bx(), point.By(), point.Bz()}; Double_t masterField[3] = {0.,0.,0.}; fFieldMatrix->LocalToMaster(localPoint, masterPoint); fFieldMatrix->LocalToMaster(localField, masterField); globalPoint.SetPosition(masterPoint[0],masterPoint[1],masterPoint[2]); globalPoint.SetField(masterField[0],masterField[1],masterField[2]); return globalPoint; } //______________________________________________________________________________ FieldVertex Field::ConvertToLocalFrame(const FieldVertex& point) const { // -- Convert supplied point to local, Field's frame FieldVertex globalPoint; Double_t localPoint[3] = {0.,0.,0.}; Double_t masterPoint[3] = {point.X(), point.Y(), point.Z()}; Double_t localField[3] = {0.,0.,0.}; Double_t masterField[3] = {point.Bx(), point.By(), point.Bz()}; fFieldMatrix->MasterToLocal(masterPoint, localPoint); fFieldMatrix->MasterToLocal(masterField, localField); globalPoint.SetPosition(localPoint[0],localPoint[1],localPoint[2]); globalPoint.SetField(localField[0],localField[1],localField[2]); return globalPoint; }
// Field // Author: Matthew Raso-Barnett 30/09/2009 #include "Field.h" #include "FieldVertex.h" //______________________________________________________________________________ // Field - ABC for magnetic field. // //______________________________________________________________________________ ClassImp(Field) //_____________________________________________________________________________ Field::Field() :TNamed(), fFieldShape(NULL), fFieldMatrix(NULL) { // Default constructor. Info("Field", "Default Constructor"); } //_____________________________________________________________________________ Field::Field(const std::string& name, const TGeoShape* shape, const TGeoMatrix* matrix) :TNamed(name, ""), fFieldShape(shape), fFieldMatrix(matrix) { // Default constructor. Info("Field", "Constructor"); } //_____________________________________________________________________________ Field::Field(const Field& other) :TNamed(other), fFieldShape(other.fFieldShape), fFieldMatrix(other.fFieldMatrix) { // Copy constructor. } //______________________________________________________________________________ Field::~Field() { // Destructor. Info("Field", "Destructor"); if(fFieldShape) {delete fFieldShape; fFieldShape = NULL;} if(fFieldMatrix) {delete fFieldMatrix; fFieldMatrix = NULL;} } //______________________________________________________________________________ Bool_t Field::Contains(const TVector3& point) const { // -- Check whether supplied point is contained by Field-shape // First convert point to local coordinates Double_t masterPoint[3] = {point[0], point[1], point[2]}; Double_t localPoint[3] = {0.,0.,0.}; fFieldMatrix->MasterToLocal(masterPoint, localPoint); // Check and return whether its contained return fFieldShape->Contains(localPoint); } //______________________________________________________________________________ FieldVertex Field::ConvertToGlobalFrame(const FieldVertex& point) const { // -- Convert supplied point to global frame FieldVertex globalPoint; Double_t localPoint[3] = {point.X(), point.Y(), point.Z()}; Double_t masterPoint[3] = {0.,0.,0.}; Double_t localField[3] = {point.Bx(), point.By(), point.Bz()}; Double_t masterField[3] = {0.,0.,0.}; fFieldMatrix->LocalToMaster(localPoint, masterPoint); fFieldMatrix->LocalToMaster(localField, masterField); globalPoint.SetPosition(masterPoint[0],masterPoint[1],masterPoint[2]); globalPoint.SetField(masterField[0],masterField[1],masterField[2]); return globalPoint; } //______________________________________________________________________________ FieldVertex Field::ConvertToLocalFrame(const FieldVertex& point) const { // -- Convert supplied point to local, Field's frame FieldVertex globalPoint; Double_t localPoint[3] = {0.,0.,0.}; Double_t masterPoint[3] = {point.X(), point.Y(), point.Z()}; Double_t localField[3] = {0.,0.,0.}; Double_t masterField[3] = {point.Bx(), point.By(), point.Bz()}; fFieldMatrix->MasterToLocal(masterPoint, localPoint); fFieldMatrix->MasterToLocal(masterField, localField); globalPoint.SetPosition(localPoint[0],localPoint[1],localPoint[2]); globalPoint.SetField(localField[0],localField[1],localField[2]); return globalPoint; }
Set Field Shape pointers to NULL after delete
Set Field Shape pointers to NULL after delete
C++
mit
mjrasobarnett/ucnsim,mjrasobarnett/ucnsim,mjrasobarnett/ucnsim
196f626cc2a978956f2463907a2721a751e05e64
dfdm/src/densification.cpp
dfdm/src/densification.cpp
/* -------------------------------------------------------------------------------- DESCRIPTION simple firn model with overburden compaction and heat diffusion DATE 15-JAN-2016 AUTHOR [email protected] -------------------------------------------------------------------------------- */ #include <cstdlib> #include <iostream> #include <ctime> #include "logging.h" #include "settings.h" #include "iniparser.h" #include "idealizedcoresite.h" #include "netcdfcoresite.h" namespace Densification{ std::ofstream logger; } using namespace Densification; void readSettingsFromIniFile(char ininame[], Settings& s){ dictionary* d = iniparser_load(ininame); s.heat = iniparser_getboolean(d, "general:heat", -1); const char * tmp = iniparser_getstring(d, "general:compaction", "NOT_SPECIFIED"); if (std::string(tmp) == "overburden"){ s.dm = DensificationMethod::Overburden; } else { s.dm = DensificationMethod::Ar10T; } s.eta0 = iniparser_getdouble(d, "overburden:eta0", -1.0); s.c5 = iniparser_getdouble(d, "overburden:c5", -1.0); s.c6 = iniparser_getdouble(d, "overburden:c6", -1.0); s.forcing_dt = iniparser_getint(d, "forcing:dt", -1); tmp = iniparser_getstring(d, "forcing:f_acc", "NOT_SPECIFIED"); s.f_acc = std::string(tmp); tmp = iniparser_getstring(d, "forcing:f_wind10m", "NOT_SPECIFIED"); s.f_wind10m = std::string(tmp); tmp = iniparser_getstring(d, "forcing:f_tskin", "NOT_SPECIFIED"); s.f_tskin = std::string(tmp); logger << "INFO: general:compaction = " << tmp << std::endl; logger << "INFO: general:heat = " << s.heat << std::endl; logger << "INFO: overburden:eta0 = " << s.eta0 << std::endl; logger << "INFO: overburden:c5 = " << s.c5 << std::endl; logger << "INFO: overburden:c6 = " << s.c6 << std::endl; logger << "INFO: forcing:dt = " << s.forcing_dt << std::endl; logger << "INFO: forcing:f_acc = " << s.f_acc << std::endl; logger << "INFO: forcing:f_w10m = " << s.f_wind10m << std::endl; logger << "INFO: forcing:f_tskin = " << s.f_tskin << std::endl; iniparser_freedict(d); } int main(){ logger.open("densification.log"); char ininame[] = "settings.ini"; Settings settings; readSettingsFromIniFile(ininame, settings); //IdealizedCoreSite core(settings); NetcdfCoreSite core(settings); core.init(); /* Time loop */ long sec_in_3h = 3*3600; long dt = sec_in_3h; // timestep of 3 hours in seconds long dt_per_year = sec_in_year/dt; long nyears = 3; // simulation duration in years logger << "INFO: dt=" << dt << std::endl; logger << "INFO: nyears=" << nyears << std::endl; logger << "INFO: dt_per_year=" << dt_per_year << std::endl; logger << "INFO: starting simulation of " << core.toString() << std::endl; std::clock_t start; for (int year = 0; year < nyears; year++){ start = clock(); for(int tstep = 0; tstep < dt_per_year; tstep++) core.runTimeStep(dt); double elapsed = ((double)(clock() - start)) / CLOCKS_PER_SEC; logger << "year=" << year << ", Tmin=" << core.minTemp() << ", Tmax=" << core.maxTemp() << ", rho_max=" << core.maxDens() << ", sec/year=" << elapsed << ", year/hour=" << 3600./elapsed << std::endl; } core.printIceCoreSummary(); core.writeFiles(); logger.close(); }
/* -------------------------------------------------------------------------------- DESCRIPTION simple firn model with overburden compaction and heat diffusion DATE 15-JAN-2016 AUTHOR [email protected] -------------------------------------------------------------------------------- */ #include <cstdlib> #include <iostream> #include <ctime> #include "logging.h" #include "settings.h" #include "iniparser.h" #include "idealizedcoresite.h" #include "netcdfcoresite.h" namespace Densification{ std::ofstream logger; } using namespace Densification; void readSettingsFromIniFile(char ininame[], Settings& s){ dictionary* d = iniparser_load(ininame); s.heat = iniparser_getboolean(d, "general:heat", -1); const char * tmp = iniparser_getstring(d, "general:compaction", "NOT_SPECIFIED"); if (std::string(tmp) == "overburden"){ s.dm = DensificationMethod::Overburden; } else { s.dm = DensificationMethod::Ar10T; } s.eta0 = iniparser_getdouble(d, "overburden:eta0", -1.0); s.c5 = iniparser_getdouble(d, "overburden:c5", -1.0); s.c6 = iniparser_getdouble(d, "overburden:c6", -1.0); s.forcing_dt = iniparser_getint(d, "forcing:dt", -1); tmp = iniparser_getstring(d, "forcing:f_acc", "NOT_SPECIFIED"); s.f_acc = std::string(tmp); tmp = iniparser_getstring(d, "forcing:f_wind10m", "NOT_SPECIFIED"); s.f_wind10m = std::string(tmp); tmp = iniparser_getstring(d, "forcing:f_tskin", "NOT_SPECIFIED"); s.f_tskin = std::string(tmp); logger << "INFO: general:compaction = " << tmp << std::endl; logger << "INFO: general:heat = " << s.heat << std::endl; logger << "INFO: overburden:eta0 = " << s.eta0 << std::endl; logger << "INFO: overburden:c5 = " << s.c5 << std::endl; logger << "INFO: overburden:c6 = " << s.c6 << std::endl; logger << "INFO: forcing:dt = " << s.forcing_dt << std::endl; logger << "INFO: forcing:f_acc = " << s.f_acc << std::endl; logger << "INFO: forcing:f_w10m = " << s.f_wind10m << std::endl; logger << "INFO: forcing:f_tskin = " << s.f_tskin << std::endl; iniparser_freedict(d); } int main(){ logger.open("densification.log"); logger.precision(16); char ininame[] = "settings.ini"; Settings settings; readSettingsFromIniFile(ininame, settings); //IdealizedCoreSite core(settings); NetcdfCoreSite core(settings); core.init(); /* Time loop */ long sec_in_3h = 3*3600; long dt = sec_in_3h; // timestep of 3 hours in seconds long dt_per_year = sec_in_year/dt; //long nyears = 3; // simulation duration in years int maxYear = 500; logger << "INFO: dt=" << dt << std::endl; // logger << "INFO: nyears=" << nyears << std::endl; logger << "INFO: dt_per_year=" << dt_per_year << std::endl; logger << "INFO: starting simulation of " << core.toString() << std::endl; std::clock_t start; int kYear = 0; while(! core.hasReachedDensity(850.) && kYear < maxYear) { // for (int year = 0; year < nyears; year++){ start = clock(); for(int tstep = 0; tstep < dt_per_year; tstep++) core.runTimeStep(dt); double elapsed = ((double)(clock() - start)) / CLOCKS_PER_SEC; logger << "year=" << kYear << ", Tmin=" << core.minTemp() << ", Tmax=" << core.maxTemp() << ", rho_max=" << core.maxDens() << ", sec/year=" << elapsed << ", year/hour=" << 3600./elapsed << std::endl; kYear++; } core.printIceCoreSummary(); core.writeFiles(); logger.close(); }
stop simulation when some target density is reached
stop simulation when some target density is reached
C++
mit
kampe004/compaction,kampe004/compaction,kampe004/compaction
25ca1eb603500dc9a62cf20c30103e5b7995bca6
src/client/opengl.hpp
src/client/opengl.hpp
#ifndef CLIENT_OPENGL_HPP #define CLIENT_OPENGL_HPP #if defined(__APPLE__) /* Mac OS X */ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #else /* GNU/Linux */ #include <GL/gl.h> #include <GL/glu.h> #endif #endif
#ifndef CLIENT_OPENGL_HPP #define CLIENT_OPENGL_HPP #if defined(__APPLE__) /* Mac OS X */ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #else #if defined(_WIN32) #include <WTypes.h> #include <wingdi.h> #endif /* GNU/Linux */ #include <GL/gl.h> #include <GL/glu.h> #endif #endif
Fix OpenGL header on Windows
Fix OpenGL header on Windows
C++
bsd-2-clause
depp/sglib,depp/sglib
d297b285889e949ab763184a56f6d42dcd24728f
src/clientversion.cpp
src/clientversion.cpp
// Copyright (c) 2012-2020 The Bitcoin Core developers // Copyright (c) 2021 The Gridcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <clientversion.h> #include <tinyformat.h> /** * Name of client reported in the 'version' message. Report the same name * for both gridcoinresearchd and gridcoinresearch-qt, to make it harder for attackers to * target servers or GUI users specifically. */ const std::string CLIENT_NAME("Halford"); #ifdef HAVE_BUILD_INFO #include "obj/build.h" // The <obj/build.h>, which is generated by the build environment (share/genbuild.sh), // could contain only one line of the following: // - "#define BUILD_GIT_TAG ...", if the top commit is tagged // - "#define BUILD_GIT_COMMIT ...", if the top commit is not tagged // - "// No build information available", if proper git information is not available #endif //! git will put "#define GIT_COMMIT_ID ..." on the next line inside archives. $Format:%n#define GIT_COMMIT_ID "%H"$ #ifdef BUILD_GIT_TAG #define BUILD_DESC BUILD_GIT_TAG #define BUILD_SUFFIX "" #else #define BUILD_DESC_FROM_PACKAGE(package, build) "v" package "." DO_STRINGIZE(build) #define BUILD_DESC BUILD_DESC_FROM_PACKAGE(PACKAGE_VERSION, CLIENT_VERSION_BUILD) #if CLIENT_VERSION_IS_RELEASE #define BUILD_SUFFIX "" #elif defined(BUILD_GIT_COMMIT) #define BUILD_SUFFIX "-" BUILD_GIT_COMMIT #elif defined(GIT_COMMIT_ID) #define BUILD_SUFFIX "-g" GIT_COMMIT_ID #else #define BUILD_SUFFIX "-unk" #endif #endif static std::string FormatVersion(int nVersion) { return strprintf("%d.%d.%d", nVersion / 10000, (nVersion / 100) % 100, nVersion % 100); } std::string FormatFullVersion() { static const std::string CLIENT_BUILD(BUILD_DESC BUILD_SUFFIX); return CLIENT_BUILD; } /** * Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki) */ std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments) { std::ostringstream ss; ss << "/"; ss << name << ":" << FormatVersion(nClientVersion); if (!comments.empty()) { std::vector<std::string>::const_iterator it(comments.begin()); ss << "(" << *it; for(++it; it != comments.end(); ++it) ss << "; " << *it; ss << ")"; } ss << "/"; return ss.str(); }
// Copyright (c) 2012-2020 The Bitcoin Core developers // Copyright (c) 2021 The Gridcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <clientversion.h> #include <tinyformat.h> /** * Name of client reported in the 'version' message. Report the same name * for both gridcoinresearchd and gridcoinresearch-qt, to make it harder for attackers to * target servers or GUI users specifically. */ const std::string CLIENT_NAME("Halford"); #ifdef HAVE_BUILD_INFO #include "obj/build.h" // The <obj/build.h>, which is generated by the build environment (share/genbuild.sh), // could contain only one line of the following: // - "#define BUILD_GIT_TAG ...", if the top commit is tagged // - "#define BUILD_GIT_COMMIT ...", if the top commit is not tagged // - "// No build information available", if proper git information is not available #endif //! git will put "#define GIT_COMMIT_ID ..." on the next line inside archives. $Format:%n#define GIT_COMMIT_ID "%H"$ #ifdef BUILD_GIT_TAG #define BUILD_DESC BUILD_GIT_TAG #define BUILD_SUFFIX "" #else #define BUILD_DESC_FROM_PACKAGE(package, build) "v" package "." DO_STRINGIZE(build) #define BUILD_DESC BUILD_DESC_FROM_PACKAGE(PACKAGE_VERSION, CLIENT_VERSION_BUILD) #if CLIENT_VERSION_IS_RELEASE #define BUILD_SUFFIX "" #elif defined(BUILD_GIT_COMMIT) #define BUILD_SUFFIX "-" BUILD_GIT_COMMIT #elif defined(GIT_COMMIT_ID) #define BUILD_SUFFIX "-g" GIT_COMMIT_ID #else #define BUILD_SUFFIX "-unk" #endif #endif static std::string FormatVersion(int nVersion) { if (nVersion % 100 == 0) { return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100); } return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100); } std::string FormatFullVersion() { static const std::string CLIENT_BUILD(BUILD_DESC BUILD_SUFFIX); return CLIENT_BUILD; } /** * Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki) */ std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments) { std::ostringstream ss; ss << "/"; ss << name << ":" << FormatVersion(nClientVersion); if (!comments.empty()) { std::vector<std::string>::const_iterator it(comments.begin()); ss << "(" << *it; for(++it; it != comments.end(); ++it) ss << "; " << *it; ss << ")"; } ss << "/"; return ss.str(); }
fix FormatVersion
util: fix FormatVersion `FormatVersion` function was broken in a5de7c91c641151c74ed523edd86aeaf197ccebb which results in user agent strings to be formatted weirdly and may result in alerts falsely being ignored.
C++
mit
caraka/gridcoinresearch,caraka/gridcoinresearch,caraka/gridcoinresearch,caraka/gridcoinresearch,caraka/gridcoinresearch,caraka/gridcoinresearch
f4fc71e2f3b134fa259c86673c14c9760a41581a
src/cm-jqcolumnize.cc
src/cm-jqcolumnize.cc
/** * Copyright (c) 2015 - The CM Authors <[email protected]> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <algorithm> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "fnord-base/io/fileutil.h" #include "fnord-base/application.h" #include "fnord-base/logging.h" #include "fnord-base/cli/flagparser.h" #include "fnord-base/util/SimpleRateLimit.h" #include "fnord-base/InternMap.h" #include "fnord-json/json.h" #include "fnord-mdb/MDB.h" #include "fnord-mdb/MDBUtil.h" #include "fnord-sstable/sstablereader.h" #include "fnord-sstable/sstablewriter.h" #include "fnord-sstable/SSTableColumnSchema.h" #include "fnord-sstable/SSTableColumnReader.h" #include "fnord-sstable/SSTableColumnWriter.h" #include "fnord-cstable/BitPackedIntColumnReader.h" #include "fnord-cstable/BitPackedIntColumnWriter.h" #include "fnord-cstable/UInt32ColumnReader.h" #include "fnord-cstable/UInt32ColumnWriter.h" #include "fnord-cstable/BooleanColumnReader.h" #include "fnord-cstable/BooleanColumnWriter.h" #include "fnord-cstable/CSTableWriter.h" #include "fnord-cstable/CSTableReader.h" #include "common.h" #include "CustomerNamespace.h" #include "FeatureSchema.h" #include "JoinedQuery.h" #include "CTRCounter.h" #include "analytics/AnalyticsTableScan.h" #include "analytics/CTRByPositionQuery.h" using namespace cm; using namespace fnord; int main(int argc, const char** argv) { fnord::Application::init(); fnord::Application::logToStderr(); fnord::cli::FlagParser flags; flags.defineFlag( "input_file", fnord::cli::FlagParser::T_STRING, true, "i", NULL, "file", "<filename>"); flags.defineFlag( "output_file", fnord::cli::FlagParser::T_STRING, true, "o", NULL, "file", "<filename>"); flags.defineFlag( "loglevel", fnord::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); size_t debug_n = 0; size_t debug_z = 0; /* query level */ cstable::UInt32ColumnWriter jq_time_col(1, 1); cstable::BitPackedIntColumnWriter jq_page_col(1, 1, 100); cstable::BitPackedIntColumnWriter jq_lang_col(1, 1, kMaxLanguage); cstable::BitPackedIntColumnWriter jq_numitems_col(1, 1, 250); cstable::BitPackedIntColumnWriter jq_numitemclicks_col(1, 1, 250); cstable::BitPackedIntColumnWriter jq_numadimprs_col(1, 1, 250); cstable::BitPackedIntColumnWriter jq_numadclicks_col(1, 1, 250); cstable::BitPackedIntColumnWriter jq_abtestgroup_col(1, 1, 100); cstable::BitPackedIntColumnWriter jq_devicetype_col(1, 1, kMaxDeviceType); cstable::BitPackedIntColumnWriter jq_pagetype_col(1, 1, kMaxPageType); cstable::BitPackedIntColumnWriter jq_cat1_col(1, 1, 0xffff); cstable::BitPackedIntColumnWriter jq_cat2_col(1, 1, 0xffff); cstable::BitPackedIntColumnWriter jq_cat3_col(1, 1, 0xffff); /* query item level */ cstable::BitPackedIntColumnWriter jqi_position_col(2, 2, 64); cstable::BooleanColumnWriter jqi_clicked_col(2, 2); uint64_t r = 0; uint64_t n = 0; auto add_session = [&] (cm::JoinedSession& sess) { ++n; for (auto& q : sess.queries) { /* queries.time */ jq_time_col.addDatum(r, 1, q.time.unixMicros() / kMicrosPerSecond); /* queries.language */ auto lang = cm::extractLanguage(q.attrs); uint32_t l = (uint16_t) lang; jq_lang_col.addDatum(r, 1, l); /* queries.num_item_clicks, queries.num_items */ size_t nitems = 0; size_t nclicks = 0; size_t nads = 0; size_t nadclicks = 0; for (auto& i : q.items) { // DAWANDA HACK if (i.position >= 1 && i.position <= 4) { if (lang != Language::DE) { i.position = 0; continue; } ++nads; nadclicks += i.clicked; } // EOF DAWANDA HACK ++nitems; nclicks += i.clicked; } if (nadclicks > 0 && lang != Language::DE) { abort(); } jq_numitems_col.addDatum(r, 1, nitems); jq_numitemclicks_col.addDatum(r, 1, nclicks); jq_numadimprs_col.addDatum(r, 1, nads); jq_numadclicks_col.addDatum(r, 1, nadclicks); /* queries.page */ auto pg_str = cm::extractAttr(q.attrs, "pg"); if (pg_str.isEmpty()) { jq_page_col.addNull(r, 1); } else { jq_page_col.addDatum(r, 1, std::stoul(pg_str.get())); } /* queries.ab_test_group */ auto abgrp = cm::extractABTestGroup(q.attrs); if (abgrp.isEmpty()) { jq_abtestgroup_col.addNull(r, 1); } else { jq_abtestgroup_col.addDatum(r, 1, abgrp.get()); } /* queries.category1 */ auto qcat1 = cm::extractAttr(q.attrs, "q_cat1"); if (qcat1.isEmpty()) { jq_cat1_col.addNull(r, 1); } else { jq_cat1_col.addDatum(r, 1, std::stoul(qcat1.get())); } /* queries.category2 */ auto qcat2 = cm::extractAttr(q.attrs, "q_cat2"); if (qcat2.isEmpty()) { jq_cat2_col.addNull(r, 1); } else { jq_cat2_col.addDatum(r, 1, std::stoul(qcat2.get())); } /* queries.category3 */ auto qcat3 = cm::extractAttr(q.attrs, "q_cat3"); if (qcat3.isEmpty()) { jq_cat3_col.addNull(r, 1); } else { jq_cat3_col.addDatum(r, 1, std::stoul(qcat3.get())); } /* queries.device_type */ jq_devicetype_col.addDatum(r, 1, (uint32_t) extractDeviceType(q.attrs)); /* queries.page_type */ jq_pagetype_col.addDatum(r, 1, (uint32_t) extractPageType(q.attrs)); if (q.items.size() == 0) { jqi_position_col.addNull(r, 1); jqi_clicked_col.addNull(r, 1); } for (const auto& i : q.items) { jqi_position_col.addDatum(r, 2, i.position); jqi_clicked_col.addDatum(r, 2, i.clicked); r = 2; } r = 1; } r = 0; }; /* read input tables */ int row_idx = 0; const auto& sstable = flags.getString("input_file"); fnord::logInfo("cm.jqcolumnize", "Importing sstable: $0", sstable); /* read sstable header */ sstable::SSTableReader reader(File::openFile(sstable, File::O_READ)); if (reader.bodySize() == 0) { fnord::logCritical("cm.jqcolumnize", "unfinished sstable: $0", sstable); exit(1); } /* get sstable cursor */ auto cursor = reader.getCursor(); auto body_size = reader.bodySize(); /* status line */ util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () { fnord::logInfo( "cm.jqcolumnize", "[$0%] Reading sstable... rows=$1", (size_t) ((cursor->position() / (double) body_size) * 100), row_idx); }); /* read sstable rows */ for (; cursor->valid(); ++row_idx) { status_line.runMaybe(); auto key = cursor->getKeyString(); auto val = cursor->getDataBuffer(); Option<cm::JoinedQuery> q; try { q = Some(json::fromJSON<cm::JoinedQuery>(val)); } catch (const Exception& e) { fnord::logWarning("cm.jqcolumnize", e, "invalid json: $0", val.toString()); } if (!q.isEmpty()) { cm::JoinedSession s; s.queries.emplace_back(q.get()); add_session(s); } if (!cursor->next()) { break; } } status_line.runForce(); { cstable::CSTableWriter writer(flags.getString("output_file") + "~", n); writer.addColumn("queries.time", &jq_time_col); writer.addColumn("queries.page", &jq_page_col); writer.addColumn("queries.language", &jq_lang_col); writer.addColumn("queries.num_items", &jq_numitems_col); writer.addColumn("queries.num_items_clicked", &jq_numitemclicks_col); writer.addColumn("queries.num_ad_impressions", &jq_numadimprs_col); writer.addColumn("queries.num_ad_clicks", &jq_numadclicks_col); writer.addColumn("queries.ab_test_group", &jq_abtestgroup_col); writer.addColumn("queries.device_type", &jq_devicetype_col); writer.addColumn("queries.page_type", &jq_pagetype_col); writer.addColumn("queries.category1", &jq_cat1_col); writer.addColumn("queries.category2", &jq_cat2_col); writer.addColumn("queries.category3", &jq_cat3_col); writer.addColumn("queries.items.position", &jqi_position_col); writer.addColumn("queries.items.clicked", &jqi_clicked_col); writer.commit(); } FileUtil::mv( flags.getString("output_file") + "~", flags.getString("output_file")); //{ // cstable::CSTableReader reader(flags.getString("output_file")); // auto t0 = WallClock::unixMicros(); // cm::AnalyticsTableScan aq; // auto lcol = aq.fetchColumn("queries.language"); // auto ccol = aq.fetchColumn("queries.num_ad_clicks"); // aq.onQuery([&] () { // auto l = languageToString((Language) lcol->getUInt32()); // auto c = ccol->getUInt32(); // fnord::iputs("lang: $0 -> $1", l, c); // }); // aq.scanTable(&reader); // //cm::CTRByGroupResult<uint16_t> res; // //cm::CTRByPositionQuery q(&aq, &res); // //auto t1 = WallClock::unixMicros(); // //fnord::iputs("scanned $0 rows in $1 ms", res.rows_scanned, (t1 - t0) / 1000.0f); // //for (const auto& p : res.counters) { // // fnord::iputs( // // "pos: $0, views: $1, clicks: $2, ctr: $3", // // p.first, p.second.num_views, // // p.second.num_clicks, // // p.second.num_clicks / (double) p.second.num_views); // //} //} return 0; }
/** * Copyright (c) 2015 - The CM Authors <[email protected]> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <algorithm> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "fnord-base/io/fileutil.h" #include "fnord-base/application.h" #include "fnord-base/logging.h" #include "fnord-base/cli/flagparser.h" #include "fnord-base/util/SimpleRateLimit.h" #include "fnord-base/InternMap.h" #include "fnord-json/json.h" #include "fnord-mdb/MDB.h" #include "fnord-mdb/MDBUtil.h" #include "fnord-sstable/sstablereader.h" #include "fnord-sstable/sstablewriter.h" #include "fnord-sstable/SSTableColumnSchema.h" #include "fnord-sstable/SSTableColumnReader.h" #include "fnord-sstable/SSTableColumnWriter.h" #include "fnord-cstable/BitPackedIntColumnReader.h" #include "fnord-cstable/BitPackedIntColumnWriter.h" #include "fnord-cstable/UInt32ColumnReader.h" #include "fnord-cstable/UInt32ColumnWriter.h" #include "fnord-cstable/BooleanColumnReader.h" #include "fnord-cstable/BooleanColumnWriter.h" #include "fnord-cstable/CSTableWriter.h" #include "fnord-cstable/CSTableReader.h" #include "common.h" #include "CustomerNamespace.h" #include "FeatureSchema.h" #include "JoinedQuery.h" #include "CTRCounter.h" #include "analytics/AnalyticsTableScan.h" #include "analytics/CTRByPositionQuery.h" using namespace cm; using namespace fnord; int main(int argc, const char** argv) { fnord::Application::init(); fnord::Application::logToStderr(); fnord::cli::FlagParser flags; flags.defineFlag( "input_file", fnord::cli::FlagParser::T_STRING, true, "i", NULL, "file", "<filename>"); flags.defineFlag( "output_file", fnord::cli::FlagParser::T_STRING, true, "o", NULL, "file", "<filename>"); flags.defineFlag( "loglevel", fnord::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); size_t debug_n = 0; size_t debug_z = 0; /* query level */ cstable::UInt32ColumnWriter jq_time_col(1, 1); cstable::BitPackedIntColumnWriter jq_page_col(1, 1, 100); cstable::BitPackedIntColumnWriter jq_lang_col(1, 1, kMaxLanguage); cstable::BitPackedIntColumnWriter jq_numitems_col(1, 1, 250); cstable::BitPackedIntColumnWriter jq_numitemclicks_col(1, 1, 250); cstable::BitPackedIntColumnWriter jq_numadimprs_col(1, 1, 250); cstable::BitPackedIntColumnWriter jq_numadclicks_col(1, 1, 250); cstable::BitPackedIntColumnWriter jq_abtestgroup_col(1, 1, 100); cstable::BitPackedIntColumnWriter jq_devicetype_col(1, 1, kMaxDeviceType); cstable::BitPackedIntColumnWriter jq_pagetype_col(1, 1, kMaxPageType); cstable::BitPackedIntColumnWriter jq_cat1_col(1, 1, 0xffff); cstable::BitPackedIntColumnWriter jq_cat2_col(1, 1, 0xffff); cstable::BitPackedIntColumnWriter jq_cat3_col(1, 1, 0xffff); /* query item level */ cstable::BitPackedIntColumnWriter jqi_position_col(2, 2, 64); cstable::BooleanColumnWriter jqi_clicked_col(2, 2); uint64_t r = 0; uint64_t n = 0; auto add_session = [&] (const cm::JoinedSession& sess) { ++n; for (const auto& q : sess.queries) { /* queries.time */ jq_time_col.addDatum(r, 1, q.time.unixMicros() / kMicrosPerSecond); /* queries.language */ auto lang = cm::extractLanguage(q.attrs); uint32_t l = (uint16_t) lang; jq_lang_col.addDatum(r, 1, l); /* queries.num_item_clicks, queries.num_items */ size_t nitems = 0; size_t nclicks = 0; size_t nads = 0; size_t nadclicks = 0; for (const auto& i : q.items) { // DAWANDA HACK if (i.position >= 1 && i.position <= 4) { ++nads; nadclicks += i.clicked; } // EOF DAWANDA HACK ++nitems; nclicks += i.clicked; } if (nadclicks > 0 && lang != Language::DE) { abort(); } jq_numitems_col.addDatum(r, 1, nitems); jq_numitemclicks_col.addDatum(r, 1, nclicks); jq_numadimprs_col.addDatum(r, 1, nads); jq_numadclicks_col.addDatum(r, 1, nadclicks); /* queries.page */ auto pg_str = cm::extractAttr(q.attrs, "pg"); if (pg_str.isEmpty()) { jq_page_col.addNull(r, 1); } else { jq_page_col.addDatum(r, 1, std::stoul(pg_str.get())); } /* queries.ab_test_group */ auto abgrp = cm::extractABTestGroup(q.attrs); if (abgrp.isEmpty()) { jq_abtestgroup_col.addNull(r, 1); } else { jq_abtestgroup_col.addDatum(r, 1, abgrp.get()); } /* queries.category1 */ auto qcat1 = cm::extractAttr(q.attrs, "q_cat1"); if (qcat1.isEmpty()) { jq_cat1_col.addNull(r, 1); } else { jq_cat1_col.addDatum(r, 1, std::stoul(qcat1.get())); } /* queries.category2 */ auto qcat2 = cm::extractAttr(q.attrs, "q_cat2"); if (qcat2.isEmpty()) { jq_cat2_col.addNull(r, 1); } else { jq_cat2_col.addDatum(r, 1, std::stoul(qcat2.get())); } /* queries.category3 */ auto qcat3 = cm::extractAttr(q.attrs, "q_cat3"); if (qcat3.isEmpty()) { jq_cat3_col.addNull(r, 1); } else { jq_cat3_col.addDatum(r, 1, std::stoul(qcat3.get())); } /* queries.device_type */ jq_devicetype_col.addDatum(r, 1, (uint32_t) extractDeviceType(q.attrs)); /* queries.page_type */ jq_pagetype_col.addDatum(r, 1, (uint32_t) extractPageType(q.attrs)); if (q.items.size() == 0) { jqi_position_col.addNull(r, 1); jqi_clicked_col.addNull(r, 1); } for (const auto& i : q.items) { jqi_position_col.addDatum(r, 2, i.position); jqi_clicked_col.addDatum(r, 2, i.clicked); r = 2; } r = 1; } r = 0; }; /* read input tables */ int row_idx = 0; const auto& sstable = flags.getString("input_file"); fnord::logInfo("cm.jqcolumnize", "Importing sstable: $0", sstable); /* read sstable header */ sstable::SSTableReader reader(File::openFile(sstable, File::O_READ)); if (reader.bodySize() == 0) { fnord::logCritical("cm.jqcolumnize", "unfinished sstable: $0", sstable); exit(1); } /* get sstable cursor */ auto cursor = reader.getCursor(); auto body_size = reader.bodySize(); /* status line */ util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () { fnord::logInfo( "cm.jqcolumnize", "[$0%] Reading sstable... rows=$1", (size_t) ((cursor->position() / (double) body_size) * 100), row_idx); }); /* read sstable rows */ for (; cursor->valid(); ++row_idx) { status_line.runMaybe(); auto key = cursor->getKeyString(); auto val = cursor->getDataBuffer(); Option<cm::JoinedQuery> q; try { q = Some(json::fromJSON<cm::JoinedQuery>(val)); } catch (const Exception& e) { fnord::logWarning("cm.jqcolumnize", e, "invalid json: $0", val.toString()); } if (!q.isEmpty()) { cm::JoinedSession s; s.queries.emplace_back(q.get()); add_session(s); } if (!cursor->next()) { break; } } status_line.runForce(); { cstable::CSTableWriter writer(flags.getString("output_file") + "~", n); writer.addColumn("queries.time", &jq_time_col); writer.addColumn("queries.page", &jq_page_col); writer.addColumn("queries.language", &jq_lang_col); writer.addColumn("queries.num_items", &jq_numitems_col); writer.addColumn("queries.num_items_clicked", &jq_numitemclicks_col); writer.addColumn("queries.num_ad_impressions", &jq_numadimprs_col); writer.addColumn("queries.num_ad_clicks", &jq_numadclicks_col); writer.addColumn("queries.ab_test_group", &jq_abtestgroup_col); writer.addColumn("queries.device_type", &jq_devicetype_col); writer.addColumn("queries.page_type", &jq_pagetype_col); writer.addColumn("queries.category1", &jq_cat1_col); writer.addColumn("queries.category2", &jq_cat2_col); writer.addColumn("queries.category3", &jq_cat3_col); writer.addColumn("queries.items.position", &jqi_position_col); writer.addColumn("queries.items.clicked", &jqi_clicked_col); writer.commit(); } FileUtil::mv( flags.getString("output_file") + "~", flags.getString("output_file")); //{ // cstable::CSTableReader reader(flags.getString("output_file")); // auto t0 = WallClock::unixMicros(); // cm::AnalyticsTableScan aq; // auto lcol = aq.fetchColumn("queries.language"); // auto ccol = aq.fetchColumn("queries.num_ad_clicks"); // aq.onQuery([&] () { // auto l = languageToString((Language) lcol->getUInt32()); // auto c = ccol->getUInt32(); // fnord::iputs("lang: $0 -> $1", l, c); // }); // aq.scanTable(&reader); // //cm::CTRByGroupResult<uint16_t> res; // //cm::CTRByPositionQuery q(&aq, &res); // //auto t1 = WallClock::unixMicros(); // //fnord::iputs("scanned $0 rows in $1 ms", res.rows_scanned, (t1 - t0) / 1000.0f); // //for (const auto& p : res.counters) { // // fnord::iputs( // // "pos: $0, views: $1, clicks: $2, ctr: $3", // // p.first, p.second.num_views, // // p.second.num_clicks, // // p.second.num_clicks / (double) p.second.num_views); // //} //} return 0; }
remove hack
remove hack
C++
agpl-3.0
eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql
5ee32db9c46951d68e59e5988ad674bb14d7a780
tools/extra_defs_gen/generate_defs_gst.cc
tools/extra_defs_gen/generate_defs_gst.cc
/* generate_defs_gst.cc * * Copyright 2008 The gstreamermm Development Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <glibmm_generate_extra_defs/generate_extra_defs.h> #include "get_plugin_defs.h" // Core includes #include <gst/gst.h> // Core library includes #include <gst/base/base.h> #include <gst/controller/controller.h> #include <gst/net/net.h> // Base library includes #include <gst/audio/audio.h> #include <gst/pbutils/pbutils.h> #include <gst/rtp/rtp.h> #include <gst/tag/tag.h> #include <gst/video/video.h> bool gst_type_is_a_pointer(GType gtype) { return (gtype_is_a_pointer(gtype)); } int main (int argc, char *argv[]) { gst_init (&argc, &argv); // GStreamer core types: std::cout << get_defs(GST_TYPE_BUS, gst_type_is_a_pointer) << get_defs(GST_TYPE_BIN, gst_type_is_a_pointer) << get_defs(GST_TYPE_BUFFER, gst_type_is_a_pointer) << get_defs(GST_TYPE_CAPS, gst_type_is_a_pointer) << get_defs(GST_TYPE_CHILD_PROXY, gst_type_is_a_pointer) << get_defs(GST_TYPE_CLOCK, gst_type_is_a_pointer) << get_defs(GST_TYPE_ELEMENT, gst_type_is_a_pointer) << get_defs(GST_TYPE_ELEMENT_FACTORY, gst_type_is_a_pointer) << get_defs(GST_TYPE_EVENT, gst_type_is_a_pointer) << get_defs(GST_TYPE_FORMAT, gst_type_is_a_pointer) << get_defs(GST_TYPE_GHOST_PAD, gst_type_is_a_pointer) << get_defs(GST_TYPE_MESSAGE, gst_type_is_a_pointer) << get_defs(GST_TYPE_OBJECT, gst_type_is_a_pointer) << get_defs(GST_TYPE_PAD, gst_type_is_a_pointer) << get_defs(GST_TYPE_PAD_TEMPLATE, gst_type_is_a_pointer) << get_defs(GST_TYPE_PIPELINE, gst_type_is_a_pointer) << get_defs(GST_TYPE_PLUGIN, gst_type_is_a_pointer) << get_defs(GST_TYPE_PLUGIN_FEATURE, gst_type_is_a_pointer) << get_defs(GST_TYPE_QUERY, gst_type_is_a_pointer) << get_defs(GST_TYPE_REGISTRY, gst_type_is_a_pointer) << get_defs(GST_TYPE_SEGMENT, gst_type_is_a_pointer) << get_defs(GST_TYPE_STRUCTURE, gst_type_is_a_pointer) << get_defs(GST_TYPE_SYSTEM_CLOCK, gst_type_is_a_pointer) << get_defs(GST_TYPE_TAG_LIST, gst_type_is_a_pointer) << get_defs(GST_TYPE_TAG_SETTER, gst_type_is_a_pointer) << get_defs(GST_TYPE_TASK, gst_type_is_a_pointer) << get_defs(GST_TYPE_TYPE_FIND, gst_type_is_a_pointer) << get_defs(GST_TYPE_TYPE_FIND_FACTORY, gst_type_is_a_pointer) << get_defs(GST_TYPE_URI_HANDLER, gst_type_is_a_pointer) // GStreamer core library types: << get_defs(GST_TYPE_BASE_SRC, gst_type_is_a_pointer) << get_defs(GST_TYPE_BASE_SINK, gst_type_is_a_pointer) << get_defs(GST_TYPE_BASE_TRANSFORM, gst_type_is_a_pointer) << get_defs(GST_TYPE_PUSH_SRC, gst_type_is_a_pointer) << get_defs(GST_TYPE_ADAPTER, gst_type_is_a_pointer) << get_defs(GST_TYPE_COLLECT_PADS, gst_type_is_a_pointer) << get_defs(GST_TYPE_DATA_QUEUE, gst_type_is_a_pointer) << get_defs(GST_TYPE_CONTROL_SOURCE, gst_type_is_a_pointer) << get_defs(GST_TYPE_INTERPOLATION_CONTROL_SOURCE, gst_type_is_a_pointer) << get_defs(GST_TYPE_LFO_CONTROL_SOURCE, gst_type_is_a_pointer) << get_defs(GST_TYPE_NET_CLIENT_CLOCK, gst_type_is_a_pointer) << get_defs(GST_TYPE_NET_TIME_PROVIDER, gst_type_is_a_pointer) << get_defs(GST_TYPE_NET_TIME_PROVIDER, gst_type_is_a_pointer) // GStreamer core plugin types: << get_plugin_defs("capsfilter", gst_type_is_a_pointer) << get_plugin_defs("fakesrc", gst_type_is_a_pointer) << get_plugin_defs("fakesink", gst_type_is_a_pointer) << get_plugin_defs("fdsink", gst_type_is_a_pointer) << get_plugin_defs("fdsrc", gst_type_is_a_pointer) << get_plugin_defs("filesrc", gst_type_is_a_pointer) << get_plugin_defs("filesink", gst_type_is_a_pointer) << get_plugin_defs("funnel", gst_type_is_a_pointer) << get_plugin_defs("identity", gst_type_is_a_pointer) << get_plugin_defs("input-selector", gst_type_is_a_pointer) << get_plugin_defs("multiqueue", gst_type_is_a_pointer) << get_plugin_defs("output-selector", gst_type_is_a_pointer) << get_plugin_defs("queue", gst_type_is_a_pointer) << get_plugin_defs("queue2", gst_type_is_a_pointer) << get_plugin_defs("tee", gst_type_is_a_pointer) << get_plugin_defs("typefind", gst_type_is_a_pointer) << get_plugin_defs("valve", gst_type_is_a_pointer) // gst-plugins-base (GStreamer base) types: << get_defs(GST_TYPE_AUDIO_BASE_SINK, gst_type_is_a_pointer) << get_defs(GST_TYPE_AUDIO_BASE_SRC, gst_type_is_a_pointer) << get_defs(GST_TYPE_AUDIO_CD_SRC, gst_type_is_a_pointer) << get_defs(GST_TYPE_AUDIO_CLOCK, gst_type_is_a_pointer) << get_defs(GST_TYPE_AUDIO_FILTER, gst_type_is_a_pointer) << get_defs(GST_TYPE_AUDIO_RING_BUFFER, gst_type_is_a_pointer) << get_defs(GST_TYPE_AUDIO_SINK, gst_type_is_a_pointer) << get_defs(GST_TYPE_AUDIO_SRC, gst_type_is_a_pointer) << get_defs(GST_TYPE_DISCOVERER, gst_type_is_a_pointer) << get_defs(GST_TYPE_RTP_BASE_AUDIO_PAYLOAD, gst_type_is_a_pointer) << get_defs(GST_TYPE_RTP_BASE_DEPAYLOAD, gst_type_is_a_pointer) << get_defs(GST_TYPE_RTP_BASE_PAYLOAD, gst_type_is_a_pointer) << get_defs(GST_TYPE_TAG_DEMUX, gst_type_is_a_pointer) << get_defs(GST_TYPE_VIDEO_FILTER, gst_type_is_a_pointer) << get_defs(GST_TYPE_VIDEO_SINK, gst_type_is_a_pointer) // gst-plugins-base (GStreamer base) interfaces: << get_defs(GST_TYPE_COLOR_BALANCE, gst_type_is_a_pointer) << get_defs(GST_TYPE_COLOR_BALANCE_CHANNEL, gst_type_is_a_pointer) << get_defs(GST_TYPE_NAVIGATION, gst_type_is_a_pointer) << get_defs(GST_TYPE_STREAM_VOLUME, gst_type_is_a_pointer) << get_defs(GST_TYPE_VIDEO_ORIENTATION, gst_type_is_a_pointer) << get_defs(GST_TYPE_VIDEO_OVERLAY, gst_type_is_a_pointer) // gst-plugins-base (GStreamer base) plugin types: << get_plugin_defs("adder", gst_type_is_a_pointer) << get_plugin_defs("alsasink", gst_type_is_a_pointer) << get_plugin_defs("alsasrc", gst_type_is_a_pointer) << get_plugin_defs("appsrc", gst_type_is_a_pointer) << get_plugin_defs("appsink", gst_type_is_a_pointer) << get_plugin_defs("audioconvert", gst_type_is_a_pointer) << get_plugin_defs("audiorate", gst_type_is_a_pointer) << get_plugin_defs("audioresample", gst_type_is_a_pointer) << get_plugin_defs("audiotestsrc", gst_type_is_a_pointer) << get_plugin_defs("cdparanoiasrc", gst_type_is_a_pointer) << get_plugin_defs("clockoverlay", gst_type_is_a_pointer) << get_plugin_defs("decodebin", gst_type_is_a_pointer) << get_plugin_defs("giosink", gst_type_is_a_pointer) << get_plugin_defs("giosrc", gst_type_is_a_pointer) << get_plugin_defs("giostreamsink", gst_type_is_a_pointer) << get_plugin_defs("giostreamsrc", gst_type_is_a_pointer) << get_plugin_defs("gnomevfssink", gst_type_is_a_pointer) << get_plugin_defs("gnomevfssrc", gst_type_is_a_pointer) << get_plugin_defs("multifdsink", gst_type_is_a_pointer) << get_plugin_defs("oggdemux", gst_type_is_a_pointer) << get_plugin_defs("oggmux", gst_type_is_a_pointer) << get_plugin_defs("playbin", gst_type_is_a_pointer) << get_plugin_defs("subtitleoverlay", gst_type_is_a_pointer) << get_plugin_defs("tcpclientsrc", gst_type_is_a_pointer) << get_plugin_defs("tcpclientsink", gst_type_is_a_pointer) << get_plugin_defs("tcpserversrc", gst_type_is_a_pointer) << get_plugin_defs("tcpserversink", gst_type_is_a_pointer) << get_plugin_defs("textoverlay", gst_type_is_a_pointer) << get_plugin_defs("textrender", gst_type_is_a_pointer) << get_plugin_defs("theoradec", gst_type_is_a_pointer) << get_plugin_defs("theoraenc", gst_type_is_a_pointer) << get_plugin_defs("theoraparse", gst_type_is_a_pointer) << get_plugin_defs("timeoverlay", gst_type_is_a_pointer) << get_plugin_defs("uridecodebin", gst_type_is_a_pointer) << get_plugin_defs("videorate", gst_type_is_a_pointer) << get_plugin_defs("videoscale", gst_type_is_a_pointer) << get_plugin_defs("videotestsrc", gst_type_is_a_pointer) << get_plugin_defs("volume", gst_type_is_a_pointer) << get_plugin_defs("vorbisdec", gst_type_is_a_pointer) << get_plugin_defs("vorbisenc", gst_type_is_a_pointer) << get_plugin_defs("vorbisparse", gst_type_is_a_pointer) << get_plugin_defs("vorbistag", gst_type_is_a_pointer) << get_plugin_defs("ximagesink", gst_type_is_a_pointer) << get_plugin_defs("xvimagesink", gst_type_is_a_pointer) ; return 0; }
/* generate_defs_gst.cc * * Copyright 2008 The gstreamermm Development Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <glibmm_generate_extra_defs/generate_extra_defs.h> #include "get_plugin_defs.h" // Core includes #include <gst/gst.h> // Core library includes #include <gst/base/gstadapter.h> #include <gst/base/gstbaseparse.h> #include <gst/base/gstbasesink.h> #include <gst/base/gstbasesrc.h> #include <gst/base/gstbasetransform.h> #include <gst/base/gstcollectpads.h> #include <gst/base/gstpushsrc.h> #include <gst/gstcontrolsource.h> #include <gst/gstcontrolbinding.h> #include <gst/controller/gstinterpolationcontrolsource.h> #include <gst/controller/gstlfocontrolsource.h> #include <gst/net/gstnetclientclock.h> #include <gst/net/gstnettimeprovider.h> // Base library includes #include <gst/audio/audio.h> #include <gst/audio/audio-enumtypes.h> #include <gst/audio/gstaudiobasesink.h> #include <gst/audio/gstaudiobasesrc.h> #include <gst/audio/gstaudiocdsrc.h> #include <gst/audio/gstaudioclock.h> #include <gst/audio/gstaudiodecoder.h> #include <gst/audio/gstaudioencoder.h> #include <gst/audio/gstaudiofilter.h> #include <gst/audio/gstaudioringbuffer.h> #include <gst/audio/gstaudiosink.h> #include <gst/audio/gstaudiosrc.h> #include <gst/audio/streamvolume.h> #include <gst/rtp/gstrtpbaseaudiopayload.h> #include <gst/rtp/gstrtpbasedepayload.h> #include <gst/rtp/gstrtpbasepayload.h> #include <gst/tag/gsttagdemux.h> #include <gst/video/video.h> #include <gst/video/gstvideodecoder.h> #include <gst/video/gstvideoencoder.h> #include <gst/video/gstvideofilter.h> #include <gst/video/gstvideopool.h> #include <gst/video/gstvideosink.h> #include <gst/video/gstvideoutils.h> #include <gst/video/videoorientation.h> #include <gst/video/video-overlay-composition.h> #include <gst/video/videooverlay.h> #include <gst/video/colorbalancechannel.h> #include <gst/video/colorbalance.h> #include <gst/video/navigation.h> #include <gst/pbutils/pbutils.h> #include <gst/tag/tag.h> bool gst_type_is_a_pointer(GType gtype) { return (gtype_is_a_pointer(gtype)); } int main (int argc, char *argv[]) { gst_init (&argc, &argv); // GStreamer core types: std::cout << get_defs(GST_TYPE_BUS, gst_type_is_a_pointer) << get_defs(GST_TYPE_BIN, gst_type_is_a_pointer) << get_defs(GST_TYPE_BUFFER, gst_type_is_a_pointer) << get_defs(GST_TYPE_CAPS, gst_type_is_a_pointer) << get_defs(GST_TYPE_CHILD_PROXY, gst_type_is_a_pointer) << get_defs(GST_TYPE_CLOCK, gst_type_is_a_pointer) << get_defs(GST_TYPE_ELEMENT, gst_type_is_a_pointer) << get_defs(GST_TYPE_ELEMENT_FACTORY, gst_type_is_a_pointer) << get_defs(GST_TYPE_EVENT, gst_type_is_a_pointer) << get_defs(GST_TYPE_FORMAT, gst_type_is_a_pointer) << get_defs(GST_TYPE_GHOST_PAD, gst_type_is_a_pointer) << get_defs(GST_TYPE_MESSAGE, gst_type_is_a_pointer) << get_defs(GST_TYPE_OBJECT, gst_type_is_a_pointer) << get_defs(GST_TYPE_PAD, gst_type_is_a_pointer) << get_defs(GST_TYPE_PAD_TEMPLATE, gst_type_is_a_pointer) << get_defs(GST_TYPE_PIPELINE, gst_type_is_a_pointer) << get_defs(GST_TYPE_PLUGIN, gst_type_is_a_pointer) << get_defs(GST_TYPE_PLUGIN_FEATURE, gst_type_is_a_pointer) << get_defs(GST_TYPE_QUERY, gst_type_is_a_pointer) << get_defs(GST_TYPE_REGISTRY, gst_type_is_a_pointer) << get_defs(GST_TYPE_SEGMENT, gst_type_is_a_pointer) << get_defs(GST_TYPE_STRUCTURE, gst_type_is_a_pointer) << get_defs(GST_TYPE_SYSTEM_CLOCK, gst_type_is_a_pointer) << get_defs(GST_TYPE_TAG_LIST, gst_type_is_a_pointer) << get_defs(GST_TYPE_TAG_SETTER, gst_type_is_a_pointer) << get_defs(GST_TYPE_TASK, gst_type_is_a_pointer) << get_defs(GST_TYPE_TYPE_FIND, gst_type_is_a_pointer) << get_defs(GST_TYPE_TYPE_FIND_FACTORY, gst_type_is_a_pointer) << get_defs(GST_TYPE_URI_HANDLER, gst_type_is_a_pointer) // GStreamer core library types: << get_defs(GST_TYPE_BASE_SRC, gst_type_is_a_pointer) << get_defs(GST_TYPE_BASE_SINK, gst_type_is_a_pointer) << get_defs(GST_TYPE_BASE_TRANSFORM, gst_type_is_a_pointer) << get_defs(GST_TYPE_BASE_PARSE, gst_type_is_a_pointer) << get_defs(GST_TYPE_PUSH_SRC, gst_type_is_a_pointer) << get_defs(GST_TYPE_ADAPTER, gst_type_is_a_pointer) << get_defs(GST_TYPE_COLLECT_PADS, gst_type_is_a_pointer) << get_defs(GST_TYPE_CONTROL_SOURCE, gst_type_is_a_pointer) << get_defs(GST_TYPE_CONTROL_BINDING, gst_type_is_a_pointer) << get_defs(GST_TYPE_INTERPOLATION_CONTROL_SOURCE, gst_type_is_a_pointer) << get_defs(GST_TYPE_LFO_CONTROL_SOURCE, gst_type_is_a_pointer) << get_defs(GST_TYPE_NET_CLIENT_CLOCK, gst_type_is_a_pointer) << get_defs(GST_TYPE_NET_TIME_PROVIDER, gst_type_is_a_pointer) // GStreamer core plugin types: << get_plugin_defs("capsfilter", gst_type_is_a_pointer) << get_plugin_defs("fakesrc", gst_type_is_a_pointer) << get_plugin_defs("fakesink", gst_type_is_a_pointer) << get_plugin_defs("fdsink", gst_type_is_a_pointer) << get_plugin_defs("fdsrc", gst_type_is_a_pointer) << get_plugin_defs("filesrc", gst_type_is_a_pointer) << get_plugin_defs("filesink", gst_type_is_a_pointer) << get_plugin_defs("funnel", gst_type_is_a_pointer) << get_plugin_defs("identity", gst_type_is_a_pointer) << get_plugin_defs("input-selector", gst_type_is_a_pointer) << get_plugin_defs("multiqueue", gst_type_is_a_pointer) << get_plugin_defs("output-selector", gst_type_is_a_pointer) << get_plugin_defs("queue", gst_type_is_a_pointer) << get_plugin_defs("queue2", gst_type_is_a_pointer) << get_plugin_defs("tee", gst_type_is_a_pointer) << get_plugin_defs("typefind", gst_type_is_a_pointer) << get_plugin_defs("valve", gst_type_is_a_pointer) // gst-plugins-base (GStreamer base) types: << get_defs(GST_TYPE_AUDIO_BASE_SINK, gst_type_is_a_pointer) << get_defs(GST_TYPE_AUDIO_BASE_SRC, gst_type_is_a_pointer) << get_defs(GST_TYPE_AUDIO_CD_SRC, gst_type_is_a_pointer) << get_defs(GST_TYPE_AUDIO_CLOCK, gst_type_is_a_pointer) << get_defs(GST_TYPE_AUDIO_FILTER, gst_type_is_a_pointer) << get_defs(GST_TYPE_AUDIO_RING_BUFFER, gst_type_is_a_pointer) << get_defs(GST_TYPE_AUDIO_SINK, gst_type_is_a_pointer) << get_defs(GST_TYPE_AUDIO_SRC, gst_type_is_a_pointer) << get_defs(GST_TYPE_DISCOVERER, gst_type_is_a_pointer) << get_defs(GST_TYPE_RTP_BASE_AUDIO_PAYLOAD, gst_type_is_a_pointer) << get_defs(GST_TYPE_RTP_BASE_DEPAYLOAD, gst_type_is_a_pointer) << get_defs(GST_TYPE_RTP_BASE_PAYLOAD, gst_type_is_a_pointer) << get_defs(GST_TYPE_TAG_DEMUX, gst_type_is_a_pointer) << get_defs(GST_TYPE_VIDEO_FILTER, gst_type_is_a_pointer) << get_defs(GST_TYPE_VIDEO_SINK, gst_type_is_a_pointer) // gst-plugins-base (GStreamer base) interfaces: << get_defs(GST_TYPE_COLOR_BALANCE, gst_type_is_a_pointer) << get_defs(GST_TYPE_COLOR_BALANCE_CHANNEL, gst_type_is_a_pointer) << get_defs(GST_TYPE_NAVIGATION, gst_type_is_a_pointer) << get_defs(GST_TYPE_STREAM_VOLUME, gst_type_is_a_pointer) << get_defs(GST_TYPE_VIDEO_ORIENTATION, gst_type_is_a_pointer) << get_defs(GST_TYPE_VIDEO_OVERLAY, gst_type_is_a_pointer) // gst-plugins-base (GStreamer base) plugin types: << get_plugin_defs("adder", gst_type_is_a_pointer) << get_plugin_defs("alsasink", gst_type_is_a_pointer) << get_plugin_defs("alsasrc", gst_type_is_a_pointer) << get_plugin_defs("appsrc", gst_type_is_a_pointer) << get_plugin_defs("appsink", gst_type_is_a_pointer) << get_plugin_defs("audioconvert", gst_type_is_a_pointer) << get_plugin_defs("audiorate", gst_type_is_a_pointer) << get_plugin_defs("audioresample", gst_type_is_a_pointer) << get_plugin_defs("audiotestsrc", gst_type_is_a_pointer) << get_plugin_defs("cdparanoiasrc", gst_type_is_a_pointer) << get_plugin_defs("clockoverlay", gst_type_is_a_pointer) << get_plugin_defs("decodebin", gst_type_is_a_pointer) << get_plugin_defs("giosink", gst_type_is_a_pointer) << get_plugin_defs("giosrc", gst_type_is_a_pointer) << get_plugin_defs("giostreamsink", gst_type_is_a_pointer) << get_plugin_defs("giostreamsrc", gst_type_is_a_pointer) << get_plugin_defs("gnomevfssink", gst_type_is_a_pointer) << get_plugin_defs("gnomevfssrc", gst_type_is_a_pointer) << get_plugin_defs("multifdsink", gst_type_is_a_pointer) << get_plugin_defs("oggdemux", gst_type_is_a_pointer) << get_plugin_defs("oggmux", gst_type_is_a_pointer) << get_plugin_defs("playbin", gst_type_is_a_pointer) << get_plugin_defs("subtitleoverlay", gst_type_is_a_pointer) << get_plugin_defs("tcpclientsrc", gst_type_is_a_pointer) << get_plugin_defs("tcpclientsink", gst_type_is_a_pointer) << get_plugin_defs("tcpserversrc", gst_type_is_a_pointer) << get_plugin_defs("tcpserversink", gst_type_is_a_pointer) << get_plugin_defs("textoverlay", gst_type_is_a_pointer) << get_plugin_defs("textrender", gst_type_is_a_pointer) << get_plugin_defs("theoradec", gst_type_is_a_pointer) << get_plugin_defs("theoraenc", gst_type_is_a_pointer) << get_plugin_defs("theoraparse", gst_type_is_a_pointer) << get_plugin_defs("timeoverlay", gst_type_is_a_pointer) << get_plugin_defs("uridecodebin", gst_type_is_a_pointer) << get_plugin_defs("videorate", gst_type_is_a_pointer) << get_plugin_defs("videoscale", gst_type_is_a_pointer) << get_plugin_defs("videotestsrc", gst_type_is_a_pointer) << get_plugin_defs("volume", gst_type_is_a_pointer) << get_plugin_defs("vorbisdec", gst_type_is_a_pointer) << get_plugin_defs("vorbisenc", gst_type_is_a_pointer) << get_plugin_defs("vorbisparse", gst_type_is_a_pointer) << get_plugin_defs("vorbistag", gst_type_is_a_pointer) << get_plugin_defs("ximagesink", gst_type_is_a_pointer) << get_plugin_defs("xvimagesink", gst_type_is_a_pointer) ; return 0; }
update types and includes in generator's hardcoded lists
update types and includes in generator's hardcoded lists
C++
lgpl-2.1
jledet/gstreamermm,jledet/gstreamermm,jledet/gstreamermm
ced64d7571b2c334bccc0e1a12b709276103a676
partition_snapshot_reader.hh
partition_snapshot_reader.hh
/* * Copyright (C) 2017 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "partition_version.hh" struct partition_snapshot_reader_dummy_accounter { void operator()(const clustering_row& cr) {} void operator()(const static_row& sr) {} void operator()(const range_tombstone& rt) {} void operator()(const partition_start& ph) {} void operator()(const partition_end& eop) {} }; extern partition_snapshot_reader_dummy_accounter no_accounter; inline void maybe_merge_versions(lw_shared_ptr<partition_snapshot>& snp, logalloc::region& lsa_region, logalloc::allocating_section& read_section) { if (!snp.owned()) { return; } // If no one else is using this particular snapshot try to merge partition // versions. with_allocator(lsa_region.allocator(), [&snp, &lsa_region, &read_section] { return with_linearized_managed_bytes([&snp, &lsa_region, &read_section] { try { // Allocating sections require the region to be reclaimable // which means that they cannot be nested. // It is, however, possible, that if the snapshot is taken // inside an allocating section and then an exception is thrown // this function will be called to clean up even though we // still will be in the context of the allocating section. if (lsa_region.reclaiming_enabled()) { read_section(lsa_region, [&snp] { snp->merge_partition_versions(); }); } } catch (...) { } snp = {}; }); }); } template <typename MemoryAccounter = partition_snapshot_reader_dummy_accounter> class partition_snapshot_reader : public streamed_mutation::impl, public MemoryAccounter { struct rows_position { mutation_partition::rows_type::const_iterator _position; mutation_partition::rows_type::const_iterator _end; }; class heap_compare { rows_entry::compare _cmp; public: explicit heap_compare(const schema& s) : _cmp(s) { } bool operator()(const rows_position& a, const rows_position& b) { return _cmp(*b._position, *a._position); } }; private: // Keeps shared pointer to the container we read mutation from to make sure // that its lifetime is appropriately extended. boost::any _container_guard; query::clustering_key_filter_ranges _ck_ranges; query::clustering_row_ranges::const_iterator _current_ck_range; query::clustering_row_ranges::const_iterator _ck_range_end; bool _in_ck_range = false; rows_entry::compare _cmp; position_in_partition::equal_compare _eq; heap_compare _heap_cmp; lw_shared_ptr<partition_snapshot> _snapshot; stdx::optional<position_in_partition> _last_entry; std::vector<rows_position> _clustering_rows; range_tombstone_stream _range_tombstones; logalloc::region& _lsa_region; logalloc::allocating_section& _read_section; MemoryAccounter& mem_accounter() { return *this; } partition_snapshot::change_mark _change_mark; private: void refresh_iterators() { _clustering_rows.clear(); if (!_in_ck_range) { if (_current_ck_range == _ck_range_end) { _end_of_stream = true; return; } for (auto&& v : _snapshot->versions()) { _range_tombstones.apply(v.partition().row_tombstones(), *_current_ck_range); } } for (auto&& v : _snapshot->versions()) { auto cr_end = v.partition().upper_bound(*_schema, *_current_ck_range); auto cr = [&] () -> mutation_partition::rows_type::const_iterator { if (_in_ck_range) { return v.partition().clustered_rows().upper_bound(*_last_entry, _cmp); } else { return v.partition().lower_bound(*_schema, *_current_ck_range); } }(); if (cr != cr_end) { _clustering_rows.emplace_back(rows_position { cr, cr_end }); } } _in_ck_range = true; boost::range::make_heap(_clustering_rows, _heap_cmp); } // Valid if has_more_rows() const rows_entry& pop_clustering_row() { boost::range::pop_heap(_clustering_rows, _heap_cmp); auto& current = _clustering_rows.back(); const rows_entry& e = *current._position; current._position = std::next(current._position); if (current._position == current._end) { _clustering_rows.pop_back(); } else { boost::range::push_heap(_clustering_rows, _heap_cmp); } return e; } // Valid if has_more_rows() const rows_entry& peek_row() const { return *_clustering_rows.front()._position; } bool has_more_rows() const { return !_clustering_rows.empty(); } mutation_fragment_opt read_static_row() { _last_entry = position_in_partition(position_in_partition::static_row_tag_t()); mutation_fragment_opt sr; for (auto&& v : _snapshot->versions()) { if (!v.partition().static_row().empty()) { if (!sr) { sr = mutation_fragment(static_row(v.partition().static_row())); } else { sr->as_mutable_static_row().apply(*_schema, v.partition().static_row()); } } } return sr; } mutation_fragment_opt read_next() { while (has_more_rows()) { auto mf = _range_tombstones.get_next(peek_row()); if (mf) { return mf; } const rows_entry& e = pop_clustering_row(); if (e.dummy()) { continue; } clustering_row result = e; while (has_more_rows() && _eq(peek_row().position(), result.position())) { result.apply(*_schema, pop_clustering_row()); } _last_entry = position_in_partition(result.position()); return mutation_fragment(std::move(result)); } return _range_tombstones.get_next(); } void emplace_mutation_fragment(mutation_fragment&& mfopt) { mfopt.visit(mem_accounter()); push_mutation_fragment(std::move(mfopt)); } void do_fill_buffer() { if (!_last_entry) { auto mfopt = read_static_row(); if (mfopt) { emplace_mutation_fragment(std::move(*mfopt)); } } auto mark = _snapshot->get_change_mark(); if (!_in_ck_range || mark != _change_mark) { refresh_iterators(); _change_mark = mark; } while (!is_end_of_stream() && !is_buffer_full()) { auto mfopt = read_next(); if (mfopt) { emplace_mutation_fragment(std::move(*mfopt)); } else { _in_ck_range = false; _current_ck_range = std::next(_current_ck_range); refresh_iterators(); } } } static tombstone tomb(partition_snapshot& snp) { tombstone t; for (auto& v : snp.versions()) { t.apply(v.partition().partition_tombstone()); } return t; } public: template <typename... Args> partition_snapshot_reader(schema_ptr s, dht::decorated_key dk, lw_shared_ptr<partition_snapshot> snp, query::clustering_key_filter_ranges crr, logalloc::region& region, logalloc::allocating_section& read_section, boost::any pointer_to_container, Args&&... args) : streamed_mutation::impl(s, std::move(dk), tomb(*snp)) , MemoryAccounter(std::forward<Args>(args)...) , _container_guard(std::move(pointer_to_container)) , _ck_ranges(std::move(crr)) , _current_ck_range(_ck_ranges.begin()) , _ck_range_end(_ck_ranges.end()) , _cmp(*s) , _eq(*s) , _heap_cmp(*s) , _snapshot(snp) , _range_tombstones(*s) , _lsa_region(region) , _read_section(read_section) { do_fill_buffer(); } ~partition_snapshot_reader() { maybe_merge_versions(_snapshot, _lsa_region, _read_section); } virtual future<> fill_buffer() override { return _read_section(_lsa_region, [&] { return with_linearized_managed_bytes([&] { do_fill_buffer(); return make_ready_future<>(); }); }); } }; template <typename MemoryAccounter, typename... Args> inline streamed_mutation make_partition_snapshot_reader(schema_ptr s, dht::decorated_key dk, query::clustering_key_filter_ranges crr, lw_shared_ptr<partition_snapshot> snp, logalloc::region& region, logalloc::allocating_section& read_section, boost::any pointer_to_container, streamed_mutation::forwarding fwd, Args&&... args) { auto sm = make_streamed_mutation<partition_snapshot_reader<MemoryAccounter>>(s, std::move(dk), snp, std::move(crr), region, read_section, std::move(pointer_to_container), std::forward<Args>(args)...); if (fwd) { return make_forwardable(std::move(sm)); // FIXME: optimize } else { return std::move(sm); } } inline streamed_mutation make_partition_snapshot_reader(schema_ptr s, dht::decorated_key dk, query::clustering_key_filter_ranges crr, lw_shared_ptr<partition_snapshot> snp, logalloc::region& region, logalloc::allocating_section& read_section, boost::any pointer_to_container, streamed_mutation::forwarding fwd) { return make_partition_snapshot_reader<partition_snapshot_reader_dummy_accounter>(std::move(s), std::move(dk), std::move(crr), std::move(snp), region, read_section, std::move(pointer_to_container), fwd); }
/* * Copyright (C) 2017 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "partition_version.hh" struct partition_snapshot_reader_dummy_accounter { void operator()(const clustering_row& cr) {} void operator()(const static_row& sr) {} void operator()(const range_tombstone& rt) {} void operator()(const partition_start& ph) {} void operator()(const partition_end& eop) {} }; extern partition_snapshot_reader_dummy_accounter no_accounter; inline void maybe_merge_versions(lw_shared_ptr<partition_snapshot>& snp, logalloc::region& lsa_region, logalloc::allocating_section& read_section) { if (!snp.owned()) { return; } // If no one else is using this particular snapshot try to merge partition // versions. with_allocator(lsa_region.allocator(), [&snp, &lsa_region, &read_section] { return with_linearized_managed_bytes([&snp, &lsa_region, &read_section] { try { // Allocating sections require the region to be reclaimable // which means that they cannot be nested. // It is, however, possible, that if the snapshot is taken // inside an allocating section and then an exception is thrown // this function will be called to clean up even though we // still will be in the context of the allocating section. if (lsa_region.reclaiming_enabled()) { read_section(lsa_region, [&snp] { snp->merge_partition_versions(); }); } } catch (...) { } snp = {}; }); }); } template <typename MemoryAccounter = partition_snapshot_reader_dummy_accounter> class partition_snapshot_reader : public streamed_mutation::impl, public MemoryAccounter { struct rows_position { mutation_partition::rows_type::const_iterator _position; mutation_partition::rows_type::const_iterator _end; }; class heap_compare { rows_entry::compare _cmp; public: explicit heap_compare(const schema& s) : _cmp(s) { } bool operator()(const rows_position& a, const rows_position& b) { return _cmp(*b._position, *a._position); } }; private: // Keeps shared pointer to the container we read mutation from to make sure // that its lifetime is appropriately extended. boost::any _container_guard; query::clustering_key_filter_ranges _ck_ranges; query::clustering_row_ranges::const_iterator _current_ck_range; query::clustering_row_ranges::const_iterator _ck_range_end; bool _in_ck_range = false; rows_entry::compare _cmp; position_in_partition::equal_compare _eq; heap_compare _heap_cmp; lw_shared_ptr<partition_snapshot> _snapshot; stdx::optional<position_in_partition> _last_entry; std::vector<rows_position> _clustering_rows; range_tombstone_stream _range_tombstones; logalloc::region& _lsa_region; logalloc::allocating_section& _read_section; MemoryAccounter& mem_accounter() { return *this; } partition_snapshot::change_mark _change_mark; private: void refresh_iterators() { _clustering_rows.clear(); if (!_in_ck_range) { if (_current_ck_range == _ck_range_end) { _end_of_stream = true; return; } for (auto&& v : _snapshot->versions()) { _range_tombstones.apply(v.partition().row_tombstones(), *_current_ck_range); } } for (auto&& v : _snapshot->versions()) { auto cr_end = v.partition().upper_bound(*_schema, *_current_ck_range); auto cr = [&] () -> mutation_partition::rows_type::const_iterator { if (_in_ck_range) { return v.partition().clustered_rows().upper_bound(*_last_entry, _cmp); } else { return v.partition().lower_bound(*_schema, *_current_ck_range); } }(); if (cr != cr_end) { _clustering_rows.emplace_back(rows_position { cr, cr_end }); } } _in_ck_range = true; boost::range::make_heap(_clustering_rows, _heap_cmp); } // Valid if has_more_rows() const rows_entry& pop_clustering_row() { boost::range::pop_heap(_clustering_rows, _heap_cmp); auto& current = _clustering_rows.back(); const rows_entry& e = *current._position; current._position = std::next(current._position); if (current._position == current._end) { _clustering_rows.pop_back(); } else { boost::range::push_heap(_clustering_rows, _heap_cmp); } return e; } // Valid if has_more_rows() const rows_entry& peek_row() const { return *_clustering_rows.front()._position; } bool has_more_rows() const { return !_clustering_rows.empty(); } mutation_fragment_opt read_static_row() { _last_entry = position_in_partition(position_in_partition::static_row_tag_t()); mutation_fragment_opt sr; for (auto&& v : _snapshot->versions()) { if (!v.partition().static_row().empty()) { if (!sr) { sr = mutation_fragment(static_row(v.partition().static_row())); } else { sr->as_mutable_static_row().apply(*_schema, v.partition().static_row()); } } } return sr; } mutation_fragment_opt read_next() { while (has_more_rows()) { auto mf = _range_tombstones.get_next(peek_row()); if (mf) { return mf; } const rows_entry& e = pop_clustering_row(); if (e.dummy()) { continue; } clustering_row result = e; while (has_more_rows() && _eq(peek_row().position(), result.position())) { result.apply(*_schema, pop_clustering_row()); } _last_entry = position_in_partition(result.position()); return mutation_fragment(std::move(result)); } return _range_tombstones.get_next(); } void emplace_mutation_fragment(mutation_fragment&& mfopt) { mfopt.visit(mem_accounter()); push_mutation_fragment(std::move(mfopt)); } void do_fill_buffer() { if (!_last_entry) { auto mfopt = read_static_row(); if (mfopt) { emplace_mutation_fragment(std::move(*mfopt)); } } auto mark = _snapshot->get_change_mark(); if (!_in_ck_range || mark != _change_mark) { refresh_iterators(); _change_mark = mark; } while (!is_end_of_stream() && !is_buffer_full()) { auto mfopt = read_next(); if (mfopt) { emplace_mutation_fragment(std::move(*mfopt)); } else { _in_ck_range = false; _current_ck_range = std::next(_current_ck_range); refresh_iterators(); } } } static tombstone tomb(partition_snapshot& snp) { tombstone t; for (auto& v : snp.versions()) { t.apply(v.partition().partition_tombstone()); } return t; } public: template <typename... Args> partition_snapshot_reader(schema_ptr s, dht::decorated_key dk, lw_shared_ptr<partition_snapshot> snp, query::clustering_key_filter_ranges crr, logalloc::region& region, logalloc::allocating_section& read_section, boost::any pointer_to_container, Args&&... args) : streamed_mutation::impl(s, std::move(dk), tomb(*snp)) , MemoryAccounter(std::forward<Args>(args)...) , _container_guard(std::move(pointer_to_container)) , _ck_ranges(std::move(crr)) , _current_ck_range(_ck_ranges.begin()) , _ck_range_end(_ck_ranges.end()) , _cmp(*s) , _eq(*s) , _heap_cmp(*s) , _snapshot(snp) , _range_tombstones(*s) , _lsa_region(region) , _read_section(read_section) { do_fill_buffer(); } ~partition_snapshot_reader() { maybe_merge_versions(_snapshot, _lsa_region, _read_section); } virtual future<> fill_buffer() override { return _read_section(_lsa_region, [&] { return with_linearized_managed_bytes([&] { do_fill_buffer(); return make_ready_future<>(); }); }); } }; template <typename MemoryAccounter, typename... Args> inline streamed_mutation make_partition_snapshot_reader(schema_ptr s, dht::decorated_key dk, query::clustering_key_filter_ranges crr, lw_shared_ptr<partition_snapshot> snp, logalloc::region& region, logalloc::allocating_section& read_section, boost::any pointer_to_container, streamed_mutation::forwarding fwd, Args&&... args) { auto sm = make_streamed_mutation<partition_snapshot_reader<MemoryAccounter>>(s, std::move(dk), snp, std::move(crr), region, read_section, std::move(pointer_to_container), std::forward<Args>(args)...); if (fwd) { return make_forwardable(std::move(sm)); // FIXME: optimize } else { return std::move(sm); } } inline streamed_mutation make_partition_snapshot_reader(schema_ptr s, dht::decorated_key dk, query::clustering_key_filter_ranges crr, lw_shared_ptr<partition_snapshot> snp, logalloc::region& region, logalloc::allocating_section& read_section, boost::any pointer_to_container, streamed_mutation::forwarding fwd) { return make_partition_snapshot_reader<partition_snapshot_reader_dummy_accounter>(std::move(s), std::move(dk), std::move(crr), std::move(snp), region, read_section, std::move(pointer_to_container), fwd); } template <typename MemoryAccounter = partition_snapshot_reader_dummy_accounter> class partition_snapshot_flat_reader : public streamed_mutation::impl, public MemoryAccounter { struct rows_position { mutation_partition::rows_type::const_iterator _position; mutation_partition::rows_type::const_iterator _end; }; class heap_compare { rows_entry::compare _cmp; public: explicit heap_compare(const schema& s) : _cmp(s) { } bool operator()(const rows_position& a, const rows_position& b) { return _cmp(*b._position, *a._position); } }; private: // Keeps shared pointer to the container we read mutation from to make sure // that its lifetime is appropriately extended. boost::any _container_guard; query::clustering_key_filter_ranges _ck_ranges; query::clustering_row_ranges::const_iterator _current_ck_range; query::clustering_row_ranges::const_iterator _ck_range_end; bool _in_ck_range = false; rows_entry::compare _cmp; position_in_partition::equal_compare _eq; heap_compare _heap_cmp; lw_shared_ptr<partition_snapshot> _snapshot; stdx::optional<position_in_partition> _last_entry; std::vector<rows_position> _clustering_rows; range_tombstone_stream _range_tombstones; logalloc::region& _lsa_region; logalloc::allocating_section& _read_section; MemoryAccounter& mem_accounter() { return *this; } partition_snapshot::change_mark _change_mark; private: void refresh_iterators() { _clustering_rows.clear(); if (!_in_ck_range) { if (_current_ck_range == _ck_range_end) { _end_of_stream = true; return; } for (auto&& v : _snapshot->versions()) { _range_tombstones.apply(v.partition().row_tombstones(), *_current_ck_range); } } for (auto&& v : _snapshot->versions()) { auto cr_end = v.partition().upper_bound(*_schema, *_current_ck_range); auto cr = [&] () -> mutation_partition::rows_type::const_iterator { if (_in_ck_range) { return v.partition().clustered_rows().upper_bound(*_last_entry, _cmp); } else { return v.partition().lower_bound(*_schema, *_current_ck_range); } }(); if (cr != cr_end) { _clustering_rows.emplace_back(rows_position { cr, cr_end }); } } _in_ck_range = true; boost::range::make_heap(_clustering_rows, _heap_cmp); } // Valid if has_more_rows() const rows_entry& pop_clustering_row() { boost::range::pop_heap(_clustering_rows, _heap_cmp); auto& current = _clustering_rows.back(); const rows_entry& e = *current._position; current._position = std::next(current._position); if (current._position == current._end) { _clustering_rows.pop_back(); } else { boost::range::push_heap(_clustering_rows, _heap_cmp); } return e; } // Valid if has_more_rows() const rows_entry& peek_row() const { return *_clustering_rows.front()._position; } bool has_more_rows() const { return !_clustering_rows.empty(); } mutation_fragment_opt read_static_row() { _last_entry = position_in_partition(position_in_partition::static_row_tag_t()); mutation_fragment_opt sr; for (auto&& v : _snapshot->versions()) { if (!v.partition().static_row().empty()) { if (!sr) { sr = mutation_fragment(static_row(v.partition().static_row())); } else { sr->as_mutable_static_row().apply(*_schema, v.partition().static_row()); } } } return sr; } mutation_fragment_opt read_next() { while (has_more_rows()) { auto mf = _range_tombstones.get_next(peek_row()); if (mf) { return mf; } const rows_entry& e = pop_clustering_row(); if (e.dummy()) { continue; } clustering_row result = e; while (has_more_rows() && _eq(peek_row().position(), result.position())) { result.apply(*_schema, pop_clustering_row()); } _last_entry = position_in_partition(result.position()); return mutation_fragment(std::move(result)); } return _range_tombstones.get_next(); } void emplace_mutation_fragment(mutation_fragment&& mfopt) { mfopt.visit(mem_accounter()); push_mutation_fragment(std::move(mfopt)); } void do_fill_buffer() { if (!_last_entry) { auto mfopt = read_static_row(); if (mfopt) { emplace_mutation_fragment(std::move(*mfopt)); } } auto mark = _snapshot->get_change_mark(); if (!_in_ck_range || mark != _change_mark) { refresh_iterators(); _change_mark = mark; } while (!is_end_of_stream() && !is_buffer_full()) { auto mfopt = read_next(); if (mfopt) { emplace_mutation_fragment(std::move(*mfopt)); } else { _in_ck_range = false; _current_ck_range = std::next(_current_ck_range); refresh_iterators(); } } } static tombstone tomb(partition_snapshot& snp) { tombstone t; for (auto& v : snp.versions()) { t.apply(v.partition().partition_tombstone()); } return t; } public: template <typename... Args> partition_snapshot_flat_reader(schema_ptr s, dht::decorated_key dk, lw_shared_ptr<partition_snapshot> snp, query::clustering_key_filter_ranges crr, logalloc::region& region, logalloc::allocating_section& read_section, boost::any pointer_to_container, Args&&... args) : streamed_mutation::impl(s, std::move(dk), tomb(*snp)) , MemoryAccounter(std::forward<Args>(args)...) , _container_guard(std::move(pointer_to_container)) , _ck_ranges(std::move(crr)) , _current_ck_range(_ck_ranges.begin()) , _ck_range_end(_ck_ranges.end()) , _cmp(*s) , _eq(*s) , _heap_cmp(*s) , _snapshot(snp) , _range_tombstones(*s) , _lsa_region(region) , _read_section(read_section) { do_fill_buffer(); } ~partition_snapshot_flat_reader() { maybe_merge_versions(_snapshot, _lsa_region, _read_section); } virtual future<> fill_buffer() override { return _read_section(_lsa_region, [&] { return with_linearized_managed_bytes([&] { do_fill_buffer(); return make_ready_future<>(); }); }); } };
Prepare partition_snapshot_flat_reader
Prepare partition_snapshot_flat_reader This commit creates a copy of partition_snapshot_reader and names it partition_snapshot_flat_reader. This new class will be turned into a flat_mutation_reader in the next commit. The purpose of this commit is to make it easier to review the next commit. Signed-off-by: Piotr Jastrzebski <[email protected]>
C++
agpl-3.0
scylladb/scylla,duarten/scylla,avikivity/scylla,scylladb/scylla,scylladb/scylla,duarten/scylla,scylladb/scylla,avikivity/scylla,duarten/scylla,avikivity/scylla
d5f0094d520be2789662a5148a357b94d037d890
processing/yas_processing_send_signal_processor.cpp
processing/yas_processing_send_signal_processor.cpp
// // yas_processing_send_signal_processor.cpp // #include "yas_processing_send_signal_processor.h" #include "yas_processing_processor.h" #include "yas_processing_module.h" #include "yas_processing_channel.h" #include "yas_processing_signal_event.h" #include "yas_stl_utils.h" using namespace yas; template <typename T> processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<T> handler) { return [handler = std::move(handler)](time::range const &current_time_range, connector_map_t const &input_connectors, connector_map_t const &output_connectors, stream &stream) { if (handler) { for (auto const &connector_pair : output_connectors) { auto const &connector_key = connector_pair.first; auto const &connector = connector_pair.second; auto const &ch_idx = connector.channel_index; if (stream.has_channel(ch_idx)) { auto &channel = stream.channel(ch_idx); processing::time::range combined_time_range = current_time_range; auto predicate = [&current_time_range](auto const &pair) { time const &time = pair.first; auto const &time_range = time.get<time::range>(); if (time_range.can_combine(current_time_range)) { return true; } return false; }; auto const filtered_events = channel.filtered_events<T, signal_event>(predicate); if (filtered_events.size() > 0) { for (auto const &pair : filtered_events) { combined_time_range = *combined_time_range.combine(pair.first); } std::vector<T> vec(combined_time_range.length); for (auto const &pair : filtered_events) { auto const &time_range = pair.first; auto const length = time_range.length; auto const dst_idx = time_range.frame - combined_time_range.frame; auto *dst_ptr = &vec[dst_idx]; signal_event const signal = cast<processing::signal_event>(pair.second); signal.copy_to<T>(dst_ptr, length); } channel.erase_event_if(std::move(predicate)); handler(current_time_range, ch_idx, connector_key, &vec[current_time_range.frame - combined_time_range.frame]); channel.insert_event(time{combined_time_range}, signal_event{std::move(vec)}); return; } } else { stream.add_channel(ch_idx); } std::vector<T> vec(current_time_range.length); handler(current_time_range, ch_idx, connector_key, vec.data()); auto &channel = stream.channel(ch_idx); channel.insert_event(time{current_time_range}, signal_event{std::move(vec)}); } } }; } template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<double>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<float>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<int64_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<int32_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<int16_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<int8_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<uint64_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<uint32_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<uint16_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<uint8_t>);
// // yas_processing_send_signal_processor.cpp // #include "yas_processing_send_signal_processor.h" #include "yas_processing_processor.h" #include "yas_processing_module.h" #include "yas_processing_channel.h" #include "yas_processing_signal_event.h" #include "yas_stl_utils.h" using namespace yas; template <typename T> processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<T> handler) { return [handler = std::move(handler)](time::range const &current_time_range, connector_map_t const &input_connectors, connector_map_t const &output_connectors, stream &stream) { if (handler) { for (auto const &connector_pair : output_connectors) { auto const &connector_key = connector_pair.first; auto const &connector = connector_pair.second; auto const &ch_idx = connector.channel_index; if (stream.has_channel(ch_idx)) { auto &channel = stream.channel(ch_idx); processing::time::range combined_time_range = current_time_range; auto predicate = [&current_time_range](auto const &pair) { time const &time = pair.first; auto const &time_range = time.get<time::range>(); if (time_range.can_combine(current_time_range)) { return true; } return false; }; auto const filtered_events = channel.filtered_events<T, signal_event>(predicate); if (filtered_events.size() > 0) { for (auto const &pair : filtered_events) { combined_time_range = *combined_time_range.combine(pair.first); } std::vector<T> vec(combined_time_range.length); for (auto const &pair : filtered_events) { auto const &time_range = pair.first; auto const length = time_range.length; auto const dst_idx = time_range.frame - combined_time_range.frame; auto *dst_ptr = &vec[dst_idx]; signal_event const signal = cast<processing::signal_event>(pair.second); signal.copy_to<T>(dst_ptr, length); } channel.erase_event_if<T, signal_event>(std::move(predicate)); handler(current_time_range, ch_idx, connector_key, &vec[current_time_range.frame - combined_time_range.frame]); channel.insert_event(time{combined_time_range}, signal_event{std::move(vec)}); return; } } else { stream.add_channel(ch_idx); } std::vector<T> vec(current_time_range.length); handler(current_time_range, ch_idx, connector_key, vec.data()); auto &channel = stream.channel(ch_idx); channel.insert_event(time{current_time_range}, signal_event{std::move(vec)}); } } }; } template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<double>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<float>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<int64_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<int32_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<int16_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<int8_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<uint64_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<uint32_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<uint16_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<uint8_t>);
fix send_signal_processor
fix send_signal_processor
C++
mit
objective-audio/processing,objective-audio/processing,objective-audio/processing
3a0690e6dc760722377ce72d8a6db7df80fc4135
paddle/fluid/inference/analysis/passes/ir_params_sync_among_devices_pass.cc
paddle/fluid/inference/analysis/passes/ir_params_sync_among_devices_pass.cc
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/inference/analysis/passes/ir_params_sync_among_devices_pass.h" #include <string> #include <unordered_set> #include "paddle/fluid/framework/data_layout.h" #include "paddle/fluid/framework/framework.pb.h" #include "paddle/fluid/framework/ir/graph_helper.h" #include "paddle/fluid/framework/lod_tensor.h" #include "paddle/fluid/framework/tensor.h" #include "paddle/fluid/framework/tensor_util.h" #include "paddle/fluid/inference/api/helper.h" #include "paddle/fluid/platform/bfloat16.h" #include "paddle/fluid/platform/enforce.h" #include "paddle/fluid/platform/place.h" #include "paddle/phi/common/data_type.h" namespace paddle { namespace inference { namespace analysis { #ifdef PADDLE_WITH_ASCEND_CL void IrParamsSyncAmongDevicesPass::CopyParamsToNpu(Argument *argument) { if (!argument->use_npu()) return; auto &graph = argument->main_graph(); std::vector<std::string> repetitive_params; if (graph.Has(framework::ir::kRepetitiveParamAttr)) repetitive_params = graph.Get<std::vector<std::string>>( framework::ir::kRepetitiveParamAttr); LOG(INFO) << "Sync params from CPU to NPU"; PADDLE_ENFORCE_EQ(argument->npu_device_id_valid(), true, platform::errors::PreconditionNotMet( "The npu_device_id field should be valid")); platform::Place place = platform::NPUPlace(argument->npu_device_id()); auto *scope = argument->scope_ptr(); std::vector<std::string> all_vars = scope->LocalVarNames(); for (auto &var_name : all_vars) { auto *var = scope->FindLocalVar(var_name); PADDLE_ENFORCE_NOT_NULL( var, platform::errors::PreconditionNotMet("The var should not be nullptr")); if (var->IsType<phi::DenseTensor>() || var->IsType<phi::DenseTensor>()) { auto *t = var->GetMutable<phi::DenseTensor>(); platform::CPUPlace cpu_place; phi::DenseTensor temp_tensor; temp_tensor.Resize(t->dims()); temp_tensor.mutable_data<float>(cpu_place); paddle::framework::TensorCopySync(*t, cpu_place, &temp_tensor); t->clear(); paddle::framework::TensorCopySync(temp_tensor, place, t); } } } #else void IrParamsSyncAmongDevicesPass::CopyParamsToGpu(Argument *argument) { // The parameters are on the cpu, therefore, synchronization is not necessary. if (!argument->use_gpu()) return; auto &graph = argument->main_graph(); std::vector<std::string> repetitive_params; if (graph.Has(framework::ir::kRepetitiveParamAttr)) repetitive_params = graph.Get<std::vector<std::string>>( framework::ir::kRepetitiveParamAttr); LOG(INFO) << "Sync params from CPU to GPU"; PADDLE_ENFORCE_EQ(argument->gpu_device_id_valid(), true, platform::errors::PreconditionNotMet( "The gpu_device_id field should be valid")); platform::Place place = platform::CUDAPlace(argument->gpu_device_id()); auto *scope = argument->scope_ptr(); std::vector<std::string> all_vars = scope->LocalVarNames(); // We get all the vars from local_scope instead of the ProgramDesc. // Because there exists the case that new parameter variables are not added to // the program in the analysis pass. bool reserve_cpu_weights = false; bool with_dynamic_shape = false; if (argument->Has("max_input_shape") && argument->Has("min_input_shape") && argument->Has("optim_input_shape")) { with_dynamic_shape = (argument->max_input_shape().size() > 0 && argument->min_input_shape().size() > 0 && argument->optim_input_shape().size() > 0); } with_dynamic_shape = with_dynamic_shape || (argument->Has("tensorrt_tuned_dynamic_shape") && argument->tensorrt_tuned_dynamic_shape()); if (with_dynamic_shape) { reserve_cpu_weights = true; } int64_t params_total_bytes{0}; for (auto *node : paddle::framework::ir::TopologySortOperations(graph)) { if (!node->IsOp()) continue; if (node->Op()->Type() == "feed" || node->Op()->Type() == "fetch") continue; for (auto *var_node : node->inputs) { if (!var_node->Var()->Persistable()) continue; auto var_name = var_node->Var()->Name(); auto *var = scope->FindLocalVar(var_name); if (var->IsType<phi::DenseTensor>() || var->IsType<phi::DenseTensor>()) { auto *t = var->GetMutable<phi::DenseTensor>(); params_total_bytes += t->numel() * experimental::SizeOf(t->dtype()); } } } { // Alloc memory in pool to store all parameters. phi::DenseTensor ts; ts.mutable_data(place, params_total_bytes); } std::unordered_set<std::string> visited; for (auto *node : paddle::framework::ir::TopologySortOperations(graph)) { if (!node->IsOp()) continue; if (node->Op()->Type() == "feed" || node->Op()->Type() == "fetch") continue; for (auto *var_node : node->inputs) { if (!var_node->Var()->Persistable()) continue; auto var_name = var_node->Var()->Name(); if (std::count( repetitive_params.begin(), repetitive_params.end(), var_name)) { if (!reserve_cpu_weights) { scope->EraseVars({var_name}); } continue; } if (visited.count(var_name)) continue; visited.insert(var_name); auto *var = scope->FindLocalVar(var_name); PADDLE_ENFORCE_NOT_NULL(var, platform::errors::PreconditionNotMet( "The var should not be nullptr")); if (var->IsType<phi::DenseTensor>() || var->IsType<phi::DenseTensor>()) { auto *t = var->GetMutable<phi::DenseTensor>(); auto var_data_type = var_node->Var()->GetDataType(); VLOG(5) << "var_name is " << var_name << ", data type is " << var_data_type; platform::CPUPlace cpu_place; framework::LoDTensor temp_tensor; temp_tensor.Resize(t->dims()); paddle::framework::TensorCopySync(*t, cpu_place, &temp_tensor); t->clear(); paddle::framework::TensorCopySync(temp_tensor, place, t); } } } } #endif void IrParamsSyncAmongDevicesPass::RunImpl(Argument *argument) { PADDLE_ENFORCE_EQ( argument->scope_valid(), true, platform::errors::PreconditionNotMet("The scope field should be valid")); #ifdef PADDLE_WITH_ASCEND_CL if (!argument->use_npu_valid()) return; CopyParamsToNpu(argument); #else if (!argument->use_gpu_valid()) return; CopyParamsToGpu(argument); #endif } std::string IrParamsSyncAmongDevicesPass::repr() const { return "ir-params-sync-among-devices-pass"; } } // namespace analysis } // namespace inference } // namespace paddle
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/inference/analysis/passes/ir_params_sync_among_devices_pass.h" #include <string> #include <unordered_set> #include "paddle/fluid/framework/data_layout.h" #include "paddle/fluid/framework/framework.pb.h" #include "paddle/fluid/framework/ir/graph_helper.h" #include "paddle/fluid/framework/lod_tensor.h" #include "paddle/fluid/framework/tensor.h" #include "paddle/fluid/framework/tensor_util.h" #include "paddle/fluid/inference/api/helper.h" #include "paddle/fluid/platform/bfloat16.h" #include "paddle/fluid/platform/enforce.h" #include "paddle/fluid/platform/place.h" #include "paddle/phi/common/data_type.h" namespace paddle { namespace inference { namespace analysis { #ifdef PADDLE_WITH_ASCEND_CL void IrParamsSyncAmongDevicesPass::CopyParamsToNpu(Argument *argument) { if (!argument->use_npu()) return; auto &graph = argument->main_graph(); std::vector<std::string> repetitive_params; if (graph.Has(framework::ir::kRepetitiveParamAttr)) repetitive_params = graph.Get<std::vector<std::string>>( framework::ir::kRepetitiveParamAttr); LOG(INFO) << "Sync params from CPU to NPU"; PADDLE_ENFORCE_EQ(argument->npu_device_id_valid(), true, platform::errors::PreconditionNotMet( "The npu_device_id field should be valid")); platform::Place place = platform::NPUPlace(argument->npu_device_id()); auto *scope = argument->scope_ptr(); std::vector<std::string> all_vars = scope->LocalVarNames(); for (auto &var_name : all_vars) { auto *var = scope->FindLocalVar(var_name); PADDLE_ENFORCE_NOT_NULL( var, platform::errors::PreconditionNotMet("The var should not be nullptr")); if (var->IsType<phi::DenseTensor>() || var->IsType<phi::DenseTensor>()) { auto *t = var->GetMutable<phi::DenseTensor>(); platform::CPUPlace cpu_place; phi::DenseTensor temp_tensor; temp_tensor.Resize(t->dims()); temp_tensor.mutable_data<float>(cpu_place); paddle::framework::TensorCopySync(*t, cpu_place, &temp_tensor); t->clear(); paddle::framework::TensorCopySync(temp_tensor, place, t); } } } #else void IrParamsSyncAmongDevicesPass::CopyParamsToGpu(Argument *argument) { // The parameters are on the cpu, therefore, synchronization is not necessary. if (!argument->use_gpu()) return; auto &graph = argument->main_graph(); std::vector<std::string> repetitive_params; if (graph.Has(framework::ir::kRepetitiveParamAttr)) repetitive_params = graph.Get<std::vector<std::string>>( framework::ir::kRepetitiveParamAttr); LOG(INFO) << "Sync params from CPU to GPU"; PADDLE_ENFORCE_EQ(argument->gpu_device_id_valid(), true, platform::errors::PreconditionNotMet( "The gpu_device_id field should be valid")); platform::Place place = platform::CUDAPlace(argument->gpu_device_id()); auto *scope = argument->scope_ptr(); std::vector<std::string> all_vars = scope->LocalVarNames(); // We get all the vars from local_scope instead of the ProgramDesc. // Because there exists the case that new parameter variables are not added to // the program in the analysis pass. bool reserve_cpu_weights = false; bool with_dynamic_shape = false; if (argument->Has("max_input_shape") && argument->Has("min_input_shape") && argument->Has("optim_input_shape")) { with_dynamic_shape = (argument->max_input_shape().size() > 0 && argument->min_input_shape().size() > 0 && argument->optim_input_shape().size() > 0); } with_dynamic_shape = with_dynamic_shape || (argument->Has("tensorrt_tuned_dynamic_shape") && argument->tensorrt_tuned_dynamic_shape()); if (with_dynamic_shape) { reserve_cpu_weights = true; } int64_t params_total_bytes{0}; for (auto *node : paddle::framework::ir::TopologySortOperations(graph)) { if (!node->IsOp()) continue; if (node->Op()->Type() == "feed" || node->Op()->Type() == "fetch") continue; for (auto *var_node : node->inputs) { if (!var_node->Var()->Persistable()) continue; auto var_name = var_node->Var()->Name(); auto *var = scope->FindLocalVar(var_name); if (var->IsType<phi::DenseTensor>()) { auto *t = var->GetMutable<phi::DenseTensor>(); params_total_bytes += t->numel() * experimental::SizeOf(t->dtype()); } } } { // Alloc memory in pool to store all parameters. phi::DenseTensor ts; ts.mutable_data(place, params_total_bytes); } std::unordered_set<std::string> visited; for (auto *node : paddle::framework::ir::TopologySortOperations(graph)) { if (!node->IsOp()) continue; if (node->Op()->Type() == "feed" || node->Op()->Type() == "fetch") continue; for (auto *var_node : node->inputs) { if (!var_node->Var()->Persistable()) continue; auto var_name = var_node->Var()->Name(); if (std::count( repetitive_params.begin(), repetitive_params.end(), var_name)) { if (!reserve_cpu_weights) { scope->EraseVars({var_name}); } continue; } if (visited.count(var_name)) continue; visited.insert(var_name); auto *var = scope->FindLocalVar(var_name); PADDLE_ENFORCE_NOT_NULL(var, platform::errors::PreconditionNotMet( "The var should not be nullptr")); if (var->IsType<phi::DenseTensor>() || var->IsType<phi::DenseTensor>()) { auto *t = var->GetMutable<phi::DenseTensor>(); auto var_data_type = var_node->Var()->GetDataType(); VLOG(5) << "var_name is " << var_name << ", data type is " << var_data_type; platform::CPUPlace cpu_place; framework::LoDTensor temp_tensor; temp_tensor.Resize(t->dims()); paddle::framework::TensorCopySync(*t, cpu_place, &temp_tensor); t->clear(); paddle::framework::TensorCopySync(temp_tensor, place, t); } } } } #endif void IrParamsSyncAmongDevicesPass::RunImpl(Argument *argument) { PADDLE_ENFORCE_EQ( argument->scope_valid(), true, platform::errors::PreconditionNotMet("The scope field should be valid")); #ifdef PADDLE_WITH_ASCEND_CL if (!argument->use_npu_valid()) return; CopyParamsToNpu(argument); #else if (!argument->use_gpu_valid()) return; CopyParamsToGpu(argument); #endif } std::string IrParamsSyncAmongDevicesPass::repr() const { return "ir-params-sync-among-devices-pass"; } } // namespace analysis } // namespace inference } // namespace paddle
fix issue (#47250)
fix issue (#47250)
C++
apache-2.0
PaddlePaddle/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,luotao1/Paddle,luotao1/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,PaddlePaddle/Paddle
2f104df29ba3f925bae5525291e5aaaecf5cc28a
ash/wm/coordinate_conversion.cc
ash/wm/coordinate_conversion.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/wm/coordinate_conversion.h" #include "ash/display/display_controller.h" #include "ash/shell.h" #include "ui/aura/client/screen_position_client.h" #include "ui/gfx/display.h" #include "ui/gfx/point.h" #include "ui/gfx/rect.h" #include "ui/gfx/screen.h" namespace ash { namespace wm { aura::Window* GetRootWindowAt(const gfx::Point& point) { const gfx::Display& display = Shell::GetScreen()->GetDisplayNearestPoint(point); DCHECK(display.is_valid()); // TODO(yusukes): Move coordinate_conversion.cc and .h to ui/aura/ once // GetRootWindowForDisplayId() is moved to aura::Env. return Shell::GetInstance()->display_controller()-> GetRootWindowForDisplayId(display.id()); } aura::Window* GetRootWindowMatching(const gfx::Rect& rect) { const gfx::Display& display = Shell::GetScreen()->GetDisplayMatching(rect); return Shell::GetInstance()->display_controller()-> GetRootWindowForDisplayId(display.id()); } void ConvertPointToScreen(aura::Window* window, gfx::Point* point) { aura::client::GetScreenPositionClient(window->GetRootWindow())-> ConvertPointToScreen(window, point); } void ConvertPointFromScreen(aura::Window* window, gfx::Point* point_in_screen) { aura::client::GetScreenPositionClient(window->GetRootWindow())-> ConvertPointFromScreen(window, point_in_screen); } } // namespace wm } // namespace ash
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/wm/coordinate_conversion.h" #include "ash/display/display_controller.h" #include "ash/shell.h" #include "ui/aura/client/screen_position_client.h" #include "ui/gfx/display.h" #include "ui/gfx/point.h" #include "ui/gfx/rect.h" #include "ui/gfx/screen.h" namespace ash { namespace wm { aura::Window* GetRootWindowAt(const gfx::Point& point) { const gfx::Display& display = Shell::GetScreen()->GetDisplayNearestPoint(point); DCHECK(display.is_valid()); // TODO(yusukes): Move coordinate_conversion.cc and .h to ui/aura/ once // GetRootWindowForDisplayId() is moved to aura::Env. return Shell::GetInstance()->display_controller()-> GetRootWindowForDisplayId(display.id()); } aura::Window* GetRootWindowMatching(const gfx::Rect& rect) { const gfx::Display& display = Shell::GetScreen()->GetDisplayMatching(rect); return Shell::GetInstance()->display_controller()-> GetRootWindowForDisplayId(display.id()); } void ConvertPointToScreen(aura::Window* window, gfx::Point* point) { CHECK(window); CHECK(window->GetRootWindow()); CHECK(aura::client::GetScreenPositionClient(window->GetRootWindow())); aura::client::GetScreenPositionClient(window->GetRootWindow())-> ConvertPointToScreen(window, point); } void ConvertPointFromScreen(aura::Window* window, gfx::Point* point_in_screen) { aura::client::GetScreenPositionClient(window->GetRootWindow())-> ConvertPointFromScreen(window, point_in_screen); } } // namespace wm } // namespace ash
Add some null-checks to understand/debug a crash.
ash: Add some null-checks to understand/debug a crash. BUG=358266 [email protected] Review URL: https://codereview.chromium.org/216603009 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@261270 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
Jonekee/chromium.src,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,dednal/chromium.src,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,jaruba/chromium.src,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,littlstar/chromium.src,littlstar/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,ondra-novak/chromium.src,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,Just-D/chromium-1,M4sse/chromium.src,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,Just-D/chromium-1,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,dednal/chromium.src,dednal/chromium.src,ondra-novak/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,Chilledheart/chromium,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,Chilledheart/chromium,Jonekee/chromium.src,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,dednal/chromium.src,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,Just-D/chromium-1,Fireblend/chromium-crosswalk,M4sse/chromium.src,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,markYoungH/chromium.src,dednal/chromium.src,M4sse/chromium.src,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,dednal/chromium.src,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,ltilve/chromium,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,littlstar/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,jaruba/chromium.src,dednal/chromium.src,jaruba/chromium.src,Chilledheart/chromium,ltilve/chromium,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,fujunwei/chromium-crosswalk,M4sse/chromium.src,chuan9/chromium-crosswalk,Chilledheart/chromium,ondra-novak/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,jaruba/chromium.src,fujunwei/chromium-crosswalk,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,ltilve/chromium,Pluto-tv/chromium-crosswalk,ltilve/chromium,Just-D/chromium-1,M4sse/chromium.src,Just-D/chromium-1,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,ltilve/chromium,markYoungH/chromium.src,axinging/chromium-crosswalk,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,fujunwei/chromium-crosswalk,littlstar/chromium.src,hgl888/chromium-crosswalk,dushu1203/chromium.src,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,littlstar/chromium.src,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ltilve/chromium,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,dednal/chromium.src,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,littlstar/chromium.src,Fireblend/chromium-crosswalk,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,M4sse/chromium.src,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,chuan9/chromium-crosswalk,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,ltilve/chromium,dushu1203/chromium.src,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,fujunwei/chromium-crosswalk,jaruba/chromium.src,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk
679196880e2cdfc4b51fd038f13da020c5c2a861
rclcpp/include/rclcpp/node_interfaces/node_base.hpp
rclcpp/include/rclcpp/node_interfaces/node_base.hpp
// Copyright 2016 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef RCLCPP__NODE_INTERFACES__NODE_BASE_HPP_ #define RCLCPP__NODE_INTERFACES__NODE_BASE_HPP_ #include <memory> #include <string> #include <vector> #include "rcl/node.h" #include "rclcpp/context.hpp" #include "rclcpp/macros.hpp" #include "rclcpp/node_interfaces/node_base_interface.hpp" #include "rclcpp/visibility_control.hpp" namespace rclcpp { namespace node_interfaces { /// Implementation of the NodeBase part of the Node API. class NodeBase : public NodeBaseInterface { public: RCLCPP_SMART_PTR_ALIASES_ONLY(NodeBase) RCLCPP_PUBLIC NodeBase( const std::string & node_name, const std::string & namespace_, rclcpp::Context::SharedPtr context, const rcl_node_options_t & rcl_node_options, bool use_intra_process_default, bool enable_topic_statistics_default); RCLCPP_PUBLIC virtual ~NodeBase(); RCLCPP_PUBLIC const char * get_name() const override; RCLCPP_PUBLIC const char * get_namespace() const override; RCLCPP_PUBLIC const char * get_fully_qualified_name() const override; RCLCPP_PUBLIC rclcpp::Context::SharedPtr get_context() override; RCLCPP_PUBLIC rcl_node_t * get_rcl_node_handle() override; RCLCPP_PUBLIC const rcl_node_t * get_rcl_node_handle() const override; RCLCPP_PUBLIC std::shared_ptr<rcl_node_t> get_shared_rcl_node_handle() override; RCLCPP_PUBLIC std::shared_ptr<const rcl_node_t> get_shared_rcl_node_handle() const override; RCLCPP_PUBLIC bool assert_liveliness() const override; RCLCPP_PUBLIC rclcpp::callback_group::CallbackGroup::SharedPtr create_callback_group(rclcpp::callback_group::CallbackGroupType group_type) override; RCLCPP_PUBLIC rclcpp::callback_group::CallbackGroup::SharedPtr get_default_callback_group() override; RCLCPP_PUBLIC bool callback_group_in_node(rclcpp::callback_group::CallbackGroup::SharedPtr group) override; RCLCPP_PUBLIC const std::vector<rclcpp::callback_group::CallbackGroup::WeakPtr> & get_callback_groups() const override; RCLCPP_PUBLIC std::atomic_bool & get_associated_with_executor_atomic() override; RCLCPP_PUBLIC rcl_guard_condition_t * get_notify_guard_condition() override; RCLCPP_PUBLIC std::unique_lock<std::recursive_mutex> acquire_notify_guard_condition_lock() const override; RCLCPP_PUBLIC bool get_use_intra_process_default() const override; bool get_enable_topic_statistics_default() const override; private: RCLCPP_DISABLE_COPY(NodeBase) rclcpp::Context::SharedPtr context_; bool use_intra_process_default_; bool enable_topic_statistics_default_; std::shared_ptr<rcl_node_t> node_handle_; rclcpp::callback_group::CallbackGroup::SharedPtr default_callback_group_; std::vector<rclcpp::callback_group::CallbackGroup::WeakPtr> callback_groups_; std::atomic_bool associated_with_executor_; /// Guard condition for notifying the Executor of changes to this node. mutable std::recursive_mutex notify_guard_condition_mutex_; rcl_guard_condition_t notify_guard_condition_ = rcl_get_zero_initialized_guard_condition(); bool notify_guard_condition_is_valid_; }; } // namespace node_interfaces } // namespace rclcpp #endif // RCLCPP__NODE_INTERFACES__NODE_BASE_HPP_
// Copyright 2016 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef RCLCPP__NODE_INTERFACES__NODE_BASE_HPP_ #define RCLCPP__NODE_INTERFACES__NODE_BASE_HPP_ #include <memory> #include <string> #include <vector> #include "rcl/node.h" #include "rclcpp/context.hpp" #include "rclcpp/macros.hpp" #include "rclcpp/node_interfaces/node_base_interface.hpp" #include "rclcpp/visibility_control.hpp" namespace rclcpp { namespace node_interfaces { /// Implementation of the NodeBase part of the Node API. class NodeBase : public NodeBaseInterface { public: RCLCPP_SMART_PTR_ALIASES_ONLY(NodeBase) RCLCPP_PUBLIC NodeBase( const std::string & node_name, const std::string & namespace_, rclcpp::Context::SharedPtr context, const rcl_node_options_t & rcl_node_options, bool use_intra_process_default, bool enable_topic_statistics_default=false); RCLCPP_PUBLIC virtual ~NodeBase(); RCLCPP_PUBLIC const char * get_name() const override; RCLCPP_PUBLIC const char * get_namespace() const override; RCLCPP_PUBLIC const char * get_fully_qualified_name() const override; RCLCPP_PUBLIC rclcpp::Context::SharedPtr get_context() override; RCLCPP_PUBLIC rcl_node_t * get_rcl_node_handle() override; RCLCPP_PUBLIC const rcl_node_t * get_rcl_node_handle() const override; RCLCPP_PUBLIC std::shared_ptr<rcl_node_t> get_shared_rcl_node_handle() override; RCLCPP_PUBLIC std::shared_ptr<const rcl_node_t> get_shared_rcl_node_handle() const override; RCLCPP_PUBLIC bool assert_liveliness() const override; RCLCPP_PUBLIC rclcpp::callback_group::CallbackGroup::SharedPtr create_callback_group(rclcpp::callback_group::CallbackGroupType group_type) override; RCLCPP_PUBLIC rclcpp::callback_group::CallbackGroup::SharedPtr get_default_callback_group() override; RCLCPP_PUBLIC bool callback_group_in_node(rclcpp::callback_group::CallbackGroup::SharedPtr group) override; RCLCPP_PUBLIC const std::vector<rclcpp::callback_group::CallbackGroup::WeakPtr> & get_callback_groups() const override; RCLCPP_PUBLIC std::atomic_bool & get_associated_with_executor_atomic() override; RCLCPP_PUBLIC rcl_guard_condition_t * get_notify_guard_condition() override; RCLCPP_PUBLIC std::unique_lock<std::recursive_mutex> acquire_notify_guard_condition_lock() const override; RCLCPP_PUBLIC bool get_use_intra_process_default() const override; bool get_enable_topic_statistics_default() const override; private: RCLCPP_DISABLE_COPY(NodeBase) rclcpp::Context::SharedPtr context_; bool use_intra_process_default_; bool enable_topic_statistics_default_; std::shared_ptr<rcl_node_t> node_handle_; rclcpp::callback_group::CallbackGroup::SharedPtr default_callback_group_; std::vector<rclcpp::callback_group::CallbackGroup::WeakPtr> callback_groups_; std::atomic_bool associated_with_executor_; /// Guard condition for notifying the Executor of changes to this node. mutable std::recursive_mutex notify_guard_condition_mutex_; rcl_guard_condition_t notify_guard_condition_ = rcl_get_zero_initialized_guard_condition(); bool notify_guard_condition_is_valid_; }; } // namespace node_interfaces } // namespace rclcpp #endif // RCLCPP__NODE_INTERFACES__NODE_BASE_HPP_
fix build regression (#1078)
fix build regression (#1078) Signed-off-by: Dirk Thomas <19795c8185177e940eedd30ceb2b716a54a3d5dc@users.noreply.github.com>
C++
apache-2.0
ros2/rclcpp,ros2/rclcpp
559db057d54589ee46effa8140a051932729d347
samples/1_Utils/hipBusBandwidth/hipBusBandwidth.cpp
samples/1_Utils/hipBusBandwidth/hipBusBandwidth.cpp
#include <stdio.h> #include <iostream> #include <hip_runtime.h> #include "ResultDatabase.h" // Cmdline parms: const bool p_verbose = false; const bool p_pinned = true; const unsigned int p_iters = 10; #define CHECK_HIP_ERROR() \ { \ hipError_t err = hipGetLastError(); \ if (err != hipSuccess) \ { \ printf("error=%d name=%s at " \ "ln: %d\n ",err,hipGetErrorString(err),__LINE__); \ exit(EXIT_FAILURE); \ } \ } // **************************************************************************** // Function: runBenchmark // // Purpose: // Measures the bandwidth of the bus connecting the host processor to the // OpenCL device. This benchmark repeatedly transfers data chunks of various // sizes across the bus to the OpenCL device, and calculates the bandwidth. // // // Arguments: // // Returns: nothing // // Programmer: Jeremy Meredith // Creation: September 08, 2009 // // Modifications: // Jeremy Meredith, Wed Dec 1 17:05:27 EST 2010 // Added calculation of latency estimate. // Ben Sander - moved to standalone test // // **************************************************************************** void RunBenchmark(ResultDatabase &resultDB) { // Sizes are in kb int nSizes = 20; int sizes[20] = {1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384, 32768,65536,131072,262144,524288}; long long numMaxFloats = 1024 * (sizes[nSizes-1]) / 4; // Create some host memory pattern float *hostMem = NULL; if (p_pinned) { hipMallocHost((void**)&hostMem, sizeof(float) * numMaxFloats); while (hipGetLastError() != hipSuccess) { // drop the size and try again if (p_verbose) std::cout << " - dropping size allocating pinned mem\n"; --nSizes; if (nSizes < 1) { std::cerr << "Error: Couldn't allocated any pinned buffer\n"; return; } numMaxFloats = 1024 * (sizes[nSizes-1]) / 4; hipMallocHost((void**)&hostMem, sizeof(float) * numMaxFloats); } } else { hostMem = new float[numMaxFloats]; } for (int i = 0; i < numMaxFloats; i++) { hostMem[i] = i % 77; } float *device; hipMalloc((void**)&device, sizeof(float) * numMaxFloats); while (hipGetLastError() != hipSuccess) { // drop the size and try again if (p_verbose) std::cout << " - dropping size allocating device mem\n"; --nSizes; if (nSizes < 1) { std::cerr << "Error: Couldn't allocated any device buffer\n"; return; } numMaxFloats = 1024 * (sizes[nSizes-1]) / 4; hipMalloc((void**)&device, sizeof(float) * numMaxFloats); } hipEvent_t start, stop; hipEventCreate(&start); hipEventCreate(&stop); CHECK_HIP_ERROR(); // Three passes, forward and backward both for (int pass = 0; pass < p_iters; pass++) { // store the times temporarily to estimate latency //float times[nSizes]; // Step through sizes forward on even passes and backward on odd for (int i = 0; i < nSizes; i++) { int sizeIndex; if ((pass % 2) == 0) sizeIndex = i; else sizeIndex = (nSizes - 1) - i; int nbytes = sizes[sizeIndex] * 1024; hipEventRecord(start, 0); hipMemcpy(device, hostMem, nbytes, hipMemcpyHostToDevice); hipEventRecord(stop, 0); hipEventSynchronize(stop); float t = 0; hipEventElapsedTime(&t, start, stop); //times[sizeIndex] = t; // Convert to GB/sec if (p_verbose) { std::cerr << "size " << sizes[sizeIndex] << "k took " << t << " ms\n"; } double speed = (double(sizes[sizeIndex]) * 1024. / (1000*1000)) / t; char sizeStr[256]; sprintf(sizeStr, "% 7dkB", sizes[sizeIndex]); resultDB.AddResult("DownloadSpeed", sizeStr, "GB/sec", speed); resultDB.AddResult("DownloadTime", sizeStr, "ms", t); } } // Cleanup hipFree((void*)device); CHECK_HIP_ERROR(); if (p_pinned) { hipFreeHost((void*)hostMem); CHECK_HIP_ERROR(); } else { delete[] hostMem; } hipEventDestroy(start); hipEventDestroy(stop); } int main(int argc, char *argv[]) { ResultDatabase resultDB; RunBenchmark(resultDB); resultDB.DumpSummary(std::cout); resultDB.DumpDetailed(std::cout); }
#include <stdio.h> #include <iostream> #include <hip_runtime.h> #include "ResultDatabase.h" // Cmdline parms: bool p_verbose = false; bool p_pinned = true; int p_iterations = 10; int p_device = 0; int p_detailed = 0; bool p_h2d = true; bool p_d2h = true; #define CHECK_HIP_ERROR() \ { \ hipError_t err = hipGetLastError(); \ if (err != hipSuccess) \ { \ printf("error=%d name=%s at " \ "ln: %d\n ",err,hipGetErrorString(err),__LINE__); \ exit(EXIT_FAILURE); \ } \ } // **************************************************************************** // Function: runBenchmark // // Purpose: // Measures the bandwidth of the bus connecting the host processor to the // OpenCL device. This benchmark repeatedly transfers data chunks of various // sizes across the bus to the OpenCL device, and calculates the bandwidth. // // // Arguments: // // Returns: nothing // // Programmer: Jeremy Meredith // Creation: September 08, 2009 // // Modifications: // Jeremy Meredith, Wed Dec 1 17:05:27 EST 2010 // Added calculation of latency estimate. // Ben Sander - moved to standalone test // // **************************************************************************** void RunBenchmark_H2D(ResultDatabase &resultDB) { // Sizes are in kb int nSizes = 20; int sizes[20] = {1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384, 32768,65536,131072,262144,524288}; long long numMaxFloats = 1024 * (sizes[nSizes-1]) / 4; hipSetDevice(p_device); // Create some host memory pattern float *hostMem = NULL; if (p_pinned) { hipMallocHost((void**)&hostMem, sizeof(float) * numMaxFloats); while (hipGetLastError() != hipSuccess) { // drop the size and try again if (p_verbose) std::cout << " - dropping size allocating pinned mem\n"; --nSizes; if (nSizes < 1) { std::cerr << "Error: Couldn't allocated any pinned buffer\n"; return; } numMaxFloats = 1024 * (sizes[nSizes-1]) / 4; hipMallocHost((void**)&hostMem, sizeof(float) * numMaxFloats); } } else { hostMem = new float[numMaxFloats]; } for (int i = 0; i < numMaxFloats; i++) { hostMem[i] = i % 77; } float *device; hipMalloc((void**)&device, sizeof(float) * numMaxFloats); while (hipGetLastError() != hipSuccess) { // drop the size and try again if (p_verbose) std::cout << " - dropping size allocating device mem\n"; --nSizes; if (nSizes < 1) { std::cerr << "Error: Couldn't allocated any device buffer\n"; return; } numMaxFloats = 1024 * (sizes[nSizes-1]) / 4; hipMalloc((void**)&device, sizeof(float) * numMaxFloats); } hipEvent_t start, stop; hipEventCreate(&start); hipEventCreate(&stop); CHECK_HIP_ERROR(); // Three passes, forward and backward both for (int pass = 0; pass < p_iterations; pass++) { // store the times temporarily to estimate latency //float times[nSizes]; // Step through sizes forward on even passes and backward on odd for (int i = 0; i < nSizes; i++) { int sizeIndex; if ((pass % 2) == 0) sizeIndex = i; else sizeIndex = (nSizes - 1) - i; int nbytes = sizes[sizeIndex] * 1024; hipEventRecord(start, 0); hipMemcpy(device, hostMem, nbytes, hipMemcpyHostToDevice); hipEventRecord(stop, 0); hipEventSynchronize(stop); float t = 0; hipEventElapsedTime(&t, start, stop); //times[sizeIndex] = t; // Convert to GB/sec if (p_verbose) { std::cerr << "size " << sizes[sizeIndex] << "k took " << t << " ms\n"; } double speed = (double(sizes[sizeIndex]) * 1024. / (1000*1000)) / t; char sizeStr[256]; sprintf(sizeStr, "% 7dkB", sizes[sizeIndex]); resultDB.AddResult("DownloadSpeed", sizeStr, "GB/sec", speed); resultDB.AddResult("DownloadTime", sizeStr, "ms", t); } } // Cleanup hipFree((void*)device); CHECK_HIP_ERROR(); if (p_pinned) { hipFreeHost((void*)hostMem); CHECK_HIP_ERROR(); } else { delete[] hostMem; } hipEventDestroy(start); hipEventDestroy(stop); } void RunBenchmark_D2H(ResultDatabase &resultDB) { // Sizes are in kb int nSizes = 20; int sizes[20] = {1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384, 32768,65536,131072,262144,524288}; long long numMaxFloats = 1024 * (sizes[nSizes-1]) / 4; // Create some host memory pattern float *hostMem1; float *hostMem2; if (p_pinned) { hipMallocHost((void**)&hostMem1, sizeof(float)*numMaxFloats); hipError_t err1 = hipGetLastError(); hipMallocHost((void**)&hostMem2, sizeof(float)*numMaxFloats); hipError_t err2 = hipGetLastError(); while (err1 != hipSuccess || err2 != hipSuccess) { // free the first buffer if only the second failed if (err1 == hipSuccess) hipFreeHost((void*)hostMem1); // drop the size and try again if (p_verbose) std::cout << " - dropping size allocating pinned mem\n"; --nSizes; if (nSizes < 1) { std::cerr << "Error: Couldn't allocated any pinned buffer\n"; return; } numMaxFloats = 1024 * (sizes[nSizes-1]) / 4; hipMallocHost((void**)&hostMem1, sizeof(float)*numMaxFloats); err1 = hipGetLastError(); hipMallocHost((void**)&hostMem2, sizeof(float)*numMaxFloats); err2 = hipGetLastError(); } } else { hostMem1 = new float[numMaxFloats]; hostMem2 = new float[numMaxFloats]; } for (int i=0; i<numMaxFloats; i++) hostMem1[i] = i % 77; float *device; hipMalloc((void**)&device, sizeof(float) * numMaxFloats); while (hipGetLastError() != hipSuccess) { // drop the size and try again if (p_verbose) std::cout << " - dropping size allocating device mem\n"; --nSizes; if (nSizes < 1) { std::cerr << "Error: Couldn't allocated any device buffer\n"; return; } numMaxFloats = 1024 * (sizes[nSizes-1]) / 4; hipMalloc((void**)&device, sizeof(float) * numMaxFloats); } hipMemcpy(device, hostMem1, numMaxFloats*sizeof(float), hipMemcpyHostToDevice); hipDeviceSynchronize(); hipEvent_t start, stop; hipEventCreate(&start); hipEventCreate(&stop); CHECK_HIP_ERROR(); // Three passes, forward and backward both for (int pass = 0; pass < p_iterations; pass++) { // store the times temporarily to estimate latency //float times[nSizes]; // Step through sizes forward on even passes and backward on odd for (int i = 0; i < nSizes; i++) { int sizeIndex; if ((pass % 2) == 0) sizeIndex = i; else sizeIndex = (nSizes - 1) - i; int nbytes = sizes[sizeIndex] * 1024; hipEventRecord(start, 0); hipMemcpy(hostMem2, device, nbytes, hipMemcpyDeviceToHost); hipEventRecord(stop, 0); hipEventSynchronize(stop); float t = 0; hipEventElapsedTime(&t, start, stop); //times[sizeIndex] = t; // Convert to GB/sec if (p_verbose) { std::cerr << "size " <<sizes[sizeIndex] << "k took " << t << " ms\n"; } double speed = (double(sizes[sizeIndex]) * 1024. / (1000*1000)) / t; char sizeStr[256]; sprintf(sizeStr, "% 7dkB", sizes[sizeIndex]); resultDB.AddResult("ReadbackSpeed", sizeStr, "GB/sec", speed); resultDB.AddResult("ReadbackTime", sizeStr, "ms", t); } //resultDB.AddResult("ReadbackLatencyEstimate", "1-2kb", "ms", times[0]-(times[1]-times[0])/1.); //resultDB.AddResult("ReadbackLatencyEstimate", "1-4kb", "ms", times[0]-(times[2]-times[0])/3.); //resultDB.AddResult("ReadbackLatencyEstimate", "2-4kb", "ms", times[1]-(times[2]-times[1])/1.); } // Cleanup hipFree((void*)device); CHECK_HIP_ERROR(); if (p_pinned) { hipFreeHost((void*)hostMem1); CHECK_HIP_ERROR(); hipFreeHost((void*)hostMem2); CHECK_HIP_ERROR(); } else { delete[] hostMem1; delete[] hostMem2; hipEventDestroy(start); hipEventDestroy(stop); } } #define failed(...) \ printf ("error: ");\ printf (__VA_ARGS__);\ printf ("\n");\ exit(EXIT_FAILURE); int parseInt(const char *str, int *output) { char *next; *output = strtol(str, &next, 0); return !strlen(next); } void help() { }; int parseStandardArguments(int argc, char *argv[]) { for (int i = 1; i < argc; i++) { const char *arg = argv[i]; if (!strcmp(arg, " ")) { // skip NULL args. } else if (!strcmp(arg, "--iterations") || (!strcmp(arg, "-i"))) { if (++i >= argc || !parseInt(argv[i], &p_iterations)) { failed("Bad iterations argument"); } } else if (!strcmp(arg, "--device") || (!strcmp(arg, "-d"))) { if (++i >= argc || !parseInt(argv[i], &p_device)) { failed("Bad device argument"); } } else if (!strcmp(arg, "--unpinned")) { p_pinned = 0; } else if (!strcmp(arg, "--h2d")) { p_h2d = true; p_d2h = false; } else if (!strcmp(arg, "--d2h")) { p_h2d = false; p_d2h = true; } else if (!strcmp(arg, "--help") || (!strcmp(arg, "-h"))) { help(); } else if (!strcmp(arg, "--verbose")) { p_verbose = 1; } else if (!strcmp(arg, "--detailed")) { p_detailed = 1; } else { failed("Bad argument '%s'", arg); } } return 0; }; int main(int argc, char *argv[]) { parseStandardArguments(argc, argv); if (p_h2d) { ResultDatabase resultDB; RunBenchmark_H2D(resultDB); resultDB.DumpSummary(std::cout); if (p_detailed) { resultDB.DumpDetailed(std::cout); } } if (p_d2h) { ResultDatabase resultDB; RunBenchmark_D2H(resultDB); resultDB.DumpSummary(std::cout); if (p_detailed) { resultDB.DumpDetailed(std::cout); } } }
Add D2H test
Add D2H test
C++
mit
GPUOpen-ProfessionalCompute-Tools/HIP,ROCm-Developer-Tools/HIP,ROCm-Developer-Tools/HIP,GPUOpen-ProfessionalCompute-Tools/HIP,ROCm-Developer-Tools/HIP,GPUOpen-ProfessionalCompute-Tools/HIP,GPUOpen-ProfessionalCompute-Tools/HIP,ROCm-Developer-Tools/HIP,ROCm-Developer-Tools/HIP,GPUOpen-ProfessionalCompute-Tools/HIP
e9aad44f8468bf9ab3a1ccaf6405724dab88a2e5
applicationsSrc/bbCycle/bbCycleBlockCode.cpp
applicationsSrc/bbCycle/bbCycleBlockCode.cpp
/* * BbCycleBlockCode.cpp * * Created on: 26 mars 2013 * Author: dom */ #include <iostream> #include <sstream> #include <boost/asio.hpp> #include <boost/shared_ptr.hpp> #include <stdio.h> #include "scheduler.h" #include "network.h" #include "bbCycleBlockCode.h" #include "bbCycleEvents.h" #include "trace.h" using namespace std; using namespace BlinkyBlocks; #define SYNC_PERIOD (1*1000*1000) #define COLOR_CHANGE_PERIOD_USEC (2.3*1000*1000) #define SIMULATION_DURATION_USEC (10*60*1000*1000) BbCycleBlockCode::BbCycleBlockCode(BlinkyBlocksBlock *host): BlinkyBlocksBlockCode(host) { OUTPUT << "BbCycleBlockCode constructor" << endl; } BbCycleBlockCode::~BbCycleBlockCode() { OUTPUT << "BbCycleBlockCode destructor" << endl; } void BbCycleBlockCode::init() { BlinkyBlocksBlock *bb = (BlinkyBlocksBlock*) hostBlock; stringstream info; Color c = PINK; BlinkyBlocks::getScheduler()->schedule(new SetColorEvent(COLOR_CHANGE_PERIOD_USEC,bb,c)); block2Answer=NULL; received=false; cycle=true; if(hostBlock->blockId==1){ received=true; BlinkyBlocks::getScheduler()->schedule(new SynchronizeEvent(BlinkyBlocks::getScheduler()->now()+SYNC_PERIOD,hostBlock)); info << "This block is the Master Block" << endl; } BlinkyBlocks::getScheduler()->trace(info.str(),hostBlock->blockId); } void BbCycleBlockCode::startup() { stringstream info; delay=0; info << " Starting BbCycleBlockCode in block " << hostBlock->blockId; init(); } void BbCycleBlockCode::processLocalEvent(EventPtr pev) { stringstream info; MessagePtr message; BlinkyBlocksBlock *bb = (BlinkyBlocksBlock*) hostBlock; info.str(""); OUTPUT << bb->blockId << " processLocalEvent: date: "<< BaseSimulator::getScheduler()->now() << " process event " << pev->getEventName() << "(" << pev->eventType << ")" << ", random number : " << pev->randomNumber << endl; switch (pev->eventType) { case EVENT_SET_COLOR: { Color color = (boost::static_pointer_cast<SetColorEvent>(pev))->color; bb->setColor(color); info << "set color "<< color << endl; if (cycle){ color = BLUE; cycle = false; } else{ color = RED; cycle = true; } BlinkyBlocks::getScheduler()->schedule(new SetColorEvent(bb->getTime()+COLOR_CHANGE_PERIOD_USEC+delay,bb,color)); info << "Setcolor scheduled" << endl; received=false; } break; case EVENT_NI_RECEIVE: { message = (boost::static_pointer_cast<NetworkInterfaceReceiveEvent>(pev))->message; P2PNetworkInterface * recvInterface = message->destinationInterface; switch(message->id){ case SYNC_MSG_ID : { SynchroMessage_ptr recvMessage = boost::static_pointer_cast<SynchroMessage>(message); if (!received){ received=true; block2Answer=recvInterface; sendClockToNeighbors(block2Answer,recvMessage->nbhop+1,recvMessage->time); if (recvMessage->time > bb->getTime()-6000*recvMessage->nbhop) delay = recvMessage->time - bb->getTime() + 6000*recvMessage->nbhop; else if ((recvMessage->time + 6000*recvMessage->nbhop) < bb->getTime()){ info << bb->getTime() << " paused for " << bb->getTime()-recvMessage->time << endl; BlinkyBlocks::getScheduler()->trace(info.str(),hostBlock->blockId); bb->clock->pause((bb->getTime()-recvMessage->time),BlinkyBlocks::getScheduler()->now()); } info<<"synchronized"<< bb->getTime() << " / " << recvMessage->time+6000*recvMessage->nbhop << endl; } } break; default: break; } } break; case EVENT_SYNC: { received=true; sendClockToNeighbors(NULL,1,bb->getTime()); uint64_t nextSync = bb->getTime()+SYNC_PERIOD; BlinkyBlocks::getScheduler()->schedule(new SynchronizeEvent(nextSync,bb)); info << "scheduled synchro" << endl; } break; default: ERRPUT << "*** ERROR *** : unknown local event" << endl; break; } BlinkyBlocks::getScheduler()->trace(info.str(),hostBlock->blockId); } BlinkyBlocks::BlinkyBlocksBlockCode* BbCycleBlockCode::buildNewBlockCode(BlinkyBlocksBlock *host) { return(new BbCycleBlockCode(host)); } void BbCycleBlockCode::sendClockToNeighbors (P2PNetworkInterface *p2pExcept, int hop, uint64_t clock){ P2PNetworkInterface * p2p; BlinkyBlocksBlock *bb = (BlinkyBlocksBlock*) hostBlock; for (int i=0; i<6 ; i++) { p2p = bb->getInterface(NeighborDirection::Direction(i)); if (p2p->connectedInterface && p2p!=p2pExcept){ <<<<<<< HEAD uint64_t message = bb->getTime(); ======= SynchroMessage *message = new SynchroMessage(clock, hop); >>>>>>> 0b477109c4ceee33077eeae79fa8d93223c13025 BlinkyBlocks::getScheduler()->schedule(new NetworkInterfaceEnqueueOutgoingEvent (BlinkyBlocks::getScheduler()->now(), message, p2p)); } } } SynchroMessage::SynchroMessage(uint64_t t, int hop) :Message(){ id = SYNC_MSG_ID; time = t; nbhop = hop; } SynchroMessage::~SynchroMessage(){ }
/* * BbCycleBlockCode.cpp * * Created on: 26 mars 2013 * Author: dom */ #include <iostream> #include <sstream> #include <boost/asio.hpp> #include <boost/shared_ptr.hpp> #include <stdio.h> #include "scheduler.h" #include "network.h" #include "bbCycleBlockCode.h" #include "bbCycleEvents.h" #include "trace.h" using namespace std; using namespace BlinkyBlocks; #define SYNC_PERIOD (1*1000*1000) #define COLOR_CHANGE_PERIOD_USEC (2.3*1000*1000) #define SIMULATION_DURATION_USEC (10*60*1000*1000) BbCycleBlockCode::BbCycleBlockCode(BlinkyBlocksBlock *host): BlinkyBlocksBlockCode(host) { OUTPUT << "BbCycleBlockCode constructor" << endl; } BbCycleBlockCode::~BbCycleBlockCode() { OUTPUT << "BbCycleBlockCode destructor" << endl; } void BbCycleBlockCode::init() { BlinkyBlocksBlock *bb = (BlinkyBlocksBlock*) hostBlock; stringstream info; Color c = PINK; BlinkyBlocks::getScheduler()->schedule(new SetColorEvent(COLOR_CHANGE_PERIOD_USEC,bb,c)); block2Answer=NULL; received=false; cycle=true; if(hostBlock->blockId==1){ received=true; BlinkyBlocks::getScheduler()->schedule(new SynchronizeEvent(BlinkyBlocks::getScheduler()->now()+SYNC_PERIOD,hostBlock)); info << "This block is the Master Block" << endl; } BlinkyBlocks::getScheduler()->trace(info.str(),hostBlock->blockId); } void BbCycleBlockCode::startup() { stringstream info; delay=0; info << " Starting BbCycleBlockCode in block " << hostBlock->blockId; init(); } void BbCycleBlockCode::processLocalEvent(EventPtr pev) { stringstream info; MessagePtr message; BlinkyBlocksBlock *bb = (BlinkyBlocksBlock*) hostBlock; info.str(""); OUTPUT << bb->blockId << " processLocalEvent: date: "<< BaseSimulator::getScheduler()->now() << " process event " << pev->getEventName() << "(" << pev->eventType << ")" << ", random number : " << pev->randomNumber << endl; switch (pev->eventType) { case EVENT_SET_COLOR: { Color color = (boost::static_pointer_cast<SetColorEvent>(pev))->color; bb->setColor(color); info << "set color "<< color << endl; if (cycle){ color = BLUE; cycle = false; } else{ color = RED; cycle = true; } BlinkyBlocks::getScheduler()->schedule(new SetColorEvent(bb->getTime()+COLOR_CHANGE_PERIOD_USEC+delay,bb,color)); info << "Setcolor scheduled" << endl; received=false; } break; case EVENT_NI_RECEIVE: { message = (boost::static_pointer_cast<NetworkInterfaceReceiveEvent>(pev))->message; P2PNetworkInterface * recvInterface = message->destinationInterface; switch(message->id){ case SYNC_MSG_ID : { SynchroMessage_ptr recvMessage = boost::static_pointer_cast<SynchroMessage>(message); if (!received){ received=true; block2Answer=recvInterface; sendClockToNeighbors(block2Answer,recvMessage->nbhop+1,recvMessage->time); if (recvMessage->time > bb->getTime()-6000*recvMessage->nbhop) delay = recvMessage->time - bb->getTime() + 6000*recvMessage->nbhop; else if ((recvMessage->time + 6000*recvMessage->nbhop) < bb->getTime()){ info << bb->getTime() << " paused for " << bb->getTime()-recvMessage->time << endl; BlinkyBlocks::getScheduler()->trace(info.str(),hostBlock->blockId); bb->clock->pause((bb->getTime()-recvMessage->time),BlinkyBlocks::getScheduler()->now()); } info<<"synchronized"<< bb->getTime() << " / " << recvMessage->time+6000*recvMessage->nbhop << endl; } } break; default: break; } } break; case EVENT_SYNC: { received=true; sendClockToNeighbors(NULL,1,bb->getTime()); uint64_t nextSync = bb->getTime()+SYNC_PERIOD; BlinkyBlocks::getScheduler()->schedule(new SynchronizeEvent(nextSync,bb)); info << "scheduled synchro" << endl; } break; default: ERRPUT << "*** ERROR *** : unknown local event" << endl; break; } BlinkyBlocks::getScheduler()->trace(info.str(),hostBlock->blockId); } BlinkyBlocks::BlinkyBlocksBlockCode* BbCycleBlockCode::buildNewBlockCode(BlinkyBlocksBlock *host) { return(new BbCycleBlockCode(host)); } void BbCycleBlockCode::sendClockToNeighbors (P2PNetworkInterface *p2pExcept, int hop, uint64_t clock){ P2PNetworkInterface * p2p; BlinkyBlocksBlock *bb = (BlinkyBlocksBlock*) hostBlock; for (int i=0; i<6 ; i++) { p2p = bb->getInterface(NeighborDirection::Direction(i)); if (p2p->connectedInterface && p2p!=p2pExcept){ uint64_t message = bb->getTime(); SynchroMessage *message = new SynchroMessage(clock, hop); BlinkyBlocks::getScheduler()->schedule(new NetworkInterfaceEnqueueOutgoingEvent (BlinkyBlocks::getScheduler()->now(), message, p2p)); } } } SynchroMessage::SynchroMessage(uint64_t t, int hop) :Message(){ id = SYNC_MSG_ID; time = t; nbhop = hop; } SynchroMessage::~SynchroMessage(){ }
Work on clock synchronization : scheduling events with specific delay depending on the clock drifting
Work on clock synchronization : scheduling events with specific delay depending on the clock drifting
C++
apache-2.0
egartner/MR-maze-exploration,egartner/MR-maze-exploration,egartner/MR-maze-exploration,egartner/MR-maze-exploration,egartner/MR-maze-exploration
ed6d0536ec6ff8396618acf36b5349a7ed9d40d9
event/dispatcher.cc
event/dispatcher.cc
// Copyright © 2016 by Donald King <[email protected]> // Available under the MIT License. See LICENSE for details. #include "event/dispatcher.h" #include <algorithm> #include <chrono> #include <condition_variable> #include <deque> #include <exception> #include <iostream> #include <mutex> #include <stdexcept> #include <system_error> #include <thread> #include <tuple> #include <typeinfo> #include "base/cleanup.h" #include "base/logging.h" #include "base/util.h" static thread_local std::size_t l_depth = 0; namespace event { namespace { struct Work { Task* task; CallbackPtr callback; Work(Task* task, CallbackPtr callback) noexcept : task(task), callback(std::move(callback)) {} Work() noexcept : Work(nullptr, nullptr) {} }; static void invoke(base::Lock& lock, std::size_t& busy, std::size_t& done, std::size_t& caught, Work item) noexcept { bool threw = true; ++busy; auto cleanup0 = base::cleanup([&busy, &done, &caught, &threw] { --busy; ++done; if (threw) ++caught; }); lock.unlock(); auto cleanup1 = base::cleanup([&lock] { lock.lock(); }); if (item.task == nullptr || item.task->start()) { try { base::Result result = item.callback->run(); if (item.task != nullptr) item.task->finish(std::move(result)); else result.expect_ok(__FILE__, __LINE__); threw = false; } catch (...) { std::exception_ptr eptr = std::current_exception(); if (item.task != nullptr) item.task->finish_exception(eptr); else LOG_EXCEPTION(eptr); } } item.callback.reset(); } static void invoke(base::Lock& lock, IdleFunction idle) noexcept { if (!idle) return; lock.unlock(); auto cleanup = base::cleanup([&lock] { lock.lock(); }); try { idle(); } catch (...) { LOG_EXCEPTION(std::current_exception()); } } } // anonymous namespace namespace internal { void assert_depth() { CHECK_EQ(l_depth, 0U); } } // namespace internal base::Result Dispatcher::adjust(const DispatcherOptions& opts) noexcept { return base::Result::not_implemented(); } void Dispatcher::shutdown() noexcept {} void Dispatcher::cork() noexcept {} void Dispatcher::uncork() noexcept {} void Dispatcher::donate(bool forever) noexcept {} namespace { // The implementation for inline Dispatchers is fairly minimal. class InlineDispatcher : public Dispatcher { public: InlineDispatcher() noexcept : busy_(0), done_(0), caught_(0) {} DispatcherType type() const noexcept override { return DispatcherType::inline_dispatcher; } void dispatch(Task* task, CallbackPtr callback) override { auto lock = base::acquire_lock(mu_); invoke(lock, busy_, done_, caught_, Work(task, std::move(callback))); } DispatcherStats stats() const noexcept override { auto lock = base::acquire_lock(mu_); DispatcherStats tmp; tmp.active_count = busy_; tmp.completed_count = done_; tmp.caught_exceptions = caught_; return tmp; } private: mutable std::mutex mu_; std::size_t busy_; std::size_t done_; std::size_t caught_; }; // The implementation for async Dispatchers is slightly more complex. class AsyncDispatcher : public Dispatcher { public: AsyncDispatcher(IdleFunction idle) noexcept : idle_(std::move(idle)), busy_(0), done_(0), caught_(0) {} DispatcherType type() const noexcept override { return DispatcherType::async_dispatcher; } void dispatch(Task* task, CallbackPtr callback) override { auto lock = base::acquire_lock(mu_); work_.emplace_back(task, std::move(callback)); } DispatcherStats stats() const noexcept override { auto lock = base::acquire_lock(mu_); DispatcherStats tmp; tmp.pending_count = work_.size(); tmp.active_count = busy_; tmp.completed_count = done_; tmp.caught_exceptions = caught_; return tmp; } void donate(bool forever) noexcept override { internal::assert_depth(); auto lock = base::acquire_lock(mu_); Work item; while (!work_.empty()) { item = std::move(work_.front()); work_.pop_front(); ++l_depth; auto cleanup = base::cleanup([] { --l_depth; }); invoke(lock, busy_, done_, caught_, std::move(item)); } invoke(lock, idle_); } private: mutable std::mutex mu_; std::deque<Work> work_; IdleFunction idle_; std::size_t busy_; std::size_t done_; std::size_t caught_; }; // The threaded implementation of Dispatcher is much more complex than that of // the other two. The basic idea is to match threads to workload. class ThreadPoolDispatcher : public Dispatcher { public: ThreadPoolDispatcher(IdleFunction idle, std::size_t min, std::size_t max) : idle_(std::move(idle)), min_(min), max_(max), desired_(min), current_(0), busy_(0), done_(0), caught_(0), corked_(false) { if (min > max) { LOG(DFATAL) << "BUG: min > max"; max = min; } auto lock = base::acquire_lock(mu_); ensure(); while (current_ < min_) curr_cv_.wait(lock); } ~ThreadPoolDispatcher() noexcept override { shutdown(); } DispatcherType type() const noexcept override { return DispatcherType::threaded_dispatcher; } void dispatch(Task* task, CallbackPtr callback) override { auto lock = base::acquire_lock(mu_); work_.emplace_back(task, std::move(callback)); if (corked_) return; std::size_t n = work_.size(); // HEURISTIC: if queue size is greater than num threads, add a thread. // (Threads that haven't finished starting add to the count.) // This is (intentionally) a fairly aggressive growth policy. if (desired_ < max_ && n >= desired_) { ++desired_; ensure(); } work_cv_.notify_one(); } DispatcherStats stats() const noexcept override { auto lock = base::acquire_lock(mu_); DispatcherStats tmp; tmp.min_workers = min_; tmp.max_workers = max_; tmp.desired_num_workers = desired_; tmp.current_num_workers = current_; tmp.pending_count = work_.size(); tmp.active_count = busy_; tmp.completed_count = done_; tmp.caught_exceptions = caught_; tmp.corked = corked_; return tmp; } void shutdown() noexcept override { auto lock = base::acquire_lock(mu_); min_ = max_ = desired_ = 0; while (current_ > desired_) curr_cv_.wait(lock); } base::Result adjust(const DispatcherOptions& opts) noexcept override { auto lock = base::acquire_lock(mu_); std::size_t min, max; bool has_min, has_max; std::tie(has_min, min) = opts.min_workers(); std::tie(has_max, max) = opts.max_workers(); if (!has_min) min = min_; if (!has_max) max = std::max(min, max_); if (min > max) return base::Result::invalid_argument( "bad event::DispatcherOptions: min_workers > max_workers"); min_ = min; max_ = max; if (desired_ < min_) desired_ = min_; if (desired_ > max_) desired_ = max_; ensure(); // Block until the thread count is within the new bounds. while (current_ < min_) curr_cv_.wait(lock); while (current_ > max_) curr_cv_.wait(lock); return base::Result(); } void cork() noexcept override { auto lock = base::acquire_lock(mu_); CHECK(!corked_); corked_ = true; while (busy_ > 0) busy_cv_.wait(lock); } void uncork() noexcept override { auto lock = base::acquire_lock(mu_); CHECK(corked_); corked_ = false; std::size_t n = work_.size(); n = std::min(n, max_); // HEURISTIC: when uncorking, aggressively spawn 1 thread per callback. if (n > desired_) { desired_ = n; ensure(); } if (n > 1) work_cv_.notify_all(); else if (n == 1) work_cv_.notify_one(); } void donate(bool forever) noexcept override { internal::assert_depth(); auto lock = base::acquire_lock(mu_); if (forever) donate_forever(lock); else donate_once(lock); } private: bool has_work() { return !corked_ && !work_.empty(); } void donate_once(base::Lock& lock) noexcept { Work item; while (has_work()) { item = std::move(work_.front()); work_.pop_front(); ++l_depth; auto cleanup = base::cleanup([] { --l_depth; }); invoke(lock, busy_, done_, caught_, std::move(item)); } if (busy_ == 0) busy_cv_.notify_all(); invoke(lock, idle_); } bool inc_current() noexcept { if (current_ >= desired_) return true; ++current_; curr_cv_.notify_all(); return false; } void dec_current() noexcept { --current_; curr_cv_.notify_all(); } bool should_exit() noexcept { return current_ > desired_; } void donate_forever(base::Lock& lock) noexcept { using MS = std::chrono::milliseconds; static constexpr MS kInitialTimeout = MS(125); static constexpr MS kMaximumTimeout = MS(8000); if (inc_current()) return; auto cleanup0 = base::cleanup([this] { dec_current(); }); Work item; MS ms(kInitialTimeout); while (true) { while (has_work()) { if (should_exit()) return; ms = kInitialTimeout; item = std::move(work_.front()); work_.pop_front(); ++l_depth; auto cleanup1 = base::cleanup([] { --l_depth; }); invoke(lock, busy_, done_, caught_, std::move(item)); } if (busy_ == 0) busy_cv_.notify_all(); if (should_exit()) return; invoke(lock, idle_); if (has_work()) continue; if (work_cv_.wait_for(lock, ms) == std::cv_status::timeout) { // HEURISTIC: If we've waited too long (approx. 2*kMaximumTimeout) with // no work coming from the queue, then reduce the num // threads by one. // // Each worker thread is doing this calculation in parallel, // so if five threads all reach this threshold, then the num // threads will be reduced by five. The net effect is that // all idle threads above the minimum will be aggressively // pruned once sufficient time has passed. if (ms < kMaximumTimeout) { ms *= 2; } else { if (desired_ > min_) { --desired_; return; } } } } } void ensure() { auto closure = [this] { donate(true); }; for (std::size_t i = current_, j = desired_; i < j; ++i) { std::thread t(closure); t.detach(); } } mutable std::mutex mu_; std::condition_variable work_cv_; std::condition_variable curr_cv_; std::condition_variable busy_cv_; std::deque<Work> work_; IdleFunction idle_; std::size_t min_; std::size_t max_; std::size_t desired_; std::size_t current_; std::size_t busy_; std::size_t done_; std::size_t caught_; bool corked_; }; } // anonymous namespace base::Result new_dispatcher(DispatcherPtr* out, const DispatcherOptions& opts) { auto idle = opts.idle_function(); auto type = opts.type(); std::size_t min, max; bool has_min, has_max; std::tie(has_min, min) = opts.min_workers(); std::tie(has_max, max) = opts.max_workers(); switch (type) { case DispatcherType::inline_dispatcher: *out = std::make_shared<InlineDispatcher>(); break; case DispatcherType::unspecified: case DispatcherType::async_dispatcher: *out = std::make_shared<AsyncDispatcher>(std::move(idle)); break; case DispatcherType::threaded_dispatcher: if (!has_min) min = 1; if (!has_max) max = std::max(min, num_cores()); if (min > max) return base::Result::invalid_argument( "bad event::DispatcherOptions: min_workers > max_workers"); *out = std::make_shared<ThreadPoolDispatcher>(std::move(idle), min, max); break; case DispatcherType::system_dispatcher: *out = system_dispatcher(); break; default: return base::Result::not_implemented(); } return base::Result(); } static std::mutex g_sys_mu; static DispatcherPtr* g_sys_i = nullptr; static DispatcherPtr* g_sys_d = nullptr; DispatcherPtr system_inline_dispatcher() { auto lock = base::acquire_lock(g_sys_mu); if (g_sys_i == nullptr) g_sys_i = new DispatcherPtr; if (!*g_sys_i) *g_sys_i = std::make_shared<InlineDispatcher>(); return *g_sys_i; } DispatcherPtr system_dispatcher() { auto lock = base::acquire_lock(g_sys_mu); if (g_sys_d == nullptr) g_sys_d = new DispatcherPtr; if (!*g_sys_d) *g_sys_d = std::make_shared<ThreadPoolDispatcher>(nullptr, 1, num_cores()); return *g_sys_d; } void set_system_dispatcher(DispatcherPtr ptr) { auto lock = base::acquire_lock(g_sys_mu); if (g_sys_d == nullptr) g_sys_d = new DispatcherPtr; g_sys_d->swap(ptr); } } // namespace event
// Copyright © 2016 by Donald King <[email protected]> // Available under the MIT License. See LICENSE for details. #include "event/dispatcher.h" #include <algorithm> #include <chrono> #include <condition_variable> #include <deque> #include <exception> #include <iostream> #include <mutex> #include <stdexcept> #include <system_error> #include <thread> #include <tuple> #include <typeinfo> #include "base/cleanup.h" #include "base/logging.h" #include "base/util.h" static thread_local std::size_t l_depth = 0; namespace event { namespace { struct Work { Task* task; CallbackPtr callback; Work(Task* task, CallbackPtr callback) noexcept : task(task), callback(std::move(callback)) {} Work() noexcept : Work(nullptr, nullptr) {} }; static void invoke(base::Lock& lock, std::size_t& busy, std::size_t& done, std::size_t& caught, Work item) noexcept { bool threw = true; ++busy; auto cleanup = base::cleanup([&busy, &done, &caught, &threw] { --busy; ++done; if (threw) ++caught; }); lock.unlock(); auto reacquire = base::cleanup([&lock] { lock.lock(); }); if (item.task == nullptr || item.task->start()) { try { base::Result result = item.callback->run(); if (item.task != nullptr) item.task->finish(std::move(result)); else result.expect_ok(__FILE__, __LINE__); threw = false; } catch (...) { std::exception_ptr eptr = std::current_exception(); if (item.task != nullptr) item.task->finish_exception(eptr); else LOG_EXCEPTION(eptr); } } item.callback.reset(); } static void invoke(base::Lock& lock, IdleFunction idle) noexcept { if (!idle) return; lock.unlock(); auto reacquire = base::cleanup([&lock] { lock.lock(); }); try { idle(); } catch (...) { LOG_EXCEPTION(std::current_exception()); } } } // anonymous namespace namespace internal { void assert_depth() { CHECK_EQ(l_depth, 0U); } } // namespace internal base::Result Dispatcher::adjust(const DispatcherOptions& opts) noexcept { return base::Result::not_implemented(); } void Dispatcher::shutdown() noexcept {} void Dispatcher::cork() noexcept {} void Dispatcher::uncork() noexcept {} void Dispatcher::donate(bool forever) noexcept {} namespace { // The implementation for inline Dispatchers is fairly minimal. class InlineDispatcher : public Dispatcher { public: InlineDispatcher() noexcept : busy_(0), done_(0), caught_(0) {} DispatcherType type() const noexcept override { return DispatcherType::inline_dispatcher; } void dispatch(Task* task, CallbackPtr callback) override { auto lock = base::acquire_lock(mu_); invoke(lock, busy_, done_, caught_, Work(task, std::move(callback))); } DispatcherStats stats() const noexcept override { auto lock = base::acquire_lock(mu_); DispatcherStats tmp; tmp.active_count = busy_; tmp.completed_count = done_; tmp.caught_exceptions = caught_; return tmp; } private: mutable std::mutex mu_; std::size_t busy_; std::size_t done_; std::size_t caught_; }; // The implementation for async Dispatchers is slightly more complex. class AsyncDispatcher : public Dispatcher { public: AsyncDispatcher(IdleFunction idle) noexcept : idle_(std::move(idle)), busy_(0), done_(0), caught_(0) {} DispatcherType type() const noexcept override { return DispatcherType::async_dispatcher; } void dispatch(Task* task, CallbackPtr callback) override { auto lock = base::acquire_lock(mu_); work_.emplace_back(task, std::move(callback)); } DispatcherStats stats() const noexcept override { auto lock = base::acquire_lock(mu_); DispatcherStats tmp; tmp.pending_count = work_.size(); tmp.active_count = busy_; tmp.completed_count = done_; tmp.caught_exceptions = caught_; return tmp; } void donate(bool forever) noexcept override { internal::assert_depth(); auto lock = base::acquire_lock(mu_); Work item; while (!work_.empty()) { item = std::move(work_.front()); work_.pop_front(); ++l_depth; auto cleanup = base::cleanup([] { --l_depth; }); invoke(lock, busy_, done_, caught_, std::move(item)); } invoke(lock, idle_); } private: mutable std::mutex mu_; std::deque<Work> work_; IdleFunction idle_; std::size_t busy_; std::size_t done_; std::size_t caught_; }; // The threaded implementation of Dispatcher is much more complex than that of // the other two. The basic idea is to match threads to workload. class ThreadPoolDispatcher : public Dispatcher { public: ThreadPoolDispatcher(IdleFunction idle, std::size_t min, std::size_t max) : idle_(std::move(idle)), min_(min), max_(max), desired_(min), current_(0), busy_(0), done_(0), caught_(0), corked_(false) { auto lock1 = base::acquire_lock(mu1_); ensure(lock1); } ~ThreadPoolDispatcher() noexcept override { shutdown(); } DispatcherType type() const noexcept override { return DispatcherType::threaded_dispatcher; } void dispatch(Task* task, CallbackPtr callback) override { auto lock0 = base::acquire_lock(mu0_); std::size_t n = work_.size(); work_.emplace_back(task, std::move(callback)); if (corked_) return; work_cv_.notify_one(); lock0.unlock(); // HEURISTIC: if queue size is greater than num threads, add a thread. // (Threads that haven't finished starting add to the count.) // This is (intentionally) a fairly aggressive growth policy. auto lock1 = base::acquire_lock(mu1_); if (desired_ < max_ && n > desired_) { ++desired_; ensure(lock1); } } DispatcherStats stats() const noexcept override { auto lock0 = base::acquire_lock(mu0_); auto lock1 = base::acquire_lock(mu1_); DispatcherStats tmp; tmp.min_workers = min_; tmp.max_workers = max_; tmp.desired_num_workers = desired_; tmp.current_num_workers = current_; tmp.pending_count = work_.size(); tmp.active_count = busy_; tmp.completed_count = done_; tmp.caught_exceptions = caught_; tmp.corked = corked_; return tmp; } void shutdown() noexcept override { auto lock1 = base::acquire_lock(mu0_); min_ = max_ = desired_ = 0; ensure(lock1); } base::Result adjust(const DispatcherOptions& opts) noexcept override { std::size_t min, max; bool has_min, has_max; std::tie(has_min, min) = opts.min_workers(); std::tie(has_max, max) = opts.max_workers(); auto lock1 = base::acquire_lock(mu1_); if (!has_min) min = min_; if (!has_max) max = std::max(min, max_); if (min > max) return base::Result::invalid_argument( "bad event::DispatcherOptions: min_workers > max_workers"); min_ = min; max_ = max; if (desired_ < min_) desired_ = min_; if (desired_ > max_) desired_ = max_; ensure(lock1); return base::Result(); } void cork() noexcept override { auto lock0 = base::acquire_lock(mu0_); CHECK(!corked_); corked_ = true; while (busy_ != 0) busy_cv_.wait(lock0); } void uncork() noexcept override { auto lock0 = base::acquire_lock(mu0_); CHECK(corked_); corked_ = false; std::size_t n = work_.size(); if (n > 1) work_cv_.notify_all(); else if (n == 1) work_cv_.notify_one(); lock0.unlock(); auto lock1 = base::acquire_lock(mu1_); n = std::min(n, max_); // HEURISTIC: when uncorking, aggressively spawn 1 thread per callback. if (n > desired_) { desired_ = n; ensure(lock1); } } void donate(bool forever) noexcept override { internal::assert_depth(); auto lock0 = base::acquire_lock(mu0_); if (forever) donate_forever(lock0); else donate_once(lock0); } private: struct Monitor { ThreadPoolDispatcher* d; bool is_live; Monitor(const Monitor&) = delete; Monitor(Monitor&&) = delete; Monitor& operator=(const Monitor&) = delete; Monitor& operator=(Monitor&&) = delete; explicit Monitor(ThreadPoolDispatcher* d) noexcept : d(d), is_live(false) { auto lock1 = base::acquire_lock(d->mu1_); inc(lock1); } ~Monitor() noexcept { auto lock1 = base::acquire_lock(d->mu1_); if (is_live) dec(lock1); } bool maybe_exit() noexcept { auto lock1 = base::acquire_lock(d->mu1_); if (d->current_ > d->desired_) { dec(lock1); return true; } return false; } bool too_many() noexcept { auto lock1 = base::acquire_lock(d->mu1_); if (d->desired_ > d->min_) { --d->desired_; dec(lock1); return true; } return false; } void inc(base::Lock& lock1) noexcept { CHECK(!is_live); is_live = true; ++d->current_; if (d->current_ == d->desired_) d->curr_cv_.notify_all(); } void dec(base::Lock& lock1) noexcept { CHECK(is_live); is_live = false; --d->current_; if (d->current_ == d->desired_) d->curr_cv_.notify_all(); } }; bool has_work() { return !corked_ && !work_.empty(); } void donate_once(base::Lock& lock0) noexcept { Work item; while (has_work()) { item = std::move(work_.front()); work_.pop_front(); ++l_depth; auto cleanup = base::cleanup([] { --l_depth; }); invoke(lock0, busy_, done_, caught_, std::move(item)); } if (busy_ == 0) busy_cv_.notify_all(); invoke(lock0, idle_); } void donate_forever(base::Lock& lock0) noexcept { using MS = std::chrono::milliseconds; static constexpr MS kInitialTimeout = MS(125); static constexpr MS kMaximumTimeout = MS(8000); Monitor monitor(this); Work item; MS ms(kInitialTimeout); while (true) { while (has_work()) { if (monitor.maybe_exit()) return; ms = kInitialTimeout; item = std::move(work_.front()); work_.pop_front(); ++l_depth; auto cleanup = base::cleanup([] { --l_depth; }); invoke(lock0, busy_, done_, caught_, std::move(item)); } if (busy_ == 0) busy_cv_.notify_all(); if (monitor.maybe_exit()) return; invoke(lock0, idle_); if (has_work()) continue; if (work_cv_.wait_for(lock0, ms) == std::cv_status::timeout) { // HEURISTIC: If we've waited too long (approx. 2*kMaximumTimeout) with // no work coming from the queue, then reduce the num // threads by one. // // Each worker thread is doing this calculation in parallel, // so if five threads all reach this threshold, then the num // threads will be reduced by five. The net effect is that // all idle threads above the minimum will be aggressively // pruned once sufficient time has passed. if (ms < kMaximumTimeout) { ms *= 2; } else if (monitor.too_many()) { return; } } } } void ensure(base::Lock& lock1) { CHECK_LE(min_, max_); CHECK_LE(min_, desired_); CHECK_LE(desired_, max_); if (current_ < desired_) { // Spin up new threads. std::size_t delta = desired_ - current_; while (delta != 0) { auto closure = [this] { donate(true); }; std::thread(closure).detach(); --delta; } } else if (current_ > desired_) { // Wake up existing threads to self-terminate. lock1.unlock(); auto reacquire = base::cleanup([&lock1] { lock1.lock(); }); auto lock0 = base::acquire_lock(mu0_); work_cv_.notify_all(); } // Block until the thread count has stabilized. while (current_ != desired_) curr_cv_.wait(lock1); CHECK_LE(min_, max_); CHECK_LE(min_, desired_); CHECK_LE(desired_, max_); CHECK_EQ(desired_, current_); } mutable std::mutex mu0_; mutable std::mutex mu1_; std::condition_variable work_cv_; // mu0_: !work_.empty() std::condition_variable busy_cv_; // mu0_: busy_ == 0 std::condition_variable curr_cv_; // mu1_: current_ == desired_ std::deque<Work> work_; // protected by mu0_ IdleFunction idle_; // protected by mu0_ std::size_t min_; // protected by mu1_ std::size_t max_; // protected by mu1_ std::size_t desired_; // protected by mu1_ std::size_t current_; // protected by mu1_ std::size_t busy_; // protected by mu0_ std::size_t done_; // protected by mu0_ std::size_t caught_; // protected by mu0_ bool corked_; // protected by mu0_ }; } // anonymous namespace base::Result new_dispatcher(DispatcherPtr* out, const DispatcherOptions& opts) { auto idle = opts.idle_function(); auto type = opts.type(); std::size_t min, max; bool has_min, has_max; std::tie(has_min, min) = opts.min_workers(); std::tie(has_max, max) = opts.max_workers(); switch (type) { case DispatcherType::inline_dispatcher: *out = std::make_shared<InlineDispatcher>(); break; case DispatcherType::unspecified: case DispatcherType::async_dispatcher: *out = std::make_shared<AsyncDispatcher>(std::move(idle)); break; case DispatcherType::threaded_dispatcher: if (!has_min) min = 1; if (!has_max) max = std::max(min, num_cores()); if (min > max) return base::Result::invalid_argument( "bad event::DispatcherOptions: min_workers > max_workers"); *out = std::make_shared<ThreadPoolDispatcher>(std::move(idle), min, max); break; case DispatcherType::system_dispatcher: *out = system_dispatcher(); break; default: return base::Result::not_implemented(); } return base::Result(); } static std::mutex g_sys_mu; static DispatcherPtr* g_sys_i = nullptr; static DispatcherPtr* g_sys_d = nullptr; DispatcherPtr system_inline_dispatcher() { auto lock = base::acquire_lock(g_sys_mu); if (g_sys_i == nullptr) g_sys_i = new DispatcherPtr; if (!*g_sys_i) *g_sys_i = std::make_shared<InlineDispatcher>(); return *g_sys_i; } DispatcherPtr system_dispatcher() { auto lock = base::acquire_lock(g_sys_mu); if (g_sys_d == nullptr) g_sys_d = new DispatcherPtr; if (!*g_sys_d) *g_sys_d = std::make_shared<ThreadPoolDispatcher>(nullptr, 1, num_cores()); return *g_sys_d; } void set_system_dispatcher(DispatcherPtr ptr) { auto lock = base::acquire_lock(g_sys_mu); if (g_sys_d == nullptr) g_sys_d = new DispatcherPtr; g_sys_d->swap(ptr); } } // namespace event
Refactor threaded dispatcher to split members over two mutexes.
Refactor threaded dispatcher to split members over two mutexes.
C++
mit
chronos-tachyon/mojo,chronos-tachyon/mojo
b14178d6841a1e4e35eb3c6468642ee5a660553d
example/example.cpp
example/example.cpp
#include "AdsLib.h" #include <iostream> #include <iomanip> static void NotifyCallback(const AmsAddr* pAddr, const AdsNotificationHeader* pNotification, uint32_t hUser) { const uint8_t* data = reinterpret_cast<const uint8_t*>(pNotification + 1); std::cout << std::setfill('0') << "NetId: " << pAddr->netId << " hUser 0x" << std::hex << hUser << " sample time: " << std::dec << pNotification->nTimeStamp << " sample size: " << std::dec << pNotification->cbSampleSize << " value:"; for (size_t i = 0; i < pNotification->cbSampleSize; ++i) { std::cout << " 0x" << std::hex << (int)data[i]; } std::cout << '\n'; } uint32_t getHandleByNameExample(std::ostream& out, long port, const AmsAddr& server, const std::string handleName) { uint32_t handle = 0; const long handleStatus = AdsSyncReadWriteReqEx2(port, &server, ADSIGRP_SYM_HNDBYNAME, 0, sizeof(handle), &handle, handleName.size(), handleName.c_str(), nullptr); if (handleStatus) { out << "Create handle for '" << handleName << "' failed with: " << std::dec << handleStatus << '\n'; } return handle; } void releaseHandleExample(std::ostream& out, long port, const AmsAddr& server, uint32_t handle) { const long releaseHandle = AdsSyncWriteReqEx(port, &server, ADSIGRP_SYM_RELEASEHND, 0, sizeof(handle), &handle); if (releaseHandle) { out << "Release handle 0x" << std::hex << handle << "' failed with: 0x" << releaseHandle << '\n'; } } uint32_t getSymbolSize(std::ostream& out, long port, const AmsAddr& server, const std::string handleName) { AdsSymbolEntry symbolEntry; uint32_t bytesRead; const long status = AdsSyncReadWriteReqEx2(port, &server, ADSIGRP_SYM_INFOBYNAMEEX, 0, sizeof(symbolEntry), &symbolEntry, handleName.size(), handleName.c_str(), &bytesRead); if (status) { throw std::runtime_error("Unable to determine symbol size, reading ADS symbol information failed with: " + std::to_string( status)); } return symbolEntry.size; } void notificationExample(std::ostream& out, long port, const AmsAddr& server) { const AdsNotificationAttrib attrib = { 1, ADSTRANS_SERVERCYCLE, 0, {4000000} }; uint32_t hNotify; uint32_t hUser = 0; const long addStatus = AdsSyncAddDeviceNotificationReqEx(port, &server, 0x4020, 4, &attrib, &NotifyCallback, hUser, &hNotify); if (addStatus) { out << "Add device notification failed with: " << std::dec << addStatus << '\n'; return; } std::cout << "Hit ENTER to stop notifications\n"; std::cin.ignore(); const long delStatus = AdsSyncDelDeviceNotificationReqEx(port, &server, hNotify); if (delStatus) { out << "Delete device notification failed with: " << std::dec << delStatus; return; } } void notificationByNameExample(std::ostream& out, long port, const AmsAddr& server) { const AdsNotificationAttrib attrib = { 1, ADSTRANS_SERVERCYCLE, 0, {4000000} }; uint32_t hNotify; uint32_t hUser = 0; uint32_t handle; out << __FUNCTION__ << "():\n"; handle = getHandleByNameExample(out, port, server, "MAIN.byByte[4]"); const long addStatus = AdsSyncAddDeviceNotificationReqEx(port, &server, ADSIGRP_SYM_VALBYHND, handle, &attrib, &NotifyCallback, hUser, &hNotify); if (addStatus) { out << "Add device notification failed with: " << std::dec << addStatus << '\n'; return; } std::cout << "Hit ENTER to stop by name notifications\n"; std::cin.ignore(); const long delStatus = AdsSyncDelDeviceNotificationReqEx(port, &server, hNotify); if (delStatus) { out << "Delete device notification failed with: " << std::dec << delStatus; return; } releaseHandleExample(out, port, server, handle); } void readExample(std::ostream& out, long port, const AmsAddr& server) { uint32_t bytesRead; uint32_t buffer; out << __FUNCTION__ << "():\n"; for (size_t i = 0; i < 8; ++i) { const long status = AdsSyncReadReqEx2(port, &server, 0x4020, 0, sizeof(buffer), &buffer, &bytesRead); if (status) { out << "ADS read failed with: " << std::dec << status << '\n'; return; } out << "ADS read " << std::dec << bytesRead << " bytes, value: 0x" << std::hex << buffer << '\n'; } } void readByNameExample(std::ostream& out, long port, const AmsAddr& server) { static const char handleName[] = "MAIN.byByte[4]"; uint32_t bytesRead; out << __FUNCTION__ << "():\n"; const uint32_t handle = getHandleByNameExample(out, port, server, handleName); const uint32_t bufferSize = getSymbolSize(out, port, server, handleName); const auto buffer = std::unique_ptr<uint8_t>(new uint8_t[bufferSize]); for (size_t i = 0; i < 8; ++i) { const long status = AdsSyncReadReqEx2(port, &server, ADSIGRP_SYM_VALBYHND, handle, bufferSize, buffer.get(), &bytesRead); if (status) { out << "ADS read failed with: " << std::dec << status << '\n'; return; } out << "ADS read " << std::dec << bytesRead << " bytes:" << std::hex; for (size_t i = 0; i < bytesRead; ++i) { out << ' ' << (int)buffer.get()[i]; } out << '\n'; } releaseHandleExample(out, port, server, handle); } void readStateExample(std::ostream& out, long port, const AmsAddr& server) { uint16_t adsState; uint16_t devState; const long status = AdsSyncReadStateReqEx(port, &server, &adsState, &devState); if (status) { out << "ADS read failed with: " << std::dec << status << '\n'; return; } out << "ADS state: " << std::dec << adsState << " devState: " << std::dec << devState << '\n'; } void runExample(std::ostream& out) { static const AmsNetId remoteNetId { 192, 168, 0, 231, 1, 1 }; static const char remoteIpV4[] = "ads-server"; // uncomment and adjust if automatic AmsNetId deduction is not working as expected //AdsSetLocalAddress({192, 168, 0, 1, 1, 1}); // add local route to your EtherCAT Master if (AdsAddRoute(remoteNetId, remoteIpV4)) { out << "Adding ADS route failed, did you specify valid addresses?\n"; return; } // open a new ADS port const long port = AdsPortOpenEx(); if (!port) { out << "Open ADS port failed\n"; return; } const AmsAddr remote { remoteNetId, AMSPORT_R0_PLC_TC3 }; notificationExample(out, port, remote); notificationByNameExample(out, port, remote); readExample(out, port, remote); readByNameExample(out, port, remote); readStateExample(out, port, remote); const long closeStatus = AdsPortCloseEx(port); if (closeStatus) { out << "Close ADS port failed with: " << std::dec << closeStatus << '\n'; } #ifdef _WIN32 // WORKAROUND: On Win7 std::thread::join() called in destructors // of static objects might wait forever... AdsDelRoute(remoteNetId); #endif } int main() { try { runExample(std::cout); } catch (const std::runtime_error& ex) { std::cout << ex.what() << '\n'; } }
#include "AdsLib.h" #include "AdsDevice.h" #include "AdsVariable.h" #include <iostream> #include <iomanip> static void NotifyCallback(const AmsAddr* pAddr, const AdsNotificationHeader* pNotification, uint32_t hUser) { const uint8_t* data = reinterpret_cast<const uint8_t*>(pNotification + 1); std::cout << std::setfill('0') << "NetId: " << pAddr->netId << " hUser 0x" << std::hex << hUser << " sample time: " << std::dec << pNotification->nTimeStamp << " sample size: " << std::dec << pNotification->cbSampleSize << " value:"; for (size_t i = 0; i < pNotification->cbSampleSize; ++i) { std::cout << " 0x" << std::hex << (int)data[i]; } std::cout << '\n'; } uint32_t getHandleByNameExample(std::ostream& out, long port, const AmsAddr& server, const std::string handleName) { uint32_t handle = 0; const long handleStatus = AdsSyncReadWriteReqEx2(port, &server, ADSIGRP_SYM_HNDBYNAME, 0, sizeof(handle), &handle, handleName.size(), handleName.c_str(), nullptr); if (handleStatus) { out << "Create handle for '" << handleName << "' failed with: " << std::dec << handleStatus << '\n'; } return handle; } void releaseHandleExample(std::ostream& out, long port, const AmsAddr& server, uint32_t handle) { const long releaseHandle = AdsSyncWriteReqEx(port, &server, ADSIGRP_SYM_RELEASEHND, 0, sizeof(handle), &handle); if (releaseHandle) { out << "Release handle 0x" << std::hex << handle << "' failed with: 0x" << releaseHandle << '\n'; } } uint32_t getSymbolSize(std::ostream& out, long port, const AmsAddr& server, const std::string handleName) { AdsSymbolEntry symbolEntry; uint32_t bytesRead; const long status = AdsSyncReadWriteReqEx2(port, &server, ADSIGRP_SYM_INFOBYNAMEEX, 0, sizeof(symbolEntry), &symbolEntry, handleName.size(), handleName.c_str(), &bytesRead); if (status) { throw std::runtime_error("Unable to determine symbol size, reading ADS symbol information failed with: " + std::to_string( status)); } return symbolEntry.size; } void notificationExample(std::ostream& out, long port, const AmsAddr& server) { const AdsNotificationAttrib attrib = { 1, ADSTRANS_SERVERCYCLE, 0, {4000000} }; uint32_t hNotify; uint32_t hUser = 0; const long addStatus = AdsSyncAddDeviceNotificationReqEx(port, &server, 0x4020, 4, &attrib, &NotifyCallback, hUser, &hNotify); if (addStatus) { out << "Add device notification failed with: " << std::dec << addStatus << '\n'; return; } std::cout << "Hit ENTER to stop notifications\n"; std::cin.ignore(); const long delStatus = AdsSyncDelDeviceNotificationReqEx(port, &server, hNotify); if (delStatus) { out << "Delete device notification failed with: " << std::dec << delStatus; return; } } void notificationByNameExample(std::ostream& out, long port, const AmsAddr& server) { const AdsNotificationAttrib attrib = { 1, ADSTRANS_SERVERCYCLE, 0, {4000000} }; uint32_t hNotify; uint32_t hUser = 0; uint32_t handle; out << __FUNCTION__ << "():\n"; handle = getHandleByNameExample(out, port, server, "MAIN.byByte[4]"); const long addStatus = AdsSyncAddDeviceNotificationReqEx(port, &server, ADSIGRP_SYM_VALBYHND, handle, &attrib, &NotifyCallback, hUser, &hNotify); if (addStatus) { out << "Add device notification failed with: " << std::dec << addStatus << '\n'; return; } std::cout << "Hit ENTER to stop by name notifications\n"; std::cin.ignore(); const long delStatus = AdsSyncDelDeviceNotificationReqEx(port, &server, hNotify); if (delStatus) { out << "Delete device notification failed with: " << std::dec << delStatus; return; } releaseHandleExample(out, port, server, handle); } static void readExample(std::ostream& out, const AdsDevice& route) { AdsVariable<uint8_t> readVar {route, 0x4020, 0}; out << __FUNCTION__ << "():\n"; for (size_t i = 0; i < 8; ++i) { out << "ADS read " << std::hex << (uint32_t)readVar << '\n'; } } void readByNameExample(std::ostream& out, long port, const AmsAddr& server) { static const char handleName[] = "MAIN.byByte[4]"; uint32_t bytesRead; out << __FUNCTION__ << "():\n"; const uint32_t handle = getHandleByNameExample(out, port, server, handleName); const uint32_t bufferSize = getSymbolSize(out, port, server, handleName); const auto buffer = std::unique_ptr<uint8_t>(new uint8_t[bufferSize]); for (size_t i = 0; i < 8; ++i) { const long status = AdsSyncReadReqEx2(port, &server, ADSIGRP_SYM_VALBYHND, handle, bufferSize, buffer.get(), &bytesRead); if (status) { out << "ADS read failed with: " << std::dec << status << '\n'; return; } out << "ADS read " << std::dec << bytesRead << " bytes:" << std::hex; for (size_t i = 0; i < bytesRead; ++i) { out << ' ' << (int)buffer.get()[i]; } out << '\n'; } releaseHandleExample(out, port, server, handle); } void readStateExample(std::ostream& out, long port, const AmsAddr& server) { uint16_t adsState; uint16_t devState; const long status = AdsSyncReadStateReqEx(port, &server, &adsState, &devState); if (status) { out << "ADS read failed with: " << std::dec << status << '\n'; return; } out << "ADS state: " << std::dec << adsState << " devState: " << std::dec << devState << '\n'; } void runExample(std::ostream& out) { static const AmsNetId remoteNetId { 192, 168, 0, 231, 1, 1 }; static const char remoteIpV4[] = "ads-server"; // uncomment and adjust if automatic AmsNetId deduction is not working as expected //AdsSetLocalAddress({192, 168, 0, 1, 1, 1}); // add local route to your EtherCAT Master if (AdsAddRoute(remoteNetId, remoteIpV4)) { out << "Adding ADS route failed, did you specify valid addresses?\n"; return; } // open a new ADS port const long port = AdsPortOpenEx(); if (!port) { out << "Open ADS port failed\n"; return; } const AmsAddr remote { remoteNetId, AMSPORT_R0_PLC_TC3 }; AdsDevice route {remoteIpV4, remoteNetId, AMSPORT_R0_PLC_TC3}; notificationExample(out, port, remote); notificationByNameExample(out, port, remote); readExample(out, route); readByNameExample(out, port, remote); readStateExample(out, port, remote); const long closeStatus = AdsPortCloseEx(port); if (closeStatus) { out << "Close ADS port failed with: " << std::dec << closeStatus << '\n'; } #ifdef _WIN32 // WORKAROUND: On Win7 std::thread::join() called in destructors // of static objects might wait forever... AdsDelRoute(remoteNetId); #endif } int main() { try { runExample(std::cout); } catch (const std::runtime_error& ex) { std::cout << ex.what() << '\n'; } }
convert readExample to use OOI
example: convert readExample to use OOI
C++
mit
Beckhoff/ADS,Beckhoff/ADS,Beckhoff/ADS,Beckhoff/ADS
fc337922accbb6fed8386024d80b3e4a15d43043
deps/ox/src/ox/std/strops.hpp
deps/ox/src/ox/std/strops.hpp
/* * Copyright 2015 - 2018 [email protected] * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "math.hpp" #include "types.hpp" #include "typetraits.hpp" template<typename T1, typename T2> constexpr char *ox_strncpy(T1 dest, T2 src, std::size_t maxLen) noexcept { for (std::size_t i = 0; i < maxLen && src[i]; i++) { dest[i] = src[i]; } return dest; } [[nodiscard]] constexpr auto ox_strnlen(const char *str1, std::size_t maxLen) noexcept { std::size_t len = 0; for (; len < maxLen && str1[len]; len++); return len; } template<typename T> [[nodiscard]] constexpr auto ox_strlen(T str1) noexcept { std::size_t len = 0; for (; str1[len]; len++); return len; } template<typename T1, typename T2> [[nodiscard]] constexpr int ox_strcmp(T1 str1, T2 str2) noexcept { auto retval = 0; auto i = 0; while (str1[i] || str2[i]) { if (str1[i] < str2[i]) { retval = -1; break; } else if (str1[i] > str2[i]) { retval = 1; break; } i++; } return retval; } [[nodiscard]] constexpr int ox_strncmp(const char *str1, const char *str2, std::size_t len) noexcept { auto retval = 0; std::size_t i = 0; while (i < len && (str1[i] || str2[i])) { if (str1[i] < str2[i]) { retval = -1; break; } else if (str1[i] > str2[i]) { retval = 1; break; } i++; } return retval; } [[nodiscard]] constexpr const char *ox_strchr(const char *str, int character, std::size_t maxLen = 0xFFFFFFFF) noexcept { for (std::size_t i = 0; i <= maxLen; i++) { if (str[i] == character) { return &str[i]; } else if (str[i] == 0) { return nullptr; } } return nullptr; } [[nodiscard]] constexpr char *ox_strchr(char *str, int character, std::size_t maxLen = 0xFFFFFFFF) noexcept { for (std::size_t i = 0; i < maxLen; i++) { if (str[i] == character) { return &str[i]; } else if (str[i] == 0) { return nullptr; } } return nullptr; } [[nodiscard]] constexpr int ox_lastIndexOf(const char *str, int character, std::size_t maxLen = 0xFFFFFFFF) noexcept { int retval = -1; for (std::size_t i = 0; i < maxLen && str[i]; i++) { if (str[i] == character) { retval = i; } } return retval; } [[nodiscard]] constexpr int ox_lastIndexOf(char *str, int character, std::size_t maxLen = 0xFFFFFFFF) noexcept { int retval = -1; for (std::size_t i = 0; i < maxLen && str[i]; i++) { if (str[i] == character) { retval = i; } } return retval; } [[nodiscard]] constexpr int ox_atoi(const char *str) noexcept { int total = 0; int multiplier = 1; for (auto i = static_cast<int64_t>(ox_strlen(str)) - 1; i != -1; i--) { total += (str[i] - '0') * multiplier; multiplier *= 10; } return total; } template<typename Integer, typename T> constexpr T ox_itoa(Integer v, T str) noexcept { if (v) { auto mod = 1000000000000000000; constexpr auto base = 10; auto it = 0; if (v < 0) { str[it] = '-'; it++; } while (mod) { auto digit = v / mod; v %= mod; mod /= base; if (it or digit) { int start = '0'; if (digit >= 10) { start = 'a'; digit -= 10; } str[it] = start + digit; it++; } } str[it] = 0; } else { // 0 is a special case str[0] = '0'; str[1] = 0; } return str; }
/* * Copyright 2015 - 2018 [email protected] * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "math.hpp" #include "types.hpp" #include "typetraits.hpp" template<typename T1, typename T2> constexpr char *ox_strncpy(T1 dest, T2 src, std::size_t maxLen) noexcept { std::size_t i = 0; while (i < maxLen && src[i]) { dest[i] = src[i]; ++i; } // set null terminator dest[i] = 0; return dest; } [[nodiscard]] constexpr auto ox_strnlen(const char *str1, std::size_t maxLen) noexcept { std::size_t len = 0; for (; len < maxLen && str1[len]; len++); return len; } template<typename T> [[nodiscard]] constexpr auto ox_strlen(T str1) noexcept { std::size_t len = 0; for (; str1[len]; len++); return len; } template<typename T1, typename T2> [[nodiscard]] constexpr int ox_strcmp(T1 str1, T2 str2) noexcept { auto retval = 0; auto i = 0; while (str1[i] || str2[i]) { if (str1[i] < str2[i]) { retval = -1; break; } else if (str1[i] > str2[i]) { retval = 1; break; } i++; } return retval; } [[nodiscard]] constexpr int ox_strncmp(const char *str1, const char *str2, const std::size_t maxLen) noexcept { auto retval = 0; std::size_t i = 0; while (i < maxLen && (str1[i] || str2[i])) { if (str1[i] < str2[i]) { retval = -1; break; } else if (str1[i] > str2[i]) { retval = 1; break; } i++; } return retval; } [[nodiscard]] constexpr const char *ox_strchr(const char *str, int character, std::size_t maxLen = 0xFFFFFFFF) noexcept { for (std::size_t i = 0; i <= maxLen; i++) { if (str[i] == character) { return &str[i]; } else if (str[i] == 0) { return nullptr; } } return nullptr; } [[nodiscard]] constexpr char *ox_strchr(char *str, int character, std::size_t maxLen = 0xFFFFFFFF) noexcept { for (std::size_t i = 0; i < maxLen; i++) { if (str[i] == character) { return &str[i]; } else if (str[i] == 0) { return nullptr; } } return nullptr; } [[nodiscard]] constexpr int ox_lastIndexOf(const char *str, int character, std::size_t maxLen = 0xFFFFFFFF) noexcept { int retval = -1; for (std::size_t i = 0; i < maxLen && str[i]; i++) { if (str[i] == character) { retval = i; } } return retval; } [[nodiscard]] constexpr int ox_lastIndexOf(char *str, int character, std::size_t maxLen = 0xFFFFFFFF) noexcept { int retval = -1; for (std::size_t i = 0; i < maxLen && str[i]; i++) { if (str[i] == character) { retval = i; } } return retval; } [[nodiscard]] constexpr int ox_atoi(const char *str) noexcept { int total = 0; int multiplier = 1; for (auto i = static_cast<int64_t>(ox_strlen(str)) - 1; i != -1; i--) { total += (str[i] - '0') * multiplier; multiplier *= 10; } return total; } template<typename Integer, typename T> constexpr T ox_itoa(Integer v, T str) noexcept { if (v) { auto mod = 1000000000000000000; constexpr auto base = 10; auto it = 0; if (v < 0) { str[it] = '-'; it++; } while (mod) { auto digit = v / mod; v %= mod; mod /= base; if (it || digit) { int start = '0'; if (digit >= 10) { start = 'a'; digit -= 10; } str[it] = start + digit; it++; } } str[it] = 0; } else { // 0 is a special case str[0] = '0'; str[1] = 0; } return str; }
Add missing null terminator to ox_strncpy
[ox/std] Add missing null terminator to ox_strncpy
C++
mpl-2.0
wombatant/nostalgia,wombatant/nostalgia,wombatant/nostalgia
4a532e557e91f129d65752ef737e637c28568da2
radio.cpp
radio.cpp
#include <iostream> #include <iomanip> #include <chrono> #include <arm_neon.h> #include <stdlib.h> #include <inttypes.h> #include <thread> #include <mutex> #include <condition_variable> #include <signal.h> std::mutex m ; std::condition_variable cv ; std::chrono::high_resolution_clock::time_point mid ; std::chrono::high_resolution_clock::time_point reset ; int32x4_t va; int32_t a ; int32_t * ptr; int32_t n = 2500; int64_t size = sizeof(a)*n; int32_t mm = n-4; void inline sig_handler(int sign) { free(ptr); std::cout << "Received signal. aborting.\n" ; exit(-1); } void inline boost_song() { using namespace std::chrono ; int i{0} ; while( true ) { std::unique_lock<std::mutex> lk{m} ; cv.wait( lk ) ; while( high_resolution_clock::now() < mid ) { int32_t var[4] = { *(ptr + i), *(ptr + i + 2), *(ptr + i + 3), *(ptr + i + 4) }; va = vld1q_s32(var); i++; } if(i==mm) i=0; std::this_thread::sleep_until( reset ) ; } } int init_memory(void) { ptr = (int32_t *)malloc(size); if( ptr == NULL ){ std::cout << "Malloc Error\n"; return -1; } for(int i=0; i<=n; i++){ ptr[i] = i; } return 0; } void square_am_signal(float time, float frequency) { using namespace std::chrono ; std::cout << "Playing / " << time << " seconds / " << frequency << " Hz\n" ; seconds const sec{1} ; nanoseconds const nsec{ sec } ; using rep = nanoseconds::rep ; auto nsec_per_sec = nsec.count() ; nanoseconds const period( static_cast<rep>( nsec_per_sec / frequency) ) ; auto start = high_resolution_clock::now() ; auto const end = start + nanoseconds( static_cast<rep>(time * nsec_per_sec) ) ; while (high_resolution_clock::now() < end) { mid = start + period / 2 ; reset = start + period ; cv.notify_all() ; std::this_thread::sleep_until( reset ) ; start = reset; } } int main(){ signal(SIGINT, sig_handler); init_memory(); for ( unsigned i = 0 ; i < std::thread::hardware_concurrency() ; ++i ) { std::thread t( boost_song ) ; t.detach() ; } while (1) { square_am_signal(0.400, 2673); square_am_signal(0.400, 2349); square_am_signal(0.400, 2093); square_am_signal(0.400, 2349); square_am_signal(0.400, 2673); square_am_signal(0.400, 2673); square_am_signal(0.790, 2673); square_am_signal(0.400, 2349); square_am_signal(0.400, 2349); square_am_signal(0.790, 2349); square_am_signal(0.400, 2673); square_am_signal(0.400, 3136); square_am_signal(0.790, 3136); square_am_signal(0.400, 2673); square_am_signal(0.400, 2349); square_am_signal(0.400, 2093); square_am_signal(0.400, 2349); square_am_signal(0.400, 2673); square_am_signal(0.400, 2673); square_am_signal(0.400, 2673); square_am_signal(0.400, 2673); square_am_signal(0.400, 2349); square_am_signal(0.400, 2349); square_am_signal(0.400, 2673); square_am_signal(0.400, 2349); square_am_signal(0.790, 2093); } free(ptr); return 0; }
#include <iostream> #include <iomanip> #include <chrono> #include <arm_neon.h> #include <stdlib.h> #include <inttypes.h> #include <thread> #include <mutex> #include <condition_variable> #include <signal.h> std::mutex m ; std::condition_variable cv ; std::chrono::high_resolution_clock::time_point mid ; std::chrono::high_resolution_clock::time_point reset ; int32x4_t va; int32_t a ; int32_t * ptr; int32_t n = 2500; int64_t size = sizeof(a)*n; int32_t mm = n-4; void inline sig_handler(int sign) { free(ptr); std::cout << "Received signal. aborting.\n" ; exit(-1); } void inline boost_song() { using namespace std::chrono ; int i{0} ; while( true ) { std::unique_lock<std::mutex> lk{m} ; cv.wait( lk ) ; while( high_resolution_clock::now() < mid ) { int32_t var[4] = { *(ptr + i), *(ptr + i + 2), *(ptr + i + 3), *(ptr + i + 4) }; va = vld1q_s32(var); i++; if(i==mm) i=0; } std::this_thread::sleep_until( reset ) ; } } int init_memory(void) { ptr = (int32_t *)malloc(size); if( ptr == NULL ){ std::cout << "Malloc Error\n"; return -1; } for(int i=0; i<=n; i++){ ptr[i] = i; } return 0; } void square_am_signal(float time, float frequency) { using namespace std::chrono ; std::cout << "Playing / " << time << " seconds / " << frequency << " Hz\n" ; seconds const sec{1} ; nanoseconds const nsec{ sec } ; using rep = nanoseconds::rep ; auto nsec_per_sec = nsec.count() ; nanoseconds const period( static_cast<rep>( nsec_per_sec / frequency) ) ; auto start = high_resolution_clock::now() ; auto const end = start + nanoseconds( static_cast<rep>(time * nsec_per_sec) ) ; while (high_resolution_clock::now() < end) { mid = start + period / 2 ; reset = start + period ; cv.notify_all() ; std::this_thread::sleep_until( reset ) ; start = reset; } } int main(){ signal(SIGINT, sig_handler); init_memory(); for ( unsigned i = 0 ; i < std::thread::hardware_concurrency() ; ++i ) { std::thread t( boost_song ) ; t.detach() ; } while (1) { square_am_signal(0.400, 2673); square_am_signal(0.400, 2349); square_am_signal(0.400, 2093); square_am_signal(0.400, 2349); square_am_signal(0.400, 2673); square_am_signal(0.400, 2673); square_am_signal(0.790, 2673); square_am_signal(0.400, 2349); square_am_signal(0.400, 2349); square_am_signal(0.790, 2349); square_am_signal(0.400, 2673); square_am_signal(0.400, 3136); square_am_signal(0.790, 3136); square_am_signal(0.400, 2673); square_am_signal(0.400, 2349); square_am_signal(0.400, 2093); square_am_signal(0.400, 2349); square_am_signal(0.400, 2673); square_am_signal(0.400, 2673); square_am_signal(0.400, 2673); square_am_signal(0.400, 2673); square_am_signal(0.400, 2349); square_am_signal(0.400, 2349); square_am_signal(0.400, 2673); square_am_signal(0.400, 2349); square_am_signal(0.790, 2093); } free(ptr); return 0; }
fix segfault error
fix segfault error
C++
mit
gorillanet/system-bus-radio-neon
e3dd14152abfdda47888847b64d8b1fd4af7c834
gecode/kernel/shared-array.hpp
gecode/kernel/shared-array.hpp
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Christian Schulte <[email protected]> * Guido Tack <[email protected]> * * Contributing authors: * Gregory Crosswhite <[email protected]> * * Copyright: * Gregory Crosswhite, 2011 * Christian Schulte, 2003 * Guido Tack, 2004 * * Last modified: * $Date$ by $Author$ * $Revision$ * * This file is part of Gecode, the generic constraint * development environment: * http://www.gecode.org * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ #include <cstdarg> #include <iostream> #include <sstream> namespace Gecode { /** * \brief Shared array with arbitrary number of elements * * Sharing is implemented by reference counting: the same elements * are shared among several objects. * */ template<class T> class SharedArray : public SharedHandle { protected: /// Implementation of object for shared arrays class SAO : public SharedHandle::Object { private: /// Elements T* a; /// Number of elements int n; public: /// Allocate for \a n elements SAO(int n); /// Create copy of elements virtual SharedHandle::Object* copy(void) const; /// Delete object virtual ~SAO(void); /// Access element at position \a i T& operator [](int i); /// Access element at position \a i const T& operator [](int i) const; /// Return number of elements int size(void) const; }; public: /// \name Associated types //@{ /// Type of the view stored in this array typedef T value_type; /// Type of a reference to the value type typedef T& reference; /// Type of a constant reference to the value type typedef const T& const_reference; /// Type of a pointer to the value type typedef T* pointer; /// Type of a read-only pointer to the value type typedef const T* const_pointer; /// Type of the iterator used to iterate through this array's elements typedef T* iterator; /// Type of the iterator used to iterate read-only through this array's elements typedef const T* const_iterator; /// Type of the iterator used to iterate backwards through this array's elements typedef std::reverse_iterator<T*> reverse_iterator; /// Type of the iterator used to iterate backwards and read-only through this array's elements typedef std::reverse_iterator<const T*> const_reverse_iterator; //@} /** * \brief Construct as not yet intialized * * The only member functions that can be used on a constructed but not * yet initialized shared array is init and the assignment operator . * */ SharedArray(void); /// Initialize as array with \a n elements SharedArray(int n); /** * \brief Initialize as array with \a n elements * * This member function can only be used once and only if the shared * array has been constructed with the default constructor. * */ void init(int n); /// Initialize from shared array \a a (share elements) SharedArray(const SharedArray& a); /// Initialize from argument array \a a SharedArray(const ArgArrayBase<T>& a); /// Access element at position \a i T& operator [](int i); /// Access element at position \a i const T& operator [](int i) const; /// Return number of elements int size(void) const; /// \name Array iteration //@{ /// Return an iterator at the beginning of the array iterator begin(void); /// Return a read-only iterator at the beginning of the array const_iterator begin(void) const; /// Return an iterator past the end of the array iterator end(void); /// Return a read-only iterator past the end of the array const_iterator end(void) const; /// Return a reverse iterator at the end of the array reverse_iterator rbegin(void); /// Return a reverse and read-only iterator at the end of the array const_reverse_iterator rbegin(void) const; /// Return a reverse iterator past the beginning of the array reverse_iterator rend(void); /// Return a reverse and read-only iterator past the beginning of the array const_reverse_iterator rend(void) const; //@} }; /** * \brief Print array elements enclosed in curly brackets * \relates SharedArray */ template<class Char, class Traits, class T> std::basic_ostream<Char,Traits>& operator <<(std::basic_ostream<Char,Traits>& os, const SharedArray<T>& x); /* * Implementation * */ /* * Shared arrays * */ template<class T> forceinline SharedArray<T>::SAO::SAO(int n0) : n(n0) { a = (n>0) ? heap.alloc<T>(n) : NULL; } template<class T> SharedHandle::Object* SharedArray<T>::SAO::copy(void) const { SAO* o = new SAO(n); for (int i=n; i--;) o->a[i] = a[i]; return o; } template<class T> SharedArray<T>::SAO::~SAO(void) { if (n>0) { heap.free<T>(a,n); } } template<class T> forceinline T& SharedArray<T>::SAO::operator [](int i) { assert((i>=0) && (i<n)); return a[i]; } template<class T> forceinline const T& SharedArray<T>::SAO::operator [](int i) const { assert((i>=0) && (i<n)); return a[i]; } template<class T> forceinline int SharedArray<T>::SAO::size(void) const { return n; } template<class T> forceinline SharedArray<T>::SharedArray(void) {} template<class T> forceinline SharedArray<T>::SharedArray(int n) : SharedHandle(new SAO(n)) {} template<class T> forceinline SharedArray<T>::SharedArray(const SharedArray<T>& sa) : SharedHandle(sa) {} template<class T> forceinline void SharedArray<T>::init(int n) { assert(object() == NULL); object(new SAO(n)); } template<class T> forceinline T& SharedArray<T>::operator [](int i) { assert(object() != NULL); return (*static_cast<SAO*>(object()))[i]; } template<class T> forceinline const T& SharedArray<T>::operator [](int i) const { assert(object() != NULL); return (*static_cast<SAO*>(object()))[i]; } template<class T> forceinline SharedArray<T>::SharedArray(const ArgArrayBase<T>& a) : SharedHandle(new SAO(a.size())) { for (int i=a.size(); i--; ) operator [](i)=a[i]; } template<class T> forceinline int SharedArray<T>::size(void) const { assert(object() != NULL); return static_cast<SAO*>(object())->size(); } template<class T> forceinline typename SharedArray<T>::iterator SharedArray<T>::begin(void) { assert(object() != NULL); return &(*static_cast<SAO*>(object()))[0]; } template<class T> forceinline typename SharedArray<T>::const_iterator SharedArray<T>::begin(void) const { assert(object() != NULL); return &(*static_cast<SAO*>(object()))[0]; } template<class T> forceinline typename SharedArray<T>::iterator SharedArray<T>::end(void) { assert(object() != NULL); return &(*static_cast<SAO*>(object()))[0] + size(); } template<class T> forceinline typename SharedArray<T>::const_iterator SharedArray<T>::end(void) const { assert(object() != NULL); return &(*static_cast<SAO*>(object()))[0] + size(); } template<class T> forceinline typename SharedArray<T>::reverse_iterator SharedArray<T>::rbegin(void) { assert(object() != NULL); return reverse_iterator(&(*static_cast<SAO*>(object()))[0] + size()); } template<class T> forceinline typename SharedArray<T>::const_reverse_iterator SharedArray<T>::rbegin(void) const { assert(object() != NULL); return const_reverse_iterator(&(*static_cast<SAO*>(object()))[0] + size()); } template<class T> forceinline typename SharedArray<T>::reverse_iterator SharedArray<T>::rend(void) { assert(object() != NULL); return reverse_iterator(&(*static_cast<SAO*>(object()))[0]); } template<class T> forceinline typename SharedArray<T>::const_reverse_iterator SharedArray<T>::rend(void) const { assert(object() != NULL); return const_reverse_iterator(&(*static_cast<SAO*>(object()))[0]); } template<class Char, class Traits, class T> std::basic_ostream<Char,Traits>& operator <<(std::basic_ostream<Char,Traits>& os, const SharedArray<T>& x) { std::basic_ostringstream<Char,Traits> s; s.copyfmt(os); s.width(0); s << '{'; if (x.size() > 0) { s << x[0]; for (int i=1; i<x.size(); i++) s << ", " << x[i]; } s << '}'; return os << s.str(); } } // STATISTICS: kernel-other
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Christian Schulte <[email protected]> * Guido Tack <[email protected]> * * Contributing authors: * Gregory Crosswhite <[email protected]> * * Copyright: * Gregory Crosswhite, 2011 * Christian Schulte, 2003 * Guido Tack, 2004 * * Last modified: * $Date$ by $Author$ * $Revision$ * * This file is part of Gecode, the generic constraint * development environment: * http://www.gecode.org * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ #include <cstdarg> #include <iostream> #include <sstream> namespace Gecode { /** * \brief Shared array with arbitrary number of elements * * Sharing is implemented by reference counting: the same elements * are shared among several objects. * */ template<class T> class SharedArray : public SharedHandle { protected: /// Implementation of object for shared arrays class SAO : public SharedHandle::Object { private: /// Elements T* a; /// Number of elements int n; public: /// Allocate for \a n elements SAO(int n); /// Create copy of elements virtual SharedHandle::Object* copy(void) const; /// Delete object virtual ~SAO(void); /// Access element at position \a i T& operator [](int i); /// Access element at position \a i const T& operator [](int i) const; /// Return number of elements int size(void) const; /// Return beginning of array (for iterators) T* begin(void); /// Return beginning of array (for iterators) const T* begin(void) const; /// Return end of array (for iterators) T* end(void); /// Return end of array (for iterators) const T* end(void) const; }; public: /// \name Associated types //@{ /// Type of the view stored in this array typedef T value_type; /// Type of a reference to the value type typedef T& reference; /// Type of a constant reference to the value type typedef const T& const_reference; /// Type of a pointer to the value type typedef T* pointer; /// Type of a read-only pointer to the value type typedef const T* const_pointer; /// Type of the iterator used to iterate through this array's elements typedef T* iterator; /// Type of the iterator used to iterate read-only through this array's elements typedef const T* const_iterator; /// Type of the iterator used to iterate backwards through this array's elements typedef std::reverse_iterator<T*> reverse_iterator; /// Type of the iterator used to iterate backwards and read-only through this array's elements typedef std::reverse_iterator<const T*> const_reverse_iterator; //@} /** * \brief Construct as not yet intialized * * The only member functions that can be used on a constructed but not * yet initialized shared array is init and the assignment operator . * */ SharedArray(void); /// Initialize as array with \a n elements SharedArray(int n); /** * \brief Initialize as array with \a n elements * * This member function can only be used once and only if the shared * array has been constructed with the default constructor. * */ void init(int n); /// Initialize from shared array \a a (share elements) SharedArray(const SharedArray& a); /// Initialize from argument array \a a SharedArray(const ArgArrayBase<T>& a); /// Access element at position \a i T& operator [](int i); /// Access element at position \a i const T& operator [](int i) const; /// Return number of elements int size(void) const; /// \name Array iteration //@{ /// Return an iterator at the beginning of the array iterator begin(void); /// Return a read-only iterator at the beginning of the array const_iterator begin(void) const; /// Return an iterator past the end of the array iterator end(void); /// Return a read-only iterator past the end of the array const_iterator end(void) const; /// Return a reverse iterator at the end of the array reverse_iterator rbegin(void); /// Return a reverse and read-only iterator at the end of the array const_reverse_iterator rbegin(void) const; /// Return a reverse iterator past the beginning of the array reverse_iterator rend(void); /// Return a reverse and read-only iterator past the beginning of the array const_reverse_iterator rend(void) const; //@} }; /** * \brief Print array elements enclosed in curly brackets * \relates SharedArray */ template<class Char, class Traits, class T> std::basic_ostream<Char,Traits>& operator <<(std::basic_ostream<Char,Traits>& os, const SharedArray<T>& x); /* * Implementation * */ /* * Shared arrays * */ template<class T> forceinline SharedArray<T>::SAO::SAO(int n0) : n(n0) { a = (n>0) ? heap.alloc<T>(n) : NULL; } template<class T> SharedHandle::Object* SharedArray<T>::SAO::copy(void) const { SAO* o = new SAO(n); for (int i=n; i--;) o->a[i] = a[i]; return o; } template<class T> SharedArray<T>::SAO::~SAO(void) { if (n>0) { heap.free<T>(a,n); } } template<class T> forceinline T& SharedArray<T>::SAO::operator [](int i) { assert((i>=0) && (i<n)); return a[i]; } template<class T> forceinline const T& SharedArray<T>::SAO::operator [](int i) const { assert((i>=0) && (i<n)); return a[i]; } template<class T> forceinline int SharedArray<T>::SAO::size(void) const { return n; } template<class T> forceinline T* SharedArray<T>::SAO::begin(void) { return a; } template<class T> forceinline const T* SharedArray<T>::SAO::begin(void) const { return a; } template<class T> forceinline T* SharedArray<T>::SAO::end(void) { return a+n; } template<class T> forceinline const T* SharedArray<T>::SAO::end(void) const { return a+n; } template<class T> forceinline SharedArray<T>::SharedArray(void) {} template<class T> forceinline SharedArray<T>::SharedArray(int n) : SharedHandle(new SAO(n)) {} template<class T> forceinline SharedArray<T>::SharedArray(const SharedArray<T>& sa) : SharedHandle(sa) {} template<class T> forceinline void SharedArray<T>::init(int n) { assert(object() == NULL); object(new SAO(n)); } template<class T> forceinline T& SharedArray<T>::operator [](int i) { assert(object() != NULL); return (*static_cast<SAO*>(object()))[i]; } template<class T> forceinline const T& SharedArray<T>::operator [](int i) const { assert(object() != NULL); return (*static_cast<SAO*>(object()))[i]; } template<class T> forceinline SharedArray<T>::SharedArray(const ArgArrayBase<T>& a) : SharedHandle(new SAO(a.size())) { for (int i=a.size(); i--; ) operator [](i)=a[i]; } template<class T> forceinline int SharedArray<T>::size(void) const { assert(object() != NULL); return static_cast<SAO*>(object())->size(); } template<class T> forceinline typename SharedArray<T>::iterator SharedArray<T>::begin(void) { assert(object() != NULL); return static_cast<SAO*>(object())->begin(); } template<class T> forceinline typename SharedArray<T>::const_iterator SharedArray<T>::begin(void) const { assert(object() != NULL); return static_cast<SAO*>(object())->begin(); } template<class T> forceinline typename SharedArray<T>::iterator SharedArray<T>::end(void) { assert(object() != NULL); return static_cast<SAO*>(object())->end(); } template<class T> forceinline typename SharedArray<T>::const_iterator SharedArray<T>::end(void) const { assert(object() != NULL); return static_cast<SAO*>(object())->end(); } template<class T> forceinline typename SharedArray<T>::reverse_iterator SharedArray<T>::rbegin(void) { assert(object() != NULL); return reverse_iterator(static_cast<SAO*>(object())->end()); } template<class T> forceinline typename SharedArray<T>::const_reverse_iterator SharedArray<T>::rbegin(void) const { assert(object() != NULL); return const_reverse_iterator(static_cast<SAO*>(object())->end()); } template<class T> forceinline typename SharedArray<T>::reverse_iterator SharedArray<T>::rend(void) { assert(object() != NULL); return reverse_iterator(static_cast<SAO*>(object())->begin()); } template<class T> forceinline typename SharedArray<T>::const_reverse_iterator SharedArray<T>::rend(void) const { assert(object() != NULL); return const_reverse_iterator(static_cast<SAO*>(object())->begin()); } template<class Char, class Traits, class T> std::basic_ostream<Char,Traits>& operator <<(std::basic_ostream<Char,Traits>& os, const SharedArray<T>& x) { std::basic_ostringstream<Char,Traits> s; s.copyfmt(os); s.width(0); s << '{'; if (x.size() > 0) { s << x[0]; for (int i=1; i<x.size(); i++) s << ", " << x[i]; } s << '}'; return os << s.str(); } } // STATISTICS: kernel-other
Fix iterators for shared arrays to work with empty arrays
Fix iterators for shared arrays to work with empty arrays git-svn-id: 2d17a59ec5406331c31d756b3601458bc52cc290@13521 64335634-5103-0410-b293-fc3d331e086d
C++
mit
cp-profiler/gecode-profiling,cp-profiler/gecode-profiling,cp-profiler/gecode-profiling,cp-profiler/gecode-profiling
783dd7058a41fd792bfe74c5ba01e8f0fd9f424b
veapp/main/vsccameraadd.cpp
veapp/main/vsccameraadd.cpp
#include "vsccameraadd.h" #include "vscvwidget.h" #include <QFileDialog> extern Factory *gFactory; VSCCameraAdd::VSCCameraAdd(DeviceParam &Param, QWidget *parent) : QWidget(parent) { ui.setupUi(this); m_Param = Param; m_nId = m_Param.m_Conf.data.conf.nId; #if 0 m_pFloating = new QAction(QIcon(tr("images/open.ico")), tr("Floating"), this); //m_pUnFloating = new QAction(QIcon(tr("images/open.ico")), tr("UnFloating"), this); connect(m_pFloating, SIGNAL(triggered()), this, SLOT(floatingAction())); //connect(m_pUnFloating, SIGNAL(triggered()), this, SLOT(unFloatingAction())); createContentMenu(); #endif //connect(ui.lineFilePath, SIGNAL(triggered()), this, SLOT(floatingAction())); //ui.radioButtonFile->setChecked(true); setupDefaultValue(); radioButtonClicked(); m_pVideo = new VSCVWidget(m_nId, this); QVBoxLayout* layout = new QVBoxLayout(); layout->addWidget(m_pVideo); layout->setMargin(0); ui.widget->setLayout(layout); PreView(); SetupConnections(); } VSCCameraAdd::~VSCCameraAdd() { } void VSCCameraAdd::SetupConnections() { connect( this->ui.radioButtonFile, SIGNAL( clicked() ), this, SLOT(radioButtonClicked())); connect( this->ui.radioButtonRtsp, SIGNAL( clicked() ), this, SLOT(radioButtonClicked())); connect( this->ui.radioButtonOnvif, SIGNAL( clicked() ), this, SLOT(radioButtonClicked())); connect( this->ui.pushButtonApply, SIGNAL( clicked() ), this, SLOT(applyConfig())); connect( this->ui.pushButtonFile, SIGNAL( clicked() ), this, SLOT(fileSelect())); } void VSCCameraAdd::fileSelect() { QFileDialog *fileDialog = new QFileDialog(this); fileDialog->setWindowTitle(tr("Select File")); fileDialog->setDirectory(ui.fileLoc->text()); fileDialog->setNameFilter(tr("Video Files(*.MOV *.mp4 *.avi *.ts *.mpg)")); QIcon icon; icon.addFile(QStringLiteral(":/logo/resources/vscsmall.png"), QSize(), QIcon::Normal, QIcon::Off); fileDialog->setWindowIcon(icon); if(fileDialog->exec() == QDialog::Accepted) { QString path = fileDialog->selectedFiles()[0]; ui.fileLoc->setText(path); VDC_DEBUG( "%s QFileDialog %s\n",__FUNCTION__, path.toStdString().c_str()); } else { } } void VSCCameraAdd::PreView() { if (m_nId <= 0) { return; } m_pVideo->StopPlay(); m_pVideo->SetPlayId(m_nId); m_pVideo->StartPlay("fake"); } void VSCCameraAdd::setupDefaultValue() { switch(m_Param.m_Conf.data.conf.nSubType) { case VSC_SUB_DEVICE_FILE: ui.radioButtonFile->setChecked(true); break; case VSC_SUB_DEVICE_RTSP: ui.radioButtonRtsp->setChecked(true); break; case VSC_SUB_DEVICE_ONVIF: ui.radioButtonOnvif->setChecked(true); break; default: return; } ui.lineEditName->setText(m_Param.m_Conf.data.conf.Name); ui.lineEditIP->setText(m_Param.m_Conf.data.conf.IP); ui.lineEditPort->setText(m_Param.m_Conf.data.conf.Port); ui.lineEditUser->setText(m_Param.m_Conf.data.conf.User); ui.lineEditPassword->setText(m_Param.m_Conf.data.conf.Password); ui.lineEditRtspLoc->setText(m_Param.m_Conf.data.conf.RtspLocation); //ui.lineFileLoc->setText(m_Param.m_Conf.data.conf.FileLocation); ui.fileLoc->setText(m_Param.m_Conf.data.conf.FileLocation); ui.lineOnvifAddr->setText(m_Param.m_Conf.data.conf.OnvifAddress); ui.lineEditProfileToken->setText(m_Param.m_Conf.data.conf.OnvifProfileToken); if (m_Param.m_Conf.data.conf.UseProfileToken == 1) { ui.checkBoxProfileToken->setChecked(true); ui.lineEditProfileToken->setDisabled(0); }else { ui.checkBoxProfileToken->setChecked(false); ui.lineEditProfileToken->setDisabled(1); } } void VSCCameraAdd::updateParamValue(QLineEdit *ld, s8 * pParam) { if (pParam && ld) { strcpy(pParam, ld->text().toStdString().c_str()); } } void VSCCameraAdd::applyConfig() { VDC_DEBUG( "%s ID %d\n",__FUNCTION__, m_nId); /* Update m_Param from UI */ updateParamValue(ui.lineEditName, m_Param.m_Conf.data.conf.Name); updateParamValue(ui.lineEditIP, m_Param.m_Conf.data.conf.IP); updateParamValue(ui.lineEditPort, m_Param.m_Conf.data.conf.Port); updateParamValue(ui.lineEditUser, m_Param.m_Conf.data.conf.User); updateParamValue(ui.lineEditPassword, m_Param.m_Conf.data.conf.Password); updateParamValue(ui.lineEditRtspLoc, m_Param.m_Conf.data.conf.RtspLocation); //updateParamValue(ui.lineFileLoc, m_Param.m_Conf.data.conf.FileLocation); /* Update the File location */ strcpy(m_Param.m_Conf.data.conf.FileLocation, ui.fileLoc->text().toStdString().c_str()); updateParamValue(ui.lineOnvifAddr, m_Param.m_Conf.data.conf.OnvifAddress); updateParamValue(ui.lineEditProfileToken, m_Param.m_Conf.data.conf.OnvifProfileToken); m_Param.m_Conf.data.conf.nType = VSC_DEVICE_CAM; if (ui.radioButtonRtsp->isChecked() == true) { m_Param.m_Conf.data.conf.nSubType = VSC_SUB_DEVICE_RTSP; }else if (ui.radioButtonOnvif->isChecked() == true) { m_Param.m_Conf.data.conf.nSubType = VSC_SUB_DEVICE_ONVIF; }else if (ui.radioButtonFile->isChecked() == true) { m_Param.m_Conf.data.conf.nSubType = VSC_SUB_DEVICE_FILE; } if (ui.checkBoxProfileToken->isChecked() == true) { m_Param.m_Conf.data.conf.UseProfileToken = 1; }else { m_Param.m_Conf.data.conf.UseProfileToken = 0; } if (m_nId > 0) { gFactory->DelDevice(m_nId); } VDC_DEBUG( "%s Line %d\n",__FUNCTION__, __LINE__); /* m_nId <= 0 is Add Camera Device */ m_nId = gFactory->AddDevice(m_Param); VDC_DEBUG( "%s ID %d\n",__FUNCTION__, m_nId); //PreView(); VDC_DEBUG( "%s Line %d\n",__FUNCTION__, __LINE__); //emit CameraTreeUpdated(); } void VSCCameraAdd::mouseDoubleClickEvent(QMouseEvent *e) { #if 0 VDC_DEBUG( "%s mouseDoubleClickEvent\n",__FUNCTION__); QWidget::mouseDoubleClickEvent(e); if(isFullScreen()) { //setParent(m_pParent); //resize(m_pParent->width(), m_pParent->height()); //showMaximized(); this->setWindowState(Qt::WindowMaximized); } else { //m_pParent = parentWidget(); //setParent(NULL); //showFullScreen(); this->setWindowState(Qt::WindowFullScreen); } #endif } void VSCCameraAdd::floatingAction() { if (m_bFloated == TRUE) { return; } m_pParent = parentWidget(); setParent(NULL); showMaximized(); m_bFloated = TRUE; } void VSCCameraAdd::unFloatingAction() { if (m_bFloated == FALSE) { return; } showFullScreen(); setParent(m_pParent); resize(m_pParent->width(), m_pParent->height()); showFullScreen(); m_bFloated = FALSE; } void VSCCameraAdd::createContentMenu() { this->addAction(m_pFloating); //this->addAction(m_pUnFloating); this->setContextMenuPolicy(Qt::ActionsContextMenu); } void VSCCameraAdd::radioButtonClicked() { ui.lineEditIP->setDisabled(0); ui.lineEditPort->setDisabled(0); ui.lineEditUser->setDisabled(0); ui.lineEditPassword->setDisabled(0); ui.lineEditRtspLoc->setDisabled(0); //ui.lineFileLoc->setDisabled(0); ui.lineOnvifAddr->setDisabled(0); ui.lineEditProfileToken->setDisabled(0); ui.checkBoxProfileToken->setDisabled(0); if(this->ui.radioButtonFile->isChecked()) { ui.lineEditIP->setDisabled(1); ui.lineEditPort->setDisabled(1); ui.lineEditUser->setDisabled(1); ui.lineEditPassword->setDisabled(1); ui.lineEditRtspLoc->setDisabled(1); ui.lineOnvifAddr->setDisabled(1); ui.lineEditProfileToken->setDisabled(1); ui.checkBoxProfileToken->setDisabled(1); } if(this->ui.radioButtonRtsp->isChecked()) { ui.lineOnvifAddr->setDisabled(1); //ui.lineFileLoc->setDisabled(1); ui.lineEditProfileToken->setDisabled(1); ui.checkBoxProfileToken->setDisabled(1); } if(this->ui.radioButtonOnvif->isChecked()) { ui.lineEditRtspLoc->setDisabled(1); //ui.lineFileLoc->setDisabled(1); } }
#include "vsccameraadd.h" #include "vscvwidget.h" #include <QFileDialog> extern Factory *gFactory; VSCCameraAdd::VSCCameraAdd(DeviceParam &Param, QWidget *parent) : QWidget(parent) { ui.setupUi(this); m_Param = Param; m_nId = m_Param.m_Conf.data.conf.nId; #if 0 m_pFloating = new QAction(QIcon(tr("images/open.ico")), tr("Floating"), this); //m_pUnFloating = new QAction(QIcon(tr("images/open.ico")), tr("UnFloating"), this); connect(m_pFloating, SIGNAL(triggered()), this, SLOT(floatingAction())); //connect(m_pUnFloating, SIGNAL(triggered()), this, SLOT(unFloatingAction())); createContentMenu(); #endif //connect(ui.lineFilePath, SIGNAL(triggered()), this, SLOT(floatingAction())); //ui.radioButtonFile->setChecked(true); setupDefaultValue(); radioButtonClicked(); m_pVideo = new VSCVWidget(m_nId, this); QVBoxLayout* layout = new QVBoxLayout(); layout->addWidget(m_pVideo); layout->setMargin(0); ui.widget->setLayout(layout); PreView(); SetupConnections(); } VSCCameraAdd::~VSCCameraAdd() { } void VSCCameraAdd::SetupConnections() { connect( this->ui.radioButtonFile, SIGNAL( clicked() ), this, SLOT(radioButtonClicked())); connect( this->ui.radioButtonRtsp, SIGNAL( clicked() ), this, SLOT(radioButtonClicked())); connect( this->ui.radioButtonOnvif, SIGNAL( clicked() ), this, SLOT(radioButtonClicked())); connect( this->ui.pushButtonApply, SIGNAL( clicked() ), this, SLOT(applyConfig())); connect( this->ui.pushButtonFile, SIGNAL( clicked() ), this, SLOT(fileSelect())); } void VSCCameraAdd::fileSelect() { QFileDialog *fileDialog = new QFileDialog(this); fileDialog->setWindowTitle(tr("Select File")); fileDialog->setDirectory(ui.fileLoc->text()); fileDialog->setNameFilter(tr("Video Files(*.MOV *.mp4 *.avi *.ts *.mpg)")); QIcon icon; icon.addFile(QStringLiteral(":/logo/resources/vscsmall.png"), QSize(), QIcon::Normal, QIcon::Off); fileDialog->setWindowIcon(icon); if(fileDialog->exec() == QDialog::Accepted) { QString path = fileDialog->selectedFiles()[0]; ui.fileLoc->setText(path); VDC_DEBUG( "%s QFileDialog %s\n",__FUNCTION__, path.toStdString().c_str()); } else { } } void VSCCameraAdd::PreView() { if (m_nId <= 0) { return; } m_pVideo->StopPlay(); m_pVideo->SetPlayId(m_nId); m_pVideo->StartPlay("fake"); } void VSCCameraAdd::setupDefaultValue() { switch(m_Param.m_Conf.data.conf.nSubType) { case VSC_SUB_DEVICE_FILE: ui.radioButtonFile->setChecked(true); break; case VSC_SUB_DEVICE_RTSP: ui.radioButtonRtsp->setChecked(true); break; case VSC_SUB_DEVICE_ONVIF: ui.radioButtonOnvif->setChecked(true); break; default: return; } ui.lineEditName->setText(m_Param.m_Conf.data.conf.Name); ui.lineEditIP->setText(m_Param.m_Conf.data.conf.IP); ui.lineEditPort->setText(m_Param.m_Conf.data.conf.Port); ui.lineEditUser->setText(m_Param.m_Conf.data.conf.User); ui.lineEditPassword->setText(m_Param.m_Conf.data.conf.Password); ui.lineEditRtspLoc->setText(m_Param.m_Conf.data.conf.RtspLocation); //ui.lineFileLoc->setText(m_Param.m_Conf.data.conf.FileLocation); ui.fileLoc->setText(m_Param.m_Conf.data.conf.FileLocation); ui.lineOnvifAddr->setText(m_Param.m_Conf.data.conf.OnvifAddress); ui.lineEditProfileToken->setText(m_Param.m_Conf.data.conf.OnvifProfileToken); if (m_Param.m_Conf.data.conf.UseProfileToken == 1) { ui.checkBoxProfileToken->setChecked(true); ui.lineEditProfileToken->setDisabled(0); }else { ui.checkBoxProfileToken->setChecked(false); ui.lineEditProfileToken->setDisabled(1); } if (m_Param.m_Conf.data.conf.HWAccel == 1) { ui.checkBoxHWAccel->setChecked(true); }else { ui.checkBoxHWAccel->setChecked(false); } if (m_Param.m_Conf.data.conf.Mining == 1) { ui.checkBoxDataMining->setChecked(true); }else { ui.checkBoxDataMining->setChecked(false); } } void VSCCameraAdd::updateParamValue(QLineEdit *ld, s8 * pParam) { if (pParam && ld) { strcpy(pParam, ld->text().toStdString().c_str()); } } void VSCCameraAdd::applyConfig() { VDC_DEBUG( "%s ID %d\n",__FUNCTION__, m_nId); /* Update m_Param from UI */ updateParamValue(ui.lineEditName, m_Param.m_Conf.data.conf.Name); updateParamValue(ui.lineEditIP, m_Param.m_Conf.data.conf.IP); updateParamValue(ui.lineEditPort, m_Param.m_Conf.data.conf.Port); updateParamValue(ui.lineEditUser, m_Param.m_Conf.data.conf.User); updateParamValue(ui.lineEditPassword, m_Param.m_Conf.data.conf.Password); updateParamValue(ui.lineEditRtspLoc, m_Param.m_Conf.data.conf.RtspLocation); //updateParamValue(ui.lineFileLoc, m_Param.m_Conf.data.conf.FileLocation); /* Update the File location */ strcpy(m_Param.m_Conf.data.conf.FileLocation, ui.fileLoc->text().toStdString().c_str()); updateParamValue(ui.lineOnvifAddr, m_Param.m_Conf.data.conf.OnvifAddress); updateParamValue(ui.lineEditProfileToken, m_Param.m_Conf.data.conf.OnvifProfileToken); updateParamValue(ui.lineEditProfileToken2, m_Param.m_Conf.data.conf.OnvifProfileToken2); m_Param.m_Conf.data.conf.nType = VSC_DEVICE_CAM; if (ui.radioButtonRtsp->isChecked() == true) { m_Param.m_Conf.data.conf.nSubType = VSC_SUB_DEVICE_RTSP; }else if (ui.radioButtonOnvif->isChecked() == true) { m_Param.m_Conf.data.conf.nSubType = VSC_SUB_DEVICE_ONVIF; }else if (ui.radioButtonFile->isChecked() == true) { m_Param.m_Conf.data.conf.nSubType = VSC_SUB_DEVICE_FILE; } if (ui.checkBoxProfileToken->isChecked() == true) { m_Param.m_Conf.data.conf.UseProfileToken = 1; }else { m_Param.m_Conf.data.conf.UseProfileToken = 0; } /* HWAccel */ if (ui.checkBoxHWAccel->isChecked() == true) { m_Param.m_Conf.data.conf.HWAccel = 1; }else { m_Param.m_Conf.data.conf.HWAccel = 0; } /* Mining */ if (ui.checkBoxDataMining->isChecked() == true) { m_Param.m_Conf.data.conf.Mining = 1; }else { m_Param.m_Conf.data.conf.Mining = 0; } if (m_nId > 0) { gFactory->DelDevice(m_nId); } VDC_DEBUG( "%s Line %d\n",__FUNCTION__, __LINE__); /* m_nId <= 0 is Add Camera Device */ m_nId = gFactory->AddDevice(m_Param); VDC_DEBUG( "%s ID %d\n",__FUNCTION__, m_nId); //PreView(); VDC_DEBUG( "%s Line %d\n",__FUNCTION__, __LINE__); //emit CameraTreeUpdated(); } void VSCCameraAdd::mouseDoubleClickEvent(QMouseEvent *e) { #if 0 VDC_DEBUG( "%s mouseDoubleClickEvent\n",__FUNCTION__); QWidget::mouseDoubleClickEvent(e); if(isFullScreen()) { //setParent(m_pParent); //resize(m_pParent->width(), m_pParent->height()); //showMaximized(); this->setWindowState(Qt::WindowMaximized); } else { //m_pParent = parentWidget(); //setParent(NULL); //showFullScreen(); this->setWindowState(Qt::WindowFullScreen); } #endif } void VSCCameraAdd::floatingAction() { if (m_bFloated == TRUE) { return; } m_pParent = parentWidget(); setParent(NULL); showMaximized(); m_bFloated = TRUE; } void VSCCameraAdd::unFloatingAction() { if (m_bFloated == FALSE) { return; } showFullScreen(); setParent(m_pParent); resize(m_pParent->width(), m_pParent->height()); showFullScreen(); m_bFloated = FALSE; } void VSCCameraAdd::createContentMenu() { this->addAction(m_pFloating); //this->addAction(m_pUnFloating); this->setContextMenuPolicy(Qt::ActionsContextMenu); } void VSCCameraAdd::radioButtonClicked() { ui.lineEditIP->setDisabled(0); ui.lineEditPort->setDisabled(0); ui.lineEditUser->setDisabled(0); ui.lineEditPassword->setDisabled(0); ui.lineEditRtspLoc->setDisabled(0); //ui.lineFileLoc->setDisabled(0); ui.lineOnvifAddr->setDisabled(0); ui.lineEditProfileToken->setDisabled(0); ui.checkBoxProfileToken->setDisabled(0); if(this->ui.radioButtonFile->isChecked()) { ui.lineEditIP->setDisabled(1); ui.lineEditPort->setDisabled(1); ui.lineEditUser->setDisabled(1); ui.lineEditPassword->setDisabled(1); ui.lineEditRtspLoc->setDisabled(1); ui.lineOnvifAddr->setDisabled(1); ui.lineEditProfileToken->setDisabled(1); ui.checkBoxProfileToken->setDisabled(1); } if(this->ui.radioButtonRtsp->isChecked()) { ui.lineOnvifAddr->setDisabled(1); //ui.lineFileLoc->setDisabled(1); ui.lineEditProfileToken->setDisabled(1); ui.checkBoxProfileToken->setDisabled(1); } if(this->ui.radioButtonOnvif->isChecked()) { ui.lineEditRtspLoc->setDisabled(1); //ui.lineFileLoc->setDisabled(1); } }
enable hwaccel conf & mining conf
enable hwaccel conf & mining conf
C++
mit
xsmart/opencvr,veyesys/opencvr,veyesys/opencvr,veyesys/opencvr,telecamera/opencvr,telecamera/opencvr,herocodemaster/opencvr,veyesys/opencvr,xiaojuntong/opencvr,telecamera/opencvr,xsmart/opencvr,herocodemaster/opencvr,xsmart/opencvr,herocodemaster/opencvr,xsmart/opencvr,veyesys/opencvr,xiaojuntong/opencvr,xiaojuntong/opencvr,telecamera/opencvr,herocodemaster/opencvr,xsmart/opencvr,xiaojuntong/opencvr
6437f5d2b20f8c6e204cc35921dc1329a3d9dfb2
tests/src/runtimeApi/memory/hipHostRegister.cpp
tests/src/runtimeApi/memory/hipHostRegister.cpp
/* Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* HIT_START * BUILD: %t %s ../../test_common.cpp * RUN: %t --tests 0x1 * RUN: %t --tests 0x2 * RUN: %t --tests 0x4 * HIT_END */ // TODO - bug if run both back-to-back, once fixed should just need one command line #include"test_common.h" #include<malloc.h> __global__ void Inc(hipLaunchParm lp, float *Ad){ int tx = hipThreadIdx_x + hipBlockIdx_x * hipBlockDim_x; Ad[tx] = Ad[tx] + float(1); } template<typename T> void doMemCopy(size_t numElements, int offset, T *A, T *Bh, T *Bd, bool internalRegister) { A = A + offset; numElements -= offset; size_t sizeBytes = numElements * sizeof(T); if (internalRegister) { HIPCHECK(hipHostRegister(A, sizeBytes, 0)); } // Reset for(size_t i=0;i<numElements;i++){ A[i] = float(i); Bh[i] = 0.0f; } HIPCHECK(hipMemset(Bd, 13.0f, sizeBytes)); // HIPCHECK(hipMemcpy(Bd, A, sizeBytes, hipMemcpyHostToDevice)); HIPCHECK(hipMemcpy(Bh, Bd, sizeBytes, hipMemcpyDeviceToHost)); // Make sure the copy worked for(size_t i=0;i<numElements;i++){ if (Bh[i] != A[i]) { printf ("mismatch at Bh[%zu]=%f, A[%zu]=%f\n", i, Bh[i], i, A[i]); failed("mismatch"); }; } if (internalRegister) { HIPCHECK(hipHostUnregister(A)); } } int main(int argc, char *argv[]) { HipTest::parseStandardArguments(argc, argv, true); const size_t size = N * sizeof(float); if (p_tests & 0x1) { float *A, **Ad; int num_devices; HIPCHECK(hipGetDeviceCount(&num_devices)); Ad = new float*[num_devices]; A = (float*)malloc(size); HIPCHECK(hipHostRegister(A, size, 0)); for(int i=0;i<N;i++){ A[i] = float(1); } for(int i=0;i<num_devices;i++){ HIPCHECK(hipSetDevice(i)); HIPCHECK(hipHostGetDevicePointer((void**)&Ad[i], A, 0)); } // Reference the registered device pointer Ad from inside the kernel: for(int i=0;i<num_devices;i++){ HIPCHECK(hipSetDevice(i)); hipLaunchKernel(Inc, dim3(N/512), dim3(512), 0, 0, Ad[i]); HIPCHECK(hipDeviceSynchronize()); } HIPASSERT(A[10] == 1.0f + float(num_devices)); HIPCHECK(hipHostUnregister(A)); free (A); } if (p_tests & 0x6) { // Sensitize HIP bug if device does not match where the memory was registered. HIPCHECK(hipSetDevice(0)); float * A = (float*)malloc(size); // Copy to B, this should be optimal pinned malloc copy: // Note we are using the host pointer here: float *Bh, *Bd; Bh = (float*)malloc(size); HIPCHECK(hipMalloc(&Bd, size)); // TODO - set to 128 #define OFFSETS_TO_TRY 1 assert (N>OFFSETS_TO_TRY); if (p_tests & 0x2) { for (size_t i=0; i<OFFSETS_TO_TRY; i++) { doMemCopy(N, i, A, Bh, Bd, true/*internalRegister*/); } } if (p_tests & 0x4) { HIPCHECK(hipHostRegister(A, size, 0)); for (size_t i=0; i<OFFSETS_TO_TRY; i++) { doMemCopy(N, i, A, Bh, Bd, false/*internalRegister*/); } HIPCHECK(hipHostUnregister(A)); } free (A); } passed(); }
/* Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* HIT_START * BUILD: %t %s ../../test_common.cpp * RUN: %t * HIT_END */ // TODO - bug if run both back-to-back, once fixed should just need one command line #include"test_common.h" #include<malloc.h> __global__ void Inc(hipLaunchParm lp, float *Ad){ int tx = hipThreadIdx_x + hipBlockIdx_x * hipBlockDim_x; Ad[tx] = Ad[tx] + float(1); } template<typename T> void doMemCopy(size_t numElements, int offset, T *A, T *Bh, T *Bd, bool internalRegister) { A = A + offset; numElements -= offset; size_t sizeBytes = numElements * sizeof(T); if (internalRegister) { HIPCHECK(hipHostRegister(A, sizeBytes, 0)); } // Reset for(size_t i=0;i<numElements;i++){ A[i] = float(i); Bh[i] = 0.0f; } HIPCHECK(hipMemset(Bd, 13.0f, sizeBytes)); // HIPCHECK(hipMemcpy(Bd, A, sizeBytes, hipMemcpyHostToDevice)); HIPCHECK(hipMemcpy(Bh, Bd, sizeBytes, hipMemcpyDeviceToHost)); // Make sure the copy worked for(size_t i=0;i<numElements;i++){ if (Bh[i] != A[i]) { printf ("mismatch at Bh[%zu]=%f, A[%zu]=%f\n", i, Bh[i], i, A[i]); failed("mismatch"); }; } if (internalRegister) { HIPCHECK(hipHostUnregister(A)); } } int main(int argc, char *argv[]) { HipTest::parseStandardArguments(argc, argv, true); const size_t size = N * sizeof(float); if (p_tests & 0x1) { float *A, **Ad; int num_devices; HIPCHECK(hipGetDeviceCount(&num_devices)); Ad = new float*[num_devices]; A = (float*)malloc(size); HIPCHECK(hipHostRegister(A, size, 0)); for(int i=0;i<N;i++){ A[i] = float(1); } for(int i=0;i<num_devices;i++){ HIPCHECK(hipSetDevice(i)); HIPCHECK(hipHostGetDevicePointer((void**)&Ad[i], A, 0)); } // Reference the registered device pointer Ad from inside the kernel: for(int i=0;i<num_devices;i++){ HIPCHECK(hipSetDevice(i)); hipLaunchKernel(Inc, dim3(N/512), dim3(512), 0, 0, Ad[i]); HIPCHECK(hipDeviceSynchronize()); } HIPASSERT(A[10] == 1.0f + float(num_devices)); HIPCHECK(hipHostUnregister(A)); free (A); } if (p_tests & 0x6) { // Sensitize HIP bug if device does not match where the memory was registered. HIPCHECK(hipSetDevice(0)); float * A = (float*)malloc(size); // Copy to B, this should be optimal pinned malloc copy: // Note we are using the host pointer here: float *Bh, *Bd; Bh = (float*)malloc(size); HIPCHECK(hipMalloc(&Bd, size)); // TODO - set to 128 #define OFFSETS_TO_TRY 128 assert (N>OFFSETS_TO_TRY); if (p_tests & 0x2) { for (size_t i=0; i<OFFSETS_TO_TRY; i++) { doMemCopy(N, i, A, Bh, Bd, true/*internalRegister*/); } } if (p_tests & 0x4) { HIPCHECK(hipHostRegister(A, size, 0)); for (size_t i=0; i<OFFSETS_TO_TRY; i++) { doMemCopy(N, i, A, Bh, Bd, false/*internalRegister*/); } HIPCHECK(hipHostUnregister(A)); } free (A); } passed(); }
Refactor hipHostRegister test.
Refactor hipHostRegister test. Run all tests in one command. Run 128 offsets.
C++
mit
ROCm-Developer-Tools/HIP,ROCm-Developer-Tools/HIP,ROCm-Developer-Tools/HIP,GPUOpen-ProfessionalCompute-Tools/HIP,GPUOpen-ProfessionalCompute-Tools/HIP,ROCm-Developer-Tools/HIP,GPUOpen-ProfessionalCompute-Tools/HIP,ROCm-Developer-Tools/HIP,GPUOpen-ProfessionalCompute-Tools/HIP,GPUOpen-ProfessionalCompute-Tools/HIP
88fb0b36ecd4bbf4206267433aa5dde2fb529b17
src/common/fourcc.cpp
src/common/fourcc.cpp
/* * Copyright (c) 2016-2021 Fredrik Mellbin * * This file is part of VapourSynth. * * VapourSynth is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * VapourSynth is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with VapourSynth; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <algorithm> #include <cassert> #include <iterator> #include <utility> #include "fourcc.h" #include "p2p_api.h" #include "VSHelper4.h" namespace { constexpr VSColorFamily cfPackedRGB = static_cast<VSColorFamily>(-static_cast<int>(cfRGB)); constexpr VSColorFamily cfPackedYUV = static_cast<VSColorFamily>(-static_cast<int>(cfYUV)); constexpr unsigned UPSIDE_DOWN = 1; constexpr unsigned SWAP_UV = 2; constexpr unsigned NV_PACKED = 4; constexpr p2p_packing PLANAR = static_cast<p2p_packing>(-1); struct Traits { unsigned colorFamily; unsigned sampleType; unsigned bitsPerSample; unsigned subSamplingW; unsigned subSamplingH; int alt_output_mode; unsigned fourcc; p2p_packing packing_mode; unsigned bytesPerLumaSampleNum; unsigned bytesPerLumaSampleDen = 1; unsigned biBitCount = 0; unsigned flags = 0; unsigned alignment = 1; }; constexpr Traits fourcc_traits[] = { { cfRGB, stInteger, 8, 0, 0, 0, VS_FCC('DIB '), p2p_argb32_le, 4, 1, 32, UPSIDE_DOWN }, { cfRGB, stInteger, 10, 0, 0, 0, VS_FCC('r210'), p2p_rgb30_be, 4, 1, 30, 0, 256, }, { cfRGB, stInteger, 16, 0, 0, 0, VS_FCC('b64a'), p2p_argb64_be, 8, 1, 64 }, { cfYUV, stInteger, 8, 1, 1, 0, VS_FCC('YV12'), PLANAR, 1 }, { cfYUV, stInteger, 8, 1, 1, 1, VS_FCC('I420'), PLANAR, 1, 1, 0, SWAP_UV }, { cfYUV, stInteger, 8, 1, 1, 2, VS_FCC('IYUV'), PLANAR, 1, 1, 0, SWAP_UV }, { cfGray, stInteger, 8, 0, 0, 0, VS_FCC('Y800'), PLANAR, 1 }, { cfYUV, stInteger, 8, 0, 0, 0, VS_FCC('YV24'), PLANAR, 1 }, { cfYUV, stInteger, 8, 1, 0, 0, VS_FCC('YV16'), PLANAR, 1 }, { cfYUV, stInteger, 8, 2, 0, 0, VS_FCC('Y41B'), PLANAR, 1 }, { cfYUV, stInteger, 8, 1, 0, 1, VS_FCC('YUY2'), p2p_yuy2, 2 }, { cfYUV, stInteger, 8, 1, 0, 2, VS_FCC('UYVY'), p2p_uyvy, 2 }, { cfYUV, stInteger, 8, 2, 2, 0, VS_FCC('YVU9'), PLANAR, 1 }, { cfYUV, stInteger, 10, 1, 1, 0, VS_FCC('P010'), p2p_p010_le, 2, 1, 0, NV_PACKED }, { cfYUV, stInteger, 16, 1, 1, 0, VS_FCC('P016'), p2p_p016_le, 2, 1, 0, NV_PACKED }, { cfYUV, stInteger, 10, 1, 0, 0, VS_FCC('P210'), p2p_p210_le, 2, 1, 0, NV_PACKED }, { cfYUV, stInteger, 10, 1, 0, 1, VS_FCC('v210'), p2p_v210_le, 16, 6, 20, 0, 128 }, { cfYUV, stInteger, 16, 1, 0, 0, VS_FCC('P216'), p2p_p216_le, 2, 1, 0, NV_PACKED }, { cfYUV, stInteger, 10, 0, 0, 0, VS_FCC('Y410'), p2p_y410_le, 4, 1, 32 }, { cfYUV, stInteger, 16, 0, 0, 0, VS_FCC('Y416'), p2p_y416_le, 8, 1, 64 }, // AVS commpatibility formats. { cfPackedRGB, stInteger, 24, 0, 0, 0, VS_FCC('DIB '), PLANAR, 3, 1, 24, 0, 4 }, // AVS is already upside down! { cfPackedRGB, stInteger, 32, 0, 0, 0, VS_FCC('DIB '), PLANAR, 4, 1, 32, 0, 4 }, { cfPackedYUV, stInteger, 16, 1, 0, 0, VS_FCC('YUY2'), PLANAR, 2, 1, 16 }, }; const Traits *find_traits(const VSVideoFormat &fi, int alt_output) { auto it = std::find_if(std::begin(fourcc_traits), std::end(fourcc_traits), [=](const Traits &traits) { return traits.colorFamily == fi.colorFamily && traits.sampleType == fi.sampleType && traits.bitsPerSample == fi.bitsPerSample && traits.subSamplingW == fi.subSamplingW && traits.subSamplingH == fi.subSamplingH && traits.alt_output_mode == alt_output; }); return it == std::end(fourcc_traits) ? nullptr : &*it; } } // namespace static bool IsSameVideoFormat(const VSVideoFormat &f, unsigned colorFamily, unsigned sampleType, unsigned bitsPerSample, unsigned subSamplingW = 0, unsigned subSamplingH = 0) noexcept { return f.colorFamily == colorFamily && f.sampleType == sampleType && f.bitsPerSample == bitsPerSample && f.subSamplingW == subSamplingW && f.subSamplingH == subSamplingH; } bool GetFourCC(const VSVideoFormat &fi, int alt_output, unsigned long &fourcc) { const Traits *traits = find_traits(fi, alt_output); fourcc = traits ? traits->fourcc : VS_FCC('UNKN'); return !!traits; } bool GetBiCompression(const VSVideoFormat &format, int alt_output, unsigned long &compression) { bool success = GetFourCC(format, alt_output, compression); if (success && compression == VS_FCC('DIB ')) compression = 0; // BI_RGB return success; } static int RowSizeAligned(int rowsize, int alignment) { return rowsize % alignment ? rowsize + (alignment - rowsize % alignment) : rowsize; } static int RowSizePlanar(int width, int bytesPerSample, const Traits *traits) { int alignment = traits ? traits->alignment : 1; return RowSizeAligned(width * bytesPerSample, alignment); } static int RowSizeInterleaved(int width, const Traits *traits) { assert(traits); int rowsize = (width * traits->bytesPerLumaSampleNum + (traits->bytesPerLumaSampleDen - 1)) / traits->bytesPerLumaSampleDen; return RowSizeAligned(rowsize, traits->alignment); } int BMPSize(const VSVideoInfo *vi, int alt_output) { if (!vi) return 0; const Traits *traits = find_traits(vi->format, alt_output); if (!traits || traits->packing_mode == PLANAR) { int lumarowsize = RowSizePlanar(vi->width, vi->format.bytesPerSample, traits); int lumasize = lumarowsize * vi->height; if (vi->format.colorFamily == cfGray || vi->format.colorFamily == cfPackedRGB || vi->format.colorFamily == cfPackedYUV) return lumasize; assert(vi->format.numPlanes == 3); assert(vi->width % (1 << vi->format.subSamplingW) == 0); assert(vi->height % (1 << vi->format.subSamplingH) == 0); int chromarowsize = RowSizePlanar(vi->width >> vi->format.subSamplingW, vi->format.bytesPerSample, traits); int chromasize = chromarowsize * (vi->height >> vi->format.subSamplingH); return lumasize + chromasize * 2; } else if (traits->flags & NV_PACKED) { assert(vi->format.numPlanes == 3); assert(vi->width % (1 << vi->format.subSamplingW) == 0); assert(vi->height % (1 << vi->format.subSamplingH) == 0); int lumarowsize = RowSizePlanar(vi->width, vi->format.bytesPerSample, traits); int lumasize = lumarowsize * vi->height; int chromarowsize = RowSizePlanar((vi->width >> vi->format.subSamplingW) * 2, vi->format.bytesPerSample, traits); int chromasize = chromarowsize * (vi->height >> vi->format.subSamplingH); return lumasize + chromasize; } else { return RowSizeInterleaved(vi->width, traits) * vi->height; } } int BitsPerPixel(const VSVideoFormat &format, int alt_output) { const Traits *traits = find_traits(format, alt_output); if (!traits) return 0; if (traits->biBitCount) return traits->biBitCount; // Generic algorithm for biBitCount of YUV. int bits = format.bytesPerSample * 8; bits += (bits * 2) >> (format.subSamplingW + format.subSamplingH); return bits; } bool HasSupportedFourCC(const VSVideoFormat &fi) { unsigned long dummy; return GetFourCC(fi, 0, dummy); } bool NeedsPacking(const VSVideoFormat &fi, int alt_output) { const Traits *traits = find_traits(fi, alt_output); return traits && ((traits->packing_mode != PLANAR) || (traits->flags & UPSIDE_DOWN)); } // Returns false for YVU plane order and true for YUV whn doing planar output bool NeedsUVSwap(const VSVideoFormat &fi, int alt_output) { const Traits *traits = find_traits(fi, alt_output); return traits && (traits->flags & SWAP_UV); } void PackOutputFrame(const uint8_t *src[3], const ptrdiff_t src_stride[3], uint8_t *dst, int width, int height, const VSVideoFormat &fi, int alt_output) { const Traits *traits = find_traits(fi, alt_output); if (!traits || traits->packing_mode == PLANAR) { // Generic plane copy. int planeOrder[] = { 0, 1, 2 }; if (traits && (traits->flags & SWAP_UV)) std::swap(planeOrder[1], planeOrder[2]); for (int p = 0; p < fi.numPlanes; ++p) { int inputPlane = planeOrder[p]; int subSamplingW = (inputPlane == 1 || inputPlane == 2) ? fi.subSamplingW : 0; int subSamplingH = (inputPlane == 1 || inputPlane == 2) ? fi.subSamplingH : 0; int row_size = RowSizePlanar(width, fi.bytesPerSample, traits); uint8_t *dst_ptr = dst; int dst_stride = row_size; if (traits && (traits->flags & UPSIDE_DOWN)) { dst_ptr += row_size * ((height >> subSamplingH) - 1); dst_stride = -row_size; } vsh::bitblt(dst_ptr, dst_stride, src[inputPlane], src_stride[inputPlane], (width >> subSamplingW) * fi.bytesPerSample, height >> subSamplingH); dst += row_size * (height >> subSamplingH); } } else { p2p_buffer_param p2p_params = {}; p2p_params.width = width; p2p_params.height = height; p2p_params.packing = traits->packing_mode; for (int p = 0; p < fi.numPlanes; ++p) { p2p_params.src[p] = src[p]; p2p_params.src_stride[p] = src_stride[p]; } p2p_params.dst[0] = dst; assert(!(traits->flags & SWAP_UV)); // SWAP_UV is only for planar. if (traits->flags & NV_PACKED) { p2p_params.dst_stride[0] = RowSizePlanar(width, fi.bytesPerSample, traits); p2p_params.dst[1] = dst + p2p_params.dst_stride[0] * height; p2p_params.dst_stride[1] = RowSizePlanar((width >> fi.subSamplingW) * 2, fi.bytesPerSample, traits); } else { p2p_params.dst_stride[0] = RowSizeInterleaved(width, traits); } if (traits->flags & UPSIDE_DOWN) { for (int p = 0; p < 4; ++p) { if (!p2p_params.dst[p]) continue; int heightP = p == 1 || p == 2 ? (height >> fi.subSamplingH) : height; assert(p2p_params.dst_stride[p] > 0); // Stride is initially equal to RowSize, which is positive. uint8_t *ptr = static_cast<uint8_t *>(p2p_params.dst[p]); p2p_params.dst[p] = ptr + (heightP - 1) * p2p_params.dst_stride[p]; p2p_params.dst_stride[p] = -p2p_params.dst_stride[p]; } } p2p_pack_frame(&p2p_params, P2P_ALPHA_SET_ONE); } }
/* * Copyright (c) 2016-2021 Fredrik Mellbin * * This file is part of VapourSynth. * * VapourSynth is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * VapourSynth is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with VapourSynth; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <algorithm> #include <cassert> #include <iterator> #include <utility> #include "fourcc.h" #include "p2p_api.h" #include "VSHelper4.h" namespace { constexpr VSColorFamily cfPackedRGB = static_cast<VSColorFamily>(-static_cast<int>(cfRGB)); constexpr VSColorFamily cfPackedYUV = static_cast<VSColorFamily>(-static_cast<int>(cfYUV)); constexpr unsigned UPSIDE_DOWN = 1; constexpr unsigned SWAP_UV = 2; constexpr unsigned NV_PACKED = 4; constexpr p2p_packing PLANAR = static_cast<p2p_packing>(-1); struct Traits { unsigned colorFamily; unsigned sampleType; unsigned bitsPerSample; unsigned subSamplingW; unsigned subSamplingH; int alt_output_mode; unsigned fourcc; p2p_packing packing_mode; unsigned bytesPerLumaSampleNum; unsigned bytesPerLumaSampleDen = 1; unsigned biBitCount = 0; unsigned flags = 0; unsigned alignment = 1; }; constexpr Traits fourcc_traits[] = { { cfRGB, stInteger, 8, 0, 0, 0, VS_FCC('DIB '), p2p_argb32_le, 4, 1, 32, UPSIDE_DOWN }, { cfRGB, stInteger, 10, 0, 0, 0, VS_FCC('r210'), p2p_rgb30_be, 4, 1, 30, 0, 256, }, { cfRGB, stInteger, 16, 0, 0, 0, VS_FCC('b64a'), p2p_argb64_be, 8, 1, 64 }, { cfYUV, stInteger, 8, 1, 1, 0, VS_FCC('YV12'), PLANAR, 1 }, { cfYUV, stInteger, 8, 1, 1, 1, VS_FCC('I420'), PLANAR, 1, 1, 0, SWAP_UV }, { cfYUV, stInteger, 8, 1, 1, 2, VS_FCC('IYUV'), PLANAR, 1, 1, 0, SWAP_UV }, { cfGray, stInteger, 8, 0, 0, 0, VS_FCC('Y800'), PLANAR, 1 }, { cfYUV, stInteger, 8, 0, 0, 0, VS_FCC('YV24'), PLANAR, 1 }, { cfYUV, stInteger, 8, 1, 0, 0, VS_FCC('YV16'), PLANAR, 1 }, { cfYUV, stInteger, 8, 2, 0, 0, VS_FCC('Y41B'), PLANAR, 1 }, { cfYUV, stInteger, 8, 1, 0, 1, VS_FCC('YUY2'), p2p_yuy2, 2 }, { cfYUV, stInteger, 8, 1, 0, 2, VS_FCC('UYVY'), p2p_uyvy, 2 }, { cfYUV, stInteger, 8, 2, 2, 0, VS_FCC('YVU9'), PLANAR, 1 }, { cfYUV, stInteger, 10, 1, 1, 0, VS_FCC('P010'), p2p_p010_le, 2, 1, 0, NV_PACKED }, { cfYUV, stInteger, 16, 1, 1, 0, VS_FCC('P016'), p2p_p016_le, 2, 1, 0, NV_PACKED }, { cfYUV, stInteger, 10, 1, 0, 0, VS_FCC('P210'), p2p_p210_le, 2, 1, 0, NV_PACKED }, { cfYUV, stInteger, 10, 1, 0, 1, VS_FCC('v210'), p2p_v210_le, 16, 6, 20, 0, 128 }, { cfYUV, stInteger, 16, 1, 0, 0, VS_FCC('P216'), p2p_p216_le, 2, 1, 0, NV_PACKED }, { cfYUV, stInteger, 10, 0, 0, 0, VS_FCC('Y410'), p2p_y410_le, 4, 1, 32 }, { cfYUV, stInteger, 16, 0, 0, 0, VS_FCC('Y416'), p2p_y416_le, 8, 1, 64 }, // AVS commpatibility formats. { cfPackedRGB, stInteger, 24, 0, 0, 0, VS_FCC('DIB '), PLANAR, 3, 1, 24, 0, 4 }, // AVS is already upside down! { cfPackedRGB, stInteger, 32, 0, 0, 0, VS_FCC('DIB '), PLANAR, 4, 1, 32, 0, 4 }, { cfPackedYUV, stInteger, 16, 1, 0, 0, VS_FCC('YUY2'), PLANAR, 2, 1, 16 }, }; const Traits *find_traits(const VSVideoFormat &fi, int alt_output) { auto it = std::find_if(std::begin(fourcc_traits), std::end(fourcc_traits), [=](const Traits &traits) { return traits.colorFamily == fi.colorFamily && traits.sampleType == fi.sampleType && traits.bitsPerSample == fi.bitsPerSample && traits.subSamplingW == fi.subSamplingW && traits.subSamplingH == fi.subSamplingH && traits.alt_output_mode == alt_output; }); return it == std::end(fourcc_traits) ? nullptr : &*it; } } // namespace static bool IsSameVideoFormat(const VSVideoFormat &f, unsigned colorFamily, unsigned sampleType, unsigned bitsPerSample, unsigned subSamplingW = 0, unsigned subSamplingH = 0) noexcept { return f.colorFamily == colorFamily && f.sampleType == sampleType && f.bitsPerSample == bitsPerSample && f.subSamplingW == subSamplingW && f.subSamplingH == subSamplingH; } bool GetFourCC(const VSVideoFormat &fi, int alt_output, unsigned long &fourcc) { const Traits *traits = find_traits(fi, alt_output); fourcc = traits ? traits->fourcc : VS_FCC('UNKN'); return !!traits; } bool GetBiCompression(const VSVideoFormat &format, int alt_output, unsigned long &compression) { bool success = GetFourCC(format, alt_output, compression); if (success && compression == VS_FCC('DIB ')) compression = 0; // BI_RGB return success; } static int RowSizeAligned(int rowsize, int alignment) { return rowsize % alignment ? rowsize + (alignment - rowsize % alignment) : rowsize; } static int RowSizePlanar(int width, int bytesPerSample, const Traits *traits) { int alignment = traits ? traits->alignment : 1; return RowSizeAligned(width * bytesPerSample, alignment); } static int RowSizeInterleaved(int width, const Traits *traits) { assert(traits); int rowsize = (width * traits->bytesPerLumaSampleNum + (traits->bytesPerLumaSampleDen - 1)) / traits->bytesPerLumaSampleDen; return RowSizeAligned(rowsize, traits->alignment); } int BMPSize(const VSVideoInfo *vi, int alt_output) { if (!vi) return 0; const Traits *traits = find_traits(vi->format, alt_output); if (!traits || traits->packing_mode == PLANAR) { int lumarowsize = RowSizePlanar(vi->width, vi->format.bytesPerSample, traits); int lumasize = lumarowsize * vi->height; if (vi->format.colorFamily == cfGray || vi->format.colorFamily == cfPackedRGB || vi->format.colorFamily == cfPackedYUV) return lumasize; assert(vi->format.numPlanes == 3); assert(vi->width % (1 << vi->format.subSamplingW) == 0); assert(vi->height % (1 << vi->format.subSamplingH) == 0); int chromarowsize = RowSizePlanar(vi->width >> vi->format.subSamplingW, vi->format.bytesPerSample, traits); int chromasize = chromarowsize * (vi->height >> vi->format.subSamplingH); return lumasize + chromasize * 2; } else if (traits->flags & NV_PACKED) { assert(vi->format.numPlanes == 3); assert(vi->width % (1 << vi->format.subSamplingW) == 0); assert(vi->height % (1 << vi->format.subSamplingH) == 0); int lumarowsize = RowSizePlanar(vi->width, vi->format.bytesPerSample, traits); int lumasize = lumarowsize * vi->height; int chromarowsize = RowSizePlanar((vi->width >> vi->format.subSamplingW) * 2, vi->format.bytesPerSample, traits); int chromasize = chromarowsize * (vi->height >> vi->format.subSamplingH); return lumasize + chromasize; } else { return RowSizeInterleaved(vi->width, traits) * vi->height; } } int BitsPerPixel(const VSVideoFormat &format, int alt_output) { const Traits *traits = find_traits(format, alt_output); if (!traits) return 0; if (traits->biBitCount) return traits->biBitCount; // Generic algorithm for biBitCount of YUV. int bits = format.bytesPerSample * 8; bits += (bits * 2) >> (format.subSamplingW + format.subSamplingH); return bits; } bool HasSupportedFourCC(const VSVideoFormat &fi) { unsigned long dummy; return GetFourCC(fi, 0, dummy); } bool NeedsPacking(const VSVideoFormat &fi, int alt_output) { const Traits *traits = find_traits(fi, alt_output); return traits && ((traits->packing_mode != PLANAR) || (traits->flags & UPSIDE_DOWN)); } // Returns false for YVU plane order and true for YUV whn doing planar output bool NeedsUVSwap(const VSVideoFormat &fi, int alt_output) { const Traits *traits = find_traits(fi, alt_output); return traits && (traits->flags & SWAP_UV); } void PackOutputFrame(const uint8_t *src[3], const ptrdiff_t src_stride[3], uint8_t *dst, int width, int height, const VSVideoFormat &fi, int alt_output) { const Traits *traits = find_traits(fi, alt_output); if (!traits || traits->packing_mode == PLANAR) { // Generic plane copy. int planeOrder[] = { 0, 2, 1 }; if (traits && (traits->flags & SWAP_UV)) std::swap(planeOrder[1], planeOrder[2]); for (int p = 0; p < fi.numPlanes; ++p) { int inputPlane = planeOrder[p]; int subSamplingW = (inputPlane == 1 || inputPlane == 2) ? fi.subSamplingW : 0; int subSamplingH = (inputPlane == 1 || inputPlane == 2) ? fi.subSamplingH : 0; int row_size = RowSizePlanar(width, fi.bytesPerSample, traits); uint8_t *dst_ptr = dst; int dst_stride = row_size; if (traits && (traits->flags & UPSIDE_DOWN)) { dst_ptr += row_size * ((height >> subSamplingH) - 1); dst_stride = -row_size; } vsh::bitblt(dst_ptr, dst_stride, src[inputPlane], src_stride[inputPlane], (width >> subSamplingW) * fi.bytesPerSample, height >> subSamplingH); dst += row_size * (height >> subSamplingH); } } else { p2p_buffer_param p2p_params = {}; p2p_params.width = width; p2p_params.height = height; p2p_params.packing = traits->packing_mode; for (int p = 0; p < fi.numPlanes; ++p) { p2p_params.src[p] = src[p]; p2p_params.src_stride[p] = src_stride[p]; } p2p_params.dst[0] = dst; assert(!(traits->flags & SWAP_UV)); // SWAP_UV is only for planar. if (traits->flags & NV_PACKED) { p2p_params.dst_stride[0] = RowSizePlanar(width, fi.bytesPerSample, traits); p2p_params.dst[1] = dst + p2p_params.dst_stride[0] * height; p2p_params.dst_stride[1] = RowSizePlanar((width >> fi.subSamplingW) * 2, fi.bytesPerSample, traits); } else { p2p_params.dst_stride[0] = RowSizeInterleaved(width, traits); } if (traits->flags & UPSIDE_DOWN) { for (int p = 0; p < 4; ++p) { if (!p2p_params.dst[p]) continue; int heightP = p == 1 || p == 2 ? (height >> fi.subSamplingH) : height; assert(p2p_params.dst_stride[p] > 0); // Stride is initially equal to RowSize, which is positive. uint8_t *ptr = static_cast<uint8_t *>(p2p_params.dst[p]); p2p_params.dst[p] = ptr + (heightP - 1) * p2p_params.dst_stride[p]; p2p_params.dst_stride[p] = -p2p_params.dst_stride[p]; } } p2p_pack_frame(&p2p_params, P2P_ALPHA_SET_ONE); } }
Use YVU plane order in vfw too
Use YVU plane order in vfw too
C++
lgpl-2.1
vapoursynth/vapoursynth,vapoursynth/vapoursynth,vapoursynth/vapoursynth,vapoursynth/vapoursynth
9be05b63fae4dad04b0119bc0f43e4126407fa30
examples/determ.cpp
examples/determ.cpp
/* * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* Demonstration of deterministic wallet. */ #include <bitcoin/bitcoin.hpp> #include <wallet/wallet.hpp> using namespace bc; using namespace libwallet; int main() { deterministic_wallet wallet; // Set seed. if (!wallet.set_seed("a219213f9b12422aa206d988e3e49607")) log_error() << "Error setting seed."; // Get an address from wallet... data_chunk pubkey = wallet.generate_public_key(2); payment_address addr; set_public_key(addr, pubkey); assert(addr.encoded() == "1E4vM9q25xsyDwWwdqHUWnwshdWC9PykmL"); // ... Get the corresponding private key. // Extract the secret parameter. secret_parameter secret = wallet.generate_secret(2); assert(encode_hex(secret) == "33cc7e35fbb78d17d207e53d0fe950d1db571be889b3ff87aec653e501759264"); // The secret parameter is used to compute the private key // by the elliptic curve formula. elliptic_curve_key privkey; if (!privkey.set_secret(secret)) log_error() << "Error set private key."; // Wallet generated public key should match corresponding public key // in the private key. assert(privkey.public_key() == pubkey); // Master public key data_chunk mpk = wallet.master_public_key(); assert(encode_hex(mpk) == "d996c1a50ca4a57a9dface614338a1d837cb339e08361cfaf66ffd7da8e21786a7142a014056439d579654d7bb58dd5724b93372b5efae62e76783300f2b6cb5"); // A master key can only generate public keys and not the private keys. deterministic_wallet wallet2; wallet2.set_master_public_key(mpk); assert(wallet2.generate_public_key(2) == pubkey); // Trying to generate the secret parameter will always return null_hash. assert(wallet2.generate_secret(2) == null_hash); return 0; }
/* * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* Demonstration of deterministic wallet. */ #include <bitcoin/bitcoin.hpp> #include <wallet/wallet.hpp> using namespace bc; using namespace libwallet; int main() { deterministic_wallet wallet; // Set seed. if (!wallet.set_seed("a219213f9b12422aa206d988e3e49607")) log_error() << "Error setting seed."; // Get an address from wallet... data_chunk pubkey = wallet.generate_public_key(2); payment_address addr; set_public_key(addr, pubkey); assert(addr.encoded() == "1E4vM9q25xsyDwWwdqHUWnwshdWC9PykmL"); // ... Get the corresponding private key. // Extract the secret parameter. secret_parameter secret = wallet.generate_secret(2); assert(encode_hex(secret) == "33cc7e35fbb78d17d207e53d0fe950d1db571be889b3ff87aec653e501759264"); // The secret parameter is used to compute the private key // by the elliptic curve formula. Set compressed to false, this is testing the electrum-style deterministic wallet elliptic_curve_key privkey; if (!privkey.set_secret(secret, false)) log_error() << "Error set private key."; // Wallet generated public key should match corresponding public key // in the private key. assert(privkey.public_key() == pubkey); // Master public key data_chunk mpk = wallet.master_public_key(); assert(encode_hex(mpk) == "d996c1a50ca4a57a9dface614338a1d837cb339e08361cfaf66ffd7da8e21786a7142a014056439d579654d7bb58dd5724b93372b5efae62e76783300f2b6cb5"); // A master key can only generate public keys and not the private keys. deterministic_wallet wallet2; wallet2.set_master_public_key(mpk); assert(wallet2.generate_public_key(2) == pubkey); // Trying to generate the secret parameter will always return null_hash. assert(wallet2.generate_secret(2) == null_hash); return 0; }
Set the eckey to uncompressed when testing against the deterministic wallet.
Set the eckey to uncompressed when testing against the deterministic wallet.
C++
agpl-3.0
Airbitz/libwallet,Airbitz/libwallet,BWallet/libwallet,BWallet/libwallet,BWallet/libwallet
b2ee919fcb6ecae2d71f2a91a6f8e9c2d04dab8d
re2_c.cxx
re2_c.cxx
#include <ctype.h> // for tolower() #include <stdio.h> // for snprintf() #include <re2/re2.h> #include <re2/stringpiece.h> #include "re2_c.h" using namespace std; #define likely(x) __builtin_expect((x),1) #define unlikely(x) __builtin_expect((x),0) #ifdef DEBUG // Usage examples: ASSERT(a > b), ASSERT(foo() && "Opps, foo() reutrn 0"); #define ASSERT(c) if (!(c))\ { fprintf(stderr, "%s:%d Assert: %s\n", __FILE__, __LINE__, #c); abort(); } #else #define ASSERT(c) ((void)0) #endif /* This data structure is used to return some variable-length results back to * caller. */ struct re2c_match_aux { char* errstr; re2::StringPiece* captures; unsigned short errstr_buf_len; unsigned short cap_vect_len; /* the capacity of captures vector */ unsigned short ncap; /* cache of RE2::NumberOfCapturingGroups() */ }; /* Return the "idx"-th capture. NOTE: Captures are not necessarily ended with * '\0'. */ const char* re2c_get_capture(struct re2c_match_aux* aux, unsigned idx) { if (unlikely(!aux->captures)) return 0; if (unlikely(aux->ncap <= idx)) return 0; return aux->captures[idx].data(); } unsigned re2c_get_capture_len(struct re2c_match_aux* aux, unsigned idx) { if (unlikely(!aux->captures)) return 0; if (unlikely(aux->ncap <= idx)) return 0; return aux->captures[idx].size(); } struct re2c_match_aux* re2c_alloc_aux(void) { struct re2c_match_aux* p = new struct re2c_match_aux; p->errstr = 0; p->captures = 0; p->errstr_buf_len = 0; p->cap_vect_len = 0; p->ncap = 0; return p; } void re2c_free_aux(struct re2c_match_aux* p) { delete[] p->errstr; delete[] p->captures; delete p; } const char* re2c_get_errstr(struct re2c_match_aux* aux) { return aux->errstr; } static void copy_errstr(char* buffer, int buf_len, const string& src) { if (!buffer) return; int copy_len = src.size(); if (copy_len > buf_len - 1) copy_len = buf_len - 1; strncpy(buffer, src.c_str(), copy_len); buffer[copy_len] = '\0'; } struct re2_pattern_t* re2c_compile(const char* pattern, int pattern_len, const char* re2_options, char* errstr, int errstrlen, unsigned max_mem) { const char* ptn_ptr = pattern; int ptn_len = pattern_len; // Process the options re2::RE2::Options opts; opts.set_log_errors(false); if (re2_options) { const char* p = re2_options; bool multiline = false; opts.set_perl_classes(true); opts.set_word_boundary(true); while (char c = *p++) { bool turn_on = true; if (c >= 'A' && c <= 'Z') { turn_on = false; c = tolower(c); } switch (c) { case 'u': opts.set_utf8(turn_on); break; case 'p': opts.set_posix_syntax(turn_on); break; case 'a': opts.set_longest_match(turn_on); break; case 'e': opts.set_log_errors(turn_on); break; case 'l': opts.set_literal(turn_on); break; case 'n': opts.set_never_nl(turn_on); break; case 's': opts.set_dot_nl(turn_on); break; case 'c': opts.set_never_capture(turn_on); break; case 'i': opts.set_case_sensitive(!turn_on); break; case 'm': multiline = true; break; default: { fprintf(stderr, "unsupport flag\n"); string s = "unsupport flags "; s += c; copy_errstr(errstr, errstrlen, s); return 0; } } } if (max_mem == 0) {max_mem = 2048 * 1024; } opts.set_max_mem(max_mem); opts.set_log_errors(true); // FIXME:one-line mode is always turned on in non-posix mode. To // workaround the problem, we enclose the pattern with "(?m:...)" if (multiline) { const char* prefix = "(?m:"; const char* postfix = ")"; char* t; t = new char[ptn_len + strlen(prefix) + strlen(postfix) + 1]; strcpy(t, prefix); memcpy(t + strlen(prefix), pattern, ptn_len); strcpy(t + strlen(prefix) + ptn_len, postfix); ptn_ptr = t; ptn_len += strlen(prefix) + strlen(postfix); } } // Now compile the pattern RE2* pat = new RE2(re2::StringPiece(ptn_ptr, ptn_len), opts); if (ptn_ptr != pattern) delete[] ptn_ptr; if (pat && !pat->ok()) { copy_errstr(errstr, errstrlen, pat->error()); delete pat; return 0; } return (re2_pattern_t*)(void*)pat; } void re2c_free(struct re2_pattern_t* pat) { delete (RE2*)(void*)pat; } /* Return the number of captures of the given pattern */ int re2c_getncap(struct re2_pattern_t* pattern) { RE2* pat = reinterpret_cast<RE2*>(pattern); return pat->NumberOfCapturingGroups(); } /* Return 0 if the pattern matches the given text, 1 otherwise. */ int re2c_find(const char* text, int text_len, struct re2_pattern_t* pattern) { RE2* re2 = (RE2*)(void*)pattern; if (unlikely(!re2)) return 1; bool match = re2->Match(re2::StringPiece(text, text_len), 0 /* startpos */, text_len /* endpos*/, re2::RE2::UNANCHORED, 0, 0); return match ? 0 : 1; } /* Return 0 if the pattern matches the given text, 1 otherwise; captures are * returned via "aux". */ int re2c_match(const char* text, int text_len, struct re2_pattern_t* pattern, struct re2c_match_aux* aux) { RE2* re2 = (RE2*)(void*)pattern; if (unlikely(!re2)) return 1; int ncap = re2->NumberOfCapturingGroups() + 1; if (!aux->cap_vect_len || aux->cap_vect_len < ncap) { delete[] aux->captures; aux->captures = new re2::StringPiece[ncap]; aux->cap_vect_len = ncap; } aux->ncap = ncap; bool match = re2->Match(re2::StringPiece(text, text_len), 0 /* startpos */, text_len /* endpos*/, re2::RE2::UNANCHORED, aux->captures, ncap); return match ? 0 : 1; }
#include <ctype.h> // for tolower() #include <stdio.h> // for snprintf() #include <re2/re2.h> #include <re2/stringpiece.h> #include "re2_c.h" using namespace std; #define likely(x) __builtin_expect((x),1) #define unlikely(x) __builtin_expect((x),0) #ifdef DEBUG // Usage examples: ASSERT(a > b), ASSERT(foo() && "Opps, foo() reutrn 0"); #define ASSERT(c) if (!(c))\ { fprintf(stderr, "%s:%d Assert: %s\n", __FILE__, __LINE__, #c); abort(); } #else #define ASSERT(c) ((void)0) #endif /* This data structure is used to return some variable-length results back to * caller. */ struct re2c_match_aux { char* errstr; re2::StringPiece* captures; unsigned short errstr_buf_len; unsigned short cap_vect_len; /* the capacity of captures vector */ unsigned short ncap; /* cache of RE2::NumberOfCapturingGroups() */ }; /* Return the "idx"-th capture. NOTE: Captures are not necessarily ended with * '\0'. */ const char* re2c_get_capture(struct re2c_match_aux* aux, unsigned idx) { if (unlikely(!aux->captures)) return 0; if (unlikely(aux->ncap <= idx)) return 0; return aux->captures[idx].data(); } unsigned re2c_get_capture_len(struct re2c_match_aux* aux, unsigned idx) { if (unlikely(!aux->captures)) return 0; if (unlikely(aux->ncap <= idx)) return 0; return aux->captures[idx].size(); } struct re2c_match_aux* re2c_alloc_aux(void) { struct re2c_match_aux* p = new struct re2c_match_aux; p->errstr = 0; p->captures = 0; p->errstr_buf_len = 0; p->cap_vect_len = 0; p->ncap = 0; return p; } void re2c_free_aux(struct re2c_match_aux* p) { delete[] p->errstr; delete[] p->captures; delete p; } const char* re2c_get_errstr(struct re2c_match_aux* aux) { return aux->errstr; } static void copy_errstr(char* buffer, int buf_len, const string& src) { if (!buffer) return; int copy_len = src.size(); if (copy_len > buf_len - 1) copy_len = buf_len - 1; strncpy(buffer, src.c_str(), copy_len); buffer[copy_len] = '\0'; } struct re2_pattern_t* re2c_compile(const char* pattern, int pattern_len, const char* re2_options, char* errstr, int errstrlen, unsigned max_mem) { const char* ptn_ptr = pattern; int ptn_len = pattern_len; // Process the options re2::RE2::Options opts; opts.set_log_errors(false); if (re2_options) { const char* p = re2_options; bool multiline = false; opts.set_perl_classes(true); opts.set_word_boundary(true); while (char c = *p++) { bool turn_on = true; if (c >= 'A' && c <= 'Z') { turn_on = false; c = tolower(c); } switch (c) { case 'u': opts.set_utf8(turn_on); break; case 'p': opts.set_posix_syntax(turn_on); break; case 'a': opts.set_longest_match(turn_on); break; case 'e': opts.set_log_errors(turn_on); break; case 'l': opts.set_literal(turn_on); break; case 'n': opts.set_never_nl(turn_on); break; case 's': opts.set_dot_nl(turn_on); break; case 'c': opts.set_never_capture(turn_on); break; case 'i': opts.set_case_sensitive(!turn_on); break; case 'm': multiline = true; break; default: { fprintf(stderr, "unsupport flag\n"); string s = "unsupport flags "; s += c; copy_errstr(errstr, errstrlen, s); return 0; } } } if (max_mem == 0) {max_mem = 2048 * 1024; } opts.set_max_mem(max_mem); // FIXME:one-line mode is always turned on in non-posix mode. To // workaround the problem, we enclose the pattern with "(?m:...)" if (multiline) { const char* prefix = "(?m:"; const char* postfix = ")"; char* t; t = new char[ptn_len + strlen(prefix) + strlen(postfix) + 1]; strcpy(t, prefix); memcpy(t + strlen(prefix), pattern, ptn_len); strcpy(t + strlen(prefix) + ptn_len, postfix); ptn_ptr = t; ptn_len += strlen(prefix) + strlen(postfix); } } // Now compile the pattern RE2* pat = new RE2(re2::StringPiece(ptn_ptr, ptn_len), opts); if (ptn_ptr != pattern) delete[] ptn_ptr; if (pat && !pat->ok()) { copy_errstr(errstr, errstrlen, pat->error()); delete pat; return 0; } return (re2_pattern_t*)(void*)pat; } void re2c_free(struct re2_pattern_t* pat) { delete (RE2*)(void*)pat; } /* Return the number of captures of the given pattern */ int re2c_getncap(struct re2_pattern_t* pattern) { RE2* pat = reinterpret_cast<RE2*>(pattern); return pat->NumberOfCapturingGroups(); } /* Return 0 if the pattern matches the given text, 1 otherwise. */ int re2c_find(const char* text, int text_len, struct re2_pattern_t* pattern) { RE2* re2 = (RE2*)(void*)pattern; if (unlikely(!re2)) return 1; bool match = re2->Match(re2::StringPiece(text, text_len), 0 /* startpos */, text_len /* endpos*/, re2::RE2::UNANCHORED, 0, 0); return match ? 0 : 1; } /* Return 0 if the pattern matches the given text, 1 otherwise; captures are * returned via "aux". */ int re2c_match(const char* text, int text_len, struct re2_pattern_t* pattern, struct re2c_match_aux* aux) { RE2* re2 = (RE2*)(void*)pattern; if (unlikely(!re2)) return 1; int ncap = re2->NumberOfCapturingGroups() + 1; if (!aux->cap_vect_len || aux->cap_vect_len < ncap) { delete[] aux->captures; aux->captures = new re2::StringPiece[ncap]; aux->cap_vect_len = ncap; } aux->ncap = ncap; bool match = re2->Match(re2::StringPiece(text, text_len), 0 /* startpos */, text_len /* endpos*/, re2::RE2::UNANCHORED, aux->captures, ncap); return match ? 0 : 1; }
Revise option process: delete set_log_errors on after parse options
Revise option process: delete set_log_errors on after parse options Revise option process: delete set_log_errors on after parse options
C++
bsd-3-clause
cloudflare/lua-re2,cloudflare/lua-re2
a7f8f4857e4f6c3b8f89a3a3b9515f0cf9adf3fc
tests/unit/regression/LinearMachine_unittest.cc
tests/unit/regression/LinearMachine_unittest.cc
/* * Copyright (c) The Shogun Machine Learning Toolbox * Written (W) 2016 Youssef Emad El-Din * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the Shogun Development Team. * */ #include <shogun/lib/config.h> #include <shogun/labels/RegressionLabels.h> #include <shogun/features/DenseFeatures.h> #include <gtest/gtest.h> #include <shogun/regression/Regression.h> #include <shogun/machine/LinearMachine.h> #include <shogun/features/DenseFeatures.h> #include <shogun/regression/LinearRidgeRegression.h> #include <shogun/mathematics/eigen3.h> using namespace shogun; using namespace Eigen; TEST(LinearMachine,apply_train) { index_t n=20; SGMatrix<float64_t> X(1, n); SGMatrix<float64_t> X_test(1, 3); SGVector<float64_t> Y(n); X_test[0]=3; X_test[1]=7.5; X_test[2]=12; for (index_t i=0; i<n; ++i) { X[i] = i; Y[i]=2*X[i] +1; } CDenseFeatures<float64_t>* feat_train=new CDenseFeatures<float64_t>(X); CDenseFeatures<float64_t>* feat_test=new CDenseFeatures<float64_t>(X_test); CRegressionLabels* label_train=new CRegressionLabels(Y); float64_t tau=0.8; CLinearRidgeRegression* model=new CLinearRidgeRegression(tau, feat_train,label_train); model->train(); CRegressionLabels* predictions=model->apply_regression(feat_test); SGVector<float64_t> prediction_vector=predictions->get_labels(); EXPECT_LE(CMath::abs(prediction_vector[0]-7), 0.5); EXPECT_LE(CMath::abs(prediction_vector[1]-16), 0.5); EXPECT_LE(CMath::abs(prediction_vector[2]-25), 0.5); } TEST(LinearMachine,compute_bias) { index_t n=3; SGMatrix<float64_t> X(1, n); SGMatrix<float64_t> X_test(1, n); SGVector<float64_t> Y(n); X[0]=0; X[1]=1.1; X[2]=2.2; for (index_t i=0; i<n; ++i) { Y[i]=CMath::sin(X(0, i)); } CDenseFeatures<float64_t>* feat_train=new CDenseFeatures<float64_t>(X); CRegressionLabels* label_train=new CRegressionLabels(Y); float64_t tau=0.8; CLinearRidgeRegression* model=new CLinearRidgeRegression(tau, feat_train,label_train); model->train(); float64_t output_bias = model->get_bias(); CLinearRidgeRegression* model_nobias=new CLinearRidgeRegression(tau, feat_train,label_train); model_nobias->set_compute_bias(false); model_nobias->train(); // Calculate bias manually CRegressionLabels* predictions_nobias = model_nobias->apply_regression(feat_train); SGVector<float64_t> prediction_vector = predictions_nobias->get_labels(); Map<VectorXd> eigen_prediction(prediction_vector.vector, 3); Map<VectorXd> eigen_labels(Y, 3); float64_t expected_bias = (eigen_labels-eigen_prediction).mean(); EXPECT_LE(CMath::abs(output_bias - expected_bias), 10E-15); }
/* * Copyright (c) The Shogun Machine Learning Toolbox * Written (W) 2016 Youssef Emad El-Din * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the Shogun Development Team. * */ #include <shogun/lib/config.h> #include <shogun/labels/RegressionLabels.h> #include <shogun/features/DenseFeatures.h> #include <gtest/gtest.h> #include <shogun/regression/Regression.h> #include <shogun/machine/LinearMachine.h> #include <shogun/features/DenseFeatures.h> #include <shogun/regression/LinearRidgeRegression.h> #include <shogun/mathematics/eigen3.h> using namespace shogun; using namespace Eigen; #ifdef HAVE_LAPACK TEST(LinearMachine,apply_train) { index_t n=20; SGMatrix<float64_t> X(1, n); SGMatrix<float64_t> X_test(1, 3); SGVector<float64_t> Y(n); X_test[0]=3; X_test[1]=7.5; X_test[2]=12; for (index_t i=0; i<n; ++i) { X[i] = i; Y[i]=2*X[i] +1; } CDenseFeatures<float64_t>* feat_train=new CDenseFeatures<float64_t>(X); CDenseFeatures<float64_t>* feat_test=new CDenseFeatures<float64_t>(X_test); CRegressionLabels* label_train=new CRegressionLabels(Y); float64_t tau=0.8; CLinearRidgeRegression* model=new CLinearRidgeRegression(tau, feat_train,label_train); model->train(); CRegressionLabels* predictions=model->apply_regression(feat_test); SGVector<float64_t> prediction_vector=predictions->get_labels(); EXPECT_LE(CMath::abs(prediction_vector[0]-7), 0.5); EXPECT_LE(CMath::abs(prediction_vector[1]-16), 0.5); EXPECT_LE(CMath::abs(prediction_vector[2]-25), 0.5); } TEST(LinearMachine,compute_bias) { index_t n=3; SGMatrix<float64_t> X(1, n); SGMatrix<float64_t> X_test(1, n); SGVector<float64_t> Y(n); X[0]=0; X[1]=1.1; X[2]=2.2; for (index_t i=0; i<n; ++i) { Y[i]=CMath::sin(X(0, i)); } CDenseFeatures<float64_t>* feat_train=new CDenseFeatures<float64_t>(X); CRegressionLabels* label_train=new CRegressionLabels(Y); float64_t tau=0.8; CLinearRidgeRegression* model=new CLinearRidgeRegression(tau, feat_train,label_train); model->train(); float64_t output_bias = model->get_bias(); CLinearRidgeRegression* model_nobias=new CLinearRidgeRegression(tau, feat_train,label_train); model_nobias->set_compute_bias(false); model_nobias->train(); // Calculate bias manually CRegressionLabels* predictions_nobias = model_nobias->apply_regression(feat_train); SGVector<float64_t> prediction_vector = predictions_nobias->get_labels(); Map<VectorXd> eigen_prediction(prediction_vector.vector, 3); Map<VectorXd> eigen_labels(Y, 3); float64_t expected_bias = (eigen_labels-eigen_prediction).mean(); EXPECT_LE(CMath::abs(output_bias - expected_bias), 10E-15); } #endif /* HAVE_LAPACK */
Fix LinearMachine unit test LinearRidgeRegression requires HAVE_LAPACK
Fix LinearMachine unit test LinearRidgeRegression requires HAVE_LAPACK
C++
bsd-3-clause
lambday/shogun,lambday/shogun,besser82/shogun,shogun-toolbox/shogun,shogun-toolbox/shogun,sorig/shogun,sorig/shogun,shogun-toolbox/shogun,shogun-toolbox/shogun,sorig/shogun,geektoni/shogun,lambday/shogun,lambday/shogun,sorig/shogun,besser82/shogun,besser82/shogun,besser82/shogun,lisitsyn/shogun,besser82/shogun,lambday/shogun,sorig/shogun,lisitsyn/shogun,shogun-toolbox/shogun,karlnapf/shogun,karlnapf/shogun,karlnapf/shogun,lisitsyn/shogun,lambday/shogun,karlnapf/shogun,besser82/shogun,karlnapf/shogun,lisitsyn/shogun,geektoni/shogun,sorig/shogun,shogun-toolbox/shogun,lisitsyn/shogun,geektoni/shogun,lisitsyn/shogun,geektoni/shogun,geektoni/shogun,karlnapf/shogun,geektoni/shogun
5c6e3210c4981f1a0a056173f548953cd5313170
source/Plugins/Platform/OpenBSD/PlatformOpenBSD.cpp
source/Plugins/Platform/OpenBSD/PlatformOpenBSD.cpp
//===-- PlatformOpenBSD.cpp -------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "PlatformOpenBSD.h" #include "lldb/Host/Config.h" // C Includes #include <stdio.h> #ifndef LLDB_DISABLE_POSIX #include <sys/utsname.h> #endif // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Core/Debugger.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/State.h" #include "lldb/Host/HostInfo.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" // Define these constants from OpenBSD mman.h for use when targeting // remote openbsd systems even when host has different values. #define MAP_PRIVATE 0x0002 #define MAP_ANON 0x1000 using namespace lldb; using namespace lldb_private; using namespace lldb_private::platform_openbsd; static uint32_t g_initialize_count = 0; //------------------------------------------------------------------ PlatformSP PlatformOpenBSD::CreateInstance(bool force, const ArchSpec *arch) { Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); LLDB_LOG(log, "force = {0}, arch=({1}, {2})", force, arch ? arch->GetArchitectureName() : "<null>", arch ? arch->GetTriple().getTriple() : "<null>"); bool create = force; if (create == false && arch && arch->IsValid()) { const llvm::Triple &triple = arch->GetTriple(); switch (triple.getOS()) { case llvm::Triple::OpenBSD: create = true; break; #if defined(__OpenBSD__) // Only accept "unknown" for the OS if the host is BSD and // it "unknown" wasn't specified (it was just returned because it // was NOT specified) case llvm::Triple::OSType::UnknownOS: create = !arch->TripleOSWasSpecified(); break; #endif default: break; } } LLDB_LOG(log, "create = {0}", create); if (create) { return PlatformSP(new PlatformOpenBSD(false)); } return PlatformSP(); } ConstString PlatformOpenBSD::GetPluginNameStatic(bool is_host) { if (is_host) { static ConstString g_host_name(Platform::GetHostPlatformName()); return g_host_name; } else { static ConstString g_remote_name("remote-openbsd"); return g_remote_name; } } const char *PlatformOpenBSD::GetPluginDescriptionStatic(bool is_host) { if (is_host) return "Local OpenBSD user platform plug-in."; else return "Remote OpenBSD user platform plug-in."; } ConstString PlatformOpenBSD::GetPluginName() { return GetPluginNameStatic(IsHost()); } void PlatformOpenBSD::Initialize() { Platform::Initialize(); if (g_initialize_count++ == 0) { #if defined(__OpenBSD__) PlatformSP default_platform_sp(new PlatformOpenBSD(true)); default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture()); Platform::SetHostPlatform(default_platform_sp); #endif PluginManager::RegisterPlugin( PlatformOpenBSD::GetPluginNameStatic(false), PlatformOpenBSD::GetPluginDescriptionStatic(false), PlatformOpenBSD::CreateInstance, nullptr); } } void PlatformOpenBSD::Terminate() { if (g_initialize_count > 0) { if (--g_initialize_count == 0) { PluginManager::UnregisterPlugin(PlatformOpenBSD::CreateInstance); } } PlatformPOSIX::Terminate(); } //------------------------------------------------------------------ /// Default Constructor //------------------------------------------------------------------ PlatformOpenBSD::PlatformOpenBSD(bool is_host) : PlatformPOSIX(is_host) // This is the local host platform {} PlatformOpenBSD::~PlatformOpenBSD() = default; bool PlatformOpenBSD::GetSupportedArchitectureAtIndex(uint32_t idx, ArchSpec &arch) { if (IsHost()) { ArchSpec hostArch = HostInfo::GetArchitecture(HostInfo::eArchKindDefault); if (hostArch.GetTriple().isOSOpenBSD()) { if (idx == 0) { arch = hostArch; return arch.IsValid(); } } } else { if (m_remote_platform_sp) return m_remote_platform_sp->GetSupportedArchitectureAtIndex(idx, arch); llvm::Triple triple; // Set the OS to OpenBSD triple.setOS(llvm::Triple::OpenBSD); // Set the architecture switch (idx) { case 0: triple.setArchName("x86_64"); break; case 1: triple.setArchName("i386"); break; case 2: triple.setArchName("aarch64"); break; case 3: triple.setArchName("arm"); break; default: return false; } // Leave the vendor as "llvm::Triple:UnknownVendor" and don't specify the // vendor by // calling triple.SetVendorName("unknown") so that it is a "unspecified // unknown". // This means when someone calls triple.GetVendorName() it will return an // empty string // which indicates that the vendor can be set when two architectures are // merged // Now set the triple into "arch" and return true arch.SetTriple(triple); return true; } return false; } void PlatformOpenBSD::GetStatus(Stream &strm) { Platform::GetStatus(strm); #ifndef LLDB_DISABLE_POSIX // Display local kernel information only when we are running in host mode. // Otherwise, we would end up printing non-OpenBSD information (when running // on Mac OS for example). if (IsHost()) { struct utsname un; if (uname(&un)) return; strm.Printf(" Kernel: %s\n", un.sysname); strm.Printf(" Release: %s\n", un.release); strm.Printf(" Version: %s\n", un.version); } #endif } // OpenBSD processes cannot yet be launched by spawning and attaching. bool PlatformOpenBSD::CanDebugProcess() { return false; } void PlatformOpenBSD::CalculateTrapHandlerSymbolNames() { m_trap_handlers.push_back(ConstString("_sigtramp")); } MmapArgList PlatformOpenBSD::GetMmapArgumentList(const ArchSpec &arch, addr_t addr, addr_t length, unsigned prot, unsigned flags, addr_t fd, addr_t offset) { uint64_t flags_platform = 0; if (flags & eMmapFlagsPrivate) flags_platform |= MAP_PRIVATE; if (flags & eMmapFlagsAnon) flags_platform |= MAP_ANON; MmapArgList args({addr, length, prot, flags_platform, fd, offset}); return args; }
//===-- PlatformOpenBSD.cpp -------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "PlatformOpenBSD.h" #include "lldb/Host/Config.h" // C Includes #include <stdio.h> #ifndef LLDB_DISABLE_POSIX #include <sys/utsname.h> #endif // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Core/Debugger.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/State.h" #include "lldb/Host/HostInfo.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" // Define these constants from OpenBSD mman.h for use when targeting // remote openbsd systems even when host has different values. #define MAP_PRIVATE 0x0002 #define MAP_ANON 0x1000 using namespace lldb; using namespace lldb_private; using namespace lldb_private::platform_openbsd; static uint32_t g_initialize_count = 0; //------------------------------------------------------------------ PlatformSP PlatformOpenBSD::CreateInstance(bool force, const ArchSpec *arch) { Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); LLDB_LOG(log, "force = {0}, arch=({1}, {2})", force, arch ? arch->GetArchitectureName() : "<null>", arch ? arch->GetTriple().getTriple() : "<null>"); bool create = force; if (create == false && arch && arch->IsValid()) { const llvm::Triple &triple = arch->GetTriple(); switch (triple.getOS()) { case llvm::Triple::OpenBSD: create = true; break; #if defined(__OpenBSD__) // Only accept "unknown" for the OS if the host is BSD and // it "unknown" wasn't specified (it was just returned because it // was NOT specified) case llvm::Triple::OSType::UnknownOS: create = !arch->TripleOSWasSpecified(); break; #endif default: break; } } LLDB_LOG(log, "create = {0}", create); if (create) { return PlatformSP(new PlatformOpenBSD(false)); } return PlatformSP(); } ConstString PlatformOpenBSD::GetPluginNameStatic(bool is_host) { if (is_host) { static ConstString g_host_name(Platform::GetHostPlatformName()); return g_host_name; } else { static ConstString g_remote_name("remote-openbsd"); return g_remote_name; } } const char *PlatformOpenBSD::GetPluginDescriptionStatic(bool is_host) { if (is_host) return "Local OpenBSD user platform plug-in."; else return "Remote OpenBSD user platform plug-in."; } ConstString PlatformOpenBSD::GetPluginName() { return GetPluginNameStatic(IsHost()); } void PlatformOpenBSD::Initialize() { Platform::Initialize(); if (g_initialize_count++ == 0) { #if defined(__OpenBSD__) PlatformSP default_platform_sp(new PlatformOpenBSD(true)); default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture()); Platform::SetHostPlatform(default_platform_sp); #endif PluginManager::RegisterPlugin( PlatformOpenBSD::GetPluginNameStatic(false), PlatformOpenBSD::GetPluginDescriptionStatic(false), PlatformOpenBSD::CreateInstance, nullptr); } } void PlatformOpenBSD::Terminate() { if (g_initialize_count > 0) { if (--g_initialize_count == 0) { PluginManager::UnregisterPlugin(PlatformOpenBSD::CreateInstance); } } PlatformPOSIX::Terminate(); } //------------------------------------------------------------------ /// Default Constructor //------------------------------------------------------------------ PlatformOpenBSD::PlatformOpenBSD(bool is_host) : PlatformPOSIX(is_host) // This is the local host platform {} PlatformOpenBSD::~PlatformOpenBSD() = default; bool PlatformOpenBSD::GetSupportedArchitectureAtIndex(uint32_t idx, ArchSpec &arch) { if (IsHost()) { ArchSpec hostArch = HostInfo::GetArchitecture(HostInfo::eArchKindDefault); if (hostArch.GetTriple().isOSOpenBSD()) { if (idx == 0) { arch = hostArch; return arch.IsValid(); } } } else { if (m_remote_platform_sp) return m_remote_platform_sp->GetSupportedArchitectureAtIndex(idx, arch); llvm::Triple triple; // Set the OS to OpenBSD triple.setOS(llvm::Triple::OpenBSD); // Set the architecture switch (idx) { case 0: triple.setArchName("x86_64"); break; case 1: triple.setArchName("i386"); break; case 2: triple.setArchName("aarch64"); break; case 3: triple.setArchName("arm"); break; default: return false; } // Leave the vendor as "llvm::Triple:UnknownVendor" and don't specify the // vendor by // calling triple.SetVendorName("unknown") so that it is a "unspecified // unknown". // This means when someone calls triple.GetVendorName() it will return an // empty string // which indicates that the vendor can be set when two architectures are // merged // Now set the triple into "arch" and return true arch.SetTriple(triple); return true; } return false; } void PlatformOpenBSD::GetStatus(Stream &strm) { Platform::GetStatus(strm); #ifndef LLDB_DISABLE_POSIX // Display local kernel information only when we are running in host mode. // Otherwise, we would end up printing non-OpenBSD information (when running // on Mac OS for example). if (IsHost()) { struct utsname un; if (uname(&un)) return; strm.Printf(" Kernel: %s\n", un.sysname); strm.Printf(" Release: %s\n", un.release); strm.Printf(" Version: %s\n", un.version); } #endif } // OpenBSD processes cannot yet be launched by spawning and attaching. bool PlatformOpenBSD::CanDebugProcess() { return false; } void PlatformOpenBSD::CalculateTrapHandlerSymbolNames() { m_trap_handlers.push_back(ConstString("_sigtramp")); } MmapArgList PlatformOpenBSD::GetMmapArgumentList(const ArchSpec &arch, addr_t addr, addr_t length, unsigned prot, unsigned flags, addr_t fd, addr_t offset) { uint64_t flags_platform = 0; if (flags & eMmapFlagsPrivate) flags_platform |= MAP_PRIVATE; if (flags & eMmapFlagsAnon) flags_platform |= MAP_ANON; MmapArgList args({addr, length, prot, flags_platform, fd, offset}); return args; }
convert hard tabs to spaces in PlatformOpenBSD.cpp
convert hard tabs to spaces in PlatformOpenBSD.cpp Another case of this was responsible for the whitespace conflict in D34776. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@311003 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb
bb9f0dc5aae51a40885df3f50ce22c2b68153eea
be/src/common/logging.cc
be/src/common/logging.cc
// Copyright 2012 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "common/logging.h" #include <boost/foreach.hpp> #include <boost/thread/mutex.hpp> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_generators.hpp> #include <boost/uuid/uuid_io.hpp> #include <cerrno> #include <ctime> #include <fstream> #include <glob.h> #include <gutil/strings/substitute.h> #include <iostream> #include <map> #include <sstream> #include <stdio.h> #include <sys/stat.h> #include "common/logging.h" #include "util/error-util.h" #include "util/test-info.h" DEFINE_string(log_filename, "", "Prefix of log filename - " "full path is <log_dir>/<log_filename>.[INFO|WARN|ERROR|FATAL]"); DEFINE_bool(redirect_stdout_stderr, true, "If true, redirects stdout/stderr to INFO/ERROR log."); bool logging_initialized = false; using namespace boost; using namespace std; using namespace boost::uuids; mutex logging_mutex; void impala::InitGoogleLoggingSafe(const char* arg) { mutex::scoped_lock logging_lock(logging_mutex); if (logging_initialized) return; if (!FLAGS_log_filename.empty()) { for (int severity = google::INFO; severity <= google::FATAL; ++severity) { google::SetLogSymlink(severity, FLAGS_log_filename.c_str()); } } // This forces our logging to use /tmp rather than looking for a // temporary directory if none is specified. This is done so that we // can reliably construct the log file name without duplicating the // complex logic that glog uses to guess at a temporary dir. if (FLAGS_log_dir.empty()) { FLAGS_log_dir = "/tmp"; } if (FLAGS_redirect_stdout_stderr && !TestInfo::is_test()) { // We will be redirecting stdout/stderr to INFO/LOG so override any glog settings // that log to stdout/stderr... FLAGS_logtostderr = false; FLAGS_alsologtostderr = false; // Don't log to stderr on any threshold. FLAGS_stderrthreshold = google::FATAL + 1; } if (!FLAGS_logtostderr) { // Verify that a log file can be created in log_dir by creating a tmp file. stringstream ss; random_generator uuid_generator; ss << FLAGS_log_dir << "/" << "impala_test_log." << uuid_generator(); const string file_name = ss.str(); ofstream test_file(file_name.c_str()); if (!test_file.is_open()) { stringstream error_msg; error_msg << "Could not open file in log_dir " << FLAGS_log_dir; perror(error_msg.str().c_str()); // Unlock the mutex before exiting the program to avoid mutex d'tor assert. logging_mutex.unlock(); exit(1); } remove(file_name.c_str()); } google::InitGoogleLogging(arg); // Needs to be done after InitGoogleLogging if (FLAGS_log_filename.empty()) { FLAGS_log_filename = google::ProgramInvocationShortName(); } if (FLAGS_redirect_stdout_stderr && !TestInfo::is_test()) { // Needs to be done after InitGoogleLogging, to get the INFO/ERROR file paths. // Redirect stdout to INFO log and stderr to ERROR log string info_log_path, error_log_path; GetFullLogFilename(google::INFO, &info_log_path); GetFullLogFilename(google::ERROR, &error_log_path); // The log files are created on first use, log something to each before redirecting. LOG(INFO) << "stdout will be logged to this file."; LOG(ERROR) << "stderr will be logged to this file."; // Print to stderr/stdout before redirecting so people looking for these logs in // the standard place know where to look. cout << "Redirecting stdout to " << info_log_path << endl; cerr << "Redirecting stderr to " << error_log_path << endl; // TODO: how to handle these errors? Maybe abort the process? if (freopen(info_log_path.c_str(), "a", stdout) == NULL) { cout << "Could not redirect stdout: " << GetStrErrMsg(); } if (freopen(error_log_path.c_str(), "a", stderr) == NULL) { cerr << "Could not redirect stderr: " << GetStrErrMsg(); } } logging_initialized = true; } void impala::GetFullLogFilename(google::LogSeverity severity, string* filename) { stringstream ss; ss << FLAGS_log_dir << "/" << FLAGS_log_filename << "." << google::GetLogSeverityName(severity); *filename = ss.str(); } void impala::ShutdownLogging() { // This method may only correctly be called once (which this lock does not // enforce), but this lock protects against concurrent calls with // InitGoogleLoggingSafe mutex::scoped_lock logging_lock(logging_mutex); google::ShutdownGoogleLogging(); } void impala::LogCommandLineFlags() { LOG(INFO) << "Flags (see also /varz are on debug webserver):" << endl << google::CommandlineFlagsIntoString(); } void impala::CheckAndRotateLogFiles(int max_log_files) { // Map capturing mtimes, oldest files first typedef map<time_t, string> LogFileMap; // Ignore bad input or disable log rotation if (max_log_files <= 1) return; // Check log files for all severities for (int severity = 0; severity < google::NUM_SEVERITIES; ++severity) { // Build glob pattern for input // e.g. /tmp/impalad.*.INFO.* string fname = strings::Substitute("$0/$1.*.$2*", FLAGS_log_dir, FLAGS_log_filename, google::GetLogSeverityName(severity)); LogFileMap log_file_mtime; glob_t result; glob(fname.c_str(), GLOB_TILDE, NULL, &result); for (size_t i = 0; i < result.gl_pathc; ++i) { // Get the mtime for each match struct stat stat_val; if (stat(result.gl_pathv[i], &stat_val) != 0) { LOG(ERROR) << "Could not read last-modified-timestamp for log file " << result.gl_pathv[i] << ", will not delete (error was: " << strerror(errno) << ")"; continue; } log_file_mtime[stat_val.st_mtime] = result.gl_pathv[i]; } globfree(&result); // Iterate over the map and remove oldest log files first when too many // log files exist if (log_file_mtime.size() <= max_log_files) return; int files_to_delete = log_file_mtime.size() - max_log_files; DCHECK_GT(files_to_delete, 0); BOOST_FOREACH(const LogFileMap::reference val, log_file_mtime) { if (unlink(val.second.c_str()) == 0) { LOG(INFO) << "Old log file deleted during log rotation: " << val.second; } else { LOG(ERROR) << "Failed to delete old log file: " << val.second << "(error was: " << strerror(errno) << ")"; } if (--files_to_delete == 0) break; } } }
// Copyright 2012 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "common/logging.h" #include <boost/foreach.hpp> #include <boost/thread/mutex.hpp> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_generators.hpp> #include <boost/uuid/uuid_io.hpp> #include <cerrno> #include <ctime> #include <fstream> #include <glob.h> #include <gutil/strings/substitute.h> #include <iostream> #include <map> #include <sstream> #include <stdio.h> #include <sys/stat.h> #include "common/logging.h" #include "util/error-util.h" #include "util/test-info.h" DEFINE_string(log_filename, "", "Prefix of log filename - " "full path is <log_dir>/<log_filename>.[INFO|WARN|ERROR|FATAL]"); DEFINE_bool(redirect_stdout_stderr, true, "If true, redirects stdout/stderr to INFO/ERROR log."); bool logging_initialized = false; using namespace boost; using namespace std; using namespace boost::uuids; mutex logging_mutex; void impala::InitGoogleLoggingSafe(const char* arg) { mutex::scoped_lock logging_lock(logging_mutex); if (logging_initialized) return; if (!FLAGS_log_filename.empty()) { for (int severity = google::INFO; severity <= google::FATAL; ++severity) { google::SetLogSymlink(severity, FLAGS_log_filename.c_str()); } } // This forces our logging to use /tmp rather than looking for a // temporary directory if none is specified. This is done so that we // can reliably construct the log file name without duplicating the // complex logic that glog uses to guess at a temporary dir. if (FLAGS_log_dir.empty()) { FLAGS_log_dir = "/tmp"; } // Don't double log to stderr on any threshold. FLAGS_stderrthreshold = google::FATAL + 1; if (FLAGS_redirect_stdout_stderr && !TestInfo::is_test()) { // We will be redirecting stdout/stderr to INFO/LOG so override any glog settings // that log to stdout/stderr... FLAGS_logtostderr = false; FLAGS_alsologtostderr = false; } if (!FLAGS_logtostderr) { // Verify that a log file can be created in log_dir by creating a tmp file. stringstream ss; random_generator uuid_generator; ss << FLAGS_log_dir << "/" << "impala_test_log." << uuid_generator(); const string file_name = ss.str(); ofstream test_file(file_name.c_str()); if (!test_file.is_open()) { stringstream error_msg; error_msg << "Could not open file in log_dir " << FLAGS_log_dir; perror(error_msg.str().c_str()); // Unlock the mutex before exiting the program to avoid mutex d'tor assert. logging_mutex.unlock(); exit(1); } remove(file_name.c_str()); } google::InitGoogleLogging(arg); // Needs to be done after InitGoogleLogging if (FLAGS_log_filename.empty()) { FLAGS_log_filename = google::ProgramInvocationShortName(); } if (FLAGS_redirect_stdout_stderr && !TestInfo::is_test()) { // Needs to be done after InitGoogleLogging, to get the INFO/ERROR file paths. // Redirect stdout to INFO log and stderr to ERROR log string info_log_path, error_log_path; GetFullLogFilename(google::INFO, &info_log_path); GetFullLogFilename(google::ERROR, &error_log_path); // The log files are created on first use, log something to each before redirecting. LOG(INFO) << "stdout will be logged to this file."; LOG(ERROR) << "stderr will be logged to this file."; // Print to stderr/stdout before redirecting so people looking for these logs in // the standard place know where to look. cout << "Redirecting stdout to " << info_log_path << endl; cerr << "Redirecting stderr to " << error_log_path << endl; // TODO: how to handle these errors? Maybe abort the process? if (freopen(info_log_path.c_str(), "a", stdout) == NULL) { cout << "Could not redirect stdout: " << GetStrErrMsg(); } if (freopen(error_log_path.c_str(), "a", stderr) == NULL) { cerr << "Could not redirect stderr: " << GetStrErrMsg(); } } logging_initialized = true; } void impala::GetFullLogFilename(google::LogSeverity severity, string* filename) { stringstream ss; ss << FLAGS_log_dir << "/" << FLAGS_log_filename << "." << google::GetLogSeverityName(severity); *filename = ss.str(); } void impala::ShutdownLogging() { // This method may only correctly be called once (which this lock does not // enforce), but this lock protects against concurrent calls with // InitGoogleLoggingSafe mutex::scoped_lock logging_lock(logging_mutex); google::ShutdownGoogleLogging(); } void impala::LogCommandLineFlags() { LOG(INFO) << "Flags (see also /varz are on debug webserver):" << endl << google::CommandlineFlagsIntoString(); } void impala::CheckAndRotateLogFiles(int max_log_files) { // Map capturing mtimes, oldest files first typedef map<time_t, string> LogFileMap; // Ignore bad input or disable log rotation if (max_log_files <= 1) return; // Check log files for all severities for (int severity = 0; severity < google::NUM_SEVERITIES; ++severity) { // Build glob pattern for input // e.g. /tmp/impalad.*.INFO.* string fname = strings::Substitute("$0/$1.*.$2*", FLAGS_log_dir, FLAGS_log_filename, google::GetLogSeverityName(severity)); LogFileMap log_file_mtime; glob_t result; glob(fname.c_str(), GLOB_TILDE, NULL, &result); for (size_t i = 0; i < result.gl_pathc; ++i) { // Get the mtime for each match struct stat stat_val; if (stat(result.gl_pathv[i], &stat_val) != 0) { LOG(ERROR) << "Could not read last-modified-timestamp for log file " << result.gl_pathv[i] << ", will not delete (error was: " << strerror(errno) << ")"; continue; } log_file_mtime[stat_val.st_mtime] = result.gl_pathv[i]; } globfree(&result); // Iterate over the map and remove oldest log files first when too many // log files exist if (log_file_mtime.size() <= max_log_files) return; int files_to_delete = log_file_mtime.size() - max_log_files; DCHECK_GT(files_to_delete, 0); BOOST_FOREACH(const LogFileMap::reference val, log_file_mtime) { if (unlink(val.second.c_str()) == 0) { LOG(INFO) << "Old log file deleted during log rotation: " << val.second; } else { LOG(ERROR) << "Failed to delete old log file: " << val.second << "(error was: " << strerror(errno) << ")"; } if (--files_to_delete == 0) break; } } }
Disable ERROR double-logging to stdout
Disable ERROR double-logging to stdout Glog has a useful feature where ERROR messages are always at least written to stdout, no matter what the rest of the logging setup is. However, we don't rely on stdout in our deployments, and for local tests this means that Java LOG.error() messages are always written to stdout. This affects some of our tests which deliberately hit error paths, and produce a lot of output (Sentry is the prime example). So let's always disable double-logging (it was mostly disabled before). Change-Id: Ife6f8e37b1b8eed0fee887c296c40f8ddb3a73e7 Reviewed-on: http://gerrit.sjc.cloudera.com:8080/5787 Reviewed-by: Henry Robinson <[email protected]> Tested-by: jenkins
C++
apache-2.0
ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC
15cb3dea5e84e94111666a052081b0f182b0b2c9
be/src/util/avro-util.cc
be/src/util/avro-util.cc
// Copyright 2015 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <avro/schema.h> #include "util/avro-util.h" using namespace std; namespace impala { const char* AvroSchemaElement::LLVM_CLASS_NAME = "struct.impala::AvroSchemaElement"; bool IsSupportedAvroType(const avro_schema_t& schema) { switch (schema->type) { case AVRO_STRING: case AVRO_BYTES: case AVRO_INT32: case AVRO_INT64: case AVRO_FLOAT: case AVRO_DOUBLE: case AVRO_BOOLEAN: case AVRO_NULL: case AVRO_RECORD: case AVRO_DECIMAL: return true; default: return false; } } Status AvroSchemaElement::ConvertSchema( const avro_schema_t& schema, AvroSchemaElement* element) { element->schema = schema; // Look for special case of [<supported type>, "null"] union if (element->schema->type == AVRO_UNION) { int num_fields = avro_schema_union_size(schema); DCHECK_GT(num_fields, 0); if (num_fields == 2) { const avro_schema_t& child0 = avro_schema_union_branch(schema, 0); const avro_schema_t& child1 = avro_schema_union_branch(schema, 1); int null_position = -1; if (child0->type == AVRO_NULL) { null_position = 0; } else if (child1->type == AVRO_NULL) { null_position = 1; } if (null_position != -1) { const avro_schema_t& non_null_child = null_position == 0 ? child1 : child0; AvroSchemaElement child; RETURN_IF_ERROR(ConvertSchema(non_null_child, &child)); // 'schema' is a [<child>, "null"] union. Treat this node as the same type as // child except with null_union_position set appropriately. DCHECK_EQ(child.null_union_position, -1) << "Avro spec does not allow immediately nested unions"; *element = child; element->null_union_position = null_position; } } } // Check type after we process unions so we don't flag null unions. if (!IsSupportedAvroType(element->schema)) { stringstream ss; ss << "Avro enum, array, map, union, and fixed types are not supported. " << "Got type: " << avro_type_name(element->schema->type); return Status(ss.str()); } if (element->schema->type == AVRO_RECORD) { int num_fields = avro_schema_record_size(element->schema); element->children.resize(num_fields); for (int i = 0; i < num_fields; ++i) { avro_schema_t field = avro_schema_record_field_get_by_index(element->schema, i); RETURN_IF_ERROR(ConvertSchema(field, &element->children[i])); } } return Status::OK(); } ScopedAvroSchemaElement::~ScopedAvroSchemaElement() { // avro_schema_decref can handle NULL. If element_.schema is a record or other complex // type, it will recursively decref it's children when it's free. avro_schema_decref(element_.schema); } ColumnType AvroSchemaToColumnType(const avro_schema_t& schema) { switch (schema->type) { case AVRO_BYTES: case AVRO_STRING: return TYPE_STRING; case AVRO_INT32: return TYPE_INT; case AVRO_INT64: return TYPE_BIGINT; case AVRO_FLOAT: return TYPE_FLOAT; case AVRO_DOUBLE: return TYPE_DOUBLE; case AVRO_BOOLEAN: return TYPE_BOOLEAN; case AVRO_DECIMAL: return ColumnType::CreateDecimalType( avro_schema_decimal_precision(schema), avro_schema_decimal_scale(schema)); default: DCHECK(false) << "NYI: " << avro_type_name(schema->type); return INVALID_TYPE; } } }
// Copyright 2015 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <avro/schema.h> #include "util/avro-util.h" using namespace std; namespace impala { const char* AvroSchemaElement::LLVM_CLASS_NAME = "struct.impala::AvroSchemaElement"; bool IsSupportedAvroType(const avro_schema_t& schema) { switch (schema->type) { case AVRO_STRING: case AVRO_BYTES: case AVRO_INT32: case AVRO_INT64: case AVRO_FLOAT: case AVRO_DOUBLE: case AVRO_BOOLEAN: case AVRO_NULL: case AVRO_RECORD: case AVRO_DECIMAL: return true; default: return false; } } Status AvroSchemaElement::ConvertSchema( const avro_schema_t& schema, AvroSchemaElement* element) { element->schema = schema; // Look for special case of [<supported type>, "null"] union if (element->schema->type == AVRO_UNION) { int num_fields = avro_schema_union_size(schema); DCHECK_GT(num_fields, 0); if (num_fields == 2) { const avro_schema_t& child0 = avro_schema_union_branch(schema, 0); const avro_schema_t& child1 = avro_schema_union_branch(schema, 1); int null_position = -1; if (child0->type == AVRO_NULL) { null_position = 0; } else if (child1->type == AVRO_NULL) { null_position = 1; } if (null_position != -1) { const avro_schema_t& non_null_child = null_position == 0 ? child1 : child0; AvroSchemaElement child; RETURN_IF_ERROR(ConvertSchema(non_null_child, &child)); // 'schema' is a [<child>, "null"] union. Treat this node as the same type as // child except with null_union_position set appropriately. DCHECK_EQ(child.null_union_position, -1) << "Avro spec does not allow immediately nested unions"; *element = child; element->null_union_position = null_position; return Status::OK(); } } } if (!IsSupportedAvroType(element->schema)) { stringstream ss; ss << "Avro enum, array, map, union, and fixed types are not supported. " << "Got type: " << avro_type_name(element->schema->type); return Status(ss.str()); } if (element->schema->type == AVRO_RECORD) { int num_fields = avro_schema_record_size(element->schema); element->children.resize(num_fields); for (int i = 0; i < num_fields; ++i) { avro_schema_t field = avro_schema_record_field_get_by_index(element->schema, i); RETURN_IF_ERROR(ConvertSchema(field, &element->children[i])); } } return Status::OK(); } ScopedAvroSchemaElement::~ScopedAvroSchemaElement() { // avro_schema_decref can handle NULL. If element_.schema is a record or other complex // type, it will recursively decref it's children when it's free. avro_schema_decref(element_.schema); } ColumnType AvroSchemaToColumnType(const avro_schema_t& schema) { switch (schema->type) { case AVRO_BYTES: case AVRO_STRING: return TYPE_STRING; case AVRO_INT32: return TYPE_INT; case AVRO_INT64: return TYPE_BIGINT; case AVRO_FLOAT: return TYPE_FLOAT; case AVRO_DOUBLE: return TYPE_DOUBLE; case AVRO_BOOLEAN: return TYPE_BOOLEAN; case AVRO_DECIMAL: return ColumnType::CreateDecimalType( avro_schema_decimal_precision(schema), avro_schema_decimal_scale(schema)); default: DCHECK(false) << "NYI: " << avro_type_name(schema->type); return INVALID_TYPE; } } }
make AvroSchemaElement::ConvertSchema() run in linear time
IMPALA-2374: make AvroSchemaElement::ConvertSchema() run in linear time In the case of nullable records, ConvertSchema() was recursively calling itself twice, rather than once. This made ConvertSchema() run in exponential time with respect to the number of nested nullable records. Change-Id: I39ba75076a348640bfb9a3d6e14948f6720cb0c8 Reviewed-on: http://gerrit.cloudera.org:8080/1123 Reviewed-by: Dan Hecht <[email protected]> Tested-by: Internal Jenkins
C++
apache-2.0
ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC
27f5a5bcf5b7066c6314acdccd1e7c4ac304a5aa
compiler/AST/ForLoop.cpp
compiler/AST/ForLoop.cpp
/* * Copyright 2004-2014 Cray Inc. * Other additional copyright holders may be indicated within. * * The entirety of this work is licensed under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ForLoop.h" #include "astutil.h" #include "AstVisitor.h" #include "build.h" #include "codegen.h" #include <algorithm> /************************************ | ************************************* * * * Helper functions to optimize anonymous range iteration * * * ************************************* | ************************************/ /* * Attempts to replace iteration over simple anonymous ranges with calls to * direct iterators that take low, high and stride as arguments. This is to * avoid the cost of constructing ranges, and if the stride is known at compile * time, provide a more optimized iterator that uses "<, <=, >, or >=" as the * relational operator. * * This is only meant to replace anonymous range iteration for "simple" bounded * ranges. Simple means it's a range of the form "low..high" or "low..high by * stride". Anything more complex is ignored with the thinking that this should * optimize the most common range iterators, but it could be expanded to handle * more cases. * * An alternative is to update scalar replacement of aggregates to work on * ranges, which should be able to achieve similar results as this optimization * while handling all ranges, including non-anonymous ranges. * * Will optimize things like: * - "for i in 1..10" * - "for i in 1..10 by 2" * - "for (i, j) in zip(1..10 by 2, 1..10 by -2)" * - "for (i, j) in zip(A, 1..10 by 2)" // will optimize range iter still * - "coforall i in 1..10 by 2" // works for coforalls as well * * Will not optimize ranges like: * - "for in in (1..)" // doesn't handle unbounded ranges * - "for i in 1..10 by 2 by 2" // doesn't handle more than one by operator * - "for i in 1..10 align 2" // doesn't handle align operator * - "for i in 1..#10" // doesn't handle # operator * - "var r = 1..10"; for i in r" // not an anonymous range * - "forall i in 1..10" // does not get applied to foralls * * Note that this function is pretty fragile because it relies on names of * functions/iterators as well as the arguments and order of those * functions/iterators but there's not really a way around it this early in * compilation. If the iterator can't be replaced the original, unchanged * iteratorExpr is returned. */ static Expr* tryToUseDirectRangeIterator(Expr* iteratorExpr) { CallExpr* range = NULL; Expr* stride = NULL; if (CallExpr* call = toCallExpr(iteratorExpr)) { // grab the stride if we have a strided ranges if (call->isNamed("by")) { range = toCallExpr(call->get(1)->copy()); stride = toExpr(call->get(2)->copy()); } else { range = call; } // see if we're looking at a _build_range for an anonymous range if (range && range->isNamed("_build_range")) { // just a sanity check, this should always be true if (range->numActuals() == 2) { Expr* low = range->get(1)->copy(); Expr* high = range->get(2)->copy(); // only get bounded ranges, unbounded takes a BoundedRangeType as the // first argument, which turns into a CallExpr. This is probably the // best way to check for bounded ranges this early in compilation if ((isUnresolvedSymExpr(low) || isSymExpr(low)) && (isUnresolvedSymExpr(high) || isSymExpr(high))) { // replace the range construction with a direct range iterator if (stride) { iteratorExpr = (new CallExpr("_direct_range_iter", low, high, stride)); } else { SymExpr* noStr = new SymExpr(new_IntSymbol(1)); iteratorExpr = (new CallExpr("_direct_range_iter", low, high, noStr)); } } } } } return iteratorExpr; } static Expr* optimizeRangeIteration(Expr* iteratorExpr, bool zippered) { iteratorExpr = tryToUseDirectRangeIterator(iteratorExpr); // for zippered iterators, try to replace each iterator of the tuple if (zippered) { if (CallExpr* call = toCallExpr(iteratorExpr)) { if (call->isNamed("_build_tuple")) { for_actuals(actual, call) { actual->replace(tryToUseDirectRangeIterator(actual->copy())); } } } } return iteratorExpr; } /************************************ | ************************************* * * * Factory methods for the Parser * * * ************************************* | ************************************/ BlockStmt* ForLoop::buildForLoop(Expr* indices, Expr* iteratorExpr, BlockStmt* body, bool coforall, bool zippered) { VarSymbol* index = newTemp("_indexOfInterest"); VarSymbol* iterator = newTemp("_iterator"); CallExpr* iterInit = 0; CallExpr* iterMove = 0; ForLoop* loop = new ForLoop(index, iterator, body); LabelSymbol* continueLabel = new LabelSymbol("_continueLabel"); LabelSymbol* breakLabel = new LabelSymbol("_breakLabel"); BlockStmt* retval = new BlockStmt(); iteratorExpr = optimizeRangeIteration(iteratorExpr, zippered); iterator->addFlag(FLAG_EXPR_TEMP); // Unzippered loop, treat all objects (including tuples) the same if (zippered == false) iterInit = new CallExpr(PRIM_MOVE, iterator, new CallExpr("_getIterator", iteratorExpr)); // Expand tuple to a tuple containing appropriate iterators for each value. else iterInit = new CallExpr(PRIM_MOVE, iterator, new CallExpr("_getIteratorZip", iteratorExpr)); index->addFlag(FLAG_INDEX_OF_INTEREST); iterMove = new CallExpr(PRIM_MOVE, index, new CallExpr("iteratorIndex", iterator)); if (indices == 0) indices = new UnresolvedSymExpr("chpl__elidedIdx"); checkIndices(indices); destructureIndices(loop, indices, new SymExpr(index), coforall); if (coforall) index->addFlag(FLAG_COFORALL_INDEX_VAR); loop->mContinueLabel = continueLabel; loop->mBreakLabel = breakLabel; loop->insertAtTail(new DefExpr(continueLabel)); retval->insertAtTail(new DefExpr(index)); retval->insertAtTail(new DefExpr(iterator)); retval->insertAtTail(iterInit); retval->insertAtTail(new BlockStmt(iterMove, BLOCK_TYPE)); retval->insertAtTail(loop); retval->insertAtTail(new DefExpr(breakLabel)); retval->insertAtTail(new CallExpr("_freeIterator", iterator)); return retval; } /************************************ | ************************************* * * * Instance methods * * * ************************************* | ************************************/ ForLoop::ForLoop() : LoopStmt(0) { mIndex = 0; mIterator = 0; } ForLoop::ForLoop(VarSymbol* index, VarSymbol* iterator, BlockStmt* initBody) : LoopStmt(initBody) { mIndex = new SymExpr(index); mIterator = new SymExpr(iterator); } ForLoop::~ForLoop() { } ForLoop* ForLoop::copy(SymbolMap* mapRef, bool internal) { SymbolMap localMap; SymbolMap* map = (mapRef != 0) ? mapRef : &localMap; ForLoop* retval = new ForLoop(); retval->astloc = astloc; retval->blockTag = blockTag; retval->mBreakLabel = mBreakLabel; retval->mContinueLabel = mContinueLabel; retval->mIndex = mIndex->copy(map, true), retval->mIterator = mIterator->copy(map, true); for_alist(expr, body) retval->insertAtTail(expr->copy(map, true)); if (internal == false) update_symbols(retval, map); return retval; } BlockStmt* ForLoop::copyBody() { SymbolMap map; return copyBody(&map); } BlockStmt* ForLoop::copyBody(SymbolMap* map) { BlockStmt* retval = new BlockStmt(); retval->astloc = astloc; retval->blockTag = blockTag; for_alist(expr, body) retval->insertAtTail(expr->copy(map, true)); update_symbols(retval, map); return retval; } bool ForLoop::isForLoop() const { return true; } SymExpr* ForLoop::indexGet() const { return mIndex; } SymExpr* ForLoop::iteratorGet() const { return mIterator; } CallExpr* ForLoop::blockInfoGet() const { printf("Migration: ForLoop %12d Unexpected call to blockInfoGet()\n", id); return 0; } CallExpr* ForLoop::blockInfoSet(CallExpr* expr) { printf("Migration: ForLoop %12d Unexpected call to blockInfoSet()\n", id); return 0; } bool ForLoop::deadBlockCleanup() { bool retval = false; INT_ASSERT(false); return retval; } void ForLoop::verify() { BlockStmt::verify(); if (BlockStmt::blockInfoGet() != 0) INT_FATAL(this, "ForLoop::verify. blockInfo is not NULL"); if (mIndex == 0) INT_FATAL(this, "ForLoop::verify. index is NULL"); if (mIterator == 0) INT_FATAL(this, "ForLoop::verify. iterator is NULL"); if (modUses != 0) INT_FATAL(this, "ForLoop::verify. modUses is not NULL"); if (byrefVars != 0) INT_FATAL(this, "ForLoop::verify. byrefVars is not NULL"); } GenRet ForLoop::codegen() { GenRet ret; INT_FATAL(this, "ForLoop::codegen This should be unreachable"); return ret; } void ForLoop::accept(AstVisitor* visitor) { if (visitor->enterForLoop(this) == true) { for_alist(next_ast, body) next_ast->accept(visitor); if (indexGet() != 0) indexGet()->accept(visitor); if (iteratorGet() != 0) iteratorGet()->accept(visitor); if (modUses) modUses->accept(visitor); if (byrefVars) byrefVars->accept(visitor); visitor->exitForLoop(this); } } Expr* ForLoop::getFirstExpr() { Expr* retval = 0; if (mIndex != 0) retval = mIndex; else if (mIterator != 0) retval = mIterator; else if (body.head != 0) retval = body.head->getFirstExpr(); else retval = this; return retval; } Expr* ForLoop::getNextExpr(Expr* expr) { Expr* retval = this; if (expr == mIndex && mIterator != NULL) retval = mIterator; else if (expr == mIndex && body.head != NULL) retval = body.head->getFirstExpr(); else if (expr == mIterator && body.head != NULL) retval = body.head->getFirstExpr(); return retval; }
/* * Copyright 2004-2014 Cray Inc. * Other additional copyright holders may be indicated within. * * The entirety of this work is licensed under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ForLoop.h" #include "astutil.h" #include "AstVisitor.h" #include "build.h" #include "codegen.h" #include <algorithm> /************************************ | ************************************* * * * Helper functions to optimize anonymous range iteration * * * ************************************* | ************************************/ /* * Attempts to replace iteration over simple anonymous ranges with calls to * direct iterators that take low, high and stride as arguments. This is to * avoid the cost of constructing ranges, and if the stride is known at compile * time, provide a more optimized iterator that uses "<, <=, >, or >=" as the * relational operator. * * This is only meant to replace anonymous range iteration for "simple" bounded * ranges. Simple means it's a range of the form "low..high" or "low..high by * stride". Anything more complex is ignored with the thinking that this should * optimize the most common range iterators, but it could be expanded to handle * more cases. * * An alternative is to update scalar replacement of aggregates to work on * ranges, which should be able to achieve similar results as this optimization * while handling all ranges, including non-anonymous ranges. * * Will optimize things like: * - "for i in 1..10" * - "for i in 1..10 by 2" * - "for (i, j) in zip(1..10 by 2, 1..10 by -2)" * - "for (i, j) in zip(A, 1..10 by 2)" // will optimize range iter still * - "coforall i in 1..10 by 2" // works for coforalls as well * * Will not optimize ranges like: * - "for in in (1..)" // doesn't handle unbounded ranges * - "for i in 1..10 by 2 by 2" // doesn't handle more than one by operator * - "for i in 1..10 align 2" // doesn't handle align operator * - "for i in 1..#10" // doesn't handle # operator * - "var r = 1..10"; for i in r" // not an anonymous range * - "forall i in 1..10" // does not get applied to foralls * * Note that this function is pretty fragile because it relies on names of * functions/iterators as well as the arguments and order of those * functions/iterators but there's not really a way around it this early in * compilation. If the iterator can't be replaced the original, unchanged * iteratorExpr is returned. */ static Expr* tryToUseDirectRangeIterator(Expr* iteratorExpr) { CallExpr* range = NULL; Expr* stride = NULL; if (CallExpr* call = toCallExpr(iteratorExpr)) { // grab the stride if we have a strided ranges if (call->isNamed("by")) { range = toCallExpr(call->get(1)->copy()); stride = toExpr(call->get(2)->copy()); } else { range = call; } // see if we're looking at a _build_range for an anonymous range if (range && range->isNamed("chpl_build_bounded_range")) { Expr* low = range->get(1)->copy(); Expr* high = range->get(2)->copy(); // replace the range construction with a direct range iterator if (stride) { iteratorExpr = (new CallExpr("_direct_range_iter", low, high, stride)); } else { SymExpr* noStr = new SymExpr(new_IntSymbol(1)); iteratorExpr = (new CallExpr("_direct_range_iter", low, high, noStr)); } } } return iteratorExpr; } static Expr* optimizeRangeIteration(Expr* iteratorExpr, bool zippered) { iteratorExpr = tryToUseDirectRangeIterator(iteratorExpr); // for zippered iterators, try to replace each iterator of the tuple if (zippered) { if (CallExpr* call = toCallExpr(iteratorExpr)) { if (call->isNamed("_build_tuple")) { for_actuals(actual, call) { actual->replace(tryToUseDirectRangeIterator(actual->copy())); } } } } return iteratorExpr; } /************************************ | ************************************* * * * Factory methods for the Parser * * * ************************************* | ************************************/ BlockStmt* ForLoop::buildForLoop(Expr* indices, Expr* iteratorExpr, BlockStmt* body, bool coforall, bool zippered) { VarSymbol* index = newTemp("_indexOfInterest"); VarSymbol* iterator = newTemp("_iterator"); CallExpr* iterInit = 0; CallExpr* iterMove = 0; ForLoop* loop = new ForLoop(index, iterator, body); LabelSymbol* continueLabel = new LabelSymbol("_continueLabel"); LabelSymbol* breakLabel = new LabelSymbol("_breakLabel"); BlockStmt* retval = new BlockStmt(); iteratorExpr = optimizeRangeIteration(iteratorExpr, zippered); iterator->addFlag(FLAG_EXPR_TEMP); // Unzippered loop, treat all objects (including tuples) the same if (zippered == false) iterInit = new CallExpr(PRIM_MOVE, iterator, new CallExpr("_getIterator", iteratorExpr)); // Expand tuple to a tuple containing appropriate iterators for each value. else iterInit = new CallExpr(PRIM_MOVE, iterator, new CallExpr("_getIteratorZip", iteratorExpr)); index->addFlag(FLAG_INDEX_OF_INTEREST); iterMove = new CallExpr(PRIM_MOVE, index, new CallExpr("iteratorIndex", iterator)); if (indices == 0) indices = new UnresolvedSymExpr("chpl__elidedIdx"); checkIndices(indices); destructureIndices(loop, indices, new SymExpr(index), coforall); if (coforall) index->addFlag(FLAG_COFORALL_INDEX_VAR); loop->mContinueLabel = continueLabel; loop->mBreakLabel = breakLabel; loop->insertAtTail(new DefExpr(continueLabel)); retval->insertAtTail(new DefExpr(index)); retval->insertAtTail(new DefExpr(iterator)); retval->insertAtTail(iterInit); retval->insertAtTail(new BlockStmt(iterMove, BLOCK_TYPE)); retval->insertAtTail(loop); retval->insertAtTail(new DefExpr(breakLabel)); retval->insertAtTail(new CallExpr("_freeIterator", iterator)); return retval; } /************************************ | ************************************* * * * Instance methods * * * ************************************* | ************************************/ ForLoop::ForLoop() : LoopStmt(0) { mIndex = 0; mIterator = 0; } ForLoop::ForLoop(VarSymbol* index, VarSymbol* iterator, BlockStmt* initBody) : LoopStmt(initBody) { mIndex = new SymExpr(index); mIterator = new SymExpr(iterator); } ForLoop::~ForLoop() { } ForLoop* ForLoop::copy(SymbolMap* mapRef, bool internal) { SymbolMap localMap; SymbolMap* map = (mapRef != 0) ? mapRef : &localMap; ForLoop* retval = new ForLoop(); retval->astloc = astloc; retval->blockTag = blockTag; retval->mBreakLabel = mBreakLabel; retval->mContinueLabel = mContinueLabel; retval->mIndex = mIndex->copy(map, true), retval->mIterator = mIterator->copy(map, true); for_alist(expr, body) retval->insertAtTail(expr->copy(map, true)); if (internal == false) update_symbols(retval, map); return retval; } BlockStmt* ForLoop::copyBody() { SymbolMap map; return copyBody(&map); } BlockStmt* ForLoop::copyBody(SymbolMap* map) { BlockStmt* retval = new BlockStmt(); retval->astloc = astloc; retval->blockTag = blockTag; for_alist(expr, body) retval->insertAtTail(expr->copy(map, true)); update_symbols(retval, map); return retval; } bool ForLoop::isForLoop() const { return true; } SymExpr* ForLoop::indexGet() const { return mIndex; } SymExpr* ForLoop::iteratorGet() const { return mIterator; } CallExpr* ForLoop::blockInfoGet() const { printf("Migration: ForLoop %12d Unexpected call to blockInfoGet()\n", id); return 0; } CallExpr* ForLoop::blockInfoSet(CallExpr* expr) { printf("Migration: ForLoop %12d Unexpected call to blockInfoSet()\n", id); return 0; } bool ForLoop::deadBlockCleanup() { bool retval = false; INT_ASSERT(false); return retval; } void ForLoop::verify() { BlockStmt::verify(); if (BlockStmt::blockInfoGet() != 0) INT_FATAL(this, "ForLoop::verify. blockInfo is not NULL"); if (mIndex == 0) INT_FATAL(this, "ForLoop::verify. index is NULL"); if (mIterator == 0) INT_FATAL(this, "ForLoop::verify. iterator is NULL"); if (modUses != 0) INT_FATAL(this, "ForLoop::verify. modUses is not NULL"); if (byrefVars != 0) INT_FATAL(this, "ForLoop::verify. byrefVars is not NULL"); } GenRet ForLoop::codegen() { GenRet ret; INT_FATAL(this, "ForLoop::codegen This should be unreachable"); return ret; } void ForLoop::accept(AstVisitor* visitor) { if (visitor->enterForLoop(this) == true) { for_alist(next_ast, body) next_ast->accept(visitor); if (indexGet() != 0) indexGet()->accept(visitor); if (iteratorGet() != 0) iteratorGet()->accept(visitor); if (modUses) modUses->accept(visitor); if (byrefVars) byrefVars->accept(visitor); visitor->exitForLoop(this); } } Expr* ForLoop::getFirstExpr() { Expr* retval = 0; if (mIndex != 0) retval = mIndex; else if (mIterator != 0) retval = mIterator; else if (body.head != 0) retval = body.head->getFirstExpr(); else retval = this; return retval; } Expr* ForLoop::getNextExpr(Expr* expr) { Expr* retval = this; if (expr == mIndex && mIterator != NULL) retval = mIterator; else if (expr == mIndex && body.head != NULL) retval = body.head->getFirstExpr(); else if (expr == mIterator && body.head != NULL) retval = body.head->getFirstExpr(); return retval; }
Update to use chpl_build_bounded_range
Update to use chpl_build_bounded_range
C++
apache-2.0
chizarlicious/chapel,hildeth/chapel,hildeth/chapel,chizarlicious/chapel,hildeth/chapel,chizarlicious/chapel,chizarlicious/chapel,chizarlicious/chapel,CoryMcCartan/chapel,chizarlicious/chapel,CoryMcCartan/chapel,hildeth/chapel,CoryMcCartan/chapel,CoryMcCartan/chapel,hildeth/chapel,CoryMcCartan/chapel,hildeth/chapel,CoryMcCartan/chapel,CoryMcCartan/chapel,chizarlicious/chapel,hildeth/chapel
e9a167bb9fa59f4adfdb780fcc9eccb59469ebd8
benchmarks/benchmark.cpp
benchmarks/benchmark.cpp
#include <cstdio> #include <cstdlib> #include <cstring> #include <iomanip> #include <iostream> using namespace std; extern "C" { #include "tabulated.h" #include "clhash.h" } inline uint64_t RDTSC_START() { register unsigned cyc_high, cyc_low; __asm volatile("cpuid\n\t" "rdtsc\n\t" "mov %%edx, %0\n\t" "mov %%eax, %1\n\t" : "=r"(cyc_high), "=r"(cyc_low)::"%rax", "%rbx", "%rcx", "%rdx"); return ((uint64_t)cyc_high << 32) | cyc_low; } inline uint64_t RDTSC_FINAL() { register unsigned cyc_high, cyc_low; __asm volatile("rdtscp\n\t" "mov %%edx, %0\n\t" "mov %%eax, %1\n\t" "cpuid\n\t" : "=r"(cyc_high), "=r"(cyc_low)::"%rax", "%rbx", "%rcx", "%rdx"); return ((uint64_t)cyc_high << 32) | cyc_low; } static __attribute__((noinline)) uint64_t rdtsc_overhead_func(uint64_t dummy) { return dummy; } uint64_t global_rdtsc_overhead = (uint64_t)UINT64_MAX; void RDTSC_SET_OVERHEAD(int repeat) { uint64_t cycles_start, cycles_final, cycles_diff; uint64_t min_diff = UINT64_MAX; for (int i = 0; i < repeat; i++) { __asm volatile("" ::: /* pretend to clobber */ "memory"); cycles_start = RDTSC_START(); rdtsc_overhead_func(1); cycles_final = RDTSC_FINAL(); cycles_diff = (cycles_final - cycles_start); if (cycles_diff < min_diff) min_diff = cycles_diff; } global_rdtsc_overhead = min_diff; printf("rdtsc_overhead set to %d\n", (int)global_rdtsc_overhead); } /* * Prints the best number of operations per cycle where * test is the function call, repeat is the number of times we should repeat * and size is the * number of operations represented by test. */ template <typename T> inline void BEST_TIME(const T &hasher, int repeat, int size) { fflush(NULL); uint64_t cycles_start, cycles_final, cycles_diff; uint64_t min_diff = (uint64_t)-1; int wrong_answer = 0; for (int i = 0; i < repeat; i++) { __asm volatile("" ::: /* pretend to clobber */ "memory"); hasher.Restart(); cycles_start = RDTSC_START(); if (hasher.Hash() != hasher.expected_) wrong_answer = 1; cycles_final = RDTSC_FINAL(); cycles_diff = (cycles_final - cycles_start); if (cycles_diff < min_diff) min_diff = cycles_diff; } min_diff -= global_rdtsc_overhead; uint64_t S = (uint64_t)size; float cycle_per_op = (min_diff) / (float)S; printf("%.2f cycles per word ", cycle_per_op); if (wrong_answer) printf(" [ERROR]"); printf("\n"); fflush(NULL); } template <typename HashDataType, typename HashValueType, HashValueType HashFunction(HashValueType, const HashDataType *)> struct HashBench { inline void Restart() const { flush(&k_, sizeof(k_)); } inline HashValueType Hash() const { HashValueType sum = 0; for (uint32_t x = 0; x < length_; ++x) { sum += HashFunction(array_[x], k_); } return sum; } HashBench(const HashValueType *const array, const uint32_t length, const HashDataType *const k) : array_(array), length_(length), k_(k) { expected_ = Hash(); } const HashValueType * const array_; const uint32_t length_; const HashDataType * const k_; HashValueType expected_; }; void flush(const void *b, size_t length) { char *B = (char *)b; for (uint32_t k = 0; k < length; k += 64) { __builtin_ia32_clflush(B + k); } } void basic(uint32_t length, int repeat) { printf("Testing 64-bit hashing.\n"); printf("We will construct an array of %d words (using %d bytes), to be " "hashed.\n", (int)length, (int)(length * sizeof(uint64_t))); cl_linear_t cl_lineark; cl_linear_init(&cl_lineark); cl_quadratic_t cl_quadratick; cl_quadratic_init(&cl_quadratick); cl_cubic_t cl_cubick; cl_cubic_init(&cl_cubick); zobrist_t zobristk; zobrist_init(&zobristk); printf("sizeof(cl_lineark) = %d, sizeof(cl_quadratick) = %d, " "sizeof(cl_cubick) = %d, sizeof(zobristk) = %d \n", (int)sizeof(cl_lineark), (int)sizeof(cl_quadratick), (int)sizeof(cl_cubick), (int)sizeof(zobristk)); uint64_t *array = (uint64_t *)malloc(sizeof(uint64_t) * length); for (uint32_t i = 0; i < length; ++i) { array[i] = get64rand(); } uint32_t size = length; cout << setw(20) << "zobrist: "; HashBench<zobrist_t, uint64_t, zobrist> demo_zobrist(array, length, &zobristk); BEST_TIME(demo_zobrist, repeat, size); cout << setw(20) << "cl_linear: "; HashBench<cl_linear_t, uint64_t, cl_linear> demo_linear(array, length, &cl_lineark); BEST_TIME(demo_linear, repeat, size); cout << setw(20) << "cl_quadratic: "; HashBench<cl_quadratic_t, uint64_t, cl_quadratic> demo_quadratic( array, length, &cl_quadratick); BEST_TIME(demo_quadratic, repeat, size); cout << setw(20) << "cl_cubic: "; HashBench<cl_cubic_t, uint64_t, cl_cubic> demo_cubic(array, length, &cl_cubick); BEST_TIME(demo_cubic, repeat, size); free(array); printf("\n"); } void basic32(uint32_t length, int repeat) { printf("Testing 32-bit hashing.\n"); printf("We will construct an array of %d words (using %d bytes), to be " "hashed.\n", (int)length, (int)(length * sizeof(uint32_t))); cl_quadratic_t cl_quadratick; cl_quadratic32_init(&cl_quadratick); cl_linear_t cl_lineark; cl_linear32_init(&cl_lineark); zobrist32_t zobristk; zobrist32_init(&zobristk); printf(" sizeof(cl_lineark) = %d, sizeof(cl_quadratick) = %d, " "sizeof(zobristk) = %d \n", (int)sizeof(cl_lineark), (int)sizeof(cl_quadratick), (int)sizeof(zobristk)); uint32_t *array = (uint32_t *)malloc(sizeof(uint32_t) * length); for (uint32_t i = 0; i < length; ++i) { array[i] = get32rand(); } uint32_t size = length; cout << setw(20) << "zobrist: "; HashBench<zobrist32_t, uint32_t, zobrist32> demo_zobrist(array, length, &zobristk); BEST_TIME(demo_zobrist, repeat, size); cout << setw(20) << "cl_linear: "; HashBench<cl_linear_t, uint32_t, cl_linear32> demo_linear(array, length, &cl_lineark); BEST_TIME(demo_linear, repeat, size); cout << setw(20) << "cl_quadratic: "; HashBench<cl_quadratic_t, uint32_t, cl_quadratic32> demo_quadratic( array, length, &cl_quadratick); BEST_TIME(demo_quadratic, repeat, size); free(array); printf("\n"); } int main() { int repeat = 50000; if (global_rdtsc_overhead == UINT64_MAX) { RDTSC_SET_OVERHEAD(repeat); } printf("zobrist is 3-wise ind., linear is 2-wise ind., quadratic is 3-wise " "ind., cubic is 4-wise ind.\n"); printf("Keys are flushed at the beginning of each run.\n"); printf("======="); basic(10, repeat); basic(20, repeat); basic(100, repeat); basic(1000, repeat); printf("======="); basic32(10, repeat); basic32(20, repeat); basic32(100, repeat); basic32(1000, repeat); printf("Large runs are beneficial to tabulation-based hashing because they " "amortize cache faults.\n"); }
#include <cstdio> #include <cstdlib> #include <cstring> #include <iomanip> #include <iostream> using namespace std; extern "C" { #include "tabulated.h" #include "clhash.h" } inline uint64_t RDTSC_START() { register unsigned cyc_high, cyc_low; __asm volatile("cpuid\n\t" "rdtsc\n\t" "mov %%edx, %0\n\t" "mov %%eax, %1\n\t" : "=r"(cyc_high), "=r"(cyc_low)::"%rax", "%rbx", "%rcx", "%rdx"); return ((uint64_t)cyc_high << 32) | cyc_low; } inline uint64_t RDTSC_FINAL() { register unsigned cyc_high, cyc_low; __asm volatile("rdtscp\n\t" "mov %%edx, %0\n\t" "mov %%eax, %1\n\t" "cpuid\n\t" : "=r"(cyc_high), "=r"(cyc_low)::"%rax", "%rbx", "%rcx", "%rdx"); return ((uint64_t)cyc_high << 32) | cyc_low; } static __attribute__((noinline)) uint64_t rdtsc_overhead_func(uint64_t dummy) { return dummy; } uint64_t global_rdtsc_overhead = (uint64_t)UINT64_MAX; void RDTSC_SET_OVERHEAD(int repeat) { uint64_t cycles_start, cycles_final, cycles_diff; uint64_t min_diff = UINT64_MAX; for (int i = 0; i < repeat; i++) { __asm volatile("" ::: /* pretend to clobber */ "memory"); cycles_start = RDTSC_START(); rdtsc_overhead_func(1); cycles_final = RDTSC_FINAL(); cycles_diff = (cycles_final - cycles_start); if (cycles_diff < min_diff) min_diff = cycles_diff; } global_rdtsc_overhead = min_diff; printf("rdtsc_overhead set to %d\n", (int)global_rdtsc_overhead); } /* * Prints the best number of operations per cycle where * test is the function call, repeat is the number of times we should repeat * and size is the * number of operations represented by test. */ template <typename T> inline float BEST_TIME(const T &hasher, int repeat, int size) { uint64_t cycles_start, cycles_final, cycles_diff; uint64_t min_diff = (uint64_t)-1; bool wrong_answer = false; for (int i = 0; i < repeat; i++) { __asm volatile("" ::: /* pretend to clobber */ "memory"); hasher.Restart(); cycles_start = RDTSC_START(); if (hasher.Hash() != hasher.expected_) wrong_answer = true; cycles_final = RDTSC_FINAL(); cycles_diff = (cycles_final - cycles_start); if (cycles_diff < min_diff) min_diff = cycles_diff; } if (wrong_answer) return -1; min_diff -= global_rdtsc_overhead; return min_diff / (float)size; } template <typename HashDataType, typename HashValueType, HashValueType HashFunction(HashValueType, const HashDataType *)> struct HashBench { inline void Restart() const { flush(&k_, sizeof(k_)); } inline HashValueType Hash() const { HashValueType sum = 0; for (uint32_t x = 0; x < length_; ++x) { sum += HashFunction(array_[x], k_); } return sum; } HashBench(const HashValueType *const array, const uint32_t length, const HashDataType *const k) : array_(array), length_(length), k_(k) { expected_ = Hash(); } const HashValueType * const array_; const uint32_t length_; const HashDataType * const k_; HashValueType expected_; }; void flush(const void *b, size_t length) { char *B = (char *)b; for (uint32_t k = 0; k < length; k += 64) { __builtin_ia32_clflush(B + k); } } void basic(uint32_t length, int repeat) { cl_linear_t cl_lineark; cl_linear_init(&cl_lineark); cl_quadratic_t cl_quadratick; cl_quadratic_init(&cl_quadratick); cl_cubic_t cl_cubick; cl_cubic_init(&cl_cubick); zobrist_t zobristk; zobrist_init(&zobristk); static const int FIRST_FIELD_WIDTH = 20; static const int FIELD_WIDTH = 13; static bool first_run = true; if (first_run) { printf("Testing 64-bit hashing.\n"); printf("sizeof(cl_lineark) = %d, sizeof(cl_quadratick) = %d, " "sizeof(cl_cubick) = %d, sizeof(zobristk) = %d \n", (int)sizeof(cl_lineark), (int)sizeof(cl_quadratick), (int)sizeof(cl_cubick), (int)sizeof(zobristk)); cout << setw(FIELD_WIDTH) << "array size \\ hash fn" << setw(FIELD_WIDTH) << "zobrist" << setw(FIELD_WIDTH) << "cl_linear" << setw(FIELD_WIDTH) << "cl_quadratic" << setw(FIELD_WIDTH) << "cl_cubic" << endl; first_run = false; } uint64_t *array = (uint64_t *)malloc(sizeof(uint64_t) * length); for (uint32_t i = 0; i < length; ++i) { array[i] = get64rand(); } uint32_t size = length; cout << setw(FIRST_FIELD_WIDTH) << length; HashBench<zobrist_t, uint64_t, zobrist> demo_zobrist(array, length, &zobristk); cout << setw(FIELD_WIDTH) << fixed << setprecision(2) << BEST_TIME(demo_zobrist, repeat, size); HashBench<cl_linear_t, uint64_t, cl_linear> demo_linear(array, length, &cl_lineark); cout << setw(FIELD_WIDTH) << BEST_TIME(demo_linear, repeat, size); HashBench<cl_quadratic_t, uint64_t, cl_quadratic> demo_quadratic( array, length, &cl_quadratick); cout << setw(FIELD_WIDTH) << BEST_TIME(demo_quadratic, repeat, size); HashBench<cl_cubic_t, uint64_t, cl_cubic> demo_cubic(array, length, &cl_cubick); cout << setw(FIELD_WIDTH) << BEST_TIME(demo_cubic, repeat, size); free(array); printf("\n"); } void basic32(uint32_t length, int repeat) { cl_quadratic_t cl_quadratick; cl_quadratic32_init(&cl_quadratick); cl_linear_t cl_lineark; cl_linear32_init(&cl_lineark); zobrist32_t zobristk; zobrist32_init(&zobristk); static const int FIRST_FIELD_WIDTH = 20; static const int FIELD_WIDTH = 13; static bool first_run = true; if (first_run) { printf("Testing 32-bit hashing.\n"); printf("sizeof(cl_lineark) = %d, sizeof(cl_quadratick) = %d, " "sizeof(zobristk) = %d \n", (int)sizeof(cl_lineark), (int)sizeof(cl_quadratick), (int)sizeof(zobristk)); cout << setw(FIRST_FIELD_WIDTH) << "array size \\ hash fn" << setw(FIELD_WIDTH) << "zobrist" << setw(FIELD_WIDTH) << "cl_linear" << setw(FIELD_WIDTH) << "cl_quadratic" << endl; first_run = false; } uint32_t *array = (uint32_t *)malloc(sizeof(uint32_t) * length); for (uint32_t i = 0; i < length; ++i) { array[i] = get32rand(); } uint32_t size = length; cout << setw(FIRST_FIELD_WIDTH) << length; HashBench<zobrist32_t, uint32_t, zobrist32> demo_zobrist(array, length, &zobristk); cout << setw(FIELD_WIDTH) << fixed << setprecision(2) << BEST_TIME(demo_zobrist, repeat, size); HashBench<cl_linear_t, uint32_t, cl_linear32> demo_linear(array, length, &cl_lineark); cout << setw(FIELD_WIDTH) << BEST_TIME(demo_linear, repeat, size); HashBench<cl_quadratic_t, uint32_t, cl_quadratic32> demo_quadratic( array, length, &cl_quadratick); cout << setw(FIELD_WIDTH) << BEST_TIME(demo_quadratic, repeat, size); free(array); printf("\n"); } int main() { int repeat = 50000; if (global_rdtsc_overhead == UINT64_MAX) { RDTSC_SET_OVERHEAD(repeat); } printf("zobrist is 3-wise ind., linear is 2-wise ind., quadratic is 3-wise " "ind., cubic is 4-wise ind.\n"); printf("Keys are flushed at the beginning of each run.\n"); printf("======="); basic(10, repeat); basic(20, repeat); basic(100, repeat); basic(1000, repeat); printf("======="); basic32(10, repeat); basic32(20, repeat); basic32(100, repeat); basic32(1000, repeat); printf("Large runs are beneficial to tabulation-based hashing because they " "amortize cache faults.\n"); }
reduce duplication in output even more
reduce duplication in output even more
C++
apache-2.0
speedyhash/shorthash,speedyhash/shorthash,speedyhash/shorthash,speedyhash/shorthash
8c244a62d8597fa94d57191f8fec7c1b7005e5f4
bindings/go/llvm/InstrumentationBindings.cpp
bindings/go/llvm/InstrumentationBindings.cpp
//===- InstrumentationBindings.cpp - instrumentation bindings -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines C bindings for the instrumentation component. // //===----------------------------------------------------------------------===// #include "InstrumentationBindings.h" #include "llvm-c/Core.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/IR/Module.h" #include "llvm/Transforms/Instrumentation.h" #include "llvm/Transforms/Instrumentation/MemorySanitizer.h" using namespace llvm; void LLVMAddAddressSanitizerFunctionPass(LLVMPassManagerRef PM) { unwrap(PM)->add(createAddressSanitizerFunctionPass()); } void LLVMAddAddressSanitizerModulePass(LLVMPassManagerRef PM) { unwrap(PM)->add(createAddressSanitizerModulePass()); } void LLVMAddThreadSanitizerPass(LLVMPassManagerRef PM) { unwrap(PM)->add(createThreadSanitizerPass()); } void LLVMAddMemorySanitizerLegacyPassPass(LLVMPassManagerRef PM) { unwrap(PM)->add(createMemorySanitizerLegacyPassPass()); } void LLVMAddDataFlowSanitizerPass(LLVMPassManagerRef PM, int ABIListFilesNum, const char **ABIListFiles) { std::vector<std::string> ABIListFilesVec; for (int i = 0; i != ABIListFilesNum; ++i) { ABIListFilesVec.push_back(ABIListFiles[i]); } unwrap(PM)->add(createDataFlowSanitizerPass(ABIListFilesVec)); }
//===- InstrumentationBindings.cpp - instrumentation bindings -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines C bindings for the instrumentation component. // //===----------------------------------------------------------------------===// #include "InstrumentationBindings.h" #include "llvm-c/Core.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/IR/Module.h" #include "llvm/Transforms/Instrumentation.h" #include "llvm/Transforms/Instrumentation/MemorySanitizer.h" #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h" using namespace llvm; void LLVMAddAddressSanitizerFunctionPass(LLVMPassManagerRef PM) { unwrap(PM)->add(createAddressSanitizerFunctionPass()); } void LLVMAddAddressSanitizerModulePass(LLVMPassManagerRef PM) { unwrap(PM)->add(createAddressSanitizerModulePass()); } void LLVMAddThreadSanitizerPass(LLVMPassManagerRef PM) { unwrap(PM)->add(createThreadSanitizerLegacyPassPass()); } void LLVMAddMemorySanitizerLegacyPassPass(LLVMPassManagerRef PM) { unwrap(PM)->add(createMemorySanitizerLegacyPassPass()); } void LLVMAddDataFlowSanitizerPass(LLVMPassManagerRef PM, int ABIListFilesNum, const char **ABIListFiles) { std::vector<std::string> ABIListFilesVec; for (int i = 0; i != ABIListFilesNum; ++i) { ABIListFilesVec.push_back(ABIListFiles[i]); } unwrap(PM)->add(createDataFlowSanitizerPass(ABIListFilesVec)); }
Fix go bindings for r350647: missed a function rename
Fix go bindings for r350647: missed a function rename Differential Revision: https://reviews.llvm.org/D56452 git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@350657 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm
01f4caf50b525092ecfad11187a2b35f96782a34
include/cybozu/event.hpp
include/cybozu/event.hpp
#pragma once /** @file @brief event class Copyright (C) 2007 Cybozu Labs, Inc., all rights reserved. */ #ifdef _WIN32 #include <windows.h> #else #include <unistd.h> #endif #include <cybozu/exception.hpp> #if CYBOZU_CPP_VERSION == CYBOZU_CPP_VERSION_CPP11 #include <mutex> #include <condition_variable> #endif namespace cybozu { struct EventException : cybozu::Exception { EventException() : cybozu::Exception("event") { } }; #ifdef _WIN32 class Event { HANDLE event_; public: Event() { event_ = ::CreateEvent(NULL, FALSE, FALSE, NULL); if (event_ == 0) { cybozu::EventException e; e << "CreateEvent"; throw e; } } ~Event() { ::CloseHandle(event_); } void wakeup() { ::SetEvent(event_); } void wait() { DWORD msec = INFINITE; if (WaitForSingleObject(event_, msec) != WAIT_OBJECT_0) { cybozu::EventException e; e << "wait"; throw e; } } }; #else #if CYBOZU_CPP_VERSION == CYBOZU_CPP_VERSION_CPP11 class Event { bool isSignaled_; std::mutex m_; std::condition_variable cv_; public: Event() : isSignaled_(false) {} void wakeup() { std::unique_lock<std::mutex> lk(m_); isSignaled_ = true; cv_.notify_one(); } void wait() { std::unique_lock<std::mutex> lk(m_); cv_.wait(lk, [this] { return isSignaled_; }); isSignaled_ = false; } }; #else class Event { int pipefd_[2]; public: Event() { if (::pipe(pipefd_) < 0) { cybozu::EventException e; e << "pipe"; throw e; } } ~Event() { ::close(pipefd_[0]); ::close(pipefd_[1]); } void wakeup() { char c = 'a'; ssize_t size = ::write(pipefd_[1], &c, 1); cybozu::disable_warning_unused_variable(size); } void wait() { char c; ssize_t size = ::read(pipefd_[0], &c, 1); cybozu::disable_warning_unused_variable(size); } }; #endif #endif } // cybozu
#pragma once /** @file @brief event class Copyright (C) 2007 Cybozu Labs, Inc., all rights reserved. */ #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #else #include <unistd.h> #endif #include <cybozu/exception.hpp> #if CYBOZU_CPP_VERSION == CYBOZU_CPP_VERSION_CPP11 #include <mutex> #include <condition_variable> #endif namespace cybozu { struct EventException : cybozu::Exception { EventException() : cybozu::Exception("event") { } }; #ifdef _WIN32 class Event { HANDLE event_; Event(const Event&); void operator=(const Event&); public: Event() { event_ = ::CreateEvent(NULL, FALSE, FALSE, NULL); if (event_ == 0) { cybozu::EventException e; e << "CreateEvent"; throw e; } } ~Event() { ::CloseHandle(event_); } void wakeup() { ::SetEvent(event_); } void wait() { DWORD msec = INFINITE; if (WaitForSingleObject(event_, msec) != WAIT_OBJECT_0) { cybozu::EventException e; e << "wait"; throw e; } } }; #else #if CYBOZU_CPP_VERSION == CYBOZU_CPP_VERSION_CPP11 class Event { bool isSignaled_; std::mutex m_; std::condition_variable cv_; Event(const Event&) = delete; void operator=(const Event&) = delete; public: Event() : isSignaled_(false) {} void wakeup() { std::unique_lock<std::mutex> lk(m_); isSignaled_ = true; cv_.notify_one(); } void wait() { std::unique_lock<std::mutex> lk(m_); cv_.wait(lk, [this] { return isSignaled_; }); isSignaled_ = false; } }; #else class Event { int pipefd_[2]; Event(const Event&); void operator=(const Event&); public: Event() { if (::pipe(pipefd_) < 0) { cybozu::EventException e; e << "pipe"; throw e; } } ~Event() { ::close(pipefd_[0]); ::close(pipefd_[1]); } void wakeup() { char c = 'a'; ssize_t size = ::write(pipefd_[1], &c, 1); cybozu::disable_warning_unused_variable(size); } void wait() { char c; ssize_t size = ::read(pipefd_[0], &c, 1); cybozu::disable_warning_unused_variable(size); } }; #endif #endif } // cybozu
add include winsock2.h
add include winsock2.h
C++
bsd-3-clause
herumi/cybozulib,herumi/cybozulib
2b2b348fd6f643a7c541c5c2126b7869e10641ac
include/draw/Texture.cpp
include/draw/Texture.cpp
// // Texture.cpp // SHSoftwareRasterizer // // Created by 7heaven on 16/5/16. // Copyright © 2016年 7heaven. All rights reserved. // #include "draw/Texture.h" namespace sh{ Texture::Texture(SHColor *pixels, unsigned int width, unsigned int height){ this->pixels = pixels; this->width = width; this->height = height; this->totalSize = this->width * this->height; } SHColor Texture::getPixel(unsigned int u, unsigned int v){ int pos = v * this->width + u; if(pos < 0 || pos >= this->totalSize) return (SHColor){0xFF, 0xFF, 0xFF, 0xFF}; return this->pixels[pos]; } SHColor Texture::getPixelF(float u, float v){ float ru = u * this->width; float rv = v * this->height; int x = (int) (ru); int y = (int) (rv); ru = ru - x; rv = rv - y; if(ru == 0 && rv == 0){ return getPixel(x, y); }else{ if(ru == 0){ SHColor lowerY = getPixel(x, y); SHColor upperY = getPixel(x, y + 1); return mixRGB(lowerY, upperY, rv); }else if(rv == 0){ SHColor lowerX = getPixel(x, y); SHColor upperX = getPixel(x + 1, y); return mixRGB(lowerX, upperX, ru); }else{ SHColor tlC = getPixel(x, y); SHColor trC = getPixel(x + 1, y); SHColor blC = getPixel(x, y + 1); SHColor brC = getPixel(x + 1, y); SHColor mixLeft = mixRGB(tlC, blC, rv); SHColor mixRight = mixRGB(trC, brC, rv); return mixRGB(mixLeft, mixRight, ru); } } } SHColor Texture::mixARGB(SHColor a, SHColor b, float mixedValue){ unsigned char alpha = a.a; unsigned char red = a.r; unsigned char green = a.g; unsigned char blue = a.b; char da = b.a - a.a; char dr = b.r - a.r; char dg = b.g - a.g; char db = b.b - a.b; alpha += (float) da * mixedValue; red += (float) dr * mixedValue; green += (float) dg * mixedValue; blue += (float) db * mixedValue; return SHColorMake(alpha << 24 | red << 16 | green << 8 | blue); } SHColor Texture::mixRGB(SHColor a, SHColor b, float mixedValue){ unsigned char red = a.r; unsigned char green = a.g; unsigned char blue = a.b; char dr = b.r - a.r; char dg = b.g - a.g; char db = b.b - a.b; red += (float) dr * mixedValue; green += (float) dg * mixedValue; blue += (float) db * mixedValue; return SHColorMake(0xFF000000 | red << 16 | green << 8 | blue); } }
// // Texture.cpp // SHSoftwareRasterizer // // Created by 7heaven on 16/5/16. // Copyright © 2016年 7heaven. All rights reserved. // #include "draw/Texture.h" namespace sh{ Texture::Texture(SHColor *pixels, unsigned int width, unsigned int height){ this->pixels = pixels; this->width = width; this->height = height; this->totalSize = this->width * this->height; } SHColor Texture::getPixel(unsigned int u, unsigned int v){ int pos = v * this->width + u; while(pos < 0) pos += this->totalSize; while(pos >= this->totalSize) pos -= this->totalSize; return this->pixels[pos]; } SHColor Texture::getPixelF(float u, float v){ float ru = u * this->width; float rv = v * this->height; int x = (int) (ru); int y = (int) (rv); ru = ru - x; rv = rv - y; if(ru == 0 && rv == 0){ return getPixel(x, y); }else{ if(ru == 0){ SHColor lowerY = getPixel(x, y); SHColor upperY = getPixel(x, y + 1); return mixRGB(lowerY, upperY, rv); }else if(rv == 0){ SHColor lowerX = getPixel(x, y); SHColor upperX = getPixel(x + 1, y); return mixRGB(lowerX, upperX, ru); }else{ SHColor tlC = getPixel(x, y); SHColor trC = getPixel(x + 1, y); SHColor blC = getPixel(x, y + 1); SHColor brC = getPixel(x + 1, y); SHColor mixLeft = mixRGB(tlC, blC, rv); SHColor mixRight = mixRGB(trC, brC, rv); return mixRGB(mixLeft, mixRight, ru); } } } SHColor Texture::mixARGB(SHColor a, SHColor b, float mixedValue){ unsigned char alpha = a.a; unsigned char red = a.r; unsigned char green = a.g; unsigned char blue = a.b; char da = b.a - a.a; char dr = b.r - a.r; char dg = b.g - a.g; char db = b.b - a.b; alpha += (float) da * mixedValue; red += (float) dr * mixedValue; green += (float) dg * mixedValue; blue += (float) db * mixedValue; return SHColorMake(alpha << 24 | red << 16 | green << 8 | blue); } SHColor Texture::mixRGB(SHColor a, SHColor b, float mixedValue){ unsigned char red = a.r; unsigned char green = a.g; unsigned char blue = a.b; char dr = b.r - a.r; char dg = b.g - a.g; char db = b.b - a.b; red += (float) dr * mixedValue; green += (float) dg * mixedValue; blue += (float) db * mixedValue; return SHColorMake(0xFF000000 | red << 16 | green << 8 | blue); } }
modify Texture getPixel behavier
modify Texture getPixel behavier
C++
mit
KunKua/Aiks,KunKua/Aiks
25837e9d8f7a6dcee3d2966713a67f2fb985e0b4
include/nonius/clock.h++
include/nonius/clock.h++
// Nonius - C++ benchmarking tool // // Written in 2014 by Martinho Fernandes <[email protected]> // // To the extent possible under law, the author(s) have dedicated all copyright and related // and neighboring rights to this software to the public domain worldwide. This software is // distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/> // Clocks #ifndef NONIUS_CLOCK_HPP #define NONIUS_CLOCK_HPP #if defined(_MSC_VER) && (_MSC_VER < 1900) // MSVC <chrono> is borken and had little to no testing done before shipping (Dev14/VS15 CTP fixes it) #include <boost/chrono.hpp> #else #include <chrono> #include <ratio> #endif namespace nonius { #if defined(_MSC_VER) && (_MSC_VER < 1900) // MSVC <chrono> is borken and had little to no testing done before shipping (Dev14/VS15 CTP fixes it) namespace chrono = boost::chrono; template <unsigned Num, unsigned Den = 1> using ratio = boost::ratio<Num, Den>; #else namespace chrono = std::chrono; template <unsigned Num, unsigned Den = 1> using ratio = std::ratio<Num, Den>; #endif using milli = ratio<1, 1000>; using micro = ratio<1, 1000000>; using nano = ratio<1, 1000000000>; template <typename Clock> using Duration = typename Clock::duration; template <typename Clock> using FloatDuration = chrono::duration<double, typename Clock::period>; template <typename Clock> using TimePoint = typename Clock::time_point; using default_clock = chrono::high_resolution_clock; template <typename Clock> struct now { TimePoint<Clock> operator()() const { return Clock::now(); } }; using fp_seconds = chrono::duration<double, ratio<1>>; } // namespace nonius #endif // NONIUS_CLOCK_HPP
// Nonius - C++ benchmarking tool // // Written in 2014 by Martinho Fernandes <[email protected]> // // To the extent possible under law, the author(s) have dedicated all copyright and related // and neighboring rights to this software to the public domain worldwide. This software is // distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/> // Clocks #ifndef NONIUS_CLOCK_HPP #define NONIUS_CLOCK_HPP #if defined(_MSC_VER) && (_MSC_VER) < 1900 #if !defined(NONIUS_USE_BOOST_CHRONO) #define NONIUS_USE_BOOST_CHRONO #endif // NONIUS_USE_BOOST_CHRONO #endif // MSVC <chrono> is borken and had little to no testing done before shipping (Dev14/VS15 CTP fixes it) #if defined(NONIUS_USE_BOOST_CHRONO) #include <boost/chrono.hpp> #else #include <chrono> #include <ratio> #endif namespace nonius { #if defined(NONIUS_USE_BOOST_CHRONO) namespace chrono = boost::chrono; template <unsigned Num, unsigned Den = 1> using ratio = boost::ratio<Num, Den>; #else namespace chrono = std::chrono; template <unsigned Num, unsigned Den = 1> using ratio = std::ratio<Num, Den>; #endif using milli = ratio<1, 1000>; using micro = ratio<1, 1000000>; using nano = ratio<1, 1000000000>; template <typename Clock> using Duration = typename Clock::duration; template <typename Clock> using FloatDuration = chrono::duration<double, typename Clock::period>; template <typename Clock> using TimePoint = typename Clock::time_point; using default_clock = chrono::high_resolution_clock; template <typename Clock> struct now { TimePoint<Clock> operator()() const { return Clock::now(); } }; using fp_seconds = chrono::duration<double, ratio<1>>; } // namespace nonius #endif // NONIUS_CLOCK_HPP
Allow using Boost.Chrono for defining NONIUS_USE_BOOST_CHRONO.
Allow using Boost.Chrono for defining NONIUS_USE_BOOST_CHRONO.
C++
cc0-1.0
marcmo/nonius
c9980ff0dd4c4a8864ce925a9e2f9445e6c16372
include/proton/tuple.hpp
include/proton/tuple.hpp
#ifndef PROTON_TUPLE_HEADER #define PROTON_TUPLE_HEADER /** @file vector.hpp * @brief vector support. * Please include this header instead of \<vector\>. */ #include <tuple> #include <algorithm> #include <iostream> #include <initializer_list> #include <algorithm> #include <stdexcept> #include <proton/base.hpp> namespace proton{ /** @addtogroup tuple_ * @{ */ namespace detail{ // helper function to print a tuple of any size template<typename T, std::size_t I> struct output_tuple { static void output(std::ostream& s, T&& t) { output_tuple<T, I-1>::output(s,t); s << ", " << std::get<I-1>(t); } }; template<typename T> struct output_tuple<T, 1> { static void output(std::ostream& s, T&& t) { s << std::get<0>(t); } }; template<typename T> struct output_tuple<T, 0> { static void output(std::ostream& s, T&& t) { } }; template<typename T, size_t begin, size_t size> struct sub{ private: static_assert(begin < std::tuple_size<T>::value, "out of range"); static_assert(begin+size <= std::tuple_size<T>::value, "out of range"); std::tuple<typename std::tuple_element<begin, T>::type> *p; typedef typename sub<T, begin+1, size-1>::type next_types; next_types* q; public: typedef decltype(std::tuple_cat(*p,*q)) type; }; template<typename T, size_t begin> struct sub<T, begin, 0>{ typedef std::tuple<> type; }; template<typename T, size_t begin> struct sub<T,begin,1>{ static_assert(begin < std::tuple_size<T>::value, "out of range"); typedef std::tuple<typename std::tuple_element<begin,T>::type > type; }; } // ns detail /** get a slice of tuple x[begin:end] in python. * @param begin must be constexpr determined during compile time * @param end must be constexpr determined during compile time */ template<size_t begin, size_t end, typename ...T> typename detail::sub<std::tuple<T...>, begin, end-begin>::type sub(const std::tuple<T...>& x) { typedef typename detail::sub<std::tuple<T...>, begin, end-begin>::type ret_t; return ret_t(*(ret_t*)(&std::get<end-1>(x))); // [FIXME] in g++, the items in a tuple is in reverse order. for other implementation, need fix. } /** get a slice of tuple x[begin:] in python. * @param begin must be constexpr determined during compile time */ template<size_t begin, typename ...T> typename detail::sub<std::tuple<T...>, begin, sizeof...(T)-begin>::type sub_to_end(const std::tuple<T...>& x) { typedef typename detail::sub<std::tuple<T...>, begin, sizeof...(T)-begin>::type ret_t; return ret_t(*(ret_t*)(&std::get<sizeof...(T)-1>(x))); // [FIXME] in g++, the items in a tuple is in reverse order. for other implementation, need fix. } /** general output for tuple. * @param s the output stream * @param x the tuple to be outputed * @return s */ template <typename ...T> std::ostream& operator<<(std::ostream& s, const std::tuple<T...>& x) { s << "("; detail::output_tuple<decltype(x), sizeof...(T)>::output(s,x); s << ")"; return s; } template <typename ...T> std::wostream& operator<<(std::wostream& s, const std::tuple<T...>& x) { s << L"("; detail::output_tuple<decltype(x), sizeof...(T)>::output(s,x); s << L")"; return s; } /** tuple + tuple */ template<typename T2, typename ...T1> auto operator+(const std::tuple<T1...>& x, T2&& y) -> decltype(std::tuple_cat(x,y)) { return std::tuple_cat(x,y); } template<typename T2, typename ...T1> auto operator+(std::tuple<T1...>&& x, T2&& y) -> decltype(std::tuple_cat(x,y)) { return std::tuple_cat(x,y); } /** eq to make_tuple */ template<typename ...T> auto _t(T&& ...x) -> decltype(make_tuple(x...)) { return make_tuple(x...); } #if 0 /* vector_ * n */ template<typename T, typename A> vector_<T,A> operator*(const std::vector<T,A>& s, size_t n) { vector_<T,A> r; r.reserve(s.size()*n); for(size_t i=0; i<n; i++) r.extend(s); return r; } /* n * vector_ */ template<typename T, typename A> vector_<T,A> operator*(size_t n, const std::vector<T,A>& s) { return s*n; } #endif /** * @} */ } #endif // PROTON_TUPLE_HEADER
#ifndef PROTON_TUPLE_HEADER #define PROTON_TUPLE_HEADER /** @file vector.hpp * @brief vector support. * Please include this header instead of \<vector\>. */ #include <tuple> #include <algorithm> #include <iostream> #include <initializer_list> #include <algorithm> #include <stdexcept> #include <limits> #include <proton/base.hpp> namespace proton{ /** @addtogroup tuple_ * @{ */ namespace detail{ // helper function to print a tuple of any size template<typename T, std::size_t I> struct output_tuple { static void output(std::ostream& s, T&& t) { output_tuple<T, I-1>::output(s,t); s << ", " << std::get<I-1>(t); } }; template<typename T> struct output_tuple<T, 1> { static void output(std::ostream& s, T&& t) { s << std::get<0>(t); } }; template<typename T> struct output_tuple<T, 0> { static void output(std::ostream& s, T&& t) { } }; constexpr long fix_index(long i, long size) { return (i>size)? size :( (i<0)? (i+size < 0 ? 0 : i+size ) : i ); } constexpr long sub_index(long i, long size) { return (i>=size)? size-1 :( (i<0)? (i+size < 0 ? 0 : i+size ) : i ); } constexpr long get_index(long i, long size) { return (i>=size)? -1 :( (i<0)? (i+size < 0 ? -1 : i+size ) : i ); } template<long i, typename ...T> struct at_index{ static_assert(i>=0, "out of range"); const std::tuple<T...>* p; typedef decltype(std::get<i>(*p)) type; }; constexpr long fix_size(long begin, long end, long size) { return fix_index(begin,size)>fix_index(end,size)? 0 : fix_index(end,size)-fix_index(begin,size); } template<typename T, size_t begin, size_t size> struct sub{ private: static_assert(begin < std::tuple_size<T>::value, "out of range"); std::tuple<typename std::tuple_element<begin, T>::type> *p; typedef typename sub<T, begin+1, (begin+size > std::tuple_size<T>::value ? (std::tuple_size<T>::value-begin-1) : (size-1)) >::type next_types; next_types* q; public: typedef decltype(std::tuple_cat(*p,*q)) type; }; template<typename T, size_t begin> struct sub<T, begin, 0>{ typedef std::tuple<> type; }; template<typename T, size_t begin> struct sub<T,begin,1>{ static_assert(begin < std::tuple_size<T>::value, "out of range"); typedef std::tuple<typename std::tuple_element<begin,T>::type > type; }; } // ns detail /** like x[index] in python */ template<long index, typename ...T> typename detail::at_index<detail::get_index(index,sizeof...(T)),T...>::type at(const std::tuple<T...>& x) { static_assert(detail::get_index(index,sizeof...(T))<sizeof...(T), "out of range"); return std::get<detail::get_index(index,sizeof...(T))>(x); } /** get a slice of tuple x[begin:end] in python */ template<long begin, long end=std::numeric_limits<long>::max(), typename ...T> typename detail::sub<std::tuple<T...>, detail::fix_index(begin, sizeof...(T)), detail::fix_size(begin,end, sizeof...(T))>::type sub(const std::tuple<T...>& x) { typedef typename detail::sub<std::tuple<T...>, detail::fix_index(begin, sizeof...(T)), detail::fix_size(begin,end, sizeof...(T))>::type ret_t; return ret_t(*(ret_t*)(&std::get<(detail::sub_index(end-1, sizeof...(T)))>(x))); // [FIXME] in g++, the items in a tuple is in reverse order. for other implementation, need fix. } /** general output for tuple. * @param s the output stream * @param x the tuple to be outputed * @return s */ template <typename ...T> std::ostream& operator<<(std::ostream& s, const std::tuple<T...>& x) { s << "("; detail::output_tuple<decltype(x), sizeof...(T)>::output(s,x); s << ")"; return s; } template <typename ...T> std::wostream& operator<<(std::wostream& s, const std::tuple<T...>& x) { s << L"("; detail::output_tuple<decltype(x), sizeof...(T)>::output(s,x); s << L")"; return s; } /** tuple + tuple */ template<typename T2, typename ...T1> auto operator+(const std::tuple<T1...>& x, T2&& y) -> decltype(std::tuple_cat(x,y)) { return std::tuple_cat(x,y); } template<typename T2, typename ...T1> auto operator+(std::tuple<T1...>&& x, T2&& y) -> decltype(std::tuple_cat(x,y)) { return std::tuple_cat(x,y); } /** eq to make_tuple */ template<typename ...T> auto _t(T&& ...x) -> decltype(make_tuple(x...)) { return make_tuple(x...); } #if 0 /* vector_ * n */ template<typename T, typename A> vector_<T,A> operator*(const std::vector<T,A>& s, size_t n) { vector_<T,A> r; r.reserve(s.size()*n); for(size_t i=0; i<n; i++) r.extend(s); return r; } /* n * vector_ */ template<typename T, typename A> vector_<T,A> operator*(size_t n, const std::vector<T,A>& s) { return s*n; } #endif /** * @} */ } #endif // PROTON_TUPLE_HEADER
add at, sub for tuple
add at, sub for tuple
C++
bsd-2-clause
LenxWei/libproton,LenxWei/libproton,LenxWei/libproton
d7bd78d612d40af5bf392c7f2c085025a0a91f3d
createHierarchy.cpp
createHierarchy.cpp
/* open source routing machine Copyright (C) Dennis Luxen, 2010 This program is free software; you can redistribute it and/or modify it under the terms of the GNU AFFERO General Public License as published by the Free Software Foundation; either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or see http://www.gnu.org/licenses/agpl.txt. */ #include "Algorithms/IteratorBasedCRC32.h" #include "Contractor/Contractor.h" #include "Contractor/EdgeBasedGraphFactory.h" #include "DataStructures/BinaryHeap.h" #include "DataStructures/DeallocatingVector.h" #include "DataStructures/QueryEdge.h" #include "DataStructures/StaticGraph.h" #include "DataStructures/StaticRTree.h" #include "Util/IniFile.h" #include "Util/GraphLoader.h" #include "Util/InputFileUtil.h" #include "Util/LuaUtil.h" #include "Util/OpenMPWrapper.h" #include "Util/OSRMException.h" #include "Util/SimpleLogger.h" #include "Util/StringUtil.h" #include "typedefs.h" #include <boost/foreach.hpp> #include <luabind/luabind.hpp> #include <fstream> #include <istream> #include <iostream> #include <cstring> #include <string> #include <vector> typedef QueryEdge::EdgeData EdgeData; typedef DynamicGraph<EdgeData>::InputEdge InputEdge; typedef StaticGraph<EdgeData>::InputEdge StaticEdge; typedef IniFile ContractorConfiguration; std::vector<NodeInfo> internalToExternalNodeMapping; std::vector<_Restriction> inputRestrictions; std::vector<NodeID> bollardNodes; std::vector<NodeID> trafficLightNodes; std::vector<ImportEdge> edgeList; int main (int argc, char *argv[]) { try { LogPolicy::GetInstance().Unmute(); if(argc < 3) { SimpleLogger().Write(logWARNING) << "usage: \n" << argv[0] << " <osrm-data> <osrm-restrictions> [<profile>]"; return -1; } double startupTime = get_timestamp(); unsigned number_of_threads = omp_get_num_procs(); if(testDataFile("contractor.ini")) { ContractorConfiguration contractorConfig("contractor.ini"); unsigned rawNumber = stringToInt(contractorConfig.GetParameter("Threads")); if(rawNumber != 0 && rawNumber <= number_of_threads) number_of_threads = rawNumber; } omp_set_num_threads(number_of_threads); LogPolicy::GetInstance().Unmute(); SimpleLogger().Write() << "Using restrictions from file: " << argv[2]; std::ifstream restrictionsInstream(argv[2], std::ios::binary); if(!restrictionsInstream.good()) { std::cerr << "Could not access <osrm-restrictions> files" << std::endl; } _Restriction restriction; UUID uuid_loaded, uuid_orig; unsigned usableRestrictionsCounter(0); restrictionsInstream.read((char*)&uuid_loaded, sizeof(UUID)); if( !uuid_loaded.TestPrepare(uuid_orig) ) { SimpleLogger().Write(logWARNING) << ".restrictions was prepared with different build.\n" "Reprocess to get rid of this warning."; } restrictionsInstream.read((char*)&usableRestrictionsCounter, sizeof(unsigned)); inputRestrictions.resize(usableRestrictionsCounter); restrictionsInstream.read((char *)&(inputRestrictions[0]), usableRestrictionsCounter*sizeof(_Restriction)); restrictionsInstream.close(); std::ifstream in; in.open (argv[1], std::ifstream::in | std::ifstream::binary); if (!in.is_open()) { throw OSRMException("Cannot open osrm input file"); } std::string nodeOut(argv[1]); nodeOut += ".nodes"; std::string edgeOut(argv[1]); edgeOut += ".edges"; std::string graphOut(argv[1]); graphOut += ".hsgr"; std::string rtree_nodes_path(argv[1]); rtree_nodes_path += ".ramIndex"; std::string rtree_leafs_path(argv[1]); rtree_leafs_path += ".fileIndex"; /*** Setup Scripting Environment ***/ if(!testDataFile( (argc > 3 ? argv[3] : "profile.lua") )) { throw OSRMException("Cannot open profile.lua "); } // Create a new lua state lua_State *myLuaState = luaL_newstate(); // Connect LuaBind to this lua state luabind::open(myLuaState); //open utility libraries string library; luaL_openlibs(myLuaState); //adjust lua load path luaAddScriptFolderToLoadPath( myLuaState, (argc > 3 ? argv[3] : "profile.lua") ); // Now call our function in a lua script SimpleLogger().Write() << "Parsing speedprofile from " << (argc > 3 ? argv[3] : "profile.lua"); if(0 != luaL_dofile(myLuaState, (argc > 3 ? argv[3] : "profile.lua") )) { std::cerr << lua_tostring(myLuaState,-1) << " occured in scripting block" << std::endl; } EdgeBasedGraphFactory::SpeedProfileProperties speedProfile; if(0 != luaL_dostring( myLuaState, "return traffic_signal_penalty\n")) { std::cerr << lua_tostring(myLuaState,-1) << " occured in scripting block" << std::endl; return -1; } speedProfile.trafficSignalPenalty = 10*lua_tointeger(myLuaState, -1); if(0 != luaL_dostring( myLuaState, "return u_turn_penalty\n")) { std::cerr << lua_tostring(myLuaState,-1) << " occured in scripting block" << std::endl; return -1; } speedProfile.uTurnPenalty = 10*lua_tointeger(myLuaState, -1); speedProfile.has_turn_penalty_function = lua_function_exists( myLuaState, "turn_function" ); std::vector<ImportEdge> edgeList; NodeID nodeBasedNodeNumber = readBinaryOSRMGraphFromStream(in, edgeList, bollardNodes, trafficLightNodes, &internalToExternalNodeMapping, inputRestrictions); in.close(); SimpleLogger().Write() << inputRestrictions.size() << " restrictions, " << bollardNodes.size() << " bollard nodes, " << trafficLightNodes.size() << " traffic lights"; if(0 == edgeList.size()) { std::cerr << "The input data is broken. " "It is impossible to do any turns in this graph" << std::endl; return -1; } /*** * Building an edge-expanded graph from node-based input an turn restrictions */ SimpleLogger().Write() << "Generating edge-expanded graph representation"; EdgeBasedGraphFactory * edgeBasedGraphFactory = new EdgeBasedGraphFactory (nodeBasedNodeNumber, edgeList, bollardNodes, trafficLightNodes, inputRestrictions, internalToExternalNodeMapping, speedProfile); std::vector<ImportEdge>().swap(edgeList); edgeBasedGraphFactory->Run(edgeOut.c_str(), myLuaState); std::vector<_Restriction>().swap(inputRestrictions); std::vector<NodeID>().swap(bollardNodes); std::vector<NodeID>().swap(trafficLightNodes); NodeID edgeBasedNodeNumber = edgeBasedGraphFactory->GetNumberOfNodes(); DeallocatingVector<EdgeBasedEdge> edgeBasedEdgeList; edgeBasedGraphFactory->GetEdgeBasedEdges(edgeBasedEdgeList); std::vector<EdgeBasedGraphFactory::EdgeBasedNode> nodeBasedEdgeList; edgeBasedGraphFactory->GetEdgeBasedNodes(nodeBasedEdgeList); delete edgeBasedGraphFactory; /*** * Writing info on original (node-based) nodes */ SimpleLogger().Write() << "writing node map ..."; std::ofstream mapOutFile(nodeOut.c_str(), std::ios::binary); mapOutFile.write((char *)&(internalToExternalNodeMapping[0]), internalToExternalNodeMapping.size()*sizeof(NodeInfo)); mapOutFile.close(); std::vector<NodeInfo>().swap(internalToExternalNodeMapping); double expansionHasFinishedTime = get_timestamp() - startupTime; /*** * Building grid-like nearest-neighbor data structure */ SimpleLogger().Write() << "building r-tree ..."; StaticRTree<EdgeBasedGraphFactory::EdgeBasedNode> * rtree = new StaticRTree<EdgeBasedGraphFactory::EdgeBasedNode>( nodeBasedEdgeList, rtree_nodes_path.c_str(), rtree_leafs_path.c_str() ); delete rtree; IteratorbasedCRC32<std::vector<EdgeBasedGraphFactory::EdgeBasedNode> > crc32; unsigned crc32OfNodeBasedEdgeList = crc32(nodeBasedEdgeList.begin(), nodeBasedEdgeList.end() ); nodeBasedEdgeList.clear(); SimpleLogger().Write() << "CRC32: " << crc32OfNodeBasedEdgeList; /*** * Contracting the edge-expanded graph */ SimpleLogger().Write() << "initializing contractor"; Contractor* contractor = new Contractor( edgeBasedNodeNumber, edgeBasedEdgeList ); double contractionStartedTimestamp(get_timestamp()); contractor->Run(); SimpleLogger().Write() << "Contraction took " << (get_timestamp() - contractionStartedTimestamp) << " sec"; DeallocatingVector< QueryEdge > contractedEdgeList; contractor->GetEdges( contractedEdgeList ); delete contractor; /*** * Sorting contracted edges in a way that the static query graph can read some in in-place. */ SimpleLogger().Write() << "Building Node Array"; std::sort(contractedEdgeList.begin(), contractedEdgeList.end()); unsigned numberOfNodes = 0; unsigned numberOfEdges = contractedEdgeList.size(); SimpleLogger().Write() << "Serializing compacted graph of " << numberOfEdges << " edges"; std::ofstream hsgr_output_stream(graphOut.c_str(), std::ios::binary); hsgr_output_stream.write((char*)&uuid_orig, sizeof(UUID) ); BOOST_FOREACH(const QueryEdge & edge, contractedEdgeList) { if(edge.source > numberOfNodes) { numberOfNodes = edge.source; } if(edge.target > numberOfNodes) { numberOfNodes = edge.target; } } numberOfNodes+=1; std::vector< StaticGraph<EdgeData>::_StrNode > _nodes; _nodes.resize( numberOfNodes + 1 ); StaticGraph<EdgeData>::EdgeIterator edge = 0; StaticGraph<EdgeData>::EdgeIterator position = 0; for ( StaticGraph<EdgeData>::NodeIterator node = 0; node <= numberOfNodes; ++node ) { StaticGraph<EdgeData>::EdgeIterator lastEdge = edge; while ( edge < numberOfEdges && contractedEdgeList[edge].source == node ) ++edge; _nodes[node].firstEdge = position; //=edge position += edge - lastEdge; //remove } ++numberOfNodes; //Serialize numberOfNodes, nodes hsgr_output_stream.write((char*) &crc32OfNodeBasedEdgeList, sizeof(unsigned)); hsgr_output_stream.write((char*) &numberOfNodes, sizeof(unsigned)); hsgr_output_stream.write((char*) &_nodes[0], sizeof(StaticGraph<EdgeData>::_StrNode)*(numberOfNodes)); //Serialize number of Edges hsgr_output_stream.write((char*) &position, sizeof(unsigned)); --numberOfNodes; edge = 0; int usedEdgeCounter = 0; StaticGraph<EdgeData>::_StrEdge currentEdge; for ( StaticGraph<EdgeData>::NodeIterator node = 0; node < numberOfNodes; ++node ) { for ( StaticGraph<EdgeData>::EdgeIterator i = _nodes[node].firstEdge, e = _nodes[node+1].firstEdge; i != e; ++i ) { assert(node != contractedEdgeList[edge].target); currentEdge.target = contractedEdgeList[edge].target; currentEdge.data = contractedEdgeList[edge].data; if(currentEdge.data.distance <= 0) { SimpleLogger().Write(logWARNING) << "Edge: " << i << ",source: " << contractedEdgeList[edge].source << ", target: " << contractedEdgeList[edge].target << ", dist: " << currentEdge.data.distance; SimpleLogger().Write(logWARNING) << "Failed at edges of node " << node << " of " << numberOfNodes; return -1; } //Serialize edges hsgr_output_stream.write((char*) &currentEdge, sizeof(StaticGraph<EdgeData>::_StrEdge)); ++edge; ++usedEdgeCounter; } } double endTime = (get_timestamp() - startupTime); SimpleLogger().Write() << "Expansion : " << (nodeBasedNodeNumber/expansionHasFinishedTime) << " nodes/sec and " << (edgeBasedNodeNumber/expansionHasFinishedTime) << " edges/sec"; SimpleLogger().Write() << "Contraction: " << (edgeBasedNodeNumber/expansionHasFinishedTime) << " nodes/sec and " << usedEdgeCounter/endTime << " edges/sec"; hsgr_output_stream.close(); //cleanedEdgeList.clear(); _nodes.clear(); SimpleLogger().Write() << "finished preprocessing"; } catch ( const std::exception &e ) { SimpleLogger().Write(logWARNING) << "Exception occured: " << e.what() << std::endl; return -1; } return 0; }
/* open source routing machine Copyright (C) Dennis Luxen, 2010 This program is free software; you can redistribute it and/or modify it under the terms of the GNU AFFERO General Public License as published by the Free Software Foundation; either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or see http://www.gnu.org/licenses/agpl.txt. */ #include "Algorithms/IteratorBasedCRC32.h" #include "Contractor/Contractor.h" #include "Contractor/EdgeBasedGraphFactory.h" #include "DataStructures/BinaryHeap.h" #include "DataStructures/DeallocatingVector.h" #include "DataStructures/QueryEdge.h" #include "DataStructures/StaticGraph.h" #include "DataStructures/StaticRTree.h" #include "Util/IniFile.h" #include "Util/GraphLoader.h" #include "Util/InputFileUtil.h" #include "Util/LuaUtil.h" #include "Util/OpenMPWrapper.h" #include "Util/OSRMException.h" #include "Util/SimpleLogger.h" #include "Util/StringUtil.h" #include "typedefs.h" #include <boost/foreach.hpp> #include <luabind/luabind.hpp> #include <fstream> #include <istream> #include <iostream> #include <cstring> #include <string> #include <vector> typedef QueryEdge::EdgeData EdgeData; typedef DynamicGraph<EdgeData>::InputEdge InputEdge; typedef StaticGraph<EdgeData>::InputEdge StaticEdge; typedef IniFile ContractorConfiguration; std::vector<NodeInfo> internalToExternalNodeMapping; std::vector<_Restriction> inputRestrictions; std::vector<NodeID> bollardNodes; std::vector<NodeID> trafficLightNodes; std::vector<ImportEdge> edgeList; int main (int argc, char *argv[]) { try { LogPolicy::GetInstance().Unmute(); if(argc < 3) { SimpleLogger().Write(logWARNING) << "usage: \n" << argv[0] << " <osrm-data> <osrm-restrictions> [<profile>]"; return -1; } double startupTime = get_timestamp(); unsigned number_of_threads = omp_get_num_procs(); if(testDataFile("contractor.ini")) { ContractorConfiguration contractorConfig("contractor.ini"); unsigned rawNumber = stringToInt(contractorConfig.GetParameter("Threads")); if(rawNumber != 0 && rawNumber <= number_of_threads) number_of_threads = rawNumber; } omp_set_num_threads(number_of_threads); LogPolicy::GetInstance().Unmute(); SimpleLogger().Write() << "Using restrictions from file: " << argv[2]; std::ifstream restrictionsInstream(argv[2], std::ios::binary); if(!restrictionsInstream.good()) { std::cerr << "Could not access <osrm-restrictions> files" << std::endl; } _Restriction restriction; UUID uuid_loaded, uuid_orig; unsigned usableRestrictionsCounter(0); restrictionsInstream.read((char*)&uuid_loaded, sizeof(UUID)); if( !uuid_loaded.TestPrepare(uuid_orig) ) { SimpleLogger().Write(logWARNING) << ".restrictions was prepared with different build.\n" "Reprocess to get rid of this warning."; } restrictionsInstream.read((char*)&usableRestrictionsCounter, sizeof(unsigned)); inputRestrictions.resize(usableRestrictionsCounter); restrictionsInstream.read((char *)&(inputRestrictions[0]), usableRestrictionsCounter*sizeof(_Restriction)); restrictionsInstream.close(); std::ifstream in; in.open (argv[1], std::ifstream::in | std::ifstream::binary); if (!in.is_open()) { throw OSRMException("Cannot open osrm input file"); } std::string nodeOut(argv[1]); nodeOut += ".nodes"; std::string edgeOut(argv[1]); edgeOut += ".edges"; std::string graphOut(argv[1]); graphOut += ".hsgr"; std::string rtree_nodes_path(argv[1]); rtree_nodes_path += ".ramIndex"; std::string rtree_leafs_path(argv[1]); rtree_leafs_path += ".fileIndex"; /*** Setup Scripting Environment ***/ if(!testDataFile( (argc > 3 ? argv[3] : "profile.lua") )) { throw OSRMException("Cannot open profile.lua "); } // Create a new lua state lua_State *myLuaState = luaL_newstate(); // Connect LuaBind to this lua state luabind::open(myLuaState); //open utility libraries string library; luaL_openlibs(myLuaState); //adjust lua load path luaAddScriptFolderToLoadPath( myLuaState, (argc > 3 ? argv[3] : "profile.lua") ); // Now call our function in a lua script SimpleLogger().Write() << "Parsing speedprofile from " << (argc > 3 ? argv[3] : "profile.lua"); if(0 != luaL_dofile(myLuaState, (argc > 3 ? argv[3] : "profile.lua") )) { std::cerr << lua_tostring(myLuaState,-1) << " occured in scripting block" << std::endl; } EdgeBasedGraphFactory::SpeedProfileProperties speedProfile; if(0 != luaL_dostring( myLuaState, "return traffic_signal_penalty\n")) { std::cerr << lua_tostring(myLuaState,-1) << " occured in scripting block" << std::endl; return -1; } speedProfile.trafficSignalPenalty = 10*lua_tointeger(myLuaState, -1); if(0 != luaL_dostring( myLuaState, "return u_turn_penalty\n")) { std::cerr << lua_tostring(myLuaState,-1) << " occured in scripting block" << std::endl; return -1; } speedProfile.uTurnPenalty = 10*lua_tointeger(myLuaState, -1); speedProfile.has_turn_penalty_function = lua_function_exists( myLuaState, "turn_function" ); std::vector<ImportEdge> edgeList; NodeID nodeBasedNodeNumber = readBinaryOSRMGraphFromStream(in, edgeList, bollardNodes, trafficLightNodes, &internalToExternalNodeMapping, inputRestrictions); in.close(); SimpleLogger().Write() << inputRestrictions.size() << " restrictions, " << bollardNodes.size() << " bollard nodes, " << trafficLightNodes.size() << " traffic lights"; if(0 == edgeList.size()) { std::cerr << "The input data is broken. " "It is impossible to do any turns in this graph" << std::endl; return -1; } /*** * Building an edge-expanded graph from node-based input an turn restrictions */ SimpleLogger().Write() << "Generating edge-expanded graph representation"; EdgeBasedGraphFactory * edgeBasedGraphFactory = new EdgeBasedGraphFactory (nodeBasedNodeNumber, edgeList, bollardNodes, trafficLightNodes, inputRestrictions, internalToExternalNodeMapping, speedProfile); std::vector<ImportEdge>().swap(edgeList); edgeBasedGraphFactory->Run(edgeOut.c_str(), myLuaState); std::vector<_Restriction>().swap(inputRestrictions); std::vector<NodeID>().swap(bollardNodes); std::vector<NodeID>().swap(trafficLightNodes); NodeID edgeBasedNodeNumber = edgeBasedGraphFactory->GetNumberOfNodes(); DeallocatingVector<EdgeBasedEdge> edgeBasedEdgeList; edgeBasedGraphFactory->GetEdgeBasedEdges(edgeBasedEdgeList); std::vector<EdgeBasedGraphFactory::EdgeBasedNode> nodeBasedEdgeList; edgeBasedGraphFactory->GetEdgeBasedNodes(nodeBasedEdgeList); delete edgeBasedGraphFactory; /*** * Writing info on original (node-based) nodes */ SimpleLogger().Write() << "writing node map ..."; std::ofstream mapOutFile(nodeOut.c_str(), std::ios::binary); mapOutFile.write((char *)&(internalToExternalNodeMapping[0]), internalToExternalNodeMapping.size()*sizeof(NodeInfo)); mapOutFile.close(); std::vector<NodeInfo>().swap(internalToExternalNodeMapping); double expansionHasFinishedTime = get_timestamp() - startupTime; /*** * Building grid-like nearest-neighbor data structure */ SimpleLogger().Write() << "building r-tree ..."; StaticRTree<EdgeBasedGraphFactory::EdgeBasedNode> * rtree = new StaticRTree<EdgeBasedGraphFactory::EdgeBasedNode>( nodeBasedEdgeList, rtree_nodes_path.c_str(), rtree_leafs_path.c_str() ); delete rtree; IteratorbasedCRC32<std::vector<EdgeBasedGraphFactory::EdgeBasedNode> > crc32; unsigned crc32OfNodeBasedEdgeList = crc32(nodeBasedEdgeList.begin(), nodeBasedEdgeList.end() ); nodeBasedEdgeList.clear(); SimpleLogger().Write() << "CRC32: " << crc32OfNodeBasedEdgeList; /*** * Contracting the edge-expanded graph */ SimpleLogger().Write() << "initializing contractor"; Contractor* contractor = new Contractor( edgeBasedNodeNumber, edgeBasedEdgeList ); double contractionStartedTimestamp(get_timestamp()); contractor->Run(); const double contraction_duration = (get_timestamp() - contractionStartedTimestamp); SimpleLogger().Write() << "Contraction took " << contraction_duration << " sec"; DeallocatingVector< QueryEdge > contractedEdgeList; contractor->GetEdges( contractedEdgeList ); delete contractor; /*** * Sorting contracted edges in a way that the static query graph can read some in in-place. */ SimpleLogger().Write() << "Building Node Array"; std::sort(contractedEdgeList.begin(), contractedEdgeList.end()); unsigned numberOfNodes = 0; unsigned numberOfEdges = contractedEdgeList.size(); SimpleLogger().Write() << "Serializing compacted graph of " << numberOfEdges << " edges"; std::ofstream hsgr_output_stream(graphOut.c_str(), std::ios::binary); hsgr_output_stream.write((char*)&uuid_orig, sizeof(UUID) ); BOOST_FOREACH(const QueryEdge & edge, contractedEdgeList) { if(edge.source > numberOfNodes) { numberOfNodes = edge.source; } if(edge.target > numberOfNodes) { numberOfNodes = edge.target; } } numberOfNodes+=1; std::vector< StaticGraph<EdgeData>::_StrNode > _nodes; _nodes.resize( numberOfNodes + 1 ); StaticGraph<EdgeData>::EdgeIterator edge = 0; StaticGraph<EdgeData>::EdgeIterator position = 0; for ( StaticGraph<EdgeData>::NodeIterator node = 0; node <= numberOfNodes; ++node ) { StaticGraph<EdgeData>::EdgeIterator lastEdge = edge; while ( edge < numberOfEdges && contractedEdgeList[edge].source == node ) ++edge; _nodes[node].firstEdge = position; //=edge position += edge - lastEdge; //remove } ++numberOfNodes; //Serialize numberOfNodes, nodes hsgr_output_stream.write((char*) &crc32OfNodeBasedEdgeList, sizeof(unsigned)); hsgr_output_stream.write((char*) &numberOfNodes, sizeof(unsigned)); hsgr_output_stream.write((char*) &_nodes[0], sizeof(StaticGraph<EdgeData>::_StrNode)*(numberOfNodes)); //Serialize number of Edges hsgr_output_stream.write((char*) &position, sizeof(unsigned)); --numberOfNodes; edge = 0; int usedEdgeCounter = 0; StaticGraph<EdgeData>::_StrEdge currentEdge; for ( StaticGraph<EdgeData>::NodeIterator node = 0; node < numberOfNodes; ++node ) { for ( StaticGraph<EdgeData>::EdgeIterator i = _nodes[node].firstEdge, e = _nodes[node+1].firstEdge; i != e; ++i ) { assert(node != contractedEdgeList[edge].target); currentEdge.target = contractedEdgeList[edge].target; currentEdge.data = contractedEdgeList[edge].data; if(currentEdge.data.distance <= 0) { SimpleLogger().Write(logWARNING) << "Edge: " << i << ",source: " << contractedEdgeList[edge].source << ", target: " << contractedEdgeList[edge].target << ", dist: " << currentEdge.data.distance; SimpleLogger().Write(logWARNING) << "Failed at edges of node " << node << " of " << numberOfNodes; return -1; } //Serialize edges hsgr_output_stream.write((char*) &currentEdge, sizeof(StaticGraph<EdgeData>::_StrEdge)); ++edge; ++usedEdgeCounter; } } SimpleLogger().Write() << "Preprocessing : " << (get_timestamp() - startupTime) << " seconds"; SimpleLogger().Write() << "Expansion : " << (nodeBasedNodeNumber/expansionHasFinishedTime) << " nodes/sec and " << (edgeBasedNodeNumber/expansionHasFinishedTime) << " edges/sec"; SimpleLogger().Write() << "Contraction: " << (edgeBasedNodeNumber/contraction_duration) << " nodes/sec and " << usedEdgeCounter/contraction_duration << " edges/sec"; hsgr_output_stream.close(); //cleanedEdgeList.clear(); _nodes.clear(); SimpleLogger().Write() << "finished preprocessing"; } catch ( const std::exception &e ) { SimpleLogger().Write(logWARNING) << "Exception occured: " << e.what() << std::endl; return -1; } return 0; }
correct timing of durations
correct timing of durations
C++
bsd-2-clause
tkhaxton/osrm-backend,bjtaylor1/Project-OSRM-Old,antoinegiret/osrm-geovelo,duizendnegen/osrm-backend,Tristramg/osrm-backend,raymond0/osrm-backend,antoinegiret/osrm-backend,tkhaxton/osrm-backend,bjtaylor1/Project-OSRM-Old,hydrays/osrm-backend,antoinegiret/osrm-backend,arnekaiser/osrm-backend,hydrays/osrm-backend,alex85k/Project-OSRM,keesklopt/matrix,bjtaylor1/Project-OSRM-Old,prembasumatary/osrm-backend,neilbu/osrm-backend,neilbu/osrm-backend,frodrigo/osrm-backend,beemogmbh/osrm-backend,keesklopt/matrix,duizendnegen/osrm-backend,Carsten64/OSRM-aux-git,nagyistoce/osrm-backend,KnockSoftware/osrm-backend,Tristramg/osrm-backend,keesklopt/matrix,atsuyim/osrm-backend,Conggge/osrm-backend,ammeurer/osrm-backend,frodrigo/osrm-backend,chaupow/osrm-backend,ammeurer/osrm-backend,yuryleb/osrm-backend,antoinegiret/osrm-geovelo,raymond0/osrm-backend,bjtaylor1/osrm-backend,oxidase/osrm-backend,prembasumatary/osrm-backend,beemogmbh/osrm-backend,ramyaragupathy/osrm-backend,yuryleb/osrm-backend,felixguendling/osrm-backend,agruss/osrm-backend,keesklopt/matrix,antoinegiret/osrm-geovelo,jpizarrom/osrm-backend,skyborla/osrm-backend,skyborla/osrm-backend,yuryleb/osrm-backend,ramyaragupathy/osrm-backend,arnekaiser/osrm-backend,bjtaylor1/osrm-backend,KnockSoftware/osrm-backend,neilbu/osrm-backend,ramyaragupathy/osrm-backend,bjtaylor1/osrm-backend,atsuyim/osrm-backend,KnockSoftware/osrm-backend,stevevance/Project-OSRM,agruss/osrm-backend,Conggge/osrm-backend,nagyistoce/osrm-backend,hydrays/osrm-backend,neilbu/osrm-backend,raymond0/osrm-backend,duizendnegen/osrm-backend,Carsten64/OSRM-aux-git,oxidase/osrm-backend,ammeurer/osrm-backend,KnockSoftware/osrm-backend,duizendnegen/osrm-backend,jpizarrom/osrm-backend,chaupow/osrm-backend,stevevance/Project-OSRM,deniskoronchik/osrm-backend,Carsten64/OSRM-aux-git,stevevance/Project-OSRM,hydrays/osrm-backend,frodrigo/osrm-backend,Conggge/osrm-backend,Carsten64/OSRM-aux-git,bitsteller/osrm-backend,agruss/osrm-backend,felixguendling/osrm-backend,Project-OSRM/osrm-backend,deniskoronchik/osrm-backend,oxidase/osrm-backend,Project-OSRM/osrm-backend,Tristramg/osrm-backend,ammeurer/osrm-backend,antoinegiret/osrm-backend,skyborla/osrm-backend,ammeurer/osrm-backend,alex85k/Project-OSRM,felixguendling/osrm-backend,Conggge/osrm-backend,atsuyim/osrm-backend,deniskoronchik/osrm-backend,ammeurer/osrm-backend,deniskoronchik/osrm-backend,Project-OSRM/osrm-backend,alex85k/Project-OSRM,raymond0/osrm-backend,beemogmbh/osrm-backend,ammeurer/osrm-backend,bjtaylor1/osrm-backend,frodrigo/osrm-backend,oxidase/osrm-backend,Project-OSRM/osrm-backend,arnekaiser/osrm-backend,chaupow/osrm-backend,jpizarrom/osrm-backend,bjtaylor1/Project-OSRM-Old,arnekaiser/osrm-backend,beemogmbh/osrm-backend,prembasumatary/osrm-backend,yuryleb/osrm-backend,nagyistoce/osrm-backend,tkhaxton/osrm-backend,bitsteller/osrm-backend,stevevance/Project-OSRM,bitsteller/osrm-backend
e43920cc688d05a299ea8100722a9f229bdfdb91
firmware/Parser.cpp
firmware/Parser.cpp
#include <string.h> #include <Arduino.h> #include <MutilaDebug.h> #include "Matrix.h" #include "Parser.h" #include "Config.h" #include "SmallTextMode.h" #include "ClearMode.h" #include "CountdownMode.h" #include "TimerMode.h" #include "WinnerMode.h" #include "PowerMode.h" #include "SetMaxPowerMode.h" #include "SetIDMode.h" #include "Settings.h" RIDisplayCommandParser Parser; RIDisplayCommandMapper::RIDisplayCommandMapper() : _count(0) { } void RIDisplayCommandMapper::add(const char* id, RIDisplayCommand cmd, uint8_t maxData, DisplayMode* mode) { if (_count < RIDCP_MAX_IDS) { DB(F("RIDisplayCommandMapper::add ")); DBLN(id); strncpy(_id[_count], id, 2); _cmd[_count] = cmd; _maxData[_count] = maxData; _modes[_count] = mode; _count++; } else { DBLN(F("RIDisplayCommandMapper::add FULL")); } } RIDisplayCommand RIDisplayCommandMapper::getCmd(const char* id) { for (uint8_t i=0; i<_count; i++) { if (strncmp(id, _id[i], 2) == 0) { return _cmd[i]; } } return None; } uint8_t RIDisplayCommandMapper::getMaxData(RIDisplayCommand cmd) { for (uint8_t i=0; i<_count; i++) { if (cmd == _cmd[i]) { return _maxData[i]; } } return 0; } DisplayMode* RIDisplayCommandMapper::getMode(RIDisplayCommand cmd) { for (uint8_t i=0; i<_count; i++) { if (cmd == _cmd[i]) { return _modes[i]; } } return NULL; } RIDisplayCommandParser::RIDisplayCommandParser() { } void RIDisplayCommandParser::begin() { // Do this here rather than the constructor so that // we can expect Serial to be initialized for debugging // output... setID(DisplayID0.get(), DisplayID1.get()); _mapper.add("P", Power, 5, &PowerMode); _mapper.add("V", VoltageAndCurrent, 8, &SmallTextMode); _mapper.add("TI", Timer, 4, &TimerMode); _mapper.add("CL", Clear, 0, &ClearMode); _mapper.add("MP", MaxGraphPower, 4, &SetMaxPowerMode); _mapper.add("ST", String, 35, &SmallTextMode); _mapper.add("WN", Winner, 1, &WinnerMode); _mapper.add("CD", Countdown, 1, &CountdownMode); _mapper.add("ID", SetID, 2, &SetIDMode); // Make sure the buffer is reset reset(); } void RIDisplayCommandParser::update() { if (millis() > _timeout && _ptr > 0) { DBLN(F("TIMEOUT")); reset(); } bool fire = false; if (Serial.available() > 0) { int c = Serial.read(); if (c == '\n' || c == '\r') { fire = true; } else { _buf[_ptr] = c; DB('+'); DB(_buf[_ptr]); switch(_ptr++) { case 0: if (_buf[0] != 'a') { DBLN(F("RST HDR0")); reset(); } else { _last = millis(); _timeout = _last + CMD_TIMEOUT_MS; } break; case 1: if (_buf[1] != _id0 && _id0 != '*') { DBLN(F("RST HDR1")); reset(); } break; case 2: if (_buf[2] != _id1 && _id1 != '*') { DBLN(F("RST HDR2")); reset(); } break; case 3: _cmd = _mapper.getCmd(_buf+3); if (_cmd != None) { DB(F("1-byte cmd=#")); DBLN(_cmd); _dataOffset = 4; } break; case 4: if (_cmd == None) { _cmd = _mapper.getCmd(_buf+3); if (_cmd != None) { DB(F("2-byte cmd=#")); DBLN(_cmd); _dataOffset = 5; } else { DB(F("RST CMD")); reset(); } } break; default: break; } DB(F("_buf now=")); DBLN(_buf); } // Double check we didn't exceed the buffer size. Shouldn't ever // trigger cos we have set the mapper data lengths to be small // enough that we never do this, but just in case... if (_ptr >= RIDCP_BUFFER_LEN) { fire = true; } // Test to see if we've had enough data for the current command... if (_cmd != None) { DB(F("we have command id=#")); DB(_cmd); DB(F(" data we have: ")); DB(_ptr-_dataOffset); DB('/'); DBLN(_mapper.getMaxData(_cmd)); if (_ptr-_dataOffset >= _mapper.getMaxData(_cmd)) { fire = true; } } if (fire) { DB(F("READY! AIM! ")); DisplayMode* mode = _mapper.getMode(_cmd); if (mode != NULL) { DBLN(F("FIRE!")); Matrix.startMode(mode, _buf+_dataOffset); } else { DBLN(F("[click]")); } reset(); } } } bool RIDisplayCommandParser::valid() { return false; } bool RIDisplayCommandParser::complete() { return false; } void RIDisplayCommandParser::reset() { _last = 0; memset(_buf, 0, RIDCP_BUFFER_LEN); _ptr = 0; _dataOffset = 0; _cmd = None; _timeout = 0; } void RIDisplayCommandParser::setID(uint8_t id0, uint8_t id1) { _id0 = id0; _id1 = id1; if ((_id0 < 'A' || id0 > 'Z') && id0 != '*') _id0 = '*'; if ((_id1 < 'A' || id1 > 'Z') && id1 != '*') _id1 = '*'; Serial.print(F("Display ID is: ")); Serial.print((char)_id0); Serial.println((char)_id1); }
#include <string.h> #include <Arduino.h> #include <MutilaDebug.h> #include "Matrix.h" #include "Parser.h" #include "Config.h" #include "SmallTextMode.h" #include "ClearMode.h" #include "CountdownMode.h" #include "TimerMode.h" #include "WinnerMode.h" #include "PowerMode.h" #include "SetMaxPowerMode.h" #include "SetIDMode.h" #include "Settings.h" RIDisplayCommandParser Parser; RIDisplayCommandMapper::RIDisplayCommandMapper() : _count(0) { } void RIDisplayCommandMapper::add(const char* id, RIDisplayCommand cmd, uint8_t maxData, DisplayMode* mode) { if (_count < RIDCP_MAX_IDS) { DB(F("RIDisplayCommandMapper::add ")); DBLN(id); strncpy(_id[_count], id, 2); _cmd[_count] = cmd; _maxData[_count] = maxData; _modes[_count] = mode; _count++; } else { DBLN(F("RIDisplayCommandMapper::add FULL")); } } RIDisplayCommand RIDisplayCommandMapper::getCmd(const char* id) { for (uint8_t i=0; i<_count; i++) { if (strncmp(id, _id[i], 2) == 0) { return _cmd[i]; } } return None; } uint8_t RIDisplayCommandMapper::getMaxData(RIDisplayCommand cmd) { for (uint8_t i=0; i<_count; i++) { if (cmd == _cmd[i]) { return _maxData[i]; } } return 0; } DisplayMode* RIDisplayCommandMapper::getMode(RIDisplayCommand cmd) { for (uint8_t i=0; i<_count; i++) { if (cmd == _cmd[i]) { return _modes[i]; } } return NULL; } RIDisplayCommandParser::RIDisplayCommandParser() { } void RIDisplayCommandParser::begin() { // Do this here rather than the constructor so that // we can expect Serial to be initialized for debugging // output... setID(DisplayID0.get(), DisplayID1.get()); _mapper.add("P", Power, 5, &PowerMode); _mapper.add("V", VoltageAndCurrent, 8, &SmallTextMode); _mapper.add("TI", Timer, 4, &TimerMode); _mapper.add("CL", Clear, 0, &ClearMode); _mapper.add("MP", MaxGraphPower, 4, &SetMaxPowerMode); _mapper.add("ST", String, RIDCP_BUFFER_LEN-6, &SmallTextMode); _mapper.add("WN", Winner, 1, &WinnerMode); _mapper.add("CD", Countdown, 1, &CountdownMode); _mapper.add("ID", SetID, 2, &SetIDMode); // Make sure the buffer is reset reset(); } void RIDisplayCommandParser::update() { if (millis() > _timeout && _ptr > 0) { DBLN(F("TIMEOUT")); reset(); } bool fire = false; if (Serial.available() > 0) { int c = Serial.read(); if (c == '\n' || c == '\r') { fire = true; } else { _buf[_ptr] = c; DB('+'); DB(_buf[_ptr]); switch(_ptr++) { case 0: if (_buf[0] != 'a') { DBLN(F("RST HDR0")); reset(); } else { _last = millis(); _timeout = _last + CMD_TIMEOUT_MS; } break; case 1: if (_buf[1] != _id0 && _id0 != '*') { DBLN(F("RST HDR1")); reset(); } break; case 2: if (_buf[2] != _id1 && _id1 != '*') { DBLN(F("RST HDR2")); reset(); } break; case 3: _cmd = _mapper.getCmd(_buf+3); if (_cmd != None) { DB(F("1-byte cmd=#")); DBLN(_cmd); _dataOffset = 4; } break; case 4: if (_cmd == None) { _cmd = _mapper.getCmd(_buf+3); if (_cmd != None) { DB(F("2-byte cmd=#")); DBLN(_cmd); _dataOffset = 5; } else { DB(F("RST CMD")); reset(); } } break; default: break; } DB(F("_buf now=")); DBLN(_buf); } // Double check we didn't exceed the buffer size. Shouldn't ever // trigger cos we have set the mapper data lengths to be small // enough that we never do this, but just in case... if (_ptr >= RIDCP_BUFFER_LEN) { fire = true; } // Test to see if we've had enough data for the current command... if (_cmd != None) { DB(F("we have command id=#")); DB(_cmd); DB(F(" data we have: ")); DB(_ptr-_dataOffset); DB('/'); DBLN(_mapper.getMaxData(_cmd)); if (_ptr-_dataOffset >= _mapper.getMaxData(_cmd)) { fire = true; } } if (fire) { DB(F("READY! AIM! ")); DisplayMode* mode = _mapper.getMode(_cmd); if (mode != NULL) { DBLN(F("FIRE!")); Matrix.startMode(mode, _buf+_dataOffset); } else { DBLN(F("[click]")); } reset(); } } } bool RIDisplayCommandParser::valid() { return false; } bool RIDisplayCommandParser::complete() { return false; } void RIDisplayCommandParser::reset() { _last = 0; memset(_buf, 0, RIDCP_BUFFER_LEN); _ptr = 0; _dataOffset = 0; _cmd = None; _timeout = 0; } void RIDisplayCommandParser::setID(uint8_t id0, uint8_t id1) { _id0 = id0; _id1 = id1; if ((_id0 < 'A' || id0 > 'Z') && id0 != '*') _id0 = '*'; if ((_id1 < 'A' || id1 > 'Z') && id1 != '*') _id1 = '*'; Serial.print(F("Display ID is: ")); Serial.print((char)_id0); Serial.println((char)_id1); }
extend ST param size
extend ST param size
C++
mit
bespokegear/Power_Meter_Display_EA_LED_Matrix,bespokegear/Power_Meter_Display_EA_LED_Matrix,bespokegear/Power_Meter_Display_EA_LED_Matrix
b87e78e478ee71c5b208795b2a6df26af2f45366
io/xml/src/TXMLSetup.cxx
io/xml/src/TXMLSetup.cxx
// @(#)root/xml:$Id$ // Author: Sergey Linev 10.05.2004 /************************************************************************* * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //________________________________________________________________________ // // Class TXMLSetup is used as storage of xml file settings // This class is used in TXMLFile and in TXmlBuffer classes. // Xml settings can be coded via a string in following format // // "2xoo" // ||| \ . // || \ usage of name spaces. // | \ usage of DTD; // \ storage of TStreamerInfo objects in file; // layout of xml file (= 2 - specialized (default), = 3 - generic) // // For last three boolean parameters "x" means true, "o" - false // // Such string can be set as argument of TXMLFile constructor. In that // case new TXMLFile with such parameters will be created. // These settings automatically stored in xml file. //________________________________________________________________________ #include "TXMLSetup.h" #include "TROOT.h" #include "TClass.h" #include "TStreamerElement.h" #include "Riostream.h" #include <stdlib.h> ClassImp(TXMLSetup); namespace xmlio { const char *Root = "root"; const char *Setup = "setup"; const char *ClassVersion = "version"; const char *IOVersion = "version"; const char *OnlyVersion = "Version"; const char *Ptr = "ptr"; const char *Ref = "ref"; const char *Null = "null"; const char *IdBase = "id"; const char *Size = "size"; const char *Xmlobject = "XmlObject"; const char *Xmlkey = "XmlKey"; const char *Cycle = "cycle"; const char *XmlBlock = "XmlBlock"; const char *Zip = "zip"; const char *Object = "Object"; const char *ObjClass = "class"; const char *Class = "Class"; const char *Member = "Member"; const char *Item = "Item"; const char *Name = "name"; const char *Title = "title"; const char *CreateTm = "created"; const char *ModifyTm = "modified"; const char *ObjectUUID = "uuid"; const char *Type = "type"; const char *Value = "value"; const char *v = "v"; const char *cnt = "cnt"; const char *True = "true"; const char *False = "false"; const char *SInfos = "StreamerInfos"; const char *Array = "Array"; const char *Bool = "Bool_t"; const char *Char = "Char_t"; const char *Short = "Short_t"; const char *Int = "Int_t"; const char *Long = "Long_t"; const char *Long64 = "Long64_t"; const char *Float = "Float_t"; const char *Double = "Double_t"; const char *UChar = "UChar_t"; const char *UShort = "UShort_t"; const char *UInt = "UInt_t"; const char *ULong = "ULong_t"; const char *ULong64 = "ULong64_t"; const char *String = "string"; const char *CharStar = "CharStar"; }; TString TXMLSetup::fgNameSpaceBase = "http://root.cern.ch/root/htmldoc/"; //////////////////////////////////////////////////////////////////////////////// /// return default value for XML setup TString TXMLSetup::DefaultXmlSetup() { return TString("2xoo"); } //////////////////////////////////////////////////////////////////////////////// /// set namespace base void TXMLSetup::SetNameSpaceBase(const char *namespacebase) { fgNameSpaceBase = namespacebase; } //////////////////////////////////////////////////////////////////////////////// /// creates TXMLSetup object getting values from string TXMLSetup::TXMLSetup(const char *opt) { ReadSetupFromStr(opt); } //////////////////////////////////////////////////////////////////////////////// /// copy constructor of TXMLSetup class TXMLSetup::TXMLSetup(const TXMLSetup &src) : fXmlLayout(src.fXmlLayout), fStoreStreamerInfos(src.fStoreStreamerInfos), fUseDtd(src.fUseDtd), fUseNamespaces(src.fUseNamespaces) { } //////////////////////////////////////////////////////////////////////////////// /// assign operator TXMLSetup &TXMLSetup::operator=(const TXMLSetup &rhs) { fXmlLayout = rhs.fXmlLayout; fStoreStreamerInfos = rhs.fStoreStreamerInfos; fUseDtd = rhs.fUseDtd; fUseNamespaces = rhs.fUseNamespaces; } //////////////////////////////////////////////////////////////////////////////// /// return setup values as string TString TXMLSetup::GetSetupAsString() { char setupstr[10] = "2xxx"; setupstr[0] = char(48 + fXmlLayout); setupstr[1] = fStoreStreamerInfos ? 'x' : 'o'; setupstr[2] = fUseDtd ? 'x' : 'o'; setupstr[3] = fUseNamespaces ? 'x' : 'o'; return TString(setupstr); } //////////////////////////////////////////////////////////////////////////////// /// checks if string is valid setup Bool_t TXMLSetup::IsValidXmlSetup(const char *setupstr) { if (!setupstr || (strlen(setupstr) != 4)) return kFALSE; TString str = setupstr; str.ToLower(); if ((str[0] < 48) || (str[0] > 53)) return kFALSE; for (int n = 1; n < 4; n++) if ((str[n] != 'o') && (str[n] != 'x')) return kFALSE; return kTRUE; } //////////////////////////////////////////////////////////////////////////////// /// get values from string Bool_t TXMLSetup::ReadSetupFromStr(const char *setupstr) { if (!setupstr || (strlen(setupstr) < 4)) return kFALSE; Int_t lay = EXMLLayout(setupstr[0] - 48); if (lay == kGeneralized) fXmlLayout = kGeneralized; else fXmlLayout = kSpecialized; fStoreStreamerInfos = setupstr[1] == 'x'; fUseDtd = kFALSE; fUseNamespaces = setupstr[3] == 'x'; return kTRUE; } //////////////////////////////////////////////////////////////////////////////// /// show setup values void TXMLSetup::PrintSetup() { std::cout << " *** Setup printout ***" << std::endl; std::cout << "Attribute mode = " << fXmlLayout << std::endl; std::cout << "Store streamer infos = " << (fStoreStreamerInfos ? "true" : "false") << std::endl; std::cout << "Use dtd = " << (fUseDtd ? "true" : "false") << std::endl; std::cout << "Use name spaces = " << (fUseNamespaces ? "true" : "false") << std::endl; } //////////////////////////////////////////////////////////////////////////////// /// convert class name to exclude any special symbols like ':', '<' '>' ',' and spaces const char *TXMLSetup::XmlConvertClassName(const char *clname) { fStrBuf = clname; fStrBuf.ReplaceAll("<", "_"); fStrBuf.ReplaceAll(">", "_"); fStrBuf.ReplaceAll(",", "_"); fStrBuf.ReplaceAll(" ", "_"); fStrBuf.ReplaceAll(":", "_"); return fStrBuf.Data(); } //////////////////////////////////////////////////////////////////////////////// /// produce string which used as reference in class namespace definition const char *TXMLSetup::XmlClassNameSpaceRef(const TClass *cl) { TString clname = XmlConvertClassName(cl->GetName()); fStrBuf = fgNameSpaceBase; fStrBuf += clname; if (fgNameSpaceBase == "http://root.cern.ch/root/htmldoc/") fStrBuf += ".html"; return fStrBuf.Data(); } //////////////////////////////////////////////////////////////////////////////// /// return converted name for TStreamerElement const char *TXMLSetup::XmlGetElementName(const TStreamerElement *el) { if (!el) return nullptr; if (!el->InheritsFrom(TStreamerSTL::Class())) return el->GetName(); if (strcmp(el->GetName(), el->GetClassPointer()->GetName()) != 0) return el->GetName(); return XmlConvertClassName(el->GetName()); } //////////////////////////////////////////////////////////////////////////////// /// get item name for given element const char *TXMLSetup::GetElItemName(TStreamerElement *el) { if (!el) return nullptr; fStrBuf = el->GetName(); fStrBuf += "_item"; return fStrBuf.Data(); } //////////////////////////////////////////////////////////////////////////////// /// define class for the converted class name, where /// special symbols were replaced by '_' TClass *TXMLSetup::XmlDefineClass(const char *xmlClassName) { if (strchr(xmlClassName, '_') == 0) return TClass::GetClass(xmlClassName); TIter iter(gROOT->GetListOfClasses()); TClass *cl = nullptr; while ((cl = (TClass *)iter()) != nullptr) { const char *name = XmlConvertClassName(cl->GetName()); if (strcmp(xmlClassName, name) == 0) return cl; } return nullptr; } //////////////////////////////////////////////////////////////////////////////// /// converts string to integer. /// if error, returns default value Int_t TXMLSetup::AtoI(const char *sbuf, Int_t def, const char *errinfo) { if (sbuf) return atoi(sbuf); if (errinfo) std::cerr << "<Error in TXMLSetup::AtoI>" << errinfo << " not valid integer: sbuf <NULL>" << std::endl; return def; }
// @(#)root/xml:$Id$ // Author: Sergey Linev 10.05.2004 /************************************************************************* * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //________________________________________________________________________ // // Class TXMLSetup is used as storage of xml file settings // This class is used in TXMLFile and in TXmlBuffer classes. // Xml settings can be coded via a string in following format // // "2xoo" // ||| \ . // || \ usage of name spaces. // | \ usage of DTD; // \ storage of TStreamerInfo objects in file; // layout of xml file (= 2 - specialized (default), = 3 - generic) // // For last three boolean parameters "x" means true, "o" - false // // Such string can be set as argument of TXMLFile constructor. In that // case new TXMLFile with such parameters will be created. // These settings automatically stored in xml file. //________________________________________________________________________ #include "TXMLSetup.h" #include "TROOT.h" #include "TClass.h" #include "TStreamerElement.h" #include "Riostream.h" #include <stdlib.h> ClassImp(TXMLSetup); namespace xmlio { const char *Root = "root"; const char *Setup = "setup"; const char *ClassVersion = "version"; const char *IOVersion = "version"; const char *OnlyVersion = "Version"; const char *Ptr = "ptr"; const char *Ref = "ref"; const char *Null = "null"; const char *IdBase = "id"; const char *Size = "size"; const char *Xmlobject = "XmlObject"; const char *Xmlkey = "XmlKey"; const char *Cycle = "cycle"; const char *XmlBlock = "XmlBlock"; const char *Zip = "zip"; const char *Object = "Object"; const char *ObjClass = "class"; const char *Class = "Class"; const char *Member = "Member"; const char *Item = "Item"; const char *Name = "name"; const char *Title = "title"; const char *CreateTm = "created"; const char *ModifyTm = "modified"; const char *ObjectUUID = "uuid"; const char *Type = "type"; const char *Value = "value"; const char *v = "v"; const char *cnt = "cnt"; const char *True = "true"; const char *False = "false"; const char *SInfos = "StreamerInfos"; const char *Array = "Array"; const char *Bool = "Bool_t"; const char *Char = "Char_t"; const char *Short = "Short_t"; const char *Int = "Int_t"; const char *Long = "Long_t"; const char *Long64 = "Long64_t"; const char *Float = "Float_t"; const char *Double = "Double_t"; const char *UChar = "UChar_t"; const char *UShort = "UShort_t"; const char *UInt = "UInt_t"; const char *ULong = "ULong_t"; const char *ULong64 = "ULong64_t"; const char *String = "string"; const char *CharStar = "CharStar"; }; TString TXMLSetup::fgNameSpaceBase = "http://root.cern.ch/root/htmldoc/"; //////////////////////////////////////////////////////////////////////////////// /// return default value for XML setup TString TXMLSetup::DefaultXmlSetup() { return TString("2xoo"); } //////////////////////////////////////////////////////////////////////////////// /// set namespace base void TXMLSetup::SetNameSpaceBase(const char *namespacebase) { fgNameSpaceBase = namespacebase; } //////////////////////////////////////////////////////////////////////////////// /// creates TXMLSetup object getting values from string TXMLSetup::TXMLSetup(const char *opt) { ReadSetupFromStr(opt); } //////////////////////////////////////////////////////////////////////////////// /// copy constructor of TXMLSetup class TXMLSetup::TXMLSetup(const TXMLSetup &src) : fXmlLayout(src.fXmlLayout), fStoreStreamerInfos(src.fStoreStreamerInfos), fUseDtd(src.fUseDtd), fUseNamespaces(src.fUseNamespaces) { } //////////////////////////////////////////////////////////////////////////////// /// assign operator TXMLSetup &TXMLSetup::operator=(const TXMLSetup &rhs) { fXmlLayout = rhs.fXmlLayout; fStoreStreamerInfos = rhs.fStoreStreamerInfos; fUseDtd = rhs.fUseDtd; fUseNamespaces = rhs.fUseNamespaces; return *this; } //////////////////////////////////////////////////////////////////////////////// /// return setup values as string TString TXMLSetup::GetSetupAsString() { char setupstr[10] = "2xxx"; setupstr[0] = char(48 + fXmlLayout); setupstr[1] = fStoreStreamerInfos ? 'x' : 'o'; setupstr[2] = fUseDtd ? 'x' : 'o'; setupstr[3] = fUseNamespaces ? 'x' : 'o'; return TString(setupstr); } //////////////////////////////////////////////////////////////////////////////// /// checks if string is valid setup Bool_t TXMLSetup::IsValidXmlSetup(const char *setupstr) { if (!setupstr || (strlen(setupstr) != 4)) return kFALSE; TString str = setupstr; str.ToLower(); if ((str[0] < 48) || (str[0] > 53)) return kFALSE; for (int n = 1; n < 4; n++) if ((str[n] != 'o') && (str[n] != 'x')) return kFALSE; return kTRUE; } //////////////////////////////////////////////////////////////////////////////// /// get values from string Bool_t TXMLSetup::ReadSetupFromStr(const char *setupstr) { if (!setupstr || (strlen(setupstr) < 4)) return kFALSE; Int_t lay = EXMLLayout(setupstr[0] - 48); if (lay == kGeneralized) fXmlLayout = kGeneralized; else fXmlLayout = kSpecialized; fStoreStreamerInfos = setupstr[1] == 'x'; fUseDtd = kFALSE; fUseNamespaces = setupstr[3] == 'x'; return kTRUE; } //////////////////////////////////////////////////////////////////////////////// /// show setup values void TXMLSetup::PrintSetup() { std::cout << " *** Setup printout ***" << std::endl; std::cout << "Attribute mode = " << fXmlLayout << std::endl; std::cout << "Store streamer infos = " << (fStoreStreamerInfos ? "true" : "false") << std::endl; std::cout << "Use dtd = " << (fUseDtd ? "true" : "false") << std::endl; std::cout << "Use name spaces = " << (fUseNamespaces ? "true" : "false") << std::endl; } //////////////////////////////////////////////////////////////////////////////// /// convert class name to exclude any special symbols like ':', '<' '>' ',' and spaces const char *TXMLSetup::XmlConvertClassName(const char *clname) { fStrBuf = clname; fStrBuf.ReplaceAll("<", "_"); fStrBuf.ReplaceAll(">", "_"); fStrBuf.ReplaceAll(",", "_"); fStrBuf.ReplaceAll(" ", "_"); fStrBuf.ReplaceAll(":", "_"); return fStrBuf.Data(); } //////////////////////////////////////////////////////////////////////////////// /// produce string which used as reference in class namespace definition const char *TXMLSetup::XmlClassNameSpaceRef(const TClass *cl) { TString clname = XmlConvertClassName(cl->GetName()); fStrBuf = fgNameSpaceBase; fStrBuf += clname; if (fgNameSpaceBase == "http://root.cern.ch/root/htmldoc/") fStrBuf += ".html"; return fStrBuf.Data(); } //////////////////////////////////////////////////////////////////////////////// /// return converted name for TStreamerElement const char *TXMLSetup::XmlGetElementName(const TStreamerElement *el) { if (!el) return nullptr; if (!el->InheritsFrom(TStreamerSTL::Class())) return el->GetName(); if (strcmp(el->GetName(), el->GetClassPointer()->GetName()) != 0) return el->GetName(); return XmlConvertClassName(el->GetName()); } //////////////////////////////////////////////////////////////////////////////// /// get item name for given element const char *TXMLSetup::GetElItemName(TStreamerElement *el) { if (!el) return nullptr; fStrBuf = el->GetName(); fStrBuf += "_item"; return fStrBuf.Data(); } //////////////////////////////////////////////////////////////////////////////// /// define class for the converted class name, where /// special symbols were replaced by '_' TClass *TXMLSetup::XmlDefineClass(const char *xmlClassName) { if (strchr(xmlClassName, '_') == 0) return TClass::GetClass(xmlClassName); TIter iter(gROOT->GetListOfClasses()); TClass *cl = nullptr; while ((cl = (TClass *)iter()) != nullptr) { const char *name = XmlConvertClassName(cl->GetName()); if (strcmp(xmlClassName, name) == 0) return cl; } return nullptr; } //////////////////////////////////////////////////////////////////////////////// /// converts string to integer. /// if error, returns default value Int_t TXMLSetup::AtoI(const char *sbuf, Int_t def, const char *errinfo) { if (sbuf) return atoi(sbuf); if (errinfo) std::cerr << "<Error in TXMLSetup::AtoI>" << errinfo << " not valid integer: sbuf <NULL>" << std::endl; return def; }
add missing return statement
[xml] add missing return statement
C++
lgpl-2.1
olifre/root,karies/root,olifre/root,karies/root,olifre/root,root-mirror/root,root-mirror/root,karies/root,root-mirror/root,olifre/root,karies/root,olifre/root,root-mirror/root,karies/root,karies/root,root-mirror/root,root-mirror/root,root-mirror/root,root-mirror/root,olifre/root,root-mirror/root,karies/root,root-mirror/root,karies/root,olifre/root,karies/root,karies/root,olifre/root,root-mirror/root,olifre/root,olifre/root,karies/root,olifre/root
7f8002ee5f1efcb092b0d7a22f8ecc2fd113960b
scythe/id3.hpp
scythe/id3.hpp
#ifndef ID3_HPP_ #define ID3_HPP_ #include <assert.h> #include <cmath> #include <math.h> #include <queue> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define NO_FEATURE -1 #define NO_INSTANCE 0 #define NO_SPLIT_VALUE INFINITY #define NUM_SPLIT_LABELS 3 #define COST_OF_EMPTINESS INFINITY typedef unsigned int uint; typedef double data_t; typedef int target_t; namespace gbdf_part { const int QUARTILE_PARTITIONING = 0xB23A40; const int DECILE_PARTITIONING = 0xB23A41; const int PERCENTILE_PARTITIONING = 0xB23A42; } namespace gbdf_task { const int CLASSIFICATION_TASK = 0xF55A90; const int REGRESSION_TASK = 0xF55A91; } struct Node { int id; int feature_id; size_t* counters; size_t n_instances; double score; data_t split_value; struct Node* left_child; struct Node* right_child; }; struct TreeConfig { int task; bool is_incremental; double min_threshold; size_t max_height; size_t n_classes; size_t max_nodes; int partitioning; data_t nan_value; }; struct Density { bool is_categorical; data_t split_value; data_t* quartiles; data_t* deciles; data_t* percentiles; size_t* counters_left; size_t* counters_right; size_t* counters_nan; }; template <typename T> struct Splitter { int task; struct Node* node; size_t n_instances; data_t* partition_values; size_t n_classes; size_t* belongs_to; size_t feature_id; size_t n_features; T* targets; data_t nan_value; }; struct Tree { struct Node* root; size_t n_nodes; size_t n_classes; size_t n_features; struct TreeConfig* config; }; #include "id3.tpp" #endif // ID3_HPP_
#ifndef ID3_HPP_ #define ID3_HPP_ #include <assert.h> #include <cmath> #include <math.h> #include <queue> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits> constexpr int NO_FEATURE = -1; constexpr int NO_INSTANCE = 0; constexpr int NO_SPLIT_VALUE = std::numeric_limits<int>::max(); constexpr int NUM_SPLIT_LABELS = 3; constexpr int COST_OF_EMPTINESS = std::numeric_limits<int>::max(); typedef unsigned int uint; typedef double data_t; typedef int target_t; namespace gbdf_part { constexpr int QUARTILE_PARTITIONING = 0xB23A40; constexpr int DECILE_PARTITIONING = 0xB23A41; constexpr int PERCENTILE_PARTITIONING = 0xB23A42; } namespace gbdf_task { constexpr int CLASSIFICATION_TASK = 0xF55A90; constexpr int REGRESSION_TASK = 0xF55A91; } struct Node { int id; int feature_id; size_t* counters; size_t n_instances; double score; data_t split_value; struct Node* left_child; struct Node* right_child; }; struct TreeConfig { int task; bool is_incremental; double min_threshold; size_t max_height; size_t n_classes; size_t max_nodes; int partitioning; data_t nan_value; }; struct Density { bool is_categorical; data_t split_value; data_t* quartiles; data_t* deciles; data_t* percentiles; size_t* counters_left; size_t* counters_right; size_t* counters_nan; }; template <typename T> struct Splitter { int task; struct Node* node; size_t n_instances; data_t* partition_values; size_t n_classes; size_t* belongs_to; size_t feature_id; size_t n_features; T* targets; data_t nan_value; }; struct Tree { struct Node* root; size_t n_nodes; size_t n_classes; size_t n_features; struct TreeConfig* config; }; #include "id3.tpp" #endif // ID3_HPP_
Use constexpr constants rather than defines
Use constexpr constants rather than defines Constexpr constants are more type-safe, respect namespaces, and are true lvalue, while constants with #define does not even respect your wife. In C++, preprocessor is only used for compilation logic (such as optional compilation, include, library compilation options).
C++
apache-2.0
AntoinePassemiers/Scythe,AntoinePassemiers/Scythe,AntoinePassemiers/Scythe
6207ba409f36c7e5ecca33d82b663dc9060a86eb
src/cpp/session/modules/rmarkdown/NotebookPlots.cpp
src/cpp/session/modules/rmarkdown/NotebookPlots.cpp
/* * NotebookPlots.cpp * * Copyright (C) 2009-16 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionRmdNotebook.hpp" #include "NotebookPlots.hpp" #include "../SessionPlots.hpp" #include <boost/format.hpp> #include <boost/foreach.hpp> #include <boost/signals/connection.hpp> #include <core/system/FileMonitor.hpp> #include <core/StringUtils.hpp> #include <session/SessionModuleContext.hpp> #include <r/RExec.hpp> #include <r/RSexp.hpp> #include <r/session/RGraphics.hpp> #define kPlotPrefix "_rs_chunk_plot_" using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace rmarkdown { namespace notebook { namespace { class PlotState { public: PlotState(): hasPlots(false) { } bool hasPlots; r::sexp::PreservedSEXP sexpMargins; boost::signals::connection onConsolePrompt; boost::signals::connection onNewPlot; }; bool isPlotPath(const FilePath& path) { return path.hasExtensionLowerCase(".png") && string_utils::isPrefixOf(path.stem(), kPlotPrefix); } void processPlots(const FilePath& plotFolder, boost::shared_ptr<PlotState> pPlotState) { // ensure plot folder exists if (!plotFolder.exists()) return; // collect plots from the folder std::vector<FilePath> folderContents; Error error = plotFolder.children(&folderContents); if (error) LOG_ERROR(error); BOOST_FOREACH(const FilePath& path, folderContents) { if (isPlotPath(path)) { #ifndef _WIN32 // on Windows, turning off the PNG device writes an empty PNG file if no // plot output occurs; we avoid treating that empty file as an actual plot // by only emitting an event if a plot occurred. // // TODO: not all plot libraries cause the new plot hooks to invoke, so this // heuristic may cause us to miss a plot on Windows; we may need some // mechanism by which we can determine whether the device or its output is // empty. if (pPlotState->hasPlots) #endif events().onPlotOutput(path); // clean up the plot so it isn't emitted twice error = path.removeIfExists(); if (error) LOG_ERROR(error); } } } void removeGraphicsDevice(const FilePath& plotFolder, boost::shared_ptr<PlotState> pPlotState) { // restore the figure margins Error error = r::exec::RFunction("par", pPlotState->sexpMargins).call(); if (error) LOG_ERROR(error); // turn off the graphics device -- this has the side effect of writing the // device's remaining output to files error = r::exec::RFunction("dev.off").call(); if (error) LOG_ERROR(error); processPlots(plotFolder, pPlotState); } void onNewPlot(const FilePath& plotFolder, boost::shared_ptr<PlotState> pPlotState) { pPlotState->hasPlots = true; processPlots(plotFolder, pPlotState); } void onConsolePrompt(const FilePath& plotFolder, boost::shared_ptr<PlotState> pPlotState, const std::string& ) { removeGraphicsDevice(plotFolder, pPlotState); pPlotState->onConsolePrompt.disconnect(); pPlotState->onNewPlot.disconnect(); } } // anonymous namespace // begins capturing plot output core::Error beginPlotCapture(const FilePath& plotFolder) { // clean up any stale plots from the folder std::vector<FilePath> folderContents; Error error = plotFolder.children(&folderContents); if (error) return error; BOOST_FOREACH(const core::FilePath& file, folderContents) { // remove if it looks like a plot if (isPlotPath(file)) { error = file.remove(); if (error) { // this is non-fatal LOG_ERROR(error); } } } // generate code for creating PNG device boost::format fmt("{ require(grDevices, quietly=TRUE); " " png(file = \"%1%/" kPlotPrefix "%%03d.png\", " " width = 6.5, height = 4, " " units=\"in\", res = 96 %2%)" "}"); // marker for content; this is necessary because on Windows, turning off // the png device writes an empty PNG file even if nothing was plotted, and // we need to avoid treating that file as though it were an actual plot boost::shared_ptr<PlotState> pPlotState = boost::make_shared<PlotState>(); // create the PNG device error = r::exec::executeString( (fmt % string_utils::utf8ToSystem(plotFolder.absolutePath()) % r::session::graphics::extraBitmapParams()).str()); if (error) return error; // save old plot state r::exec::RFunction par("par"); par.addParam("no.readonly", true); r::sexp::Protect protect; SEXP sexpMargins; error = par.call(&sexpMargins, &protect); if (error) LOG_ERROR(error); // preserve until chunk is finished executing pPlotState->sexpMargins.set(sexpMargins); // set notebook-friendly figure margins // bot left top right error = r::exec::executeString("par(mar = c(5.1, 4.1, 2.1, 2.1))"); if (error) LOG_ERROR(error); // complete the capture on the next console prompt pPlotState->onConsolePrompt = module_context::events().onConsolePrompt.connect( boost::bind(onConsolePrompt, plotFolder, pPlotState, _1)); pPlotState->onNewPlot = plots::events().onNewPlot.connect( boost::bind(onNewPlot, plotFolder, pPlotState)); return Success(); } } // namespace notebook } // namespace rmarkdown } // namespace modules } // namespace session } // namespace rstudio
/* * NotebookPlots.cpp * * Copyright (C) 2009-16 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionRmdNotebook.hpp" #include "NotebookPlots.hpp" #include "../SessionPlots.hpp" #include <boost/format.hpp> #include <boost/foreach.hpp> #include <boost/signals/connection.hpp> #include <core/system/FileMonitor.hpp> #include <core/StringUtils.hpp> #include <session/SessionModuleContext.hpp> #include <r/RExec.hpp> #include <r/RSexp.hpp> #include <r/session/RGraphics.hpp> #define kPlotPrefix "_rs_chunk_plot_" using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace rmarkdown { namespace notebook { namespace { class PlotState { public: PlotState(): hasPlots(false) { } bool hasPlots; r::sexp::PreservedSEXP sexpMargins; boost::signals::connection onConsolePrompt; boost::signals::connection onNewPlot; }; bool isPlotPath(const FilePath& path) { return path.hasExtensionLowerCase(".png") && string_utils::isPrefixOf(path.stem(), kPlotPrefix); } void processPlots(const FilePath& plotFolder, boost::shared_ptr<PlotState> pPlotState) { // ensure plot folder exists if (!plotFolder.exists()) return; // collect plots from the folder std::vector<FilePath> folderContents; Error error = plotFolder.children(&folderContents); if (error) LOG_ERROR(error); BOOST_FOREACH(const FilePath& path, folderContents) { if (isPlotPath(path)) { #ifdef _WIN32 // on Windows, turning off the PNG device writes an empty PNG file if no // plot output occurs; we avoid treating that empty file as an actual plot // by only emitting an event if a plot occurred. // // TODO: not all plot libraries cause the new plot hooks to invoke, so this // heuristic may cause us to miss a plot on Windows; we may need some // mechanism by which we can determine whether the device or its output is // empty. if (pPlotState->hasPlots) #endif events().onPlotOutput(path); // clean up the plot so it isn't emitted twice error = path.removeIfExists(); if (error) LOG_ERROR(error); } } } void removeGraphicsDevice(const FilePath& plotFolder, boost::shared_ptr<PlotState> pPlotState) { // restore the figure margins Error error = r::exec::RFunction("par", pPlotState->sexpMargins).call(); if (error) LOG_ERROR(error); // turn off the graphics device -- this has the side effect of writing the // device's remaining output to files error = r::exec::RFunction("dev.off").call(); if (error) LOG_ERROR(error); processPlots(plotFolder, pPlotState); } void onNewPlot(const FilePath& plotFolder, boost::shared_ptr<PlotState> pPlotState) { pPlotState->hasPlots = true; processPlots(plotFolder, pPlotState); } void onConsolePrompt(const FilePath& plotFolder, boost::shared_ptr<PlotState> pPlotState, const std::string& ) { removeGraphicsDevice(plotFolder, pPlotState); pPlotState->onConsolePrompt.disconnect(); pPlotState->onNewPlot.disconnect(); } } // anonymous namespace // begins capturing plot output core::Error beginPlotCapture(const FilePath& plotFolder) { // clean up any stale plots from the folder std::vector<FilePath> folderContents; Error error = plotFolder.children(&folderContents); if (error) return error; BOOST_FOREACH(const core::FilePath& file, folderContents) { // remove if it looks like a plot if (isPlotPath(file)) { error = file.remove(); if (error) { // this is non-fatal LOG_ERROR(error); } } } // generate code for creating PNG device boost::format fmt("{ require(grDevices, quietly=TRUE); " " png(file = \"%1%/" kPlotPrefix "%%03d.png\", " " width = 6.5, height = 4, " " units=\"in\", res = 96 %2%)" "}"); // marker for content; this is necessary because on Windows, turning off // the png device writes an empty PNG file even if nothing was plotted, and // we need to avoid treating that file as though it were an actual plot boost::shared_ptr<PlotState> pPlotState = boost::make_shared<PlotState>(); // create the PNG device error = r::exec::executeString( (fmt % string_utils::utf8ToSystem(plotFolder.absolutePath()) % r::session::graphics::extraBitmapParams()).str()); if (error) return error; // save old plot state r::exec::RFunction par("par"); par.addParam("no.readonly", true); r::sexp::Protect protect; SEXP sexpMargins; error = par.call(&sexpMargins, &protect); if (error) LOG_ERROR(error); // preserve until chunk is finished executing pPlotState->sexpMargins.set(sexpMargins); // set notebook-friendly figure margins // bot left top right error = r::exec::executeString("par(mar = c(5.1, 4.1, 2.1, 2.1))"); if (error) LOG_ERROR(error); // complete the capture on the next console prompt pPlotState->onConsolePrompt = module_context::events().onConsolePrompt.connect( boost::bind(onConsolePrompt, plotFolder, pPlotState, _1)); pPlotState->onNewPlot = plots::events().onNewPlot.connect( boost::bind(onNewPlot, plotFolder, pPlotState)); return Success(); } } // namespace notebook } // namespace rmarkdown } // namespace modules } // namespace session } // namespace rstudio
fix ggplot output on non-Windows
fix ggplot output on non-Windows
C++
agpl-3.0
JanMarvin/rstudio,jrnold/rstudio,jar1karp/rstudio,jar1karp/rstudio,jrnold/rstudio,jar1karp/rstudio,jar1karp/rstudio,jar1karp/rstudio,jrnold/rstudio,jrnold/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,jrnold/rstudio,JanMarvin/rstudio,jrnold/rstudio,JanMarvin/rstudio,jrnold/rstudio,jar1karp/rstudio,JanMarvin/rstudio,jrnold/rstudio,JanMarvin/rstudio,jar1karp/rstudio,jar1karp/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,jar1karp/rstudio,jrnold/rstudio
68f64d960ad3e7f00615612e017ea27ec7defc2b
host/cv/OCV.cpp
host/cv/OCV.cpp
/** * OpenCV (OCV) - Video capture on BBB * * GOAL: * This program takes continuous images from the host camera and detect a circular * object of specific color. The color and other configuration are provided as * input argument to the program. * * INPUT: * The program takes two arguments: * - The video device node (0/1) * - The object color (blue/red) * * OUTPUT: * On each frame captured by the program, three files are exported into the * host filesystem (apache directory specifically): * - A colored image with a green circular around the circular object * - A binarized image of the colored image (previous bullet) * - A text file containing information about the object captured * In addition to storing images, at each frame iteration, the program executes a shell script * to communicate information about the frame with the ATMEGA328. * * HOST REQUIREMENTS: * The following packages are required to be installed on the host: * - Apache2 server * - OpenSSH server **/ #include <fstream> #include <iostream> #include <cstring> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <string> #include <vector> #include <math.h> #include <stdlib.h> #include <cstdlib> #include <sstream> #include <stdio.h> #include <ctime> #include <unistd.h> #define PI 3.14159265 using namespace cv; using namespace std; // Keep track of video camera frame number long frameNumber = 0; // Write to files every time the counter reaches zero const int FRAME_EVERY = 3; int currentFrame = FRAME_EVERY; // Assign unique ID for each direction. // The ID must be in sync with the GUI direction values // (Please refer to the documentation for more information about the GUI code) int direction = 0; clock_t start_time; const int FORWARD = 1; const int REVERSE = 2; const int RIGHT = 3; const int LEFT = 4; const int ROTATE = 5; const int PAUSE = 6; const int STOP = 7; /** * Get the distance between the object and the camera * Please refer to the documentation report for more information * about the calculations * @return Distance in cm **/ double getDistance(double realDimention, double digitalDimention) { double FOCAL_LENGTH = 339.079; // in pixels int ERROR_MARGIN = 0; //pixels lost due to selection of circular shape return realDimention * FOCAL_LENGTH / (digitalDimention + ERROR_MARGIN); } /** * Detect the edge point of the object. This information allows the * conclusion of the object digial radius * @param imageDest Current video frame * @param def Default point value in case no object was found * @return arbitrary point on the object edge **/ Point edgePoint(Mat imageDest, Point def) { int thresh = 100; // Canny Algorithm for object edge detection Canny(imageDest, imageDest, thresh /*threshold1*/, thresh*2 /*threshold2*/, 3/*apertureSize*/); // Prepare data structure to store the edge points vector<vector<Point> > contours; vector<Vec4i> hierarchy; // Perform the countour finder findContours(imageDest, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); // If no object foud, return the provided default value if(contours.size() == 0) { return def; } // Return a point from the countour return contours[0][0]; } /** * Predefined set of colors that can be detected by the program * The colors supported by the current program are blue and red * @param specs Data strucutre to hold the HSV channel color information * based on the color specified * @param color Color of the object (blue/red) **/ void get_color_specs(vector<vector<int> > &specs, string color){ if (!color.compare("blue")) { specs[0][0] = 100; specs[0][1] = 115; specs[0][2] = 50; specs[1][0] = 130; specs[1][1] = 255; specs[1][2] = 255; } else if (!color.compare("red")) { specs[0][0] = 0; specs[0][1] = 197; specs[0][2] = 109; specs[1][0] = 182; specs[1][1] = 255; specs[1][2] = 255; } else { specs[0][0] = 255; specs[0][1] = 255; specs[0][2] = 255; specs[1][0] = 255; specs[1][1] = 255; specs[1][2] = 255; } } void drive(int left, int right) { stringstream ss; ss << "/home/debian/mr_robot/tools/control/write " << left << "," << right << "#" << endl; cout << left << "," << right << "#" << endl; system(ss.str().c_str()); } /** * Drive the car based on the angle and distance * Decisions are mainly taken based on experiments * @param angle Car angel * @param distance Distance of the car from the camera * @param diameter Digital diameter of the circular object * @param loop_count Necessary to keep from writing to Atmega328p faster than it can read messages * @return Direction code **/ void find_ball(double angle, double distance, double diameter, int &loop_count) { int full_speed = 255; int rotation_speed = 140; int turn_speed = 40; int pausing_distance = 45; int target_angle = 4; if (loop_count > 1) { // If no object found: rotate if(diameter == 0 && direction != ROTATE) { cout << endl << "rotating "; drive(rotation_speed, -rotation_speed); direction = ROTATE; loop_count = 0; start_time = clock(); // If object is within pausing_distance and visible: pause } else if(distance <= pausing_distance && diameter > 0 && direction != PAUSE) { cout << endl << "pausing "; drive(0, 0); direction = PAUSE; loop_count = 0; cout << "\n**** BALL FOUND ****\n" << endl; // If object more than target_angle degrees to right and farther than pausing distance: turn right } else if (angle > target_angle && distance >= pausing_distance && direction != RIGHT){ cout << endl << "turning right "; drive(turn_speed, -turn_speed); direction = RIGHT; loop_count = 0; // If object more than target_angle degrees to left and farther than pausing distance: turn left } else if (angle < -target_angle && distance >= pausing_distance && direction != LEFT) { cout << endl << "turning left "; drive(-turn_speed, turn_speed); direction = LEFT; loop_count = 0; // If ball is past pausing distance and within target_angle: forward } else if (distance > pausing_distance && angle < target_angle && angle > -target_angle && direction != FORWARD) { cout << endl << "going forward "; drive(full_speed, full_speed); direction = FORWARD; loop_count = 0; // If ball rotates ~360 degrees and doesn't see ball: stop } else if (direction == ROTATE) { clock_t rotation_duration = (clock() - start_time) / (double)(CLOCKS_PER_SEC); cout << "\trot time: " << rotation_duration << " s" << endl; if (rotation_duration > 12) { drive(0, 0); cout << "\n**** BALL NOT FOUND ****\n" << endl; direction = STOP; } } } loop_count++; } /** * Start the OpenCV program **/ int main( int argc, char** argv ) { // Capture video number is: /dev/video(0/1) int cap_num = atoi(argv[1]); // Color blue/red string color = argv[2]; // Start camera VideoCapture cap; if(!cap.open(cap_num)) return 1; // Configure the camera for fast capture and good resolution cap.set(CV_CAP_PROP_FRAME_WIDTH, 432); cap.set(CV_CAP_PROP_FRAME_HEIGHT,240); cap.set(CV_CAP_PROP_FPS , 30); // loop_count is used to make sure that the find_ball function has looped at least twice // before sending a message to the Atmega328p. This was created in response to a bug found // when writing too fast to the Atmega328p. The direction variable would be modified however // the write message wouldn't be interpreted. This causes the car to get stuck in a // certain direction. Initialized to 2 so that the car begins moving immediately int loop_count = 2; // Keep taking pictures while(1) { // Store the frame in a matrix Mat imageSrc; cap >> imageSrc; // Fetch the color information vector<vector<int> > color_specs(2, vector<int>(3)); get_color_specs(color_specs, color); // HSV low-high values int lowH = color_specs[0][0]; int highH = color_specs[1][0]; int lowS = color_specs[0][1]; int highS = color_specs[1][1]; int lowV = color_specs[0][2]; int highV = color_specs[1][2]; // Destination image Mat imageDest; // Convert BGR to HSV cvtColor(imageSrc, imageDest, COLOR_BGR2HSV); // Get colors in specified range inRange(imageDest, Scalar(lowH, lowS, lowV), Scalar(highH, highS, highV), imageDest); // Morphological opening erode(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); dilate(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); // Morphological closing dilate(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); erode(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); // Create moment Moments mmts = moments(imageDest); // Calculate center x and y (Centroids) double x_object = mmts.m10 / mmts.m00; double y_object = mmts.m01 / mmts.m00; // Center of image cv::Size size = imageSrc.size(); double x_center = size.width/2.0f; double y_center = size.height/2.0f; // Contour Mat tmpDest = imageDest.clone(); Point point = edgePoint(tmpDest, Point(x_center, y_center)); // Calculate digital diameter in cm double diameter = norm(Point(x_object, y_object)- point)*2; double realDiameter = 6.5; // Calculate the real distance double distance = getDistance(realDiameter, diameter); // Get rotation angle int digitalDiff = x_object - x_center; double realDiff = digitalDiff * (realDiameter / diameter); double rotation_angle = atan(realDiff / distance) * 180 / PI; // If no object found, then diameter is set to zero if(isnan((double)x_object) && isnan((double)y_object)) { diameter = 0.0;; } // Log the calculated information cout << endl; printf("\t%-10s%4.2f\n", "angle:", rotation_angle); printf("\t%-10s%4.2f\n", "distance:", distance); printf("\t%-10s%4.2f\n", "diameter:", diameter); // Draw circle at x and y Mat tmpSource = imageSrc.clone(); circle(tmpSource, Point(x_object,y_object), 3, Scalar(229, 240, 76), 2); circle(tmpSource, Point(x_object,y_object), diameter/2, Scalar(44, 252, 14), 3); // Center circle(tmpSource, Point(x_center,y_center), 2, Scalar(255, 255, 255), 2); // Logic to navigate to ball find_ball(rotation_angle, distance, diameter, loop_count); // Write images and text into the file system/ // Director /var/www/html correspond to the path for // Apache2 server. All files placed in this directory will be // accessible on all users in the network over host IP and port 80 string path = "/home/debian/mr_robot/dashboard/mr-robot-node/public/debug/"; string outPath = path + "out.jpg"; string bwPath = path + "bw.jpg"; string infoPath = path + "info.txt"; if(--currentFrame == 0) { imwrite(outPath, tmpSource); imwrite(bwPath, imageDest); } ofstream myfile; myfile.open (infoPath.c_str()); myfile << "Distance from camera: " << distance << " cm\n"; myfile << "Rotation angle: " << rotation_angle << "\n"; myfile << "Digital diameter: " << diameter << " px\n"; myfile << "Frame number: " << ++frameNumber << "\n"; string dir_message = "Direction: "; switch (direction) { case FORWARD: myfile << dir_message << "Forward" << endl; break; case REVERSE: myfile << dir_message << "Reversing" << endl; break; case RIGHT: myfile << dir_message << "Right" << endl; break; case LEFT: myfile << dir_message << "Left" << endl; break; case ROTATE: myfile << dir_message << "Rotating" << endl; break; case PAUSE: myfile << dir_message << "Pause" << endl; break; case STOP: myfile << dir_message << "Stop" << endl; break; } myfile << "DIR_CODE: " << direction << "\n"; myfile.close(); if (direction == STOP) { return 0; } } return 0; }
/** * OpenCV (OCV) - Video capture on BBB * * GOAL: * This program takes continuous images from the host camera and detect a circular * object of specific color. The color and other configuration are provided as * input argument to the program. * * INPUT: * The program takes two arguments: * - The video device node (0/1) * - The object color (blue/red) * * OUTPUT: * On each frame captured by the program, three files are exported into the * host filesystem (apache directory specifically): * - A colored image with a green circular around the circular object * - A binarized image of the colored image (previous bullet) * - A text file containing information about the object captured * In addition to storing images, at each frame iteration, the program executes a shell script * to communicate information about the frame with the ATMEGA328. * * HOST REQUIREMENTS: * The following packages are required to be installed on the host: * - Apache2 server * - OpenSSH server **/ #include <fstream> #include <iostream> #include <cstring> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <string> #include <vector> #include <math.h> #include <stdlib.h> #include <cstdlib> #include <sstream> #include <stdio.h> #include <ctime> #include <unistd.h> #define PI 3.14159265 using namespace cv; using namespace std; // Keep track of video camera frame number long frameNumber = 0; // Write to files every time the counter reaches zero const int FRAME_EVERY = 3; int currentFrame = FRAME_EVERY; // Assign unique ID for each direction. // The ID must be in sync with the GUI direction values // (Please refer to the documentation for more information about the GUI code) int direction = 0; clock_t start_time; const int FORWARD = 1; const int REVERSE = 2; const int RIGHT = 3; const int LEFT = 4; const int ROTATE = 5; const int PAUSE = 6; const int STOP = 7; /** * Get the distance between the object and the camera * Please refer to the documentation report for more information * about the calculations * @return Distance in cm **/ double getDistance(double realDimention, double digitalDimention) { double FOCAL_LENGTH = 339.079; // in pixels int ERROR_MARGIN = 0; //pixels lost due to selection of circular shape return realDimention * FOCAL_LENGTH / (digitalDimention + ERROR_MARGIN); } /** * Detect the edge point of the object. This information allows the * conclusion of the object digial radius * @param imageDest Current video frame * @param def Default point value in case no object was found * @return arbitrary point on the object edge **/ Point edgePoint(Mat imageDest, Point def) { int thresh = 100; // Canny Algorithm for object edge detection Canny(imageDest, imageDest, thresh /*threshold1*/, thresh*2 /*threshold2*/, 3/*apertureSize*/); // Prepare data structure to store the edge points vector<vector<Point> > contours; vector<Vec4i> hierarchy; // Perform the countour finder findContours(imageDest, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); // If no object foud, return the provided default value if(contours.size() == 0) { return def; } // Return a point from the countour return contours[0][0]; } /** * Predefined set of colors that can be detected by the program * The colors supported by the current program are blue and red * @param specs Data strucutre to hold the HSV channel color information * based on the color specified * @param color Color of the object (blue/red) **/ void get_color_specs(vector<vector<int> > &specs, string color){ if (!color.compare("blue")) { specs[0][0] = 100; specs[0][1] = 115; specs[0][2] = 50; specs[1][0] = 130; specs[1][1] = 255; specs[1][2] = 255; } else if (!color.compare("red")) { specs[0][0] = 0; specs[0][1] = 197; specs[0][2] = 109; specs[1][0] = 182; specs[1][1] = 255; specs[1][2] = 255; } else { specs[0][0] = 255; specs[0][1] = 255; specs[0][2] = 255; specs[1][0] = 255; specs[1][1] = 255; specs[1][2] = 255; } } void drive(int left, int right) { stringstream ss; ss << "/home/debian/mr_robot/tools/control/write " << left << "," << right << "#" << endl; cout << left << "," << right << "#" << endl; system(ss.str().c_str()); } /** * Drive the car based on the angle and distance * Decisions are mainly taken based on experiments * @param angle Car angel * @param distance Distance of the car from the camera * @param diameter Digital diameter of the circular object * @param loop_count Necessary to keep from writing to Atmega328p faster than it can read messages * @return Direction code **/ void find_ball(double angle, double distance, double diameter, int &loop_count) { int full_speed = 255; int rotation_speed = 140; int turn_speed = 40; int pausing_distance = 45; int target_angle = 4; if (loop_count > 1) { // If no object found: rotate if(diameter == 0 && direction != ROTATE) { cout << endl << "rotating "; drive(rotation_speed, -rotation_speed); direction = ROTATE; loop_count = 0; start_time = clock(); // If object is within pausing_distance and visible: pause } else if(distance <= pausing_distance && diameter > 0 && direction != PAUSE) { cout << endl << "pausing "; drive(0, 0); direction = PAUSE; loop_count = 0; cout << "\n**** BALL FOUND ****\n" << endl; // If object more than target_angle degrees to right and farther than pausing distance: turn right } else if (angle > target_angle && distance >= pausing_distance && direction != RIGHT){ cout << endl << "turning right "; drive(turn_speed, -turn_speed); direction = RIGHT; loop_count = 0; // If object more than target_angle degrees to left and farther than pausing distance: turn left } else if (angle < -target_angle && distance >= pausing_distance && direction != LEFT) { cout << endl << "turning left "; drive(-turn_speed, turn_speed); direction = LEFT; loop_count = 0; // If ball is past pausing distance and within target_angle: forward } else if (distance > pausing_distance && angle < target_angle && angle > -target_angle && direction != FORWARD) { cout << endl << "going forward "; drive(full_speed, full_speed); direction = FORWARD; loop_count = 0; // If ball rotates ~360 degrees and doesn't see ball: stop } else if (direction == ROTATE) { clock_t rotation_duration = (clock() - start_time) / (double)(CLOCKS_PER_SEC); cout << "\trot time: " << rotation_duration << " s" << endl; if (rotation_duration > 12) { drive(0, 0); cout << "\n**** BALL NOT FOUND ****\n" << endl; direction = STOP; } } } loop_count++; } /** * Start the OpenCV program **/ int main( int argc, char** argv ) { // Capture video number is: /dev/video(0/1) int cap_num = atoi(argv[1]); // Color blue/red string color = argv[2]; // Start camera VideoCapture cap; if(!cap.open(cap_num)) return 1; // Configure the camera for fast capture and good resolution cap.set(CV_CAP_PROP_FRAME_WIDTH, 432); cap.set(CV_CAP_PROP_FRAME_HEIGHT,240); cap.set(CV_CAP_PROP_FPS , 30); // loop_count is used to make sure that the find_ball function has looped at least twice // before sending a message to the Atmega328p. This was created in response to a bug found // when writing too fast to the Atmega328p. The direction variable would be modified however // the write message wouldn't be interpreted. This causes the car to get stuck in a // certain direction. Initialized to 2 so that the car begins moving immediately int loop_count = 2; // Keep taking pictures while(1) { // Store the frame in a matrix Mat imageSrc; cap >> imageSrc; // Fetch the color information vector<vector<int> > color_specs(2, vector<int>(3)); get_color_specs(color_specs, color); // HSV low-high values int lowH = color_specs[0][0]; int highH = color_specs[1][0]; int lowS = color_specs[0][1]; int highS = color_specs[1][1]; int lowV = color_specs[0][2]; int highV = color_specs[1][2]; // Destination image Mat imageDest; // Convert BGR to HSV cvtColor(imageSrc, imageDest, COLOR_BGR2HSV); // Get colors in specified range inRange(imageDest, Scalar(lowH, lowS, lowV), Scalar(highH, highS, highV), imageDest); // Morphological opening erode(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); dilate(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); // Morphological closing dilate(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); erode(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); // Create moment Moments mmts = moments(imageDest); // Calculate center x and y (Centroids) double x_object = mmts.m10 / mmts.m00; double y_object = mmts.m01 / mmts.m00; // Center of image cv::Size size = imageSrc.size(); double x_center = size.width/2.0f; double y_center = size.height/2.0f; // Contour Mat tmpDest = imageDest.clone(); Point point = edgePoint(tmpDest, Point(x_center, y_center)); // Calculate digital diameter in cm double diameter = norm(Point(x_object, y_object)- point)*2; double realDiameter = 6.5; // Calculate the real distance double distance = getDistance(realDiameter, diameter); // Get rotation angle int digitalDiff = x_object - x_center; double realDiff = digitalDiff * (realDiameter / diameter); double rotation_angle = atan(realDiff / distance) * 180 / PI; // If no object found, then diameter is set to zero if(isnan((double)x_object) && isnan((double)y_object)) { diameter = 0.0;; } // Log the calculated information cout << endl; printf("\t%-10s%4.2f\n", "angle:", rotation_angle); printf("\t%-10s%4.2f\n", "distance:", distance); printf("\t%-10s%4.2f\n", "diameter:", diameter); // Draw circle at x and y Mat tmpSource = imageSrc.clone(); circle(tmpSource, Point(x_object,y_object), 3, Scalar(229, 240, 76), 2); circle(tmpSource, Point(x_object,y_object), diameter/2, Scalar(44, 252, 14), 3); // Center circle(tmpSource, Point(x_center,y_center), 2, Scalar(255, 255, 255), 2); // Logic to navigate to ball find_ball(rotation_angle, distance, diameter, loop_count); // Write images and text into the file system/ // Director /var/www/html correspond to the path for // Apache2 server. All files placed in this directory will be // accessible on all users in the network over host IP and port 80 string path = "/home/debian/mr_robot/dashboard/mr-robot-node/public/debug/"; string outPath = path + "out.jpg"; string bwPath = path + "bw.jpg"; string infoPath = path + "info.txt"; if(--currentFrame == 0) { imwrite(outPath, tmpSource); imwrite(bwPath, imageDest); currentFrame = FRAME_EVERY; } ofstream myfile; myfile.open (infoPath.c_str()); myfile << "Distance from camera: " << distance << " cm\n"; myfile << "Rotation angle: " << rotation_angle << "\n"; myfile << "Digital diameter: " << diameter << " px\n"; myfile << "Frame number: " << ++frameNumber << "\n"; string dir_message = "Direction: "; switch (direction) { case FORWARD: myfile << dir_message << "Forward" << endl; break; case REVERSE: myfile << dir_message << "Reversing" << endl; break; case RIGHT: myfile << dir_message << "Right" << endl; break; case LEFT: myfile << dir_message << "Left" << endl; break; case ROTATE: myfile << dir_message << "Rotating" << endl; break; case PAUSE: myfile << dir_message << "Pause" << endl; break; case STOP: myfile << dir_message << "Stop" << endl; break; } myfile << "DIR_CODE: " << direction << "\n"; myfile.close(); if (direction == STOP) { return 0; } } return 0; }
Update OCV.cpp
Update OCV.cpp
C++
mit
EliHar/mr_robot,EliHar/mr_robot,EliHar/mr_robot,EliHar/mr_robot,EliHar/mr_robot,EliHar/mr_robot,EliHar/mr_robot
ac2c44cbb9085d78a74e074fb1adb8ad79c199b6
chrome/browser/android/crash_dump_manager.cc
chrome/browser/android/crash_dump_manager.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/android/crash_dump_manager.h" #include "base/bind.h" #include "base/file_util.h" #include "base/format_macros.h" #include "base/global_descriptors_posix.h" #include "base/logging.h" #include "base/path_service.h" #include "base/process.h" #include "base/rand_util.h" #include "base/stl_util.h" #include "base/stringprintf.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/descriptors_android.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_data.h" #include "content/public/browser/file_descriptor_info.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_process_host.h" using content::BrowserThread; CrashDumpManager::CrashDumpManager() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); notification_registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED, content::NotificationService::AllSources()); notification_registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CLOSED, content::NotificationService::AllSources()); notification_registrar_.Add(this, content::NOTIFICATION_CHILD_PROCESS_HOST_DISCONNECTED, content::NotificationService::AllSources()); notification_registrar_.Add(this, content::NOTIFICATION_CHILD_PROCESS_CRASHED, content::NotificationService::AllSources()); } CrashDumpManager::~CrashDumpManager() { } int CrashDumpManager::CreateMinidumpFile(int child_process_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::PROCESS_LAUNCHER)); FilePath minidump_path; if (!file_util::CreateTemporaryFile(&minidump_path)) return base::kInvalidPlatformFileValue; base::PlatformFileError error; // We need read permission as the minidump is generated in several phases // and needs to be read at some point. int flags = base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ | base::PLATFORM_FILE_WRITE; base::PlatformFile minidump_file = base::CreatePlatformFile(minidump_path, flags, NULL, &error); if (minidump_file == base::kInvalidPlatformFileValue) { LOG(ERROR) << "Failed to create temporary file, crash won't be reported."; return base::kInvalidPlatformFileValue; } MinidumpInfo minidump_info; minidump_info.file = minidump_file; minidump_info.path = minidump_path; { base::AutoLock auto_lock(child_process_id_to_minidump_info_lock_); DCHECK(!ContainsKey(child_process_id_to_minidump_info_, child_process_id)); child_process_id_to_minidump_info_[child_process_id] = minidump_info; } return minidump_file; } void CrashDumpManager::ProcessMinidump(const MinidumpInfo& minidump) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // Close the file descriptor, it is still open. bool r = base::ClosePlatformFile(minidump.file); DCHECK(r) << "Failed to close minidump file descriptor."; int64 file_size = 0; r = file_util::GetFileSize(minidump.path, &file_size); DCHECK(r) << "Failed to retrieve size for minidump " << minidump.path.value(); if (file_size == 0) { // Empty minidump, this process did not crash. Just remove the file. r = file_util::Delete(minidump.path, false); DCHECK(r) << "Failed to delete temporary minidump file " << minidump.path.value(); return; } // We are dealing with a valid minidump. Copy it to the crash report // directory from where Java code will upload it later on. FilePath crash_dump_dir; r = PathService::Get(chrome::DIR_CRASH_DUMPS, &crash_dump_dir); if (!r) { NOTREACHED() << "Failed to retrieve the crash dump directory."; return; } const uint64 rand = base::RandUint64(); const std::string filename = base::StringPrintf("chromium-renderer-minidump-%016" PRIx64 ".dmp%d", rand, minidump.pid); FilePath dest_path = crash_dump_dir.Append(filename); r = file_util::Move(minidump.path, dest_path); if (!r) { LOG(ERROR) << "Failed to move crash dump from " << minidump.path.value() << " to " << dest_path.value(); file_util::Delete(minidump.path, false); return; } LOG(INFO) << "Crash minidump successfully generated: " << crash_dump_dir.Append(filename).value(); } void CrashDumpManager::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { int child_process_id; switch (type) { case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: // NOTIFICATION_RENDERER_PROCESS_TERMINATED is sent when the renderer // process is cleanly shutdown. However, we need to fallthrough so that // we close the minidump_fd we kept open. case content::NOTIFICATION_RENDERER_PROCESS_CLOSED: { content::RenderProcessHost* rph = content::Source<content::RenderProcessHost>(source).ptr(); child_process_id = rph->GetID(); break; } case content::NOTIFICATION_CHILD_PROCESS_CRASHED: case content::NOTIFICATION_CHILD_PROCESS_HOST_DISCONNECTED: { content::ChildProcessData* child_process_data = content::Details<content::ChildProcessData>(details).ptr(); child_process_id = child_process_data->id; break; } default: NOTREACHED(); return; } MinidumpInfo minidump_info; { base::AutoLock auto_lock(child_process_id_to_minidump_info_lock_); ChildProcessIDToMinidumpInfo::iterator iter = child_process_id_to_minidump_info_.find(child_process_id); if (iter == child_process_id_to_minidump_info_.end()) { // We might get a NOTIFICATION_RENDERER_PROCESS_TERMINATED and a // NOTIFICATION_RENDERER_PROCESS_CLOSED. return; } minidump_info = iter->second; child_process_id_to_minidump_info_.erase(iter); } ProcessMinidump(minidump_info); }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/android/crash_dump_manager.h" #include "base/bind.h" #include "base/file_util.h" #include "base/format_macros.h" #include "base/global_descriptors_posix.h" #include "base/logging.h" #include "base/path_service.h" #include "base/process.h" #include "base/rand_util.h" #include "base/stl_util.h" #include "base/stringprintf.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/descriptors_android.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_data.h" #include "content/public/browser/file_descriptor_info.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_process_host.h" using content::BrowserThread; CrashDumpManager::CrashDumpManager() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); notification_registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED, content::NotificationService::AllSources()); notification_registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CLOSED, content::NotificationService::AllSources()); notification_registrar_.Add(this, content::NOTIFICATION_CHILD_PROCESS_HOST_DISCONNECTED, content::NotificationService::AllSources()); notification_registrar_.Add(this, content::NOTIFICATION_CHILD_PROCESS_CRASHED, content::NotificationService::AllSources()); } CrashDumpManager::~CrashDumpManager() { } int CrashDumpManager::CreateMinidumpFile(int child_process_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::PROCESS_LAUNCHER)); FilePath minidump_path; if (!file_util::CreateTemporaryFile(&minidump_path)) return base::kInvalidPlatformFileValue; base::PlatformFileError error; // We need read permission as the minidump is generated in several phases // and needs to be read at some point. int flags = base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ | base::PLATFORM_FILE_WRITE; base::PlatformFile minidump_file = base::CreatePlatformFile(minidump_path, flags, NULL, &error); if (minidump_file == base::kInvalidPlatformFileValue) { LOG(ERROR) << "Failed to create temporary file, crash won't be reported."; return base::kInvalidPlatformFileValue; } MinidumpInfo minidump_info; minidump_info.file = minidump_file; minidump_info.path = minidump_path; { base::AutoLock auto_lock(child_process_id_to_minidump_info_lock_); DCHECK(!ContainsKey(child_process_id_to_minidump_info_, child_process_id)); child_process_id_to_minidump_info_[child_process_id] = minidump_info; } return minidump_file; } void CrashDumpManager::ProcessMinidump(const MinidumpInfo& minidump) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); // Close the file descriptor, it is still open. bool r = base::ClosePlatformFile(minidump.file); DCHECK(r) << "Failed to close minidump file descriptor."; int64 file_size = 0; r = file_util::GetFileSize(minidump.path, &file_size); DCHECK(r) << "Failed to retrieve size for minidump " << minidump.path.value(); if (file_size == 0) { // Empty minidump, this process did not crash. Just remove the file. r = file_util::Delete(minidump.path, false); DCHECK(r) << "Failed to delete temporary minidump file " << minidump.path.value(); return; } // We are dealing with a valid minidump. Copy it to the crash report // directory from where Java code will upload it later on. FilePath crash_dump_dir; r = PathService::Get(chrome::DIR_CRASH_DUMPS, &crash_dump_dir); if (!r) { NOTREACHED() << "Failed to retrieve the crash dump directory."; return; } const uint64 rand = base::RandUint64(); const std::string filename = base::StringPrintf("chromium-renderer-minidump-%016" PRIx64 ".dmp%d", rand, minidump.pid); FilePath dest_path = crash_dump_dir.Append(filename); r = file_util::Move(minidump.path, dest_path); if (!r) { LOG(ERROR) << "Failed to move crash dump from " << minidump.path.value() << " to " << dest_path.value(); file_util::Delete(minidump.path, false); return; } LOG(INFO) << "Crash minidump successfully generated: " << crash_dump_dir.Append(filename).value(); } void CrashDumpManager::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { int child_process_id; switch (type) { case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: // NOTIFICATION_RENDERER_PROCESS_TERMINATED is sent when the renderer // process is cleanly shutdown. However, we need to fallthrough so that // we close the minidump_fd we kept open. case content::NOTIFICATION_RENDERER_PROCESS_CLOSED: { content::RenderProcessHost* rph = content::Source<content::RenderProcessHost>(source).ptr(); child_process_id = rph->GetID(); break; } case content::NOTIFICATION_CHILD_PROCESS_CRASHED: case content::NOTIFICATION_CHILD_PROCESS_HOST_DISCONNECTED: { content::ChildProcessData* child_process_data = content::Details<content::ChildProcessData>(details).ptr(); child_process_id = child_process_data->id; break; } default: NOTREACHED(); return; } MinidumpInfo minidump_info; { base::AutoLock auto_lock(child_process_id_to_minidump_info_lock_); ChildProcessIDToMinidumpInfo::iterator iter = child_process_id_to_minidump_info_.find(child_process_id); if (iter == child_process_id_to_minidump_info_.end()) { // We might get a NOTIFICATION_RENDERER_PROCESS_TERMINATED and a // NOTIFICATION_RENDERER_PROCESS_CLOSED. return; } minidump_info = iter->second; child_process_id_to_minidump_info_.erase(iter); } BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&CrashDumpManager::ProcessMinidump, minidump_info)); }
Call CrashDumpManager::ProcessMiniDump() on the FILE thread.
Call CrashDumpManager::ProcessMiniDump() on the FILE thread. This method was previously supposed to be called on the IO thread although it appeared (failing DCHECK) to be running on another thread (presumably the UI thread). This makes it run on the FILE thread (which seems more appropriate than the IO thread). Review URL: https://chromiumcodereview.appspot.com/11322002 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@164402 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,dushu1203/chromium.src,M4sse/chromium.src,dednal/chromium.src,chuan9/chromium-crosswalk,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,ltilve/chromium,krieger-od/nwjs_chromium.src,Just-D/chromium-1,markYoungH/chromium.src,Fireblend/chromium-crosswalk,dednal/chromium.src,timopulkkinen/BubbleFish,hujiajie/pa-chromium,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,anirudhSK/chromium,jaruba/chromium.src,anirudhSK/chromium,hujiajie/pa-chromium,chuan9/chromium-crosswalk,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,timopulkkinen/BubbleFish,jaruba/chromium.src,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,mogoweb/chromium-crosswalk,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,nacl-webkit/chrome_deps,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,anirudhSK/chromium,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,zcbenz/cefode-chromium,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,dednal/chromium.src,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,M4sse/chromium.src,M4sse/chromium.src,dednal/chromium.src,pozdnyakov/chromium-crosswalk,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk,ltilve/chromium,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,M4sse/chromium.src,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,ltilve/chromium,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,Chilledheart/chromium,M4sse/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,hujiajie/pa-chromium,M4sse/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,jaruba/chromium.src,markYoungH/chromium.src,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,Chilledheart/chromium,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,jaruba/chromium.src,mogoweb/chromium-crosswalk,dednal/chromium.src,Just-D/chromium-1,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,ltilve/chromium,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,Jonekee/chromium.src,Chilledheart/chromium,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,hujiajie/pa-chromium,ondra-novak/chromium.src,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,Jonekee/chromium.src,dednal/chromium.src,zcbenz/cefode-chromium,markYoungH/chromium.src,M4sse/chromium.src,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,ltilve/chromium,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,bright-sparks/chromium-spacewalk,littlstar/chromium.src,bright-sparks/chromium-spacewalk,ltilve/chromium,nacl-webkit/chrome_deps,ltilve/chromium,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ltilve/chromium,fujunwei/chromium-crosswalk,dushu1203/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,nacl-webkit/chrome_deps,anirudhSK/chromium,dednal/chromium.src,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,littlstar/chromium.src,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,anirudhSK/chromium,patrickm/chromium.src,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,dednal/chromium.src,nacl-webkit/chrome_deps,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,axinging/chromium-crosswalk,dednal/chromium.src,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,markYoungH/chromium.src,ChromiumWebApps/chromium,ondra-novak/chromium.src,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,jaruba/chromium.src,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,axinging/chromium-crosswalk,dednal/chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,Jonekee/chromium.src,patrickm/chromium.src,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,markYoungH/chromium.src,ChromiumWebApps/chromium,Just-D/chromium-1,nacl-webkit/chrome_deps,anirudhSK/chromium,dushu1203/chromium.src,Jonekee/chromium.src,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,chuan9/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk,markYoungH/chromium.src,patrickm/chromium.src,jaruba/chromium.src,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,markYoungH/chromium.src,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,Jonekee/chromium.src,M4sse/chromium.src,patrickm/chromium.src,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,anirudhSK/chromium,patrickm/chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,nacl-webkit/chrome_deps,Jonekee/chromium.src,patrickm/chromium.src,axinging/chromium-crosswalk,dushu1203/chromium.src,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,zcbenz/cefode-chromium,dushu1203/chromium.src,axinging/chromium-crosswalk,Chilledheart/chromium,littlstar/chromium.src,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,Just-D/chromium-1,hujiajie/pa-chromium,hujiajie/pa-chromium,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,timopulkkinen/BubbleFish,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk
b13a9b775e36550d77c12cd0ab51257a32183e97
sim/sim_events.cc
sim/sim_events.cc
/* * Copyright (c) 2003 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <string> #include "sim/param.hh" #include "sim/eventq.hh" #include "base/hostinfo.hh" #include "sim/sim_events.hh" #include "sim/sim_exit.hh" #include "sim/sim_stats.hh" using namespace std; // // handle termination event // void SimExitEvent::process() { // This event does not autodelete because exitNow may be called, // and the function will never be allowed to finish. if (theQueue() == &mainEventQueue) { string _cause = cause; int _code = code; delete this; exitNow(_cause, _code); } else { new SimExitEvent(cause, code); delete this; } } const char * SimExitEvent::description() { return "simulation termination"; } // // constructor: automatically schedules at specified time // CountedExitEvent::CountedExitEvent(EventQueue *q, const std::string &_cause, Tick _when, int &_downCounter) : Event(q, Sim_Exit_Pri), cause(_cause), downCounter(_downCounter) { // catch stupid mistakes assert(downCounter > 0); schedule(_when); } // // handle termination event // void CountedExitEvent::process() { if (--downCounter == 0) { new SimExitEvent(cause, 0); } } const char * CountedExitEvent::description() { return "counted exit"; } #ifdef CHECK_SWAP_CYCLES new CheckSwapEvent(&mainEventQueue, CHECK_SWAP_CYCLES); #endif void CheckSwapEvent::process() { /* Check the amount of free swap space */ long swap; /* returns free swap in KBytes */ swap = procInfo("/proc/meminfo", "SwapFree:"); if (swap < 1000) ccprintf(cerr, "\a\a\aWarning! Swap space is low (%d)\n", swap); if (swap < 100) { cerr << "\a\aAborting Simulation! Inadequate swap space!\n\n"; new SimExitEvent("Lack of swap space"); } schedule(curTick + interval); } const char * CheckSwapEvent::description() { return "check swap"; } /////////////////////////////////////////////////// // // Simulation termination parameters // /////////////////////////////////////////////////// class TermParamContext : public ParamContext { public: TermParamContext(const string &_iniSection) : ParamContext(_iniSection) {} void checkParams(); }; TermParamContext simTerminationParams("max"); Param<Tick> max_cycle(&simTerminationParams, "cycle", "maximum number of cycles to execute"); void TermParamContext::checkParams() { // if a max cycle count was specified, put a termination event on // the event queue at that point if (max_cycle.isValid()) new SimExitEvent(max_cycle, "reached maximum cycle count"); } // // Progress event: print out cycle every so often so we know we're // making forward progress. // class ProgressEvent : public Event { protected: Tick interval; public: ProgressEvent(EventQueue *q, Tick interval); void process(); // process event virtual const char *description(); }; // // constructor: schedule at specified time // ProgressEvent::ProgressEvent(EventQueue *q, Tick _interval) : Event(q), interval(_interval) { schedule(interval); } // // handle progress event: print message and reschedule // void ProgressEvent::process() { DPRINTFN("ProgressEvent\n"); // reschedule for next interval schedule(curTick + interval); } const char * ProgressEvent::description() { return "progress message"; } ///////// // // Periodic progress message support: print out a message every n // cycles so we know we're making forward progress. // ///////// // Parameter space for execution address tracing options. Derive // from ParamContext so we can override checkParams() function. class ProgressParamContext : public ParamContext { public: ProgressParamContext(const string &_iniSection) : ParamContext(_iniSection) {} void checkParams(); }; ProgressParamContext progessMessageParams("progress"); Param<Tick> progress_interval(&progessMessageParams, "cycle", "cycle interval for progress messages"); /* check execute options */ void ProgressParamContext::checkParams() { if (progress_interval.isValid()) new ProgressEvent(&mainEventQueue, progress_interval); }
/* * Copyright (c) 2003 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <string> #include "base/callback.hh" #include "base/hostinfo.hh" #include "sim/eventq.hh" #include "sim/param.hh" #include "sim/sim_events.hh" #include "sim/sim_exit.hh" #include "sim/sim_init.hh" #include "sim/sim_stats.hh" using namespace std; // // handle termination event // void SimExitEvent::process() { // This event does not autodelete because exitNow may be called, // and the function will never be allowed to finish. if (theQueue() == &mainEventQueue) { string _cause = cause; int _code = code; delete this; exitNow(_cause, _code); } else { new SimExitEvent(cause, code); delete this; } } const char * SimExitEvent::description() { return "simulation termination"; } // // constructor: automatically schedules at specified time // CountedExitEvent::CountedExitEvent(EventQueue *q, const std::string &_cause, Tick _when, int &_downCounter) : Event(q, Sim_Exit_Pri), cause(_cause), downCounter(_downCounter) { // catch stupid mistakes assert(downCounter > 0); schedule(_when); } // // handle termination event // void CountedExitEvent::process() { if (--downCounter == 0) { new SimExitEvent(cause, 0); } } const char * CountedExitEvent::description() { return "counted exit"; } #ifdef CHECK_SWAP_CYCLES new CheckSwapEvent(&mainEventQueue, CHECK_SWAP_CYCLES); #endif void CheckSwapEvent::process() { /* Check the amount of free swap space */ long swap; /* returns free swap in KBytes */ swap = procInfo("/proc/meminfo", "SwapFree:"); if (swap < 1000) ccprintf(cerr, "\a\a\aWarning! Swap space is low (%d)\n", swap); if (swap < 100) { cerr << "\a\aAborting Simulation! Inadequate swap space!\n\n"; new SimExitEvent("Lack of swap space"); } schedule(curTick + interval); } const char * CheckSwapEvent::description() { return "check swap"; } /////////////////////////////////////////////////// // // Simulation termination parameters // /////////////////////////////////////////////////// class TermParamContext : public ParamContext { public: TermParamContext(const string &_iniSection) : ParamContext(_iniSection) {} void checkParams(); }; TermParamContext simTerminationParams("max"); Param<Tick> max_cycle(&simTerminationParams, "cycle", "maximum number of cycles to execute"); void TermParamContext::checkParams() { // if a max cycle count was specified, put a termination event on // the event queue at that point if (max_cycle.isValid()) new SimExitEvent(max_cycle, "reached maximum cycle count"); } // // Progress event: print out cycle every so often so we know we're // making forward progress. // class ProgressEvent : public Event { protected: Tick interval; public: ProgressEvent(EventQueue *q, Tick interval); void process(); // process event virtual const char *description(); }; // // constructor: schedule at specified time // ProgressEvent::ProgressEvent(EventQueue *q, Tick _interval) : Event(q), interval(_interval) { schedule(curTick + interval); } // // handle progress event: print message and reschedule // void ProgressEvent::process() { DPRINTFN("ProgressEvent\n"); // reschedule for next interval schedule(curTick + interval); } const char * ProgressEvent::description() { return "progress message"; } ///////// // // Periodic progress message support: print out a message every n // cycles so we know we're making forward progress. // ///////// // Parameter space for execution address tracing options. Derive // from ParamContext so we can override checkParams() function. class ProgressParamContext : public ParamContext { public: ProgressParamContext(const string &_iniSection) : ParamContext(_iniSection) {} void checkParams(); }; ProgressParamContext progessMessageParams("progress"); Param<Tick> progress_interval(&progessMessageParams, "cycle", "cycle interval for progress messages"); namespace { struct SetupProgress : public Callback { Tick interval; SetupProgress(Tick tick) : interval(tick) {} virtual void process() { new ProgressEvent(&mainEventQueue, interval); delete this; } }; } /* check execute options */ void ProgressParamContext::checkParams() { if (progress_interval.isValid()) registerInitCallback(new SetupProgress(progress_interval)); }
Make the progress event work even after restoring from a checkpoint
Make the progress event work even after restoring from a checkpoint
C++
bsd-3-clause
pombredanne/http-repo.gem5.org-gem5-,hoangt/tpzsimul.gem5,vovojh/gem5,hoangt/tpzsimul.gem5,vovojh/gem5,vovojh/gem5,vovojh/gem5,pombredanne/http-repo.gem5.org-gem5-,hoangt/tpzsimul.gem5,pombredanne/http-repo.gem5.org-gem5-,hoangt/tpzsimul.gem5,pombredanne/http-repo.gem5.org-gem5-,pombredanne/http-repo.gem5.org-gem5-,hoangt/tpzsimul.gem5,hoangt/tpzsimul.gem5,pombredanne/http-repo.gem5.org-gem5-,vovojh/gem5,vovojh/gem5,hoangt/tpzsimul.gem5,pombredanne/http-repo.gem5.org-gem5-,vovojh/gem5
13a6e28e5b4a77249d5a57df338987a0b6accea1
filesystem/src/filesystem.cpp
filesystem/src/filesystem.cpp
#include <primitives/filesystem.h> #include <primitives/file_iterator.h> #include <boost/algorithm/string.hpp> #include <boost/nowide/fstream.hpp> #include <boost/nowide/integration/filesystem.hpp> #include <boost/nowide/convert.hpp> #include <iostream> #include <regex> path get_home_directory() { #ifdef WIN32 auto home = getenv("USERPROFILE"); if (!home) std::cerr << "Cannot get user's home directory (%USERPROFILE%)\n"; #else auto home = getenv("HOME"); if (!home) std::cerr << "Cannot get user's home directory ($HOME)\n"; #endif if (home == nullptr) return ""; return home; } void remove_file(const path &p) { boost::system::error_code ec; fs::remove(p, ec); if (ec) std::cerr << "Cannot remove file: " << p.string() << "\n"; } void remove_all_from_dir(const path &dir) { for (auto &f : boost::make_iterator_range(fs::directory_iterator(dir), {})) fs::remove_all(f); } String normalize_path(const path &p) { if (p.empty()) return ""; String s = p.string(); normalize_string(s); return s; } String read_file(const path &p, bool no_size_check) { if (!fs::exists(p)) throw std::runtime_error("File '" + p.string() + "' does not exist"); auto fn = p.string(); boost::nowide::ifstream ifile(fn, std::ios::in | std::ios::binary); if (!ifile) throw std::runtime_error("Cannot open file '" + fn + "' for reading"); size_t sz = (size_t)fs::file_size(p); if (!no_size_check && sz > 10'000'000) throw std::runtime_error("File " + fn + " is very big (> ~10 MB)"); String f; f.resize(sz); ifile.read(&f[0], sz); return f; } Strings read_lines(const path &p) { auto s = read_file(p); return split_lines(s); } void write_file(const path &p, const String &s) { auto pp = p.parent_path(); if (!pp.empty()) fs::create_directories(pp); boost::nowide::ofstream ofile(p.string(), std::ios::out | std::ios::binary); if (!ofile) throw std::runtime_error("Cannot open file '" + p.string() + "' for writing"); ofile << s; } void write_file_if_different(const path &p, const String &s) { if (fs::exists(p)) { auto s2 = read_file(p, true); if (s == s2) return; } write_file(p, s); } void copy_dir(const path &src, const path &dst) { boost::system::error_code ec; fs::create_directories(dst, ec); for (auto &f : boost::make_iterator_range(fs::directory_iterator(src), {})) { if (fs::is_directory(f)) copy_dir(f, dst / f.path().filename()); else fs::copy_file(f, dst / f.path().filename(), fs::copy_option::overwrite_if_exists); } } void remove_files(const Files &files) { for (auto &f : files) fs::remove(f); } void remove_files_like(const Files &files, const String &regex) { remove_files(filter_files_like(files, regex)); } void remove_files_like(const path &dir, const String &regex, bool recursive) { remove_files_like(enumerate_files(dir, recursive), regex); } Files enumerate_files(const path &dir, bool recursive) { Files files; if (!fs::exists(dir)) return files; if (recursive) { for (auto &f : boost::make_iterator_range(fs::recursive_directory_iterator(dir), {})) { if (!fs::is_regular_file(f)) continue; files.insert(f); } } else { for (auto &f : boost::make_iterator_range(fs::directory_iterator(dir), {})) { if (!fs::is_regular_file(f)) continue; files.insert(f); } } return files; } Files enumerate_files_like(const path &dir, const String &regex, bool recursive) { return filter_files_like(enumerate_files(dir, recursive), regex); } Files enumerate_files_like(const Files &files, const String &regex) { return filter_files_like(files, regex); } Files filter_files_like(const Files &files, const String &regex) { Files fls; std::regex r(regex); for (auto &f : files) { if (!std::regex_match(f.filename().string(), r)) continue; fls.insert(f); } return fls; } bool is_under_root(path p, const path &root_dir) { if (p.empty()) return false; if (fs::exists(p)) // Converts p, which must exist, to an absolute path // that has no symbolic link, dot, or dot-dot elements. p = fs::canonical(p); while (!p.empty()) { if (p == root_dir) return true; p = p.parent_path(); } return false; } bool compare_files(const path &fn1, const path &fn2) { FileIterator fi({ fn1, fn2 }); return fi.iterate([](const auto &bufs, auto sz) { if (memcmp(bufs[0].get().data(), bufs[1].get().data(), (size_t)sz) != 0) return false; return true; }); } bool compare_dirs(const path &dir1, const path &dir2) { auto traverse_dir = [](const auto &dir) { std::vector<path> files; if (fs::exists(dir)) for (auto &f : boost::make_iterator_range(fs::recursive_directory_iterator(dir), {})) { if (!fs::is_regular_file(f)) continue; files.push_back(f); } return files; }; auto files1 = traverse_dir(dir1); auto files2 = traverse_dir(dir2); if (files1.empty()) return false; // throw std::runtime_error("left side has no files"); if (files2.empty()) return false; // throw std::runtime_error("right side has no files"); if (files1.size() != files2.size()) return false; // throw std::runtime_error("different number of files"); auto sz = files1.size(); for (size_t i = 0; i < sz; i++) { if (!compare_files(files1[i], files2[i])) return false; } return true; } FileIterator::FileIterator(const std::vector<path> &fns) { if (fns.empty()) throw std::runtime_error("Provide at least one file"); for (auto &f : fns) { File d; d.size = fs::file_size(f); d.ifile = std::make_unique<boost::nowide::ifstream>(f.string(), std::ifstream::binary); files.push_back(std::move(d)); } } bool FileIterator::is_same_size() const { auto sz = files.front().size; return std::all_of(files.begin(), files.end(), [sz](const auto &f) { return f.size == sz; }); } bool FileIterator::is_same_read_size() const { auto sz = files.front().read; return std::all_of(files.begin(), files.end(), [sz](const auto &f) { return f.read == sz; }); } bool FileIterator::iterate(std::function<bool(const BuffersRef &, uint64_t)> f) { if (!is_same_size()) return false; BuffersRef buffers; for (auto &f : files) { f.buf.resize(buffer_size); buffers.emplace_back(f.buf); } while (std::none_of(files.begin(), files.end(), [](const auto &f) { return f.ifile->eof(); })) { std::for_each(files.begin(), files.end(), [this](auto &f) { f.ifile->read((char *)&f.buf[0], buffer_size); f.read = f.ifile->gcount(); }); if (!is_same_read_size()) return false; if (!f(buffers, files.front().read)) return false; } return true; } void setup_utf8_filesystem() { boost::nowide::nowide_filesystem(); }
#include <primitives/filesystem.h> #include <primitives/file_iterator.h> #include <boost/algorithm/string.hpp> #include <boost/nowide/fstream.hpp> #include <boost/nowide/integration/filesystem.hpp> #include <boost/nowide/convert.hpp> #include <iostream> #include <regex> path get_home_directory() { #ifdef WIN32 auto home = getenv("USERPROFILE"); if (!home) std::cerr << "Cannot get user's home directory (%USERPROFILE%)\n"; #else auto home = getenv("HOME"); if (!home) std::cerr << "Cannot get user's home directory ($HOME)\n"; #endif if (home == nullptr) return ""; return home; } void remove_file(const path &p) { boost::system::error_code ec; fs::remove(p, ec); if (ec) std::cerr << "Cannot remove file: " << p.string() << "\n"; } void remove_all_from_dir(const path &dir) { for (auto &f : boost::make_iterator_range(fs::directory_iterator(dir), {})) fs::remove_all(f); } String normalize_path(const path &p) { if (p.empty()) return ""; // double path to resolve .. elements path p2 = p.string(); String s = p2.string(); normalize_string(s); return s; } String read_file(const path &p, bool no_size_check) { if (!fs::exists(p)) throw std::runtime_error("File '" + p.string() + "' does not exist"); auto fn = p.string(); boost::nowide::ifstream ifile(fn, std::ios::in | std::ios::binary); if (!ifile) throw std::runtime_error("Cannot open file '" + fn + "' for reading"); size_t sz = (size_t)fs::file_size(p); if (!no_size_check && sz > 10'000'000) throw std::runtime_error("File " + fn + " is very big (> ~10 MB)"); String f; f.resize(sz); ifile.read(&f[0], sz); return f; } Strings read_lines(const path &p) { auto s = read_file(p); return split_lines(s); } void write_file(const path &p, const String &s) { auto pp = p.parent_path(); if (!pp.empty()) fs::create_directories(pp); boost::nowide::ofstream ofile(p.string(), std::ios::out | std::ios::binary); if (!ofile) throw std::runtime_error("Cannot open file '" + p.string() + "' for writing"); ofile << s; } void write_file_if_different(const path &p, const String &s) { if (fs::exists(p)) { auto s2 = read_file(p, true); if (s == s2) return; } write_file(p, s); } void copy_dir(const path &src, const path &dst) { boost::system::error_code ec; fs::create_directories(dst, ec); for (auto &f : boost::make_iterator_range(fs::directory_iterator(src), {})) { if (fs::is_directory(f)) copy_dir(f, dst / f.path().filename()); else fs::copy_file(f, dst / f.path().filename(), fs::copy_option::overwrite_if_exists); } } void remove_files(const Files &files) { for (auto &f : files) fs::remove(f); } void remove_files_like(const Files &files, const String &regex) { remove_files(filter_files_like(files, regex)); } void remove_files_like(const path &dir, const String &regex, bool recursive) { remove_files_like(enumerate_files(dir, recursive), regex); } Files enumerate_files(const path &dir, bool recursive) { Files files; if (!fs::exists(dir)) return files; if (recursive) { for (auto &f : boost::make_iterator_range(fs::recursive_directory_iterator(dir), {})) { if (!fs::is_regular_file(f)) continue; files.insert(f); } } else { for (auto &f : boost::make_iterator_range(fs::directory_iterator(dir), {})) { if (!fs::is_regular_file(f)) continue; files.insert(f); } } return files; } Files enumerate_files_like(const path &dir, const String &regex, bool recursive) { return filter_files_like(enumerate_files(dir, recursive), regex); } Files enumerate_files_like(const Files &files, const String &regex) { return filter_files_like(files, regex); } Files filter_files_like(const Files &files, const String &regex) { Files fls; std::regex r(regex); for (auto &f : files) { if (!std::regex_match(f.filename().string(), r)) continue; fls.insert(f); } return fls; } bool is_under_root(path p, const path &root_dir) { if (p.empty()) return false; if (fs::exists(p)) // Converts p, which must exist, to an absolute path // that has no symbolic link, dot, or dot-dot elements. p = fs::canonical(p); while (!p.empty()) { if (p == root_dir) return true; p = p.parent_path(); } return false; } bool compare_files(const path &fn1, const path &fn2) { FileIterator fi({ fn1, fn2 }); return fi.iterate([](const auto &bufs, auto sz) { if (memcmp(bufs[0].get().data(), bufs[1].get().data(), (size_t)sz) != 0) return false; return true; }); } bool compare_dirs(const path &dir1, const path &dir2) { auto traverse_dir = [](const auto &dir) { std::vector<path> files; if (fs::exists(dir)) for (auto &f : boost::make_iterator_range(fs::recursive_directory_iterator(dir), {})) { if (!fs::is_regular_file(f)) continue; files.push_back(f); } return files; }; auto files1 = traverse_dir(dir1); auto files2 = traverse_dir(dir2); if (files1.empty()) return false; // throw std::runtime_error("left side has no files"); if (files2.empty()) return false; // throw std::runtime_error("right side has no files"); if (files1.size() != files2.size()) return false; // throw std::runtime_error("different number of files"); auto sz = files1.size(); for (size_t i = 0; i < sz; i++) { if (!compare_files(files1[i], files2[i])) return false; } return true; } FileIterator::FileIterator(const std::vector<path> &fns) { if (fns.empty()) throw std::runtime_error("Provide at least one file"); for (auto &f : fns) { File d; d.size = fs::file_size(f); d.ifile = std::make_unique<boost::nowide::ifstream>(f.string(), std::ifstream::binary); files.push_back(std::move(d)); } } bool FileIterator::is_same_size() const { auto sz = files.front().size; return std::all_of(files.begin(), files.end(), [sz](const auto &f) { return f.size == sz; }); } bool FileIterator::is_same_read_size() const { auto sz = files.front().read; return std::all_of(files.begin(), files.end(), [sz](const auto &f) { return f.read == sz; }); } bool FileIterator::iterate(std::function<bool(const BuffersRef &, uint64_t)> f) { if (!is_same_size()) return false; BuffersRef buffers; for (auto &f : files) { f.buf.resize(buffer_size); buffers.emplace_back(f.buf); } while (std::none_of(files.begin(), files.end(), [](const auto &f) { return f.ifile->eof(); })) { std::for_each(files.begin(), files.end(), [this](auto &f) { f.ifile->read((char *)&f.buf[0], buffer_size); f.read = f.ifile->gcount(); }); if (!is_same_read_size()) return false; if (!f(buffers, files.front().read)) return false; } return true; } void setup_utf8_filesystem() { boost::nowide::nowide_filesystem(); }
Resolve path elements better.
Resolve path elements better.
C++
mpl-2.0
egorpugin/primitives,egorpugin/primitives
d500576679cf1ee8b0ec43cfa460f6008594ae65
folly/test/SmallLocksTest.cpp
folly/test/SmallLocksTest.cpp
/* * Copyright 2017 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/SmallLocks.h> #include <cassert> #include <condition_variable> #include <cstdio> #include <mutex> #include <string> #include <thread> #include <vector> #include <folly/Random.h> #include <folly/portability/Asm.h> #include <folly/portability/GTest.h> #include <folly/portability/PThread.h> #include <folly/portability/Unistd.h> using folly::MSLGuard; using folly::MicroLock; using folly::MicroSpinLock; using std::string; #ifdef FOLLY_PICO_SPIN_LOCK_H_ using folly::PicoSpinLock; #endif namespace { struct LockedVal { int ar[1024]; MicroSpinLock lock; LockedVal() { lock.init(); memset(ar, 0, sizeof ar); } }; // Compile time test for packed struct support (requires that both of // these classes are POD). FOLLY_PACK_PUSH struct ignore1 { MicroSpinLock msl; int16_t foo; } FOLLY_PACK_ATTR; static_assert(sizeof(ignore1) == 3, "Size check failed"); static_assert(sizeof(MicroSpinLock) == 1, "Size check failed"); #ifdef FOLLY_PICO_SPIN_LOCK_H_ struct ignore2 { PicoSpinLock<uint32_t> psl; int16_t foo; } FOLLY_PACK_ATTR; static_assert(sizeof(ignore2) == 6, "Size check failed"); #endif FOLLY_PACK_POP LockedVal v; void splock_test() { const int max = 1000; auto rng = folly::ThreadLocalPRNG(); for (int i = 0; i < max; i++) { folly::asm_volatile_pause(); MSLGuard g(v.lock); int first = v.ar[0]; for (size_t j = 1; j < sizeof v.ar / sizeof j; ++j) { EXPECT_EQ(first, v.ar[j]); } int byte = folly::Random::rand32(rng); memset(v.ar, char(byte), sizeof v.ar); } } #ifdef FOLLY_PICO_SPIN_LOCK_H_ template <class T> struct PslTest { PicoSpinLock<T> lock; PslTest() { lock.init(); } void doTest() { using UT = typename std::make_unsigned<T>::type; T ourVal = rand() % T(UT(1) << (sizeof(UT) * 8 - 1)); for (int i = 0; i < 100; ++i) { std::lock_guard<PicoSpinLock<T>> guard(lock); lock.setData(ourVal); for (int n = 0; n < 10; ++n) { folly::asm_volatile_pause(); EXPECT_EQ(lock.getData(), ourVal); } } } }; template <class T> void doPslTest() { PslTest<T> testObj; const int nthrs = 17; std::vector<std::thread> threads; for (int i = 0; i < nthrs; ++i) { threads.push_back(std::thread(&PslTest<T>::doTest, &testObj)); } for (auto& t : threads) { t.join(); } } #endif struct TestClobber { TestClobber() { lock_.init(); } void go() { std::lock_guard<MicroSpinLock> g(lock_); // This bug depends on gcc register allocation and is very sensitive. We // have to use DCHECK instead of EXPECT_*. DCHECK(!lock_.try_lock()); } private: MicroSpinLock lock_; }; } TEST(SmallLocks, SpinLockCorrectness) { EXPECT_EQ(sizeof(MicroSpinLock), 1); int nthrs = sysconf(_SC_NPROCESSORS_ONLN) * 2; std::vector<std::thread> threads; for (int i = 0; i < nthrs; ++i) { threads.push_back(std::thread(splock_test)); } for (auto& t : threads) { t.join(); } } #ifdef FOLLY_PICO_SPIN_LOCK_H_ TEST(SmallLocks, PicoSpinCorrectness) { doPslTest<int16_t>(); doPslTest<uint16_t>(); doPslTest<int32_t>(); doPslTest<uint32_t>(); doPslTest<int64_t>(); doPslTest<uint64_t>(); } TEST(SmallLocks, PicoSpinSigned) { typedef PicoSpinLock<int16_t,0> Lock; Lock val; val.init(-4); EXPECT_EQ(val.getData(), -4); { std::lock_guard<Lock> guard(val); EXPECT_EQ(val.getData(), -4); val.setData(-8); EXPECT_EQ(val.getData(), -8); } EXPECT_EQ(val.getData(), -8); } #endif TEST(SmallLocks, RegClobber) { TestClobber().go(); } FOLLY_PACK_PUSH #if defined(__SANITIZE_ADDRESS__) && !defined(__clang__) && \ (defined(__GNUC__) || defined(__GNUG__)) static_assert(sizeof(MicroLock) == 4, "Size check failed"); #else static_assert(sizeof(MicroLock) == 1, "Size check failed"); #endif FOLLY_PACK_POP namespace { struct SimpleBarrier { SimpleBarrier() : lock_(), cv_(), ready_(false) {} void wait() { std::unique_lock<std::mutex> lockHeld(lock_); while (!ready_) { cv_.wait(lockHeld); } } void run() { { std::unique_lock<std::mutex> lockHeld(lock_); ready_ = true; } cv_.notify_all(); } private: std::mutex lock_; std::condition_variable cv_; bool ready_; }; } TEST(SmallLocks, MicroLock) { volatile uint64_t counters[4] = {0, 0, 0, 0}; std::vector<std::thread> threads; static const unsigned nrThreads = 20; static const unsigned iterPerThread = 10000; SimpleBarrier startBarrier; assert(iterPerThread % 4 == 0); // Embed the lock in a larger structure to ensure that we do not // affect bits outside the ones MicroLock is defined to affect. struct { uint8_t a; std::atomic<uint8_t> b; MicroLock alock; std::atomic<uint8_t> d; } x; uint8_t origB = 'b'; uint8_t origD = 'd'; x.a = 'a'; x.b = origB; x.alock.init(); x.d = origD; // This thread touches other parts of the host word to show that // MicroLock does not interfere with memory outside of the byte // it owns. std::thread adjacentMemoryToucher = std::thread([&] { startBarrier.wait(); for (unsigned iter = 0; iter < iterPerThread; ++iter) { if (iter % 2) { x.b++; } else { x.d++; } } }); for (unsigned i = 0; i < nrThreads; ++i) { threads.emplace_back([&] { startBarrier.wait(); for (unsigned iter = 0; iter < iterPerThread; ++iter) { unsigned slotNo = iter % 4; x.alock.lock(slotNo); counters[slotNo] += 1; // The occasional sleep makes it more likely that we'll // exercise the futex-wait path inside MicroLock. if (iter % 1000 == 0) { struct timespec ts = {0, 10000}; (void)nanosleep(&ts, nullptr); } x.alock.unlock(slotNo); } }); } startBarrier.run(); for (auto it = threads.begin(); it != threads.end(); ++it) { it->join(); } adjacentMemoryToucher.join(); EXPECT_EQ(x.a, 'a'); EXPECT_EQ(x.b, (uint8_t)(origB + iterPerThread / 2)); EXPECT_EQ(x.d, (uint8_t)(origD + iterPerThread / 2)); for (unsigned i = 0; i < 4; ++i) { EXPECT_EQ(counters[i], ((uint64_t)nrThreads * iterPerThread) / 4); } } TEST(SmallLocks, MicroLockTryLock) { MicroLock lock; lock.init(); EXPECT_TRUE(lock.try_lock()); EXPECT_FALSE(lock.try_lock()); lock.unlock(); }
/* * Copyright 2017 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/SmallLocks.h> #include <cassert> #include <condition_variable> #include <cstdio> #include <mutex> #include <string> #include <thread> #include <vector> #include <glog/logging.h> #include <folly/Random.h> #include <folly/portability/Asm.h> #include <folly/portability/GTest.h> #include <folly/portability/PThread.h> #include <folly/portability/Unistd.h> using folly::MSLGuard; using folly::MicroLock; using folly::MicroSpinLock; using std::string; #ifdef FOLLY_PICO_SPIN_LOCK_H_ using folly::PicoSpinLock; #endif namespace { struct LockedVal { int ar[1024]; MicroSpinLock lock; LockedVal() { lock.init(); memset(ar, 0, sizeof ar); } }; // Compile time test for packed struct support (requires that both of // these classes are POD). FOLLY_PACK_PUSH struct ignore1 { MicroSpinLock msl; int16_t foo; } FOLLY_PACK_ATTR; static_assert(sizeof(ignore1) == 3, "Size check failed"); static_assert(sizeof(MicroSpinLock) == 1, "Size check failed"); #ifdef FOLLY_PICO_SPIN_LOCK_H_ struct ignore2 { PicoSpinLock<uint32_t> psl; int16_t foo; } FOLLY_PACK_ATTR; static_assert(sizeof(ignore2) == 6, "Size check failed"); #endif FOLLY_PACK_POP LockedVal v; void splock_test() { const int max = 1000; auto rng = folly::ThreadLocalPRNG(); for (int i = 0; i < max; i++) { folly::asm_volatile_pause(); MSLGuard g(v.lock); int first = v.ar[0]; for (size_t j = 1; j < sizeof v.ar / sizeof j; ++j) { EXPECT_EQ(first, v.ar[j]); } int byte = folly::Random::rand32(rng); memset(v.ar, char(byte), sizeof v.ar); } } #ifdef FOLLY_PICO_SPIN_LOCK_H_ template <class T> struct PslTest { PicoSpinLock<T> lock; PslTest() { lock.init(); } void doTest() { using UT = typename std::make_unsigned<T>::type; T ourVal = rand() % T(UT(1) << (sizeof(UT) * 8 - 1)); for (int i = 0; i < 100; ++i) { std::lock_guard<PicoSpinLock<T>> guard(lock); lock.setData(ourVal); for (int n = 0; n < 10; ++n) { folly::asm_volatile_pause(); EXPECT_EQ(lock.getData(), ourVal); } } } }; template <class T> void doPslTest() { PslTest<T> testObj; const int nthrs = 17; std::vector<std::thread> threads; for (int i = 0; i < nthrs; ++i) { threads.push_back(std::thread(&PslTest<T>::doTest, &testObj)); } for (auto& t : threads) { t.join(); } } #endif struct TestClobber { TestClobber() { lock_.init(); } void go() { std::lock_guard<MicroSpinLock> g(lock_); // This bug depends on gcc register allocation and is very sensitive. We // have to use DCHECK instead of EXPECT_*. DCHECK(!lock_.try_lock()); } private: MicroSpinLock lock_; }; } TEST(SmallLocks, SpinLockCorrectness) { EXPECT_EQ(sizeof(MicroSpinLock), 1); int nthrs = sysconf(_SC_NPROCESSORS_ONLN) * 2; std::vector<std::thread> threads; for (int i = 0; i < nthrs; ++i) { threads.push_back(std::thread(splock_test)); } for (auto& t : threads) { t.join(); } } #ifdef FOLLY_PICO_SPIN_LOCK_H_ TEST(SmallLocks, PicoSpinCorrectness) { doPslTest<int16_t>(); doPslTest<uint16_t>(); doPslTest<int32_t>(); doPslTest<uint32_t>(); doPslTest<int64_t>(); doPslTest<uint64_t>(); } TEST(SmallLocks, PicoSpinSigned) { typedef PicoSpinLock<int16_t,0> Lock; Lock val; val.init(-4); EXPECT_EQ(val.getData(), -4); { std::lock_guard<Lock> guard(val); EXPECT_EQ(val.getData(), -4); val.setData(-8); EXPECT_EQ(val.getData(), -8); } EXPECT_EQ(val.getData(), -8); } #endif TEST(SmallLocks, RegClobber) { TestClobber().go(); } FOLLY_PACK_PUSH #if defined(__SANITIZE_ADDRESS__) && !defined(__clang__) && \ (defined(__GNUC__) || defined(__GNUG__)) static_assert(sizeof(MicroLock) == 4, "Size check failed"); #else static_assert(sizeof(MicroLock) == 1, "Size check failed"); #endif FOLLY_PACK_POP namespace { struct SimpleBarrier { SimpleBarrier() : lock_(), cv_(), ready_(false) {} void wait() { std::unique_lock<std::mutex> lockHeld(lock_); while (!ready_) { cv_.wait(lockHeld); } } void run() { { std::unique_lock<std::mutex> lockHeld(lock_); ready_ = true; } cv_.notify_all(); } private: std::mutex lock_; std::condition_variable cv_; bool ready_; }; } TEST(SmallLocks, MicroLock) { volatile uint64_t counters[4] = {0, 0, 0, 0}; std::vector<std::thread> threads; static const unsigned nrThreads = 20; static const unsigned iterPerThread = 10000; SimpleBarrier startBarrier; assert(iterPerThread % 4 == 0); // Embed the lock in a larger structure to ensure that we do not // affect bits outside the ones MicroLock is defined to affect. struct { uint8_t a; std::atomic<uint8_t> b; MicroLock alock; std::atomic<uint8_t> d; } x; uint8_t origB = 'b'; uint8_t origD = 'd'; x.a = 'a'; x.b = origB; x.alock.init(); x.d = origD; // This thread touches other parts of the host word to show that // MicroLock does not interfere with memory outside of the byte // it owns. std::thread adjacentMemoryToucher = std::thread([&] { startBarrier.wait(); for (unsigned iter = 0; iter < iterPerThread; ++iter) { if (iter % 2) { x.b++; } else { x.d++; } } }); for (unsigned i = 0; i < nrThreads; ++i) { threads.emplace_back([&] { startBarrier.wait(); for (unsigned iter = 0; iter < iterPerThread; ++iter) { unsigned slotNo = iter % 4; x.alock.lock(slotNo); counters[slotNo] += 1; // The occasional sleep makes it more likely that we'll // exercise the futex-wait path inside MicroLock. if (iter % 1000 == 0) { struct timespec ts = {0, 10000}; (void)nanosleep(&ts, nullptr); } x.alock.unlock(slotNo); } }); } startBarrier.run(); for (auto it = threads.begin(); it != threads.end(); ++it) { it->join(); } adjacentMemoryToucher.join(); EXPECT_EQ(x.a, 'a'); EXPECT_EQ(x.b, (uint8_t)(origB + iterPerThread / 2)); EXPECT_EQ(x.d, (uint8_t)(origD + iterPerThread / 2)); for (unsigned i = 0; i < 4; ++i) { EXPECT_EQ(counters[i], ((uint64_t)nrThreads * iterPerThread) / 4); } } TEST(SmallLocks, MicroLockTryLock) { MicroLock lock; lock.init(); EXPECT_TRUE(lock.try_lock()); EXPECT_FALSE(lock.try_lock()); lock.unlock(); }
Include glog/logging.h in SmallLocksTest for DCHECK
Include glog/logging.h in SmallLocksTest for DCHECK Summary: The test uses DCHECK, but does not include glog/logging.h. Reviewed By: yfeldblum Differential Revision: D5818647 fbshipit-source-id: fcb2630ac2b12acd1a7b84e228349b2887e976cd
C++
apache-2.0
facebook/folly,Orvid/folly,Orvid/folly,rklabs/folly,rklabs/folly,Orvid/folly,facebook/folly,rklabs/folly,facebook/folly,facebook/folly,rklabs/folly,Orvid/folly,rklabs/folly,Orvid/folly,facebook/folly
e7057ec5e112713c7ef91b5c7291bb85793de491
utils/geom.cc
utils/geom.cc
#include "geom.hpp" #include "utils.hpp" #include <algorithm> #include <cstdarg> static void xsortedpts(std::vector<Point>&, double, double, double); static bool cmpx(const Point&, const Point&); void Bbox::draw(Image &img, Color c, double lwidth) const { Image::Path *p = new Image::Path(); p->setlinewidth(lwidth < 0 ? 0.1 : lwidth); p->setcolor(c); p->moveto(min.x, min.y); p->lineto(min.x, max.y); p->lineto(max.x, max.y); p->lineto(max.x, min.y); p->closepath(); img.add(p); } Polygon::Polygon(unsigned int n, ...) { va_list ap; va_start(ap, n); for (unsigned int i = 0; i < n; i++) { double x = va_arg(ap, double); double y = va_arg(ap, double); verts.push_back(Point(x, y)); } va_end(ap); bbox = Bbox(verts); initsides(verts); } bool Polygon::contains(const Point &p) const { bool even = true, isect = false; LineSeg ray(p, Point(p.x + 1, p.y)); for (unsigned int i = 0; i < sides.size(); i++) { Point hit = ray.isect(sides[i]); if (hit.x > p.x && sides[i].contains(hit)) { isect = true; even = !even; } } return isect && !even; } static bool isisect(const Point &p) { return !std::isinf(p.x) && !std::isnan(p.x) && !std::isinf(p.y) && !std::isnan(p.y); } void Polygon::isects(const LineSeg &l, std::vector<Point> &is) const { is.clear(); for (unsigned int i = 0; i < sides.size(); i++) { Point p = l.isect(sides[i]); if (isisect(p)) is.push_back(p); } } Point Polygon::minisect(const LineSeg &l) const { Point min = Point::inf(); double mindist = std::numeric_limits<double>::infinity(); for (unsigned int i = 0; i < sides.size(); i++) { Point p = l.isect(sides[i]); double d = Point::distance(p, l.p0); if (isisect(p) && d < mindist) { mindist = d; min = p; } } return min; } bool Polygon::hits(const LineSeg &l) const { for (unsigned int i = 0; i < sides.size(); i++) { Point p = l.isect(sides[i]); if (isisect(p)) return true; } return false; } void Polygon::draw(Image &img, Color c, double lwidth) const { Image::Path *p = new Image::Path(); p->setlinewidth(lwidth < 0 ? 0.1 : lwidth); p->setcolor(c); p->moveto(verts[0].x, verts[0].y); for (unsigned int i = 1; i < verts.size(); i++) p->lineto(verts[i].x, verts[i].y); p->closepath(); if (lwidth < 0) p->fill(); img.add(p); } void Polygon::initsides(std::vector<Point> &pts) { sides.clear(); for (unsigned int i = 1; i < pts.size(); i++) sides.push_back(LineSeg(pts[i-1], pts[i])); sides.push_back(LineSeg(pts[pts.size() - 1], pts[0])); } Polygon Polygon::random(unsigned int n, double xc, double yc, double r) { if (n < 3) fatal("A polygon needs at least 3 points\n"); std::vector<Point> pts(n); xsortedpts(pts, xc, yc, r); Line l(pts[0], pts[pts.size()-1]); std::vector<Point> verts, rev; verts.push_back(pts[0]); for (unsigned int i = 1; i < pts.size() - 1; i++) { if (l.isabove(pts[i])) verts.push_back(pts[i]); else rev.push_back(pts[i]); } verts.push_back(pts[pts.size()-1]); for (unsigned int i = 0; i < rev.size(); i++) verts.push_back(rev[i]); return Polygon(verts); } void Polygon::reflexes(std::vector<unsigned int> &rs) const { rs.clear(); for (unsigned int i = 0; i < verts.size(); i++) { const Point &u = i == 0 ? verts[verts.size() - 1] : verts[i-1]; const Point &v = verts[i]; const Point &w = i == verts.size() - 1 ? verts[0] : verts[i+1]; Point a = v.minus(u), b = w.minus(v); // interior angle via some voodoo from the internet. double t = M_PI - fmod(atan2(b.x*a.y - a.x*b.y, b.x*a.x + b.y*a.y), 2 * M_PI); if (t < 180) rs.push_back(i); } } void Polygon::output(FILE *out) const { fprintf(out, "%lu vertices\n", (unsigned long) verts.size()); for (unsigned int i = 0; i < verts.size(); i++) fprintf(out, " %g %g\n", verts[i].x, verts[i].y); } static void xsortedpts(std::vector<Point> &pts, double xc, double yc, double r) { for (unsigned int i = 0; i < pts.size(); i++) { double x = (2 * r * randgen.real()) - r; double y = (2 * r * randgen.real()) - r; pts[i] = Point(x + xc, y + yc); } std::sort(pts.begin(), pts.end(), cmpx); } static bool cmpx(const Point &a, const Point &b) { return a.x < b.x; }
#include "geom.hpp" #include "utils.hpp" #include <algorithm> #include <cstdarg> static void xsortedpts(std::vector<Point>&, double, double, double); static bool cmpx(const Point&, const Point&); void Bbox::draw(Image &img, Color c, double lwidth) const { Image::Path *p = new Image::Path(); p->setlinewidth(lwidth < 0 ? 0.1 : lwidth); p->setcolor(c); p->moveto(min.x, min.y); p->lineto(min.x, max.y); p->lineto(max.x, max.y); p->lineto(max.x, min.y); p->closepath(); img.add(p); } Polygon::Polygon(unsigned int n, ...) { va_list ap; va_start(ap, n); for (unsigned int i = 0; i < n; i++) { double x = va_arg(ap, double); double y = va_arg(ap, double); verts.push_back(Point(x, y)); } va_end(ap); bbox = Bbox(verts); initsides(verts); } bool Polygon::contains(const Point &p) const { bool even = true, isect = false; LineSeg ray(p, Point(p.x + 1, p.y)); for (unsigned int i = 0; i < sides.size(); i++) { Point hit = ray.isect(sides[i]); if (hit.x > p.x && sides[i].contains(hit)) { isect = true; even = !even; } } return isect && !even; } static bool isisect(const Point &p) { return !std::isinf(p.x) && !std::isnan(p.x) && !std::isinf(p.y) && !std::isnan(p.y); } void Polygon::isects(const LineSeg &l, std::vector<Point> &is) const { is.clear(); for (unsigned int i = 0; i < sides.size(); i++) { Point p = l.isect(sides[i]); if (isisect(p)) is.push_back(p); } } Point Polygon::minisect(const LineSeg &l) const { Point min = Point::inf(); double mindist = std::numeric_limits<double>::infinity(); for (unsigned int i = 0; i < sides.size(); i++) { Point p = l.isect(sides[i]); double d = Point::distance(p, l.p0); if (isisect(p) && d < mindist) { mindist = d; min = p; } } return min; } bool Polygon::hits(const LineSeg &l) const { for (unsigned int i = 0; i < sides.size(); i++) { Point p = l.isect(sides[i]); if (isisect(p)) return true; } return false; } void Polygon::draw(Image &img, Color c, double lwidth) const { Image::Path *p = new Image::Path(); p->setlinewidth(lwidth < 0 ? 0.1 : lwidth); p->setcolor(c); p->moveto(verts[0].x, verts[0].y); for (unsigned int i = 1; i < verts.size(); i++) p->lineto(verts[i].x, verts[i].y); p->closepath(); if (lwidth < 0) p->fill(); img.add(p); } void Polygon::initsides(std::vector<Point> &pts) { sides.clear(); for (unsigned int i = 1; i < pts.size(); i++) sides.push_back(LineSeg(pts[i-1], pts[i])); sides.push_back(LineSeg(pts[pts.size() - 1], pts[0])); } Polygon Polygon::random(unsigned int n, double xc, double yc, double r) { if (n < 3) fatal("A polygon needs at least 3 points\n"); std::vector<Point> pts(n); xsortedpts(pts, xc, yc, r); Line l(pts[0], pts[pts.size()-1]); std::vector<Point> verts, rev; verts.push_back(pts[0]); for (unsigned int i = 1; i < pts.size() - 1; i++) { if (l.isabove(pts[i])) verts.push_back(pts[i]); else rev.push_back(pts[i]); } verts.push_back(pts[pts.size()-1]); for (unsigned int i = 0; i < rev.size(); i++) verts.push_back(rev[i]); return Polygon(verts); } void Polygon::reflexes(std::vector<unsigned int> &rs) const { rs.clear(); for (unsigned int i = 0; i < verts.size(); i++) { const Point &u = i == 0 ? verts[verts.size() - 1] : verts[i-1]; const Point &v = verts[i]; const Point &w = i == verts.size() - 1 ? verts[0] : verts[i+1]; Point a = v.minus(u), b = w.minus(v); // interior angle via some voodoo from the internet. double t = M_PI - fmod(atan2(b.x*a.y - a.x*b.y, b.x*a.x + b.y*a.y), 2 * M_PI); if (t < M_PI) rs.push_back(i); } } void Polygon::output(FILE *out) const { fprintf(out, "%lu vertices\n", (unsigned long) verts.size()); for (unsigned int i = 0; i < verts.size(); i++) fprintf(out, " %g %g\n", verts[i].x, verts[i].y); } static void xsortedpts(std::vector<Point> &pts, double xc, double yc, double r) { for (unsigned int i = 0; i < pts.size(); i++) { double x = (2 * r * randgen.real()) - r; double y = (2 * r * randgen.real()) - r; pts[i] = Point(x + xc, y + yc); } std::sort(pts.begin(), pts.end(), cmpx); } static bool cmpx(const Point &a, const Point &b) { return a.x < b.x; }
Use radians when computing reflexes.
Use radians when computing reflexes.
C++
mit
eaburns/search,eaburns/search,eaburns/search,skiesel/search,skiesel/search,skiesel/search
0b767ee0dae926cb6718cc85ede3d5bad193bbc4
neighborsMinHash/computation/bloomierFilter/bloomierHash.cpp
neighborsMinHash/computation/bloomierFilter/bloomierHash.cpp
#include "bloomierHash.h" #include <set> #include <bitset> BloomierHash::BloomierHash(const size_t pModulo, const size_t pNumberOfElements, const size_t pBitVectorSize, const size_t pHashSeed) { mModulo = pModulo; mNumberOfElements = pNumberOfElements; // mQ = pQ; mHash = new Hash(); mBitVectorSize = pBitVectorSize; mHashSeed = pHashSeed; }; BloomierHash::~BloomierHash() { }; bitVector* BloomierHash::getMask(const size_t pKey) { bitVector* mask = new bitVector(mBitVectorSize); srand(mHashSeed*pKey); size_t randValue = rand(); for (size_t i = 0; i < mBitVectorSize; ++i) { (*mask)[i] = static_cast<unsigned char>((randValue >> (8*i))& 0b00000000000000000000000011111111); } return mask; }; void BloomierHash::getKNeighbors(const size_t pElement, const size_t pSeed, vsize_t* pNeighbors) { size_t seedValue = pSeed; if (seedValue == 0) { seedValue = mHashSeed; } size_t seedChange = 1; bitVector* bloomFilterValueSeen = new bitVector(ceil(mModulo/8.0)); for (size_t i = 0; i < pNeighbors->size(); ++i) { size_t neighbor = mHash->hash(pElement+i, seedValue+seedChange, mModulo); unsigned char index = floor(neighbor / 8.0); unsigned char value = 1 << (neighbor % 8); unsigned char valueSeen = (*bloomFilterValueSeen)[index] & value; while (value == valueSeen) { ++seedChange; neighbor = mHash->hash(pElement+1, (seedValue+seedChange)*(seedValue+seedChange), mModulo); index = floor(neighbor / 8.0); value = 1 << (neighbor % 8); valueSeen = (*bloomFilterValueSeen)[index] & value; } (*bloomFilterValueSeen)[index] = (*bloomFilterValueSeen)[index] | value; seedChange = 1; (*pNeighbors)[i] = neighbor; // ++pElement; } delete bloomFilterValueSeen; }; size_t BloomierHash::getHashSeed() const { return mHashSeed; }; void BloomierHash::setHashSeed(size_t pHashSeed) { mHashSeed = pHashSeed; }
#include "bloomierHash.h" #include <set> #include <bitset> BloomierHash::BloomierHash(const size_t pModulo, const size_t pNumberOfElements, const size_t pBitVectorSize, const size_t pHashSeed) { mModulo = pModulo; mNumberOfElements = pNumberOfElements; mHash = new Hash(); mBitVectorSize = pBitVectorSize; mHashSeed = pHashSeed; }; BloomierHash::~BloomierHash() { }; bitVector* BloomierHash::getMask(const size_t pKey) { bitVector* mask = new bitVector(mBitVectorSize); size_t randValue = mHash->hash(pKey+1, mHashSeed, mModulo); for (size_t i = 0; i < mBitVectorSize; ++i) { (*mask)[i] = static_cast<unsigned char>((randValue >> (8*i))& 0b00000000000000000000000011111111); } return mask; }; void BloomierHash::getKNeighbors(const size_t pElement, const size_t pSeed, vsize_t* pNeighbors) { size_t seedValue = pSeed; if (seedValue == 0) { seedValue = mHashSeed; } size_t seedChange = 1; bitVector* bloomFilterValueSeen = new bitVector(ceil(mModulo/8.0)); for (size_t i = 0; i < pNeighbors->size(); ++i) { size_t neighbor = mHash->hash(pElement+i, seedValue+seedChange, mModulo); unsigned char index = floor(neighbor / 8.0); unsigned char value = 1 << (neighbor % 8); unsigned char valueSeen = (*bloomFilterValueSeen)[index] & value; while (value == valueSeen) { ++seedChange; neighbor = mHash->hash(pElement+1, (seedValue+seedChange)*(seedValue+seedChange), mModulo); index = floor(neighbor / 8.0); value = 1 << (neighbor % 8); valueSeen = (*bloomFilterValueSeen)[index] & value; } (*bloomFilterValueSeen)[index] = (*bloomFilterValueSeen)[index] | value; seedChange = 1; (*pNeighbors)[i] = neighbor; // ++pElement; } delete bloomFilterValueSeen; }; size_t BloomierHash::getHashSeed() const { return mHashSeed; }; void BloomierHash::setHashSeed(size_t pHashSeed) { mHashSeed = pHashSeed; }
replace rand and srand with hash function from hash.h
replace rand and srand with hash function from hash.h
C++
mit
joachimwolff/minHashNearestNeighbors,joachimwolff/minHashNearestNeighbors,joachimwolff/minHashNearestNeighbors
406666f202023b5cc39dcb1319ea1f7d021ac3ff
src/cvm/dab_value.cpp
src/cvm/dab_value.cpp
#include "cvm.h" void DabValue::dump(DabVM &vm) const { static const char *kinds[] = {"INVAL", "PrvIP", "PrvSP", "nArgs", "nVars", "RETVL", "CONST", "VARIA", "STACK", "self "}; static const char *types[] = {"INVA", "FIXN", "STRI", "BOOL", "NIL ", "SYMB", "CLAS", "OBJE"}; fprintf(stderr, "%s %s ", kinds[data.kind], types[data.type]); print(vm, stderr, true); } int DabValue::class_index() const { switch (data.type) { case TYPE_FIXNUM: return data.is_constant ? CLASS_LITERALFIXNUM : CLASS_FIXNUM; break; case TYPE_STRING: return data.is_constant ? CLASS_LITERALSTRING : CLASS_STRING; break; case TYPE_SYMBOL: return CLASS_INT_SYMBOL; break; case TYPE_BOOLEAN: return CLASS_BOOLEAN; break; case TYPE_NIL: return CLASS_NILCLASS; break; case TYPE_CLASS: return data.fixnum; break; case TYPE_OBJECT: return this->data.object->object->klass; break; default: assert(false); break; } } std::string DabValue::class_name(DabVM &vm) const { return get_class(vm).name; } DabClass &DabValue::get_class(DabVM &vm) const { return vm.get_class(class_index()); } void DabValue::print(DabVM &vm, FILE *out, bool debug) const { switch (data.type) { case TYPE_FIXNUM: fprintf(out, "%zd", data.fixnum); break; case TYPE_STRING: fprintf(out, debug ? "\"%s\"" : "%s", data.string.c_str()); break; case TYPE_SYMBOL: fprintf(out, ":%s", data.string.c_str()); break; case TYPE_BOOLEAN: fprintf(out, "%s", data.boolean ? "true" : "false"); break; case TYPE_NIL: fprintf(out, "nil"); break; case TYPE_CLASS: fprintf(out, "%s", class_name(vm).c_str()); break; case TYPE_OBJECT: fprintf(out, "#%s", class_name(vm).c_str()); break; default: fprintf(out, "?"); break; } } bool DabValue::truthy() const { switch (data.type) { case TYPE_FIXNUM: return data.fixnum; case TYPE_STRING: return data.string.length(); break; case TYPE_BOOLEAN: return data.boolean; break; case TYPE_NIL: return false; break; default: return true; break; } } DabValue DabValue::create_instance() const { assert(data.type == TYPE_CLASS); DabObjectProxy *proxy = new DabObjectProxy; proxy->object = new DabObject; proxy->count_strong = 1; proxy->object->klass = this->data.fixnum; DabValue ret; ret.data.type = TYPE_OBJECT; ret.data.object = proxy; return ret; } DabValue DabValue::_get_instvar(DabVM &vm, const std::string &name) { assert(this->data.type == TYPE_OBJECT); assert(this->data.object); if (!this->data.object->object) { return DabValue(nullptr); } auto &instvars = this->data.object->object->instvars; if (!instvars.count(name)) { return DabValue(nullptr); } return instvars[name]; } DabValue DabValue::get_instvar(DabVM &vm, const std::string &name) { auto ret = _get_instvar(vm, name); fprintf(stderr, "VM: proxy %p (strong %d): Get instvar <%s> -> ", this->data.object, (int)this->data.object->count_strong, name.c_str()); ret.print(vm, stderr); fprintf(stderr, "\n"); return ret; } void DabValue::set_instvar(DabVM &vm, const std::string &name, const DabValue &value) { assert(this->data.type == TYPE_OBJECT); assert(this->data.object); fprintf(stderr, "VM: proxy %p (strong %d): Set instvar <%s> to ", this->data.object, (int)this->data.object->count_strong, name.c_str()); value.print(vm, stderr); fprintf(stderr, "\n"); if (!this->data.object->object) { return; } auto &instvars = this->data.object->object->instvars; instvars[name] = value; } void DabValue::set_data(const DabValueData &other_data) { data = other_data; if (data.type == TYPE_OBJECT) { data.object->retain(); } } DabValue::DabValue(const DabValue &other) { set_data(other.data); } DabValue &DabValue::operator=(const DabValue &other) { set_data(other.data); return *this; } DabValue::~DabValue() { if (this->data.type == TYPE_OBJECT) { this->data.object->release(); } } // void DabObjectProxy::retain() { count_strong += 1; } void DabObjectProxy::release() { count_strong -= 1; if (count_strong == 0) { delete object; delete this; } }
#include "cvm.h" void DabValue::dump(DabVM &vm) const { static const char *kinds[] = {"INVAL", "PrvIP", "PrvSP", "nArgs", "nVars", "RETVL", "CONST", "VARIA", "STACK", "self "}; static const char *types[] = {"INVA", "FIXN", "STRI", "BOOL", "NIL ", "SYMB", "CLAS", "OBJE"}; fprintf(stderr, "%s %s ", kinds[data.kind], types[data.type]); print(vm, stderr, true); } int DabValue::class_index() const { switch (data.type) { case TYPE_FIXNUM: return data.is_constant ? CLASS_LITERALFIXNUM : CLASS_FIXNUM; break; case TYPE_STRING: return data.is_constant ? CLASS_LITERALSTRING : CLASS_STRING; break; case TYPE_SYMBOL: return CLASS_INT_SYMBOL; break; case TYPE_BOOLEAN: return CLASS_BOOLEAN; break; case TYPE_NIL: return CLASS_NILCLASS; break; case TYPE_CLASS: return data.fixnum; break; case TYPE_OBJECT: return this->data.object->object->klass; break; default: assert(false); break; } } std::string DabValue::class_name(DabVM &vm) const { return get_class(vm).name; } DabClass &DabValue::get_class(DabVM &vm) const { return vm.get_class(class_index()); } void DabValue::print(DabVM &vm, FILE *out, bool debug) const { switch (data.type) { case TYPE_FIXNUM: fprintf(out, "%zd", data.fixnum); break; case TYPE_STRING: fprintf(out, debug ? "\"%s\"" : "%s", data.string.c_str()); break; case TYPE_SYMBOL: fprintf(out, ":%s", data.string.c_str()); break; case TYPE_BOOLEAN: fprintf(out, "%s", data.boolean ? "true" : "false"); break; case TYPE_NIL: fprintf(out, "nil"); break; case TYPE_CLASS: fprintf(out, "%s", class_name(vm).c_str()); break; case TYPE_OBJECT: fprintf(out, "#%s", class_name(vm).c_str()); break; default: fprintf(out, "?"); break; } } bool DabValue::truthy() const { switch (data.type) { case TYPE_FIXNUM: return data.fixnum; case TYPE_STRING: return data.string.length(); break; case TYPE_BOOLEAN: return data.boolean; break; case TYPE_NIL: return false; break; default: return true; break; } } DabValue DabValue::create_instance() const { assert(data.type == TYPE_CLASS); DabObjectProxy *proxy = new DabObjectProxy; proxy->object = new DabObject; proxy->count_strong = 1; proxy->object->klass = this->data.fixnum; DabValue ret; ret.data.type = TYPE_OBJECT; ret.data.object = proxy; fprintf(stderr, "VM: proxy %p (strong %d): ! created\n", proxy, (int)proxy->count_strong); return ret; } DabValue DabValue::_get_instvar(DabVM &vm, const std::string &name) { assert(this->data.type == TYPE_OBJECT); assert(this->data.object); if (!this->data.object->object) { return DabValue(nullptr); } auto &instvars = this->data.object->object->instvars; if (!instvars.count(name)) { return DabValue(nullptr); } return instvars[name]; } DabValue DabValue::get_instvar(DabVM &vm, const std::string &name) { auto ret = _get_instvar(vm, name); fprintf(stderr, "VM: proxy %p (strong %d): Get instvar <%s> -> ", this->data.object, (int)this->data.object->count_strong, name.c_str()); ret.print(vm, stderr); fprintf(stderr, "\n"); return ret; } void DabValue::set_instvar(DabVM &vm, const std::string &name, const DabValue &value) { assert(this->data.type == TYPE_OBJECT); assert(this->data.object); fprintf(stderr, "VM: proxy %p (strong %d): Set instvar <%s> to ", this->data.object, (int)this->data.object->count_strong, name.c_str()); value.print(vm, stderr); fprintf(stderr, "\n"); if (!this->data.object->object) { return; } auto &instvars = this->data.object->object->instvars; instvars[name] = value; } void DabValue::set_data(const DabValueData &other_data) { data = other_data; if (data.type == TYPE_OBJECT) { data.object->retain(); } } DabValue::DabValue(const DabValue &other) { set_data(other.data); } DabValue &DabValue::operator=(const DabValue &other) { set_data(other.data); return *this; } DabValue::~DabValue() { if (this->data.type == TYPE_OBJECT) { this->data.object->release(); } } // void DabObjectProxy::retain() { count_strong += 1; fprintf(stderr, "VM: proxy %p (strong %d): + retained\n", this, (int)this->count_strong); } void DabObjectProxy::release() { count_strong -= 1; fprintf(stderr, "VM: proxy %p (strong %d): - released\n", this, (int)this->count_strong); if (count_strong == 0) { fprintf(stderr, "VM: proxy %p (strong %d): X destroy\n", this, (int)this->count_strong); delete object; delete this; } }
debug print of retain/release
VM: debug print of retain/release
C++
mit
thomas-pendragon/dablang,thomas-pendragon/dablang,thomas-pendragon/dablang,thomas-pendragon/dablang
79da71812fed5263adb9367878220dbfd02a799d
packages/Search/src/details/DTK_DetailsTreeVisualization.hpp
packages/Search/src/details/DTK_DetailsTreeVisualization.hpp
/**************************************************************************** * Copyright (c) 2012-2019 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #ifndef DTK_DETAILS_TREE_VISUALIZATION_HPP #define DTK_DETAILS_TREE_VISUALIZATION_HPP #include <DTK_DetailsTreeTraversal.hpp> namespace DataTransferKit { namespace Details { template <typename DeviceType> struct TreeVisualization { // You have been warned :) using TreeAccess = typename TreeTraversal< DeviceType>::DoNotUseUnlessYouKnowWhatYouAreDoing; template <typename Tree> static std::string getNodeLabel( Node const *node, Tree const &tree ) { auto const node_is_leaf = TreeAccess::isLeaf( node, tree ); auto const node_index = TreeAccess::getIndex( node, tree ); std::string label = node_is_leaf ? "l" : "i"; label.append( std::to_string( node_index ) ); return label; } template <typename Tree> static std::string getNodeAttributes( Node const *node, Tree const &tree ) { return TreeAccess::isLeaf( node, tree ) ? "[leaf]" : "[internal]"; } template <typename Tree> static std::string getEdgeAttributes( Node const *parent, Node const *child, Tree const &tree ) { return TreeAccess::isLeaf( child, tree ) ? "[pendant]" : "[edge]"; } struct GraphvizVisitor { std::ostream &_os; template <typename Tree> void visit( Node const *node, Tree const &tree ) const { visitNode( node, tree ); visitEdgesStartingFromNode( node, tree ); } template <typename Tree> void visitNode( Node const *node, Tree const &tree ) const { auto const node_label = getNodeLabel( node, tree ); auto const node_attributes = getNodeAttributes( node, tree ); _os << " " << node_label << " " << node_attributes << ";\n"; } template <typename Tree> void visitEdgesStartingFromNode( Node const *node, Tree const &tree ) const { auto const node_label = getNodeLabel( node, tree ); auto const node_is_internal = !TreeAccess::isLeaf( node, tree ); if ( node_is_internal ) for ( Node const *child : {node->children.first, node->children.second} ) { auto const child_label = getNodeLabel( child, tree ); auto const edge_attributes = getEdgeAttributes( node, child, tree ); _os << " " << node_label << " -> " << child_label << " " << edge_attributes << ";\n"; } } }; }; } // namespace Details } // namespace DataTransferKit #endif
/**************************************************************************** * Copyright (c) 2012-2019 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #ifndef DTK_DETAILS_TREE_VISUALIZATION_HPP #define DTK_DETAILS_TREE_VISUALIZATION_HPP #include <DTK_DetailsTreeTraversal.hpp> namespace DataTransferKit { namespace Details { template <typename DeviceType> struct TreeVisualization { // You have been warned :) using TreeAccess = typename TreeTraversal< DeviceType>::DoNotUseUnlessYouKnowWhatYouAreDoing; template <typename Tree> static std::string getNodeLabel( Node const *node, Tree const &tree ) { auto const node_is_leaf = TreeAccess::isLeaf( node, tree ); auto const node_index = TreeAccess::getIndex( node, tree ); std::string label = node_is_leaf ? "l" : "i"; label.append( std::to_string( node_index ) ); return label; } template <typename Tree> static std::string getNodeAttributes( Node const *node, Tree const &tree ) { return TreeAccess::isLeaf( node, tree ) ? "[leaf]" : "[internal]"; } template <typename Tree> static std::string getEdgeAttributes( Node const *parent, Node const *child, Tree const &tree ) { return TreeAccess::isLeaf( child, tree ) ? "[pendant]" : "[edge]"; } struct GraphvizVisitor { std::ostream &_os; template <typename Tree> void visit( Node const *node, Tree const &tree ) const { visitNode( node, tree ); visitEdgesStartingFromNode( node, tree ); } template <typename Tree> void visitNode( Node const *node, Tree const &tree ) const { auto const node_label = getNodeLabel( node, tree ); auto const node_attributes = getNodeAttributes( node, tree ); _os << " " << node_label << " " << node_attributes << ";\n"; } template <typename Tree> void visitEdgesStartingFromNode( Node const *node, Tree const &tree ) const { auto const node_label = getNodeLabel( node, tree ); auto const node_is_internal = !TreeAccess::isLeaf( node, tree ); if ( node_is_internal ) for ( Node const *child : {node->children.first, node->children.second} ) { auto const child_label = getNodeLabel( child, tree ); auto const edge_attributes = getEdgeAttributes( node, child, tree ); _os << " " << node_label << " -> " << child_label << " " << edge_attributes << ";\n"; } } }; template <typename Tree, typename Visitor> static void visitAllIterative( Tree const &tree, Visitor const &visitor ) { Stack<Node const *> stack; stack.emplace( TreeAccess::getRoot( tree ) ); while ( !stack.empty() ) { Node const *node = stack.top(); stack.pop(); visitor.visit( node, tree ); if ( !TreeAccess::isLeaf( node, tree ) ) for ( Node const *child : {node->children.first, node->children.second} ) stack.push( child ); } } }; } // namespace Details } // namespace DataTransferKit #endif
Add iterative traversal of the entire tree to visualize it
Add iterative traversal of the entire tree to visualize it
C++
bsd-3-clause
dalg24/DataTransferKit,ORNL-CEES/DataTransferKit,dalg24/DataTransferKit,Rombur/DataTransferKit,ORNL-CEES/DataTransferKit,Rombur/DataTransferKit,dalg24/DataTransferKit,ORNL-CEES/DataTransferKit,dalg24/DataTransferKit,Rombur/DataTransferKit,Rombur/DataTransferKit,ORNL-CEES/DataTransferKit
91486c6b63382427b170ad741ee75a88b6e3e6b9
caffe2/core/context_gpu_test.cc
caffe2/core/context_gpu_test.cc
#include <chrono> #include <future> #include <random> #include <thread> #include "caffe2/proto/caffe2.pb.h" #include "caffe2/core/context_gpu.h" #include <gtest/gtest.h> namespace caffe2 { TEST(CUDAContextTest, TestAllocDealloc) { if (!HasCudaGPU()) return; CUDAContext context(0); context.SwitchToDevice(); float* data = static_cast<float*>(CUDAContext::New(10 * sizeof(float))); EXPECT_NE(data, nullptr); CUDAContext::Delete(data); } TEST(CUDAContextTest, MemoryPoolAllocateDealloc) { if (!HasCudaGPU()) return; if (GetCudaMemoryPoolType() == CudaMemoryPoolType::NONE) { LOG(ERROR) << "Choose a memory type that is not none to test memory pool."; return; } const int nbytes = 1048576; for (int i = 0; i < NumCudaDevices(); ++i) { LOG(INFO) << "Device " << i << " of " << NumCudaDevices(); DeviceGuard guard(i); void* allocated = CUDAContext::New(nbytes); EXPECT_NE(allocated, nullptr); cudaPointerAttributes attr; CUDA_ENFORCE(cudaPointerGetAttributes(&attr, allocated)); EXPECT_EQ(attr.memoryType, cudaMemoryTypeDevice); EXPECT_EQ(attr.device, i); CUDAContext::Delete(allocated); void* new_allocated = CUDAContext::New(nbytes); // With a pool, the above allocation should yield the same address. EXPECT_EQ(new_allocated, allocated); // But, if we are allocating something larger, we will have a different // chunk of memory. void* larger_allocated = CUDAContext::New(nbytes * 2); EXPECT_NE(larger_allocated, new_allocated); CUDAContext::Delete(new_allocated); CUDAContext::Delete(larger_allocated); } } cudaStream_t getStreamForHandle(cublasHandle_t handle) { cudaStream_t stream = nullptr; CUBLAS_ENFORCE(cublasGetStream(handle, &stream)); CHECK_NOTNULL(stream); return stream; } TEST(CUDAContextTest, TestSameThreadSameObject) { if (!HasCudaGPU()) return; CUDAContext context_a(0); CUDAContext context_b(0); EXPECT_EQ(context_a.cuda_stream(), context_b.cuda_stream()); EXPECT_EQ(context_a.cublas_handle(), context_b.cublas_handle()); EXPECT_EQ( context_a.cuda_stream(), getStreamForHandle(context_b.cublas_handle())); // CuRAND generators are context-local. EXPECT_NE(context_a.curand_generator(), context_b.curand_generator()); } TEST(CUDAContextTest, TestSameThreadDifferntObjectIfDifferentDevices) { if (NumCudaDevices() > 1) { CUDAContext context_a(0); CUDAContext context_b(1); EXPECT_NE(context_a.cuda_stream(), context_b.cuda_stream()); EXPECT_NE(context_a.cublas_handle(), context_b.cublas_handle()); EXPECT_NE( context_a.cuda_stream(), getStreamForHandle(context_b.cublas_handle())); EXPECT_NE(context_a.curand_generator(), context_b.curand_generator()); } } namespace { // A test function to return a stream address from a temp CUDA context. You // should not use that stream though, because the actual stream is destroyed // after thread exit. void TEST_GetStreamAddress(cudaStream_t* ptr) { CUDAContext context(0); *ptr = context.cuda_stream(); // Sleep for a while so we have concurrent thread executions std::this_thread::sleep_for(std::chrono::seconds(1)); } } // namespace TEST(CUDAContextTest, TestDifferntThreadDifferentobject) { if (!HasCudaGPU()) return; std::array<cudaStream_t, 2> temp = {0}; // Same thread TEST_GetStreamAddress(&temp[0]); TEST_GetStreamAddress(&temp[1]); EXPECT_TRUE(temp[0] != nullptr); EXPECT_TRUE(temp[1] != nullptr); EXPECT_EQ(temp[0], temp[1]); // Different threads std::thread thread_a(TEST_GetStreamAddress, &temp[0]); std::thread thread_b(TEST_GetStreamAddress, &temp[1]); thread_a.join(); thread_b.join(); EXPECT_TRUE(temp[0] != nullptr); EXPECT_TRUE(temp[1] != nullptr); EXPECT_NE(temp[0], temp[1]); } } // namespace caffe2
#include <chrono> #include <future> #include <random> #include <thread> #include <array> #include "caffe2/proto/caffe2.pb.h" #include "caffe2/core/context_gpu.h" #include <gtest/gtest.h> namespace caffe2 { TEST(CUDAContextTest, TestAllocDealloc) { if (!HasCudaGPU()) return; CUDAContext context(0); context.SwitchToDevice(); float* data = static_cast<float*>(CUDAContext::New(10 * sizeof(float))); EXPECT_NE(data, nullptr); CUDAContext::Delete(data); } TEST(CUDAContextTest, MemoryPoolAllocateDealloc) { if (!HasCudaGPU()) return; if (GetCudaMemoryPoolType() == CudaMemoryPoolType::NONE) { LOG(ERROR) << "Choose a memory type that is not none to test memory pool."; return; } const int nbytes = 1048576; for (int i = 0; i < NumCudaDevices(); ++i) { LOG(INFO) << "Device " << i << " of " << NumCudaDevices(); DeviceGuard guard(i); void* allocated = CUDAContext::New(nbytes); EXPECT_NE(allocated, nullptr); cudaPointerAttributes attr; CUDA_ENFORCE(cudaPointerGetAttributes(&attr, allocated)); EXPECT_EQ(attr.memoryType, cudaMemoryTypeDevice); EXPECT_EQ(attr.device, i); CUDAContext::Delete(allocated); void* new_allocated = CUDAContext::New(nbytes); // With a pool, the above allocation should yield the same address. EXPECT_EQ(new_allocated, allocated); // But, if we are allocating something larger, we will have a different // chunk of memory. void* larger_allocated = CUDAContext::New(nbytes * 2); EXPECT_NE(larger_allocated, new_allocated); CUDAContext::Delete(new_allocated); CUDAContext::Delete(larger_allocated); } } cudaStream_t getStreamForHandle(cublasHandle_t handle) { cudaStream_t stream = nullptr; CUBLAS_ENFORCE(cublasGetStream(handle, &stream)); CHECK_NOTNULL(stream); return stream; } TEST(CUDAContextTest, TestSameThreadSameObject) { if (!HasCudaGPU()) return; CUDAContext context_a(0); CUDAContext context_b(0); EXPECT_EQ(context_a.cuda_stream(), context_b.cuda_stream()); EXPECT_EQ(context_a.cublas_handle(), context_b.cublas_handle()); EXPECT_EQ( context_a.cuda_stream(), getStreamForHandle(context_b.cublas_handle())); // CuRAND generators are context-local. EXPECT_NE(context_a.curand_generator(), context_b.curand_generator()); } TEST(CUDAContextTest, TestSameThreadDifferntObjectIfDifferentDevices) { if (NumCudaDevices() > 1) { CUDAContext context_a(0); CUDAContext context_b(1); EXPECT_NE(context_a.cuda_stream(), context_b.cuda_stream()); EXPECT_NE(context_a.cublas_handle(), context_b.cublas_handle()); EXPECT_NE( context_a.cuda_stream(), getStreamForHandle(context_b.cublas_handle())); EXPECT_NE(context_a.curand_generator(), context_b.curand_generator()); } } namespace { // A test function to return a stream address from a temp CUDA context. You // should not use that stream though, because the actual stream is destroyed // after thread exit. void TEST_GetStreamAddress(cudaStream_t* ptr) { CUDAContext context(0); *ptr = context.cuda_stream(); // Sleep for a while so we have concurrent thread executions std::this_thread::sleep_for(std::chrono::seconds(1)); } } // namespace TEST(CUDAContextTest, TestDifferntThreadDifferentobject) { if (!HasCudaGPU()) return; std::array<cudaStream_t, 2> temp = {0}; // Same thread TEST_GetStreamAddress(&temp[0]); TEST_GetStreamAddress(&temp[1]); EXPECT_TRUE(temp[0] != nullptr); EXPECT_TRUE(temp[1] != nullptr); EXPECT_EQ(temp[0], temp[1]); // Different threads std::thread thread_a(TEST_GetStreamAddress, &temp[0]); std::thread thread_b(TEST_GetStreamAddress, &temp[1]); thread_a.join(); thread_b.join(); EXPECT_TRUE(temp[0] != nullptr); EXPECT_TRUE(temp[1] != nullptr); EXPECT_NE(temp[0], temp[1]); } } // namespace caffe2
build error in context_gpu_test.cc
build error in context_gpu_test.cc Summary: caffe2/caffe2/core/context_gpu_test.cc:97:31: error: implicit instantiation of undefined template 'std::__1::array<CUstream_st *, 2>' std::array<cudaStream_t, 2> temp = {0}; (fixes build issue on macOS 10.11.6) Closes https://github.com/caffe2/caffe2/pull/296 Differential Revision: D4914191 Pulled By: Yangqing fbshipit-source-id: 5a2c218eef0f04e0dbfcaf951dd4749424b8cfaa
C++
apache-2.0
bwasti/caffe2,Yangqing/caffe2,pietern/caffe2,sf-wind/caffe2,sf-wind/caffe2,bwasti/caffe2,Yangqing/caffe2,xzturn/caffe2,pietern/caffe2,sf-wind/caffe2,davinwang/caffe2,bwasti/caffe2,Yangqing/caffe2,pietern/caffe2,davinwang/caffe2,davinwang/caffe2,bwasti/caffe2,xzturn/caffe2,davinwang/caffe2,sf-wind/caffe2,bwasti/caffe2,pietern/caffe2,davinwang/caffe2,sf-wind/caffe2,Yangqing/caffe2,xzturn/caffe2,caffe2/caffe2,Yangqing/caffe2,xzturn/caffe2,pietern/caffe2,xzturn/caffe2
7499fc2b8526102ec9e56b14a028a8c78af84901
indra/newview/llchathistory.cpp
indra/newview/llchathistory.cpp
/** * @file llchathistory.cpp * @brief LLTextEditor base class * * $LicenseInfo:firstyear=2001&license=viewergpl$ * * Copyright (c) 2001-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llchathistory.h" #include "llpanel.h" #include "lltextbox.h" #include "lluictrlfactory.h" #include "llscrollcontainer.h" #include "llavatariconctrl.h" #include "llimview.h" #include "llcallingcard.h" //for LLAvatarTracker #include "llagentdata.h" #include "llavataractions.h" #include "lltrans.h" #include "llfloaterreg.h" #include "llmutelist.h" static LLDefaultChildRegistry::Register<LLChatHistory> r("chat_history"); std::string formatCurrentTime() { time_t utc_time; utc_time = time_corrected(); std::string timeStr ="["+ LLTrans::getString("TimeHour")+"]:[" +LLTrans::getString("TimeMin")+"] "; LLSD substitution; substitution["datetime"] = (S32) utc_time; LLStringUtil::format (timeStr, substitution); return timeStr; } class LLChatHistoryHeader: public LLPanel { public: static LLChatHistoryHeader* createInstance(const std::string& file_name) { LLChatHistoryHeader* pInstance = new LLChatHistoryHeader; LLUICtrlFactory::getInstance()->buildPanel(pInstance, file_name); return pInstance; } BOOL handleMouseUp(S32 x, S32 y, MASK mask) { return LLPanel::handleMouseUp(x,y,mask); } void onObjectIconContextMenuItemClicked(const LLSD& userdata) { std::string level = userdata.asString(); if (level == "profile") { } else if (level == "block") { LLMuteList::getInstance()->add(LLMute(getAvatarId(), mFrom, LLMute::OBJECT)); } } void onAvatarIconContextMenuItemClicked(const LLSD& userdata) { std::string level = userdata.asString(); if (level == "profile") { LLAvatarActions::showProfile(getAvatarId()); } else if (level == "im") { LLAvatarActions::startIM(getAvatarId()); } else if (level == "add") { std::string name; name.assign(getFirstName()); name.append(" "); name.append(getLastName()); LLAvatarActions::requestFriendshipDialog(getAvatarId(), name); } else if (level == "remove") { LLAvatarActions::removeFriendDialog(getAvatarId()); } } BOOL postBuild() { LLUICtrl::CommitCallbackRegistry::ScopedRegistrar registrar; registrar.add("AvatarIcon.Action", boost::bind(&LLChatHistoryHeader::onAvatarIconContextMenuItemClicked, this, _2)); registrar.add("ObjectIcon.Action", boost::bind(&LLChatHistoryHeader::onObjectIconContextMenuItemClicked, this, _2)); LLMenuGL* menu = LLUICtrlFactory::getInstance()->createFromFile<LLMenuGL>("menu_avatar_icon.xml", gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance()); mPopupMenuHandleAvatar = menu->getHandle(); menu = LLUICtrlFactory::getInstance()->createFromFile<LLMenuGL>("menu_object_icon.xml", gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance()); mPopupMenuHandleObject = menu->getHandle(); setMouseDownCallback(boost::bind(&LLChatHistoryHeader::onHeaderPanelClick, this, _2, _3, _4)); return LLPanel::postBuild(); } bool pointInChild(const std::string& name,S32 x,S32 y) { LLUICtrl* child = findChild<LLUICtrl>(name); if(!child) return false; LLView* parent = child->getParent(); if(parent!=this) { x-=parent->getRect().mLeft; y-=parent->getRect().mBottom; } S32 local_x = x - child->getRect().mLeft ; S32 local_y = y - child->getRect().mBottom ; return child->pointInView(local_x, local_y); } BOOL handleRightMouseDown(S32 x, S32 y, MASK mask) { if(pointInChild("avatar_icon",x,y) || pointInChild("user_name",x,y)) { showContextMenu(x,y); return TRUE; } return LLPanel::handleRightMouseDown(x,y,mask); } void onHeaderPanelClick(S32 x, S32 y, MASK mask) { LLFloaterReg::showInstance("inspect_avatar", LLSD().insert("avatar_id", mAvatarID)); } const LLUUID& getAvatarId () const { return mAvatarID;} const std::string& getFirstName() const { return mFirstName; } const std::string& getLastName () const { return mLastName; } void setup(const LLChat& chat,const LLStyle::Params& style_params) { mAvatarID = chat.mFromID; mSourceType = chat.mSourceType; gCacheName->get(mAvatarID, FALSE, boost::bind(&LLChatHistoryHeader::nameUpdatedCallback, this, _1, _2, _3, _4)); if(chat.mFromID.isNull()) { mSourceType = CHAT_SOURCE_SYSTEM; } LLTextBox* userName = getChild<LLTextBox>("user_name"); LLUIColor color = style_params.color; userName->setReadOnlyColor(color); userName->setColor(color); if(!chat.mFromName.empty()) { userName->setValue(chat.mFromName); mFrom = chat.mFromName; } else { std::string SL = LLTrans::getString("SECOND_LIFE"); userName->setValue(SL); } LLTextBox* timeBox = getChild<LLTextBox>("time_box"); timeBox->setValue(formatCurrentTime()); LLAvatarIconCtrl* icon = getChild<LLAvatarIconCtrl>("avatar_icon"); if(mSourceType != CHAT_SOURCE_AGENT) icon->setDrawTooltip(false); if(!chat.mFromID.isNull()) { icon->setValue(chat.mFromID); } } void nameUpdatedCallback(const LLUUID& id,const std::string& first,const std::string& last,BOOL is_group) { if (id != mAvatarID) return; mFirstName = first; mLastName = last; } protected: void showContextMenu(S32 x,S32 y) { if(mSourceType == CHAT_SOURCE_SYSTEM) showSystemContextMenu(x,y); if(mSourceType == CHAT_SOURCE_AGENT) showAvatarContextMenu(x,y); if(mSourceType == CHAT_SOURCE_OBJECT) showObjectContextMenu(x,y); } void showSystemContextMenu(S32 x,S32 y) { } void showObjectContextMenu(S32 x,S32 y) { LLMenuGL* menu = (LLMenuGL*)mPopupMenuHandleObject.get(); if(menu) LLMenuGL::showPopup(this, menu, x, y); } void showAvatarContextMenu(S32 x,S32 y) { LLMenuGL* menu = (LLMenuGL*)mPopupMenuHandleAvatar.get(); if(menu) { bool is_friend = LLAvatarTracker::instance().getBuddyInfo(mAvatarID) != NULL; menu->setItemEnabled("Add Friend", !is_friend); menu->setItemEnabled("Remove Friend", is_friend); if(gAgentID == mAvatarID) { menu->setItemEnabled("Add Friend", false); menu->setItemEnabled("Send IM", false); menu->setItemEnabled("Remove Friend", false); } menu->buildDrawLabels(); menu->updateParent(LLMenuGL::sMenuContainer); LLMenuGL::showPopup(this, menu, x, y); } } protected: LLHandle<LLView> mPopupMenuHandleAvatar; LLHandle<LLView> mPopupMenuHandleObject; LLUUID mAvatarID; EChatSourceType mSourceType; std::string mFirstName; std::string mLastName; std::string mFrom; }; LLChatHistory::LLChatHistory(const LLChatHistory::Params& p) : LLTextEditor(p), mMessageHeaderFilename(p.message_header), mMessageSeparatorFilename(p.message_separator), mLeftTextPad(p.left_text_pad), mRightTextPad(p.right_text_pad), mLeftWidgetPad(p.left_widget_pad), mRightWidgetPad(p.right_widget_pad), mTopSeparatorPad(p.top_separator_pad), mBottomSeparatorPad(p.bottom_separator_pad), mTopHeaderPad(p.top_header_pad), mBottomHeaderPad(p.bottom_header_pad) { } LLChatHistory::~LLChatHistory() { this->clear(); } /*void LLChatHistory::updateTextRect() { static LLUICachedControl<S32> texteditor_border ("UITextEditorBorder", 0); LLRect old_text_rect = mTextRect; mTextRect = mScroller->getContentWindowRect(); mTextRect.stretch(-texteditor_border); mTextRect.mLeft += mLeftTextPad; mTextRect.mRight -= mRightTextPad; if (mTextRect != old_text_rect) { needsReflow(); } }*/ LLView* LLChatHistory::getSeparator() { LLPanel* separator = LLUICtrlFactory::getInstance()->createFromFile<LLPanel>(mMessageSeparatorFilename, NULL, LLPanel::child_registry_t::instance()); return separator; } LLView* LLChatHistory::getHeader(const LLChat& chat,const LLStyle::Params& style_params) { LLChatHistoryHeader* header = LLChatHistoryHeader::createInstance(mMessageHeaderFilename); header->setup(chat,style_params); return header; } void LLChatHistory::appendWidgetMessage(const LLChat& chat) { LLView* view = NULL; std::string view_text = "\n[" + formatCurrentTime() + "] " + chat.mFromName + ": "; LLInlineViewSegment::Params p; p.force_newline = true; p.left_pad = mLeftWidgetPad; p.right_pad = mRightWidgetPad; LLColor4 txt_color = LLUIColorTable::instance().getColor("White"); LLViewerChat::getChatColor(chat,txt_color); LLFontGL* fontp = LLViewerChat::getChatFont(); LLStyle::Params style_params; style_params.color(txt_color); style_params.font(fontp); if (mLastFromName == chat.mFromName) { view = getSeparator(); p.top_pad = mTopSeparatorPad; p.bottom_pad = mBottomSeparatorPad; } else { view = getHeader(chat,style_params); if (getText().size() == 0) p.top_pad = 0; else p.top_pad = mTopHeaderPad; p.bottom_pad = mBottomHeaderPad; } p.view = view; //Prepare the rect for the view LLRect target_rect = getDocumentView()->getRect(); // squeeze down the widget by subtracting padding off left and right target_rect.mLeft += mLeftWidgetPad + mHPad; target_rect.mRight -= mRightWidgetPad; view->reshape(target_rect.getWidth(), view->getRect().getHeight()); view->setOrigin(target_rect.mLeft, view->getRect().mBottom); appendWidget(p, view_text, false); //Append the text message appendText(chat.mText, FALSE, style_params); mLastFromName = chat.mFromName; blockUndo(); }
/** * @file llchathistory.cpp * @brief LLTextEditor base class * * $LicenseInfo:firstyear=2001&license=viewergpl$ * * Copyright (c) 2001-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llchathistory.h" #include "llpanel.h" #include "lltextbox.h" #include "lluictrlfactory.h" #include "llscrollcontainer.h" #include "llavatariconctrl.h" #include "llimview.h" #include "llcallingcard.h" //for LLAvatarTracker #include "llagentdata.h" #include "llavataractions.h" #include "lltrans.h" #include "llfloaterreg.h" #include "llmutelist.h" static LLDefaultChildRegistry::Register<LLChatHistory> r("chat_history"); std::string formatCurrentTime() { time_t utc_time; utc_time = time_corrected(); std::string timeStr ="["+ LLTrans::getString("TimeHour")+"]:[" +LLTrans::getString("TimeMin")+"] "; LLSD substitution; substitution["datetime"] = (S32) utc_time; LLStringUtil::format (timeStr, substitution); return timeStr; } class LLChatHistoryHeader: public LLPanel { public: static LLChatHistoryHeader* createInstance(const std::string& file_name) { LLChatHistoryHeader* pInstance = new LLChatHistoryHeader; LLUICtrlFactory::getInstance()->buildPanel(pInstance, file_name); return pInstance; } BOOL handleMouseUp(S32 x, S32 y, MASK mask) { return LLPanel::handleMouseUp(x,y,mask); } void onObjectIconContextMenuItemClicked(const LLSD& userdata) { std::string level = userdata.asString(); if (level == "profile") { } else if (level == "block") { LLMuteList::getInstance()->add(LLMute(getAvatarId(), mFrom, LLMute::OBJECT)); } } void onAvatarIconContextMenuItemClicked(const LLSD& userdata) { std::string level = userdata.asString(); if (level == "profile") { LLAvatarActions::showProfile(getAvatarId()); } else if (level == "im") { LLAvatarActions::startIM(getAvatarId()); } else if (level == "add") { std::string name; name.assign(getFirstName()); name.append(" "); name.append(getLastName()); LLAvatarActions::requestFriendshipDialog(getAvatarId(), name); } else if (level == "remove") { LLAvatarActions::removeFriendDialog(getAvatarId()); } } BOOL postBuild() { LLUICtrl::CommitCallbackRegistry::ScopedRegistrar registrar; registrar.add("AvatarIcon.Action", boost::bind(&LLChatHistoryHeader::onAvatarIconContextMenuItemClicked, this, _2)); registrar.add("ObjectIcon.Action", boost::bind(&LLChatHistoryHeader::onObjectIconContextMenuItemClicked, this, _2)); LLMenuGL* menu = LLUICtrlFactory::getInstance()->createFromFile<LLMenuGL>("menu_avatar_icon.xml", gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance()); mPopupMenuHandleAvatar = menu->getHandle(); menu = LLUICtrlFactory::getInstance()->createFromFile<LLMenuGL>("menu_object_icon.xml", gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance()); mPopupMenuHandleObject = menu->getHandle(); setMouseDownCallback(boost::bind(&LLChatHistoryHeader::onHeaderPanelClick, this, _2, _3, _4)); return LLPanel::postBuild(); } bool pointInChild(const std::string& name,S32 x,S32 y) { LLUICtrl* child = findChild<LLUICtrl>(name); if(!child) return false; LLView* parent = child->getParent(); if(parent!=this) { x-=parent->getRect().mLeft; y-=parent->getRect().mBottom; } S32 local_x = x - child->getRect().mLeft ; S32 local_y = y - child->getRect().mBottom ; return child->pointInView(local_x, local_y); } BOOL handleRightMouseDown(S32 x, S32 y, MASK mask) { if(pointInChild("avatar_icon",x,y) || pointInChild("user_name",x,y)) { showContextMenu(x,y); return TRUE; } return LLPanel::handleRightMouseDown(x,y,mask); } void onHeaderPanelClick(S32 x, S32 y, MASK mask) { LLFloaterReg::showInstance("inspect_avatar", LLSD().insert("avatar_id", mAvatarID)); } const LLUUID& getAvatarId () const { return mAvatarID;} const std::string& getFirstName() const { return mFirstName; } const std::string& getLastName () const { return mLastName; } void setup(const LLChat& chat,const LLStyle::Params& style_params) { mAvatarID = chat.mFromID; mSourceType = chat.mSourceType; gCacheName->get(mAvatarID, FALSE, boost::bind(&LLChatHistoryHeader::nameUpdatedCallback, this, _1, _2, _3, _4)); if(chat.mFromID.isNull()) { mSourceType = CHAT_SOURCE_SYSTEM; } LLTextBox* userName = getChild<LLTextBox>("user_name"); LLUIColor color = style_params.color; userName->setReadOnlyColor(color); userName->setColor(color); if(!chat.mFromName.empty()) { userName->setValue(chat.mFromName); mFrom = chat.mFromName; } else { std::string SL = LLTrans::getString("SECOND_LIFE"); userName->setValue(SL); } LLTextBox* timeBox = getChild<LLTextBox>("time_box"); timeBox->setValue(formatCurrentTime()); LLAvatarIconCtrl* icon = getChild<LLAvatarIconCtrl>("avatar_icon"); if(mSourceType != CHAT_SOURCE_AGENT) icon->setDrawTooltip(false); if(!chat.mFromID.isNull()) { icon->setValue(chat.mFromID); } } void nameUpdatedCallback(const LLUUID& id,const std::string& first,const std::string& last,BOOL is_group) { if (id != mAvatarID) return; mFirstName = first; mLastName = last; } protected: void showContextMenu(S32 x,S32 y) { if(mSourceType == CHAT_SOURCE_SYSTEM) showSystemContextMenu(x,y); if(mSourceType == CHAT_SOURCE_AGENT) showAvatarContextMenu(x,y); if(mSourceType == CHAT_SOURCE_OBJECT) showObjectContextMenu(x,y); } void showSystemContextMenu(S32 x,S32 y) { } void showObjectContextMenu(S32 x,S32 y) { LLMenuGL* menu = (LLMenuGL*)mPopupMenuHandleObject.get(); if(menu) LLMenuGL::showPopup(this, menu, x, y); } void showAvatarContextMenu(S32 x,S32 y) { LLMenuGL* menu = (LLMenuGL*)mPopupMenuHandleAvatar.get(); if(menu) { bool is_friend = LLAvatarTracker::instance().getBuddyInfo(mAvatarID) != NULL; menu->setItemEnabled("Add Friend", !is_friend); menu->setItemEnabled("Remove Friend", is_friend); if(gAgentID == mAvatarID) { menu->setItemEnabled("Add Friend", false); menu->setItemEnabled("Send IM", false); menu->setItemEnabled("Remove Friend", false); } menu->buildDrawLabels(); menu->updateParent(LLMenuGL::sMenuContainer); LLMenuGL::showPopup(this, menu, x, y); } } protected: LLHandle<LLView> mPopupMenuHandleAvatar; LLHandle<LLView> mPopupMenuHandleObject; LLUUID mAvatarID; EChatSourceType mSourceType; std::string mFirstName; std::string mLastName; std::string mFrom; }; LLChatHistory::LLChatHistory(const LLChatHistory::Params& p) : LLTextEditor(p), mMessageHeaderFilename(p.message_header), mMessageSeparatorFilename(p.message_separator), mLeftTextPad(p.left_text_pad), mRightTextPad(p.right_text_pad), mLeftWidgetPad(p.left_widget_pad), mRightWidgetPad(p.right_widget_pad), mTopSeparatorPad(p.top_separator_pad), mBottomSeparatorPad(p.bottom_separator_pad), mTopHeaderPad(p.top_header_pad), mBottomHeaderPad(p.bottom_header_pad) { } LLChatHistory::~LLChatHistory() { this->clear(); } /*void LLChatHistory::updateTextRect() { static LLUICachedControl<S32> texteditor_border ("UITextEditorBorder", 0); LLRect old_text_rect = mTextRect; mTextRect = mScroller->getContentWindowRect(); mTextRect.stretch(-texteditor_border); mTextRect.mLeft += mLeftTextPad; mTextRect.mRight -= mRightTextPad; if (mTextRect != old_text_rect) { needsReflow(); } }*/ LLView* LLChatHistory::getSeparator() { LLPanel* separator = LLUICtrlFactory::getInstance()->createFromFile<LLPanel>(mMessageSeparatorFilename, NULL, LLPanel::child_registry_t::instance()); return separator; } LLView* LLChatHistory::getHeader(const LLChat& chat,const LLStyle::Params& style_params) { LLChatHistoryHeader* header = LLChatHistoryHeader::createInstance(mMessageHeaderFilename); header->setup(chat,style_params); return header; } void LLChatHistory::appendWidgetMessage(const LLChat& chat) { LLView* view = NULL; std::string view_text = "\n[" + formatCurrentTime() + "] " + chat.mFromName + ": "; LLInlineViewSegment::Params p; p.force_newline = true; p.left_pad = mLeftWidgetPad; p.right_pad = mRightWidgetPad; LLColor4 txt_color = LLUIColorTable::instance().getColor("White"); LLViewerChat::getChatColor(chat,txt_color); LLFontGL* fontp = LLViewerChat::getChatFont(); LLStyle::Params style_params; style_params.color(txt_color); style_params.readonly_color(txt_color); style_params.font(fontp); if (mLastFromName == chat.mFromName) { view = getSeparator(); p.top_pad = mTopSeparatorPad; p.bottom_pad = mBottomSeparatorPad; } else { view = getHeader(chat,style_params); if (getText().size() == 0) p.top_pad = 0; else p.top_pad = mTopHeaderPad; p.bottom_pad = mBottomHeaderPad; } p.view = view; //Prepare the rect for the view LLRect target_rect = getDocumentView()->getRect(); // squeeze down the widget by subtracting padding off left and right target_rect.mLeft += mLeftWidgetPad + mHPad; target_rect.mRight -= mRightWidgetPad; view->reshape(target_rect.getWidth(), view->getRect().getHeight()); view->setOrigin(target_rect.mLeft, view->getRect().mBottom); appendWidget(p, view_text, false); //Append the text message appendText(chat.mText, FALSE, style_params); mLastFromName = chat.mFromName; blockUndo(); }
fix style readonlycolor overwriting color
fix style readonlycolor overwriting color
C++
lgpl-2.1
gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm
075f1864a6237bb8fc4d21d552de5a7c3d766f1b
util/mutex.cc
util/mutex.cc
// Copyright (c) 2016 Mirants Lu. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "util/mutex.h" #include <errno.h> #include <string.h> #include <sys/time.h> #include "skywalker/logging.h" #include "util/timeops.h" namespace skywalker { static void PthreadCall(const char* label, int result) { if (result != 0) { LOG_FATAL("%s: %s", label, strerror(result)); } } Mutex::Mutex() { PthreadCall("pthread_mutex_init", pthread_mutex_init(&mutex_, nullptr)); } Mutex::~Mutex() { PthreadCall("pthread_mutex_destory", pthread_mutex_destroy(&mutex_)); } void Mutex::Lock() { PthreadCall("pthread_mutex_lock", pthread_mutex_lock(&mutex_)); } void Mutex::UnLock() { PthreadCall("pthread_mutex_unlock", pthread_mutex_unlock(&mutex_)); } Condition::Condition(Mutex* mutex) : mutex_(mutex) { #ifdef __linux__ pthread_condattr_t attr; pthread_condattr_init(&attr); PthreadCall("pthread_condattr_setclock", pthread_condattr_setclock(&attr, CLOCK_MONOTONIC)); PthreadCall("pthread_cond_init", pthread_cond_init(&cond_, &attr)); #else PthreadCall("pthread_cond_init", pthread_cond_init(&cond_, nullptr)); #endif } Condition::~Condition() { PthreadCall("pthread_cond_destory", pthread_cond_destroy(&cond_)); } void Condition::Wait() { PthreadCall("pthread_cond_wait", pthread_cond_wait(&cond_, &mutex_->mutex_)); } bool Condition::Wait(uint64_t micros) { struct timespec outtime; #ifdef __linux__ clock_gettime(CLOCK_MONOTONIC, &outtime); outtime.tv_sec += micros / 1000000; outtime.tv_nsec += (micros % 1000000) * 1000; outtime.tv_sec += outtime.tv_nsec / 1000000000; outtime.tv_nsec = outtime.tv_nsec % 1000000000; #else uint64_t now = (NowMicros() + micros) * 1000; outtime.tv_sec = now / 1000000000; outtime.tv_nsec = now % 1000000000; #endif int res = pthread_cond_timedwait(&cond_, &mutex_->mutex_, &outtime); if (res != 0 && res != ETIMEDOUT) { PthreadCall("pthread_cond_timedwait", res); } return res == 0; } void Condition::Signal() { PthreadCall("pthread_cond_signal", pthread_cond_signal(&cond_)); } void Condition::SignalAll() { PthreadCall("pthread_cond_broadcast", pthread_cond_broadcast(&cond_)); } } // namespace skywalker
// Copyright (c) 2016 Mirants Lu. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "util/mutex.h" #include <errno.h> #include <string.h> #include <sys/time.h> #include "skywalker/logging.h" #include "util/timeops.h" namespace skywalker { static void PthreadCall(const char* label, int result) { if (result != 0) { LOG_FATAL("%s: %s", label, strerror(result)); } } Mutex::Mutex() { PthreadCall("pthread_mutex_init", pthread_mutex_init(&mutex_, nullptr)); } Mutex::~Mutex() { PthreadCall("pthread_mutex_destory", pthread_mutex_destroy(&mutex_)); } void Mutex::Lock() { PthreadCall("pthread_mutex_lock", pthread_mutex_lock(&mutex_)); } void Mutex::UnLock() { PthreadCall("pthread_mutex_unlock", pthread_mutex_unlock(&mutex_)); } Condition::Condition(Mutex* mutex) : mutex_(mutex) { #ifdef __linux__ pthread_condattr_t attr; PthreadCall("pthread_condattr_init", pthread_condattr_init(&attr)); PthreadCall("pthread_condattr_setclock", pthread_condattr_setclock(&attr, CLOCK_MONOTONIC)); PthreadCall("pthread_cond_init", pthread_cond_init(&cond_, &attr)); #else PthreadCall("pthread_cond_init", pthread_cond_init(&cond_, nullptr)); #endif } Condition::~Condition() { PthreadCall("pthread_cond_destory", pthread_cond_destroy(&cond_)); } void Condition::Wait() { PthreadCall("pthread_cond_wait", pthread_cond_wait(&cond_, &mutex_->mutex_)); } bool Condition::Wait(uint64_t micros) { struct timespec outtime; #ifdef __linux__ clock_gettime(CLOCK_MONOTONIC, &outtime); outtime.tv_sec += micros / 1000000; outtime.tv_nsec += (micros % 1000000) * 1000; outtime.tv_sec += outtime.tv_nsec / 1000000000; outtime.tv_nsec = outtime.tv_nsec % 1000000000; #else uint64_t now = (NowMicros() + micros) * 1000; outtime.tv_sec = now / 1000000000; outtime.tv_nsec = now % 1000000000; #endif int res = pthread_cond_timedwait(&cond_, &mutex_->mutex_, &outtime); if (res != 0 && res != ETIMEDOUT) { PthreadCall("pthread_cond_timedwait", res); } return res == 0; } void Condition::Signal() { PthreadCall("pthread_cond_signal", pthread_cond_signal(&cond_)); } void Condition::SignalAll() { PthreadCall("pthread_cond_broadcast", pthread_cond_broadcast(&cond_)); } } // namespace skywalker
fix bug
fix bug
C++
bsd-3-clause
QiumingLu/skywalker,QiumingLu/skywalker
05736d14b872ae9754e2ec091633eabd49d42cdc
lib/AST/Availability.cpp
lib/AST/Availability.cpp
//===--- Availability.cpp - Swift Availability Structures -----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file defines data structures for API availability. // //===----------------------------------------------------------------------===// #include "swift/AST/ASTContext.h" #include "swift/AST/Attr.h" #include "swift/AST/Decl.h" #include "swift/AST/Types.h" #include "swift/AST/Availability.h" #include "swift/AST/PlatformKind.h" #include "swift/AST/TypeWalker.h" #include <map> using namespace swift; AvailabilityContext AvailabilityContext::forDeploymentTarget(ASTContext &Ctx) { return AvailabilityContext( VersionRange::allGTE(Ctx.LangOpts.getMinPlatformVersion())); } namespace { /// The inferred availability required to access a group of declarations /// on a single platform. struct InferredAvailability { PlatformAgnosticAvailabilityKind PlatformAgnostic = PlatformAgnosticAvailabilityKind::None; Optional<llvm::VersionTuple> Introduced; Optional<llvm::VersionTuple> Deprecated; Optional<llvm::VersionTuple> Obsoleted; }; /// The type of a function that merges two version tuples. typedef const llvm::VersionTuple &(*MergeFunction)( const llvm::VersionTuple &, const llvm::VersionTuple &); } // end anonymous namespace /// Apply a merge function to two optional versions, returning the result /// in Inferred. static void mergeIntoInferredVersion(const Optional<llvm::VersionTuple> &Version, Optional<llvm::VersionTuple> &Inferred, MergeFunction Merge) { if (Version.hasValue()) { if (Inferred.hasValue()) { Inferred = Merge(Inferred.getValue(), Version.getValue()); } else { Inferred = Version; } } } /// Merge an attribute's availability with an existing inferred availability /// so that the new inferred availability is at least as available as /// the attribute requires. static void mergeWithInferredAvailability(const AvailableAttr *Attr, InferredAvailability &Inferred) { Inferred.PlatformAgnostic = static_cast<PlatformAgnosticAvailabilityKind>( std::max(static_cast<unsigned>(Inferred.PlatformAgnostic), static_cast<unsigned>(Attr->getPlatformAgnosticAvailability()))); // The merge of two introduction versions is the maximum of the two versions. mergeIntoInferredVersion(Attr->Introduced, Inferred.Introduced, std::max); // The merge of deprecated and obsoleted versions takes the minimum. mergeIntoInferredVersion(Attr->Deprecated, Inferred.Deprecated, std::min); mergeIntoInferredVersion(Attr->Obsoleted, Inferred.Obsoleted, std::min); } /// Create an implicit availability attribute for the given platform /// and with the inferred availability. static AvailableAttr * createAvailableAttr(PlatformKind Platform, const InferredAvailability &Inferred, ASTContext &Context) { llvm::VersionTuple Introduced = Inferred.Introduced.getValueOr(llvm::VersionTuple()); llvm::VersionTuple Deprecated = Inferred.Deprecated.getValueOr(llvm::VersionTuple()); llvm::VersionTuple Obsoleted = Inferred.Obsoleted.getValueOr(llvm::VersionTuple()); return new (Context) AvailableAttr( SourceLoc(), SourceRange(), Platform, /*Message=*/StringRef(), /*Rename=*/StringRef(), Introduced, /*IntroducedRange=*/SourceRange(), Deprecated, /*DeprecatedRange=*/SourceRange(), Obsoleted, /*ObsoletedRange=*/SourceRange(), Inferred.PlatformAgnostic, /*Implicit=*/true); } void AvailabilityInference::applyInferredAvailableAttrs( Decl *ToDecl, ArrayRef<const Decl *> InferredFromDecls, ASTContext &Context) { // Iterate over the declarations and infer required availability on // a per-platform basis. std::map<PlatformKind, InferredAvailability> Inferred; for (const Decl *D : InferredFromDecls) { for (const DeclAttribute *Attr : D->getAttrs()) { auto *AvAttr = dyn_cast<AvailableAttr>(Attr); if (!AvAttr || AvAttr->isInvalid()) continue; mergeWithInferredAvailability(AvAttr, Inferred[AvAttr->Platform]); } } // Create an availability attribute for each observed platform and add // to ToDecl. DeclAttributes &Attrs = ToDecl->getAttrs(); for (auto &Pair : Inferred) { auto *Attr = createAvailableAttr(Pair.first, Pair.second, Context); Attrs.add(Attr); } } Optional<AvailabilityContext> AvailabilityInference::annotatedAvailableRange(const Decl *D, ASTContext &Ctx) { const AvailableAttr *bestAvailAttr = nullptr; for (auto Attr : D->getAttrs()) { auto *AvailAttr = dyn_cast<AvailableAttr>(Attr); if (AvailAttr == nullptr || !AvailAttr->Introduced.hasValue() || !AvailAttr->isActivePlatform(Ctx) || AvailAttr->isLanguageVersionSpecific() || AvailAttr->isPackageDescriptionVersionSpecific()) { continue; } // Okay, we have a candidate, but is it better than one we already found? if (!bestAvailAttr || inheritsAvailabilityFromPlatform(AvailAttr->Platform, bestAvailAttr->Platform)) { bestAvailAttr = AvailAttr; } } if (!bestAvailAttr) return None; return AvailabilityContext{ VersionRange::allGTE(bestAvailAttr->Introduced.getValue())}; } AvailabilityContext AvailabilityInference::availableRange(const Decl *D, ASTContext &Ctx) { Optional<AvailabilityContext> AnnotatedRange = annotatedAvailableRange(D, Ctx); if (AnnotatedRange.hasValue()) { return AnnotatedRange.getValue(); } // Unlike other declarations, extensions can be used without referring to them // by name (they don't have one) in the source. For this reason, when checking // the available range of a declaration we also need to check to see if it is // immediately contained in an extension and use the extension's availability // if the declaration does not have an explicit @available attribute // itself. This check relies on the fact that we cannot have nested // extensions. DeclContext *DC = D->getDeclContext(); if (auto *ED = dyn_cast<ExtensionDecl>(DC)) { AnnotatedRange = annotatedAvailableRange(ED, Ctx); if (AnnotatedRange.hasValue()) { return AnnotatedRange.getValue(); } } // Treat unannotated declarations as always available. return AvailabilityContext::alwaysAvailable(); } namespace { /// Infers the availability required to access a type. class AvailabilityInferenceTypeWalker : public TypeWalker { public: ASTContext &AC; AvailabilityContext AvailabilityInfo = AvailabilityContext::alwaysAvailable(); AvailabilityInferenceTypeWalker(ASTContext &AC) : AC(AC) {} Action walkToTypePre(Type ty) override { if (auto *nominalDecl = ty->getAnyNominal()) { AvailabilityInfo.intersectWith( AvailabilityInference::availableRange(nominalDecl, AC)); } return Action::Continue; } }; } // end anonymous namespace AvailabilityContext AvailabilityInference::inferForType(Type t) { AvailabilityInferenceTypeWalker walker(t->getASTContext()); t.walk(walker); return walker.AvailabilityInfo; } AvailabilityContext ASTContext::getObjCMetadataUpdateCallbackAvailability() { return getSwift50Availability(); } AvailabilityContext ASTContext::getObjCGetClassHookAvailability() { return getSwift50Availability(); } AvailabilityContext ASTContext::getSwift50Availability() { auto target = LangOpts.Target; if (target.getArchName() == "arm64e") return AvailabilityContext::alwaysAvailable(); if (target.isMacOSX()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(10,14,4))); } else if (target.isiOS()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(12,2))); } else if (target.isWatchOS()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(5,2))); } else { return AvailabilityContext::alwaysAvailable(); } } AvailabilityContext ASTContext::getOpaqueTypeAvailability() { return getSwift51Availability(); } AvailabilityContext ASTContext::getObjCClassStubsAvailability() { return getSwift51Availability(); } AvailabilityContext ASTContext::getSwift51Availability() { auto target = LangOpts.Target; if (target.getArchName() == "arm64e") return AvailabilityContext::alwaysAvailable(); if (target.isMacOSX()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(10,15,0))); } else if (target.isiOS()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(13,0,0))); } else if (target.isWatchOS()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(6,0,0))); } else { return AvailabilityContext::alwaysAvailable(); } } AvailabilityContext ASTContext::getTypesInAbstractMetadataStateAvailability() { return getSwift52Availability(); } AvailabilityContext ASTContext::getPrespecializedGenericMetadataAvailability() { return getSwift53Availability(); } AvailabilityContext ASTContext::getSwift52Availability() { auto target = LangOpts.Target; if (target.getArchName() == "arm64e") return AvailabilityContext::alwaysAvailable(); if (target.isMacOSX() ) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(10, 99, 0))); } else if (target.isiOS()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(99, 0, 0))); } else if (target.isWatchOS()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(9, 99, 0))); } else { return AvailabilityContext::alwaysAvailable(); } } AvailabilityContext ASTContext::getSwift53Availability() { auto target = LangOpts.Target; if (target.getArchName() == "arm64e") return AvailabilityContext::alwaysAvailable(); if (target.isMacOSX() ) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(10, 99, 0))); } else if (target.isiOS()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(99, 0, 0))); } else if (target.isWatchOS()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(9, 99, 0))); } else { return AvailabilityContext::alwaysAvailable(); } } AvailabilityContext ASTContext::getSwiftFutureAvailability() { auto target = LangOpts.Target; if (target.isMacOSX() ) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(10, 99, 0))); } else if (target.isiOS()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(99, 0, 0))); } else if (target.isWatchOS()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(9, 99, 0))); } else { return AvailabilityContext::alwaysAvailable(); } }
//===--- Availability.cpp - Swift Availability Structures -----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file defines data structures for API availability. // //===----------------------------------------------------------------------===// #include "swift/AST/ASTContext.h" #include "swift/AST/Attr.h" #include "swift/AST/Decl.h" #include "swift/AST/Types.h" #include "swift/AST/Availability.h" #include "swift/AST/PlatformKind.h" #include "swift/AST/TypeWalker.h" #include <map> using namespace swift; AvailabilityContext AvailabilityContext::forDeploymentTarget(ASTContext &Ctx) { return AvailabilityContext( VersionRange::allGTE(Ctx.LangOpts.getMinPlatformVersion())); } namespace { /// The inferred availability required to access a group of declarations /// on a single platform. struct InferredAvailability { PlatformAgnosticAvailabilityKind PlatformAgnostic = PlatformAgnosticAvailabilityKind::None; Optional<llvm::VersionTuple> Introduced; Optional<llvm::VersionTuple> Deprecated; Optional<llvm::VersionTuple> Obsoleted; }; /// The type of a function that merges two version tuples. typedef const llvm::VersionTuple &(*MergeFunction)( const llvm::VersionTuple &, const llvm::VersionTuple &); } // end anonymous namespace /// Apply a merge function to two optional versions, returning the result /// in Inferred. static void mergeIntoInferredVersion(const Optional<llvm::VersionTuple> &Version, Optional<llvm::VersionTuple> &Inferred, MergeFunction Merge) { if (Version.hasValue()) { if (Inferred.hasValue()) { Inferred = Merge(Inferred.getValue(), Version.getValue()); } else { Inferred = Version; } } } /// Merge an attribute's availability with an existing inferred availability /// so that the new inferred availability is at least as available as /// the attribute requires. static void mergeWithInferredAvailability(const AvailableAttr *Attr, InferredAvailability &Inferred) { Inferred.PlatformAgnostic = static_cast<PlatformAgnosticAvailabilityKind>( std::max(static_cast<unsigned>(Inferred.PlatformAgnostic), static_cast<unsigned>(Attr->getPlatformAgnosticAvailability()))); // The merge of two introduction versions is the maximum of the two versions. mergeIntoInferredVersion(Attr->Introduced, Inferred.Introduced, std::max); // The merge of deprecated and obsoleted versions takes the minimum. mergeIntoInferredVersion(Attr->Deprecated, Inferred.Deprecated, std::min); mergeIntoInferredVersion(Attr->Obsoleted, Inferred.Obsoleted, std::min); } /// Create an implicit availability attribute for the given platform /// and with the inferred availability. static AvailableAttr * createAvailableAttr(PlatformKind Platform, const InferredAvailability &Inferred, ASTContext &Context) { llvm::VersionTuple Introduced = Inferred.Introduced.getValueOr(llvm::VersionTuple()); llvm::VersionTuple Deprecated = Inferred.Deprecated.getValueOr(llvm::VersionTuple()); llvm::VersionTuple Obsoleted = Inferred.Obsoleted.getValueOr(llvm::VersionTuple()); return new (Context) AvailableAttr( SourceLoc(), SourceRange(), Platform, /*Message=*/StringRef(), /*Rename=*/StringRef(), Introduced, /*IntroducedRange=*/SourceRange(), Deprecated, /*DeprecatedRange=*/SourceRange(), Obsoleted, /*ObsoletedRange=*/SourceRange(), Inferred.PlatformAgnostic, /*Implicit=*/true); } void AvailabilityInference::applyInferredAvailableAttrs( Decl *ToDecl, ArrayRef<const Decl *> InferredFromDecls, ASTContext &Context) { // Iterate over the declarations and infer required availability on // a per-platform basis. std::map<PlatformKind, InferredAvailability> Inferred; for (const Decl *D : InferredFromDecls) { for (const DeclAttribute *Attr : D->getAttrs()) { auto *AvAttr = dyn_cast<AvailableAttr>(Attr); if (!AvAttr || AvAttr->isInvalid()) continue; mergeWithInferredAvailability(AvAttr, Inferred[AvAttr->Platform]); } } // Create an availability attribute for each observed platform and add // to ToDecl. DeclAttributes &Attrs = ToDecl->getAttrs(); for (auto &Pair : Inferred) { auto *Attr = createAvailableAttr(Pair.first, Pair.second, Context); Attrs.add(Attr); } } /// Returns true if the introduced version in \p newAttr should be used instead /// of the introduced version in \p prevAttr when both are attached to the same /// declaration and refer to the active platform. static bool isBetterThan(const AvailableAttr *newAttr, const AvailableAttr *prevAttr) { assert(newAttr); // If there is no prevAttr, newAttr of course wins. if (!prevAttr) return true; // If they belong to the same platform, the one that introduces later wins. if (prevAttr->Platform == newAttr->Platform) return prevAttr->Introduced.getValue() < newAttr->Introduced.getValue(); // If the new attribute's platform inherits from the old one, it wins. return inheritsAvailabilityFromPlatform(newAttr->Platform, prevAttr->Platform); } Optional<AvailabilityContext> AvailabilityInference::annotatedAvailableRange(const Decl *D, ASTContext &Ctx) { const AvailableAttr *bestAvailAttr = nullptr; for (auto Attr : D->getAttrs()) { auto *AvailAttr = dyn_cast<AvailableAttr>(Attr); if (AvailAttr == nullptr || !AvailAttr->Introduced.hasValue() || !AvailAttr->isActivePlatform(Ctx) || AvailAttr->isLanguageVersionSpecific() || AvailAttr->isPackageDescriptionVersionSpecific()) { continue; } if (isBetterThan(AvailAttr, bestAvailAttr)) bestAvailAttr = AvailAttr; } if (!bestAvailAttr) return None; return AvailabilityContext{ VersionRange::allGTE(bestAvailAttr->Introduced.getValue())}; } AvailabilityContext AvailabilityInference::availableRange(const Decl *D, ASTContext &Ctx) { Optional<AvailabilityContext> AnnotatedRange = annotatedAvailableRange(D, Ctx); if (AnnotatedRange.hasValue()) { return AnnotatedRange.getValue(); } // Unlike other declarations, extensions can be used without referring to them // by name (they don't have one) in the source. For this reason, when checking // the available range of a declaration we also need to check to see if it is // immediately contained in an extension and use the extension's availability // if the declaration does not have an explicit @available attribute // itself. This check relies on the fact that we cannot have nested // extensions. DeclContext *DC = D->getDeclContext(); if (auto *ED = dyn_cast<ExtensionDecl>(DC)) { AnnotatedRange = annotatedAvailableRange(ED, Ctx); if (AnnotatedRange.hasValue()) { return AnnotatedRange.getValue(); } } // Treat unannotated declarations as always available. return AvailabilityContext::alwaysAvailable(); } namespace { /// Infers the availability required to access a type. class AvailabilityInferenceTypeWalker : public TypeWalker { public: ASTContext &AC; AvailabilityContext AvailabilityInfo = AvailabilityContext::alwaysAvailable(); AvailabilityInferenceTypeWalker(ASTContext &AC) : AC(AC) {} Action walkToTypePre(Type ty) override { if (auto *nominalDecl = ty->getAnyNominal()) { AvailabilityInfo.intersectWith( AvailabilityInference::availableRange(nominalDecl, AC)); } return Action::Continue; } }; } // end anonymous namespace AvailabilityContext AvailabilityInference::inferForType(Type t) { AvailabilityInferenceTypeWalker walker(t->getASTContext()); t.walk(walker); return walker.AvailabilityInfo; } AvailabilityContext ASTContext::getObjCMetadataUpdateCallbackAvailability() { return getSwift50Availability(); } AvailabilityContext ASTContext::getObjCGetClassHookAvailability() { return getSwift50Availability(); } AvailabilityContext ASTContext::getSwift50Availability() { auto target = LangOpts.Target; if (target.getArchName() == "arm64e") return AvailabilityContext::alwaysAvailable(); if (target.isMacOSX()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(10,14,4))); } else if (target.isiOS()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(12,2))); } else if (target.isWatchOS()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(5,2))); } else { return AvailabilityContext::alwaysAvailable(); } } AvailabilityContext ASTContext::getOpaqueTypeAvailability() { return getSwift51Availability(); } AvailabilityContext ASTContext::getObjCClassStubsAvailability() { return getSwift51Availability(); } AvailabilityContext ASTContext::getSwift51Availability() { auto target = LangOpts.Target; if (target.getArchName() == "arm64e") return AvailabilityContext::alwaysAvailable(); if (target.isMacOSX()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(10,15,0))); } else if (target.isiOS()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(13,0,0))); } else if (target.isWatchOS()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(6,0,0))); } else { return AvailabilityContext::alwaysAvailable(); } } AvailabilityContext ASTContext::getTypesInAbstractMetadataStateAvailability() { return getSwift52Availability(); } AvailabilityContext ASTContext::getPrespecializedGenericMetadataAvailability() { return getSwift53Availability(); } AvailabilityContext ASTContext::getSwift52Availability() { auto target = LangOpts.Target; if (target.getArchName() == "arm64e") return AvailabilityContext::alwaysAvailable(); if (target.isMacOSX() ) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(10, 99, 0))); } else if (target.isiOS()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(99, 0, 0))); } else if (target.isWatchOS()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(9, 99, 0))); } else { return AvailabilityContext::alwaysAvailable(); } } AvailabilityContext ASTContext::getSwift53Availability() { auto target = LangOpts.Target; if (target.getArchName() == "arm64e") return AvailabilityContext::alwaysAvailable(); if (target.isMacOSX() ) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(10, 99, 0))); } else if (target.isiOS()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(99, 0, 0))); } else if (target.isWatchOS()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(9, 99, 0))); } else { return AvailabilityContext::alwaysAvailable(); } } AvailabilityContext ASTContext::getSwiftFutureAvailability() { auto target = LangOpts.Target; if (target.isMacOSX() ) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(10, 99, 0))); } else if (target.isiOS()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(99, 0, 0))); } else if (target.isWatchOS()) { return AvailabilityContext( VersionRange::allGTE(llvm::VersionTuple(9, 99, 0))); } else { return AvailabilityContext::alwaysAvailable(); } }
Handle multiple @available attributes correctly
Handle multiple @available attributes correctly The previous commit broke a promise made by the implementation it replaced: if there were two or more @available(introduced:) attributes for the same platform, the greatest version wins. This commit restores that property while still completely overriding the parent platform’s availability with a child platform’s.
C++
apache-2.0
rudkx/swift,harlanhaskins/swift,airspeedswift/swift,stephentyrone/swift,benlangmuir/swift,airspeedswift/swift,aschwaighofer/swift,aschwaighofer/swift,CodaFi/swift,roambotics/swift,atrick/swift,roambotics/swift,JGiola/swift,jmgc/swift,allevato/swift,rudkx/swift,xwu/swift,tkremenek/swift,xwu/swift,ahoppen/swift,roambotics/swift,aschwaighofer/swift,tkremenek/swift,JGiola/swift,nathawes/swift,parkera/swift,allevato/swift,aschwaighofer/swift,hooman/swift,gregomni/swift,tkremenek/swift,harlanhaskins/swift,nathawes/swift,apple/swift,CodaFi/swift,tkremenek/swift,roambotics/swift,tkremenek/swift,apple/swift,gregomni/swift,nathawes/swift,parkera/swift,xwu/swift,JGiola/swift,apple/swift,jckarter/swift,allevato/swift,glessard/swift,parkera/swift,apple/swift,nathawes/swift,ahoppen/swift,jckarter/swift,roambotics/swift,apple/swift,allevato/swift,CodaFi/swift,airspeedswift/swift,CodaFi/swift,parkera/swift,xwu/swift,JGiola/swift,benlangmuir/swift,roambotics/swift,nathawes/swift,glessard/swift,allevato/swift,atrick/swift,harlanhaskins/swift,jckarter/swift,jckarter/swift,rudkx/swift,harlanhaskins/swift,jmgc/swift,glessard/swift,atrick/swift,rudkx/swift,stephentyrone/swift,CodaFi/swift,jmgc/swift,stephentyrone/swift,parkera/swift,harlanhaskins/swift,jmgc/swift,jckarter/swift,stephentyrone/swift,jmgc/swift,hooman/swift,parkera/swift,parkera/swift,xwu/swift,jmgc/swift,hooman/swift,benlangmuir/swift,aschwaighofer/swift,stephentyrone/swift,allevato/swift,stephentyrone/swift,aschwaighofer/swift,rudkx/swift,gregomni/swift,ahoppen/swift,gregomni/swift,hooman/swift,ahoppen/swift,glessard/swift,airspeedswift/swift,stephentyrone/swift,xwu/swift,jckarter/swift,ahoppen/swift,atrick/swift,rudkx/swift,jmgc/swift,glessard/swift,airspeedswift/swift,nathawes/swift,JGiola/swift,harlanhaskins/swift,JGiola/swift,xwu/swift,gregomni/swift,CodaFi/swift,benlangmuir/swift,atrick/swift,CodaFi/swift,parkera/swift,allevato/swift,apple/swift,benlangmuir/swift,benlangmuir/swift,harlanhaskins/swift,atrick/swift,tkremenek/swift,ahoppen/swift,airspeedswift/swift,hooman/swift,airspeedswift/swift,jckarter/swift,hooman/swift,nathawes/swift,aschwaighofer/swift,hooman/swift,gregomni/swift,tkremenek/swift,glessard/swift
1cdfb45d9072458714604e146fb616b2494fcd4c
chrome/browser/dock_info_gtk.cc
chrome/browser/dock_info_gtk.cc
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/dock_info.h" #include <gtk/gtk.h> #include "base/gfx/native_widget_types.h" #include "base/logging.h" #include "base/task.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/gtk/browser_window_gtk.h" #include "chrome/common/gtk_util.h" //////////////////////////////////////////////////////////////////////////////// // BaseWindowFinder // // Base class used to locate a window. A subclass need only override // ShouldStopIterating to determine when iteration should stop. class BaseWindowFinder : public x11_util::EnumerateWindowsDelegate { public: explicit BaseWindowFinder(const std::set<GtkWidget*>& ignore) { std::set<GtkWidget*>::iterator iter; for (iter = ignore.begin(); iter != ignore.end(); iter++) { XID xid = x11_util::GetX11WindowFromGtkWidget(*iter); ignore_.insert(xid); } } virtual ~BaseWindowFinder() {} protected: // Returns true if |window| is in the ignore list. bool ShouldIgnoreWindow(XID window) { return (ignore_.find(window) != ignore_.end()); } // Returns true if iteration should stop, false otherwise. virtual bool ShouldStopIterating(XID window) { return false; } private: std::set<XID> ignore_; DISALLOW_COPY_AND_ASSIGN(BaseWindowFinder); }; //////////////////////////////////////////////////////////////////////////////// // TopMostFinder // // Helper class to determine if a particular point of a window is not obscured // by another window. class TopMostFinder : public BaseWindowFinder { public: // Returns true if |window| is not obscured by another window at the // location |screen_loc|, not including the windows in |ignore|. static bool IsTopMostWindowAtPoint(XID window, const gfx::Point& screen_loc, const std::set<GtkWidget*>& ignore) { TopMostFinder finder(window, screen_loc, ignore); return finder.is_top_most_; } protected: virtual bool ShouldStopIterating(XID window) { if (BaseWindowFinder::ShouldIgnoreWindow(window)) return false; if (window == target_) { // Window is topmost, stop iterating. is_top_most_ = true; return true; } if (x11_util::IsWindowVisible(window)) { // The window isn't visible, keep iterating. return false; } gfx::Rect rect; if (x11_util::GetWindowRect(window, &rect) && rect.Contains(screen_loc_)) { // At this point we haven't found our target window, so this window is // higher in the z-order than the target window. If this window contains // the point, then we can stop the search now because this window is // obscuring the target window at this point. return true; } return false; } private: TopMostFinder(XID window, const gfx::Point& screen_loc, const std::set<GtkWidget*>& ignore) : BaseWindowFinder(ignore), target_(window), screen_loc_(screen_loc), is_top_most_(false) { gtk_util::EnumerateTopLevelWindows(this); } // The window we're looking for. XID target_; // Location of window to find. gfx::Point screen_loc_; // Is target_ the top most window? This is initially false but set to true // in ShouldStopIterating if target_ is passed in. bool is_top_most_; DISALLOW_COPY_AND_ASSIGN(TopMostFinder); }; //////////////////////////////////////////////////////////////////////////////// // LocalProcessWindowFinder // // Helper class to determine if a particular point of a window from our process // is not obscured by another window. class LocalProcessWindowFinder : public BaseWindowFinder { public: // Returns the XID from our process at screen_loc that is not obscured by // another window. Returns 0 otherwise. static XID GetProcessWindowAtPoint(const gfx::Point& screen_loc, const std::set<GtkWidget*>& ignore) { LocalProcessWindowFinder finder(screen_loc, ignore); if (finder.result_ && TopMostFinder::IsTopMostWindowAtPoint(finder.result_, screen_loc, ignore)) { return finder.result_; } return 0; } protected: virtual bool ShouldStopIterating(XID window) { if (BaseWindowFinder::ShouldIgnoreWindow(window)) return false; // Check if this window is in our process. if (!BrowserWindowGtk::GetBrowserWindowForXID(window)) return false; if (!x11_util::IsWindowVisible(window)) return false; gfx::Rect rect; if (x11_util::GetWindowRect(window, &rect) && rect.Contains(screen_loc_)) { result_ = window; return true; } return false; } private: LocalProcessWindowFinder(const gfx::Point& screen_loc, const std::set<GtkWidget*>& ignore) : BaseWindowFinder(ignore), screen_loc_(screen_loc), result_(0) { gtk_util::EnumerateTopLevelWindows(this); } // Position of the mouse. gfx::Point screen_loc_; // The resulting window. This is initially null but set to true in // ShouldStopIterating if an appropriate window is found. XID result_; DISALLOW_COPY_AND_ASSIGN(LocalProcessWindowFinder); }; // static DockInfo DockInfo::GetDockInfoAtPoint(const gfx::Point& screen_point, const std::set<GtkWidget*>& ignore) { if (factory_) return factory_->GetDockInfoAtPoint(screen_point, ignore); NOTIMPLEMENTED(); return DockInfo(); } // static GtkWindow* DockInfo::GetLocalProcessWindowAtPoint( const gfx::Point& screen_point, const std::set<GtkWidget*>& ignore) { if (factory_) return factory_->GetLocalProcessWindowAtPoint(screen_point, ignore); #if !defined(TOOLKIT_VIEWS) XID xid = LocalProcessWindowFinder::GetProcessWindowAtPoint(screen_point, ignore); return BrowserWindowGtk::GetBrowserWindowForXID(xid); #else return NULL; #endif } bool DockInfo::GetWindowBounds(gfx::Rect* bounds) const { if (!window()) return false; int x, y, w, h; gtk_window_get_position(window(), &x, &y); gtk_window_get_size(window(), &w, &h); bounds->SetRect(x, y, w, h); return true; } void DockInfo::SizeOtherWindowTo(const gfx::Rect& bounds) const { gtk_window_move(window(), bounds.x(), bounds.y()); gtk_window_resize(window(), bounds.width(), bounds.height()); }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/dock_info.h" #include <gtk/gtk.h> #include "base/gfx/native_widget_types.h" #include "base/logging.h" #include "base/task.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/gtk/browser_window_gtk.h" #include "chrome/common/gtk_util.h" //////////////////////////////////////////////////////////////////////////////// // BaseWindowFinder // // Base class used to locate a window. A subclass need only override // ShouldStopIterating to determine when iteration should stop. class BaseWindowFinder : public x11_util::EnumerateWindowsDelegate { public: explicit BaseWindowFinder(const std::set<GtkWidget*>& ignore) { std::set<GtkWidget*>::iterator iter; for (iter = ignore.begin(); iter != ignore.end(); iter++) { XID xid = x11_util::GetX11WindowFromGtkWidget(*iter); ignore_.insert(xid); } } virtual ~BaseWindowFinder() {} protected: // Returns true if |window| is in the ignore list. bool ShouldIgnoreWindow(XID window) { return (ignore_.find(window) != ignore_.end()); } // Returns true if iteration should stop, false otherwise. virtual bool ShouldStopIterating(XID window) { return false; } private: std::set<XID> ignore_; DISALLOW_COPY_AND_ASSIGN(BaseWindowFinder); }; //////////////////////////////////////////////////////////////////////////////// // TopMostFinder // // Helper class to determine if a particular point of a window is not obscured // by another window. class TopMostFinder : public BaseWindowFinder { public: // Returns true if |window| is not obscured by another window at the // location |screen_loc|, not including the windows in |ignore|. static bool IsTopMostWindowAtPoint(XID window, const gfx::Point& screen_loc, const std::set<GtkWidget*>& ignore) { TopMostFinder finder(window, screen_loc, ignore); return finder.is_top_most_; } protected: virtual bool ShouldStopIterating(XID window) { if (BaseWindowFinder::ShouldIgnoreWindow(window)) return false; if (window == target_) { // Window is topmost, stop iterating. is_top_most_ = true; return true; } if (!x11_util::IsWindowVisible(window)) { // The window isn't visible, keep iterating. return false; } gfx::Rect rect; if (x11_util::GetWindowRect(window, &rect) && rect.Contains(screen_loc_)) { // At this point we haven't found our target window, so this window is // higher in the z-order than the target window. If this window contains // the point, then we can stop the search now because this window is // obscuring the target window at this point. return true; } return false; } private: TopMostFinder(XID window, const gfx::Point& screen_loc, const std::set<GtkWidget*>& ignore) : BaseWindowFinder(ignore), target_(window), screen_loc_(screen_loc), is_top_most_(false) { gtk_util::EnumerateTopLevelWindows(this); } // The window we're looking for. XID target_; // Location of window to find. gfx::Point screen_loc_; // Is target_ the top most window? This is initially false but set to true // in ShouldStopIterating if target_ is passed in. bool is_top_most_; DISALLOW_COPY_AND_ASSIGN(TopMostFinder); }; //////////////////////////////////////////////////////////////////////////////// // LocalProcessWindowFinder // // Helper class to determine if a particular point of a window from our process // is not obscured by another window. class LocalProcessWindowFinder : public BaseWindowFinder { public: // Returns the XID from our process at screen_loc that is not obscured by // another window. Returns 0 otherwise. static XID GetProcessWindowAtPoint(const gfx::Point& screen_loc, const std::set<GtkWidget*>& ignore) { LocalProcessWindowFinder finder(screen_loc, ignore); if (finder.result_ && TopMostFinder::IsTopMostWindowAtPoint(finder.result_, screen_loc, ignore)) { return finder.result_; } return 0; } protected: virtual bool ShouldStopIterating(XID window) { if (BaseWindowFinder::ShouldIgnoreWindow(window)) return false; // Check if this window is in our process. if (!BrowserWindowGtk::GetBrowserWindowForXID(window)) return false; if (!x11_util::IsWindowVisible(window)) return false; gfx::Rect rect; if (x11_util::GetWindowRect(window, &rect) && rect.Contains(screen_loc_)) { result_ = window; return true; } return false; } private: LocalProcessWindowFinder(const gfx::Point& screen_loc, const std::set<GtkWidget*>& ignore) : BaseWindowFinder(ignore), screen_loc_(screen_loc), result_(0) { gtk_util::EnumerateTopLevelWindows(this); } // Position of the mouse. gfx::Point screen_loc_; // The resulting window. This is initially null but set to true in // ShouldStopIterating if an appropriate window is found. XID result_; DISALLOW_COPY_AND_ASSIGN(LocalProcessWindowFinder); }; // static DockInfo DockInfo::GetDockInfoAtPoint(const gfx::Point& screen_point, const std::set<GtkWidget*>& ignore) { if (factory_) return factory_->GetDockInfoAtPoint(screen_point, ignore); NOTIMPLEMENTED(); return DockInfo(); } // static GtkWindow* DockInfo::GetLocalProcessWindowAtPoint( const gfx::Point& screen_point, const std::set<GtkWidget*>& ignore) { if (factory_) return factory_->GetLocalProcessWindowAtPoint(screen_point, ignore); #if !defined(TOOLKIT_VIEWS) XID xid = LocalProcessWindowFinder::GetProcessWindowAtPoint(screen_point, ignore); return BrowserWindowGtk::GetBrowserWindowForXID(xid); #else return NULL; #endif } bool DockInfo::GetWindowBounds(gfx::Rect* bounds) const { if (!window()) return false; int x, y, w, h; gtk_window_get_position(window(), &x, &y); gtk_window_get_size(window(), &w, &h); bounds->SetRect(x, y, w, h); return true; } void DockInfo::SizeOtherWindowTo(const gfx::Rect& bounds) const { gtk_window_move(window(), bounds.x(), bounds.y()); gtk_window_resize(window(), bounds.width(), bounds.height()); }
Fix a typo that breaks tab dragging when another gtk window is minimized.
gtk: Fix a typo that breaks tab dragging when another gtk window is minimized. BUG=20228,20513 TEST=Extensive tab dragging. Review URL: http://codereview.chromium.org/182034 git-svn-id: http://src.chromium.org/svn/trunk/src@25007 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: 3db9613620f226517fec87b3d982c8187643bbbf
C++
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
c56b552ff209f9b5ccd81c078dbbadb948eb711e
lib/CodeGen/CGCXXABI.cpp
lib/CodeGen/CGCXXABI.cpp
//===----- CGCXXABI.cpp - Interface to C++ ABIs -----------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This provides an abstract class for C++ code generation. Concrete subclasses // of this implement code generation for specific C++ ABIs. // //===----------------------------------------------------------------------===// #include "CGCXXABI.h" using namespace clang; using namespace CodeGen; CGCXXABI::~CGCXXABI() { } static void ErrorUnsupportedABI(CodeGenFunction &CGF, StringRef S) { DiagnosticsEngine &Diags = CGF.CGM.getDiags(); unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "cannot yet compile %1 in this ABI"); Diags.Report(CGF.getContext().getFullLoc(CGF.CurCodeDecl->getLocation()), DiagID) << S; } static llvm::Constant *GetBogusMemberPointer(CodeGenModule &CGM, QualType T) { return llvm::Constant::getNullValue(CGM.getTypes().ConvertType(T)); } llvm::Type * CGCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { return CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType()); } llvm::Value *CGCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, llvm::Value *&This, llvm::Value *MemPtr, const MemberPointerType *MPT) { ErrorUnsupportedABI(CGF, "calls through member pointers"); const FunctionProtoType *FPT = MPT->getPointeeType()->getAs<FunctionProtoType>(); const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType( CGM.getTypes().arrangeCXXMethodType(RD, FPT)); return llvm::Constant::getNullValue(FTy->getPointerTo()); } llvm::Value *CGCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF, llvm::Value *Base, llvm::Value *MemPtr, const MemberPointerType *MPT) { ErrorUnsupportedABI(CGF, "loads of member pointers"); llvm::Type *Ty = CGF.ConvertType(MPT->getPointeeType())->getPointerTo(); return llvm::Constant::getNullValue(Ty); } llvm::Value *CGCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF, const CastExpr *E, llvm::Value *Src) { ErrorUnsupportedABI(CGF, "member function pointer conversions"); return GetBogusMemberPointer(CGM, E->getType()); } llvm::Constant *CGCXXABI::EmitMemberPointerConversion(const CastExpr *E, llvm::Constant *Src) { return GetBogusMemberPointer(CGM, E->getType()); } llvm::Value * CGCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF, llvm::Value *L, llvm::Value *R, const MemberPointerType *MPT, bool Inequality) { ErrorUnsupportedABI(CGF, "member function pointer comparison"); return CGF.Builder.getFalse(); } llvm::Value * CGCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF, llvm::Value *MemPtr, const MemberPointerType *MPT) { ErrorUnsupportedABI(CGF, "member function pointer null testing"); return CGF.Builder.getFalse(); } llvm::Constant * CGCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) { return GetBogusMemberPointer(CGM, QualType(MPT, 0)); } llvm::Constant *CGCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) { return GetBogusMemberPointer(CGM, CGM.getContext().getMemberPointerType(MD->getType(), MD->getParent()->getTypeForDecl())); } llvm::Constant *CGCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT, CharUnits offset) { return GetBogusMemberPointer(CGM, QualType(MPT, 0)); } llvm::Constant *CGCXXABI::EmitMemberPointer(const APValue &MP, QualType MPT) { return GetBogusMemberPointer(CGM, MPT); } bool CGCXXABI::isZeroInitializable(const MemberPointerType *MPT) { // Fake answer. return true; } void CGCXXABI::BuildThisParam(CodeGenFunction &CGF, FunctionArgList &params) { const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); // FIXME: I'm not entirely sure I like using a fake decl just for code // generation. Maybe we can come up with a better way? ImplicitParamDecl *ThisDecl = ImplicitParamDecl::Create(CGM.getContext(), 0, MD->getLocation(), &CGM.getContext().Idents.get("this"), MD->getThisType(CGM.getContext())); params.push_back(ThisDecl); getThisDecl(CGF) = ThisDecl; } void CGCXXABI::EmitThisParam(CodeGenFunction &CGF) { /// Initialize the 'this' slot. assert(getThisDecl(CGF) && "no 'this' variable for function"); getThisValue(CGF) = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getThisDecl(CGF)), "this"); } void CGCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResultType) { CGF.EmitReturnOfRValue(RV, ResultType); } CharUnits CGCXXABI::GetArrayCookieSize(const CXXNewExpr *expr) { if (!requiresArrayCookie(expr)) return CharUnits::Zero(); return getArrayCookieSizeImpl(expr->getAllocatedType()); } CharUnits CGCXXABI::getArrayCookieSizeImpl(QualType elementType) { // BOGUS return CharUnits::Zero(); } llvm::Value *CGCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, llvm::Value *NewPtr, llvm::Value *NumElements, const CXXNewExpr *expr, QualType ElementType) { // Should never be called. ErrorUnsupportedABI(CGF, "array cookie initialization"); return 0; } bool CGCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType) { // If the class's usual deallocation function takes two arguments, // it needs a cookie. if (expr->doesUsualArrayDeleteWantSize()) return true; return elementType.isDestructedType(); } bool CGCXXABI::requiresArrayCookie(const CXXNewExpr *expr) { // If the class's usual deallocation function takes two arguments, // it needs a cookie. if (expr->doesUsualArrayDeleteWantSize()) return true; return expr->getAllocatedType().isDestructedType(); } void CGCXXABI::ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *ptr, const CXXDeleteExpr *expr, QualType eltTy, llvm::Value *&numElements, llvm::Value *&allocPtr, CharUnits &cookieSize) { // Derive a char* in the same address space as the pointer. unsigned AS = cast<llvm::PointerType>(ptr->getType())->getAddressSpace(); llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS); ptr = CGF.Builder.CreateBitCast(ptr, charPtrTy); // If we don't need an array cookie, bail out early. if (!requiresArrayCookie(expr, eltTy)) { allocPtr = ptr; numElements = 0; cookieSize = CharUnits::Zero(); return; } cookieSize = getArrayCookieSizeImpl(eltTy); allocPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ptr, -cookieSize.getQuantity()); numElements = readArrayCookieImpl(CGF, allocPtr, cookieSize); } llvm::Value *CGCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *ptr, CharUnits cookieSize) { ErrorUnsupportedABI(CGF, "reading a new[] cookie"); return llvm::ConstantInt::get(CGF.SizeTy, 0); } void CGCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, llvm::GlobalVariable *GV, bool PerformInit) { ErrorUnsupportedABI(CGF, "static local variable initialization"); } void CGCXXABI::registerGlobalDtor(CodeGenFunction &CGF, llvm::Constant *dtor, llvm::Constant *addr) { // The default behavior is to use atexit. CGF.registerGlobalDtorWithAtExit(dtor, addr); } /// Returns the adjustment, in bytes, required for the given /// member-pointer operation. Returns null if no adjustment is /// required. llvm::Constant *CGCXXABI::getMemberPointerAdjustment(const CastExpr *E) { assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || E->getCastKind() == CK_BaseToDerivedMemberPointer); QualType derivedType; if (E->getCastKind() == CK_DerivedToBaseMemberPointer) derivedType = E->getSubExpr()->getType(); else derivedType = E->getType(); const CXXRecordDecl *derivedClass = derivedType->castAs<MemberPointerType>()->getClass()->getAsCXXRecordDecl(); return CGM.GetNonVirtualBaseClassOffset(derivedClass, E->path_begin(), E->path_end()); }
//===----- CGCXXABI.cpp - Interface to C++ ABIs -----------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This provides an abstract class for C++ code generation. Concrete subclasses // of this implement code generation for specific C++ ABIs. // //===----------------------------------------------------------------------===// #include "CGCXXABI.h" using namespace clang; using namespace CodeGen; CGCXXABI::~CGCXXABI() { } static void ErrorUnsupportedABI(CodeGenFunction &CGF, StringRef S) { DiagnosticsEngine &Diags = CGF.CGM.getDiags(); unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "cannot yet compile %0 in this ABI"); Diags.Report(CGF.getContext().getFullLoc(CGF.CurCodeDecl->getLocation()), DiagID) << S; } static llvm::Constant *GetBogusMemberPointer(CodeGenModule &CGM, QualType T) { return llvm::Constant::getNullValue(CGM.getTypes().ConvertType(T)); } llvm::Type * CGCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { return CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType()); } llvm::Value *CGCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, llvm::Value *&This, llvm::Value *MemPtr, const MemberPointerType *MPT) { ErrorUnsupportedABI(CGF, "calls through member pointers"); const FunctionProtoType *FPT = MPT->getPointeeType()->getAs<FunctionProtoType>(); const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType( CGM.getTypes().arrangeCXXMethodType(RD, FPT)); return llvm::Constant::getNullValue(FTy->getPointerTo()); } llvm::Value *CGCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF, llvm::Value *Base, llvm::Value *MemPtr, const MemberPointerType *MPT) { ErrorUnsupportedABI(CGF, "loads of member pointers"); llvm::Type *Ty = CGF.ConvertType(MPT->getPointeeType())->getPointerTo(); return llvm::Constant::getNullValue(Ty); } llvm::Value *CGCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF, const CastExpr *E, llvm::Value *Src) { ErrorUnsupportedABI(CGF, "member function pointer conversions"); return GetBogusMemberPointer(CGM, E->getType()); } llvm::Constant *CGCXXABI::EmitMemberPointerConversion(const CastExpr *E, llvm::Constant *Src) { return GetBogusMemberPointer(CGM, E->getType()); } llvm::Value * CGCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF, llvm::Value *L, llvm::Value *R, const MemberPointerType *MPT, bool Inequality) { ErrorUnsupportedABI(CGF, "member function pointer comparison"); return CGF.Builder.getFalse(); } llvm::Value * CGCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF, llvm::Value *MemPtr, const MemberPointerType *MPT) { ErrorUnsupportedABI(CGF, "member function pointer null testing"); return CGF.Builder.getFalse(); } llvm::Constant * CGCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) { return GetBogusMemberPointer(CGM, QualType(MPT, 0)); } llvm::Constant *CGCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) { return GetBogusMemberPointer(CGM, CGM.getContext().getMemberPointerType(MD->getType(), MD->getParent()->getTypeForDecl())); } llvm::Constant *CGCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT, CharUnits offset) { return GetBogusMemberPointer(CGM, QualType(MPT, 0)); } llvm::Constant *CGCXXABI::EmitMemberPointer(const APValue &MP, QualType MPT) { return GetBogusMemberPointer(CGM, MPT); } bool CGCXXABI::isZeroInitializable(const MemberPointerType *MPT) { // Fake answer. return true; } void CGCXXABI::BuildThisParam(CodeGenFunction &CGF, FunctionArgList &params) { const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); // FIXME: I'm not entirely sure I like using a fake decl just for code // generation. Maybe we can come up with a better way? ImplicitParamDecl *ThisDecl = ImplicitParamDecl::Create(CGM.getContext(), 0, MD->getLocation(), &CGM.getContext().Idents.get("this"), MD->getThisType(CGM.getContext())); params.push_back(ThisDecl); getThisDecl(CGF) = ThisDecl; } void CGCXXABI::EmitThisParam(CodeGenFunction &CGF) { /// Initialize the 'this' slot. assert(getThisDecl(CGF) && "no 'this' variable for function"); getThisValue(CGF) = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getThisDecl(CGF)), "this"); } void CGCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResultType) { CGF.EmitReturnOfRValue(RV, ResultType); } CharUnits CGCXXABI::GetArrayCookieSize(const CXXNewExpr *expr) { if (!requiresArrayCookie(expr)) return CharUnits::Zero(); return getArrayCookieSizeImpl(expr->getAllocatedType()); } CharUnits CGCXXABI::getArrayCookieSizeImpl(QualType elementType) { // BOGUS return CharUnits::Zero(); } llvm::Value *CGCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, llvm::Value *NewPtr, llvm::Value *NumElements, const CXXNewExpr *expr, QualType ElementType) { // Should never be called. ErrorUnsupportedABI(CGF, "array cookie initialization"); return 0; } bool CGCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType) { // If the class's usual deallocation function takes two arguments, // it needs a cookie. if (expr->doesUsualArrayDeleteWantSize()) return true; return elementType.isDestructedType(); } bool CGCXXABI::requiresArrayCookie(const CXXNewExpr *expr) { // If the class's usual deallocation function takes two arguments, // it needs a cookie. if (expr->doesUsualArrayDeleteWantSize()) return true; return expr->getAllocatedType().isDestructedType(); } void CGCXXABI::ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *ptr, const CXXDeleteExpr *expr, QualType eltTy, llvm::Value *&numElements, llvm::Value *&allocPtr, CharUnits &cookieSize) { // Derive a char* in the same address space as the pointer. unsigned AS = cast<llvm::PointerType>(ptr->getType())->getAddressSpace(); llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS); ptr = CGF.Builder.CreateBitCast(ptr, charPtrTy); // If we don't need an array cookie, bail out early. if (!requiresArrayCookie(expr, eltTy)) { allocPtr = ptr; numElements = 0; cookieSize = CharUnits::Zero(); return; } cookieSize = getArrayCookieSizeImpl(eltTy); allocPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ptr, -cookieSize.getQuantity()); numElements = readArrayCookieImpl(CGF, allocPtr, cookieSize); } llvm::Value *CGCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *ptr, CharUnits cookieSize) { ErrorUnsupportedABI(CGF, "reading a new[] cookie"); return llvm::ConstantInt::get(CGF.SizeTy, 0); } void CGCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, llvm::GlobalVariable *GV, bool PerformInit) { ErrorUnsupportedABI(CGF, "static local variable initialization"); } void CGCXXABI::registerGlobalDtor(CodeGenFunction &CGF, llvm::Constant *dtor, llvm::Constant *addr) { // The default behavior is to use atexit. CGF.registerGlobalDtorWithAtExit(dtor, addr); } /// Returns the adjustment, in bytes, required for the given /// member-pointer operation. Returns null if no adjustment is /// required. llvm::Constant *CGCXXABI::getMemberPointerAdjustment(const CastExpr *E) { assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || E->getCastKind() == CK_BaseToDerivedMemberPointer); QualType derivedType; if (E->getCastKind() == CK_DerivedToBaseMemberPointer) derivedType = E->getSubExpr()->getType(); else derivedType = E->getType(); const CXXRecordDecl *derivedClass = derivedType->castAs<MemberPointerType>()->getClass()->getAsCXXRecordDecl(); return CGM.GetNonVirtualBaseClassOffset(derivedClass, E->path_begin(), E->path_end()); }
Fix PR13234 - crash when trying to report an unsupported ABI feature
Fix PR13234 - crash when trying to report an unsupported ABI feature git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@159405 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang
fbdab2c0138190bcf8130ad5fc19013f6634123a
libopflex/engine/OpflexPool.cpp
libopflex/engine/OpflexPool.cpp
/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil */ /* * Implementation for OpflexPool * * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ #include <boost/foreach.hpp> #include "opflex/engine/internal/OpflexPool.h" #include "opflex/logging/internal/logging.hpp" #include "LockGuard.h" namespace opflex { namespace engine { namespace internal { using std::make_pair; using std::string; static void async_cb(uv_async_t* handle) { uv_close((uv_handle_t*)handle, NULL); } OpflexPool::OpflexPool(HandlerFactory& factory_) : factory(factory_) { uv_mutex_init(&conn_mutex); } OpflexPool::~OpflexPool() { uv_mutex_destroy(&conn_mutex); } void OpflexPool::start() { uv_loop_init(&client_loop); uv_timer_init(&client_loop, &timer); timer.data = this; uv_timer_start(&timer, timer_cb, 1000, 1000); uv_async_init(&client_loop, &async, async_cb); int rc = uv_thread_create(&client_thread, client_thread_func, this); if (rc < 0) { throw std::runtime_error(string("Could not create client thread: ") + uv_strerror(rc)); } } void OpflexPool::stop() { clear(); uv_timer_stop(&timer); uv_close((uv_handle_t*)&timer, NULL); uv_async_send(&async); uv_thread_join(&client_thread); int rc = uv_loop_close(&client_loop); } void OpflexPool::setOpflexIdentity(const std::string& name, const std::string& domain) { this->name = name; this->domain = domain; } OpflexClientConnection* OpflexPool::getPeer(const std::string& hostname, int port) { util::LockGuard guard(&conn_mutex); conn_map_t::iterator it = connections.find(make_pair(hostname, port)); if (it != connections.end()) { return it->second.conn; } return NULL; } void OpflexPool::addPeer(const std::string& hostname, int port) { util::LockGuard guard(&conn_mutex); ConnData& cd = connections[make_pair(hostname, port)]; if (cd.conn != NULL) { LOG(ERROR) << "Connection for " << hostname << ":" << port << " already exists; not adding peer."; } else { OpflexClientConnection* conn = new OpflexClientConnection(factory, this, hostname, port); cd.conn = conn; conn->connect(); } } void OpflexPool::addPeer(OpflexClientConnection* conn) { util::LockGuard guard(&conn_mutex); ConnData& cd = connections[make_pair(conn->getHostname(), conn->getPort())]; if (cd.conn != NULL) { LOG(ERROR) << "Connection for " << conn->getHostname() << ":" << conn->getPort() << " already exists"; conn->disconnect(); } cd.conn = conn; } void OpflexPool::doRemovePeer(const std::string& hostname, int port) { conn_map_t::iterator it = connections.find(make_pair(hostname, port)); if (it != connections.end()) { if (it->second.conn) { doSetRoles(it->second, 0); } connections.erase(it); } } void OpflexPool::clear() { util::LockGuard guard(&conn_mutex); BOOST_FOREACH(conn_map_t::value_type& v, connections) { v.second.conn->disconnect(); } } // must be called with conn_mutex held void OpflexPool::updateRole(ConnData& cd, uint8_t newroles, OpflexHandler::OpflexRole role) { if (cd.roles & role) { if (!(newroles & role)) { role_map_t::iterator it = roles.find(role); if (it != roles.end()) { if (it->second.curMaster == cd.conn) it->second.curMaster = NULL; it->second.conns.erase(cd.conn); if (it->second.conns.size() == 0) roles.erase(it); } } } else if (newroles & role) { if (!(cd.roles & role)) { conn_set_t& cl = roles[role].conns; cl.insert(cd.conn); } } } void OpflexPool::setRoles(OpflexClientConnection* conn, uint8_t newroles) { util::LockGuard guard(&conn_mutex); ConnData& cd = connections[make_pair(conn->getHostname(), conn->getPort())]; doSetRoles(cd, newroles); } // must be called with conn_mutex held void OpflexPool::doSetRoles(ConnData& cd, uint8_t newroles) { updateRole(cd, newroles, OpflexHandler::POLICY_ELEMENT); updateRole(cd, newroles, OpflexHandler::POLICY_REPOSITORY); updateRole(cd, newroles, OpflexHandler::ENDPOINT_REGISTRY); updateRole(cd, newroles, OpflexHandler::OBSERVER); } OpflexClientConnection* OpflexPool::getMasterForRole(OpflexHandler::OpflexRole role) { util::LockGuard guard(&conn_mutex); role_map_t::iterator it = roles.find(role); if (it == roles.end()) return NULL; if (it->second.curMaster != NULL && it->second.curMaster->isReady()) return it->second.curMaster; BOOST_FOREACH(OpflexClientConnection* conn, it->second.conns) { if (conn->isReady()) { it->second.curMaster = conn; return conn; } } return NULL; } void OpflexPool::client_thread_func(void* pool_) { OpflexPool* pool = (OpflexPool*)pool_; uv_run(&pool->client_loop, UV_RUN_DEFAULT); } void OpflexPool::timer_cb(uv_timer_t* handle) { // TODO retry connections, read timeouts, etc } void OpflexPool::on_conn_closed(uv_handle_t *handle) { OpflexClientConnection* conn = (OpflexClientConnection*)handle->data; OpflexPool* pool = conn->getPool(); if (conn != NULL) { util::LockGuard guard(&pool->conn_mutex); pool->doRemovePeer(conn->getHostname(), conn->getPort()); delete conn; } } void OpflexPool::writeToRole(OpflexMessage& message, OpflexHandler::OpflexRole role) { std::vector<OpflexClientConnection*> conns; { util::LockGuard guard(&conn_mutex); role_map_t::iterator it = roles.find(role); if (it == roles.end()) return; BOOST_FOREACH(OpflexClientConnection* conn, it->second.conns) { conns.push_back(conn); } } rapidjson::StringBuffer* sb = NULL; rapidjson::StringBuffer* sb_copy = NULL; for (int i = 0; i < conns.size(); ++i) { // only call serialize once if (sb == NULL) sb = message.serialize(); // make a copy for all but the last connection if (i + 1 < conns.size()) { sb_copy = new rapidjson::StringBuffer(); // sadly this appears to be the only way to copy a // rapidjson string buffer. Revisit use of string buffer // later const char* str = sb->GetString(); for (int j = 0; j < sb->GetSize(); ++j) sb_copy->Put(str[j]); } else { sb_copy = sb; } conns[i]->write(sb_copy); } // all allocated buffers should have been dispatched to // connections } } /* namespace internal */ } /* namespace engine */ } /* namespace opflex */
/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil */ /* * Implementation for OpflexPool * * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ #include <vector> #include <boost/foreach.hpp> #include "opflex/engine/internal/OpflexPool.h" #include "opflex/logging/internal/logging.hpp" #include "LockGuard.h" namespace opflex { namespace engine { namespace internal { using std::make_pair; using std::string; static void async_cb(uv_async_t* handle) { uv_close((uv_handle_t*)handle, NULL); } OpflexPool::OpflexPool(HandlerFactory& factory_) : factory(factory_) { uv_mutex_init(&conn_mutex); } OpflexPool::~OpflexPool() { uv_mutex_destroy(&conn_mutex); } void OpflexPool::start() { uv_loop_init(&client_loop); uv_timer_init(&client_loop, &timer); timer.data = this; uv_timer_start(&timer, timer_cb, 1000, 1000); uv_async_init(&client_loop, &async, async_cb); int rc = uv_thread_create(&client_thread, client_thread_func, this); if (rc < 0) { throw std::runtime_error(string("Could not create client thread: ") + uv_strerror(rc)); } } void OpflexPool::stop() { clear(); uv_timer_stop(&timer); uv_close((uv_handle_t*)&timer, NULL); uv_async_send(&async); uv_thread_join(&client_thread); int rc = uv_loop_close(&client_loop); } void OpflexPool::setOpflexIdentity(const std::string& name, const std::string& domain) { this->name = name; this->domain = domain; } OpflexClientConnection* OpflexPool::getPeer(const std::string& hostname, int port) { util::LockGuard guard(&conn_mutex); conn_map_t::iterator it = connections.find(make_pair(hostname, port)); if (it != connections.end()) { return it->second.conn; } return NULL; } void OpflexPool::addPeer(const std::string& hostname, int port) { util::LockGuard guard(&conn_mutex); ConnData& cd = connections[make_pair(hostname, port)]; if (cd.conn != NULL) { LOG(ERROR) << "Connection for " << hostname << ":" << port << " already exists; not adding peer."; } else { OpflexClientConnection* conn = new OpflexClientConnection(factory, this, hostname, port); cd.conn = conn; conn->connect(); } } void OpflexPool::addPeer(OpflexClientConnection* conn) { util::LockGuard guard(&conn_mutex); ConnData& cd = connections[make_pair(conn->getHostname(), conn->getPort())]; if (cd.conn != NULL) { LOG(ERROR) << "Connection for " << conn->getHostname() << ":" << conn->getPort() << " already exists"; conn->disconnect(); } cd.conn = conn; } void OpflexPool::doRemovePeer(const std::string& hostname, int port) { conn_map_t::iterator it = connections.find(make_pair(hostname, port)); if (it != connections.end()) { if (it->second.conn) { doSetRoles(it->second, 0); } connections.erase(it); } } void OpflexPool::clear() { util::LockGuard guard(&conn_mutex); BOOST_FOREACH(conn_map_t::value_type& v, connections) { v.second.conn->disconnect(); } } // must be called with conn_mutex held void OpflexPool::updateRole(ConnData& cd, uint8_t newroles, OpflexHandler::OpflexRole role) { if (cd.roles & role) { if (!(newroles & role)) { role_map_t::iterator it = roles.find(role); if (it != roles.end()) { if (it->second.curMaster == cd.conn) it->second.curMaster = NULL; it->second.conns.erase(cd.conn); if (it->second.conns.size() == 0) roles.erase(it); } } } else if (newroles & role) { if (!(cd.roles & role)) { conn_set_t& cl = roles[role].conns; cl.insert(cd.conn); } } } void OpflexPool::setRoles(OpflexClientConnection* conn, uint8_t newroles) { util::LockGuard guard(&conn_mutex); ConnData& cd = connections[make_pair(conn->getHostname(), conn->getPort())]; doSetRoles(cd, newroles); } // must be called with conn_mutex held void OpflexPool::doSetRoles(ConnData& cd, uint8_t newroles) { updateRole(cd, newroles, OpflexHandler::POLICY_ELEMENT); updateRole(cd, newroles, OpflexHandler::POLICY_REPOSITORY); updateRole(cd, newroles, OpflexHandler::ENDPOINT_REGISTRY); updateRole(cd, newroles, OpflexHandler::OBSERVER); } OpflexClientConnection* OpflexPool::getMasterForRole(OpflexHandler::OpflexRole role) { util::LockGuard guard(&conn_mutex); role_map_t::iterator it = roles.find(role); if (it == roles.end()) return NULL; if (it->second.curMaster != NULL && it->second.curMaster->isReady()) return it->second.curMaster; BOOST_FOREACH(OpflexClientConnection* conn, it->second.conns) { if (conn->isReady()) { it->second.curMaster = conn; return conn; } } return NULL; } void OpflexPool::client_thread_func(void* pool_) { OpflexPool* pool = (OpflexPool*)pool_; uv_run(&pool->client_loop, UV_RUN_DEFAULT); } void OpflexPool::timer_cb(uv_timer_t* handle) { // TODO retry connections, read timeouts, etc } void OpflexPool::on_conn_closed(uv_handle_t *handle) { OpflexClientConnection* conn = (OpflexClientConnection*)handle->data; OpflexPool* pool = conn->getPool(); if (conn != NULL) { util::LockGuard guard(&pool->conn_mutex); pool->doRemovePeer(conn->getHostname(), conn->getPort()); delete conn; } } void OpflexPool::writeToRole(OpflexMessage& message, OpflexHandler::OpflexRole role) { std::vector<OpflexClientConnection*> conns; { util::LockGuard guard(&conn_mutex); role_map_t::iterator it = roles.find(role); if (it == roles.end()) return; BOOST_FOREACH(OpflexClientConnection* conn, it->second.conns) { conns.push_back(conn); } } rapidjson::StringBuffer* sb = NULL; rapidjson::StringBuffer* sb_copy = NULL; for (int i = 0; i < conns.size(); ++i) { // only call serialize once if (sb == NULL) sb = message.serialize(); // make a copy for all but the last connection if (i + 1 < conns.size()) { sb_copy = new rapidjson::StringBuffer(); // sadly this appears to be the only way to copy a // rapidjson string buffer. Revisit use of string buffer // later const char* str = sb->GetString(); for (int j = 0; j < sb->GetSize(); ++j) sb_copy->Put(str[j]); } else { sb_copy = sb; } conns[i]->write(sb_copy); } // all allocated buffers should have been dispatched to // connections } } /* namespace internal */ } /* namespace engine */ } /* namespace opflex */
Fix compilation - add missing C++ standard library include (vector)
Fix compilation - add missing C++ standard library include (vector)
C++
epl-1.0
mhrobinson/opflex,mhrobinson/opflex,mhrobinson/opflex,mhrobinson/opflex
f9c5f77544acbcd143f061b555950d9d7b926462
libs/utility/prog_interface.cpp
libs/utility/prog_interface.cpp
#include <QProgressDialog> #include <QtGui/QApplication> #include <QObject> #include <memory> #include <ctime> #include <iostream> std::auto_ptr<QProgressDialog> progressDialog; long cur_time = 0; long zero_time = 0; const long interval = 500; extern "C" void begin_prog(const char* title) { if(!progressDialog.get()) return; progressDialog.reset(new QProgressDialog("initializing...","Abort",0,10,0)); progressDialog->setMinimumDuration(0); progressDialog->setWindowTitle(title); qApp->processEvents(); cur_time = zero_time = 0; } extern "C" void set_title(const char* title) { if(!progressDialog.get()) return; progressDialog->setWindowTitle(title); qApp->processEvents(); } extern "C" void can_cancel(int cancel) { if(cancel && progressDialog.get()) progressDialog->setCancelButtonText("&Cancel"); } extern "C" int check_prog(int now,int total) { long now_time = std::clock(); if(now == total && progressDialog.get()) progressDialog.reset(new QProgressDialog("","Abort",0,10,0)); if(now == 0 || now == total) zero_time = now_time; if(progressDialog.get() && (now_time - cur_time > interval)) { long expected_sec = 0; if(now != 0 && now_time != zero_time) expected_sec = (now_time-zero_time)*(total-now)/now/CLOCKS_PER_SEC; if(progressDialog->wasCanceled()) return false; progressDialog->setRange(0, total); progressDialog->setValue(now); if(expected_sec > 60) progressDialog->setLabelText(QString("%1 of %2, estimated time: %4 min"). arg(now).arg(total).arg(expected_sec/60)); else progressDialog->setLabelText(QString("%1 of %2...").arg(now).arg(total)); qApp->processEvents(); cur_time = std::clock(); } return now < total; } extern "C" int prog_aborted(void) { if(progressDialog.get()) return progressDialog->wasCanceled(); return false; }
#include <QProgressDialog> #include <QtGui/QApplication> #include <QObject> #include <memory> #include <ctime> #include <iostream> std::auto_ptr<QProgressDialog> progressDialog; long cur_time = 0; long zero_time = 0; const long interval = 500; extern "C" void begin_prog(const char* title) { if(!progressDialog.get()) return; progressDialog.reset(new QProgressDialog("initializing...","Abort",0,10,0)); progressDialog->setMinimumDuration(0); progressDialog->setWindowTitle(title); qApp->processEvents(); cur_time = zero_time = 0; } extern "C" void set_title(const char* title) { if(!progressDialog.get()) return; progressDialog->setWindowTitle(title); qApp->processEvents(); } extern "C" void can_cancel(int cancel) { if(cancel && progressDialog.get()) progressDialog->setCancelButtonText("&Cancel"); } extern "C" int check_prog(int now,int total) { long now_time = std::clock(); if(now == total && progressDialog.get()) progressDialog.reset(new QProgressDialog("","Abort",0,10,0)); if(now == 0 || now == total) zero_time = now_time; if(progressDialog.get() && (now_time - cur_time > interval)) { long expected_sec = 0; if(now != 0 && now_time != zero_time) expected_sec = ((double)(now_time-zero_time)*(double)(total-now)/(double)now/(double)CLOCKS_PER_SEC); if(progressDialog->wasCanceled()) return false; progressDialog->setRange(0, total); progressDialog->setValue(now); if(expected_sec > 60) progressDialog->setLabelText(QString("%1 of %2, estimated time: %3 min %4 sec"). arg(now).arg(total).arg(expected_sec/60).arg(expected_sec%60)); else progressDialog->setLabelText(QString("%1 of %2...").arg(now).arg(total)); qApp->processEvents(); cur_time = std::clock(); } return now < total; } extern "C" int prog_aborted(void) { if(progressDialog.get()) return progressDialog->wasCanceled(); return false; }
fix bug in progression bar
fix bug in progression bar
C++
bsd-3-clause
sbaete/DSI-Studio-qt5,sbaete/DSI-Studio-qt5,sbaete/DSI-Studio-qt5
37e5d8bf5362f60d8c4309f91c3fc83d18ee78a8
source/dib.cpp
source/dib.cpp
#include "stdafx.h" DIB::DIB() { m_w = m_h = 0; m_pitch = 0; m_p = 0; #ifdef _MSC_VER m_hbm = NULL; m_hdc = NULL; m_hbmOld = NULL; memset(&m_ds, 0, sizeof(m_ds)); #endif } DIB::~DIB() { Destroy(); } void DIB::Destroy() { #ifdef _MSC_VER if (m_hbmOld) { SelectObject(m_hdc, m_hbmOld); m_hbmOld = NULL; } if (m_hdc) { DeleteDC(m_hdc); m_hdc = NULL; } if (m_hbm) { DeleteObject(m_hbm); m_hbm = NULL; } #else free(m_p); m_p = nullptr; #endif } bool DIB::Create(int w, int h) { return Create(w, h, 32); } #ifndef _MSC_VER bool DIB::Create(int w, int h, int bits, int) { Destroy(); m_w = w; m_h = h; m_pitch = (w * (bits / 8) + 3) & ~3; m_p = malloc(m_pitch * h); return true; } #endif #ifdef _MSC_VER bool DIB::Create(int w, int h, int bits, int level) { Destroy(); switch(bits) { case 8: case 32: break; default: return false; } m_w = w; m_h = h; struct BMI256 : BITMAPINFO { RGBQUAD bmiAdditionalColors[255]; }bmi; memset(&bmi, 0, sizeof(bmi)); BITMAPINFOHEADER *bh = &bmi.bmiHeader; bh->biSize = sizeof(BITMAPINFOHEADER); bh->biWidth = w; bh->biHeight = -h; // top down bh->biPlanes = 1; bh->biBitCount = bits; if (bits == 8) { for (int i = 0; i < 256; i++) { int v = std::min(i * 255 / level, 255); bmi.bmiColors[i].rgbRed = v; bmi.bmiColors[i].rgbGreen = v; bmi.bmiColors[i].rgbBlue = v; bmi.bmiColors[i].rgbReserved = 0; } } HWND hWnd = GetDesktopWindow(); HDC hdc = GetDC(hWnd); if (!hdc){ ReleaseDC(hWnd, hdc); return false; } m_hbm = CreateDIBSection(hdc, &bmi, DIB_RGB_COLORS, (void**)&m_p, NULL, 0); if (m_hbm == NULL) { ReleaseDC(hWnd, hdc); Destroy(); return false; } m_hdc = CreateCompatibleDC(hdc); if (m_hdc == NULL) { ReleaseDC(hWnd, hdc); return false; } m_hbmOld = (HBITMAP)SelectObject(m_hdc, m_hbm); GetObject(m_hbm, sizeof(DIBSECTION), &m_ds); m_pitch = m_ds.dsBm.bmWidthBytes; ReleaseDC(hWnd, hdc); return true; } #endif void DIB::DibToGL() { for(int y = 0; y < getH(); y++) { for (int x = 0; x < getW(); x++) { pixel px = getPixel(x, y); std::swap(*((char*)(&px) + 0), *((char*)(&px) + 2)); setPixel(x, y, px); } } } void DIB::DibToGLFont() { for (int y = 0; y < getH(); y++) { for (int x = 0; x < getW(); x++) { pixel px = getPixel(x, y); px = (px << 8) | 0x00ffffff; setPixel(x, y, px); } } } void DIB::DibToDXFont() { for (int y = 0; y < getH(); y++) { for (int x = 0; x < getW(); x++) { pixel px = getPixel(x, y); px = (px << 8) | 0x00ffffff; // px |= 0xffffff00; setPixel(x, y, px); } } } void DIB::FillAlpha() { for (int y = 0; y < getH(); y++) { for (int x = 0; x < getW(); x++) { *referPixel(x, y) |= 0xff000000; } } } void DIB::Clear(pixel color) { for (int y = 0; y < getH(); y++) { for (int x = 0; x < getW(); x++) { setPixel(x, y, color); } } } #ifdef _MSC_VER static bool dibCopy32(DIB *dib, BITMAPINFO *bi, void *bits) { int srcH = bi->bmiHeader.biHeight; if (dib->getW() != bi->bmiHeader.biWidth || dib->getH() != abs(srcH)) { return false; } if (bi->bmiHeader.biBitCount != 32) { return false; } for (int y = 0; y < dib->getH(); y++) { int srcY = srcH > 0 ? srcH - 1 - y : y; // support both bottom-up and top-down void *dst = dib->referPixel(0, y); void *src = (DWORD*)bits + dib->getW() * srcY; memcpy(dst, src, dib->getW() * sizeof(DWORD)); } return true; } #endif #ifdef _MSC_VER bool DIB::LoadFromBmp(const char *file) { bool result = false; BITMAPINFO *bi; void *bits; void *tmp = NULL; int size; tmp = LoadFile(file, &size); if (!tmp) { return false; } BITMAPFILEHEADER *fh = (BITMAPFILEHEADER*)tmp; if (fh->bfType != *(WORD*)"BM") { goto end; } bi = (BITMAPINFO*)((BYTE*)tmp + sizeof(*fh)); bits = (BYTE*)tmp + fh->bfOffBits; if (!Create(bi->bmiHeader.biWidth, abs(bi->bmiHeader.biHeight))) { goto end; } StretchDIBits(m_hdc, 0, 0, m_w, m_h, 0, 0, m_w, m_h, bits, bi, DIB_RGB_COLORS, SRCCOPY); // StretchDIBits may ignore alpha channel // fill the alpha channel for textures FillAlpha(); result = true; end: if (tmp) { free(tmp); } return result; } bool DIB::Blt(HDC target, int dstX, int dstY, int w, int h) { return !!BitBlt(target, dstX, dstY, w, h, m_hdc, 0, 0, SRCCOPY); } void DIB::Save(const char* fileName) { if (m_ds.dsBm.bmBitsPixel != 32) { return; } int pixSize = + getW() * getH() * 4; int fileSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + pixSize; BYTE* img = (BYTE*)calloc(fileSize, 1); int ofs = 0; BITMAPFILEHEADER& fh = *(BITMAPFILEHEADER*)img; ofs += sizeof(BITMAPFILEHEADER); BITMAPINFOHEADER& ih = *(BITMAPINFOHEADER*)(img + ofs); ofs += sizeof(BITMAPINFOHEADER); DWORD* pxs = (DWORD*)(img + ofs); fh.bfType = 'MB'; fh.bfSize = fileSize; fh.bfOffBits = ofs; ih = m_ds.dsBmih; memcpy(pxs, m_p, pixSize); if (ih.biHeight > 0) { ih.biHeight = -ih.biHeight; // top down } SaveFile(fileName, img, fileSize); free(img); } #endif bool DIB::Blt(DIB& target, int dstX, int dstY) { if (dstX < 0 || dstY < 0) { return false; } if (dstX + getW() > target.getW()) { return false; } if (dstX + getH() > target.getH()) { return false; } for (int y = 0; y < getH(); y++) { for (int x = 0; x < getW(); x++) { target.setPixel(dstX + x, dstY + y, getPixel(x, y)); } } return true; } bool DIB::ApplySoftAA(DIB& target) { if (getW() != target.getW() * 2) { return false; } if (getH() != target.getH() * 2) { return false; } for (int y = 0; y < target.getH(); y++) { for (int x = 0; x < target.getW(); x++) { pixel color[] = { getPixel(x * 2, y * 2), getPixel(x * 2 + 1, y * 2), getPixel(x * 2, y * 2 + 1), getPixel(x * 2 + 1, y * 2 + 1) }; IVec4 sum; for (int i = 0; i < (int)dimof(color); i++) { sum += UnormToIvec4(color[i]); } sum /= 4; target.setPixel(x, y, ivec4ToUnorm(sum)); } } return true; }
#include "stdafx.h" DIB::DIB() { m_w = m_h = 0; m_pitch = 0; m_p = 0; #ifdef _MSC_VER m_hbm = NULL; m_hdc = NULL; m_hbmOld = NULL; memset(&m_ds, 0, sizeof(m_ds)); #endif } DIB::~DIB() { Destroy(); } void DIB::Destroy() { #ifdef _MSC_VER if (m_hbmOld) { SelectObject(m_hdc, m_hbmOld); m_hbmOld = NULL; } if (m_hdc) { DeleteDC(m_hdc); m_hdc = NULL; } if (m_hbm) { DeleteObject(m_hbm); m_hbm = NULL; } #else free(m_p); m_p = nullptr; #endif } bool DIB::Create(int w, int h) { return Create(w, h, 32); } #ifndef _MSC_VER bool DIB::Create(int w, int h, int bits, int) { Destroy(); m_w = w; m_h = h; m_pitch = (w * (bits / 8) + 3) & ~3; m_p = malloc(m_pitch * h); return true; } #endif #ifdef _MSC_VER bool DIB::Create(int w, int h, int bits, int level) { Destroy(); switch(bits) { case 8: case 32: break; default: return false; } m_w = w; m_h = h; struct BMI256 : BITMAPINFO { RGBQUAD bmiAdditionalColors[255]; }bmi; memset(&bmi, 0, sizeof(bmi)); BITMAPINFOHEADER *bh = &bmi.bmiHeader; bh->biSize = sizeof(BITMAPINFOHEADER); bh->biWidth = w; bh->biHeight = -h; // top down bh->biPlanes = 1; bh->biBitCount = bits; if (bits == 8) { for (int i = 0; i < 256; i++) { int v = std::min(i * 255 / level, 255); bmi.bmiColors[i].rgbRed = v; bmi.bmiColors[i].rgbGreen = v; bmi.bmiColors[i].rgbBlue = v; bmi.bmiColors[i].rgbReserved = 0; } } HWND hWnd = GetDesktopWindow(); HDC hdc = GetDC(hWnd); if (!hdc){ ReleaseDC(hWnd, hdc); return false; } m_hbm = CreateDIBSection(hdc, &bmi, DIB_RGB_COLORS, (void**)&m_p, NULL, 0); if (m_hbm == NULL) { ReleaseDC(hWnd, hdc); Destroy(); return false; } m_hdc = CreateCompatibleDC(hdc); if (m_hdc == NULL) { ReleaseDC(hWnd, hdc); return false; } m_hbmOld = (HBITMAP)SelectObject(m_hdc, m_hbm); GetObject(m_hbm, sizeof(DIBSECTION), &m_ds); m_pitch = m_ds.dsBm.bmWidthBytes; ReleaseDC(hWnd, hdc); return true; } #endif void DIB::DibToGL() { for(int y = 0; y < getH(); y++) { for (int x = 0; x < getW(); x++) { pixel px = getPixel(x, y); std::swap(*((char*)(&px) + 0), *((char*)(&px) + 2)); setPixel(x, y, px); } } } void DIB::DibToGLFont() { for (int y = 0; y < getH(); y++) { for (int x = 0; x < getW(); x++) { pixel px = getPixel(x, y); px = (px << 8) | 0x00ffffff; setPixel(x, y, px); } } } void DIB::DibToDXFont() { for (int y = 0; y < getH(); y++) { for (int x = 0; x < getW(); x++) { pixel px = getPixel(x, y); px = (px << 8) | 0x00ffffff; // px |= 0xffffff00; setPixel(x, y, px); } } } void DIB::FillAlpha() { for (int y = 0; y < getH(); y++) { for (int x = 0; x < getW(); x++) { *referPixel(x, y) |= 0xff000000; } } } void DIB::Clear(pixel color) { for (int y = 0; y < getH(); y++) { for (int x = 0; x < getW(); x++) { setPixel(x, y, color); } } } #ifdef _MSC_VER static bool dibCopy32(DIB *dib, BITMAPINFO *bi, void *bits) { int srcH = bi->bmiHeader.biHeight; if (dib->getW() != bi->bmiHeader.biWidth || dib->getH() != abs(srcH)) { return false; } if (bi->bmiHeader.biBitCount != 32) { return false; } for (int y = 0; y < dib->getH(); y++) { int srcY = srcH > 0 ? srcH - 1 - y : y; // support both bottom-up and top-down void *dst = dib->referPixel(0, y); void *src = (DWORD*)bits + dib->getW() * srcY; memcpy(dst, src, dib->getW() * sizeof(DWORD)); } return true; } #endif #ifdef _MSC_VER bool DIB::LoadFromBmp(const char *file) { bool result = false; BITMAPINFO *bi; void *bits; void *tmp = NULL; int size; tmp = LoadFile(file, &size); if (!tmp) { return false; } BITMAPFILEHEADER *fh = (BITMAPFILEHEADER*)tmp; if (fh->bfType != *(WORD*)"BM") { goto end; } bi = (BITMAPINFO*)((BYTE*)tmp + sizeof(*fh)); bits = (BYTE*)tmp + fh->bfOffBits; if (!Create(bi->bmiHeader.biWidth, abs(bi->bmiHeader.biHeight))) { goto end; } StretchDIBits(m_hdc, 0, 0, m_w, m_h, 0, 0, m_w, m_h, bits, bi, DIB_RGB_COLORS, SRCCOPY); // StretchDIBits may ignore alpha channel // fill the alpha channel for textures FillAlpha(); result = true; end: if (tmp) { free(tmp); } return result; } bool DIB::Blt(HDC target, int dstX, int dstY, int w, int h) { return !!BitBlt(target, dstX, dstY, w, h, m_hdc, 0, 0, SRCCOPY); } void DIB::Save(const char* fileName) { if (m_ds.dsBm.bmBitsPixel != 32) { return; } int pixSize = + getW() * getH() * 4; int fileSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + pixSize; BYTE* img = (BYTE*)calloc(fileSize, 1); int ofs = 0; BITMAPFILEHEADER& fh = *(BITMAPFILEHEADER*)img; ofs += sizeof(BITMAPFILEHEADER); BITMAPINFOHEADER& ih = *(BITMAPINFOHEADER*)(img + ofs); ofs += sizeof(BITMAPINFOHEADER); DWORD* pxs = (DWORD*)(img + ofs); fh.bfType = 'MB'; fh.bfSize = fileSize; fh.bfOffBits = ofs; ih = m_ds.dsBmih; memcpy(pxs, m_p, pixSize); if (ih.biHeight > 0) { ih.biHeight = -ih.biHeight; // top down } SaveFile(fileName, img, fileSize); free(img); } #endif bool DIB::Blt(DIB& target, int dstX, int dstY) { if (dstX < 0 || dstY < 0) { return false; } if (dstX + getW() > target.getW()) { return false; } if (dstY + getH() > target.getH()) { return false; } for (int y = 0; y < getH(); y++) { for (int x = 0; x < getW(); x++) { target.setPixel(dstX + x, dstY + y, getPixel(x, y)); } } return true; } bool DIB::ApplySoftAA(DIB& target) { if (getW() != target.getW() * 2) { return false; } if (getH() != target.getH() * 2) { return false; } for (int y = 0; y < target.getH(); y++) { for (int x = 0; x < target.getW(); x++) { pixel color[] = { getPixel(x * 2, y * 2), getPixel(x * 2 + 1, y * 2), getPixel(x * 2, y * 2 + 1), getPixel(x * 2 + 1, y * 2 + 1) }; IVec4 sum; for (int i = 0; i < (int)dimof(color); i++) { sum += UnormToIvec4(color[i]); } sum /= 4; target.setPixel(x, y, ivec4ToUnorm(sum)); } } return true; }
Fix missing glyph bug.
Fix missing glyph bug.
C++
mit
yorung/dx11bvh,yorung/dx11bvh
12b875862044115add059e1dd1478be089c2f64d
printing/printing_context_win.cc
printing/printing_context_win.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "printing/printing_context_win.h" #include <algorithm> #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "printing/backend/print_backend.h" #include "printing/backend/win_helper.h" #include "printing/print_settings_initializer_win.h" #include "printing/printed_document.h" #include "printing/printing_context_system_dialog_win.h" #include "printing/printing_utils.h" #include "printing/units.h" #include "skia/ext/platform_device.h" #if defined(USE_AURA) #include "ui/aura/remote_window_tree_host_win.h" #include "ui/aura/window.h" #endif namespace printing { // static scoped_ptr<PrintingContext> PrintingContext::Create(Delegate* delegate) { #if defined(ENABLE_BASIC_PRINTING) return make_scoped_ptr<PrintingContext>( new PrintingContextSytemDialogWin(delegate)); #else // ENABLE_BASIC_PRINTING return make_scoped_ptr<PrintingContext>(new PrintingContextWin(delegate)); #endif // EENABLE_BASIC_PRINTING } PrintingContextWin::PrintingContextWin(Delegate* delegate) : PrintingContext(delegate), context_(NULL) { } PrintingContextWin::~PrintingContextWin() { ReleaseContext(); } void PrintingContextWin::AskUserForSettings( int max_pages, bool has_selection, const PrintSettingsCallback& callback) { NOTIMPLEMENTED(); } PrintingContext::Result PrintingContextWin::UseDefaultSettings() { DCHECK(!in_print_job_); scoped_refptr<PrintBackend> backend = PrintBackend::CreateInstance(NULL); base::string16 default_printer = base::UTF8ToWide(backend->GetDefaultPrinterName()); if (!default_printer.empty()) { ScopedPrinterHandle printer; if (printer.OpenPrinter(default_printer.c_str())) { scoped_ptr<DEVMODE, base::FreeDeleter> dev_mode = CreateDevMode(printer.Get(), NULL); if (InitializeSettings(default_printer, dev_mode.get()) == OK) return OK; } } ReleaseContext(); // No default printer configured, do we have any printers at all? DWORD bytes_needed = 0; DWORD count_returned = 0; (void)::EnumPrinters(PRINTER_ENUM_LOCAL|PRINTER_ENUM_CONNECTIONS, NULL, 2, NULL, 0, &bytes_needed, &count_returned); if (bytes_needed) { DCHECK_GE(bytes_needed, count_returned * sizeof(PRINTER_INFO_2)); scoped_ptr<BYTE[]> printer_info_buffer(new BYTE[bytes_needed]); BOOL ret = ::EnumPrinters(PRINTER_ENUM_LOCAL|PRINTER_ENUM_CONNECTIONS, NULL, 2, printer_info_buffer.get(), bytes_needed, &bytes_needed, &count_returned); if (ret && count_returned) { // have printers // Open the first successfully found printer. const PRINTER_INFO_2* info_2 = reinterpret_cast<PRINTER_INFO_2*>(printer_info_buffer.get()); const PRINTER_INFO_2* info_2_end = info_2 + count_returned; for (; info_2 < info_2_end; ++info_2) { ScopedPrinterHandle printer; if (!printer.OpenPrinter(info_2->pPrinterName)) continue; scoped_ptr<DEVMODE, base::FreeDeleter> dev_mode = CreateDevMode(printer.Get(), NULL); if (InitializeSettings(info_2->pPrinterName, dev_mode.get()) == OK) return OK; } if (context_) return OK; } } return OnError(); } gfx::Size PrintingContextWin::GetPdfPaperSizeDeviceUnits() { // Default fallback to Letter size. gfx::SizeF paper_size(kLetterWidthInch, kLetterHeightInch); // Get settings from locale. Paper type buffer length is at most 4. const int paper_type_buffer_len = 4; wchar_t paper_type_buffer[paper_type_buffer_len] = {0}; GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IPAPERSIZE, paper_type_buffer, paper_type_buffer_len); if (wcslen(paper_type_buffer)) { // The call succeeded. int paper_code = _wtoi(paper_type_buffer); switch (paper_code) { case DMPAPER_LEGAL: paper_size.SetSize(kLegalWidthInch, kLegalHeightInch); break; case DMPAPER_A4: paper_size.SetSize(kA4WidthInch, kA4HeightInch); break; case DMPAPER_A3: paper_size.SetSize(kA3WidthInch, kA3HeightInch); break; default: // DMPAPER_LETTER is used for default fallback. break; } } return gfx::Size( paper_size.width() * settings_.device_units_per_inch(), paper_size.height() * settings_.device_units_per_inch()); } PrintingContext::Result PrintingContextWin::UpdatePrinterSettings( bool external_preview, bool show_system_dialog) { DCHECK(!in_print_job_); DCHECK(!external_preview) << "Not implemented"; ScopedPrinterHandle printer; if (!printer.OpenPrinter(settings_.device_name().c_str())) return OnError(); // Make printer changes local to Chrome. // See MSDN documentation regarding DocumentProperties. scoped_ptr<DEVMODE, base::FreeDeleter> scoped_dev_mode = CreateDevModeWithColor(printer.Get(), settings_.device_name(), settings_.color() != GRAY); if (!scoped_dev_mode) return OnError(); { DEVMODE* dev_mode = scoped_dev_mode.get(); dev_mode->dmCopies = std::max(settings_.copies(), 1); if (dev_mode->dmCopies > 1) { // do not change unless multiple copies dev_mode->dmFields |= DM_COPIES; dev_mode->dmCollate = settings_.collate() ? DMCOLLATE_TRUE : DMCOLLATE_FALSE; } switch (settings_.duplex_mode()) { case LONG_EDGE: dev_mode->dmFields |= DM_DUPLEX; dev_mode->dmDuplex = DMDUP_VERTICAL; break; case SHORT_EDGE: dev_mode->dmFields |= DM_DUPLEX; dev_mode->dmDuplex = DMDUP_HORIZONTAL; break; case SIMPLEX: dev_mode->dmFields |= DM_DUPLEX; dev_mode->dmDuplex = DMDUP_SIMPLEX; break; default: // UNKNOWN_DUPLEX_MODE break; } dev_mode->dmFields |= DM_ORIENTATION; dev_mode->dmOrientation = settings_.landscape() ? DMORIENT_LANDSCAPE : DMORIENT_PORTRAIT; const PrintSettings::RequestedMedia& requested_media = settings_.requested_media(); static const int kFromUm = 100; // Windows uses 0.1mm. int width = requested_media.size_microns.width() / kFromUm; int height = requested_media.size_microns.height() / kFromUm; unsigned id = 0; if (base::StringToUint(requested_media.vendor_id, &id) && id) { dev_mode->dmFields |= DM_PAPERSIZE; dev_mode->dmPaperSize = static_cast<short>(id); } else if (width > 0 && height > 0) { dev_mode->dmFields |= DM_PAPERWIDTH; dev_mode->dmPaperWidth = width; dev_mode->dmFields |= DM_PAPERLENGTH; dev_mode->dmPaperLength = height; } } // Update data using DocumentProperties. if (show_system_dialog) { scoped_dev_mode = ShowPrintDialog( printer.Get(), delegate_->GetParentView(), scoped_dev_mode.get()); } else { scoped_dev_mode = CreateDevMode(printer.Get(), scoped_dev_mode.get()); } // Set printer then refresh printer settings. return InitializeSettings(settings_.device_name(), scoped_dev_mode.get()); } PrintingContext::Result PrintingContextWin::InitWithSettings( const PrintSettings& settings) { DCHECK(!in_print_job_); settings_ = settings; // TODO(maruel): settings_.ToDEVMODE() ScopedPrinterHandle printer; if (!printer.OpenPrinter(settings_.device_name().c_str())) return FAILED; scoped_ptr<DEVMODE, base::FreeDeleter> dev_mode = CreateDevMode(printer.Get(), NULL); return InitializeSettings(settings_.device_name(), dev_mode.get()); } PrintingContext::Result PrintingContextWin::NewDocument( const base::string16& document_name) { DCHECK(!in_print_job_); if (!context_) return OnError(); // Set the flag used by the AbortPrintJob dialog procedure. abort_printing_ = false; in_print_job_ = true; // Register the application's AbortProc function with GDI. if (SP_ERROR == SetAbortProc(context_, &AbortProc)) return OnError(); DCHECK(SimplifyDocumentTitle(document_name) == document_name); DOCINFO di = { sizeof(DOCINFO) }; di.lpszDocName = document_name.c_str(); // Is there a debug dump directory specified? If so, force to print to a file. base::string16 debug_dump_path = PrintedDocument::CreateDebugDumpPath(document_name, FILE_PATH_LITERAL(".prn")).value(); if (!debug_dump_path.empty()) di.lpszOutput = debug_dump_path.c_str(); // No message loop running in unit tests. DCHECK(!base::MessageLoop::current() || !base::MessageLoop::current()->NestableTasksAllowed()); // Begin a print job by calling the StartDoc function. // NOTE: StartDoc() starts a message loop. That causes a lot of problems with // IPC. Make sure recursive task processing is disabled. if (StartDoc(context_, &di) <= 0) return OnError(); return OK; } PrintingContext::Result PrintingContextWin::NewPage() { if (abort_printing_) return CANCEL; DCHECK(context_); DCHECK(in_print_job_); // Intentional No-op. PdfMetafileSkia::SafePlayback takes care of calling // ::StartPage(). return OK; } PrintingContext::Result PrintingContextWin::PageDone() { if (abort_printing_) return CANCEL; DCHECK(in_print_job_); // Intentional No-op. PdfMetafileSkia::SafePlayback takes care of calling // ::EndPage(). return OK; } PrintingContext::Result PrintingContextWin::DocumentDone() { if (abort_printing_) return CANCEL; DCHECK(in_print_job_); DCHECK(context_); // Inform the driver that document has ended. if (EndDoc(context_) <= 0) return OnError(); ResetSettings(); return OK; } void PrintingContextWin::Cancel() { abort_printing_ = true; in_print_job_ = false; if (context_) CancelDC(context_); } void PrintingContextWin::ReleaseContext() { if (context_) { DeleteDC(context_); context_ = NULL; } } gfx::NativeDrawingContext PrintingContextWin::context() const { return context_; } // static BOOL PrintingContextWin::AbortProc(HDC hdc, int nCode) { if (nCode) { // TODO(maruel): Need a way to find the right instance to set. Should // leverage PrintJobManager here? // abort_printing_ = true; } return true; } PrintingContext::Result PrintingContextWin::InitializeSettings( const std::wstring& device_name, DEVMODE* dev_mode) { if (!dev_mode) return OnError(); ReleaseContext(); context_ = CreateDC(L"WINSPOOL", device_name.c_str(), NULL, dev_mode); if (!context_) return OnError(); skia::InitializeDC(context_); DCHECK(!in_print_job_); settings_.set_device_name(device_name); PrintSettingsInitializerWin::InitPrintSettings( context_, *dev_mode, &settings_); return OK; } HWND PrintingContextWin::GetRootWindow(gfx::NativeView view) { HWND window = NULL; #if defined(USE_AURA) if (view) window = view->GetHost()->GetAcceleratedWidget(); #else if (view && IsWindow(view)) { window = GetAncestor(view, GA_ROOTOWNER); } #endif if (!window) { // TODO(maruel): crbug.com/1214347 Get the right browser window instead. return GetDesktopWindow(); } return window; } scoped_ptr<DEVMODE, base::FreeDeleter> PrintingContextWin::ShowPrintDialog( HANDLE printer, gfx::NativeView parent_view, DEVMODE* dev_mode) { // Note that this cannot use ui::BaseShellDialog as the print dialog is // system modal: opening it from a background thread can cause Windows to // get the wrong Z-order which will make the print dialog appear behind the // browser frame (but still being modal) so neither the browser frame nor // the print dialog will get any input. See http://crbug.com/342697 // http://crbug.com/180997 for details. base::MessageLoop::ScopedNestableTaskAllower allow( base::MessageLoop::current()); bool canceled = false; scoped_ptr<DEVMODE, base::FreeDeleter> result = PromptDevMode(printer, settings_.device_name(), dev_mode, GetRootWindow(parent_view), &canceled); if (canceled) { result.reset(); abort_printing_ = true; } return result.Pass(); } } // namespace printing
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "printing/printing_context_win.h" #include <algorithm> #include "base/bind.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "printing/backend/print_backend.h" #include "printing/backend/win_helper.h" #include "printing/print_settings_initializer_win.h" #include "printing/printed_document.h" #include "printing/printing_context_system_dialog_win.h" #include "printing/printing_utils.h" #include "printing/units.h" #include "skia/ext/platform_device.h" #if defined(USE_AURA) #include "ui/aura/remote_window_tree_host_win.h" #include "ui/aura/window.h" #endif namespace printing { namespace { void AssingResult(PrintingContext::Result* out, PrintingContext::Result in) { *out = in; } } // namespace // static scoped_ptr<PrintingContext> PrintingContext::Create(Delegate* delegate) { #if defined(ENABLE_BASIC_PRINTING) return make_scoped_ptr<PrintingContext>( new PrintingContextSytemDialogWin(delegate)); #else // ENABLE_BASIC_PRINTING return make_scoped_ptr<PrintingContext>(new PrintingContextWin(delegate)); #endif // EENABLE_BASIC_PRINTING } PrintingContextWin::PrintingContextWin(Delegate* delegate) : PrintingContext(delegate), context_(NULL) { } PrintingContextWin::~PrintingContextWin() { ReleaseContext(); } void PrintingContextWin::AskUserForSettings( int max_pages, bool has_selection, const PrintSettingsCallback& callback) { NOTIMPLEMENTED(); } PrintingContext::Result PrintingContextWin::UseDefaultSettings() { DCHECK(!in_print_job_); scoped_refptr<PrintBackend> backend = PrintBackend::CreateInstance(NULL); base::string16 default_printer = base::UTF8ToWide(backend->GetDefaultPrinterName()); if (!default_printer.empty()) { ScopedPrinterHandle printer; if (printer.OpenPrinter(default_printer.c_str())) { scoped_ptr<DEVMODE, base::FreeDeleter> dev_mode = CreateDevMode(printer.Get(), NULL); if (InitializeSettings(default_printer, dev_mode.get()) == OK) return OK; } } ReleaseContext(); // No default printer configured, do we have any printers at all? DWORD bytes_needed = 0; DWORD count_returned = 0; (void)::EnumPrinters(PRINTER_ENUM_LOCAL|PRINTER_ENUM_CONNECTIONS, NULL, 2, NULL, 0, &bytes_needed, &count_returned); if (bytes_needed) { DCHECK_GE(bytes_needed, count_returned * sizeof(PRINTER_INFO_2)); scoped_ptr<BYTE[]> printer_info_buffer(new BYTE[bytes_needed]); BOOL ret = ::EnumPrinters(PRINTER_ENUM_LOCAL|PRINTER_ENUM_CONNECTIONS, NULL, 2, printer_info_buffer.get(), bytes_needed, &bytes_needed, &count_returned); if (ret && count_returned) { // have printers // Open the first successfully found printer. const PRINTER_INFO_2* info_2 = reinterpret_cast<PRINTER_INFO_2*>(printer_info_buffer.get()); const PRINTER_INFO_2* info_2_end = info_2 + count_returned; for (; info_2 < info_2_end; ++info_2) { ScopedPrinterHandle printer; if (!printer.OpenPrinter(info_2->pPrinterName)) continue; scoped_ptr<DEVMODE, base::FreeDeleter> dev_mode = CreateDevMode(printer.Get(), NULL); if (InitializeSettings(info_2->pPrinterName, dev_mode.get()) == OK) return OK; } if (context_) return OK; } } return OnError(); } gfx::Size PrintingContextWin::GetPdfPaperSizeDeviceUnits() { // Default fallback to Letter size. gfx::SizeF paper_size(kLetterWidthInch, kLetterHeightInch); // Get settings from locale. Paper type buffer length is at most 4. const int paper_type_buffer_len = 4; wchar_t paper_type_buffer[paper_type_buffer_len] = {0}; GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IPAPERSIZE, paper_type_buffer, paper_type_buffer_len); if (wcslen(paper_type_buffer)) { // The call succeeded. int paper_code = _wtoi(paper_type_buffer); switch (paper_code) { case DMPAPER_LEGAL: paper_size.SetSize(kLegalWidthInch, kLegalHeightInch); break; case DMPAPER_A4: paper_size.SetSize(kA4WidthInch, kA4HeightInch); break; case DMPAPER_A3: paper_size.SetSize(kA3WidthInch, kA3HeightInch); break; default: // DMPAPER_LETTER is used for default fallback. break; } } return gfx::Size( paper_size.width() * settings_.device_units_per_inch(), paper_size.height() * settings_.device_units_per_inch()); } PrintingContext::Result PrintingContextWin::UpdatePrinterSettings( bool external_preview, bool show_system_dialog) { DCHECK(!in_print_job_); DCHECK(!external_preview) << "Not implemented"; ScopedPrinterHandle printer; if (!printer.OpenPrinter(settings_.device_name().c_str())) return OnError(); // Make printer changes local to Chrome. // See MSDN documentation regarding DocumentProperties. scoped_ptr<DEVMODE, base::FreeDeleter> scoped_dev_mode = CreateDevModeWithColor(printer.Get(), settings_.device_name(), settings_.color() != GRAY); if (!scoped_dev_mode) return OnError(); { DEVMODE* dev_mode = scoped_dev_mode.get(); dev_mode->dmCopies = std::max(settings_.copies(), 1); if (dev_mode->dmCopies > 1) { // do not change unless multiple copies dev_mode->dmFields |= DM_COPIES; dev_mode->dmCollate = settings_.collate() ? DMCOLLATE_TRUE : DMCOLLATE_FALSE; } switch (settings_.duplex_mode()) { case LONG_EDGE: dev_mode->dmFields |= DM_DUPLEX; dev_mode->dmDuplex = DMDUP_VERTICAL; break; case SHORT_EDGE: dev_mode->dmFields |= DM_DUPLEX; dev_mode->dmDuplex = DMDUP_HORIZONTAL; break; case SIMPLEX: dev_mode->dmFields |= DM_DUPLEX; dev_mode->dmDuplex = DMDUP_SIMPLEX; break; default: // UNKNOWN_DUPLEX_MODE break; } dev_mode->dmFields |= DM_ORIENTATION; dev_mode->dmOrientation = settings_.landscape() ? DMORIENT_LANDSCAPE : DMORIENT_PORTRAIT; const PrintSettings::RequestedMedia& requested_media = settings_.requested_media(); static const int kFromUm = 100; // Windows uses 0.1mm. int width = requested_media.size_microns.width() / kFromUm; int height = requested_media.size_microns.height() / kFromUm; unsigned id = 0; if (base::StringToUint(requested_media.vendor_id, &id) && id) { dev_mode->dmFields |= DM_PAPERSIZE; dev_mode->dmPaperSize = static_cast<short>(id); } else if (width > 0 && height > 0) { dev_mode->dmFields |= DM_PAPERWIDTH; dev_mode->dmPaperWidth = width; dev_mode->dmFields |= DM_PAPERLENGTH; dev_mode->dmPaperLength = height; } } // Update data using DocumentProperties. if (show_system_dialog) { PrintingContext::Result result = PrintingContext::FAILED; AskUserForSettings(0, false, base::Bind(&AssingResult, &result)); return result; } else { scoped_dev_mode = CreateDevMode(printer.Get(), scoped_dev_mode.get()); } // Set printer then refresh printer settings. return InitializeSettings(settings_.device_name(), scoped_dev_mode.get()); } PrintingContext::Result PrintingContextWin::InitWithSettings( const PrintSettings& settings) { DCHECK(!in_print_job_); settings_ = settings; // TODO(maruel): settings_.ToDEVMODE() ScopedPrinterHandle printer; if (!printer.OpenPrinter(settings_.device_name().c_str())) return FAILED; scoped_ptr<DEVMODE, base::FreeDeleter> dev_mode = CreateDevMode(printer.Get(), NULL); return InitializeSettings(settings_.device_name(), dev_mode.get()); } PrintingContext::Result PrintingContextWin::NewDocument( const base::string16& document_name) { DCHECK(!in_print_job_); if (!context_) return OnError(); // Set the flag used by the AbortPrintJob dialog procedure. abort_printing_ = false; in_print_job_ = true; // Register the application's AbortProc function with GDI. if (SP_ERROR == SetAbortProc(context_, &AbortProc)) return OnError(); DCHECK(SimplifyDocumentTitle(document_name) == document_name); DOCINFO di = { sizeof(DOCINFO) }; di.lpszDocName = document_name.c_str(); // Is there a debug dump directory specified? If so, force to print to a file. base::string16 debug_dump_path = PrintedDocument::CreateDebugDumpPath(document_name, FILE_PATH_LITERAL(".prn")).value(); if (!debug_dump_path.empty()) di.lpszOutput = debug_dump_path.c_str(); // No message loop running in unit tests. DCHECK(!base::MessageLoop::current() || !base::MessageLoop::current()->NestableTasksAllowed()); // Begin a print job by calling the StartDoc function. // NOTE: StartDoc() starts a message loop. That causes a lot of problems with // IPC. Make sure recursive task processing is disabled. if (StartDoc(context_, &di) <= 0) return OnError(); return OK; } PrintingContext::Result PrintingContextWin::NewPage() { if (abort_printing_) return CANCEL; DCHECK(context_); DCHECK(in_print_job_); // Intentional No-op. PdfMetafileSkia::SafePlayback takes care of calling // ::StartPage(). return OK; } PrintingContext::Result PrintingContextWin::PageDone() { if (abort_printing_) return CANCEL; DCHECK(in_print_job_); // Intentional No-op. PdfMetafileSkia::SafePlayback takes care of calling // ::EndPage(). return OK; } PrintingContext::Result PrintingContextWin::DocumentDone() { if (abort_printing_) return CANCEL; DCHECK(in_print_job_); DCHECK(context_); // Inform the driver that document has ended. if (EndDoc(context_) <= 0) return OnError(); ResetSettings(); return OK; } void PrintingContextWin::Cancel() { abort_printing_ = true; in_print_job_ = false; if (context_) CancelDC(context_); } void PrintingContextWin::ReleaseContext() { if (context_) { DeleteDC(context_); context_ = NULL; } } gfx::NativeDrawingContext PrintingContextWin::context() const { return context_; } // static BOOL PrintingContextWin::AbortProc(HDC hdc, int nCode) { if (nCode) { // TODO(maruel): Need a way to find the right instance to set. Should // leverage PrintJobManager here? // abort_printing_ = true; } return true; } PrintingContext::Result PrintingContextWin::InitializeSettings( const std::wstring& device_name, DEVMODE* dev_mode) { if (!dev_mode) return OnError(); ReleaseContext(); context_ = CreateDC(L"WINSPOOL", device_name.c_str(), NULL, dev_mode); if (!context_) return OnError(); skia::InitializeDC(context_); DCHECK(!in_print_job_); settings_.set_device_name(device_name); PrintSettingsInitializerWin::InitPrintSettings( context_, *dev_mode, &settings_); return OK; } HWND PrintingContextWin::GetRootWindow(gfx::NativeView view) { HWND window = NULL; #if defined(USE_AURA) if (view) window = view->GetHost()->GetAcceleratedWidget(); #else if (view && IsWindow(view)) { window = GetAncestor(view, GA_ROOTOWNER); } #endif if (!window) { // TODO(maruel): crbug.com/1214347 Get the right browser window instead. return GetDesktopWindow(); } return window; } scoped_ptr<DEVMODE, base::FreeDeleter> PrintingContextWin::ShowPrintDialog( HANDLE printer, gfx::NativeView parent_view, DEVMODE* dev_mode) { // Note that this cannot use ui::BaseShellDialog as the print dialog is // system modal: opening it from a background thread can cause Windows to // get the wrong Z-order which will make the print dialog appear behind the // browser frame (but still being modal) so neither the browser frame nor // the print dialog will get any input. See http://crbug.com/342697 // http://crbug.com/180997 for details. base::MessageLoop::ScopedNestableTaskAllower allow( base::MessageLoop::current()); bool canceled = false; scoped_ptr<DEVMODE, base::FreeDeleter> result = PromptDevMode(printer, settings_.device_name(), dev_mode, GetRootWindow(parent_view), &canceled); if (canceled) { result.reset(); abort_printing_ = true; } return result.Pass(); } } // namespace printing
Switch back to PrintDlgEx instead of DocumentProperties.
Switch back to PrintDlgEx instead of DocumentProperties. For unclear reasons DocumentProperties with DM_IN_PROMPT sometimes does not return. This is happening mostly on 32bit Windows inside of base::MessageLoop::ScopedNestableTaskAllower. BUG=436810 Review URL: https://codereview.chromium.org/766823004 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#307294}
C++
bsd-3-clause
Jonekee/chromium.src,markYoungH/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,ltilve/chromium,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,ltilve/chromium,dushu1203/chromium.src,Jonekee/chromium.src,Fireblend/chromium-crosswalk,Jonekee/chromium.src,ltilve/chromium,dushu1203/chromium.src,M4sse/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,dednal/chromium.src,axinging/chromium-crosswalk,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,dednal/chromium.src,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,Fireblend/chromium-crosswalk,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,Fireblend/chromium-crosswalk,M4sse/chromium.src,ltilve/chromium,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,Chilledheart/chromium,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,markYoungH/chromium.src,jaruba/chromium.src,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,Jonekee/chromium.src,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,ltilve/chromium,jaruba/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,Fireblend/chromium-crosswalk,dushu1203/chromium.src,Fireblend/chromium-crosswalk,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,Chilledheart/chromium,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,dushu1203/chromium.src,Jonekee/chromium.src,Just-D/chromium-1,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,Chilledheart/chromium,M4sse/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,dednal/chromium.src,ltilve/chromium,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,Chilledheart/chromium,Chilledheart/chromium,markYoungH/chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,dednal/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,ltilve/chromium,jaruba/chromium.src,Just-D/chromium-1,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,dednal/chromium.src,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,dednal/chromium.src,jaruba/chromium.src,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,dednal/chromium.src,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,dednal/chromium.src,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk
fa3bac5d10ca449db9522d87d2ea11000c9098b1
libcaf_core/caf/atom.hpp
libcaf_core/caf/atom.hpp
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <string> #include <functional> #include <type_traits> #include "caf/detail/atom_val.hpp" namespace caf { /// The value type of atoms. enum class atom_value : uint64_t { /// @cond PRIVATE dirty_little_hack = 31337 /// @endcond }; /// @relates atom_value std::string to_string(const atom_value& what); atom_value atom_from_string(const std::string& x); /// Creates an atom from given string literal. template <size_t Size> constexpr atom_value atom(char const (&str)[Size]) { // last character is the NULL terminator static_assert(Size <= 11, "only 10 characters are allowed"); return static_cast<atom_value>(detail::atom_val(str)); } /// Creates an atom from given string literal and return an integer /// representation of the atom.. template <size_t Size> constexpr uint64_t atom_uint(char const (&str)[Size]) { static_assert(Size <= 11, "only 10 characters are allowed"); return detail::atom_val(str); } /// Converts an atom to its integer representation. constexpr uint64_t atom_uint(atom_value x) { return static_cast<uint64_t>(x); } /// Lifts an `atom_value` to a compile-time constant. template <atom_value V> struct atom_constant { constexpr atom_constant() { // nop } /// Returns the wrapped value. constexpr operator atom_value() const { return V; } static constexpr uint64_t uint_value() { return static_cast<uint64_t>(V); } /// Returns an instance *of this constant* (*not* an `atom_value`). static const atom_constant value; }; template <class T> struct is_atom_constant { static constexpr bool value = false; }; template <atom_value X> struct is_atom_constant<atom_constant<X>> { static constexpr bool value = true; }; template <atom_value V> std::string to_string(const atom_constant<V>&) { return to_string(V); } template <atom_value V> const atom_constant<V> atom_constant<V>::value = atom_constant<V>{}; /// Used for request operations. using add_atom = atom_constant<atom("add")>; /// Used for request operations. using get_atom = atom_constant<atom("get")>; /// Used for request operations. using put_atom = atom_constant<atom("put")>; /// Used for signalizing updates, e.g., in a key-value store. using update_atom = atom_constant<atom("update")>; /// Used for request operations. using delete_atom = atom_constant<atom("delete")>; /// Used for response messages. using ok_atom = atom_constant<atom("ok")>; /// Used for triggering system-level message handling. using sys_atom = atom_constant<atom("sys")>; /// Used for signaling group subscriptions. using join_atom = atom_constant<atom("join")>; /// Used for signaling group unsubscriptions. using leave_atom = atom_constant<atom("leave")>; /// Used for signaling forwarding paths. using forward_atom = atom_constant<atom("forward")>; /// Used for buffer management. using flush_atom = atom_constant<atom("flush")>; /// Used for I/O redirection. using redirect_atom = atom_constant<atom("redirect")>; /// Used for link requests over network. using link_atom = atom_constant<atom("link")>; /// Used for removing networked links. using unlink_atom = atom_constant<atom("unlink")>; /// Used for publishing actors at a given port. using publish_atom = atom_constant<atom("publish")>; /// Used for publishing actors at a given port. using publish_udp_atom = atom_constant<atom("pub_udp")>; /// Used for removing an actor/port mapping. using unpublish_atom = atom_constant<atom("unpublish")>; /// Used for removing an actor/port mapping. using unpublish_udp_atom = atom_constant<atom("unpub_udp")>; /// Used for signalizing group membership. using subscribe_atom = atom_constant<atom("subscribe")>; /// Used for withdrawing group membership. using unsubscribe_atom = atom_constant<atom("unsubscrib")>; /// Used for establishing network connections. using connect_atom = atom_constant<atom("connect")>; /// Used for contacting a remote UDP endpoint using contact_atom = atom_constant<atom("contact")>; /// Used for opening ports or files. using open_atom = atom_constant<atom("open")>; /// Used for closing ports or files. using close_atom = atom_constant<atom("close")>; /// Used for spawning remote actors. using spawn_atom = atom_constant<atom("spawn")>; /// Used for migrating actors to other nodes. using migrate_atom = atom_constant<atom("migrate")>; /// Used for triggering periodic operations. using tick_atom = atom_constant<atom("tick")>; /// Used for pending out of order messages. using pending_atom = atom_constant<atom("pending")>; /// Used as timeout type for `timeout_msg`. using receive_atom = atom_constant<atom("receive")>; /// Used as timeout type for `timeout_msg`. using stream_atom = atom_constant<atom("stream")>; } // namespace caf namespace std { template <> struct hash<caf::atom_value> { size_t operator()(caf::atom_value x) const { hash<uint64_t> f; return f(static_cast<uint64_t>(x)); } }; } // namespace std
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <string> #include <functional> #include <type_traits> #include "caf/detail/atom_val.hpp" namespace caf { /// The value type of atoms. enum class atom_value : uint64_t { /// @cond PRIVATE dirty_little_hack = 31337 /// @endcond }; /// @relates atom_value std::string to_string(const atom_value& what); atom_value atom_from_string(const std::string& x); /// Creates an atom from given string literal. template <size_t Size> constexpr atom_value atom(char const (&str)[Size]) { // last character is the NULL terminator static_assert(Size <= 11, "only 10 characters are allowed"); return static_cast<atom_value>(detail::atom_val(str)); } /// Creates an atom from given string literal and return an integer /// representation of the atom.. template <size_t Size> constexpr uint64_t atom_uint(char const (&str)[Size]) { static_assert(Size <= 11, "only 10 characters are allowed"); return detail::atom_val(str); } /// Converts an atom to its integer representation. constexpr uint64_t atom_uint(atom_value x) { return static_cast<uint64_t>(x); } /// Lifts an `atom_value` to a compile-time constant. template <atom_value V> struct atom_constant { constexpr atom_constant() { // nop } /// Returns the wrapped value. constexpr operator atom_value() const { return V; } /// Returns the wrapped value as its base type. static constexpr uint64_t uint_value() { return static_cast<uint64_t>(V); } /// Returns the wrapped value. static constexpr atom_value get_value() { return V; } /// Returns an instance *of this constant* (*not* an `atom_value`). static const atom_constant value; }; template <class T> struct is_atom_constant { static constexpr bool value = false; }; template <atom_value X> struct is_atom_constant<atom_constant<X>> { static constexpr bool value = true; }; template <atom_value V> std::string to_string(const atom_constant<V>&) { return to_string(V); } template <atom_value V> const atom_constant<V> atom_constant<V>::value = atom_constant<V>{}; /// Used for request operations. using add_atom = atom_constant<atom("add")>; /// Used for request operations. using get_atom = atom_constant<atom("get")>; /// Used for request operations. using put_atom = atom_constant<atom("put")>; /// Used for signalizing updates, e.g., in a key-value store. using update_atom = atom_constant<atom("update")>; /// Used for request operations. using delete_atom = atom_constant<atom("delete")>; /// Used for response messages. using ok_atom = atom_constant<atom("ok")>; /// Used for triggering system-level message handling. using sys_atom = atom_constant<atom("sys")>; /// Used for signaling group subscriptions. using join_atom = atom_constant<atom("join")>; /// Used for signaling group unsubscriptions. using leave_atom = atom_constant<atom("leave")>; /// Used for signaling forwarding paths. using forward_atom = atom_constant<atom("forward")>; /// Used for buffer management. using flush_atom = atom_constant<atom("flush")>; /// Used for I/O redirection. using redirect_atom = atom_constant<atom("redirect")>; /// Used for link requests over network. using link_atom = atom_constant<atom("link")>; /// Used for removing networked links. using unlink_atom = atom_constant<atom("unlink")>; /// Used for publishing actors at a given port. using publish_atom = atom_constant<atom("publish")>; /// Used for publishing actors at a given port. using publish_udp_atom = atom_constant<atom("pub_udp")>; /// Used for removing an actor/port mapping. using unpublish_atom = atom_constant<atom("unpublish")>; /// Used for removing an actor/port mapping. using unpublish_udp_atom = atom_constant<atom("unpub_udp")>; /// Used for signalizing group membership. using subscribe_atom = atom_constant<atom("subscribe")>; /// Used for withdrawing group membership. using unsubscribe_atom = atom_constant<atom("unsubscrib")>; /// Used for establishing network connections. using connect_atom = atom_constant<atom("connect")>; /// Used for contacting a remote UDP endpoint using contact_atom = atom_constant<atom("contact")>; /// Used for opening ports or files. using open_atom = atom_constant<atom("open")>; /// Used for closing ports or files. using close_atom = atom_constant<atom("close")>; /// Used for spawning remote actors. using spawn_atom = atom_constant<atom("spawn")>; /// Used for migrating actors to other nodes. using migrate_atom = atom_constant<atom("migrate")>; /// Used for triggering periodic operations. using tick_atom = atom_constant<atom("tick")>; /// Used for pending out of order messages. using pending_atom = atom_constant<atom("pending")>; /// Used as timeout type for `timeout_msg`. using receive_atom = atom_constant<atom("receive")>; /// Used as timeout type for `timeout_msg`. using stream_atom = atom_constant<atom("stream")>; } // namespace caf namespace std { template <> struct hash<caf::atom_value> { size_t operator()(caf::atom_value x) const { hash<uint64_t> f; return f(static_cast<uint64_t>(x)); } }; } // namespace std
Add static getter to atom constants
Add static getter to atom constants
C++
bsd-3-clause
actor-framework/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework
3f8be2aabc01836f7ae143f685d1a680937df256
libethcore/BlockInfo.cpp
libethcore/BlockInfo.cpp
/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file BlockInfo.cpp * @author Gav Wood <[email protected]> * @date 2014 */ #include <libdevcore/Common.h> #include <libdevcore/RLP.h> #include <libdevcrypto/TrieDB.h> #include <libethcore/CommonEth.h> #include "ProofOfWork.h" #include "Exceptions.h" #include "BlockInfo.h" using namespace std; using namespace dev; using namespace dev::eth; u256 dev::eth::c_genesisDifficulty = (u256)1 << 11; BlockInfo::BlockInfo(): timestamp(Invalid256) { } BlockInfo::BlockInfo(bytesConstRef _block, bool _checkNonce) { populate(_block, _checkNonce); } void BlockInfo::setEmpty() { parentHash = h256(); sha3Uncles = EmptyListSHA3; coinbaseAddress = Address(); stateRoot = EmptyTrie; transactionsRoot = EmptyTrie; receiptsRoot = EmptyTrie; logBloom = LogBloom(); difficulty = 0; number = 0; gasLimit = 0; gasUsed = 0; timestamp = 0; extraData.clear(); seedHash = h256(); mixBytes = h256(); nonce = Nonce(); hash = headerHash(WithNonce); } BlockInfo BlockInfo::fromHeader(bytesConstRef _block) { BlockInfo ret; ret.populateFromHeader(RLP(_block)); return ret; } h256 BlockInfo::headerHash(IncludeNonce _n) const { RLPStream s; streamRLP(s, _n); return sha3(s.out()); } void BlockInfo::streamRLP(RLPStream& _s, IncludeNonce _n) const { _s.appendList(_n == WithNonce ? 16 : 14) << parentHash << sha3Uncles << coinbaseAddress << stateRoot << transactionsRoot << receiptsRoot << logBloom << difficulty << number << gasLimit << gasUsed << timestamp << extraData << seedHash; if (_n == WithNonce) _s << mixBytes << nonce; } h256 BlockInfo::headerHash(bytesConstRef _block) { return sha3(RLP(_block)[0].data()); } void BlockInfo::populateFromHeader(RLP const& _header, bool _checkNonce) { hash = dev::sha3(_header.data()); int field = 0; try { parentHash = _header[field = 0].toHash<h256>(); sha3Uncles = _header[field = 1].toHash<h256>(); coinbaseAddress = _header[field = 2].toHash<Address>(); stateRoot = _header[field = 3].toHash<h256>(); transactionsRoot = _header[field = 4].toHash<h256>(); receiptsRoot = _header[field = 5].toHash<h256>(); logBloom = _header[field = 6].toHash<LogBloom>(); difficulty = _header[field = 7].toInt<u256>(); number = _header[field = 8].toInt<u256>(); gasLimit = _header[field = 9].toInt<u256>(); gasUsed = _header[field = 10].toInt<u256>(); timestamp = _header[field = 11].toInt<u256>(); extraData = _header[field = 12].toBytes(); seedHash = _header[field = 13].toHash<h256>(); mixBytes = _header[field = 14].toHash<h256>(); nonce = _header[field = 15].toHash<Nonce>(); } catch (Exception const& _e) { _e << errinfo_name("invalid block header format") << BadFieldError(field, toHex(_header[field].data().toBytes())); throw; } // check it hashes according to proof of work or that it's the genesis block. if (_checkNonce && parentHash && !ProofOfWork::verify(*this)) BOOST_THROW_EXCEPTION(InvalidBlockNonce(headerHash(WithoutNonce), nonce, difficulty)); if (gasUsed > gasLimit) BOOST_THROW_EXCEPTION(TooMuchGasUsed()); if (number && extraData.size() > 1024) BOOST_THROW_EXCEPTION(ExtraDataTooBig()); } void BlockInfo::populate(bytesConstRef _block, bool _checkNonce) { RLP root(_block); RLP header = root[0]; if (!header.isList()) BOOST_THROW_EXCEPTION(InvalidBlockFormat(0, header.data()) << errinfo_comment("block header needs to be a list")); populateFromHeader(header, _checkNonce); if (!root[1].isList()) BOOST_THROW_EXCEPTION(InvalidBlockFormat(1, root[1].data())); if (!root[2].isList()) BOOST_THROW_EXCEPTION(InvalidBlockFormat(2, root[2].data())); } void BlockInfo::verifyInternals(bytesConstRef _block) const { RLP root(_block); u256 mgp = (u256)-1; OverlayDB db; GenericTrieDB<OverlayDB> t(&db); t.init(); unsigned i = 0; for (auto const& tr: root[1]) { bytes k = rlp(i); t.insert(&k, tr.data()); u256 gasprice = tr[1].toInt<u256>(); mgp = min(mgp, gasprice); // the minimum gas price is not used for anything //TODO delete? ++i; } if (transactionsRoot != t.root()) BOOST_THROW_EXCEPTION(InvalidTransactionsHash(t.root(), transactionsRoot)); if (sha3Uncles != sha3(root[2].data())) BOOST_THROW_EXCEPTION(InvalidUnclesHash()); } void BlockInfo::populateFromParent(BlockInfo const& _parent) { stateRoot = _parent.stateRoot; parentHash = _parent.hash; number = _parent.number + 1; gasLimit = calculateGasLimit(_parent); gasUsed = 0; difficulty = calculateDifficulty(_parent); seedHash = number % 30 == 0 ? sha3(_parent.seedHash.asBytes() /*+ _parent.hash.asBytes()*/) : _parent.seedHash; } u256 BlockInfo::calculateGasLimit(BlockInfo const& _parent) const { if (!parentHash) return 1000000; else return max<u256>(125000, (_parent.gasLimit * (1024 - 1) + (_parent.gasUsed * 6 / 5)) / 1024); } u256 BlockInfo::calculateDifficulty(BlockInfo const& _parent) const { if (!parentHash) return c_genesisDifficulty; else return max<u256>(2048, timestamp >= _parent.timestamp + (c_protocolVersion == 49 ? 5 : 8) ? _parent.difficulty - (_parent.difficulty / 2048) : (_parent.difficulty + (_parent.difficulty / 2048))); } template <class N> inline N diff(N const& _a, N const& _b) { return max(_a, _b) - min(_a, _b); } void BlockInfo::verifyParent(BlockInfo const& _parent) const { // Check difficulty is correct given the two timestamps. if (difficulty != calculateDifficulty(_parent)) BOOST_THROW_EXCEPTION(InvalidDifficulty()); if (diff(gasLimit, _parent.gasLimit) <= _parent.gasLimit / 1024) BOOST_THROW_EXCEPTION(InvalidGasLimit(gasLimit, calculateGasLimit(_parent), diff(gasLimit, _parent.gasLimit), _parent.gasLimit / 1024)); // Check timestamp is after previous timestamp. if (parentHash) { if (parentHash != _parent.hash) BOOST_THROW_EXCEPTION(InvalidParentHash()); if (timestamp <= _parent.timestamp) BOOST_THROW_EXCEPTION(InvalidTimestamp()); if (number != _parent.number + 1) BOOST_THROW_EXCEPTION(InvalidNumber()); } }
/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file BlockInfo.cpp * @author Gav Wood <[email protected]> * @date 2014 */ #include <libdevcore/Common.h> #include <libdevcore/RLP.h> #include <libdevcrypto/TrieDB.h> #include <libethcore/CommonEth.h> #include "ProofOfWork.h" #include "Exceptions.h" #include "BlockInfo.h" using namespace std; using namespace dev; using namespace dev::eth; u256 dev::eth::c_genesisDifficulty = (u256)1 << 11; BlockInfo::BlockInfo(): timestamp(Invalid256) { } BlockInfo::BlockInfo(bytesConstRef _block, bool _checkNonce) { populate(_block, _checkNonce); } void BlockInfo::setEmpty() { parentHash = h256(); sha3Uncles = EmptyListSHA3; coinbaseAddress = Address(); stateRoot = EmptyTrie; transactionsRoot = EmptyTrie; receiptsRoot = EmptyTrie; logBloom = LogBloom(); difficulty = 0; number = 0; gasLimit = 0; gasUsed = 0; timestamp = 0; extraData.clear(); seedHash = h256(); mixBytes = h256(); nonce = Nonce(); hash = headerHash(WithNonce); } BlockInfo BlockInfo::fromHeader(bytesConstRef _block) { BlockInfo ret; ret.populateFromHeader(RLP(_block)); return ret; } h256 BlockInfo::headerHash(IncludeNonce _n) const { RLPStream s; streamRLP(s, _n); return sha3(s.out()); } void BlockInfo::streamRLP(RLPStream& _s, IncludeNonce _n) const { _s.appendList(_n == WithNonce ? 16 : 14) << parentHash << sha3Uncles << coinbaseAddress << stateRoot << transactionsRoot << receiptsRoot << logBloom << difficulty << number << gasLimit << gasUsed << timestamp << extraData << seedHash; if (_n == WithNonce) _s << mixBytes << nonce; } h256 BlockInfo::headerHash(bytesConstRef _block) { return sha3(RLP(_block)[0].data()); } void BlockInfo::populateFromHeader(RLP const& _header, bool _checkNonce) { hash = dev::sha3(_header.data()); int field = 0; try { parentHash = _header[field = 0].toHash<h256>(); sha3Uncles = _header[field = 1].toHash<h256>(); coinbaseAddress = _header[field = 2].toHash<Address>(); stateRoot = _header[field = 3].toHash<h256>(); transactionsRoot = _header[field = 4].toHash<h256>(); receiptsRoot = _header[field = 5].toHash<h256>(); logBloom = _header[field = 6].toHash<LogBloom>(); difficulty = _header[field = 7].toInt<u256>(); number = _header[field = 8].toInt<u256>(); gasLimit = _header[field = 9].toInt<u256>(); gasUsed = _header[field = 10].toInt<u256>(); timestamp = _header[field = 11].toInt<u256>(); extraData = _header[field = 12].toBytes(); seedHash = _header[field = 13].toHash<h256>(); mixBytes = _header[field = 14].toHash<h256>(); nonce = _header[field = 15].toHash<Nonce>(); } catch (Exception const& _e) { _e << errinfo_name("invalid block header format") << BadFieldError(field, toHex(_header[field].data().toBytes())); throw; } // check it hashes according to proof of work or that it's the genesis block. if (_checkNonce && parentHash && !ProofOfWork::verify(*this)) BOOST_THROW_EXCEPTION(InvalidBlockNonce(headerHash(WithoutNonce), nonce, difficulty)); if (gasUsed > gasLimit) BOOST_THROW_EXCEPTION(TooMuchGasUsed()); if (number && extraData.size() > 1024) BOOST_THROW_EXCEPTION(ExtraDataTooBig()); } void BlockInfo::populate(bytesConstRef _block, bool _checkNonce) { RLP root(_block); RLP header = root[0]; if (!header.isList()) BOOST_THROW_EXCEPTION(InvalidBlockFormat(0, header.data()) << errinfo_comment("block header needs to be a list")); populateFromHeader(header, _checkNonce); if (!root[1].isList()) BOOST_THROW_EXCEPTION(InvalidBlockFormat(1, root[1].data())); if (!root[2].isList()) BOOST_THROW_EXCEPTION(InvalidBlockFormat(2, root[2].data())); } void BlockInfo::verifyInternals(bytesConstRef _block) const { RLP root(_block); u256 mgp = (u256)-1; OverlayDB db; GenericTrieDB<OverlayDB> t(&db); t.init(); unsigned i = 0; for (auto const& tr: root[1]) { bytes k = rlp(i); t.insert(&k, tr.data()); u256 gasprice = tr[1].toInt<u256>(); mgp = min(mgp, gasprice); // the minimum gas price is not used for anything //TODO delete? ++i; } if (transactionsRoot != t.root()) BOOST_THROW_EXCEPTION(InvalidTransactionsHash(t.root(), transactionsRoot)); if (sha3Uncles != sha3(root[2].data())) BOOST_THROW_EXCEPTION(InvalidUnclesHash()); } void BlockInfo::populateFromParent(BlockInfo const& _parent) { stateRoot = _parent.stateRoot; parentHash = _parent.hash; number = _parent.number + 1; gasLimit = calculateGasLimit(_parent); gasUsed = 0; difficulty = calculateDifficulty(_parent); seedHash = number % 30 == 0 ? sha3(_parent.seedHash.asBytes() /*+ _parent.hash.asBytes()*/) : _parent.seedHash; } u256 BlockInfo::calculateGasLimit(BlockInfo const& _parent) const { if (!parentHash) return 1000000; else return max<u256>(125000, (_parent.gasLimit * (1024 - 1) + (_parent.gasUsed * 6 / 5)) / 1024); } u256 BlockInfo::calculateDifficulty(BlockInfo const& _parent) const { if (!parentHash) return c_genesisDifficulty; else return max<u256>(2048, timestamp >= _parent.timestamp + (c_protocolVersion == 49 ? 5 : 8) ? _parent.difficulty - (_parent.difficulty / 2048) : (_parent.difficulty + (_parent.difficulty / 2048))); } template <class N> inline N diff(N const& _a, N const& _b) { return max(_a, _b) - min(_a, _b); } void BlockInfo::verifyParent(BlockInfo const& _parent) const { // Check difficulty is correct given the two timestamps. if (difficulty != calculateDifficulty(_parent)) BOOST_THROW_EXCEPTION(InvalidDifficulty()); if (diff(gasLimit, _parent.gasLimit) <= _parent.gasLimit / 2048) BOOST_THROW_EXCEPTION(InvalidGasLimit(gasLimit, calculateGasLimit(_parent), diff(gasLimit, _parent.gasLimit), _parent.gasLimit / 2048)); // Check timestamp is after previous timestamp. if (parentHash) { if (parentHash != _parent.hash) BOOST_THROW_EXCEPTION(InvalidParentHash()); if (timestamp <= _parent.timestamp) BOOST_THROW_EXCEPTION(InvalidTimestamp()); if (number != _parent.number + 1) BOOST_THROW_EXCEPTION(InvalidNumber()); } }
fix blockGasLimit bug : 1024 -> 2048
fix blockGasLimit bug : 1024 -> 2048
C++
mit
johnpeter66/ethminer,d-das/cpp-ethereum,LefterisJP/cpp-ethereum,Sorceror32/go-get--u-github.com-tools-godep,yann300/cpp-ethereum,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,anthony-cros/cpp-ethereum,eco/cpp-ethereum,anthony-cros/cpp-ethereum,smartbitcoin/cpp-ethereum,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,ethers/cpp-ethereum,eco/cpp-ethereum,smartbitcoin/cpp-ethereum,karek314/cpp-ethereum,yann300/cpp-ethereum,xeddmc/cpp-ethereum,subtly/cpp-ethereum-micro,Sorceror32/go-get--u-github.com-tools-godep,gluk256/cpp-ethereum,vaporry/cpp-ethereum,PaulGrey30/go-get--u-github.com-tools-godep,karek314/cpp-ethereum,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,d-das/cpp-ethereum,yann300/cpp-ethereum,anthony-cros/cpp-ethereum,chfast/webthree-umbrella,expanse-project/cpp-expanse,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,subtly/cpp-ethereum-micro,gluk256/cpp-ethereum,expanse-project/cpp-expanse,LefterisJP/webthree-umbrella,vaporry/cpp-ethereum,expanse-project/cpp-expanse,joeldo/cpp-ethereum,programonauta/webthree-umbrella,LefterisJP/cpp-ethereum,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,johnpeter66/ethminer,ethers/cpp-ethereum,joeldo/cpp-ethereum,smartbitcoin/cpp-ethereum,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,vaporry/cpp-ethereum,PaulGrey30/go-get--u-github.com-tools-godep,ethers/cpp-ethereum,ethers/cpp-ethereum,Sorceror32/go-get--u-github.com-tools-godep,eco/cpp-ethereum,smartbitcoin/cpp-ethereum,yann300/cpp-ethereum,expanse-org/cpp-expanse,ethers/cpp-ethereum,Sorceror32/go-get--u-github.com-tools-godep,expanse-org/cpp-expanse,subtly/cpp-ethereum-micro,anthony-cros/cpp-ethereum,joeldo/cpp-ethereum,karek314/cpp-ethereum,gluk256/cpp-ethereum,expanse-org/cpp-expanse,smartbitcoin/cpp-ethereum,subtly/cpp-ethereum-micro,PaulGrey30/go-get--u-github.com-tools-godep,vaporry/cpp-ethereum,yann300/cpp-ethereum,anthony-cros/cpp-ethereum,yann300/cpp-ethereum,eco/cpp-ethereum,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,arkpar/webthree-umbrella,Sorceror32/go-get--u-github.com-tools-godep,gluk256/cpp-ethereum,vaporry/cpp-ethereum,karek314/cpp-ethereum,anthony-cros/cpp-ethereum,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,expanse-org/cpp-expanse,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,vaporry/cpp-ethereum,joeldo/cpp-ethereum,karek314/cpp-ethereum,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,LefterisJP/cpp-ethereum,expanse-project/cpp-expanse,vaporry/webthree-umbrella,ethers/cpp-ethereum,eco/cpp-ethereum,xeddmc/cpp-ethereum,expanse-org/cpp-expanse,d-das/cpp-ethereum,d-das/cpp-ethereum,LefterisJP/cpp-ethereum,subtly/cpp-ethereum-micro,joeldo/cpp-ethereum,joeldo/cpp-ethereum,karek314/cpp-ethereum,smartbitcoin/cpp-ethereum,johnpeter66/ethminer,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,Sorceror32/go-get--u-github.com-tools-godep,LefterisJP/cpp-ethereum,xeddmc/cpp-ethereum,eco/cpp-ethereum,subtly/cpp-ethereum-micro,gluk256/cpp-ethereum,PaulGrey30/go-get--u-github.com-tools-godep,LefterisJP/cpp-ethereum,LefterisJP/webthree-umbrella,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,d-das/cpp-ethereum,expanse-project/cpp-expanse,expanse-org/cpp-expanse,xeddmc/cpp-ethereum,d-das/cpp-ethereum,PaulGrey30/go-get--u-github.com-tools-godep,xeddmc/cpp-ethereum,xeddmc/cpp-ethereum,programonauta/webthree-umbrella,gluk256/cpp-ethereum,expanse-project/cpp-expanse,PaulGrey30/go-get--u-github.com-tools-godep
a63893ede973f2ab4ff2771ea12ce9497c48d593
libethcore/BlockInfo.cpp
libethcore/BlockInfo.cpp
/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file BlockInfo.cpp * @author Gav Wood <[email protected]> * @date 2014 */ #include <libdevcore/Common.h> #include <libdevcore/RLP.h> #include <libdevcrypto/TrieDB.h> #include <libethcore/Common.h> #include "ProofOfWork.h" #include "Exceptions.h" #include "Params.h" #include "BlockInfo.h" using namespace std; using namespace dev; using namespace dev::eth; BlockInfo::BlockInfo(): timestamp(Invalid256) { } BlockInfo::BlockInfo(bytesConstRef _block, bool _checkNonce) { populate(_block, _checkNonce); } void BlockInfo::setEmpty() { parentHash = h256(); sha3Uncles = EmptyListSHA3; coinbaseAddress = Address(); stateRoot = EmptyTrie; transactionsRoot = EmptyTrie; receiptsRoot = EmptyTrie; logBloom = LogBloom(); difficulty = 0; number = 0; gasLimit = 0; gasUsed = 0; timestamp = 0; extraData.clear(); seedHash = h256(); mixHash = h256(); nonce = Nonce(); hash = headerHash(WithNonce); } BlockInfo BlockInfo::fromHeader(bytesConstRef _block) { BlockInfo ret; ret.populateFromHeader(RLP(_block)); return ret; } h256 BlockInfo::headerHash(IncludeNonce _n) const { RLPStream s; streamRLP(s, _n); return sha3(s.out()); } void BlockInfo::streamRLP(RLPStream& _s, IncludeNonce _n) const { _s.appendList(_n == WithNonce ? 16 : 14) << parentHash << sha3Uncles << coinbaseAddress << stateRoot << transactionsRoot << receiptsRoot << logBloom << difficulty << number << gasLimit << gasUsed << timestamp << extraData << seedHash; if (_n == WithNonce) _s << mixHash << nonce; } h256 BlockInfo::headerHash(bytesConstRef _block) { return sha3(RLP(_block)[0].data()); } void BlockInfo::populateFromHeader(RLP const& _header, bool _checkNonce) { hash = dev::sha3(_header.data()); int field = 0; try { parentHash = _header[field = 0].toHash<h256>(RLP::VeryStrict); sha3Uncles = _header[field = 1].toHash<h256>(RLP::VeryStrict); coinbaseAddress = _header[field = 2].toHash<Address>(RLP::VeryStrict); stateRoot = _header[field = 3].toHash<h256>(RLP::VeryStrict); transactionsRoot = _header[field = 4].toHash<h256>(RLP::VeryStrict); receiptsRoot = _header[field = 5].toHash<h256>(RLP::VeryStrict); logBloom = _header[field = 6].toHash<LogBloom>(RLP::VeryStrict); difficulty = _header[field = 7].toInt<u256>(); number = _header[field = 8].toInt<u256>(); gasLimit = _header[field = 9].toInt<u256>(); gasUsed = _header[field = 10].toInt<u256>(); timestamp = _header[field = 11].toInt<u256>(); extraData = _header[field = 12].toBytes(); seedHash = _header[field = 13].toHash<h256>(RLP::VeryStrict); mixHash = _header[field = 14].toHash<h256>(RLP::VeryStrict); nonce = _header[field = 15].toHash<Nonce>(RLP::VeryStrict); } catch (Exception const& _e) { _e << errinfo_name("invalid block header format") << BadFieldError(field, toHex(_header[field].data().toBytes())); throw; } // check it hashes according to proof of work or that it's the genesis block. if (_checkNonce && parentHash && !ProofOfWork::verify(*this)) BOOST_THROW_EXCEPTION(InvalidBlockNonce(headerHash(WithoutNonce), nonce, difficulty)); if (gasUsed > gasLimit) BOOST_THROW_EXCEPTION(TooMuchGasUsed()); if (number && extraData.size() > c_maximumExtraDataSize) BOOST_THROW_EXCEPTION(ExtraDataTooBig()); } void BlockInfo::populate(bytesConstRef _block, bool _checkNonce) { RLP root(_block); RLP header = root[0]; if (!header.isList()) BOOST_THROW_EXCEPTION(InvalidBlockFormat(0, header.data()) << errinfo_comment("block header needs to be a list")); populateFromHeader(header, _checkNonce); if (!root[1].isList()) BOOST_THROW_EXCEPTION(InvalidBlockFormat(1, root[1].data())); if (!root[2].isList()) BOOST_THROW_EXCEPTION(InvalidBlockFormat(2, root[2].data())); } void BlockInfo::verifyInternals(bytesConstRef _block) const { RLP root(_block); u256 mgp = (u256)-1; OverlayDB db; GenericTrieDB<OverlayDB> t(&db); t.init(); unsigned i = 0; for (auto const& tr: root[1]) { bytes k = rlp(i); t.insert(&k, tr.data()); u256 gasprice = tr[1].toInt<u256>(); mgp = min(mgp, gasprice); // the minimum gas price is not used for anything //TODO delete? ++i; } if (transactionsRoot != t.root()) BOOST_THROW_EXCEPTION(InvalidTransactionsHash(t.root(), transactionsRoot)); if (sha3Uncles != sha3(root[2].data())) BOOST_THROW_EXCEPTION(InvalidUnclesHash()); } void BlockInfo::populateFromParent(BlockInfo const& _parent) { stateRoot = _parent.stateRoot; parentHash = _parent.hash; number = _parent.number + 1; gasLimit = calculateGasLimit(_parent); gasUsed = 0; difficulty = calculateDifficulty(_parent); seedHash = calculateSeedHash(_parent); } h256 BlockInfo::calculateSeedHash(BlockInfo const& _parent) const { return number % c_epochDuration == 0 ? sha3(_parent.seedHash.asBytes()) : _parent.seedHash; } u256 BlockInfo::calculateGasLimit(BlockInfo const& _parent) const { if (!parentHash) return c_genesisGasLimit; else return max<u256>(c_minGasLimit, (_parent.gasLimit * (c_gasLimitBoundDivisor - 1) + (_parent.gasUsed * 6 / 5)) / c_gasLimitBoundDivisor); } u256 BlockInfo::calculateDifficulty(BlockInfo const& _parent) const { if (!parentHash) return (u256)c_genesisDifficulty; else return max<u256>(c_minimumDifficulty, timestamp >= _parent.timestamp + c_durationLimit ? _parent.difficulty - (_parent.difficulty / c_difficultyBoundDivisor) : (_parent.difficulty + (_parent.difficulty / c_difficultyBoundDivisor))); } void BlockInfo::verifyParent(BlockInfo const& _parent) const { // Check difficulty is correct given the two timestamps. if (difficulty != calculateDifficulty(_parent)) BOOST_THROW_EXCEPTION(InvalidDifficulty()); if (gasLimit < _parent.gasLimit * (c_gasLimitBoundDivisor - 1) / c_gasLimitBoundDivisor || gasLimit > _parent.gasLimit * (c_gasLimitBoundDivisor + 1) / c_gasLimitBoundDivisor) BOOST_THROW_EXCEPTION(InvalidGasLimit(gasLimit, _parent.gasLimit * (c_gasLimitBoundDivisor - 1) / c_gasLimitBoundDivisor, _parent.gasLimit * (c_gasLimitBoundDivisor + 1) / c_gasLimitBoundDivisor)); if (seedHash != calculateSeedHash(_parent)) BOOST_THROW_EXCEPTION(InvalidSeedHash()); // Check timestamp is after previous timestamp. if (parentHash) { if (parentHash != _parent.hash) BOOST_THROW_EXCEPTION(InvalidParentHash()); if (timestamp <= _parent.timestamp) BOOST_THROW_EXCEPTION(InvalidTimestamp()); if (number != _parent.number + 1) BOOST_THROW_EXCEPTION(InvalidNumber()); } }
/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file BlockInfo.cpp * @author Gav Wood <[email protected]> * @date 2014 */ #include <libdevcore/Common.h> #include <libdevcore/RLP.h> #include <libdevcrypto/TrieDB.h> #include <libethcore/Common.h> #include "ProofOfWork.h" #include "Exceptions.h" #include "Params.h" #include "BlockInfo.h" using namespace std; using namespace dev; using namespace dev::eth; BlockInfo::BlockInfo(): timestamp(Invalid256) { } BlockInfo::BlockInfo(bytesConstRef _block, bool _checkNonce) { populate(_block, _checkNonce); } void BlockInfo::setEmpty() { parentHash = h256(); sha3Uncles = EmptyListSHA3; coinbaseAddress = Address(); stateRoot = EmptyTrie; transactionsRoot = EmptyTrie; receiptsRoot = EmptyTrie; logBloom = LogBloom(); difficulty = 0; number = 0; gasLimit = 0; gasUsed = 0; timestamp = 0; extraData.clear(); seedHash = h256(); mixHash = h256(); nonce = Nonce(); hash = headerHash(WithNonce); } BlockInfo BlockInfo::fromHeader(bytesConstRef _block) { BlockInfo ret; ret.populateFromHeader(RLP(_block)); return ret; } h256 BlockInfo::headerHash(IncludeNonce _n) const { RLPStream s; streamRLP(s, _n); return sha3(s.out()); } void BlockInfo::streamRLP(RLPStream& _s, IncludeNonce _n) const { _s.appendList(_n == WithNonce ? 16 : 14) << parentHash << sha3Uncles << coinbaseAddress << stateRoot << transactionsRoot << receiptsRoot << logBloom << difficulty << number << gasLimit << gasUsed << timestamp << extraData << seedHash; if (_n == WithNonce) _s << mixHash << nonce; } h256 BlockInfo::headerHash(bytesConstRef _block) { return sha3(RLP(_block)[0].data()); } void BlockInfo::populateFromHeader(RLP const& _header, bool _checkNonce) { hash = dev::sha3(_header.data()); int field = 0; try { parentHash = _header[field = 0].toHash<h256>(RLP::VeryStrict); sha3Uncles = _header[field = 1].toHash<h256>(RLP::VeryStrict); coinbaseAddress = _header[field = 2].toHash<Address>(RLP::VeryStrict); stateRoot = _header[field = 3].toHash<h256>(RLP::VeryStrict); transactionsRoot = _header[field = 4].toHash<h256>(RLP::VeryStrict); receiptsRoot = _header[field = 5].toHash<h256>(RLP::VeryStrict); logBloom = _header[field = 6].toHash<LogBloom>(RLP::VeryStrict); difficulty = _header[field = 7].toInt<u256>(); number = _header[field = 8].toInt<u256>(); gasLimit = _header[field = 9].toInt<u256>(); gasUsed = _header[field = 10].toInt<u256>(); timestamp = _header[field = 11].toInt<u256>(); extraData = _header[field = 12].toBytes(); seedHash = _header[field = 13].toHash<h256>(RLP::VeryStrict); mixHash = _header[field = 14].toHash<h256>(RLP::VeryStrict); nonce = _header[field = 15].toHash<Nonce>(RLP::VeryStrict); } catch (Exception const& _e) { _e << errinfo_name("invalid block header format") << BadFieldError(field, toHex(_header[field].data().toBytes())); throw; } // check it hashes according to proof of work or that it's the genesis block. if (_checkNonce && parentHash && !ProofOfWork::verify(*this)) BOOST_THROW_EXCEPTION(InvalidBlockNonce(headerHash(WithoutNonce), nonce, difficulty)); if (gasUsed > gasLimit) BOOST_THROW_EXCEPTION(TooMuchGasUsed() << RequirementError(bigint(gasLimit), bigint(gasUsed)) ); if (difficulty < c_minimumDifficulty) BOOST_THROW_EXCEPTION(InvalidDifficulty() << RequirementError(bigint(c_minimumDifficulty), bigint(difficulty)) ); if (gasLimit < c_minGasLimit) BOOST_THROW_EXCEPTION(InvalidGasLimit() << RequirementError(bigint(c_minGasLimit), bigint(gasLimit)) ); if (number && extraData.size() > c_maximumExtraDataSize) BOOST_THROW_EXCEPTION(ExtraDataTooBig() << RequirementError(bigint(c_maximumExtraDataSize), bigint(extraData.size()))); } void BlockInfo::populate(bytesConstRef _block, bool _checkNonce) { RLP root(_block); RLP header = root[0]; if (!header.isList()) BOOST_THROW_EXCEPTION(InvalidBlockFormat(0, header.data()) << errinfo_comment("block header needs to be a list")); populateFromHeader(header, _checkNonce); if (!root[1].isList()) BOOST_THROW_EXCEPTION(InvalidBlockFormat(1, root[1].data())); if (!root[2].isList()) BOOST_THROW_EXCEPTION(InvalidBlockFormat(2, root[2].data())); } void BlockInfo::verifyInternals(bytesConstRef _block) const { RLP root(_block); u256 mgp = (u256)-1; OverlayDB db; GenericTrieDB<OverlayDB> t(&db); t.init(); unsigned i = 0; for (auto const& tr: root[1]) { bytes k = rlp(i); t.insert(&k, tr.data()); u256 gasprice = tr[1].toInt<u256>(); mgp = min(mgp, gasprice); // the minimum gas price is not used for anything //TODO delete? ++i; } if (transactionsRoot != t.root()) BOOST_THROW_EXCEPTION(InvalidTransactionsHash(t.root(), transactionsRoot)); if (sha3Uncles != sha3(root[2].data())) BOOST_THROW_EXCEPTION(InvalidUnclesHash()); } void BlockInfo::populateFromParent(BlockInfo const& _parent) { stateRoot = _parent.stateRoot; parentHash = _parent.hash; number = _parent.number + 1; gasLimit = calculateGasLimit(_parent); gasUsed = 0; difficulty = calculateDifficulty(_parent); seedHash = calculateSeedHash(_parent); } h256 BlockInfo::calculateSeedHash(BlockInfo const& _parent) const { return number % c_epochDuration == 0 ? sha3(_parent.seedHash.asBytes()) : _parent.seedHash; } u256 BlockInfo::calculateGasLimit(BlockInfo const& _parent) const { if (!parentHash) return c_genesisGasLimit; else return max<u256>(c_minGasLimit, (_parent.gasLimit * (c_gasLimitBoundDivisor - 1) + (_parent.gasUsed * 6 / 5)) / c_gasLimitBoundDivisor); } u256 BlockInfo::calculateDifficulty(BlockInfo const& _parent) const { if (!parentHash) return (u256)c_genesisDifficulty; else return max<u256>(c_minimumDifficulty, timestamp >= _parent.timestamp + c_durationLimit ? _parent.difficulty - (_parent.difficulty / c_difficultyBoundDivisor) : (_parent.difficulty + (_parent.difficulty / c_difficultyBoundDivisor))); } void BlockInfo::verifyParent(BlockInfo const& _parent) const { // Check difficulty is correct given the two timestamps. if (difficulty != calculateDifficulty(_parent)) BOOST_THROW_EXCEPTION(InvalidDifficulty() << RequirementError((bigint)calculateDifficulty(_parent), (bigint)difficulty)); if (gasLimit < _parent.gasLimit * (c_gasLimitBoundDivisor - 1) / c_gasLimitBoundDivisor || gasLimit > _parent.gasLimit * (c_gasLimitBoundDivisor + 1) / c_gasLimitBoundDivisor) BOOST_THROW_EXCEPTION(InvalidGasLimit(gasLimit, _parent.gasLimit * (c_gasLimitBoundDivisor - 1) / c_gasLimitBoundDivisor, _parent.gasLimit * (c_gasLimitBoundDivisor + 1) / c_gasLimitBoundDivisor)); if (seedHash != calculateSeedHash(_parent)) BOOST_THROW_EXCEPTION(InvalidSeedHash()); // Check timestamp is after previous timestamp. if (parentHash) { if (parentHash != _parent.hash) BOOST_THROW_EXCEPTION(InvalidParentHash()); if (timestamp <= _parent.timestamp) BOOST_THROW_EXCEPTION(InvalidTimestamp()); if (number != _parent.number + 1) BOOST_THROW_EXCEPTION(InvalidNumber()); } }
check for minGasLimit and minDifficulty when constructing block
check for minGasLimit and minDifficulty when constructing block
C++
mit
d-das/cpp-ethereum,PaulGrey30/go-get--u-github.com-tools-godep,anthony-cros/cpp-ethereum,joeldo/cpp-ethereum,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,anthony-cros/cpp-ethereum,gluk256/cpp-ethereum,xeddmc/cpp-ethereum,yann300/cpp-ethereum,joeldo/cpp-ethereum,expanse-org/cpp-expanse,Sorceror32/go-get--u-github.com-tools-godep,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,gluk256/cpp-ethereum,expanse-project/cpp-expanse,arkpar/webthree-umbrella,expanse-org/cpp-expanse,xeddmc/cpp-ethereum,vaporry/cpp-ethereum,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,gluk256/cpp-ethereum,PaulGrey30/go-get--u-github.com-tools-godep,Sorceror32/go-get--u-github.com-tools-godep,eco/cpp-ethereum,joeldo/cpp-ethereum,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,eco/cpp-ethereum,ethers/cpp-ethereum,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,anthony-cros/cpp-ethereum,xeddmc/cpp-ethereum,Sorceror32/go-get--u-github.com-tools-godep,ethers/cpp-ethereum,programonauta/webthree-umbrella,karek314/cpp-ethereum,LefterisJP/webthree-umbrella,expanse-project/cpp-expanse,expanse-org/cpp-expanse,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,vaporry/cpp-ethereum,karek314/cpp-ethereum,joeldo/cpp-ethereum,subtly/cpp-ethereum-micro,karek314/cpp-ethereum,smartbitcoin/cpp-ethereum,gluk256/cpp-ethereum,d-das/cpp-ethereum,d-das/cpp-ethereum,expanse-project/cpp-expanse,expanse-project/cpp-expanse,ethers/cpp-ethereum,anthony-cros/cpp-ethereum,yann300/cpp-ethereum,anthony-cros/cpp-ethereum,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,PaulGrey30/go-get--u-github.com-tools-godep,Sorceror32/go-get--u-github.com-tools-godep,xeddmc/cpp-ethereum,ethers/cpp-ethereum,PaulGrey30/go-get--u-github.com-tools-godep,smartbitcoin/cpp-ethereum,anthony-cros/cpp-ethereum,subtly/cpp-ethereum-micro,expanse-org/cpp-expanse,ethers/cpp-ethereum,LefterisJP/cpp-ethereum,karek314/cpp-ethereum,subtly/cpp-ethereum-micro,yann300/cpp-ethereum,eco/cpp-ethereum,karek314/cpp-ethereum,yann300/cpp-ethereum,joeldo/cpp-ethereum,d-das/cpp-ethereum,LefterisJP/webthree-umbrella,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,joeldo/cpp-ethereum,subtly/cpp-ethereum-micro,smartbitcoin/cpp-ethereum,LefterisJP/cpp-ethereum,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,programonauta/webthree-umbrella,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,d-das/cpp-ethereum,PaulGrey30/go-get--u-github.com-tools-godep,chfast/webthree-umbrella,expanse-org/cpp-expanse,gluk256/cpp-ethereum,Sorceror32/go-get--u-github.com-tools-godep,vaporry/cpp-ethereum,xeddmc/cpp-ethereum,LefterisJP/cpp-ethereum,johnpeter66/ethminer,smartbitcoin/cpp-ethereum,karek314/cpp-ethereum,LefterisJP/cpp-ethereum,LefterisJP/cpp-ethereum,expanse-org/cpp-expanse,smartbitcoin/cpp-ethereum,expanse-project/cpp-expanse,gluk256/cpp-ethereum,xeddmc/cpp-ethereum,LefterisJP/cpp-ethereum,yann300/cpp-ethereum,vaporry/cpp-ethereum,ethers/cpp-ethereum,johnpeter66/ethminer,eco/cpp-ethereum,PaulGrey30/go-get--u-github.com-tools-godep,vaporry/cpp-ethereum,d-das/cpp-ethereum,subtly/cpp-ethereum-micro,vaporry/webthree-umbrella,yann300/cpp-ethereum,eco/cpp-ethereum,smartbitcoin/cpp-ethereum,Sorceror32/go-get--u-github.com-tools-godep,expanse-project/cpp-expanse,subtly/cpp-ethereum-micro,vaporry/cpp-ethereum,eco/cpp-ethereum,johnpeter66/ethminer
a08ea58a14c7ff7b379c651008e9050936866bb7
dune/gdt/mapper/default/fv.hh
dune/gdt/mapper/default/fv.hh
// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_MAPPER_DEFAULT_FV_HH #define DUNE_GDT_MAPPER_DEFAULT_FV_HH #include <type_traits> #include <dune/common/dynvector.hh> #include <dune/stuff/common/debug.hh> #include <dune/stuff/common/type_utils.hh> #include "../../mapper/interface.hh" namespace Dune { namespace GDT { namespace Mapper { // forward template< class GridViewImp, size_t rangeDim = 1, size_t rangeDimCols = 1 > class FiniteVolume { static_assert(AlwaysFalse< GridViewImp >::value, "Not available for these dimensions!"); }; namespace internal { template< class GridViewImp, size_t rangeDim, size_t rangeDimCols > class FiniteVolumeTraits { static_assert(rangeDim >= 1, "Really?"); static_assert(rangeDimCols >= 1, "Really?"); public: typedef GridViewImp GridViewType; typedef FiniteVolume< GridViewType, rangeDim, rangeDimCols> derived_type; typedef typename GridViewImp::IndexSet BackendType; typedef typename GridViewType::template Codim< 0 >::Entity EntityType; }; } // namespace internal template< class GridViewImp > class FiniteVolume< GridViewImp, 1, 1 > : public MapperInterface< internal::FiniteVolumeTraits< GridViewImp, 1, 1 > > { typedef MapperInterface< internal::FiniteVolumeTraits< GridViewImp, 1, 1 > > InterfaceType; public: typedef internal::FiniteVolumeTraits< GridViewImp, 1, 1 > Traits; typedef typename Traits::GridViewType GridViewType; typedef typename Traits::BackendType BackendType; typedef typename Traits::EntityType EntityType; FiniteVolume(const GridViewType& grid_view) : backend_(grid_view.indexSet()) {} const BackendType& backend() const { return backend_; } size_t size() const { return backend_.size(0); } size_t numDofs(const EntityType& /*entity*/) const { return 1; } size_t maxNumDofs() const { return 1; } void globalIndices(const EntityType& entity, Dune::DynamicVector< size_t >& ret) const { if (ret.size() < 1) ret.resize(1); ret[0] = mapToGlobal(entity, 0); } // ... globalIndices(...) using InterfaceType::globalIndices; size_t mapToGlobal(const EntityType& entity, const size_t& UNUSED_UNLESS_DEBUG(localIndex)) const { assert(localIndex == 0); return backend_.index(entity); } private: const BackendType& backend_; }; // class FiniteVolume< ..., 1, 1 > template< class GridViewImp, size_t rangeDim > class FiniteVolume< GridViewImp, rangeDim, 1 > : public MapperInterface< internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > > { typedef MapperInterface< internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > > InterfaceType; static const size_t dimRange = rangeDim; public: typedef internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > Traits; typedef typename Traits::GridViewType GridViewType; typedef typename Traits::BackendType BackendType; typedef typename Traits::EntityType EntityType; FiniteVolume(const GridViewType& grid_view) : backend_(grid_view.indexSet()) {} const BackendType& backend() const { return backend_; } size_t size() const { return dimRange * backend_.size(0); } size_t numDofs(const EntityType& /*entity*/) const { return dimRange; } size_t maxNumDofs() const { return dimRange; } void globalIndices(const EntityType& entity, Dune::DynamicVector< size_t >& ret) const { if (ret.size() < dimRange) ret.resize(dimRange); const size_t base = dimRange * backend_.index(entity); for (size_t ii = 0; ii < dimRange; ++ii) ret[ii] = base + ii; } // ... globalIndices(...) using InterfaceType::globalIndices; size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const { assert(localIndex < dimRange); return (dimRange * backend_.index(entity)) + localIndex; } private: const BackendType& backend_; }; // class FiniteVolume< ..., rangeDim, 1 > } // namespace Mapper } // namespace GDT } // namespace Dune #endif // DUNE_GDT_MAPPER_DEFAULT_FV_HH
// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_MAPPER_DEFAULT_FV_HH #define DUNE_GDT_MAPPER_DEFAULT_FV_HH #include <type_traits> #include <dune/common/dynvector.hh> #include <dune/common/static_assert.hh> #include <dune/stuff/common/debug.hh> #include <dune/stuff/common/type_utils.hh> #include "../../mapper/interface.hh" namespace Dune { namespace GDT { namespace Mapper { // forward template< class GridViewImp, size_t rangeDim = 1, size_t rangeDimCols = 1 > class FiniteVolume { static_assert(AlwaysFalse< GridViewImp >::value, "Not available for these dimensions!"); }; namespace internal { template< class GridViewImp, size_t rangeDim, size_t rangeDimCols > class FiniteVolumeTraits { static_assert(rangeDim >= 1, "Really?"); static_assert(rangeDimCols >= 1, "Really?"); public: typedef GridViewImp GridViewType; typedef FiniteVolume< GridViewType, rangeDim, rangeDimCols> derived_type; typedef typename GridViewImp::IndexSet BackendType; typedef typename GridViewType::template Codim< 0 >::Entity EntityType; }; } // namespace internal template< class GridViewImp > class FiniteVolume< GridViewImp, 1, 1 > : public MapperInterface< internal::FiniteVolumeTraits< GridViewImp, 1, 1 > > { typedef MapperInterface< internal::FiniteVolumeTraits< GridViewImp, 1, 1 > > InterfaceType; public: typedef internal::FiniteVolumeTraits< GridViewImp, 1, 1 > Traits; typedef typename Traits::GridViewType GridViewType; typedef typename Traits::BackendType BackendType; typedef typename Traits::EntityType EntityType; FiniteVolume(const GridViewType& grid_view) : backend_(grid_view.indexSet()) {} const BackendType& backend() const { return backend_; } size_t size() const { return backend_.size(0); } size_t numDofs(const EntityType& /*entity*/) const { return 1; } size_t maxNumDofs() const { return 1; } void globalIndices(const EntityType& entity, Dune::DynamicVector< size_t >& ret) const { if (ret.size() < 1) ret.resize(1); ret[0] = mapToGlobal(entity, 0); } // ... globalIndices(...) using InterfaceType::globalIndices; size_t mapToGlobal(const EntityType& entity, const size_t& UNUSED_UNLESS_DEBUG(localIndex)) const { assert(localIndex == 0); return backend_.index(entity); } private: const BackendType& backend_; }; // class FiniteVolume< ..., 1, 1 > template< class GridViewImp, size_t rangeDim > class FiniteVolume< GridViewImp, rangeDim, 1 > : public MapperInterface< internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > > { typedef MapperInterface< internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > > InterfaceType; static const size_t dimRange = rangeDim; public: typedef internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > Traits; typedef typename Traits::GridViewType GridViewType; typedef typename Traits::BackendType BackendType; typedef typename Traits::EntityType EntityType; FiniteVolume(const GridViewType& grid_view) : backend_(grid_view.indexSet()) {} const BackendType& backend() const { return backend_; } size_t size() const { return dimRange * backend_.size(0); } size_t numDofs(const EntityType& /*entity*/) const { return dimRange; } size_t maxNumDofs() const { return dimRange; } void globalIndices(const EntityType& entity, Dune::DynamicVector< size_t >& ret) const { if (ret.size() < dimRange) ret.resize(dimRange); const size_t base = dimRange * backend_.index(entity); for (size_t ii = 0; ii < dimRange; ++ii) ret[ii] = base + ii; } // ... globalIndices(...) using InterfaceType::globalIndices; size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const { assert(localIndex < dimRange); return (dimRange * backend_.index(entity)) + localIndex; } private: const BackendType& backend_; }; // class FiniteVolume< ..., rangeDim, 1 > } // namespace Mapper } // namespace GDT } // namespace Dune #endif // DUNE_GDT_MAPPER_DEFAULT_FV_HH
add missing include
[mapper.default.fv] add missing include
C++
bsd-2-clause
BarbaraV/dune-gdt,ftalbrecht/dune-gdt
b6a88d5a7c48fa59f970942c7131d53644e9378b
scpak.cpp
scpak.cpp
#include "pakfile.h" #include <sstream> using namespace std; using namespace scpak; int main() { stringstream ss; BinaryWriter writer(&ss); writer.writeString("test test test test test"); BinaryReader reader(&ss); string str = reader.readString(); cout << str << endl; }
#include "pakfile.h" #include <sstream> #include <fstream> using namespace std; using namespace scpak; int main(int argc, char *argv[]) { ifstream fin("Content.pak", ios::binary); PakFile pak; pak.load(fin); fin.close(); auto items = pak.contents(); for(auto item : items) { cout << item.name << endl; } ofstream fout("Content2.pak", ios::binary); stringstream ss(reinterpret_cast<char*>(items[0].data)); BinaryReader reader(&ss); cout << reader.readString() << endl; return 0; }
change to a new test
change to a new test
C++
mit
qnnnnez/scpak
7ebeba66337de38827c15e20fb7cc1c0dca6a5a6
src/motive/processor/ease_in_ease_out_processor.cpp
src/motive/processor/ease_in_ease_out_processor.cpp
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "motive/engine.h" #include "motive/init.h" #include "motive/math/curve_util.h" namespace motive { static const float kDerivativeEpsilon = 0.000001f; struct EaseInEaseOutData { EaseInEaseOutData() : q_start_time(0.0f), target_time(0.0f), elapsed_time(0.0f) {} // Create a straight line with the start value and derivative for q. EaseInEaseOutData(const EaseInEaseOutInit& init, MotiveIndex current_dimension) : q(QuadraticEaseInEaseOut( QuadraticCurve(QuadraticInitWithOrigin( init.start_values[current_dimension], init.start_derivatives[current_dimension], 0.0f)), 0.0f)), q_start_time(0.0f), target_time(0.0f), elapsed_time(0.0f) {} // Currently active curve. QuadraticEaseInEaseOut q; // Shape that holds the bias, typical y-distance that should be traveled, and // typical time it takes to travel typical delta value. MotiveCurveShape shape; // Time at which we started on current curve. float q_start_time; // Target time of the first curve generated. float target_time; // Time since the last call to SetTarget(). float elapsed_time; }; class EaseInEaseOutMotiveProcessor : public MotiveProcessorNf { public: virtual ~EaseInEaseOutMotiveProcessor() {} virtual void AdvanceFrame(MotiveTime delta_time) { Defragment(); // Loop through every motivator one at a time. for (size_t i = 0; i < data_.size(); ++i) { EaseInEaseOutData& d = data_[i]; // Advance the time and then update the current value. d.elapsed_time += static_cast<float>(delta_time); float q_time = d.elapsed_time - d.q_start_time; // If we go past the end value, with a non-zero derivative and there's // no instruction to go to another target, make it so that our curve is // adjusted to hit target value with a zero derivative. if (q_time >= d.q.total_x()) { float target_value = d.q.Evaluate(d.q.total_x()); float target_velocity = d.q.Derivative(d.q.total_x()); d.q_start_time += d.q.total_x(); q_time = d.elapsed_time - d.q_start_time; const bool ends_with_nonzero_derivative = std::fabs(target_velocity) > kDerivativeEpsilon; if (ends_with_nonzero_derivative) { // Create curve to hit target value with zero derivative. float start_second_derivative_abs = 0.0f; float end_second_derivative_abs = 0.0f; CalculateSecondDerivativesFromTypicalCurve( d.shape.typical_delta_value, d.shape.typical_total_time, d.shape.bias, &start_second_derivative_abs, &end_second_derivative_abs); d.q = CalculateQuadraticEaseInEaseOut( target_value, target_velocity, start_second_derivative_abs, target_value, 0.0f, end_second_derivative_abs, d.shape.typical_delta_value, d.shape.typical_total_time); } else { // Curve is a flat line at target_value. d.q = QuadraticEaseInEaseOut(QuadraticCurve(0.0f, 0.0f, target_value), std::numeric_limits<float>::infinity()); } } values_[i] = d.q.Evaluate(q_time); } } virtual MotivatorType Type() const { return EaseInEaseOutInit::kType; } virtual int Priority() const { return 1; } // Accessors to allow the user to get and set simluation values. virtual const float* Values(MotiveIndex index) const { return &values_[index]; } virtual void Velocities(MotiveIndex index, MotiveDimension dimensions, float* out) const { for (MotiveDimension i = 0; i < dimensions; ++i) { const EaseInEaseOutData& d = Data(index + i); out[i] = d.q.Derivative(d.elapsed_time); } } virtual void TargetValues(MotiveIndex index, MotiveDimension dimensions, float* out) const { for (MotiveDimension i = 0; i < dimensions; ++i) { const EaseInEaseOutData& d = Data(index + i); out[i] = d.q.Evaluate(d.q.total_x()); } } virtual void TargetVelocities(MotiveIndex index, MotiveDimension dimensions, float* out) const { for (MotiveDimension i = 0; i < dimensions; ++i) { const EaseInEaseOutData& d = Data(index + i); out[i] = d.q.Derivative(d.q.total_x()); } } virtual void Differences(MotiveIndex index, MotiveDimension dimensions, float* out) const { for (MotiveDimension i = 0; i < dimensions; ++i) { const EaseInEaseOutData& d = Data(index + i); out[i] = d.q.Evaluate(d.q.total_x()) - values_[i]; } } virtual MotiveTime TargetTime(MotiveIndex index) const { const EaseInEaseOutData& d = Data(index); return static_cast<MotiveTime>(d.target_time - d.elapsed_time); } virtual void SetTargetWithShape(MotiveIndex index, MotiveDimension dimensions, const float* target_values, const float* target_velocities, const MotiveCurveShape& shape) { for (MotiveDimension i = 0; i < dimensions; ++i) { float processor_index = index + i; EaseInEaseOutData& d = Data(processor_index); // Initialize curve to go from current to target. d.elapsed_time = 0.0f; d.shape = shape; float start_second_derivative_abs = 0.0f; float end_second_derivative_abs = 0.0f; CalculateSecondDerivativesFromTypicalCurve( d.shape.typical_delta_value, d.shape.typical_total_time, d.shape.bias, &start_second_derivative_abs, &end_second_derivative_abs); d.q = CalculateQuadraticEaseInEaseOut( Value(processor_index), d.q.Derivative(0.0f), start_second_derivative_abs, target_values[i], target_velocities[i], end_second_derivative_abs, d.shape.typical_delta_value, d.shape.typical_total_time); d.target_time = d.q.total_x(); d.q_start_time = 0.0f; } } protected: virtual void InitializeIndices(const MotivatorInit& init, MotiveIndex index, MotiveDimension dimensions, MotiveEngine* /*engine*/) { const EaseInEaseOutInit& ease_in_ease_out_init = static_cast<const EaseInEaseOutInit&>(init); for (MotiveDimension i = 0; i < dimensions; ++i) { const MotiveIndex processor_index = i + index; Data(processor_index) = EaseInEaseOutData(ease_in_ease_out_init, i); values_[processor_index] = ease_in_ease_out_init.start_values[i]; } } virtual void RemoveIndices(MotiveIndex index, MotiveDimension dimensions) { for (MotiveIndex i = index; i < index + dimensions; ++i) { Data(i) = EaseInEaseOutData(); values_[i] = 0.0f; } } virtual void MoveIndices(MotiveIndex old_index, MotiveIndex new_index, MotiveDimension dimensions) { MotiveIndex old_i = old_index; MotiveIndex new_i = new_index; for (MotiveDimension i = 0; i < dimensions; ++i, ++new_i, ++old_i) { data_[new_i] = data_[old_i]; values_[new_i] = values_[old_i]; } } virtual void SetNumIndices(MotiveIndex num_indices) { data_.resize(num_indices); values_.resize(num_indices); } const EaseInEaseOutData& Data(MotiveIndex index) const { assert(ValidIndex(index)); return data_[index]; } EaseInEaseOutData& Data(MotiveIndex index) { assert(ValidIndex(index)); return data_[index]; } std::vector<EaseInEaseOutData> data_; std::vector<float> values_; }; MOTIVE_INSTANCE(EaseInEaseOutInit, EaseInEaseOutMotiveProcessor); } // namespace motive
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "motive/engine.h" #include "motive/init.h" #include "motive/math/curve_util.h" namespace motive { static const float kDerivativeEpsilon = 0.000001f; struct EaseInEaseOutData { EaseInEaseOutData() : q_start_time(0.0f), target_time(0.0f), elapsed_time(0.0f) {} // Create a straight line with the start value and derivative for q. EaseInEaseOutData(const EaseInEaseOutInit& init, MotiveIndex current_dimension) : q(QuadraticEaseInEaseOut( QuadraticCurve(QuadraticInitWithOrigin( init.start_values[current_dimension], init.start_derivatives[current_dimension], 0.0f)), 0.0f)), q_start_time(0.0f), target_time(0.0f), elapsed_time(0.0f) {} // Currently active curve. QuadraticEaseInEaseOut q; // Shape that holds the bias, typical y-distance that should be traveled, and // typical time it takes to travel typical delta value. MotiveCurveShape shape; // Time at which we started on current curve. float q_start_time; // Target time of the first curve generated. float target_time; // Time since the last call to SetTarget(). float elapsed_time; }; class EaseInEaseOutMotiveProcessor : public MotiveProcessorNf { public: virtual ~EaseInEaseOutMotiveProcessor() {} virtual void AdvanceFrame(MotiveTime delta_time) { Defragment(); // Loop through every motivator one at a time. for (size_t i = 0; i < data_.size(); ++i) { EaseInEaseOutData& d = data_[i]; // Advance the time and then update the current value. d.elapsed_time += static_cast<float>(delta_time); float q_time = d.elapsed_time - d.q_start_time; // If we go past the end value, with a non-zero derivative and there's // no instruction to go to another target, make it so that our curve is // adjusted to hit target value with a zero derivative. if (q_time >= d.q.total_x()) { float target_value = d.q.Evaluate(d.q.total_x()); float target_velocity = d.q.Derivative(d.q.total_x()); d.q_start_time += d.q.total_x(); q_time = d.elapsed_time - d.q_start_time; const bool ends_with_nonzero_derivative = std::fabs(target_velocity) > kDerivativeEpsilon; if (ends_with_nonzero_derivative) { // Create curve to hit target value with zero derivative. float start_second_derivative_abs = 0.0f; float end_second_derivative_abs = 0.0f; CalculateSecondDerivativesFromTypicalCurve( d.shape.typical_delta_value, d.shape.typical_total_time, d.shape.bias, &start_second_derivative_abs, &end_second_derivative_abs); d.q = CalculateQuadraticEaseInEaseOut( target_value, target_velocity, start_second_derivative_abs, target_value, 0.0f, end_second_derivative_abs, d.shape.typical_delta_value, d.shape.typical_total_time); } else { // Curve is a flat line at target_value. d.q = QuadraticEaseInEaseOut(QuadraticCurve(0.0f, 0.0f, target_value), std::numeric_limits<float>::infinity()); } } values_[i] = d.q.Evaluate(q_time); } } virtual MotivatorType Type() const { return EaseInEaseOutInit::kType; } virtual int Priority() const { return 1; } // Accessors to allow the user to get and set simluation values. virtual const float* Values(MotiveIndex index) const { return &values_[index]; } virtual void Velocities(MotiveIndex index, MotiveDimension dimensions, float* out) const { for (MotiveDimension i = 0; i < dimensions; ++i) { const EaseInEaseOutData& d = Data(index + i); out[i] = d.q.Derivative(d.elapsed_time); } } virtual void TargetValues(MotiveIndex index, MotiveDimension dimensions, float* out) const { for (MotiveDimension i = 0; i < dimensions; ++i) { const EaseInEaseOutData& d = Data(index + i); out[i] = d.q.Evaluate(d.q.total_x()); } } virtual void TargetVelocities(MotiveIndex index, MotiveDimension dimensions, float* out) const { for (MotiveDimension i = 0; i < dimensions; ++i) { const EaseInEaseOutData& d = Data(index + i); out[i] = d.q.Derivative(d.q.total_x()); } } virtual void Differences(MotiveIndex index, MotiveDimension dimensions, float* out) const { for (MotiveDimension i = 0; i < dimensions; ++i) { const EaseInEaseOutData& d = Data(index + i); out[i] = d.q.Evaluate(d.q.total_x()) - values_[i]; } } virtual MotiveTime TargetTime(MotiveIndex index) const { const EaseInEaseOutData& d = Data(index); return static_cast<MotiveTime>(d.target_time - d.elapsed_time); } virtual void SetTargetWithShape(MotiveIndex index, MotiveDimension dimensions, const float* target_values, const float* target_velocities, const MotiveCurveShape& shape) { for (MotiveDimension i = 0; i < dimensions; ++i) { float processor_index = index + i; EaseInEaseOutData& d = Data(processor_index); // Initialize curve to go from current to target. float start_second_derivative_abs = 0.0f; float end_second_derivative_abs = 0.0f; CalculateSecondDerivativesFromTypicalCurve( shape.typical_delta_value, shape.typical_total_time, shape.bias, &start_second_derivative_abs, &end_second_derivative_abs); d.q = CalculateQuadraticEaseInEaseOut( Value(processor_index), Velocity(processor_index), start_second_derivative_abs, target_values[i], target_velocities[i], end_second_derivative_abs, shape.typical_delta_value, shape.typical_total_time); d.target_time = d.q.total_x(); d.q_start_time = 0.0f; d.elapsed_time = 0.0f; d.shape = shape; } } protected: virtual void InitializeIndices(const MotivatorInit& init, MotiveIndex index, MotiveDimension dimensions, MotiveEngine* /*engine*/) { const EaseInEaseOutInit& ease_in_ease_out_init = static_cast<const EaseInEaseOutInit&>(init); for (MotiveDimension i = 0; i < dimensions; ++i) { const MotiveIndex processor_index = i + index; Data(processor_index) = EaseInEaseOutData(ease_in_ease_out_init, i); values_[processor_index] = ease_in_ease_out_init.start_values[i]; } } virtual void RemoveIndices(MotiveIndex index, MotiveDimension dimensions) { for (MotiveIndex i = index; i < index + dimensions; ++i) { Data(i) = EaseInEaseOutData(); values_[i] = 0.0f; } } virtual void MoveIndices(MotiveIndex old_index, MotiveIndex new_index, MotiveDimension dimensions) { MotiveIndex old_i = old_index; MotiveIndex new_i = new_index; for (MotiveDimension i = 0; i < dimensions; ++i, ++new_i, ++old_i) { data_[new_i] = data_[old_i]; values_[new_i] = values_[old_i]; } } virtual void SetNumIndices(MotiveIndex num_indices) { data_.resize(num_indices); values_.resize(num_indices); } const EaseInEaseOutData& Data(MotiveIndex index) const { assert(ValidIndex(index)); return data_[index]; } EaseInEaseOutData& Data(MotiveIndex index) { assert(ValidIndex(index)); return data_[index]; } std::vector<EaseInEaseOutData> data_; std::vector<float> values_; }; MOTIVE_INSTANCE(EaseInEaseOutInit, EaseInEaseOutMotiveProcessor); } // namespace motive
Fix velocity issue in ease in ease out processor.
Fix velocity issue in ease in ease out processor. Fix issue where elapsed time would get reset to zero too early in EaseInEaseOutMotiveProcessor's SetTargetWithShape function. PiperOrigin-RevId: 141070856 Change-Id: I0f4beac1f35ca02d4e0d3bba4a7e3e2e5194cded
C++
apache-2.0
google/motive,google/motive
08334e4488a9623fe79a8a955b03c9e8a5f0b29f
bin/stego-attack/main.cc
bin/stego-attack/main.cc
#include <getopt.h> #include <vector> #include <dgtype/dgtype.hh> #include "stego-attack-lib/stego-attack-lib.hh" enum class Attack_error_code { UNKNOWN_ARG, UNKNOWN_TYPE, UNSPECIFIED_TYPE, MISSING_ARG, MISSING_INPUT, MISSING_OUTPUT, INACCESSIBLE_FILE, HELP_ARG, SUCCESS }; struct AttackArgs { bool md5_attack = false; bool original_provided = false; bool scramble = false; std::string original_file; std::string altered_file; std::vector<Attack_error_code> errors; }; int main(int argc, char *argv[]) { std::cout << "CSCE315 Project 4" << std::endl; AttackArgs attack_args; int c; bool found_error = false; while ((c = getopt(argc, argv, "m:o:s:")) != -1 && !found_error) { switch (c) { case 'm': attack_args.md5_attack = true; attack_args.altered_file = optarg; break; case 'o': attack_args.original_provided = true; attack_args.original_file = optarg; break; case 's': attack_args.scramble = true; attack_args.altered_file = optarg; break; case ':': attack_args.errors.push_back(Attack_error_code::MISSING_ARG); found_error = true; break; case '?': attack_args.errors.push_back(Attack_error_code::MISSING_ARG); found_error = true; break; } } if (!attack_args.md5_attack && !attack_args.original_provided && !attack_args.scramble) { std::cout << "Error: please provide valid arguments.\n\n" << "-m <alt file> -o <orig file> -- MD5 attack (.bmp and .wav)\n" << "Compares MD5 hashes and returns the encoded message if different.\n\n" << "-s <alt file> -- LSB scramble (.bmp and .wav)\n" << "Randomizes the altered file's LSBs to destroy the encoded message.\n\n"; return 1; } if ((!attack_args.md5_attack || attack_args.scramble || !attack_args.original_provided) && (attack_args.md5_attack || !attack_args.scramble || attack_args.original_provided)) { std::cout << "Error: Please use either -m and -o or -s." << std::endl; return 1; } if (attack_args.md5_attack && attack_args.original_provided && !attack_args.scramble) { if (file_type_of(attack_args.altered_file) == File_type::UNKNOWN) { std::cout << "Error: unknown file type used as argument for -m" << std::endl; return 1; } if (file_type_of(attack_args.original_file) == File_type::UNKNOWN) { std::cout << "Error: unknown file type used as argument for -o" << std::endl; return 1; } if (!is_file_accessible(attack_args.altered_file)) { std::cout << "Error: invalid file provided in argument -m" << std::endl; return 1; } if (!is_file_accessible(attack_args.original_file)) { std::cout << "Error: invalid file provided in argument -o" << std::endl; return 1; } std::cout << "Hidden message: " << retrieveMessage(attack_args.original_file, attack_args.altered_file) << std::endl; return 0; } if (!attack_args.md5_attack && !attack_args.original_provided && attack_args.scramble) { if (file_type_of(attack_args.altered_file) == File_type::UNKNOWN) { std::cout << "Error: unknown file type used as argument for -s" << std::endl; return 1; } if (!is_file_accessible(attack_args.altered_file)) { std::cout << "Error: invalid file provided in argument -s" << std::endl; return 1; } scrambleLSB(attack_args.altered_file); return 0; } return 0; }
#include <getopt.h> #include <vector> #include <dgtype/dgtype.hh> #include "stego-attack-lib/stego-attack-lib.hh" enum class Attack_error_code { UNKNOWN_ARG, UNKNOWN_TYPE, UNSPECIFIED_TYPE, MISSING_ARG, MISSING_INPUT, MISSING_OUTPUT, INACCESSIBLE_FILE, HELP_ARG, SUCCESS }; struct AttackArgs { bool md5_attack = false; bool original_provided = false; bool scramble = false; std::string original_file; std::string altered_file; std::vector<Attack_error_code> errors; }; int main(int argc, char *argv[]) { AttackArgs attack_args; int c; bool found_error = false; while ((c = getopt(argc, argv, "m:o:s:")) != -1 && !found_error) { switch (c) { case 'm': attack_args.md5_attack = true; attack_args.altered_file = optarg; break; case 'o': attack_args.original_provided = true; attack_args.original_file = optarg; break; case 's': attack_args.scramble = true; attack_args.altered_file = optarg; break; case ':': attack_args.errors.push_back(Attack_error_code::MISSING_ARG); found_error = true; break; case '?': attack_args.errors.push_back(Attack_error_code::MISSING_ARG); found_error = true; break; } } if (!attack_args.md5_attack && !attack_args.original_provided && !attack_args.scramble) { std::cout << "Error: please provide valid arguments.\n\n" << "-m <alt file> -o <orig file> -- MD5 attack (.bmp and .wav)\n" << "Compares MD5 hashes and returns the encoded message if different.\n\n" << "-s <alt file> -- LSB scramble (.bmp and .wav)\n" << "Randomizes the altered file's LSBs to destroy the encoded message.\n\n"; return 1; } if ((!attack_args.md5_attack || attack_args.scramble || !attack_args.original_provided) && (attack_args.md5_attack || !attack_args.scramble || attack_args.original_provided)) { std::cout << "Error: Please use either -m and -o or -s." << std::endl; return 1; } if (attack_args.md5_attack && attack_args.original_provided && !attack_args.scramble) { if (file_type_of(attack_args.altered_file) == File_type::UNKNOWN) { std::cout << "Error: unknown file type used as argument for -m" << std::endl; return 1; } if (file_type_of(attack_args.original_file) == File_type::UNKNOWN) { std::cout << "Error: unknown file type used as argument for -o" << std::endl; return 1; } if (!is_file_accessible(attack_args.altered_file)) { std::cout << "Error: invalid file provided in argument -m" << std::endl; return 1; } if (!is_file_accessible(attack_args.original_file)) { std::cout << "Error: invalid file provided in argument -o" << std::endl; return 1; } std::cout << "Hidden message: " << retrieveMessage(attack_args.original_file, attack_args.altered_file) << std::endl; return 0; } if (!attack_args.md5_attack && !attack_args.original_provided && attack_args.scramble) { if (file_type_of(attack_args.altered_file) == File_type::UNKNOWN) { std::cout << "Error: unknown file type used as argument for -s" << std::endl; return 1; } if (!is_file_accessible(attack_args.altered_file)) { std::cout << "Error: invalid file provided in argument -s" << std::endl; return 1; } scrambleLSB(attack_args.altered_file); return 0; } return 0; }
Update main.cc
Update main.cc
C++
bsd-3-clause
gwydirsam/DickGrayson,gwydirsam/DickGrayson,gwydirsam/DickGrayson
f9b1612fa701a29dfa286fde9c66df5e9fc14aa1
src/plugins/projectexplorer/applicationlauncher.cpp
src/plugins/projectexplorer/applicationlauncher.cpp
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "applicationlauncher.h" #include "consoleprocess.h" #ifdef Q_OS_WIN #include "windebuginterface.h" #endif #include <coreplugin/icore.h> #include <utils/qtcprocess.h> #ifdef Q_OS_WIN #include <utils/winutils.h> #endif #include <QtCore/QTimer> #include <QtCore/QTextCodec> #ifdef Q_OS_WIN #include <windows.h> #endif #include "projectexplorerconstants.h" #include "projectexplorer.h" #include "projectexplorersettings.h" /*! \class ProjectExplorer::ApplicationLauncher \brief Application launcher of the ProjectExplorer plugin. Encapsulates processes running in a console or as GUI processes, captures debug output of GUI processes on Windows (outputDebugString()). \sa Utils::ConsoleProcess */ namespace ProjectExplorer { #ifdef Q_OS_WIN using namespace Internal; // for WinDebugInterface #endif struct ApplicationLauncherPrivate { ApplicationLauncherPrivate(); Utils::QtcProcess m_guiProcess; Utils::ConsoleProcess m_consoleProcess; ApplicationLauncher::Mode m_currentMode; QTextCodec *m_outputCodec; QTextCodec::ConverterState m_outputCodecState; QTextCodec::ConverterState m_errorCodecState; }; ApplicationLauncherPrivate::ApplicationLauncherPrivate() : m_currentMode(ApplicationLauncher::Gui), m_outputCodec(QTextCodec::codecForLocale()) { } ApplicationLauncher::ApplicationLauncher(QObject *parent) : QObject(parent), d(new ApplicationLauncherPrivate) { if (ProjectExplorerPlugin::instance()->projectExplorerSettings().mergeStdErrAndStdOut){ d->m_guiProcess.setReadChannelMode(QProcess::MergedChannels); } else { d->m_guiProcess.setReadChannelMode(QProcess::SeparateChannels); connect(&d->m_guiProcess, SIGNAL(readyReadStandardError()), this, SLOT(readStandardError())); } connect(&d->m_guiProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readStandardOutput())); connect(&d->m_guiProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(guiProcessError())); connect(&d->m_guiProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(processDone(int, QProcess::ExitStatus))); connect(&d->m_guiProcess, SIGNAL(started()), this, SLOT(bringToForeground())); #ifdef Q_OS_UNIX d->m_consoleProcess.setSettings(Core::ICore::instance()->settings()); #endif connect(&d->m_consoleProcess, SIGNAL(processStarted()), this, SIGNAL(processStarted())); connect(&d->m_consoleProcess, SIGNAL(processError(QString)), this, SLOT(consoleProcessError(QString))); connect(&d->m_consoleProcess, SIGNAL(processStopped()), this, SLOT(processStopped())); #ifdef Q_OS_WIN connect(WinDebugInterface::instance(), SIGNAL(cannotRetrieveDebugOutput()), this, SLOT(cannotRetrieveDebugOutput())); connect(WinDebugInterface::instance(), SIGNAL(debugOutput(qint64,QString)), this, SLOT(checkDebugOutput(qint64,QString))); #endif } ApplicationLauncher::~ApplicationLauncher() { } void ApplicationLauncher::setWorkingDirectory(const QString &dir) { #ifdef Q_OS_WIN // Work around QTBUG-17529 (QtDeclarative fails with 'File name case mismatch' ...) const QString fixedPath = Utils::normalizePathName(dir); #else # define fixedPath dir #endif d->m_guiProcess.setWorkingDirectory(fixedPath); d->m_consoleProcess.setWorkingDirectory(fixedPath); #ifndef Q_OS_WIN # undef fixedPath #endif } void ApplicationLauncher::setEnvironment(const Utils::Environment &env) { d->m_guiProcess.setEnvironment(env); d->m_consoleProcess.setEnvironment(env); } void ApplicationLauncher::start(Mode mode, const QString &program, const QString &args) { #ifdef Q_OS_WIN if (!WinDebugInterface::instance()->isRunning()) WinDebugInterface::instance()->start(); // Try to start listener again... #endif d->m_currentMode = mode; if (mode == Gui) { d->m_guiProcess.setCommand(program, args); d->m_guiProcess.start(); } else { d->m_consoleProcess.start(program, args); } } void ApplicationLauncher::stop() { if (!isRunning()) return; if (d->m_currentMode == Gui) { d->m_guiProcess.terminate(); if (!d->m_guiProcess.waitForFinished(1000)) { // This is blocking, so be fast. d->m_guiProcess.kill(); d->m_guiProcess.waitForFinished(); } } else { d->m_consoleProcess.stop(); processStopped(); } } bool ApplicationLauncher::isRunning() const { if (d->m_currentMode == Gui) return d->m_guiProcess.state() != QProcess::NotRunning; else return d->m_consoleProcess.isRunning(); } qint64 ApplicationLauncher::applicationPID() const { qint64 result = 0; if (!isRunning()) return result; if (d->m_currentMode == Console) { result = d->m_consoleProcess.applicationPID(); } else { #ifdef Q_OS_WIN result = (qint64)d->m_guiProcess.pid()->dwProcessId; #else result = (qint64)d->m_guiProcess.pid(); #endif } return result; } void ApplicationLauncher::guiProcessError() { QString error; switch (d->m_guiProcess.error()) { case QProcess::FailedToStart: error = tr("Failed to start program. Path or permissions wrong?"); break; case QProcess::Crashed: error = tr("The program has unexpectedly finished."); break; default: error = tr("Some error has occurred while running the program."); } emit appendMessage(error + QLatin1Char('\n'), Utils::ErrorMessageFormat); } void ApplicationLauncher::consoleProcessError(const QString &error) { emit appendMessage(error + QLatin1Char('\n'), Utils::ErrorMessageFormat); } void ApplicationLauncher::readStandardOutput() { QByteArray data = d->m_guiProcess.readAllStandardOutput(); QString msg = d->m_outputCodec->toUnicode( data.constData(), data.length(), &d->m_outputCodecState); emit appendMessage(msg, Utils::StdOutFormatSameLine); } void ApplicationLauncher::readStandardError() { QByteArray data = d->m_guiProcess.readAllStandardError(); QString msg = d->m_outputCodec->toUnicode( data.constData(), data.length(), &d->m_outputCodecState); emit appendMessage(msg, Utils::StdErrFormatSameLine); } #ifdef Q_OS_WIN void ApplicationLauncher::cannotRetrieveDebugOutput() { disconnect(WinDebugInterface::instance(), 0, this, 0); emit appendMessage(msgWinCannotRetrieveDebuggingOutput(), Utils::ErrorMessageFormat); } void ApplicationLauncher::checkDebugOutput(qint64 pid, const QString &message) { if (applicationPID() == pid) emit appendMessage(message, Utils::DebugFormat); } #endif void ApplicationLauncher::processStopped() { emit processExited(0); } void ApplicationLauncher::processDone(int exitCode, QProcess::ExitStatus) { emit processExited(exitCode); } void ApplicationLauncher::bringToForeground() { emit bringToForegroundRequested(applicationPID()); emit processStarted(); } QString ApplicationLauncher::msgWinCannotRetrieveDebuggingOutput() { return tr("Cannot retrieve debugging output.\n"); } } // namespace ProjectExplorer
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "applicationlauncher.h" #include "consoleprocess.h" #ifdef Q_OS_WIN #include "windebuginterface.h" #endif #include <coreplugin/icore.h> #include <utils/qtcprocess.h> #ifdef Q_OS_WIN #include <utils/winutils.h> #endif #include <QtCore/QTimer> #include <QtCore/QTextCodec> #ifdef Q_OS_WIN #include <windows.h> #endif #include "projectexplorerconstants.h" #include "projectexplorer.h" #include "projectexplorersettings.h" /*! \class ProjectExplorer::ApplicationLauncher \brief Application launcher of the ProjectExplorer plugin. Encapsulates processes running in a console or as GUI processes, captures debug output of GUI processes on Windows (outputDebugString()). \sa Utils::ConsoleProcess */ namespace ProjectExplorer { #ifdef Q_OS_WIN using namespace Internal; // for WinDebugInterface #endif struct ApplicationLauncherPrivate { ApplicationLauncherPrivate(); Utils::QtcProcess m_guiProcess; Utils::ConsoleProcess m_consoleProcess; ApplicationLauncher::Mode m_currentMode; QTextCodec *m_outputCodec; QTextCodec::ConverterState m_outputCodecState; QTextCodec::ConverterState m_errorCodecState; // Keep track whether we need to emit a finished signal bool m_processRunning; }; ApplicationLauncherPrivate::ApplicationLauncherPrivate() : m_currentMode(ApplicationLauncher::Gui), m_outputCodec(QTextCodec::codecForLocale()) { } ApplicationLauncher::ApplicationLauncher(QObject *parent) : QObject(parent), d(new ApplicationLauncherPrivate) { if (ProjectExplorerPlugin::instance()->projectExplorerSettings().mergeStdErrAndStdOut){ d->m_guiProcess.setReadChannelMode(QProcess::MergedChannels); } else { d->m_guiProcess.setReadChannelMode(QProcess::SeparateChannels); connect(&d->m_guiProcess, SIGNAL(readyReadStandardError()), this, SLOT(readStandardError())); } connect(&d->m_guiProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readStandardOutput())); connect(&d->m_guiProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(guiProcessError())); connect(&d->m_guiProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(processDone(int, QProcess::ExitStatus))); connect(&d->m_guiProcess, SIGNAL(started()), this, SLOT(bringToForeground())); #ifdef Q_OS_UNIX d->m_consoleProcess.setSettings(Core::ICore::instance()->settings()); #endif connect(&d->m_consoleProcess, SIGNAL(processStarted()), this, SIGNAL(processStarted())); connect(&d->m_consoleProcess, SIGNAL(processError(QString)), this, SLOT(consoleProcessError(QString))); connect(&d->m_consoleProcess, SIGNAL(processStopped()), this, SLOT(processStopped())); #ifdef Q_OS_WIN connect(WinDebugInterface::instance(), SIGNAL(cannotRetrieveDebugOutput()), this, SLOT(cannotRetrieveDebugOutput())); connect(WinDebugInterface::instance(), SIGNAL(debugOutput(qint64,QString)), this, SLOT(checkDebugOutput(qint64,QString))); #endif } ApplicationLauncher::~ApplicationLauncher() { } void ApplicationLauncher::setWorkingDirectory(const QString &dir) { #ifdef Q_OS_WIN // Work around QTBUG-17529 (QtDeclarative fails with 'File name case mismatch' ...) const QString fixedPath = Utils::normalizePathName(dir); #else # define fixedPath dir #endif d->m_guiProcess.setWorkingDirectory(fixedPath); d->m_consoleProcess.setWorkingDirectory(fixedPath); #ifndef Q_OS_WIN # undef fixedPath #endif } void ApplicationLauncher::setEnvironment(const Utils::Environment &env) { d->m_guiProcess.setEnvironment(env); d->m_consoleProcess.setEnvironment(env); } void ApplicationLauncher::start(Mode mode, const QString &program, const QString &args) { d->m_processRunning = true; #ifdef Q_OS_WIN if (!WinDebugInterface::instance()->isRunning()) WinDebugInterface::instance()->start(); // Try to start listener again... #endif d->m_currentMode = mode; if (mode == Gui) { d->m_guiProcess.setCommand(program, args); d->m_guiProcess.start(); } else { d->m_consoleProcess.start(program, args); } } void ApplicationLauncher::stop() { if (!isRunning()) return; if (d->m_currentMode == Gui) { d->m_guiProcess.terminate(); if (!d->m_guiProcess.waitForFinished(1000)) { // This is blocking, so be fast. d->m_guiProcess.kill(); d->m_guiProcess.waitForFinished(); } } else { d->m_consoleProcess.stop(); processStopped(); } } bool ApplicationLauncher::isRunning() const { if (d->m_currentMode == Gui) return d->m_guiProcess.state() != QProcess::NotRunning; else return d->m_consoleProcess.isRunning(); } qint64 ApplicationLauncher::applicationPID() const { qint64 result = 0; if (!isRunning()) return result; if (d->m_currentMode == Console) { result = d->m_consoleProcess.applicationPID(); } else { #ifdef Q_OS_WIN result = (qint64)d->m_guiProcess.pid()->dwProcessId; #else result = (qint64)d->m_guiProcess.pid(); #endif } return result; } void ApplicationLauncher::guiProcessError() { QString error; switch (d->m_guiProcess.error()) { case QProcess::FailedToStart: error = tr("Failed to start program. Path or permissions wrong?"); break; case QProcess::Crashed: error = tr("The program has unexpectedly finished."); break; default: error = tr("Some error has occurred while running the program."); } emit appendMessage(error + QLatin1Char('\n'), Utils::ErrorMessageFormat); if (d->m_processRunning && !isRunning()) { d->m_processRunning = false; emit processExited(-1); } } void ApplicationLauncher::consoleProcessError(const QString &error) { emit appendMessage(error + QLatin1Char('\n'), Utils::ErrorMessageFormat); if (d->m_processRunning && d->m_consoleProcess.applicationPID() == 0) { d->m_processRunning = false; emit processExited(-1); } } void ApplicationLauncher::readStandardOutput() { QByteArray data = d->m_guiProcess.readAllStandardOutput(); QString msg = d->m_outputCodec->toUnicode( data.constData(), data.length(), &d->m_outputCodecState); emit appendMessage(msg, Utils::StdOutFormatSameLine); } void ApplicationLauncher::readStandardError() { QByteArray data = d->m_guiProcess.readAllStandardError(); QString msg = d->m_outputCodec->toUnicode( data.constData(), data.length(), &d->m_outputCodecState); emit appendMessage(msg, Utils::StdErrFormatSameLine); } #ifdef Q_OS_WIN void ApplicationLauncher::cannotRetrieveDebugOutput() { disconnect(WinDebugInterface::instance(), 0, this, 0); emit appendMessage(msgWinCannotRetrieveDebuggingOutput(), Utils::ErrorMessageFormat); } void ApplicationLauncher::checkDebugOutput(qint64 pid, const QString &message) { if (applicationPID() == pid) emit appendMessage(message, Utils::DebugFormat); } #endif void ApplicationLauncher::processStopped() { emit processExited(0); } void ApplicationLauncher::processDone(int exitCode, QProcess::ExitStatus) { emit processExited(exitCode); } void ApplicationLauncher::bringToForeground() { emit bringToForegroundRequested(applicationPID()); emit processStarted(); } QString ApplicationLauncher::msgWinCannotRetrieveDebuggingOutput() { return tr("Cannot retrieve debugging output.\n"); } } // namespace ProjectExplorer
Fix oddities on failing to run a local process
Fix oddities on failing to run a local process Task-number: QTCREATORBUG-5758 Change-Id: I82268936a107ba83892f06a7d2658a2a32980b85 Reviewed-on: http://codereview.qt.nokia.com/3504 Reviewed-by: Qt Sanity Bot <[email protected]> Reviewed-by: Oswald Buddenhagen <[email protected]>
C++
lgpl-2.1
colede/qtcreator,hdweiss/qt-creator-visualizer,malikcjm/qtcreator,azat/qtcreator,xianian/qt-creator,farseerri/git_code,malikcjm/qtcreator,bakaiadam/collaborative_qt_creator,farseerri/git_code,colede/qtcreator,omniacreator/qtcreator,AltarBeastiful/qt-creator,amyvmiwei/qt-creator,KDAB/KDAB-Creator,Distrotech/qtcreator,KDE/android-qt-creator,omniacreator/qtcreator,bakaiadam/collaborative_qt_creator,danimo/qt-creator,martyone/sailfish-qtcreator,malikcjm/qtcreator,amyvmiwei/qt-creator,maui-packages/qt-creator,KDAB/KDAB-Creator,richardmg/qtcreator,richardmg/qtcreator,ostash/qt-creator-i18n-uk,danimo/qt-creator,martyone/sailfish-qtcreator,farseerri/git_code,Distrotech/qtcreator,danimo/qt-creator,KDE/android-qt-creator,xianian/qt-creator,bakaiadam/collaborative_qt_creator,maui-packages/qt-creator,richardmg/qtcreator,kuba1/qtcreator,jonnor/qt-creator,jonnor/qt-creator,colede/qtcreator,KDAB/KDAB-Creator,KDAB/KDAB-Creator,ostash/qt-creator-i18n-uk,KDE/android-qt-creator,azat/qtcreator,xianian/qt-creator,jonnor/qt-creator,kuba1/qtcreator,ostash/qt-creator-i18n-uk,martyone/sailfish-qtcreator,danimo/qt-creator,colede/qtcreator,malikcjm/qtcreator,jonnor/qt-creator,richardmg/qtcreator,hdweiss/qt-creator-visualizer,omniacreator/qtcreator,danimo/qt-creator,bakaiadam/collaborative_qt_creator,danimo/qt-creator,bakaiadam/collaborative_qt_creator,hdweiss/qt-creator-visualizer,AltarBeastiful/qt-creator,AltarBeastiful/qt-creator,martyone/sailfish-qtcreator,kuba1/qtcreator,syntheticpp/qt-creator,KDE/android-qt-creator,danimo/qt-creator,azat/qtcreator,colede/qtcreator,ostash/qt-creator-i18n-uk,syntheticpp/qt-creator,xianian/qt-creator,omniacreator/qtcreator,darksylinc/qt-creator,syntheticpp/qt-creator,farseerri/git_code,darksylinc/qt-creator,duythanhphan/qt-creator,farseerri/git_code,syntheticpp/qt-creator,hdweiss/qt-creator-visualizer,martyone/sailfish-qtcreator,richardmg/qtcreator,KDAB/KDAB-Creator,KDE/android-qt-creator,hdweiss/qt-creator-visualizer,duythanhphan/qt-creator,kuba1/qtcreator,amyvmiwei/qt-creator,amyvmiwei/qt-creator,malikcjm/qtcreator,kuba1/qtcreator,maui-packages/qt-creator,bakaiadam/collaborative_qt_creator,amyvmiwei/qt-creator,maui-packages/qt-creator,farseerri/git_code,KDE/android-qt-creator,hdweiss/qt-creator-visualizer,darksylinc/qt-creator,Distrotech/qtcreator,martyone/sailfish-qtcreator,maui-packages/qt-creator,KDAB/KDAB-Creator,darksylinc/qt-creator,martyone/sailfish-qtcreator,maui-packages/qt-creator,martyone/sailfish-qtcreator,bakaiadam/collaborative_qt_creator,duythanhphan/qt-creator,omniacreator/qtcreator,AltarBeastiful/qt-creator,danimo/qt-creator,Distrotech/qtcreator,kuba1/qtcreator,darksylinc/qt-creator,syntheticpp/qt-creator,richardmg/qtcreator,Distrotech/qtcreator,KDE/android-qt-creator,darksylinc/qt-creator,kuba1/qtcreator,darksylinc/qt-creator,kuba1/qtcreator,malikcjm/qtcreator,Distrotech/qtcreator,AltarBeastiful/qt-creator,azat/qtcreator,duythanhphan/qt-creator,xianian/qt-creator,maui-packages/qt-creator,danimo/qt-creator,amyvmiwei/qt-creator,jonnor/qt-creator,syntheticpp/qt-creator,syntheticpp/qt-creator,colede/qtcreator,duythanhphan/qt-creator,duythanhphan/qt-creator,farseerri/git_code,malikcjm/qtcreator,omniacreator/qtcreator,azat/qtcreator,kuba1/qtcreator,amyvmiwei/qt-creator,xianian/qt-creator,AltarBeastiful/qt-creator,xianian/qt-creator,duythanhphan/qt-creator,colede/qtcreator,amyvmiwei/qt-creator,azat/qtcreator,omniacreator/qtcreator,jonnor/qt-creator,ostash/qt-creator-i18n-uk,ostash/qt-creator-i18n-uk,AltarBeastiful/qt-creator,martyone/sailfish-qtcreator,AltarBeastiful/qt-creator,KDE/android-qt-creator,ostash/qt-creator-i18n-uk,darksylinc/qt-creator,farseerri/git_code,xianian/qt-creator,richardmg/qtcreator,Distrotech/qtcreator,xianian/qt-creator
289df89d364df7d1a55c3324f7166a1d8ba3019e
source/core/b5m-manager/b5mo_sorter.cc
source/core/b5m-manager/b5mo_sorter.cc
#include "b5mo_sorter.h" #include "product_db.h" #include <boost/iostreams/stream.hpp> #include <boost/iostreams/device/file_descriptor.hpp> using namespace sf1r; B5moSorter::B5moSorter(const std::string& m, uint32_t mcount) :m_(m), mcount_(mcount), index_(0), sort_thread_(NULL) { } void B5moSorter::Append(const ScdDocument& doc, const std::string& ts) { if(buffer_.size()==mcount_) { WaitUntilSortFinish_(); DoSort_(); } buffer_.push_back(Value(doc, ts)); } bool B5moSorter::StageOne() { WaitUntilSortFinish_(); if(!buffer_.empty()) { DoSort_(); WaitUntilSortFinish_(); } return true; } bool B5moSorter::StageTwo(const std::string& last_m) { namespace bfs=boost::filesystem; std::string sorter_path = B5MHelper::GetB5moBlockPath(m_); ts_ = bfs::path(m_).filename().string(); if(ts_==".") { ts_ = bfs::path(m_).parent_path().filename().string(); } std::string cmd = "sort -m --buffer-size=1000M "+sorter_path+"/*"; if(!last_m.empty()) { std::string last_mirror = B5MHelper::GetB5moMirrorPath(last_m); std::string last_mirror_block = last_mirror+"/block"; if(!bfs::exists(last_mirror_block)) { if(!GenMirrorBlock_(last_mirror)) { LOG(ERROR)<<"gen mirror block fail"<<std::endl; return false; } if(!GenMBlock_()) { LOG(ERROR)<<"gen b5mo block fail"<<std::endl; return false; } } cmd+=" "+last_mirror_block; } std::string mirror_path = B5MHelper::GetB5moMirrorPath(m_); B5MHelper::PrepareEmptyDir(mirror_path); std::string b5mp_path = B5MHelper::GetB5mpPath(m_); B5MHelper::PrepareEmptyDir(b5mp_path); pwriter_.reset(new ScdTypeWriter(b5mp_path)); std::string mirror_file = mirror_path+"/block"; mirror_ofs_.open(mirror_file.c_str()); FILE* pipe = popen(cmd.c_str(), "r"); if(!pipe) { std::cerr<<"pipe error"<<std::endl; return false; } typedef boost::iostreams::stream_buffer<boost::iostreams::file_descriptor_source> boost_stream; int fd = fileno(pipe); boost::iostreams::file_descriptor_source d(fd, boost::iostreams::close_handle); boost_stream stream(d); //stream.set_auto_close(false); std::istream is(&stream); std::string line; std::string spid; std::vector<Value> buffer; while(std::getline(is, line)) { Value value; if(!value.Parse(line, &json_reader_)) { std::cerr<<"invalid line "<<line<<std::endl; continue; } //std::cerr<<"find value "<<value.spid<<","<<value.is_update<<","<<value.ts<<","<<value.doc.getPropertySize()<<std::endl; if(buffer.empty()) buffer.push_back(value); if(!buffer.empty()) { if(value.spid!=buffer.back().spid) { OBag_(buffer); buffer.resize(0); } } buffer.push_back(value); } OBag_(buffer); mirror_ofs_.close(); pwriter_->Close(); //char buffer[128]; //std::string result = ""; //while(!feof(pipe)) //{ //if(fgets(buffer, 128, pipe)!=NULL) //{ //result += buffer; //} //} pclose(pipe); //boost::algorithm::trim(result); //std::size_t c = boost::lexical_cast<std::size_t>(result); return true; } void B5moSorter::WaitUntilSortFinish_() { if(sort_thread_==NULL) { return; } sort_thread_->join(); delete sort_thread_; sort_thread_=NULL; } void B5moSorter::DoSort_() { std::vector<Value> docs; buffer_.swap(docs); sort_thread_ = new boost::thread(boost::bind(&B5moSorter::Sort_, this, docs)); } void B5moSorter::WriteValue_(std::ofstream& ofs, const ScdDocument& doc, const std::string& ts) { std::string spid; doc.getString("uuid", spid); if(spid.empty()) return; Json::Value json_value; JsonDocument::ToJson(doc, json_value); //for(Document::property_const_iterator it=doc.propertyBegin();it!=doc.propertyEnd();++it) //{ //const PropertyValue& v = it->second; //const UString& uv = v.get<UString>(); //std::string sv; //uv.convertString(sv, UString::UTF_8); //json_value[it->first] = sv; //} Json::FastWriter writer; std::string str_value = writer.write(json_value); boost::algorithm::trim(str_value); ofs<<spid<<"\t"<<doc.type<<"\t"<<ts<<"\t"<<str_value<<std::endl; } void B5moSorter::Sort_(std::vector<Value>& docs) { std::sort(docs.begin(), docs.end(), PidCompare_); uint32_t index = ++index_; std::string file = m_+"/"+boost::lexical_cast<std::string>(index); std::ofstream ofs(file.c_str()); for(uint32_t i=0;i<docs.size();i++) { const ScdDocument& doc = docs[i].doc; WriteValue_(ofs, doc, docs[i].ts); } ofs.close(); } void B5moSorter::OBag_(std::vector<Value>& docs) { bool modified=false; for(uint32_t i=0;i<docs.size();i++) { //std::cerr<<"ts "<<docs[i].ts<<","<<ts_<<std::endl; if(docs[i].ts==ts_) { modified=true; break; } } //std::cerr<<"docs count "<<docs.size()<<","<<modified<<std::endl; if(!modified) { for(uint32_t i=0;i<docs.size();i++) { WriteValue_(mirror_ofs_, docs[i].doc, docs[i].ts); } return; } std::sort(docs.begin(), docs.end(), OCompare_); std::vector<ScdDocument> prev_odocs; std::vector<ScdDocument> odocs; //Document pdoc; //ProductProperty pp; //Document prev_odoc; //Document odoc; //std::string last_soid; for(uint32_t i=0;i<docs.size();i++) { const Value& v = docs[i]; const ScdDocument& doc = v.doc; ODocMerge_(odocs, doc); if(v.ts<ts_) { ODocMerge_(prev_odocs, doc); } } //std::cerr<<"odocs count "<<odocs.size()<<std::endl; for(uint32_t i=0;i<odocs.size();i++) { if(odocs[i].type!=DELETE_SCD) { WriteValue_(mirror_ofs_, odocs[i], ts_); } } ScdDocument pdoc; pgenerator_.Gen(odocs, pdoc); if(pdoc.type==DELETE_SCD) { pwriter_->Append(pdoc, pdoc.type); } else { ScdDocument prev_pdoc; if(!prev_odocs.empty()) { pgenerator_.Gen(prev_odocs, prev_pdoc); pdoc.diff(prev_pdoc); } int64_t itemcount=0; pdoc.getProperty("itemcount", itemcount); if(itemcount>=100) return; SCD_TYPE ptype = pdoc.type; if(pdoc.getPropertySize()<2) { ptype = NOT_SCD; } else if(pdoc.getPropertySize()==2)//DATE only update { if(pdoc.hasProperty("DATE")) { ptype = NOT_SCD; } } if(ptype!=NOT_SCD) { pwriter_->Append(pdoc, ptype); } } } void B5moSorter::ODocMerge_(std::vector<ScdDocument>& vec, const ScdDocument& doc) { if(vec.empty()) vec.push_back(doc); else { if(vec.back().property("DOCID")==doc.property("DOCID")) { vec.back().merge(doc); } else { vec.push_back(doc); } } } bool B5moSorter::GenMirrorBlock_(const std::string& mirror_path) { std::vector<std::string> scd_list; ScdParser::getScdList(mirror_path, scd_list); if(scd_list.size()!=1) { return false; } std::string ts = boost::filesystem::path(mirror_path).parent_path().filename().string(); std::string scd_file = scd_list.front(); SCD_TYPE scd_type = ScdParser::checkSCDType(scd_file); ScdParser parser(izenelib::util::UString::UTF_8); parser.load(scd_file); std::ofstream block_ofs((mirror_path+"/block").c_str()); uint32_t n=0; for( ScdParser::iterator doc_iter = parser.begin(); doc_iter!= parser.end(); ++doc_iter, ++n) { if(n%100000==0) { LOG(INFO)<<"Find Mirror Documents "<<n<<std::endl; } ScdDocument doc; doc.type = scd_type; SCDDoc& scddoc = *(*doc_iter); SCDDoc::iterator p = scddoc.begin(); for(; p!=scddoc.end(); ++p) { doc.property(p->first) = p->second; } WriteValue_(block_ofs, doc, ts); } block_ofs.close(); return true; } bool B5moSorter::GenMBlock_() { std::string b5mo_path = B5MHelper::GetB5moPath(m_); std::string block_path = B5MHelper::GetB5moBlockPath(m_); std::vector<std::string> scd_list; ScdParser::getScdList(b5mo_path, scd_list); if(scd_list.size()==0) { return false; } B5MHelper::PrepareEmptyDir(block_path); std::vector<Value> values; for(uint32_t i=0;i<scd_list.size();i++) { std::string scd_file = scd_list[i]; SCD_TYPE scd_type = ScdParser::checkSCDType(scd_file); ScdParser parser(izenelib::util::UString::UTF_8); parser.load(scd_file); uint32_t n=0; LOG(INFO)<<"Processing "<<scd_file<<std::endl; for( ScdParser::iterator doc_iter = parser.begin(); doc_iter!= parser.end(); ++doc_iter, ++n) { if(n%100000==0) { LOG(INFO)<<"Find B5mo Documents "<<n<<std::endl; } Value value; value.doc.type = scd_type; value.ts = ts_; SCDDoc& scddoc = *(*doc_iter); SCDDoc::iterator p = scddoc.begin(); for(; p!=scddoc.end(); ++p) { value.doc.property(p->first) = p->second; } values.push_back(value); } } std::sort(values.begin(), values.end(), PidCompare_); std::string block_file = block_path+"/1"; std::ofstream ofs(block_file.c_str()); for(uint32_t i=0;i<values.size();i++) { WriteValue_(ofs, values[i].doc, values[i].ts); } ofs.close(); return true; }
#include "b5mo_sorter.h" #include "product_db.h" #include <boost/iostreams/stream.hpp> #include <boost/iostreams/device/file_descriptor.hpp> using namespace sf1r; B5moSorter::B5moSorter(const std::string& m, uint32_t mcount) :m_(m), mcount_(mcount), index_(0), sort_thread_(NULL) { } void B5moSorter::Append(const ScdDocument& doc, const std::string& ts) { if(buffer_.size()==mcount_) { WaitUntilSortFinish_(); DoSort_(); } buffer_.push_back(Value(doc, ts)); } bool B5moSorter::StageOne() { WaitUntilSortFinish_(); if(!buffer_.empty()) { DoSort_(); WaitUntilSortFinish_(); } return true; } bool B5moSorter::StageTwo(const std::string& last_m) { namespace bfs=boost::filesystem; std::string sorter_path = B5MHelper::GetB5moBlockPath(m_); ts_ = bfs::path(m_).filename().string(); if(ts_==".") { ts_ = bfs::path(m_).parent_path().filename().string(); } std::string cmd = "sort -m --buffer-size=1000M "+sorter_path+"/*"; if(!last_m.empty()) { std::string last_mirror = B5MHelper::GetB5moMirrorPath(last_m); std::string last_mirror_block = last_mirror+"/block"; if(!bfs::exists(last_mirror_block)) { if(!GenMirrorBlock_(last_mirror)) { LOG(ERROR)<<"gen mirror block fail"<<std::endl; return false; } if(!GenMBlock_()) { LOG(ERROR)<<"gen b5mo block fail"<<std::endl; return false; } } cmd+=" "+last_mirror_block; } std::string mirror_path = B5MHelper::GetB5moMirrorPath(m_); B5MHelper::PrepareEmptyDir(mirror_path); std::string b5mp_path = B5MHelper::GetB5mpPath(m_); B5MHelper::PrepareEmptyDir(b5mp_path); pwriter_.reset(new ScdTypeWriter(b5mp_path)); std::string mirror_file = mirror_path+"/block"; mirror_ofs_.open(mirror_file.c_str()); FILE* pipe = popen(cmd.c_str(), "r"); if(!pipe) { std::cerr<<"pipe error"<<std::endl; return false; } typedef boost::iostreams::stream_buffer<boost::iostreams::file_descriptor_source> boost_stream; int fd = fileno(pipe); boost::iostreams::file_descriptor_source d(fd, boost::iostreams::close_handle); boost_stream stream(d); //stream.set_auto_close(false); std::istream is(&stream); std::string line; std::string spid; std::vector<Value> buffer; while(std::getline(is, line)) { Value value; if(!value.Parse(line, &json_reader_)) { std::cerr<<"invalid line "<<line<<std::endl; continue; } //std::cerr<<"find value "<<value.spid<<","<<value.is_update<<","<<value.ts<<","<<value.doc.getPropertySize()<<std::endl; if(buffer.empty()) buffer.push_back(value); if(!buffer.empty()) { if(value.spid!=buffer.back().spid) { OBag_(buffer); buffer.resize(0); } } buffer.push_back(value); } OBag_(buffer); mirror_ofs_.close(); pwriter_->Close(); //char buffer[128]; //std::string result = ""; //while(!feof(pipe)) //{ //if(fgets(buffer, 128, pipe)!=NULL) //{ //result += buffer; //} //} pclose(pipe); //boost::algorithm::trim(result); //std::size_t c = boost::lexical_cast<std::size_t>(result); return true; } void B5moSorter::WaitUntilSortFinish_() { if(sort_thread_==NULL) { return; } sort_thread_->join(); delete sort_thread_; sort_thread_=NULL; } void B5moSorter::DoSort_() { std::vector<Value> docs; buffer_.swap(docs); sort_thread_ = new boost::thread(boost::bind(&B5moSorter::Sort_, this, docs)); } void B5moSorter::WriteValue_(std::ofstream& ofs, const ScdDocument& doc, const std::string& ts) { std::string spid; doc.getString("uuid", spid); if(spid.empty()) return; Json::Value json_value; JsonDocument::ToJson(doc, json_value); //for(Document::property_const_iterator it=doc.propertyBegin();it!=doc.propertyEnd();++it) //{ //const PropertyValue& v = it->second; //const UString& uv = v.get<UString>(); //std::string sv; //uv.convertString(sv, UString::UTF_8); //json_value[it->first] = sv; //} Json::FastWriter writer; std::string str_value = writer.write(json_value); boost::algorithm::trim(str_value); ofs<<spid<<"\t"<<doc.type<<"\t"<<ts<<"\t"<<str_value<<std::endl; } void B5moSorter::Sort_(std::vector<Value>& docs) { std::sort(docs.begin(), docs.end(), PidCompare_); uint32_t index = ++index_; std::string file = m_+"/"+boost::lexical_cast<std::string>(index); std::ofstream ofs(file.c_str()); for(uint32_t i=0;i<docs.size();i++) { const ScdDocument& doc = docs[i].doc; WriteValue_(ofs, doc, docs[i].ts); } ofs.close(); } void B5moSorter::OBag_(std::vector<Value>& docs) { bool modified=false; for(uint32_t i=0;i<docs.size();i++) { //std::cerr<<"ts "<<docs[i].ts<<","<<ts_<<std::endl; if(docs[i].ts==ts_) { modified=true; break; } } //std::cerr<<"docs count "<<docs.size()<<","<<modified<<std::endl; if(!modified) { for(uint32_t i=0;i<docs.size();i++) { WriteValue_(mirror_ofs_, docs[i].doc, docs[i].ts); } return; } std::sort(docs.begin(), docs.end(), OCompare_); std::vector<ScdDocument> prev_odocs; std::vector<ScdDocument> odocs; //Document pdoc; //ProductProperty pp; //Document prev_odoc; //Document odoc; //std::string last_soid; for(uint32_t i=0;i<docs.size();i++) { const Value& v = docs[i]; const ScdDocument& doc = v.doc; ODocMerge_(odocs, doc); if(v.ts<ts_) { ODocMerge_(prev_odocs, doc); } } //std::cerr<<"odocs count "<<odocs.size()<<std::endl; for(uint32_t i=0;i<odocs.size();i++) { if(odocs[i].type!=DELETE_SCD) { WriteValue_(mirror_ofs_, odocs[i], ts_); } } ScdDocument pdoc; pgenerator_.Gen(odocs, pdoc); if(pdoc.type==DELETE_SCD) { pwriter_->Append(pdoc, pdoc.type); } else { ScdDocument prev_pdoc; if(!prev_odocs.empty()) { pgenerator_.Gen(prev_odocs, prev_pdoc); pdoc.diff(prev_pdoc); } int64_t itemcount=0; pdoc.getProperty("itemcount", itemcount); //if(itemcount>=100) return; SCD_TYPE ptype = pdoc.type; if(pdoc.getPropertySize()<2) { ptype = NOT_SCD; } else if(pdoc.getPropertySize()==2)//DATE only update { if(pdoc.hasProperty("DATE")) { ptype = NOT_SCD; } } if(ptype!=NOT_SCD) { pwriter_->Append(pdoc, ptype); } } } void B5moSorter::ODocMerge_(std::vector<ScdDocument>& vec, const ScdDocument& doc) { if(vec.empty()) vec.push_back(doc); else { if(vec.back().property("DOCID")==doc.property("DOCID")) { vec.back().merge(doc); } else { vec.push_back(doc); } } } bool B5moSorter::GenMirrorBlock_(const std::string& mirror_path) { std::vector<std::string> scd_list; ScdParser::getScdList(mirror_path, scd_list); if(scd_list.size()!=1) { return false; } std::string ts = boost::filesystem::path(mirror_path).parent_path().filename().string(); std::string scd_file = scd_list.front(); SCD_TYPE scd_type = ScdParser::checkSCDType(scd_file); ScdParser parser(izenelib::util::UString::UTF_8); parser.load(scd_file); std::ofstream block_ofs((mirror_path+"/block").c_str()); uint32_t n=0; for( ScdParser::iterator doc_iter = parser.begin(); doc_iter!= parser.end(); ++doc_iter, ++n) { if(n%100000==0) { LOG(INFO)<<"Find Mirror Documents "<<n<<std::endl; } ScdDocument doc; doc.type = scd_type; SCDDoc& scddoc = *(*doc_iter); SCDDoc::iterator p = scddoc.begin(); for(; p!=scddoc.end(); ++p) { doc.property(p->first) = p->second; } WriteValue_(block_ofs, doc, ts); } block_ofs.close(); return true; } bool B5moSorter::GenMBlock_() { std::string b5mo_path = B5MHelper::GetB5moPath(m_); std::string block_path = B5MHelper::GetB5moBlockPath(m_); std::vector<std::string> scd_list; ScdParser::getScdList(b5mo_path, scd_list); if(scd_list.size()==0) { return false; } B5MHelper::PrepareEmptyDir(block_path); std::vector<Value> values; for(uint32_t i=0;i<scd_list.size();i++) { std::string scd_file = scd_list[i]; SCD_TYPE scd_type = ScdParser::checkSCDType(scd_file); ScdParser parser(izenelib::util::UString::UTF_8); parser.load(scd_file); uint32_t n=0; LOG(INFO)<<"Processing "<<scd_file<<std::endl; for( ScdParser::iterator doc_iter = parser.begin(); doc_iter!= parser.end(); ++doc_iter, ++n) { if(n%100000==0) { LOG(INFO)<<"Find B5mo Documents "<<n<<std::endl; } Value value; value.doc.type = scd_type; value.ts = ts_; SCDDoc& scddoc = *(*doc_iter); SCDDoc::iterator p = scddoc.begin(); for(; p!=scddoc.end(); ++p) { value.doc.property(p->first) = p->second; } values.push_back(value); } } std::sort(values.begin(), values.end(), PidCompare_); std::string block_file = block_path+"/1"; std::ofstream ofs(block_file.c_str()); for(uint32_t i=0;i<values.size();i++) { WriteValue_(ofs, values[i].doc, values[i].ts); } ofs.close(); return true; }
remove itemcount<100 restrict
remove itemcount<100 restrict
C++
apache-2.0
izenecloud/sf1r-lite,izenecloud/sf1r-lite,izenecloud/sf1r-lite,izenecloud/sf1r-lite,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-ad-delivery,pombredanne/sf1r-lite,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-ad-delivery,pombredanne/sf1r-lite,pombredanne/sf1r-lite,pombredanne/sf1r-lite,izenecloud/sf1r-lite,pombredanne/sf1r-lite
ce338e6236b6d56894f813a7a13d64a716dd6943
include/distortos/synchronization/MessageQueueBase.hpp
include/distortos/synchronization/MessageQueueBase.hpp
/** * \file * \brief MessageQueueBase class header * * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-01-14 */ #ifndef INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_ #define INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_ #include "distortos/Semaphore.hpp" #include "distortos/synchronization/SemaphoreFunctor.hpp" #include "distortos/allocators/FeedablePool.hpp" #include <forward_list> namespace distortos { namespace synchronization { /// MessageQueueBase class implements basic functionality of MessageQueue template class class MessageQueueBase { public: /// entry in the MessageQueueBase struct Entry { /** * \brief Entry's constructor * * \param [in] priorityy is the priority of the entry * \param [in] storagee is the storage for the entry */ constexpr Entry(const uint8_t priorityy, void* const storagee) : priority{priorityy}, storage{storagee} { } /// default copy constructor constexpr Entry(const Entry&) = default; /// priority of the entry uint8_t priority; /// storage for the entry void* storage; }; /** * \brief Functor is a type-erased interface for functors which execute some action on queue's storage (like * copy-constructing, swapping, destroying, emplacing, ...). * * The functor will be called by MessageQueueBase internals with one argument - \a storage - which is a pointer to * storage with/for element. */ using Functor = estd::TypeErasedFunctor<void(void*)>; /// link and Entry using LinkAndEntry = std::pair<void*, Entry>; /** * type of uninitialized storage for data * * \param T is the type of data in queue */ template<typename T> struct Storage { /// storage for Entry typename std::aligned_storage<sizeof(LinkAndEntry), alignof(LinkAndEntry)>::type entryStorage; /// storage for value typename std::aligned_storage<sizeof(T), alignof(T)>::type valueStorage; }; /// functor which gives descending priority order of elements on the list struct DescendingPriority { /** * \brief operator() * * \param [in] left is the object on the left side of comparison * \param [in] right is the object on the right side of comparison * * \return true if left's priority is less than right's priority */ bool operator()(const Entry& left, const Entry& right) { return left.priority < right.priority; } }; /// type of pool using Pool = allocators::FeedablePool; /// type of pool allocator using PoolAllocator = allocators::PoolAllocator<Entry, Pool>; /// type of entry list using EntryList = containers::SortedContainer<std::forward_list<Entry, PoolAllocator>, DescendingPriority>; /// type of free entry list using FreeEntryList = std::forward_list<Entry, PoolAllocator>; /** * \brief InternalFunctor is a type-erased interface for functors which execute common code of pop() and push() * operations. * * The functor will be called by MessageQueueBase internals with references to \a entryList_ and \a freeEntryList_. * It should perform common actions and execute the Functor passed from callers. */ using InternalFunctor = estd::TypeErasedFunctor<void(EntryList&, FreeEntryList&)>; /** * \brief MessageQueueBase's constructor * * \param T is the type of data in queue * * \param [in] storage is an array of Storage elements * \param [in] maxElements is the number of elements in \a storage array */ template<typename T> MessageQueueBase(Storage<T>* const storage, const size_t maxElements) : MessageQueueBase{maxElements} { for (size_t i = 0; i < maxElements; ++i) { pool_.feed(storage[i].entryStorage); freeEntryList_.emplace_front(uint8_t{}, &storage[i].valueStorage); } } /** * \brief Implementation of pop() using type-erased functor * * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a popSemaphore_ * \param [out] priority is a reference to variable that will be used to return priority of popped value * \param [in] functor is a reference to Functor which will execute actions related to popping - it will get a * pointer to storage with element * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by \a waitSemaphoreFunctor's operator() call; * - error codes returned by Semaphore::post(); */ int pop(const SemaphoreFunctor& waitSemaphoreFunctor, uint8_t& priority, const Functor& functor); /** * \brief Implementation of push() using type-erased functor * * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a pushSemaphore_ * \param [in] priority is the priority of new element * \param [in] functor is a reference to Functor which will execute actions related to pushing - it will get a * pointer to storage for element * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by \a waitSemaphoreFunctor's operator() call; * - error codes returned by Semaphore::post(); */ int push(const SemaphoreFunctor& waitSemaphoreFunctor, uint8_t priority, const Functor& functor); private: /** * \brief MessageQueueBase's constructor - internal version * * \param [in] maxElements is the maximum number of elements the queue can hold */ explicit MessageQueueBase(size_t maxElements); /** * \brief Implementation of pop() and push() using type-erased internal functor * * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a waitSemaphore * \param [in] internalFunctor is a reference to InternalFunctor which will execute actions related to * popping/pushing * \param [in] waitSemaphore is a reference to semaphore that will be waited for, \a popSemaphore_ for pop(), \a * pushSemaphore_ for push() * \param [in] postSemaphore is a reference to semaphore that will be posted after the operation, \a pushSemaphore_ * for pop(), \a popSemaphore_ for push() * * \return zero if operation was successful, error code otherwise: * - error codes returned by \a waitSemaphoreFunctor's operator() call; * - error codes returned by Semaphore::post(); */ int popPush(const SemaphoreFunctor& waitSemaphoreFunctor, const InternalFunctor& internalFunctor, Semaphore& waitSemaphore, Semaphore& postSemaphore); /// semaphore guarding access to "pop" functions - its value is equal to the number of available elements Semaphore popSemaphore_; /// semaphore guarding access to "push" functions - its value is equal to the number of free slots Semaphore pushSemaphore_; /// FeedablePool used by \a poolAllocator_ Pool pool_; /// PoolAllocator used by \a entryList_ and \a freeList_ PoolAllocator poolAllocator_; /// list of available entries, sorted in descending order of priority EntryList entryList_; /// list of "free" entries FreeEntryList freeEntryList_; }; } // namespace synchronization } // namespace distortos #endif // INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_
/** * \file * \brief MessageQueueBase class header * * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-01-15 */ #ifndef INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_ #define INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_ #include "distortos/Semaphore.hpp" #include "distortos/synchronization/SemaphoreFunctor.hpp" #include "distortos/allocators/FeedablePool.hpp" #include <forward_list> namespace distortos { namespace synchronization { /// MessageQueueBase class implements basic functionality of MessageQueue template class class MessageQueueBase { public: /// entry in the MessageQueueBase struct Entry { /** * \brief Entry's constructor * * \param [in] priorityy is the priority of the entry * \param [in] storagee is the storage for the entry */ constexpr Entry(const uint8_t priorityy, void* const storagee) : priority{priorityy}, storage{storagee} { } /// default copy constructor constexpr Entry(const Entry&) = default; /// priority of the entry uint8_t priority; /// storage for the entry void* storage; }; /** * \brief Functor is a type-erased interface for functors which execute some action on queue's storage (like * copy-constructing, swapping, destroying, emplacing, ...). * * The functor will be called by MessageQueueBase internals with one argument - \a storage - which is a pointer to * storage with/for element. */ using Functor = estd::TypeErasedFunctor<void(void*)>; /// link and Entry using LinkAndEntry = std::pair<void*, Entry>; /** * type of uninitialized storage for data * * \param T is the type of data in queue */ template<typename T> struct Storage { /// storage for Entry typename std::aligned_storage<sizeof(LinkAndEntry), alignof(LinkAndEntry)>::type entryStorage; /// storage for value typename std::aligned_storage<sizeof(T), alignof(T)>::type valueStorage; }; /// functor which gives descending priority order of elements on the list struct DescendingPriority { /** * \brief operator() * * \param [in] left is the object on the left side of comparison * \param [in] right is the object on the right side of comparison * * \return true if left's priority is less than right's priority */ bool operator()(const Entry& left, const Entry& right) { return left.priority < right.priority; } }; /// type of pool using Pool = allocators::FeedablePool; /// type of pool allocator using PoolAllocator = allocators::PoolAllocator<Entry, Pool>; /// type of entry list using EntryList = containers::SortedContainer<std::forward_list<Entry, PoolAllocator>, DescendingPriority>; /// type of free entry list using FreeEntryList = std::forward_list<Entry, PoolAllocator>; /** * \brief InternalFunctor is a type-erased interface for functors which execute common code of pop() and push() * operations. * * The functor will be called by MessageQueueBase internals with references to \a entryList_ and \a freeEntryList_. * It should perform common actions and execute the Functor passed from callers. */ using InternalFunctor = estd::TypeErasedFunctor<void(EntryList&, FreeEntryList&)>; /** * \brief MessageQueueBase's constructor * * \param T is the type of data in queue * * \param [in] storage is an array of Storage elements * \param [in] maxElements is the number of elements in \a storage array */ template<typename T> MessageQueueBase(Storage<T>* storage, size_t maxElements); /** * \brief Implementation of pop() using type-erased functor * * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a popSemaphore_ * \param [out] priority is a reference to variable that will be used to return priority of popped value * \param [in] functor is a reference to Functor which will execute actions related to popping - it will get a * pointer to storage with element * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by \a waitSemaphoreFunctor's operator() call; * - error codes returned by Semaphore::post(); */ int pop(const SemaphoreFunctor& waitSemaphoreFunctor, uint8_t& priority, const Functor& functor); /** * \brief Implementation of push() using type-erased functor * * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a pushSemaphore_ * \param [in] priority is the priority of new element * \param [in] functor is a reference to Functor which will execute actions related to pushing - it will get a * pointer to storage for element * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by \a waitSemaphoreFunctor's operator() call; * - error codes returned by Semaphore::post(); */ int push(const SemaphoreFunctor& waitSemaphoreFunctor, uint8_t priority, const Functor& functor); private: /** * \brief MessageQueueBase's constructor - internal version * * \param [in] maxElements is the maximum number of elements the queue can hold */ explicit MessageQueueBase(size_t maxElements); /** * \brief Implementation of pop() and push() using type-erased internal functor * * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a waitSemaphore * \param [in] internalFunctor is a reference to InternalFunctor which will execute actions related to * popping/pushing * \param [in] waitSemaphore is a reference to semaphore that will be waited for, \a popSemaphore_ for pop(), \a * pushSemaphore_ for push() * \param [in] postSemaphore is a reference to semaphore that will be posted after the operation, \a pushSemaphore_ * for pop(), \a popSemaphore_ for push() * * \return zero if operation was successful, error code otherwise: * - error codes returned by \a waitSemaphoreFunctor's operator() call; * - error codes returned by Semaphore::post(); */ int popPush(const SemaphoreFunctor& waitSemaphoreFunctor, const InternalFunctor& internalFunctor, Semaphore& waitSemaphore, Semaphore& postSemaphore); /// semaphore guarding access to "pop" functions - its value is equal to the number of available elements Semaphore popSemaphore_; /// semaphore guarding access to "push" functions - its value is equal to the number of free slots Semaphore pushSemaphore_; /// FeedablePool used by \a poolAllocator_ Pool pool_; /// PoolAllocator used by \a entryList_ and \a freeList_ PoolAllocator poolAllocator_; /// list of available entries, sorted in descending order of priority EntryList entryList_; /// list of "free" entries FreeEntryList freeEntryList_; }; template<typename T> MessageQueueBase::MessageQueueBase(Storage<T>* const storage, const size_t maxElements) : MessageQueueBase{maxElements} { for (size_t i = 0; i < maxElements; ++i) { pool_.feed(storage[i].entryStorage); freeEntryList_.emplace_front(uint8_t{}, &storage[i].valueStorage); } } } // namespace synchronization } // namespace distortos #endif // INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_
make template constructor non-inline
MessageQueueBase: make template constructor non-inline
C++
mpl-2.0
CezaryGapinski/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,jasmin-j/distortos,jasmin-j/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,jasmin-j/distortos,jasmin-j/distortos,jasmin-j/distortos,DISTORTEC/distortos,DISTORTEC/distortos,CezaryGapinski/distortos,CezaryGapinski/distortos
05bae14f349f038b0360f019e61610e5de593886
src/Config.cpp
src/Config.cpp
#include <string.h> #include <stdlib.h> #include "Config.h" #include "StdStream.h" #include "xml/Writer.h" #include "xml/Parser.h" #include "xml/Utils.h" #include "xml/FilteringNodeIterator.h" using namespace Framework; CConfig::CConfig(const PathType& path) : m_path(path) { Load(); } CConfig::~CConfig() { Save(); for(PreferenceMapType::iterator preferenceIterator(m_preferences.begin()); preferenceIterator != m_preferences.end(); preferenceIterator++) { delete preferenceIterator->second; } } std::string CConfig::MakePreferenceName(const std::string& level0, const std::string& level1, const std::string& level2, const std::string& level3) { std::string result = level0; if(level1.length()) { result += "." + level1; if(level2.length()) { result += "." + level2; if(level3.length()) { result += "." + level3; } } } return result; } namespace Framework { template <> CConfig::CPreference* CConfig::CastPreference<CConfig::CPreference>(CPreference* pPreference) { return pPreference; } template <> CConfig::CPreferenceInteger* CConfig::CastPreference<CConfig::CPreferenceInteger>(CPreference* pPreference) { if(pPreference->GetType() != TYPE_INTEGER) { return NULL; } return (CPreferenceInteger*)pPreference; } template <> CConfig::CPreferenceBoolean* CConfig::CastPreference<CConfig::CPreferenceBoolean>(CPreference* pPreference) { if(pPreference->GetType() != TYPE_BOOLEAN) { return NULL; } return (CPreferenceBoolean*)pPreference; } template <> CConfig::CPreferenceString* CConfig::CastPreference<CConfig::CPreferenceString>(CPreference* pPreference) { if(pPreference->GetType() != TYPE_STRING) { return NULL; } return (CPreferenceString*)pPreference; } } template <typename Type> Type* CConfig::FindPreference(const char* sName) { CPreference* pRet = NULL; { boost::mutex::scoped_lock mutexLock(m_mutex); PreferenceMapType::iterator preferenceIterator(m_preferences.find(sName)); if(preferenceIterator != m_preferences.end()) { pRet = preferenceIterator->second; } } if(pRet == NULL) return NULL; Type* pPrefCast = CastPreference<Type>(pRet); return pPrefCast; } void CConfig::RegisterPreferenceInteger(const char* sName, int nValue) { if(FindPreference<CPreference>(sName) != NULL) { return; } CPreferenceInteger* pPref = new CPreferenceInteger(sName, nValue); InsertPreference(pPref); } void CConfig::RegisterPreferenceBoolean(const char* sName, bool nValue) { if(FindPreference<CPreference>(sName) != NULL) { return; } CPreferenceBoolean* pPref = new CPreferenceBoolean(sName, nValue); InsertPreference(pPref); } void CConfig::RegisterPreferenceString(const char* sName, const char* sValue) { if(FindPreference<CPreference>(sName) != NULL) { return; } CPreferenceString* pPref = new CPreferenceString(sName, sValue); InsertPreference(pPref); } int CConfig::GetPreferenceInteger(const char* sName) { CPreferenceInteger* pPref = FindPreference<CPreferenceInteger>(sName); if(pPref == NULL) return 0; return pPref->GetValue(); } bool CConfig::GetPreferenceBoolean(const char* sName) { CPreferenceBoolean* pPref = FindPreference<CPreferenceBoolean>(sName); if(pPref == NULL) return false; return pPref->GetValue(); } const char* CConfig::GetPreferenceString(const char* sName) { CPreferenceString* pPref = FindPreference<CPreferenceString>(sName); if(pPref == NULL) return ""; return pPref->GetValue(); } bool CConfig::SetPreferenceInteger(const char* sName, int nValue) { CPreferenceInteger* pPref = FindPreference<CPreferenceInteger>(sName); if(pPref == NULL) return false; pPref->SetValue(nValue); return true; } bool CConfig::SetPreferenceBoolean(const char* sName, bool nValue) { CPreferenceBoolean* pPref = FindPreference<CPreferenceBoolean>(sName); if(pPref == NULL) return false; pPref->SetValue(nValue); return true; } bool CConfig::SetPreferenceString(const char* sName, const char* sValue) { CPreferenceString* pPref = FindPreference<CPreferenceString>(sName); if(pPref == NULL) return false; pPref->SetValue(sValue); return true; } CConfig::PathType CConfig::GetConfigPath() const { return m_path; } void CConfig::Load() { Xml::CNode* pDocument; try { CStdStream configFile(m_path.wstring().c_str(), L"rb"); pDocument = Xml::CParser::ParseDocument(&configFile); } catch(...) { return; } Xml::CNode* pConfig = pDocument->Select("Config"); if(pConfig == NULL) { delete pDocument; return; } for(Xml::CFilteringNodeIterator itNode(pConfig, "Preference"); !itNode.IsEnd(); itNode++) { Xml::CNode* pPref = (*itNode); const char* sType = pPref->GetAttribute("Type"); const char* sName = pPref->GetAttribute("Name"); if(sType == NULL) continue; if(sName == NULL) continue; if(!strcmp(sType, "integer")) { int nValue; if(Xml::GetAttributeIntValue(pPref, "Value", &nValue)) { RegisterPreferenceInteger(sName, nValue); } } else if(!strcmp(sType, "boolean")) { bool nValue; if(Xml::GetAttributeBoolValue(pPref, "Value", &nValue)) { RegisterPreferenceBoolean(sName, nValue); } } else if(!strcmp(sType, "string")) { const char* sValue; if(Xml::GetAttributeStringValue(pPref, "Value", &sValue)) { RegisterPreferenceString(sName, sValue); } } } delete pDocument; } void CConfig::Save() { try { CStdStream stream(m_path.wstring().c_str(), L"wb"); Xml::CNode* pConfig = new Xml::CNode("Config", true); for(PreferenceMapType::const_iterator preferenceIterator(m_preferences.begin()); preferenceIterator != m_preferences.end(); preferenceIterator++) { CPreference* pPref = (preferenceIterator->second); Xml::CNode* pPrefNode = new Xml::CNode("Preference", true); pPref->Serialize(pPrefNode); pConfig->InsertNode(pPrefNode); } { Xml::CNode* pDocument = new Xml::CNode; pDocument->InsertNode(pConfig); Xml::CWriter::WriteDocument(&stream, pDocument); delete pDocument; } } catch(...) { return; } } void CConfig::InsertPreference(CPreference* pPref) { boost::mutex::scoped_lock mutexLock(m_mutex); m_preferences[pPref->GetName()] = pPref; } ///////////////////////////////////////////////////////// //CPreference implementation ///////////////////////////////////////////////////////// CConfig::CPreference::CPreference(const char* sName, PREFERENCE_TYPE nType) { m_sName = sName; m_nType = nType; } CConfig::CPreference::~CPreference() { } const char* CConfig::CPreference::GetName() { return m_sName.c_str(); } CConfig::PREFERENCE_TYPE CConfig::CPreference::GetType() { return m_nType; } const char* CConfig::CPreference::GetTypeString() { switch(m_nType) { case TYPE_INTEGER: return "integer"; break; case TYPE_STRING: return "string"; break; case TYPE_BOOLEAN: return "boolean"; break; } return ""; } void CConfig::CPreference::Serialize(Xml::CNode* pNode) { pNode->InsertAttribute(Xml::CreateAttributeStringValue("Name", m_sName.c_str())); pNode->InsertAttribute(Xml::CreateAttributeStringValue("Type", GetTypeString())); } ///////////////////////////////////////////////////////// //CPreferenceInteger implementation ///////////////////////////////////////////////////////// CConfig::CPreferenceInteger::CPreferenceInteger(const char* sName, int nValue) : CPreference(sName, TYPE_INTEGER) { m_nValue = nValue; } CConfig::CPreferenceInteger::~CPreferenceInteger() { } int CConfig::CPreferenceInteger::GetValue() { return m_nValue; } void CConfig::CPreferenceInteger::SetValue(int nValue) { m_nValue = nValue; } void CConfig::CPreferenceInteger::Serialize(Xml::CNode* pNode) { CPreference::Serialize(pNode); pNode->InsertAttribute(Xml::CreateAttributeIntValue("Value", m_nValue)); } ///////////////////////////////////////////////////////// //CPreferenceBoolean implementation ///////////////////////////////////////////////////////// CConfig::CPreferenceBoolean::CPreferenceBoolean(const char* sName, bool nValue) : CPreference(sName, TYPE_BOOLEAN) { m_nValue = nValue; } CConfig::CPreferenceBoolean::~CPreferenceBoolean() { } bool CConfig::CPreferenceBoolean::GetValue() { return m_nValue; } void CConfig::CPreferenceBoolean::SetValue(bool nValue) { m_nValue = nValue; } void CConfig::CPreferenceBoolean::Serialize(Xml::CNode* pNode) { CPreference::Serialize(pNode); pNode->InsertAttribute(Xml::CreateAttributeBoolValue("Value", m_nValue)); } ///////////////////////////////////////////////////////// //CPreferenceString implementation ///////////////////////////////////////////////////////// CConfig::CPreferenceString::CPreferenceString(const char* sName, const char* sValue) : CPreference(sName, TYPE_STRING) { m_sValue = sValue; } CConfig::CPreferenceString::~CPreferenceString() { } const char* CConfig::CPreferenceString::GetValue() { return m_sValue.c_str(); } void CConfig::CPreferenceString::SetValue(const char* sValue) { m_sValue = sValue; } void CConfig::CPreferenceString::Serialize(Xml::CNode* pNode) { CPreference::Serialize(pNode); pNode->InsertAttribute(Xml::CreateAttributeStringValue("Value", m_sValue.c_str())); }
#include <string.h> #include <stdlib.h> #include "Config.h" #include "StdStream.h" #include "xml/Writer.h" #include "xml/Parser.h" #include "xml/Utils.h" #include "xml/FilteringNodeIterator.h" #include "StdStreamUtils.h" using namespace Framework; CConfig::CConfig(const PathType& path) : m_path(path) { Load(); } CConfig::~CConfig() { Save(); for(auto preferenceIterator(std::begin(m_preferences)); preferenceIterator != std::end(m_preferences); preferenceIterator++) { delete preferenceIterator->second; } } std::string CConfig::MakePreferenceName(const std::string& level0, const std::string& level1, const std::string& level2, const std::string& level3) { std::string result = level0; if(level1.length()) { result += "." + level1; if(level2.length()) { result += "." + level2; if(level3.length()) { result += "." + level3; } } } return result; } namespace Framework { template <> CConfig::CPreference* CConfig::CastPreference<CConfig::CPreference>(CPreference* pPreference) { return pPreference; } template <> CConfig::CPreferenceInteger* CConfig::CastPreference<CConfig::CPreferenceInteger>(CPreference* pPreference) { if(pPreference->GetType() != TYPE_INTEGER) { return NULL; } return (CPreferenceInteger*)pPreference; } template <> CConfig::CPreferenceBoolean* CConfig::CastPreference<CConfig::CPreferenceBoolean>(CPreference* pPreference) { if(pPreference->GetType() != TYPE_BOOLEAN) { return NULL; } return (CPreferenceBoolean*)pPreference; } template <> CConfig::CPreferenceString* CConfig::CastPreference<CConfig::CPreferenceString>(CPreference* pPreference) { if(pPreference->GetType() != TYPE_STRING) { return NULL; } return (CPreferenceString*)pPreference; } } template <typename Type> Type* CConfig::FindPreference(const char* sName) { CPreference* pRet = NULL; { boost::mutex::scoped_lock mutexLock(m_mutex); PreferenceMapType::iterator preferenceIterator(m_preferences.find(sName)); if(preferenceIterator != m_preferences.end()) { pRet = preferenceIterator->second; } } if(pRet == NULL) return NULL; Type* pPrefCast = CastPreference<Type>(pRet); return pPrefCast; } void CConfig::RegisterPreferenceInteger(const char* sName, int nValue) { if(FindPreference<CPreference>(sName) != NULL) { return; } CPreferenceInteger* pPref = new CPreferenceInteger(sName, nValue); InsertPreference(pPref); } void CConfig::RegisterPreferenceBoolean(const char* sName, bool nValue) { if(FindPreference<CPreference>(sName) != NULL) { return; } CPreferenceBoolean* pPref = new CPreferenceBoolean(sName, nValue); InsertPreference(pPref); } void CConfig::RegisterPreferenceString(const char* sName, const char* sValue) { if(FindPreference<CPreference>(sName) != NULL) { return; } CPreferenceString* pPref = new CPreferenceString(sName, sValue); InsertPreference(pPref); } int CConfig::GetPreferenceInteger(const char* sName) { CPreferenceInteger* pPref = FindPreference<CPreferenceInteger>(sName); if(pPref == NULL) return 0; return pPref->GetValue(); } bool CConfig::GetPreferenceBoolean(const char* sName) { CPreferenceBoolean* pPref = FindPreference<CPreferenceBoolean>(sName); if(pPref == NULL) return false; return pPref->GetValue(); } const char* CConfig::GetPreferenceString(const char* sName) { CPreferenceString* pPref = FindPreference<CPreferenceString>(sName); if(pPref == NULL) return ""; return pPref->GetValue(); } bool CConfig::SetPreferenceInteger(const char* sName, int nValue) { CPreferenceInteger* pPref = FindPreference<CPreferenceInteger>(sName); if(pPref == NULL) return false; pPref->SetValue(nValue); return true; } bool CConfig::SetPreferenceBoolean(const char* sName, bool nValue) { CPreferenceBoolean* pPref = FindPreference<CPreferenceBoolean>(sName); if(pPref == NULL) return false; pPref->SetValue(nValue); return true; } bool CConfig::SetPreferenceString(const char* sName, const char* sValue) { CPreferenceString* pPref = FindPreference<CPreferenceString>(sName); if(pPref == NULL) return false; pPref->SetValue(sValue); return true; } CConfig::PathType CConfig::GetConfigPath() const { return m_path; } void CConfig::Load() { Xml::CNode* pDocument(nullptr); try { boost::scoped_ptr<CStdStream> configFile(CreateInputStdStream(m_path.native())); pDocument = Xml::CParser::ParseDocument(configFile.get()); } catch(...) { return; } Xml::CNode* pConfig = pDocument->Select("Config"); if(pConfig == NULL) { delete pDocument; return; } for(Xml::CFilteringNodeIterator itNode(pConfig, "Preference"); !itNode.IsEnd(); itNode++) { Xml::CNode* pPref = (*itNode); const char* sType = pPref->GetAttribute("Type"); const char* sName = pPref->GetAttribute("Name"); if(sType == NULL) continue; if(sName == NULL) continue; if(!strcmp(sType, "integer")) { int nValue; if(Xml::GetAttributeIntValue(pPref, "Value", &nValue)) { RegisterPreferenceInteger(sName, nValue); } } else if(!strcmp(sType, "boolean")) { bool nValue; if(Xml::GetAttributeBoolValue(pPref, "Value", &nValue)) { RegisterPreferenceBoolean(sName, nValue); } } else if(!strcmp(sType, "string")) { const char* sValue; if(Xml::GetAttributeStringValue(pPref, "Value", &sValue)) { RegisterPreferenceString(sName, sValue); } } } delete pDocument; } void CConfig::Save() { try { boost::scoped_ptr<CStdStream> stream(CreateOutputStdStream(m_path.native())); Xml::CNode* pConfig = new Xml::CNode("Config", true); for(PreferenceMapType::const_iterator preferenceIterator(m_preferences.begin()); preferenceIterator != m_preferences.end(); preferenceIterator++) { CPreference* pPref = (preferenceIterator->second); Xml::CNode* pPrefNode = new Xml::CNode("Preference", true); pPref->Serialize(pPrefNode); pConfig->InsertNode(pPrefNode); } { Xml::CNode* pDocument = new Xml::CNode; pDocument->InsertNode(pConfig); Xml::CWriter::WriteDocument(stream.get(), pDocument); delete pDocument; } } catch(...) { return; } } void CConfig::InsertPreference(CPreference* pPref) { boost::mutex::scoped_lock mutexLock(m_mutex); m_preferences[pPref->GetName()] = pPref; } ///////////////////////////////////////////////////////// //CPreference implementation ///////////////////////////////////////////////////////// CConfig::CPreference::CPreference(const char* sName, PREFERENCE_TYPE nType) { m_sName = sName; m_nType = nType; } CConfig::CPreference::~CPreference() { } const char* CConfig::CPreference::GetName() { return m_sName.c_str(); } CConfig::PREFERENCE_TYPE CConfig::CPreference::GetType() { return m_nType; } const char* CConfig::CPreference::GetTypeString() { switch(m_nType) { case TYPE_INTEGER: return "integer"; break; case TYPE_STRING: return "string"; break; case TYPE_BOOLEAN: return "boolean"; break; } return ""; } void CConfig::CPreference::Serialize(Xml::CNode* pNode) { pNode->InsertAttribute(Xml::CreateAttributeStringValue("Name", m_sName.c_str())); pNode->InsertAttribute(Xml::CreateAttributeStringValue("Type", GetTypeString())); } ///////////////////////////////////////////////////////// //CPreferenceInteger implementation ///////////////////////////////////////////////////////// CConfig::CPreferenceInteger::CPreferenceInteger(const char* sName, int nValue) : CPreference(sName, TYPE_INTEGER) { m_nValue = nValue; } CConfig::CPreferenceInteger::~CPreferenceInteger() { } int CConfig::CPreferenceInteger::GetValue() { return m_nValue; } void CConfig::CPreferenceInteger::SetValue(int nValue) { m_nValue = nValue; } void CConfig::CPreferenceInteger::Serialize(Xml::CNode* pNode) { CPreference::Serialize(pNode); pNode->InsertAttribute(Xml::CreateAttributeIntValue("Value", m_nValue)); } ///////////////////////////////////////////////////////// //CPreferenceBoolean implementation ///////////////////////////////////////////////////////// CConfig::CPreferenceBoolean::CPreferenceBoolean(const char* sName, bool nValue) : CPreference(sName, TYPE_BOOLEAN) { m_nValue = nValue; } CConfig::CPreferenceBoolean::~CPreferenceBoolean() { } bool CConfig::CPreferenceBoolean::GetValue() { return m_nValue; } void CConfig::CPreferenceBoolean::SetValue(bool nValue) { m_nValue = nValue; } void CConfig::CPreferenceBoolean::Serialize(Xml::CNode* pNode) { CPreference::Serialize(pNode); pNode->InsertAttribute(Xml::CreateAttributeBoolValue("Value", m_nValue)); } ///////////////////////////////////////////////////////// //CPreferenceString implementation ///////////////////////////////////////////////////////// CConfig::CPreferenceString::CPreferenceString(const char* sName, const char* sValue) : CPreference(sName, TYPE_STRING) { m_sValue = sValue; } CConfig::CPreferenceString::~CPreferenceString() { } const char* CConfig::CPreferenceString::GetValue() { return m_sValue.c_str(); } void CConfig::CPreferenceString::SetValue(const char* sValue) { m_sValue = sValue; } void CConfig::CPreferenceString::Serialize(Xml::CNode* pNode) { CPreference::Serialize(pNode); pNode->InsertAttribute(Xml::CreateAttributeStringValue("Value", m_sValue.c_str())); }
Use StdStreamUtils to open config files + cleanup.
Use StdStreamUtils to open config files + cleanup. git-svn-id: 36de21aa7b1472b3fce746da1590bf50bb7584d6@268 6a6d099a-6a11-0410-877e-d5a07a98cbd2
C++
bsd-2-clause
Thunder07/Play--Framework,Thunder07/Play--Framework,AbandonedCart/Play-Framework,AbandonedCart/Play-Framework,Thunder07/Play--Framework,Alloyed/Play--Framework,Alloyed/Play--Framework,AbandonedCart/Play-Framework,Alloyed/Play--Framework
93b74e101662f2733d4367378aedb6bf01286a61
src/software/calibration/main_cameraCalibration.cpp
src/software/calibration/main_cameraCalibration.cpp
#include <openMVG/dataio/FeedProvider.hpp> #include <openMVG/cameras/Camera_undistort_image.hpp> #include <openMVG/cameras/Camera_Pinhole_Radial.hpp> #include <openMVG/image/image_io.hpp> #include <openMVG/calibration/patternDetect.hpp> #include <openMVG/calibration/bestImages.hpp> #include <openMVG/calibration/calibration.hpp> #include <openMVG/calibration/exportData.hpp> #include <openMVG/system/timer.hpp> #include <openMVG/logger.hpp> #include <boost/lexical_cast.hpp> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/path.hpp> #include <boost/algorithm/string/case_conv.hpp> #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/core/eigen.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <stdio.h> #include <ctime> #include <cstdio> #include <string> #include <cctype> #include <fstream> #include <iostream> #include <stdexcept> #include <exception> #include <map> #include <limits> namespace bfs = boost::filesystem; namespace po = boost::program_options; int main(int argc, char** argv) { // Command line arguments bfs::path inputPath; std::string outputFilename; std::string debugSelectedImgFolder; std::string debugRejectedImgFolder; std::vector<std::size_t> checkerboardSize; openMVG::calibration::Pattern patternType = openMVG::calibration::Pattern::CHESSBOARD; std::size_t maxNbFrames = 0; std::size_t maxCalibFrames = 100; std::size_t calibGridSize = 10; std::size_t nbDistortionCoef = 3; std::size_t minInputFrames = 10; double squareSize = 1.0; double maxTotalAvgErr = 0.1; po::options_description desc("\n\nThis program is used to calibrate a camera from a dataset of images.\n"); desc.add_options() ("help,h", "Produce help message.\n") ("input,i", po::value<bfs::path>(&inputPath)->required(), "Input images in one of the following form:\n" " - folder containing images\n" " - image sequence like /path/to/[email protected]\n" " - video file\n") ("output,o", po::value<std::string>(&outputFilename)->required(), "Output filename for intrinsic [and extrinsic] parameters.\n") ("pattern,p", po::value<openMVG::calibration::Pattern>(&patternType)->default_value(patternType), "Type of pattern: 'CHESSBOARD', 'CIRCLES', 'ASYMMETRIC_CIRCLES'" #ifdef HAVE_CCTAG " or 'ASYMMETRIC_CCTAG'" #endif ".\n") ("size,s", po::value<std::vector < std::size_t >> (&checkerboardSize)->multitoken(), "Number of inner corners per one of board dimension like W H.\n") ("squareSize", po::value<double> (&squareSize)->default_value(squareSize), "Size of the grid's square cells (mm).\n") ("nbDistortionCoef,r", po::value<std::size_t>(&nbDistortionCoef)->default_value(nbDistortionCoef), "Number of distortion coefficient.\n") ("maxFrames", po::value<std::size_t>(&maxNbFrames)->default_value(maxNbFrames), "Maximal number of frames to extract from the video file.\n") ("maxCalibFrames", po::value<std::size_t>(&maxCalibFrames)->default_value(maxCalibFrames), "Maximal number of frames to use to calibrate from the selected frames.\n") ("calibGridSize", po::value<std::size_t>(&calibGridSize)->default_value(calibGridSize), "Define the number of cells per edge.\n") ("minInputFrames", po::value<std::size_t>(&minInputFrames)->default_value(minInputFrames), "Minimal number of frames to limit the refinement loop.\n") ("maxTotalAvgErr,e", po::value<double>(&maxTotalAvgErr)->default_value(maxTotalAvgErr), "Max Total Average Error.\n") ("debugRejectedImgFolder", po::value<std::string>(&debugRejectedImgFolder)->default_value(""), "Folder to export delete images during the refinement loop.\n") ("debugSelectedImgFolder,d", po::value<std::string>(&debugSelectedImgFolder)->default_value(""), "Folder to export debug images.\n") ; po::variables_map vm; int cvCalibFlags = 0; try { po::store(po::parse_command_line(argc, argv, desc), vm); if (vm.count("help") || (argc == 1)) { OPENMVG_COUT(desc); return EXIT_SUCCESS; } cvCalibFlags |= CV_CALIB_ZERO_TANGENT_DIST; if (nbDistortionCoef < 1 || nbDistortionCoef > 6) throw boost::program_options::invalid_option_value(std::string("Only supports 2 or 3 radial coefs: ") + std::to_string(nbDistortionCoef)); const std::array<int, 6> fixDistortionCoefs = {CV_CALIB_FIX_K1, CV_CALIB_FIX_K2, CV_CALIB_FIX_K3, CV_CALIB_FIX_K4, CV_CALIB_FIX_K5, CV_CALIB_FIX_K6}; for (int i = nbDistortionCoef; i < 6; ++i) cvCalibFlags |= fixDistortionCoefs[i]; po::notify(vm); } catch (boost::program_options::required_option& e) { OPENMVG_CERR("ERROR: " << e.what()); OPENMVG_CERR("Usage:\n\n" << desc); return EXIT_FAILURE; } catch (boost::program_options::error& e) { OPENMVG_CERR("ERROR: " << e.what()); OPENMVG_CERR("Usage:\n\n" << desc); return EXIT_FAILURE; } if (checkerboardSize.size() != 2) throw std::logic_error("The size of the checkerboard is not defined"); if ((maxNbFrames != 0 && maxCalibFrames > maxNbFrames) || minInputFrames > maxCalibFrames) { throw std::logic_error("Check the value for maxFrames, maxCalibFrames & minInputFrames. It must be decreasing."); } bool writeExtrinsics = false; bool writePoints = false; float aspectRatio = 1.f; cv::Mat cameraMatrix; cv::Mat distCoeffs; cv::Size boardSize(checkerboardSize[0], checkerboardSize[1]); cv::Size imageSize(0, 0); std::vector<std::vector<cv::Point2f> > imagePoints; std::clock_t start = std::clock(); // create the feedProvider openMVG::dataio::FeedProvider feed(inputPath.string()); if (!feed.isInit()) { OPENMVG_CERR("ERROR while initializing the FeedProvider!"); return EXIT_FAILURE; } openMVG::image::Image<unsigned char> imageGrey; openMVG::cameras::Pinhole_Intrinsic_Radial_K3 queryIntrinsics; bool hasIntrinsics = false; std::string currentImgName; std::size_t iInputFrame = 0; std::vector<std::size_t> validFrames; std::vector<std::vector<int> > detectedIdPerFrame; double step = 1.0; int nbFramesToProcess = feed.nbFrames(); // Compute the discretization's step if (maxNbFrames) { if (feed.nbFrames() > maxNbFrames) step = feed.nbFrames() / (double) maxNbFrames; else nbFramesToProcess = maxNbFrames; } OPENMVG_COUT("Input video length is " << feed.nbFrames() << "."); openMVG::system::Timer durationAlgo; openMVG::system::Timer duration; std::size_t currentFrame = 0; while (feed.readImage(imageGrey, queryIntrinsics, currentImgName, hasIntrinsics)) { cv::Mat viewGray; cv::eigen2cv(imageGrey.GetMat(), viewGray); // Check image is correctly loaded if (viewGray.size() == cv::Size(0, 0)) { throw std::runtime_error(std::string("Invalid image: ") + currentImgName); } // Check image size is always the same if (imageSize == cv::Size(0, 0)) { // First image: initialize the image size. imageSize = viewGray.size(); } // Check image resolutions are always the same else if (imageSize != viewGray.size()) { throw std::runtime_error(std::string("You cannot mix multiple image resolutions during the camera calibration. See image file: ") + currentImgName); } std::vector<cv::Point2f> pointbuf; std::vector<int> detectedId; OPENMVG_CERR("[" << currentFrame << "/" << nbFramesToProcess << "]"); // Find the chosen pattern in images const bool found = openMVG::calibration::findPattern(patternType, viewGray, boardSize, detectedId, pointbuf); if (found) { validFrames.push_back(currentFrame); detectedIdPerFrame.push_back(detectedId); imagePoints.push_back(pointbuf); } ++iInputFrame; currentFrame = std::floor(iInputFrame * step); feed.goToFrame(currentFrame); } OPENMVG_CERR("find points duration: " << openMVG::system::prettyTime(duration.elapsedMs())); OPENMVG_CERR("Grid detected in " << imagePoints.size() << " images on " << iInputFrame << " input images."); if (imagePoints.empty()) throw std::logic_error("No checkerboard detected."); std::vector<std::size_t> remainingImagesIndexes; std::vector<float> calibImageScore; std::vector<std::size_t> calibInputFrames; std::vector<std::vector<cv::Point2f> > calibImagePoints; // Select best images based on repartition in images of the calibration landmarks openMVG::calibration::selectBestImages( imagePoints, imageSize, maxCalibFrames, calibGridSize, calibImageScore, calibInputFrames, calibImagePoints, remainingImagesIndexes); start = std::clock(); // Create an object which stores all the checker points of the images std::vector<std::vector<cv::Point3f> > calibObjectPoints; { std::vector<cv::Point3f> templateObjectPoints; // Generate the object points coordinates openMVG::calibration::calcChessboardCorners(templateObjectPoints, boardSize, squareSize, patternType); // Assign the corners to all items for(std::size_t frame: calibInputFrames) { // For some chessboard (ie. CCTag), we have an identification per point, // and only a sub-part of the corners may be detected. // So we only keep the visible corners from the templateObjectPoints std::vector<int>& pointsId = detectedIdPerFrame[frame]; std::vector<cv::Point3f> objectPoints(pointsId.size()); for(size_t i = 0; i < pointsId.size(); ++i) { objectPoints[i] = templateObjectPoints[pointsId[i]]; } calibObjectPoints.push_back(objectPoints); } assert(calibInputFrames.size() == calibImagePoints.size()); } double totalAvgErr = 0; std::vector<cv::Mat> rvecs; std::vector<cv::Mat> tvecs; std::vector<float> reprojErrs; std::vector<std::size_t> rejectInputFrames; duration.reset(); // Refinement loop of the calibration openMVG::calibration::calibrationIterativeOptimization(imageSize, aspectRatio, cvCalibFlags, cameraMatrix, distCoeffs, rvecs, tvecs, reprojErrs, totalAvgErr, maxTotalAvgErr, minInputFrames, calibInputFrames, calibImagePoints, calibObjectPoints, calibImageScore, rejectInputFrames); OPENMVG_COUT("Calibration duration: " << openMVG::system::prettyTime(duration.elapsedMs())); openMVG::calibration::saveCameraParams(outputFilename, imageSize, boardSize, squareSize, aspectRatio, cvCalibFlags, cameraMatrix, distCoeffs, writeExtrinsics ? rvecs : std::vector<cv::Mat>(), writeExtrinsics ? tvecs : std::vector<cv::Mat>(), writeExtrinsics ? reprojErrs : std::vector<float>(), writePoints ? calibImagePoints : std::vector<std::vector<cv::Point2f> >(), totalAvgErr); openMVG::calibration::exportDebug(debugSelectedImgFolder, debugRejectedImgFolder, feed, calibInputFrames, rejectInputFrames, remainingImagesIndexes, cameraMatrix, distCoeffs, imageSize); OPENMVG_COUT("Total duration: " << openMVG::system::prettyTime(durationAlgo.elapsedMs())); return EXIT_SUCCESS; }
#include <openMVG/dataio/FeedProvider.hpp> #include <openMVG/cameras/Camera_undistort_image.hpp> #include <openMVG/cameras/Camera_Pinhole_Radial.hpp> #include <openMVG/image/image_io.hpp> #include <openMVG/calibration/patternDetect.hpp> #include <openMVG/calibration/bestImages.hpp> #include <openMVG/calibration/calibration.hpp> #include <openMVG/calibration/exportData.hpp> #include <openMVG/system/timer.hpp> #include <openMVG/logger.hpp> #include <boost/lexical_cast.hpp> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/path.hpp> #include <boost/algorithm/string/case_conv.hpp> #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/core/eigen.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <stdio.h> #include <ctime> #include <cstdio> #include <string> #include <cctype> #include <fstream> #include <iostream> #include <stdexcept> #include <exception> #include <map> #include <limits> namespace bfs = boost::filesystem; namespace po = boost::program_options; int main(int argc, char** argv) { // Command line arguments bfs::path inputPath; std::string outputFilename; std::string debugSelectedImgFolder; std::string debugRejectedImgFolder; std::vector<std::size_t> checkerboardSize; openMVG::calibration::Pattern patternType = openMVG::calibration::Pattern::CHESSBOARD; std::size_t maxNbFrames = 0; std::size_t maxCalibFrames = 100; std::size_t calibGridSize = 10; std::size_t nbDistortionCoef = 3; std::size_t minInputFrames = 10; double squareSize = 1.0; double maxTotalAvgErr = 0.1; po::options_description desc("\n\nThis program is used to calibrate a camera from a dataset of images.\n"); desc.add_options() ("help,h", "Produce help message.\n") ("input,i", po::value<bfs::path>(&inputPath)->required(), "Input images in one of the following form:\n" " - folder containing images\n" " - image sequence like /path/to/[email protected]\n" " - video file\n") ("output,o", po::value<std::string>(&outputFilename)->required(), "Output filename for intrinsic [and extrinsic] parameters.\n") ("pattern,p", po::value<openMVG::calibration::Pattern>(&patternType)->default_value(patternType), "Type of pattern: 'CHESSBOARD', 'CIRCLES', 'ASYMMETRIC_CIRCLES'" #ifdef HAVE_CCTAG " or 'ASYMMETRIC_CCTAG'" #endif ".\n") ("size,s", po::value<std::vector < std::size_t >> (&checkerboardSize)->multitoken(), "Number of inner corners per one of board dimension like W H.\n") ("squareSize", po::value<double> (&squareSize)->default_value(squareSize), "Size of the grid's square cells (mm).\n") ("nbDistortionCoef,r", po::value<std::size_t>(&nbDistortionCoef)->default_value(nbDistortionCoef), "Number of distortion coefficient.\n") ("maxFrames", po::value<std::size_t>(&maxNbFrames)->default_value(maxNbFrames), "Maximal number of frames to extract from the video file.\n") ("maxCalibFrames", po::value<std::size_t>(&maxCalibFrames)->default_value(maxCalibFrames), "Maximal number of frames to use to calibrate from the selected frames.\n") ("calibGridSize", po::value<std::size_t>(&calibGridSize)->default_value(calibGridSize), "Define the number of cells per edge.\n") ("minInputFrames", po::value<std::size_t>(&minInputFrames)->default_value(minInputFrames), "Minimal number of frames to limit the refinement loop.\n") ("maxTotalAvgErr,e", po::value<double>(&maxTotalAvgErr)->default_value(maxTotalAvgErr), "Max Total Average Error.\n") ("debugRejectedImgFolder", po::value<std::string>(&debugRejectedImgFolder)->default_value(""), "Folder to export delete images during the refinement loop.\n") ("debugSelectedImgFolder,d", po::value<std::string>(&debugSelectedImgFolder)->default_value(""), "Folder to export debug images.\n") ; po::variables_map vm; int cvCalibFlags = 0; try { po::store(po::parse_command_line(argc, argv, desc), vm); if (vm.count("help") || (argc == 1)) { OPENMVG_COUT(desc); return EXIT_SUCCESS; } cvCalibFlags |= CV_CALIB_ZERO_TANGENT_DIST; if (nbDistortionCoef < 1 || nbDistortionCoef > 6) throw boost::program_options::invalid_option_value(std::string("Only supports 2 or 3 radial coefs: ") + std::to_string(nbDistortionCoef)); const std::array<int, 6> fixDistortionCoefs = {CV_CALIB_FIX_K1, CV_CALIB_FIX_K2, CV_CALIB_FIX_K3, CV_CALIB_FIX_K4, CV_CALIB_FIX_K5, CV_CALIB_FIX_K6}; for (int i = nbDistortionCoef; i < 6; ++i) cvCalibFlags |= fixDistortionCoefs[i]; po::notify(vm); } catch (boost::program_options::required_option& e) { OPENMVG_CERR("ERROR: " << e.what()); OPENMVG_CERR("Usage:\n\n" << desc); return EXIT_FAILURE; } catch (boost::program_options::error& e) { OPENMVG_CERR("ERROR: " << e.what()); OPENMVG_CERR("Usage:\n\n" << desc); return EXIT_FAILURE; } if (checkerboardSize.size() != 2) throw std::logic_error("The size of the checkerboard is not defined"); if ((maxNbFrames != 0 && maxCalibFrames > maxNbFrames) || minInputFrames > maxCalibFrames) { throw std::logic_error("Check the value for maxFrames, maxCalibFrames & minInputFrames. It must be decreasing."); } bool writeExtrinsics = false; bool writePoints = false; float aspectRatio = 1.f; cv::Mat cameraMatrix; cv::Mat distCoeffs; cv::Size boardSize(checkerboardSize[0], checkerboardSize[1]); cv::Size imageSize(0, 0); std::vector<std::vector<cv::Point2f> > imagePoints; std::clock_t start = std::clock(); // create the feedProvider openMVG::dataio::FeedProvider feed(inputPath.string()); if (!feed.isInit()) { OPENMVG_CERR("ERROR while initializing the FeedProvider!"); return EXIT_FAILURE; } openMVG::image::Image<unsigned char> imageGrey; openMVG::cameras::Pinhole_Intrinsic_Radial_K3 queryIntrinsics; bool hasIntrinsics = false; std::string currentImgName; std::size_t iInputFrame = 0; std::vector<std::size_t> validFrames; std::vector<std::vector<int> > detectedIdPerFrame; double step = 1.0; int nbFramesToProcess = feed.nbFrames(); // Compute the discretization's step if (maxNbFrames && feed.nbFrames() > maxNbFrames) { step = feed.nbFrames() / (double) maxNbFrames; nbFramesToProcess = maxNbFrames; } OPENMVG_COUT("Input video length is " << feed.nbFrames() << "."); openMVG::system::Timer durationAlgo; openMVG::system::Timer duration; std::size_t currentFrame = 0; while (feed.readImage(imageGrey, queryIntrinsics, currentImgName, hasIntrinsics)) { cv::Mat viewGray; cv::eigen2cv(imageGrey.GetMat(), viewGray); // Check image is correctly loaded if (viewGray.size() == cv::Size(0, 0)) { throw std::runtime_error(std::string("Invalid image: ") + currentImgName); } // Check image size is always the same if (imageSize == cv::Size(0, 0)) { // First image: initialize the image size. imageSize = viewGray.size(); } // Check image resolutions are always the same else if (imageSize != viewGray.size()) { throw std::runtime_error(std::string("You cannot mix multiple image resolutions during the camera calibration. See image file: ") + currentImgName); } std::vector<cv::Point2f> pointbuf; std::vector<int> detectedId; OPENMVG_CERR("[" << currentFrame << "/" << nbFramesToProcess << "]"); // Find the chosen pattern in images const bool found = openMVG::calibration::findPattern(patternType, viewGray, boardSize, detectedId, pointbuf); if (found) { validFrames.push_back(currentFrame); detectedIdPerFrame.push_back(detectedId); imagePoints.push_back(pointbuf); } ++iInputFrame; currentFrame = std::floor(iInputFrame * step); feed.goToFrame(currentFrame); } OPENMVG_CERR("find points duration: " << openMVG::system::prettyTime(duration.elapsedMs())); OPENMVG_CERR("Grid detected in " << imagePoints.size() << " images on " << iInputFrame << " input images."); if (imagePoints.empty()) throw std::logic_error("No checkerboard detected."); std::vector<std::size_t> remainingImagesIndexes; std::vector<float> calibImageScore; std::vector<std::size_t> calibInputFrames; std::vector<std::vector<cv::Point2f> > calibImagePoints; // Select best images based on repartition in images of the calibration landmarks openMVG::calibration::selectBestImages( imagePoints, imageSize, maxCalibFrames, calibGridSize, calibImageScore, calibInputFrames, calibImagePoints, remainingImagesIndexes); start = std::clock(); // Create an object which stores all the checker points of the images std::vector<std::vector<cv::Point3f> > calibObjectPoints; { std::vector<cv::Point3f> templateObjectPoints; // Generate the object points coordinates openMVG::calibration::calcChessboardCorners(templateObjectPoints, boardSize, squareSize, patternType); // Assign the corners to all items for(std::size_t frame: calibInputFrames) { // For some chessboard (ie. CCTag), we have an identification per point, // and only a sub-part of the corners may be detected. // So we only keep the visible corners from the templateObjectPoints std::vector<int>& pointsId = detectedIdPerFrame[frame]; std::vector<cv::Point3f> objectPoints(pointsId.size()); for(size_t i = 0; i < pointsId.size(); ++i) { objectPoints[i] = templateObjectPoints[pointsId[i]]; } calibObjectPoints.push_back(objectPoints); } assert(calibInputFrames.size() == calibImagePoints.size()); } double totalAvgErr = 0; std::vector<cv::Mat> rvecs; std::vector<cv::Mat> tvecs; std::vector<float> reprojErrs; std::vector<std::size_t> rejectInputFrames; duration.reset(); // Refinement loop of the calibration openMVG::calibration::calibrationIterativeOptimization(imageSize, aspectRatio, cvCalibFlags, cameraMatrix, distCoeffs, rvecs, tvecs, reprojErrs, totalAvgErr, maxTotalAvgErr, minInputFrames, calibInputFrames, calibImagePoints, calibObjectPoints, calibImageScore, rejectInputFrames); OPENMVG_COUT("Calibration duration: " << openMVG::system::prettyTime(duration.elapsedMs())); openMVG::calibration::saveCameraParams(outputFilename, imageSize, boardSize, squareSize, aspectRatio, cvCalibFlags, cameraMatrix, distCoeffs, writeExtrinsics ? rvecs : std::vector<cv::Mat>(), writeExtrinsics ? tvecs : std::vector<cv::Mat>(), writeExtrinsics ? reprojErrs : std::vector<float>(), writePoints ? calibImagePoints : std::vector<std::vector<cv::Point2f> >(), totalAvgErr); openMVG::calibration::exportDebug(debugSelectedImgFolder, debugRejectedImgFolder, feed, calibInputFrames, rejectInputFrames, remainingImagesIndexes, cameraMatrix, distCoeffs, imageSize); OPENMVG_COUT("Total duration: " << openMVG::system::prettyTime(durationAlgo.elapsedMs())); return EXIT_SUCCESS; }
fix nbFramesToProcess
[sw] cameraCalibration: fix nbFramesToProcess
C++
mit
poparteu/openMVG,poparteu/openMVG,poparteu/openMVG,poparteu/openMVG
e60d9a208367b74660e28d72e845e01fd16b8d66
src/DSVSCA.cpp
src/DSVSCA.cpp
#include "DSVSCA.h" int DSVSCA::process_filter_graph(process_info info) { FILE *vf; const char *vf_filename = "virtualize.aac"; AVPacket packet, packet0; AVFrame *frame = av_frame_alloc(); AVFrame *filt_frame = av_frame_alloc(); AVFrame *comb_virt_frame = av_frame_alloc(); int got_frame; std::unordered_map<Filter::Channel, Virtualizer*, std::hash<int>> c2v_; complete_sofa sofa_; AVPacket packet_out; AVPacket comb_packet_out; int got_output; Encoder *encoder = new Encoder(AV_CODEC_ID_AC3, info.format->decoder_ctx->bit_rate, AV_SAMPLE_FMT_FLTP); SJoin *sjoin = new SJoin(encoder); vf = fopen(vf_filename, "wb"); if(!vf) { std::cout << "Error opening file" << std::endl; } long total_duration = info.format->format_ctx->duration / (long)AV_TIME_BASE; uint64_t total_sample_count = 0; uint64_t samples_completed = 0; int ret = 0; AVOutputFormat *ofmt = NULL; AVFormatContext *ofmt_ctx = NULL; const char *out_filename = "output.mp4"; avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, out_filename); if(!ofmt_ctx) { av_log(NULL, AV_LOG_ERROR, "Could not create output context!\n"); exit(1); } ofmt = ofmt_ctx->oformat; for(int i = 0; i < info.format->format_ctx->nb_streams; i++) { AVStream *in_stream = info.format->format_ctx->streams[i]; AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec); if(!out_stream) { av_log(NULL, AV_LOG_ERROR, "Failed to allocate output stream!\n"); exit(1); } ret = avcodec_copy_context(out_stream->codec, in_stream->codec); out_stream->codec->codec_tag = 0; if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Failed to copy context from input to output stream codec context\n"); exit(1); } if(ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER; } av_dump_format(ofmt_ctx, 0, out_filename, 1); if(!(ofmt->flags & AVFMT_NOFILE)) { ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Unable to open output file\n"); exit(1); } } ret = avformat_write_header(ofmt_ctx, NULL); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Error opening file to write header\n"); exit(1); } /* Read all of the packets */ packet0.data = NULL; packet.data = NULL; while(1) { if(!packet0.data) { ret = av_read_frame(info.format->format_ctx, &packet); if(ret < 0) break; packet0 = packet; } //in_stream = ifmt_ctx->streams[packet.stream_index]; //out_stream = ofmt_ctx->streams[packet.stream_index]; if(packet.stream_index == 0) { ret = av_interleaved_write_frame(ofmt_ctx, &packet0); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Error muxing video packet\n"); } } if(packet.stream_index == info.format->audio_stream_index) { got_frame = 0; ret = avcodec_decode_audio4(info.format->decoder_ctx, frame, &got_frame, &packet); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Error decoding audio\n"); continue; } packet.size -= ret; packet.data += ret; if(got_frame) { /* push audio from decoded frame through filter graph */ if(av_buffersrc_add_frame_flags(info.filter->abuffer_ctx, frame, 0) < 0) { av_log(NULL, AV_LOG_ERROR, "Error feeding into filter graph\n"); break; } int i ; int frame_sample_count = 0; while(ret >= 0) { // This is where you will work with each processed frame. i = 0; for (auto it = info.filter->abuffersink_ctx_map.begin(); it != info.filter->abuffersink_ctx_map.end(); it++) { ret = av_buffersink_get_frame(it->second, filt_frame); if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break; int sample_count = filt_frame->nb_samples; int sample_rate = filt_frame->sample_rate; if (total_sample_count == 0) total_sample_count = total_duration * sample_rate; if (frame_sample_count == 0) frame_sample_count = sample_count; if (c2v_.count(it->first) == 0) { float x_y_z[3]; if (info.coords.count(it->first) == 0) Filter::get_coords(it->first, &x_y_z[0], &x_y_z[1], &x_y_z[2]); else { x_y_z[0] = info.coords.at(it->first).x; x_y_z[1] = info.coords.at(it->first).y; x_y_z[2] = info.coords.at(it->first).z; if (info.coord_type == Filter::Spherical) mysofa_s2c(x_y_z); } if (sofa_.hrtf == NULL) { Virtualizer * virt = new Virtualizer(info.sofa_file_name.c_str(), sample_rate, x_y_z[0], x_y_z[1], x_y_z[2], info.block_size); c2v_.insert(std::make_pair(it->first, virt)); sofa_ = virt->get_hrtf(); } else { Virtualizer * virt = new Virtualizer(sofa_, sample_rate, x_y_z[0], x_y_z[1], x_y_z[2], info.block_size); c2v_.insert(std::make_pair(it->first, virt)); } } float * samples = Virtualizer::get_float_samples(filt_frame->extended_data[0], info.format->decoder_ctx->sample_fmt, sample_count); float ** float_results = c2v_[it->first]->process(samples, sample_count); uint8_t * result_l = Virtualizer::get_short_samples(float_results[0], info.format->decoder_ctx->sample_fmt, sample_count); uint8_t * result_r = Virtualizer::get_short_samples(float_results[1], info.format->decoder_ctx->sample_fmt, sample_count); delete[] float_results[0]; delete[] float_results[1]; delete[] float_results; delete[] samples; AVFrame *virt_frame = encoder->new_frame(encoder->codec_ctx, result_r, result_l); virt_frame->format = AV_SAMPLE_FMT_FLTP; virt_frame->sample_rate = 48000; virt_frame->channel_layout = 3; //av_log(NULL, AV_LOG_INFO, "%d ", i); if(av_buffersrc_add_frame_flags(sjoin->abuffers_ctx[i], virt_frame, 0) < 0) av_log(NULL, AV_LOG_ERROR, "Error feeding into filtergraph\n"); av_frame_unref(filt_frame); i++; } if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break; ret = av_buffersink_get_frame(sjoin->abuffersink_ctx, comb_virt_frame); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "No virtualization frame %d\n", ret); continue; } av_init_packet(&comb_packet_out); comb_packet_out.data = NULL; comb_packet_out.size = 0; ret = avcodec_encode_audio2(encoder->codec_ctx, &comb_packet_out, comb_virt_frame, &got_output); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Error encoding comb frame %d\n", ret); exit(1); } uint8_t* data = comb_packet_out.data; av_copy_packet(&comb_packet_out, &packet0); comb_packet_out.data = data; ret = av_interleaved_write_frame(ofmt_ctx, &comb_packet_out); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Error muxing video packet\n"); } av_free_packet(&comb_packet_out); av_frame_unref(comb_virt_frame); } samples_completed += frame_sample_count; } if(packet.size <= 0) av_free_packet(&packet0); } else { av_free_packet(&packet0); } if (total_sample_count != 0) { int completion = (100 * samples_completed) / total_sample_count; if (completion > 100) completion = 100; info.progress->store(completion); } } for (auto it = c2v_.begin(); it != c2v_.end(); it++) delete it->second; av_write_trailer(ofmt_ctx); avformat_close_input(&info.format->format_ctx); if(ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE)) avio_close(ofmt_ctx->pb); avformat_free_context(ofmt_ctx); fclose(vf); av_frame_free(&frame); av_frame_free(&filt_frame); av_frame_free(&comb_virt_frame); if(ret < 0 && ret != AVERROR_EOF) { av_log(NULL, AV_LOG_ERROR, "Error occured while closing out: %d\n", ret); return ret; } }
#include "DSVSCA.h" int DSVSCA::process_filter_graph(process_info info) { AVPacket packet, packet0; AVFrame *frame = av_frame_alloc(); AVFrame *filt_frame = av_frame_alloc(); AVFrame *comb_virt_frame = av_frame_alloc(); int got_frame; std::unordered_map<Filter::Channel, Virtualizer*, std::hash<int>> c2v_; complete_sofa sofa_; AVPacket packet_out; AVPacket comb_packet_out; int got_output; Encoder *encoder = new Encoder(AV_CODEC_ID_AC3, info.format->decoder_ctx->bit_rate, AV_SAMPLE_FMT_FLTP); SJoin *sjoin = new SJoin(encoder); long total_duration = info.format->format_ctx->duration / (long)AV_TIME_BASE; uint64_t total_sample_count = 0; uint64_t samples_completed = 0; int ret = 0; AVOutputFormat *ofmt = NULL; AVFormatContext *ofmt_ctx = NULL; size_t index_of_ext = info.video_file_name.find_last_of('.'); std::string out_filename_str; if (index_of_ext == std::string::npos) out_filename_str = info.video_file_name + "-virtualized"; else out_filename_str = info.video_file_name.substr(0, index_of_ext) + "-virtualized" + info.video_file_name.substr(index_of_ext); const char *out_filename = out_filename_str.c_str(); avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, out_filename); if(!ofmt_ctx) { av_log(NULL, AV_LOG_ERROR, "Could not create output context!\n"); exit(1); } ofmt = ofmt_ctx->oformat; for(int i = 0; i < info.format->format_ctx->nb_streams; i++) { AVStream *in_stream = info.format->format_ctx->streams[i]; AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec); if(!out_stream) { av_log(NULL, AV_LOG_ERROR, "Failed to allocate output stream!\n"); exit(1); } ret = avcodec_copy_context(out_stream->codec, in_stream->codec); out_stream->codec->codec_tag = 0; if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Failed to copy context from input to output stream codec context\n"); exit(1); } if(ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER; } av_dump_format(ofmt_ctx, 0, out_filename, 1); if(!(ofmt->flags & AVFMT_NOFILE)) { ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Unable to open output file\n"); exit(1); } } ret = avformat_write_header(ofmt_ctx, NULL); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Error opening file to write header\n"); exit(1); } /* Read all of the packets */ packet0.data = NULL; packet.data = NULL; while(1) { if(!packet0.data) { ret = av_read_frame(info.format->format_ctx, &packet); if(ret < 0) break; packet0 = packet; } //in_stream = ifmt_ctx->streams[packet.stream_index]; //out_stream = ofmt_ctx->streams[packet.stream_index]; if(packet.stream_index == 0) { ret = av_interleaved_write_frame(ofmt_ctx, &packet0); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Error muxing video packet\n"); } } if(packet.stream_index == info.format->audio_stream_index) { got_frame = 0; ret = avcodec_decode_audio4(info.format->decoder_ctx, frame, &got_frame, &packet); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Error decoding audio\n"); continue; } packet.size -= ret; packet.data += ret; if(got_frame) { /* push audio from decoded frame through filter graph */ if(av_buffersrc_add_frame_flags(info.filter->abuffer_ctx, frame, 0) < 0) { av_log(NULL, AV_LOG_ERROR, "Error feeding into filter graph\n"); break; } int i ; int frame_sample_count = 0; while(ret >= 0) { // This is where you will work with each processed frame. i = 0; for (auto it = info.filter->abuffersink_ctx_map.begin(); it != info.filter->abuffersink_ctx_map.end(); it++) { ret = av_buffersink_get_frame(it->second, filt_frame); if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break; int sample_count = filt_frame->nb_samples; int sample_rate = filt_frame->sample_rate; if (total_sample_count == 0) total_sample_count = total_duration * sample_rate; if (frame_sample_count == 0) frame_sample_count = sample_count; if (c2v_.count(it->first) == 0) { float x_y_z[3]; if (info.coords.count(it->first) == 0) Filter::get_coords(it->first, &x_y_z[0], &x_y_z[1], &x_y_z[2]); else { x_y_z[0] = info.coords.at(it->first).x; x_y_z[1] = info.coords.at(it->first).y; x_y_z[2] = info.coords.at(it->first).z; if (info.coord_type == Filter::Spherical) mysofa_s2c(x_y_z); } if (sofa_.hrtf == NULL) { Virtualizer * virt = new Virtualizer(info.sofa_file_name.c_str(), sample_rate, x_y_z[0], x_y_z[1], x_y_z[2], info.block_size); c2v_.insert(std::make_pair(it->first, virt)); sofa_ = virt->get_hrtf(); } else { Virtualizer * virt = new Virtualizer(sofa_, sample_rate, x_y_z[0], x_y_z[1], x_y_z[2], info.block_size); c2v_.insert(std::make_pair(it->first, virt)); } } float * samples = Virtualizer::get_float_samples(filt_frame->extended_data[0], info.format->decoder_ctx->sample_fmt, sample_count); float ** float_results = c2v_[it->first]->process(samples, sample_count); uint8_t * result_l = Virtualizer::get_short_samples(float_results[0], info.format->decoder_ctx->sample_fmt, sample_count); uint8_t * result_r = Virtualizer::get_short_samples(float_results[1], info.format->decoder_ctx->sample_fmt, sample_count); delete[] float_results[0]; delete[] float_results[1]; delete[] float_results; delete[] samples; AVFrame *virt_frame = encoder->new_frame(encoder->codec_ctx, result_r, result_l); virt_frame->format = AV_SAMPLE_FMT_FLTP; virt_frame->sample_rate = 48000; virt_frame->channel_layout = 3; //av_log(NULL, AV_LOG_INFO, "%d ", i); if(av_buffersrc_add_frame_flags(sjoin->abuffers_ctx[i], virt_frame, 0) < 0) av_log(NULL, AV_LOG_ERROR, "Error feeding into filtergraph\n"); av_frame_unref(filt_frame); i++; } if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break; ret = av_buffersink_get_frame(sjoin->abuffersink_ctx, comb_virt_frame); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "No virtualization frame %d\n", ret); continue; } av_init_packet(&comb_packet_out); comb_packet_out.data = NULL; comb_packet_out.size = 0; ret = avcodec_encode_audio2(encoder->codec_ctx, &comb_packet_out, comb_virt_frame, &got_output); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Error encoding comb frame %d\n", ret); exit(1); } uint8_t* data = comb_packet_out.data; av_copy_packet(&comb_packet_out, &packet0); comb_packet_out.data = data; ret = av_interleaved_write_frame(ofmt_ctx, &comb_packet_out); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Error muxing video packet\n"); } av_free_packet(&comb_packet_out); av_frame_unref(comb_virt_frame); } samples_completed += frame_sample_count; } if(packet.size <= 0) av_free_packet(&packet0); } else { av_free_packet(&packet0); } if (total_sample_count != 0) { int completion = (100 * samples_completed) / total_sample_count; if (completion > 100) completion = 100; info.progress->store(completion); } } for (auto it = c2v_.begin(); it != c2v_.end(); it++) delete it->second; av_write_trailer(ofmt_ctx); avformat_close_input(&info.format->format_ctx); if(ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE)) avio_close(ofmt_ctx->pb); avformat_free_context(ofmt_ctx); av_frame_free(&frame); av_frame_free(&filt_frame); av_frame_free(&comb_virt_frame); if(ret < 0 && ret != AVERROR_EOF) { av_log(NULL, AV_LOG_ERROR, "Error occured while closing out: %d\n", ret); return ret; } }
Set output file name to be [file-name]-virtualized.[extension].
Set output file name to be [file-name]-virtualized.[extension].
C++
mit
DSVSCA/DSVSCA,DSVSCA/DSVSCA
1cd626dc9bf15368adc063ec0f7823d2cb80fd92
include/taussig/interop/materialize.h++
include/taussig/interop/materialize.h++
// Taussig // // Written in 2013 by Martinho Fernandes <[email protected]> // // To the extent possible under law, the author(s) have dedicated all copyright and related // and neighboring rights to this software to the public domain worldwide. This software is // distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // Materialization of sequences into containers #ifndef TAUSSIG_INTEROP_MATERIALIZE_HPP #define TAUSSIG_INTEROP_MATERIALIZE_HPP #include <taussig/traits/is_sequence.h++> #include <taussig/traits/value_type.h++> #include <taussig/interop/begin_end.h++> #include <wheels/meta/enable_if.h++> #include <wheels/meta/is_deduced.h++> #include <utility> // forward namespace seq { //! {function} //! *Requires*: `S` is a sequence [soft]; //! `C` is a container. //! *Returns*: a `C` container with all elements from the sequence. template <typename C, typename S, wheels::meta::EnableIf<is_sequence<S>>...> C materialize(S&& s) { return C(seq::begin(s), seq::end(s)); } //! {function} //! *Requires*: `S` is a sequence [soft]; //! `C<seq::ValueType<S>>` is a container. //! *Returns*: a `C` container with all elements from the sequence. template <template <typename...> class C, typename S, wheels::meta::EnableIf<is_sequence<S>>...> C<ValueType<S>> materialize(S&& s) { return materialize<C<ValueType<S>>>(std::forward<S>(s)); } namespace detail { template <typename S> struct materializer { template <typename C> // TODO require container operator C() const { return materialize<C>(std::forward<S>(sequence)); } S& sequence; }; } // namespace detail //! {function} //! *Requires*: `S` is a sequence [soft]. //! *Returns*: a proxy implicitly convertible to container types; //! converting the proxy results in a container with all elements from the sequence. template <typename C = wheels::meta::deduced, typename S, wheels::meta::EnableIf<wheels::meta::is_deduced<C>>..., wheels::meta::EnableIf<is_sequence<S>>...> detail::materializer<S> materialize(S&& s) { return { s }; } } // namespace seq #endif // TAUSSIG_INTEROP_MATERIALIZE_HPP
// Taussig // // Written in 2013 by Martinho Fernandes <[email protected]> // // To the extent possible under law, the author(s) have dedicated all copyright and related // and neighboring rights to this software to the public domain worldwide. This software is // distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // Materialization of sequences into containers #ifndef TAUSSIG_INTEROP_MATERIALIZE_HPP #define TAUSSIG_INTEROP_MATERIALIZE_HPP #include <taussig/traits/is_sequence.h++> #include <taussig/traits/value_type.h++> #include <taussig/interop/begin_end.h++> #include <wheels/meta/enable_if.h++> #include <wheels/meta/is_deduced.h++> #include <utility> // forward namespace seq { //! {function} //! *Requires*: `S` is a sequence [soft]; //! `C` is a container. //! *Returns*: a `C` container with all elements from the sequence. template <typename C, typename S, wheels::meta::EnableIf<is_sequence<S>>...> C materialize(S&& s) { // asymmetry in forward because end doesn't use the argument, and only begin owns it return C(seq::begin(std::forward<S>(s)), seq::end(s)); } //! {function} //! *Requires*: `S` is a sequence [soft]; //! `C<seq::ValueType<S>>` is a container. //! *Returns*: a `C` container with all elements from the sequence. template <template <typename...> class C, typename S, wheels::meta::EnableIf<is_sequence<S>>...> C<ValueType<S>> materialize(S&& s) { return materialize<C<ValueType<S>>>(std::forward<S>(s)); } namespace detail { template <typename S> struct materializer { template <typename C> // TODO require container operator C() const { return materialize<C>(std::forward<S>(sequence)); } S& sequence; }; } // namespace detail //! {function} //! *Requires*: `S` is a sequence [soft]. //! *Returns*: a proxy implicitly convertible to container types; //! converting the proxy results in a container with all elements from the sequence. template <typename C = wheels::meta::deduced, typename S, wheels::meta::EnableIf<wheels::meta::is_deduced<C>>..., wheels::meta::EnableIf<is_sequence<S>>...> detail::materializer<S> materialize(S&& s) { return { s }; // no forwarding because a reference is stored directly } } // namespace seq #endif // TAUSSIG_INTEROP_MATERIALIZE_HPP
Add missing forwarding in materialize + comments
Add missing forwarding in materialize + comments
C++
cc0-1.0
rmartinho/taussig,rmartinho/taussig
53f59cd4d646545d3118a9834f7be758c1a613ee
engines/ep/src/sizes.cc
engines/ep/src/sizes.cc
/* * Copyright 2010 NorthScale, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include <stdio.h> #include <algorithm> #include <limits> #include "atomic_unordered_map.h" #include "checkpoint.h" #include "common.h" #include "dcp/stream.h" #include <platform/histogram.h> #include "item.h" #include "stored-value.h" #include "vbucket.h" static void display(const char *name, size_t size) { std::cout << name << "\t" << size << std::endl; } template <typename T> struct histo_for_inner { void operator()(const std::unique_ptr<HistogramBin<T>>& bin) { std::cout << " " << bin->start() << " - "; if (bin->end() == std::numeric_limits<T>::max()) { std::cout << "inf"; } else { std::cout << bin->end(); } std::cout << std::endl; } }; template <> struct histo_for_inner<hrtime_t> { void operator()(const std::unique_ptr<HistogramBin<hrtime_t>>& bin) { const std::string endtext(bin->end() == std::numeric_limits<hrtime_t>::max() ? "inf" : hrtime2text(bin->end())); std::cout << " " << hrtime2text(bin->start()) << " - " << endtext << std::endl; } }; template <typename T> static void display(const char *name, const Histogram<T> &histo) { std::cout << name << std::endl; std::for_each(histo.begin(), histo.end(), histo_for_inner<T>()); } int main(int, char **) { std::string s; display("GIGANTOR", GIGANTOR); display("Stored Value", sizeof(StoredValue)); display("Blob", sizeof(Blob)); display("value_t", sizeof(value_t)); display("HashTable", sizeof(HashTable)); display("Item", sizeof(Item)); display("VBucket", sizeof(VBucket)); display("VBucketMap", sizeof(VBucketMap)); display("Stats", sizeof(EPStats)); display("CheckpointManager", sizeof(CheckpointManager)); display("Checkpoint\t", sizeof(Checkpoint)); display("CheckpointConfig", sizeof(CheckpointConfig)); display("Histogram<whatever>", sizeof(Histogram<size_t>)); display("HistogramBin<size_t>", sizeof(HistogramBin<size_t>)); display("HistogramBin<hrtime_t>", sizeof(HistogramBin<hrtime_t>)); display("HistogramBin<int>", sizeof(HistogramBin<int>)); display("AtomicUnorderedMap<uint32_t, SingleThreadedRCPtr<Stream>>", sizeof(AtomicUnorderedMap<uint32_t, SingleThreadedRCPtr<Stream>>)); std::cout << std::endl << "Histogram Ranges" << std::endl << std::endl; EPStats stats; HashTableDepthStatVisitor dv; display("Default Histo", stats.diskInsertHisto); display("Commit Histo", stats.diskCommitHisto); display("Hash table depth histo", dv.depthHisto); return 0; }
/* * Copyright 2010 NorthScale, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include <stdio.h> #include <algorithm> #include <limits> #include "atomic_unordered_map.h" #include "checkpoint.h" #include "common.h" #include "dcp/stream.h" #include <platform/histogram.h> #include "item.h" #include "stored-value.h" #include "vbucket.h" static void display(const char *name, size_t size) { std::cout << name << "\t" << size << std::endl; } template <typename T> struct histo_for_inner { void operator()(const std::unique_ptr<HistogramBin<T>>& bin) { std::cout << " " << bin->start() << " - "; if (bin->end() == std::numeric_limits<T>::max()) { std::cout << "inf"; } else { std::cout << bin->end(); } std::cout << std::endl; } }; template <> struct histo_for_inner<hrtime_t> { void operator()(const std::unique_ptr<HistogramBin<hrtime_t>>& bin) { const std::string endtext(bin->end() == std::numeric_limits<hrtime_t>::max() ? "inf" : hrtime2text(bin->end())); std::cout << " " << hrtime2text(bin->start()) << " - " << endtext << std::endl; } }; template <typename T> static void display(const char *name, const Histogram<T> &histo) { std::cout << name << std::endl; std::for_each(histo.begin(), histo.end(), histo_for_inner<T>()); } int main(int, char **) { std::string s; display("GIGANTOR", GIGANTOR); display("Stored Value", sizeof(StoredValue)); display("Ordered Stored Value", sizeof(OrderedStoredValue)); display("Blob", sizeof(Blob)); display("value_t", sizeof(value_t)); display("HashTable", sizeof(HashTable)); display("Item", sizeof(Item)); display("VBucket", sizeof(VBucket)); display("VBucketMap", sizeof(VBucketMap)); display("Stats", sizeof(EPStats)); display("CheckpointManager", sizeof(CheckpointManager)); display("Checkpoint\t", sizeof(Checkpoint)); display("CheckpointConfig", sizeof(CheckpointConfig)); display("Histogram<whatever>", sizeof(Histogram<size_t>)); display("HistogramBin<size_t>", sizeof(HistogramBin<size_t>)); display("HistogramBin<hrtime_t>", sizeof(HistogramBin<hrtime_t>)); display("HistogramBin<int>", sizeof(HistogramBin<int>)); display("AtomicUnorderedMap<uint32_t, SingleThreadedRCPtr<Stream>>", sizeof(AtomicUnorderedMap<uint32_t, SingleThreadedRCPtr<Stream>>)); std::cout << std::endl << "Histogram Ranges" << std::endl << std::endl; EPStats stats; HashTableDepthStatVisitor dv; display("Default Histo", stats.diskInsertHisto); display("Commit Histo", stats.diskCommitHisto); display("Hash table depth histo", dv.depthHisto); return 0; }
Add OrderedStoredValue to engine sizes
Add OrderedStoredValue to engine sizes Adding this would allow us to get the size immediately for debugging purposes Change-Id: If554883cc81b13c854092f187b1431c5546c3200 Reviewed-on: http://review.couchbase.org/80210 Tested-by: Build Bot <[email protected]> Reviewed-by: Manu Dhundi <[email protected]>
C++
bsd-3-clause
daverigby/kv_engine,daverigby/kv_engine,daverigby/kv_engine,daverigby/kv_engine
7da0880b3f1a6d1fec2f8299f159406939b4567f
silicium/html/tree.hpp
silicium/html/tree.hpp
#ifndef SILICIUM_HTML_TREE_HPP #define SILICIUM_HTML_TREE_HPP #include <silicium/html/generator.hpp> #include <silicium/sink/iterator_sink.hpp> #include <silicium/trait.hpp> #include <silicium/identity.hpp> #define SILICIUM_HAS_HTML_TREE \ (SILICIUM_COMPILER_HAS_VARIADIC_TEMPLATES && !SILICIUM_GCC46) namespace Si { namespace html { typedef Sink<char, success>::interface code_sink; #if SILICIUM_HAS_HTML_TREE template <std::size_t Length> struct exact_length : std::integral_constant<std::size_t, Length> { }; template <std::size_t Length> struct min_length : std::integral_constant<std::size_t, Length> { }; namespace detail { template <class FirstLength, class SecondLength> struct concatenate; template <std::size_t FirstLength, std::size_t SecondLength> struct concatenate<exact_length<FirstLength>, exact_length<SecondLength>> { typedef exact_length<FirstLength + SecondLength> type; }; template <std::size_t FirstLength, std::size_t SecondLength> struct concatenate<min_length<FirstLength>, exact_length<SecondLength>> { typedef min_length<FirstLength + SecondLength> type; }; template <std::size_t FirstLength, std::size_t SecondLength> struct concatenate<exact_length<FirstLength>, min_length<SecondLength>> { typedef min_length<FirstLength + SecondLength> type; }; template <std::size_t FirstLength, std::size_t SecondLength> struct concatenate<min_length<FirstLength>, min_length<SecondLength>> { typedef min_length<FirstLength + SecondLength> type; }; template <class ContentGenerator, class Length> struct element { typedef Length length_type; ContentGenerator generate; #if SILICIUM_VC2013 // workaround against superfluous warnings C4510 and C4610 // ("constructor cannot be generated") explicit element(ContentGenerator generate) : generate(std::move(generate)) { } #endif }; template <class Length, class ContentGenerator> auto make_element(ContentGenerator &&generate) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> element<typename std::decay<ContentGenerator>::type, Length> #endif { return element<typename std::decay<ContentGenerator>::type, Length>{ std::forward<ContentGenerator>(generate)}; } } template <class Length = min_length<0>> SILICIUM_TRAIT_WITH_TYPEDEFS(Element, typedef Length length_type; , ((generate, (1, (code_sink &)), void, const))) template <class ContentGenerator> auto dynamic(ContentGenerator &&generate) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> decltype(detail::make_element<Length>( std::forward<ContentGenerator>(generate))) #endif { return detail::make_element<min_length<0>>( std::forward<ContentGenerator>(generate)); } template <std::size_t Length, class ContentGenerator> auto fixed_length(ContentGenerator &&generate) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> decltype(detail::make_element<exact_length<Length>>( std::forward<ContentGenerator>(generate))) #endif { return detail::make_element<exact_length<Length>>( std::forward<ContentGenerator>(generate)); } template <std::size_t Length> auto raw(char const(&content)[Length]) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> detail::element<std::function<void(code_sink &)>, exact_length<Length - 1>> #endif { return fixed_length<Length - 1>( #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE std::function<void(code_sink &)> #endif ([&content](code_sink &destination) { Si::append(destination, content); })); } template <std::size_t NameLength, class Attributes, class Element, class ResultLength = typename detail::concatenate< typename std::decay<Element>::type::length_type, typename detail::concatenate< typename std::decay<Attributes>::type::length_type, exact_length<1 + (NameLength - 1) + 1 + 2 + (NameLength - 1) + 1>>::type>::type> auto tag(char const(&name)[NameLength], Attributes &&attributes, Element &&content) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> detail::element<std::function<void(code_sink &)>, ResultLength> #endif { auto &generate_content = content.generate; return detail::make_element<ResultLength>( #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE std::function<void(code_sink &)> #endif ([ &name, SILICIUM_CAPTURE_EXPRESSION( generate_content, std::move(generate_content)), SILICIUM_CAPTURE_EXPRESSION( attributes, std::forward<Attributes>(attributes)) ](code_sink & destination) { html::open_attributed_element(destination, name); attributes.generate(destination); html::finish_attributes(destination); generate_content(destination); html::close_element(destination, name); })); } template <std::size_t NameLength, class Attributes, class ResultLength = typename detail::concatenate< min_length<1 + (NameLength - 1) + 2>, typename std::decay<Attributes>::type::length_type>::type> auto tag(char const(&name)[NameLength], Attributes &&attributes, empty_t) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> detail::element<std::function<void(code_sink &)>, ResultLength> #endif { return detail::make_element<ResultLength>( #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE std::function<void(code_sink &)> #endif ([ &name, SILICIUM_CAPTURE_EXPRESSION( attributes, std::forward<Attributes>(attributes)) ](code_sink & destination) { html::open_attributed_element(destination, name); attributes.generate(destination); finish_attributes_of_unpaired_tag(destination); })); } namespace detail { inline void no_attributes(code_sink &) { } } template <std::size_t NameLength, class Element> auto tag(char const(&name)[NameLength], Element &&content) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> decltype(tag(name, detail::make_element<exact_length<0>>( &detail::no_attributes), std::forward<Element>(content))) #endif { return tag(name, detail::make_element<exact_length<0>>( &detail::no_attributes), std::forward<Element>(content)); } namespace detail { static BOOST_CONSTEXPR_OR_CONST std::size_t space = 1; static BOOST_CONSTEXPR_OR_CONST std::size_t assign = 1; static BOOST_CONSTEXPR_OR_CONST std::size_t quote = 1; } template <std::size_t KeyLength, std::size_t ValueLength, std::size_t ResultLength = detail::space + (KeyLength - 1) + detail::assign + detail::quote + (ValueLength - 1) + detail::quote> auto attribute(char const(&key)[KeyLength], char const(&value)[ValueLength]) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> detail::element<std::function<void(code_sink &)>, min_length<ResultLength>> #endif { return detail::make_element<min_length<ResultLength>>( #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE std::function<void(code_sink &)> #endif ([&key, &value](code_sink &destination) { add_attribute(destination, key, value); })); } template <std::size_t KeyLength, std::size_t ResultLength = detail::space + (KeyLength - 1) + detail::assign + detail::quote + detail::quote> auto attribute(char const(&key)[KeyLength], std::string value) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> detail::element<std::function<void(code_sink &)>, min_length<ResultLength>> #endif { return detail::make_element<min_length<ResultLength>>( #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE std::function<void(code_sink &)> #endif ([&key, SILICIUM_CAPTURE_EXPRESSION(value, std::move(value)) ]( code_sink & destination) { add_attribute(destination, key, value); })); } template <std::size_t KeyLength, std::size_t ResultLength = detail::space + (KeyLength - 1)> auto attribute(char const(&key)[KeyLength]) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> detail::element<std::function<void(code_sink &)>, min_length<ResultLength>> #endif { return detail::make_element<min_length<ResultLength>>( #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE std::function<void(code_sink &)> #endif ([&key](code_sink &destination) { add_attribute(destination, key); })); } template <std::size_t Length> auto text(char const(&content)[Length]) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> detail::element<std::function<void(code_sink &)>, min_length<Length - 1>> #endif { return detail::make_element<min_length<Length - 1>>( #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE std::function<void(code_sink &)> #endif ([&content](code_sink &destination) { html::write_string(destination, content); })); } inline auto text(std::string content) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> detail::element<std::function<void(code_sink &)>, min_length<0>> #endif { return detail::make_element<min_length<0>>( #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE std::function<void(code_sink &)> #endif ([SILICIUM_CAPTURE_EXPRESSION(content, std::move(content))]( code_sink & destination) { html::write_string(destination, content); })); } namespace detail { inline void no_content(code_sink &) { } } inline auto sequence() #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> decltype( detail::make_element<exact_length<0>>(&detail::no_content)) #endif { return detail::make_element<exact_length<0>>(&detail::no_content); } template <class Head, class... Tail> auto sequence(Head &&head, Tail &&... tail) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> detail::element< std::function<void(code_sink &)>, typename detail::concatenate< typename std::decay<Head>::type::length_type, typename identity<decltype(sequence(std::forward<Tail>( tail)...))>::type::length_type>::type> #endif { auto tail_elements = sequence(std::forward<Tail>(tail)...); auto &generate_head = head.generate; auto &generate_tail_elements = tail_elements.generate; return detail::make_element<typename detail::concatenate< typename std::decay<Head>::type::length_type, typename decltype(tail_elements)::length_type>::type>( #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE std::function<void(code_sink &)> #endif ([ SILICIUM_CAPTURE_EXPRESSION( generate_head, std::move(generate_head)), SILICIUM_CAPTURE_EXPRESSION( generate_tail_elements, std::move(generate_tail_elements)) ](code_sink & destination) { generate_head(destination); generate_tail_elements(destination); })); } namespace detail { template <class A, class B, class C, class D> auto operator+(element<A, B> &&left, element<C, D> &&right) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> decltype(sequence(std::move(left), std::move(right))) #endif { return sequence(std::move(left), std::move(right)); } } template <class ContiguousContainer, class A, class B> ContiguousContainer generate(detail::element<A, B> const &tree) { ContiguousContainer generated; auto sink = Sink<char, success>::erase(make_container_sink(generated)); tree.generate(sink); return generated; } #endif } } #endif
#ifndef SILICIUM_HTML_TREE_HPP #define SILICIUM_HTML_TREE_HPP #include <silicium/html/generator.hpp> #include <silicium/sink/iterator_sink.hpp> #include <silicium/trait.hpp> #include <silicium/identity.hpp> #define SILICIUM_HAS_HTML_TREE \ (SILICIUM_COMPILER_HAS_VARIADIC_TEMPLATES && !SILICIUM_GCC46) namespace Si { namespace html { typedef Sink<char, success>::interface code_sink; #if SILICIUM_HAS_HTML_TREE template <std::size_t Length> struct exact_length : std::integral_constant<std::size_t, Length> { }; template <std::size_t Length> struct min_length : std::integral_constant<std::size_t, Length> { }; namespace detail { template <class FirstLength, class SecondLength> struct concatenate; template <std::size_t FirstLength, std::size_t SecondLength> struct concatenate<exact_length<FirstLength>, exact_length<SecondLength>> { typedef exact_length<FirstLength + SecondLength> type; }; template <std::size_t FirstLength, std::size_t SecondLength> struct concatenate<min_length<FirstLength>, exact_length<SecondLength>> { typedef min_length<FirstLength + SecondLength> type; }; template <std::size_t FirstLength, std::size_t SecondLength> struct concatenate<exact_length<FirstLength>, min_length<SecondLength>> { typedef min_length<FirstLength + SecondLength> type; }; template <std::size_t FirstLength, std::size_t SecondLength> struct concatenate<min_length<FirstLength>, min_length<SecondLength>> { typedef min_length<FirstLength + SecondLength> type; }; template <class ContentGenerator, class Length> struct element { typedef Length length_type; ContentGenerator generate; #if SILICIUM_VC2013 // workaround against superfluous warnings C4510 and C4610 // ("constructor cannot be generated") explicit element(ContentGenerator generate) : generate(std::move(generate)) { } #endif }; template <class Length, class ContentGenerator> auto make_element(ContentGenerator &&generate) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> element<typename std::decay<ContentGenerator>::type, Length> #endif { return element<typename std::decay<ContentGenerator>::type, Length>{ std::forward<ContentGenerator>(generate)}; } } template <class Length = min_length<0>> SILICIUM_TRAIT_WITH_TYPEDEFS(Element, typedef Length length_type; , ((generate, (1, (code_sink &)), void, const))) template <class ContentGenerator> auto dynamic(ContentGenerator &&generate) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> decltype(detail::make_element<min_length<0>>( std::forward<ContentGenerator>(generate))) #endif { return detail::make_element<min_length<0>>( std::forward<ContentGenerator>(generate)); } template <std::size_t Length, class ContentGenerator> auto fixed_length(ContentGenerator &&generate) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> decltype(detail::make_element<exact_length<Length>>( std::forward<ContentGenerator>(generate))) #endif { return detail::make_element<exact_length<Length>>( std::forward<ContentGenerator>(generate)); } template <std::size_t Length> auto raw(char const(&content)[Length]) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> detail::element<std::function<void(code_sink &)>, exact_length<Length - 1>> #endif { return fixed_length<Length - 1>( #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE std::function<void(code_sink &)> #endif ([&content](code_sink &destination) { Si::append(destination, content); })); } template <std::size_t NameLength, class Attributes, class Element, class ResultLength = typename detail::concatenate< typename std::decay<Element>::type::length_type, typename detail::concatenate< typename std::decay<Attributes>::type::length_type, exact_length<1 + (NameLength - 1) + 1 + 2 + (NameLength - 1) + 1>>::type>::type> auto tag(char const(&name)[NameLength], Attributes &&attributes, Element &&content) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> detail::element<std::function<void(code_sink &)>, ResultLength> #endif { auto &generate_content = content.generate; return detail::make_element<ResultLength>( #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE std::function<void(code_sink &)> #endif ([ &name, SILICIUM_CAPTURE_EXPRESSION( generate_content, std::move(generate_content)), SILICIUM_CAPTURE_EXPRESSION( attributes, std::forward<Attributes>(attributes)) ](code_sink & destination) { html::open_attributed_element(destination, name); attributes.generate(destination); html::finish_attributes(destination); generate_content(destination); html::close_element(destination, name); })); } template <std::size_t NameLength, class Attributes, class ResultLength = typename detail::concatenate< min_length<1 + (NameLength - 1) + 2>, typename std::decay<Attributes>::type::length_type>::type> auto tag(char const(&name)[NameLength], Attributes &&attributes, empty_t) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> detail::element<std::function<void(code_sink &)>, ResultLength> #endif { return detail::make_element<ResultLength>( #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE std::function<void(code_sink &)> #endif ([ &name, SILICIUM_CAPTURE_EXPRESSION( attributes, std::forward<Attributes>(attributes)) ](code_sink & destination) { html::open_attributed_element(destination, name); attributes.generate(destination); finish_attributes_of_unpaired_tag(destination); })); } namespace detail { inline void no_attributes(code_sink &) { } } template <std::size_t NameLength, class Element> auto tag(char const(&name)[NameLength], Element &&content) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> decltype(tag(name, detail::make_element<exact_length<0>>( &detail::no_attributes), std::forward<Element>(content))) #endif { return tag(name, detail::make_element<exact_length<0>>( &detail::no_attributes), std::forward<Element>(content)); } namespace detail { static BOOST_CONSTEXPR_OR_CONST std::size_t space = 1; static BOOST_CONSTEXPR_OR_CONST std::size_t assign = 1; static BOOST_CONSTEXPR_OR_CONST std::size_t quote = 1; } template <std::size_t KeyLength, std::size_t ValueLength, std::size_t ResultLength = detail::space + (KeyLength - 1) + detail::assign + detail::quote + (ValueLength - 1) + detail::quote> auto attribute(char const(&key)[KeyLength], char const(&value)[ValueLength]) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> detail::element<std::function<void(code_sink &)>, min_length<ResultLength>> #endif { return detail::make_element<min_length<ResultLength>>( #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE std::function<void(code_sink &)> #endif ([&key, &value](code_sink &destination) { add_attribute(destination, key, value); })); } template <std::size_t KeyLength, std::size_t ResultLength = detail::space + (KeyLength - 1) + detail::assign + detail::quote + detail::quote> auto attribute(char const(&key)[KeyLength], std::string value) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> detail::element<std::function<void(code_sink &)>, min_length<ResultLength>> #endif { return detail::make_element<min_length<ResultLength>>( #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE std::function<void(code_sink &)> #endif ([&key, SILICIUM_CAPTURE_EXPRESSION(value, std::move(value)) ]( code_sink & destination) { add_attribute(destination, key, value); })); } template <std::size_t KeyLength, std::size_t ResultLength = detail::space + (KeyLength - 1)> auto attribute(char const(&key)[KeyLength]) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> detail::element<std::function<void(code_sink &)>, min_length<ResultLength>> #endif { return detail::make_element<min_length<ResultLength>>( #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE std::function<void(code_sink &)> #endif ([&key](code_sink &destination) { add_attribute(destination, key); })); } template <std::size_t Length> auto text(char const(&content)[Length]) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> detail::element<std::function<void(code_sink &)>, min_length<Length - 1>> #endif { return detail::make_element<min_length<Length - 1>>( #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE std::function<void(code_sink &)> #endif ([&content](code_sink &destination) { html::write_string(destination, content); })); } inline auto text(std::string content) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> detail::element<std::function<void(code_sink &)>, min_length<0>> #endif { return detail::make_element<min_length<0>>( #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE std::function<void(code_sink &)> #endif ([SILICIUM_CAPTURE_EXPRESSION(content, std::move(content))]( code_sink & destination) { html::write_string(destination, content); })); } namespace detail { inline void no_content(code_sink &) { } } inline auto sequence() #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> decltype( detail::make_element<exact_length<0>>(&detail::no_content)) #endif { return detail::make_element<exact_length<0>>(&detail::no_content); } template <class Head, class... Tail> auto sequence(Head &&head, Tail &&... tail) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> detail::element< std::function<void(code_sink &)>, typename detail::concatenate< typename std::decay<Head>::type::length_type, typename identity<decltype(sequence(std::forward<Tail>( tail)...))>::type::length_type>::type> #endif { auto tail_elements = sequence(std::forward<Tail>(tail)...); auto &generate_head = head.generate; auto &generate_tail_elements = tail_elements.generate; return detail::make_element<typename detail::concatenate< typename std::decay<Head>::type::length_type, typename decltype(tail_elements)::length_type>::type>( #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE std::function<void(code_sink &)> #endif ([ SILICIUM_CAPTURE_EXPRESSION( generate_head, std::move(generate_head)), SILICIUM_CAPTURE_EXPRESSION( generate_tail_elements, std::move(generate_tail_elements)) ](code_sink & destination) { generate_head(destination); generate_tail_elements(destination); })); } namespace detail { template <class A, class B, class C, class D> auto operator+(element<A, B> &&left, element<C, D> &&right) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> decltype(sequence(std::move(left), std::move(right))) #endif { return sequence(std::move(left), std::move(right)); } } template <class ContiguousContainer, class A, class B> ContiguousContainer generate(detail::element<A, B> const &tree) { ContiguousContainer generated; auto sink = Sink<char, success>::erase(make_container_sink(generated)); tree.generate(sink); return generated; } #endif } } #endif
fix for GCC <= 4.7
fix for GCC <= 4.7
C++
mit
TyRoXx/silicium,TyRoXx/silicium
d5af106840041cc78311adc11ea4dcdd74f3e35f
common/include/pcl/common/impl/intensity.hpp
common/include/pcl/common/impl/intensity.hpp
/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2012, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #ifndef PCL_COMMON_INTENSITY_FIELD_ACCESSOR_IMPL_HPP #define PCL_COMMON_INTENSITY_FIELD_ACCESSOR_IMPL_HPP #include <pcl/point_types.h> namespace pcl { namespace common { template<> struct IntensityFieldAccessor<pcl::PointNormal> { inline float operator () (const pcl::PointNormal &p) const { return p.curvature; } inline void get (const pcl::PointNormal &p, float &intensity) const { intensity = p.curvature; } inline void set (pcl::PointNormal &p, float intensity) const { p.curvature = intensity; } inline void demean (pcl::PointNormal& p, float value) const { p.curvature -= value; } inline void add (pcl::PointNormal& p, float value) const { p.curvature += value; } }; template<> struct IntensityFieldAccessor<pcl::PointXYZRGB> { inline float operator () (const pcl::PointXYZRGB &p) const { return (static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f); } inline void get (const pcl::PointXYZRGB &p, float& intensity) const { intensity = static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f; } inline void set (pcl::PointXYZRGB &p, float intensity) const { p.r = static_cast<uint8_t> (1000 * intensity / 299); p.g = static_cast<uint8_t> (1000 * intensity / 587); p.b = static_cast<uint8_t> (1000 * intensity / 114); } inline void demean (pcl::PointXYZRGB& p, float value) const { float intensity = this->operator () (p); intensity -= value; set (p, intensity); } inline void add (pcl::PointXYZRGB& p, float value) const { float intensity = this->operator () (p); intensity += value; set (p, intensity); } }; template<> struct IntensityFieldAccessor<pcl::PointXYZRGBA> { inline float operator () (const pcl::PointXYZRGBA &p) const { return (static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f); } inline void get (const pcl::PointXYZRGBA &p, float& intensity) const { intensity = static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f; } inline void set (pcl::PointXYZRGBA &p, float intensity) const { p.r = static_cast<uint8_t> (1000 * intensity / 299); p.g = static_cast<uint8_t> (1000 * intensity / 587); p.b = static_cast<uint8_t> (1000 * intensity / 114); } inline void demean (pcl::PointXYZRGBA& p, float value) const { float intensity = this->operator () (p); intensity -= value; set (p, intensity); } inline void add (pcl::PointXYZRGBA& p, float value) const { float intensity = this->operator () (p); intensity += value; set (p, intensity); } }; } } #endif
/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2012, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #ifndef PCL_COMMON_INTENSITY_FIELD_ACCESSOR_IMPL_HPP #define PCL_COMMON_INTENSITY_FIELD_ACCESSOR_IMPL_HPP #include <pcl/point_types.h> namespace pcl { namespace common { template<> struct IntensityFieldAccessor<pcl::PointNormal> { inline float operator () (const pcl::PointNormal &p) const { return p.curvature; } inline void get (const pcl::PointNormal &p, float &intensity) const { intensity = p.curvature; } inline void set (pcl::PointNormal &p, float intensity) const { p.curvature = intensity; } inline void demean (pcl::PointNormal& p, float value) const { p.curvature -= value; } inline void add (pcl::PointNormal& p, float value) const { p.curvature += value; } }; template<> struct IntensityFieldAccessor<pcl::PointXYZRGB> { inline float operator () (const pcl::PointXYZRGB &p) const { return (static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f); } inline void get (const pcl::PointXYZRGB &p, float& intensity) const { intensity = static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f; } inline void set (pcl::PointXYZRGB &p, float intensity) const { p.r = static_cast<uint8_t> (1000 * intensity / 299); p.g = static_cast<uint8_t> (1000 * intensity / 587); p.b = static_cast<uint8_t> (1000 * intensity / 114); } inline void demean (pcl::PointXYZRGB& p, float value) const { float intensity = this->operator () (p); intensity -= value; set (p, intensity); } inline void add (pcl::PointXYZRGB& p, float value) const { float intensity = this->operator () (p); intensity += value; set (p, intensity); } }; template<> struct IntensityFieldAccessor<pcl::PointXYZRGBA> { inline float operator () (const pcl::PointXYZRGBA &p) const { return (static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f); } inline void get (const pcl::PointXYZRGBA &p, float& intensity) const { intensity = static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f; } inline void set (pcl::PointXYZRGBA &p, float intensity) const { p.r = static_cast<uint8_t> (1000 * intensity / 299); p.g = static_cast<uint8_t> (1000 * intensity / 587); p.b = static_cast<uint8_t> (1000 * intensity / 114); } inline void demean (pcl::PointXYZRGBA& p, float value) const { float intensity = this->operator () (p); intensity -= value; set (p, intensity); } inline void add (pcl::PointXYZRGBA& p, float value) const { float intensity = this->operator () (p); intensity += value; set (p, intensity); } }; template<> struct IntensityFieldAccessor<pcl::PointXYZRGBL> { inline float operator () (const pcl::PointXYZRGBL &p) const { return (static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f); } inline void get (const pcl::PointXYZRGBL &p, float& intensity) const { intensity = static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f; } inline void set (pcl::PointXYZRGBL &p, float intensity) const { p.r = static_cast<uint8_t> (1000 * intensity / 299); p.g = static_cast<uint8_t> (1000 * intensity / 587); p.b = static_cast<uint8_t> (1000 * intensity / 114); } inline void demean (pcl::PointXYZRGBL& p, float value) const { float intensity = this->operator () (p); intensity -= value; set (p, intensity); } inline void add (pcl::PointXYZRGBL& p, float value) const { float intensity = this->operator () (p); intensity += value; set (p, intensity); } }; } } #endif
Add implementation for PointXYZRGBL
Add implementation for PointXYZRGBL git-svn-id: 5398946ba177a3e438c2dae55e2cdfc2fb96c905@6483 a9d63959-f2ad-4865-b262-bf0e56cfafb6
C++
bsd-3-clause
chenxingzhe/pcl,raydtang/pcl,cascheberg/pcl,starius/pcl,shangwuhencc/pcl,v4hn/pcl,krips89/pcl_newfeatures,starius/pcl,kanster/pcl,shyamalschandra/pcl,shangwuhencc/pcl,drmateo/pcl,simonleonard/pcl,raydtang/pcl,soulsheng/pcl,KevenRing/pcl,cascheberg/pcl,zhangxaochen/pcl,fskuka/pcl,ResByte/pcl,simonleonard/pcl,fanxiaochen/mypcltest,krips89/pcl_newfeatures,Tabjones/pcl,the-glu/pcl,stefanbuettner/pcl,chatchavan/pcl,lebronzhang/pcl,MMiknis/pcl,wgapl/pcl,shivmalhotra/pcl,soulsheng/pcl,chatchavan/pcl,shangwuhencc/pcl,msalvato/pcl_kinfu_highres,KevenRing/pcl,ResByte/pcl,Tabjones/pcl,KevenRing/pcl,KevenRing/vlp,KevenRing/vlp,zavataafnan/pcl-truck,jakobwilm/pcl,mschoeler/pcl,kanster/pcl,wgapl/pcl,jeppewalther/kinfu_segmentation,soulsheng/pcl,cascheberg/pcl,damienjadeduff/pcl,mikhail-matrosov/pcl,sbec/pcl,shivmalhotra/pcl,3dtof/pcl,locnx1984/pcl,shangwuhencc/pcl,shyamalschandra/pcl,starius/pcl,jeppewalther/kinfu_segmentation,shyamalschandra/pcl,KevenRing/vlp,stefanbuettner/pcl,LZRS/pcl,closerbibi/pcl,LZRS/pcl,srbhprajapati/pcl,zhangxaochen/pcl,jakobwilm/pcl,Nerei/pcl_old_repo,KevenRing/pcl,stefanbuettner/pcl,the-glu/pcl,mikhail-matrosov/pcl,ipa-rmb/pcl,LZRS/pcl,stefanbuettner/pcl,locnx1984/pcl,ipa-rmb/pcl,jakobwilm/pcl,fskuka/pcl,nikste/pcl,3dtof/pcl,mikhail-matrosov/pcl,fanxiaochen/mypcltest,v4hn/pcl,nikste/pcl,RufaelDev/pcc-mp3dg,msalvato/pcl_kinfu_highres,shivmalhotra/pcl,msalvato/pcl_kinfu_highres,KevenRing/vlp,damienjadeduff/pcl,chenxingzhe/pcl,closerbibi/pcl,zhangxaochen/pcl,v4hn/pcl,Nerei/pcl_old_repo,lydhr/pcl,fskuka/pcl,3dtof/pcl,simonleonard/pcl,MMiknis/pcl,pkuhto/pcl,raydtang/pcl,pkuhto/pcl,KevenRing/pcl,DaikiMaekawa/pcl,damienjadeduff/pcl,jeppewalther/kinfu_segmentation,mikhail-matrosov/pcl,jeppewalther/kinfu_segmentation,RufaelDev/pcc-mp3dg,drmateo/pcl,lebronzhang/pcl,chatchavan/pcl,soulsheng/pcl,ResByte/pcl,srbhprajapati/pcl,3dtof/pcl,soulsheng/pcl,the-glu/pcl,closerbibi/pcl,RufaelDev/pcc-mp3dg,raydtang/pcl,lebronzhang/pcl,sbec/pcl,Tabjones/pcl,sbec/pcl,stfuchs/pcl,stefanbuettner/pcl,stfuchs/pcl,ipa-rmb/pcl,DaikiMaekawa/pcl,mschoeler/pcl,fanxiaochen/mypcltest,zhangxaochen/pcl,chenxingzhe/pcl,simonleonard/pcl,mschoeler/pcl,nikste/pcl,cascheberg/pcl,starius/pcl,lebronzhang/pcl,shyamalschandra/pcl,nikste/pcl,zavataafnan/pcl-truck,nikste/pcl,ResByte/pcl,wgapl/pcl,locnx1984/pcl,lydhr/pcl,drmateo/pcl,drmateo/pcl,Nerei/pcl_old_repo,krips89/pcl_newfeatures,msalvato/pcl_kinfu_highres,closerbibi/pcl,fanxiaochen/mypcltest,mschoeler/pcl,fanxiaochen/mypcltest,pkuhto/pcl,Tabjones/pcl,zhangxaochen/pcl,DaikiMaekawa/pcl,nh2/pcl,lydhr/pcl,LZRS/pcl,simonleonard/pcl,zavataafnan/pcl-truck,zavataafnan/pcl-truck,ipa-rmb/pcl,wgapl/pcl,shivmalhotra/pcl,raydtang/pcl,krips89/pcl_newfeatures,MMiknis/pcl,kanster/pcl,ResByte/pcl,jakobwilm/pcl,mschoeler/pcl,stfuchs/pcl,Nerei/pcl_old_repo,locnx1984/pcl,lebronzhang/pcl,DaikiMaekawa/pcl,LZRS/pcl,MMiknis/pcl,stfuchs/pcl,MMiknis/pcl,chenxingzhe/pcl,the-glu/pcl,jeppewalther/kinfu_segmentation,nh2/pcl,fskuka/pcl,drmateo/pcl,lydhr/pcl,mikhail-matrosov/pcl,chatchavan/pcl,sbec/pcl,srbhprajapati/pcl,wgapl/pcl,chenxingzhe/pcl,shyamalschandra/pcl,v4hn/pcl,RufaelDev/pcc-mp3dg,Tabjones/pcl,pkuhto/pcl,fskuka/pcl,starius/pcl,DaikiMaekawa/pcl,msalvato/pcl_kinfu_highres,sbec/pcl,locnx1984/pcl,jakobwilm/pcl,v4hn/pcl,nh2/pcl,damienjadeduff/pcl,damienjadeduff/pcl,zavataafnan/pcl-truck,shangwuhencc/pcl,cascheberg/pcl,shivmalhotra/pcl,krips89/pcl_newfeatures,KevenRing/vlp,stfuchs/pcl,lydhr/pcl,closerbibi/pcl,kanster/pcl,3dtof/pcl,nh2/pcl,RufaelDev/pcc-mp3dg,pkuhto/pcl,srbhprajapati/pcl,the-glu/pcl,ipa-rmb/pcl,kanster/pcl,srbhprajapati/pcl
0b88af49eeab703e69c85de096301afba9683339
library/common/engine.cc
library/common/engine.cc
#include "library/common/engine.h" #include "envoy/stats/histogram.h" #include "source/common/common/lock_guard.h" #include "library/common/bridge/utility.h" #include "library/common/config/internal.h" #include "library/common/data/utility.h" #include "library/common/network/android.h" #include "library/common/stats/utility.h" namespace Envoy { Engine::Engine(envoy_engine_callbacks callbacks, envoy_logger logger, envoy_event_tracker event_tracker) : callbacks_(callbacks), logger_(logger), event_tracker_(event_tracker), dispatcher_(std::make_unique<Event::ProvisionalDispatcher>()) { // Ensure static factory registration occurs on time. // TODO: ensure this is only called one time once multiple Engine objects can be allocated. // https://github.com/envoyproxy/envoy-mobile/issues/332 ExtensionRegistry::registerFactories(); // TODO(Augustyniak): Capturing an address of event_tracker_ and registering it in the API // registry may lead to crashes at Engine shutdown. To be figured out as part of // https://github.com/envoyproxy/envoy-mobile/issues/332 Envoy::Api::External::registerApi(std::string(envoy_event_tracker_api_name), &event_tracker_); } envoy_status_t Engine::run(const std::string config, const std::string log_level, const std::string admin_address_path) { // Start the Envoy on the dedicated thread. Note: due to how the assignment operator works with // std::thread, main_thread_ is the same object after this call, but its state is replaced with // that of the temporary. The temporary object's state becomes the default state, which does // nothing. main_thread_ = std::thread(&Engine::main, this, std::string(config), std::string(log_level), admin_address_path); return ENVOY_SUCCESS; } envoy_status_t Engine::main(const std::string config, const std::string log_level, const std::string admin_address_path) { // Using unique_ptr ensures main_common's lifespan is strictly scoped to this function. std::unique_ptr<EngineCommon> main_common; const std::string name = "envoy"; const std::string config_flag = "--config-yaml"; const std::string composed_config = absl::StrCat(config_header, config); const std::string log_flag = "-l"; const std::string concurrency_option = "--concurrency"; const std::string concurrency_arg = "0"; std::vector<const char*> envoy_argv = {name.c_str(), config_flag.c_str(), composed_config.c_str(), concurrency_option.c_str(), concurrency_arg.c_str(), log_flag.c_str(), log_level.c_str()}; if (!admin_address_path.empty()) { envoy_argv.push_back("--admin-address-path"); envoy_argv.push_back(admin_address_path.c_str()); } envoy_argv.push_back(nullptr); { Thread::LockGuard lock(mutex_); try { if (event_tracker_.track != nullptr) { assert_handler_registration_ = Assert::addDebugAssertionFailureRecordAction([this](const char* location) { const auto event = Bridge::Utility::makeEnvoyMap( {{"name", "assertion"}, {"location", std::string(location)}}); event_tracker_.track(event, event_tracker_.context); }); bug_handler_registration_ = Assert::addEnvoyBugFailureRecordAction([this](const char* location) { const auto event = Bridge::Utility::makeEnvoyMap( {{"name", "bug"}, {"location", std::string(location)}}); event_tracker_.track(event, event_tracker_.context); }); } // We let the thread clean up this log delegate pointer if (logger_.log) { log_delegate_ptr_ = std::make_unique<Logger::LambdaDelegate>(logger_, Logger::Registry::getSink()); } else { log_delegate_ptr_ = std::make_unique<Logger::DefaultDelegate>(log_mutex_, Logger::Registry::getSink()); } main_common = std::make_unique<EngineCommon>(envoy_argv.size() - 1, envoy_argv.data()); server_ = main_common->server(); event_dispatcher_ = &server_->dispatcher(); cv_.notifyAll(); } catch (const Envoy::NoServingException& e) { PANIC(e.what()); } catch (const Envoy::MalformedArgvException& e) { PANIC(e.what()); } catch (const Envoy::EnvoyException& e) { PANIC(e.what()); } // Note: We're waiting longer than we might otherwise to drain to the main thread's dispatcher. // This is because we're not simply waiting for its availability and for it to have started, but // also because we're waiting for clusters to have done their first attempt at DNS resolution. // When we improve synchronous failure handling and/or move to dynamic forwarding, we only need // to wait until the dispatcher is running (and can drain by enqueueing a drain callback on it, // as we did previously). postinit_callback_handler_ = main_common->server()->lifecycleNotifier().registerCallback( Envoy::Server::ServerLifecycleNotifier::Stage::PostInit, [this]() -> void { ASSERT(Thread::MainThread::isMainOrTestThread()); connectivity_manager_ = Network::ConnectivityManagerFactory{server_->serverFactoryContext()}.get(); Envoy::Network::Android::Utility::setAlternateGetifaddrs(); auto v4_interfaces = connectivity_manager_->enumerateV4Interfaces(); auto v6_interfaces = connectivity_manager_->enumerateV6Interfaces(); logInterfaces("netconf_get_v4_interfaces", v4_interfaces); logInterfaces("netconf_get_v6_interfaces", v6_interfaces); client_scope_ = server_->serverFactoryContext().scope().createScope("pulse."); // StatNameSet is lock-free, the benefit of using it is being able to create StatsName // on-the-fly without risking contention on system with lots of threads. // It also comes with ease of programming. stat_name_set_ = client_scope_->symbolTable().makeSet("pulse"); auto api_listener = server_->listenerManager().apiListener()->get().http(); ASSERT(api_listener.has_value()); http_client_ = std::make_unique<Http::Client>(api_listener.value(), *dispatcher_, server_->serverFactoryContext().scope(), server_->api().randomGenerator()); dispatcher_->drain(server_->dispatcher()); if (callbacks_.on_engine_running != nullptr) { callbacks_.on_engine_running(callbacks_.context); } }); } // mutex_ // The main run loop must run without holding the mutex, so that the destructor can acquire it. bool run_success = main_common->run(); // The above call is blocking; at this point the event loop has exited. // Ensure destructors run on Envoy's main thread. postinit_callback_handler_.reset(nullptr); connectivity_manager_.reset(); client_scope_.reset(); stat_name_set_.reset(); main_common.reset(nullptr); bug_handler_registration_.reset(nullptr); assert_handler_registration_.reset(nullptr); callbacks_.on_exit(callbacks_.context); return run_success ? ENVOY_SUCCESS : ENVOY_FAILURE; } envoy_status_t Engine::terminate() { // If main_thread_ has finished (or hasn't started), there's nothing more to do. if (!main_thread_.joinable()) { return ENVOY_FAILURE; } // We need to be sure that MainCommon is finished being constructed so we can dispatch shutdown. { Thread::LockGuard lock(mutex_); if (!event_dispatcher_) { cv_.wait(mutex_); } ASSERT(event_dispatcher_); ASSERT(dispatcher_); // Exit the event loop and finish up in Engine::run(...) if (std::this_thread::get_id() == main_thread_.get_id()) { // TODO(goaway): figure out some way to support this. PANIC("Terminating the engine from its own main thread is currently unsupported."); } else { dispatcher_->terminate(); } } // lock(_mutex) if (std::this_thread::get_id() != main_thread_.get_id()) { main_thread_.join(); } return ENVOY_SUCCESS; } Engine::~Engine() { terminate(); } envoy_status_t Engine::recordCounterInc(const std::string& elements, envoy_stats_tags tags, uint64_t count) { ENVOY_LOG(trace, "[pulse.{}] recordCounterInc", elements); ASSERT(dispatcher_->isThreadSafe(), "pulse calls must run from dispatcher's context"); Stats::StatNameTagVector tags_vctr = Stats::Utility::transformToStatNameTagVector(tags, stat_name_set_); std::string name = Stats::Utility::sanitizeStatsName(elements); Stats::Utility::counterFromElements(*client_scope_, {Stats::DynamicName(name)}, tags_vctr) .add(count); return ENVOY_SUCCESS; } envoy_status_t Engine::recordGaugeSet(const std::string& elements, envoy_stats_tags tags, uint64_t value) { ENVOY_LOG(trace, "[pulse.{}] recordGaugeSet", elements); ASSERT(dispatcher_->isThreadSafe(), "pulse calls must run from dispatcher's context"); Stats::StatNameTagVector tags_vctr = Stats::Utility::transformToStatNameTagVector(tags, stat_name_set_); std::string name = Stats::Utility::sanitizeStatsName(elements); Stats::Utility::gaugeFromElements(*client_scope_, {Stats::DynamicName(name)}, Stats::Gauge::ImportMode::NeverImport, tags_vctr) .set(value); return ENVOY_SUCCESS; } envoy_status_t Engine::recordGaugeAdd(const std::string& elements, envoy_stats_tags tags, uint64_t amount) { ENVOY_LOG(trace, "[pulse.{}] recordGaugeAdd", elements); ASSERT(dispatcher_->isThreadSafe(), "pulse calls must run from dispatcher's context"); Stats::StatNameTagVector tags_vctr = Stats::Utility::transformToStatNameTagVector(tags, stat_name_set_); std::string name = Stats::Utility::sanitizeStatsName(elements); Stats::Utility::gaugeFromElements(*client_scope_, {Stats::DynamicName(name)}, Stats::Gauge::ImportMode::NeverImport, tags_vctr) .add(amount); return ENVOY_SUCCESS; } envoy_status_t Engine::recordGaugeSub(const std::string& elements, envoy_stats_tags tags, uint64_t amount) { ENVOY_LOG(trace, "[pulse.{}] recordGaugeSub", elements); ASSERT(dispatcher_->isThreadSafe(), "pulse calls must run from dispatcher's context"); Stats::StatNameTagVector tags_vctr = Stats::Utility::transformToStatNameTagVector(tags, stat_name_set_); std::string name = Stats::Utility::sanitizeStatsName(elements); Stats::Utility::gaugeFromElements(*client_scope_, {Stats::DynamicName(name)}, Stats::Gauge::ImportMode::NeverImport, tags_vctr) .sub(amount); return ENVOY_SUCCESS; } envoy_status_t Engine::recordHistogramValue(const std::string& elements, envoy_stats_tags tags, uint64_t value, envoy_histogram_stat_unit_t unit_measure) { ENVOY_LOG(trace, "[pulse.{}] recordHistogramValue", elements); ASSERT(dispatcher_->isThreadSafe(), "pulse calls must run from dispatcher's context"); Stats::StatNameTagVector tags_vctr = Stats::Utility::transformToStatNameTagVector(tags, stat_name_set_); std::string name = Stats::Utility::sanitizeStatsName(elements); Stats::Histogram::Unit envoy_unit_measure = Stats::Histogram::Unit::Unspecified; switch (unit_measure) { case MILLISECONDS: envoy_unit_measure = Stats::Histogram::Unit::Milliseconds; break; case MICROSECONDS: envoy_unit_measure = Stats::Histogram::Unit::Microseconds; break; case BYTES: envoy_unit_measure = Stats::Histogram::Unit::Bytes; break; case UNSPECIFIED: envoy_unit_measure = Stats::Histogram::Unit::Unspecified; break; } Stats::Utility::histogramFromElements(*client_scope_, {Stats::DynamicName(name)}, envoy_unit_measure, tags_vctr) .recordValue(value); return ENVOY_SUCCESS; } envoy_status_t Engine::makeAdminCall(absl::string_view path, absl::string_view method, envoy_data& out) { ENVOY_LOG(trace, "admin call {} {}", method, path); ASSERT(dispatcher_->isThreadSafe(), "admin calls must be run from the dispatcher's context"); auto response_headers = Http::ResponseHeaderMapImpl::create(); std::string body; const auto code = server_->admin().request(path, method, *response_headers, body); if (code != Http::Code::OK) { ENVOY_LOG(warn, "admin call failed with status {} body {}", static_cast<uint64_t>(code), body); return ENVOY_FAILURE; } out = Data::Utility::copyToBridgeData(body); return ENVOY_SUCCESS; } Event::ProvisionalDispatcher& Engine::dispatcher() { return *dispatcher_; } Http::Client& Engine::httpClient() { RELEASE_ASSERT(dispatcher_->isThreadSafe(), "httpClient must be accessed from dispatcher's context"); return *http_client_; } Network::ConnectivityManager& Engine::networkConnectivityManager() { RELEASE_ASSERT(dispatcher_->isThreadSafe(), "networkConnectivityManager must be accessed from dispatcher's context"); return *connectivity_manager_; } void Engine::flushStats() { ASSERT(dispatcher_->isThreadSafe(), "flushStats must be called from the dispatcher's context"); server_->flushStats(); } Upstream::ClusterManager& Engine::getClusterManager() { ASSERT(dispatcher_->isThreadSafe(), "getClusterManager must be called from the dispatcher's context"); return server_->clusterManager(); } void Engine::logInterfaces(absl::string_view event, std::vector<Network::InterfacePair>& interfaces) { std::vector<std::string> names; names.resize(interfaces.size()); std::transform(interfaces.begin(), interfaces.end(), names.begin(), [](Network::InterfacePair& pair) { return std::get<0>(pair); }); auto unique_end = std::unique(names.begin(), names.end()); std::string all_names = std::accumulate(names.begin(), unique_end, std::string{}, [](std::string acc, std::string next) { return acc.empty() ? next : std::move(acc) + "," + next; }); ENVOY_LOG_EVENT(debug, event, all_names); } } // namespace Envoy
#include "library/common/engine.h" #include "envoy/stats/histogram.h" #include "source/common/common/lock_guard.h" #include "library/common/bridge/utility.h" #include "library/common/config/internal.h" #include "library/common/data/utility.h" #include "library/common/network/android.h" #include "library/common/stats/utility.h" namespace Envoy { Engine::Engine(envoy_engine_callbacks callbacks, envoy_logger logger, envoy_event_tracker event_tracker) : callbacks_(callbacks), logger_(logger), event_tracker_(event_tracker), dispatcher_(std::make_unique<Event::ProvisionalDispatcher>()) { ExtensionRegistry::registerFactories(); // TODO(Augustyniak): Capturing an address of event_tracker_ and registering it in the API // registry may lead to crashes at Engine shutdown. To be figured out as part of // https://github.com/envoyproxy/envoy-mobile/issues/332 Envoy::Api::External::registerApi(std::string(envoy_event_tracker_api_name), &event_tracker_); } envoy_status_t Engine::run(const std::string config, const std::string log_level, const std::string admin_address_path) { // Start the Envoy on the dedicated thread. Note: due to how the assignment operator works with // std::thread, main_thread_ is the same object after this call, but its state is replaced with // that of the temporary. The temporary object's state becomes the default state, which does // nothing. main_thread_ = std::thread(&Engine::main, this, std::string(config), std::string(log_level), admin_address_path); return ENVOY_SUCCESS; } envoy_status_t Engine::main(const std::string config, const std::string log_level, const std::string admin_address_path) { // Using unique_ptr ensures main_common's lifespan is strictly scoped to this function. std::unique_ptr<EngineCommon> main_common; const std::string name = "envoy"; const std::string config_flag = "--config-yaml"; const std::string composed_config = absl::StrCat(config_header, config); const std::string log_flag = "-l"; const std::string concurrency_option = "--concurrency"; const std::string concurrency_arg = "0"; std::vector<const char*> envoy_argv = {name.c_str(), config_flag.c_str(), composed_config.c_str(), concurrency_option.c_str(), concurrency_arg.c_str(), log_flag.c_str(), log_level.c_str()}; if (!admin_address_path.empty()) { envoy_argv.push_back("--admin-address-path"); envoy_argv.push_back(admin_address_path.c_str()); } envoy_argv.push_back(nullptr); { Thread::LockGuard lock(mutex_); try { if (event_tracker_.track != nullptr) { assert_handler_registration_ = Assert::addDebugAssertionFailureRecordAction([this](const char* location) { const auto event = Bridge::Utility::makeEnvoyMap( {{"name", "assertion"}, {"location", std::string(location)}}); event_tracker_.track(event, event_tracker_.context); }); bug_handler_registration_ = Assert::addEnvoyBugFailureRecordAction([this](const char* location) { const auto event = Bridge::Utility::makeEnvoyMap( {{"name", "bug"}, {"location", std::string(location)}}); event_tracker_.track(event, event_tracker_.context); }); } // We let the thread clean up this log delegate pointer if (logger_.log) { log_delegate_ptr_ = std::make_unique<Logger::LambdaDelegate>(logger_, Logger::Registry::getSink()); } else { log_delegate_ptr_ = std::make_unique<Logger::DefaultDelegate>(log_mutex_, Logger::Registry::getSink()); } main_common = std::make_unique<EngineCommon>(envoy_argv.size() - 1, envoy_argv.data()); server_ = main_common->server(); event_dispatcher_ = &server_->dispatcher(); cv_.notifyAll(); } catch (const Envoy::NoServingException& e) { PANIC(e.what()); } catch (const Envoy::MalformedArgvException& e) { PANIC(e.what()); } catch (const Envoy::EnvoyException& e) { PANIC(e.what()); } // Note: We're waiting longer than we might otherwise to drain to the main thread's dispatcher. // This is because we're not simply waiting for its availability and for it to have started, but // also because we're waiting for clusters to have done their first attempt at DNS resolution. // When we improve synchronous failure handling and/or move to dynamic forwarding, we only need // to wait until the dispatcher is running (and can drain by enqueueing a drain callback on it, // as we did previously). postinit_callback_handler_ = main_common->server()->lifecycleNotifier().registerCallback( Envoy::Server::ServerLifecycleNotifier::Stage::PostInit, [this]() -> void { ASSERT(Thread::MainThread::isMainOrTestThread()); connectivity_manager_ = Network::ConnectivityManagerFactory{server_->serverFactoryContext()}.get(); Envoy::Network::Android::Utility::setAlternateGetifaddrs(); auto v4_interfaces = connectivity_manager_->enumerateV4Interfaces(); auto v6_interfaces = connectivity_manager_->enumerateV6Interfaces(); logInterfaces("netconf_get_v4_interfaces", v4_interfaces); logInterfaces("netconf_get_v6_interfaces", v6_interfaces); client_scope_ = server_->serverFactoryContext().scope().createScope("pulse."); // StatNameSet is lock-free, the benefit of using it is being able to create StatsName // on-the-fly without risking contention on system with lots of threads. // It also comes with ease of programming. stat_name_set_ = client_scope_->symbolTable().makeSet("pulse"); auto api_listener = server_->listenerManager().apiListener()->get().http(); ASSERT(api_listener.has_value()); http_client_ = std::make_unique<Http::Client>(api_listener.value(), *dispatcher_, server_->serverFactoryContext().scope(), server_->api().randomGenerator()); dispatcher_->drain(server_->dispatcher()); if (callbacks_.on_engine_running != nullptr) { callbacks_.on_engine_running(callbacks_.context); } }); } // mutex_ // The main run loop must run without holding the mutex, so that the destructor can acquire it. bool run_success = main_common->run(); // The above call is blocking; at this point the event loop has exited. // Ensure destructors run on Envoy's main thread. postinit_callback_handler_.reset(nullptr); connectivity_manager_.reset(); client_scope_.reset(); stat_name_set_.reset(); main_common.reset(nullptr); bug_handler_registration_.reset(nullptr); assert_handler_registration_.reset(nullptr); callbacks_.on_exit(callbacks_.context); return run_success ? ENVOY_SUCCESS : ENVOY_FAILURE; } envoy_status_t Engine::terminate() { // If main_thread_ has finished (or hasn't started), there's nothing more to do. if (!main_thread_.joinable()) { return ENVOY_FAILURE; } // We need to be sure that MainCommon is finished being constructed so we can dispatch shutdown. { Thread::LockGuard lock(mutex_); if (!event_dispatcher_) { cv_.wait(mutex_); } ASSERT(event_dispatcher_); ASSERT(dispatcher_); // Exit the event loop and finish up in Engine::run(...) if (std::this_thread::get_id() == main_thread_.get_id()) { // TODO(goaway): figure out some way to support this. PANIC("Terminating the engine from its own main thread is currently unsupported."); } else { dispatcher_->terminate(); } } // lock(_mutex) if (std::this_thread::get_id() != main_thread_.get_id()) { main_thread_.join(); } return ENVOY_SUCCESS; } Engine::~Engine() { terminate(); } envoy_status_t Engine::recordCounterInc(const std::string& elements, envoy_stats_tags tags, uint64_t count) { ENVOY_LOG(trace, "[pulse.{}] recordCounterInc", elements); ASSERT(dispatcher_->isThreadSafe(), "pulse calls must run from dispatcher's context"); Stats::StatNameTagVector tags_vctr = Stats::Utility::transformToStatNameTagVector(tags, stat_name_set_); std::string name = Stats::Utility::sanitizeStatsName(elements); Stats::Utility::counterFromElements(*client_scope_, {Stats::DynamicName(name)}, tags_vctr) .add(count); return ENVOY_SUCCESS; } envoy_status_t Engine::recordGaugeSet(const std::string& elements, envoy_stats_tags tags, uint64_t value) { ENVOY_LOG(trace, "[pulse.{}] recordGaugeSet", elements); ASSERT(dispatcher_->isThreadSafe(), "pulse calls must run from dispatcher's context"); Stats::StatNameTagVector tags_vctr = Stats::Utility::transformToStatNameTagVector(tags, stat_name_set_); std::string name = Stats::Utility::sanitizeStatsName(elements); Stats::Utility::gaugeFromElements(*client_scope_, {Stats::DynamicName(name)}, Stats::Gauge::ImportMode::NeverImport, tags_vctr) .set(value); return ENVOY_SUCCESS; } envoy_status_t Engine::recordGaugeAdd(const std::string& elements, envoy_stats_tags tags, uint64_t amount) { ENVOY_LOG(trace, "[pulse.{}] recordGaugeAdd", elements); ASSERT(dispatcher_->isThreadSafe(), "pulse calls must run from dispatcher's context"); Stats::StatNameTagVector tags_vctr = Stats::Utility::transformToStatNameTagVector(tags, stat_name_set_); std::string name = Stats::Utility::sanitizeStatsName(elements); Stats::Utility::gaugeFromElements(*client_scope_, {Stats::DynamicName(name)}, Stats::Gauge::ImportMode::NeverImport, tags_vctr) .add(amount); return ENVOY_SUCCESS; } envoy_status_t Engine::recordGaugeSub(const std::string& elements, envoy_stats_tags tags, uint64_t amount) { ENVOY_LOG(trace, "[pulse.{}] recordGaugeSub", elements); ASSERT(dispatcher_->isThreadSafe(), "pulse calls must run from dispatcher's context"); Stats::StatNameTagVector tags_vctr = Stats::Utility::transformToStatNameTagVector(tags, stat_name_set_); std::string name = Stats::Utility::sanitizeStatsName(elements); Stats::Utility::gaugeFromElements(*client_scope_, {Stats::DynamicName(name)}, Stats::Gauge::ImportMode::NeverImport, tags_vctr) .sub(amount); return ENVOY_SUCCESS; } envoy_status_t Engine::recordHistogramValue(const std::string& elements, envoy_stats_tags tags, uint64_t value, envoy_histogram_stat_unit_t unit_measure) { ENVOY_LOG(trace, "[pulse.{}] recordHistogramValue", elements); ASSERT(dispatcher_->isThreadSafe(), "pulse calls must run from dispatcher's context"); Stats::StatNameTagVector tags_vctr = Stats::Utility::transformToStatNameTagVector(tags, stat_name_set_); std::string name = Stats::Utility::sanitizeStatsName(elements); Stats::Histogram::Unit envoy_unit_measure = Stats::Histogram::Unit::Unspecified; switch (unit_measure) { case MILLISECONDS: envoy_unit_measure = Stats::Histogram::Unit::Milliseconds; break; case MICROSECONDS: envoy_unit_measure = Stats::Histogram::Unit::Microseconds; break; case BYTES: envoy_unit_measure = Stats::Histogram::Unit::Bytes; break; case UNSPECIFIED: envoy_unit_measure = Stats::Histogram::Unit::Unspecified; break; } Stats::Utility::histogramFromElements(*client_scope_, {Stats::DynamicName(name)}, envoy_unit_measure, tags_vctr) .recordValue(value); return ENVOY_SUCCESS; } envoy_status_t Engine::makeAdminCall(absl::string_view path, absl::string_view method, envoy_data& out) { ENVOY_LOG(trace, "admin call {} {}", method, path); ASSERT(dispatcher_->isThreadSafe(), "admin calls must be run from the dispatcher's context"); auto response_headers = Http::ResponseHeaderMapImpl::create(); std::string body; const auto code = server_->admin().request(path, method, *response_headers, body); if (code != Http::Code::OK) { ENVOY_LOG(warn, "admin call failed with status {} body {}", static_cast<uint64_t>(code), body); return ENVOY_FAILURE; } out = Data::Utility::copyToBridgeData(body); return ENVOY_SUCCESS; } Event::ProvisionalDispatcher& Engine::dispatcher() { return *dispatcher_; } Http::Client& Engine::httpClient() { RELEASE_ASSERT(dispatcher_->isThreadSafe(), "httpClient must be accessed from dispatcher's context"); return *http_client_; } Network::ConnectivityManager& Engine::networkConnectivityManager() { RELEASE_ASSERT(dispatcher_->isThreadSafe(), "networkConnectivityManager must be accessed from dispatcher's context"); return *connectivity_manager_; } void Engine::flushStats() { ASSERT(dispatcher_->isThreadSafe(), "flushStats must be called from the dispatcher's context"); server_->flushStats(); } Upstream::ClusterManager& Engine::getClusterManager() { ASSERT(dispatcher_->isThreadSafe(), "getClusterManager must be called from the dispatcher's context"); return server_->clusterManager(); } void Engine::logInterfaces(absl::string_view event, std::vector<Network::InterfacePair>& interfaces) { std::vector<std::string> names; names.resize(interfaces.size()); std::transform(interfaces.begin(), interfaces.end(), names.begin(), [](Network::InterfacePair& pair) { return std::get<0>(pair); }); auto unique_end = std::unique(names.begin(), names.end()); std::string all_names = std::accumulate(names.begin(), unique_end, std::string{}, [](std::string acc, std::string next) { return acc.empty() ? next : std::move(acc) + "," + next; }); ENVOY_LOG_EVENT(debug, event, all_names); } } // namespace Envoy
remove outdated comment about `registerFactories()` (#2412)
engine: remove outdated comment about `registerFactories()` (#2412) `ExtensionRegistry::registerFactories()` doesn't do any work at runtime, its purpose is to guarantee that the linker won't strip away these factories as dead code because they're discovered at runtime as opposed to being referenced statically. So it's safe to call on engine creation because it's a no-op at runtime. Signed-off-by: JP Simard <[email protected]>
C++
apache-2.0
envoyproxy/envoy-mobile,envoyproxy/envoy-mobile,envoyproxy/envoy-mobile,envoyproxy/envoy-mobile,envoyproxy/envoy-mobile,envoyproxy/envoy-mobile,envoyproxy/envoy-mobile,envoyproxy/envoy-mobile,envoyproxy/envoy-mobile
6b227aa882ed7dce5e907f7e62d03588216c1202
sources/stack.cpp
sources/stack.cpp
#include <iostream> #include "stack.hpp"
Update stack.cpp
Update stack.cpp
C++
mit
ArtemKokorinStudent/External-sort,ArtemKokorinStudent/StackW
66f3587bb1636599e232da9d51ac95e5e48baa52
src/traced/probes/ftrace/test/cpu_reader_support.cc
src/traced/probes/ftrace/test/cpu_reader_support.cc
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/traced/probes/ftrace/test/cpu_reader_support.h" #include "perfetto/base/utils.h" #include "src/traced/probes/ftrace/ftrace_procfs.h" #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> namespace perfetto { namespace { std::map<std::string, std::unique_ptr<ProtoTranslationTable>>* g_tables; std::string GetBinaryDirectory() { char buf[512]; ssize_t rd = readlink("/proc/self/exe", buf, sizeof(buf) - 1); if (rd < 0) { PERFETTO_ELOG("Failed to readlink(\"/proc/self/exe\""); return ""; } char* end = static_cast<char*>(memrchr(buf, '/', static_cast<size_t>(rd))); if (!end || end == buf + sizeof(buf) - 1) { PERFETTO_ELOG("Failed to find directory."); return ""; } *(end + 1) = '\0'; return std::string(buf); } } // namespace ProtoTranslationTable* GetTable(const std::string& name) { if (!g_tables) g_tables = new std::map<std::string, std::unique_ptr<ProtoTranslationTable>>(); if (!g_tables->count(name)) { std::string path = "src/traced/probes/ftrace/test/data/" + name + "/"; struct stat st; if (lstat(path.c_str(), &st) == -1 && errno == ENOENT) { // For OSS fuzz, which does not run in the correct cwd. path = GetBinaryDirectory() + path; } FtraceProcfs ftrace(path); auto table = ProtoTranslationTable::Create(&ftrace, GetStaticEventInfo(), GetStaticCommonFieldsInfo()); if (!table) return nullptr; g_tables->emplace(name, std::move(table)); } return g_tables->at(name).get(); } std::unique_ptr<uint8_t[]> PageFromXxd(const std::string& text) { auto buffer = std::unique_ptr<uint8_t[]>(new uint8_t[base::kPageSize]); const char* ptr = text.data(); memset(buffer.get(), 0xfa, base::kPageSize); uint8_t* out = buffer.get(); while (*ptr != '\0') { if (*(ptr++) != ':') continue; for (int i = 0; i < 8; i++) { PERFETTO_CHECK(text.size() >= static_cast<size_t>((ptr - text.data()) + 5)); PERFETTO_CHECK(*(ptr++) == ' '); int n = sscanf(ptr, "%02hhx%02hhx", out, out + 1); PERFETTO_CHECK(n == 2); out += n; ptr += 4; } while (*ptr != '\n') ptr++; } return buffer; } } // namespace perfetto
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/traced/probes/ftrace/test/cpu_reader_support.h" #include "perfetto/base/utils.h" #include "src/traced/probes/ftrace/ftrace_procfs.h" #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> namespace perfetto { namespace { std::map<std::string, std::unique_ptr<ProtoTranslationTable>>* g_tables; std::string GetBinaryDirectory() { std::string buf(512, '\0'); ssize_t rd = readlink("/proc/self/exe", &buf[0], buf.size()); if (rd < 0) { PERFETTO_ELOG("Failed to readlink(\"/proc/self/exe\""); return ""; } buf.resize(static_cast<size_t>(rd)); size_t end = buf.rfind('/'); if (end == std::string::npos) { PERFETTO_ELOG("Failed to find directory."); return ""; } return buf.substr(0, end + 1); } } // namespace ProtoTranslationTable* GetTable(const std::string& name) { if (!g_tables) g_tables = new std::map<std::string, std::unique_ptr<ProtoTranslationTable>>(); if (!g_tables->count(name)) { std::string path = "src/traced/probes/ftrace/test/data/" + name + "/"; struct stat st; if (lstat(path.c_str(), &st) == -1 && errno == ENOENT) { // For OSS fuzz, which does not run in the correct cwd. path = GetBinaryDirectory() + path; } FtraceProcfs ftrace(path); auto table = ProtoTranslationTable::Create(&ftrace, GetStaticEventInfo(), GetStaticCommonFieldsInfo()); if (!table) return nullptr; g_tables->emplace(name, std::move(table)); } return g_tables->at(name).get(); } std::unique_ptr<uint8_t[]> PageFromXxd(const std::string& text) { auto buffer = std::unique_ptr<uint8_t[]>(new uint8_t[base::kPageSize]); const char* ptr = text.data(); memset(buffer.get(), 0xfa, base::kPageSize); uint8_t* out = buffer.get(); while (*ptr != '\0') { if (*(ptr++) != ':') continue; for (int i = 0; i < 8; i++) { PERFETTO_CHECK(text.size() >= static_cast<size_t>((ptr - text.data()) + 5)); PERFETTO_CHECK(*(ptr++) == ' '); int n = sscanf(ptr, "%02hhx%02hhx", out, out + 1); PERFETTO_CHECK(n == 2); out += n; ptr += 4; } while (*ptr != '\n') ptr++; } return buffer; } } // namespace perfetto
Fix mac build
Fix mac build Change-Id: I3c499a1d0ab6f72775d320f4c3841586bfed02a0
C++
apache-2.0
google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto
378e4edf61c43c9a3f4cfe5ce17b513052d4f937
src/Folder.cpp
src/Folder.cpp
/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<[email protected]> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "Folder.h" #include "Device.h" #include "Media.h" #include "database/SqliteTools.h" #include "filesystem/IDirectory.h" #include "filesystem/IDevice.h" #include "utils/Filename.h" #include <unordered_map> namespace policy { const std::string FolderTable::Name = "Folder"; const std::string FolderTable::PrimaryKeyColumn = "id_folder"; unsigned int Folder::* const FolderTable::PrimaryKey = &Folder::m_id; } std::shared_ptr<factory::IFileSystem> Folder::FsFactory; Folder::Folder( DBConnection dbConnection, sqlite::Row& row ) : m_dbConection( dbConnection ) { row >> m_id >> m_path >> m_parent >> m_lastModificationDate >> m_isBlacklisted >> m_deviceId >> m_isPresent; } Folder::Folder( const std::string& path, time_t lastModificationDate, unsigned int parent, unsigned int deviceId ) : m_id( 0 ) , m_path( path ) , m_parent( parent ) , m_lastModificationDate( lastModificationDate ) , m_isBlacklisted( false ) , m_deviceId( deviceId ) , m_isPresent( true ) { // Don't fetch the device mountpoint from here, we don't have a DBConnection yet. } bool Folder::createTable(DBConnection connection) { std::string req = "CREATE TABLE IF NOT EXISTS " + policy::FolderTable::Name + "(" "id_folder INTEGER PRIMARY KEY AUTOINCREMENT," "path TEXT," "id_parent UNSIGNED INTEGER," "last_modification_date UNSIGNED INTEGER," "is_blacklisted INTEGER," "device_id UNSIGNED INTEGER," "is_present BOOLEAN NOT NULL DEFAULT 1," "FOREIGN KEY (id_parent) REFERENCES " + policy::FolderTable::Name + "(id_folder) ON DELETE CASCADE," "FOREIGN KEY (device_id) REFERENCES " + policy::DeviceTable::Name + "(id_device) ON DELETE CASCADE" ")"; std::string triggerReq = "CREATE TRIGGER IF NOT EXISTS is_device_present AFTER UPDATE OF is_present ON " + policy::DeviceTable::Name + " BEGIN" " UPDATE " + policy::FolderTable::Name + " SET is_present = new.is_present WHERE device_id = new.id_device;" " END"; return sqlite::Tools::executeRequest( connection, req ) && sqlite::Tools::executeRequest( connection, triggerReq ); } std::shared_ptr<Folder> Folder::create( DBConnection connection, const std::string& fullPath, time_t lastModificationDate, unsigned int parentId, Device& device, fs::IDevice& deviceFs ) { auto path = utils::file::removePath( fullPath, deviceFs.mountpoint() ); auto self = std::make_shared<Folder>( path, lastModificationDate, parentId, device.id() ); static const std::string req = "INSERT INTO " + policy::FolderTable::Name + "(path, id_parent, last_modification_date, device_id) VALUES(?, ?, ?, ?)"; if ( insert( connection, self, req, path, sqlite::ForeignKey( parentId ), lastModificationDate, device.id() ) == false ) return nullptr; self->m_dbConection = connection; self->m_deviceMountpoint = deviceFs.mountpoint(); self->computeFullPath(); return self; } bool Folder::blacklist( DBConnection connection, const std::string& fullPath ) { auto folderFs = FsFactory->createDirectory( fullPath ); auto deviceFs = folderFs->device(); auto device = Device::fromUuid( connection, deviceFs->uuid() ); if ( device == nullptr ) device = Device::create( connection, deviceFs->uuid(), deviceFs->isRemovable() ); auto path = utils::file::removePath( fullPath, deviceFs->mountpoint() ); static const std::string req = "INSERT INTO " + policy::FolderTable::Name + "(path, id_parent, is_blacklisted, device_id) VALUES(?, ?, ?, ?)"; return sqlite::Tools::insert( connection, req, path, nullptr, true, device->id() ) != 0; } void Folder::setFileSystemFactory( std::shared_ptr<factory::IFileSystem> fsFactory ) { FsFactory = fsFactory; } std::shared_ptr<Folder> Folder::fromPath( DBConnection conn, const std::string& fullPath ) { auto folderFs = FsFactory->createDirectory( fullPath ); if ( folderFs == nullptr ) return nullptr; auto deviceFs = folderFs->device(); if ( deviceFs == nullptr ) { LOG_ERROR( "Failed to get device containing an existing folder: ", fullPath ); return nullptr; } auto device = Device::fromUuid( conn, deviceFs->uuid() ); // We are trying to find a folder. If we don't know the device it's on, we don't know the folder. if ( device == nullptr ) return nullptr; auto path = utils::file::removePath( fullPath, deviceFs->mountpoint() ); const std::string req = "SELECT * FROM " + policy::FolderTable::Name + " WHERE path = ? AND device_id = ? " "AND is_blacklisted IS NULL"; auto folder = fetch( conn, req, path, device->id() ); if ( folder == nullptr ) return nullptr; folder->m_deviceMountpoint = deviceFs->mountpoint(); folder->computeFullPath(); return folder; } unsigned int Folder::id() const { return m_id; } const std::string& Folder::path() const { return m_fullPath; } std::vector<MediaPtr> Folder::files() { static const std::string req = "SELECT * FROM " + policy::MediaTable::Name + " WHERE folder_id = ?"; return Media::fetchAll<IMedia>( m_dbConection, req, m_id ); } std::vector<std::shared_ptr<Folder>> Folder::folders() { return fetchAll( m_dbConection, m_id ); } std::shared_ptr<Folder> Folder::parent() { return fetch( m_dbConection, m_parent ); } unsigned int Folder::lastModificationDate() { return m_lastModificationDate; } bool Folder::setLastModificationDate( unsigned int lastModificationDate ) { static const std::string req = "UPDATE " + policy::FolderTable::Name + " SET last_modification_date = ? WHERE id_folder = ?"; if ( sqlite::Tools::executeUpdate( m_dbConection, req, lastModificationDate, m_id ) == false ) return false; m_lastModificationDate = lastModificationDate; return true; } unsigned int Folder::deviceId() const { return m_deviceId; } bool Folder::isPresent() const { return m_isPresent; } void Folder::computeFullPath() { if ( ( *m_deviceMountpoint.crbegin() ) != '/' ) m_deviceMountpoint += '/'; m_fullPath = m_deviceMountpoint + m_path; } std::vector<std::shared_ptr<Folder>> Folder::fetchAll( DBConnection dbConn, unsigned int parentFolderId ) { std::vector<std::shared_ptr<Folder>> res; if ( parentFolderId == 0 ) { static const std::string req = "SELECT * FROM " + policy::FolderTable::Name + " WHERE id_parent IS NULL AND is_blacklisted is NULL"; res = DatabaseHelpers::fetchAll<Folder>( dbConn, req ); } else { static const std::string req = "SELECT * FROM " + policy::FolderTable::Name + " WHERE id_parent = ? AND is_blacklisted is NULL"; res = DatabaseHelpers::fetchAll<Folder>( dbConn, req, parentFolderId ); } std::unordered_map<unsigned int, std::string> deviceMountpoints; for ( auto& f : res ) { auto it = deviceMountpoints.find( f->deviceId() ); if ( it == end( deviceMountpoints ) ) { auto device = Device::fetch( dbConn, f->deviceId() ); auto deviceFs = FsFactory->createDevice( device->uuid() ); deviceMountpoints[f->deviceId()] = deviceFs->mountpoint(); f->m_deviceMountpoint = deviceFs->mountpoint(); } else f->m_deviceMountpoint = it->second; f->computeFullPath(); } return res; }
/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<[email protected]> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "Folder.h" #include "Device.h" #include "Media.h" #include "database/SqliteTools.h" #include "filesystem/IDirectory.h" #include "filesystem/IDevice.h" #include "utils/Filename.h" #include <unordered_map> namespace policy { const std::string FolderTable::Name = "Folder"; const std::string FolderTable::PrimaryKeyColumn = "id_folder"; unsigned int Folder::* const FolderTable::PrimaryKey = &Folder::m_id; } std::shared_ptr<factory::IFileSystem> Folder::FsFactory; Folder::Folder( DBConnection dbConnection, sqlite::Row& row ) : m_dbConection( dbConnection ) { row >> m_id >> m_path >> m_parent >> m_lastModificationDate >> m_isBlacklisted >> m_deviceId >> m_isPresent; } Folder::Folder( const std::string& path, time_t lastModificationDate, unsigned int parent, unsigned int deviceId ) : m_id( 0 ) , m_path( path ) , m_parent( parent ) , m_lastModificationDate( lastModificationDate ) , m_isBlacklisted( false ) , m_deviceId( deviceId ) , m_isPresent( true ) { // Don't fetch the device mountpoint from here, we don't have a DBConnection yet. } bool Folder::createTable(DBConnection connection) { std::string req = "CREATE TABLE IF NOT EXISTS " + policy::FolderTable::Name + "(" "id_folder INTEGER PRIMARY KEY AUTOINCREMENT," "path TEXT," "id_parent UNSIGNED INTEGER," "last_modification_date UNSIGNED INTEGER," "is_blacklisted INTEGER," "device_id UNSIGNED INTEGER," "is_present BOOLEAN NOT NULL DEFAULT 1," "FOREIGN KEY (id_parent) REFERENCES " + policy::FolderTable::Name + "(id_folder) ON DELETE CASCADE," "FOREIGN KEY (device_id) REFERENCES " + policy::DeviceTable::Name + "(id_device) ON DELETE CASCADE" ")"; std::string triggerReq = "CREATE TRIGGER IF NOT EXISTS is_device_present AFTER UPDATE OF is_present ON " + policy::DeviceTable::Name + " BEGIN" " UPDATE " + policy::FolderTable::Name + " SET is_present = new.is_present WHERE device_id = new.id_device;" " END"; return sqlite::Tools::executeRequest( connection, req ) && sqlite::Tools::executeRequest( connection, triggerReq ); } std::shared_ptr<Folder> Folder::create( DBConnection connection, const std::string& fullPath, time_t lastModificationDate, unsigned int parentId, Device& device, fs::IDevice& deviceFs ) { auto path = utils::file::removePath( fullPath, deviceFs.mountpoint() ); auto self = std::make_shared<Folder>( path, lastModificationDate, parentId, device.id() ); static const std::string req = "INSERT INTO " + policy::FolderTable::Name + "(path, id_parent, last_modification_date, device_id) VALUES(?, ?, ?, ?)"; if ( insert( connection, self, req, path, sqlite::ForeignKey( parentId ), lastModificationDate, device.id() ) == false ) return nullptr; self->m_dbConection = connection; self->m_deviceMountpoint = deviceFs.mountpoint(); self->computeFullPath(); return self; } bool Folder::blacklist( DBConnection connection, const std::string& fullPath ) { auto folderFs = FsFactory->createDirectory( fullPath ); if ( folderFs == nullptr ) return false; auto deviceFs = folderFs->device(); auto device = Device::fromUuid( connection, deviceFs->uuid() ); if ( device == nullptr ) device = Device::create( connection, deviceFs->uuid(), deviceFs->isRemovable() ); auto path = utils::file::removePath( fullPath, deviceFs->mountpoint() ); static const std::string req = "INSERT INTO " + policy::FolderTable::Name + "(path, id_parent, is_blacklisted, device_id) VALUES(?, ?, ?, ?)"; return sqlite::Tools::insert( connection, req, path, nullptr, true, device->id() ) != 0; } void Folder::setFileSystemFactory( std::shared_ptr<factory::IFileSystem> fsFactory ) { FsFactory = fsFactory; } std::shared_ptr<Folder> Folder::fromPath( DBConnection conn, const std::string& fullPath ) { auto folderFs = FsFactory->createDirectory( fullPath ); if ( folderFs == nullptr ) return nullptr; auto deviceFs = folderFs->device(); if ( deviceFs == nullptr ) { LOG_ERROR( "Failed to get device containing an existing folder: ", fullPath ); return nullptr; } auto device = Device::fromUuid( conn, deviceFs->uuid() ); // We are trying to find a folder. If we don't know the device it's on, we don't know the folder. if ( device == nullptr ) return nullptr; auto path = utils::file::removePath( fullPath, deviceFs->mountpoint() ); const std::string req = "SELECT * FROM " + policy::FolderTable::Name + " WHERE path = ? AND device_id = ? " "AND is_blacklisted IS NULL"; auto folder = fetch( conn, req, path, device->id() ); if ( folder == nullptr ) return nullptr; folder->m_deviceMountpoint = deviceFs->mountpoint(); folder->computeFullPath(); return folder; } unsigned int Folder::id() const { return m_id; } const std::string& Folder::path() const { return m_fullPath; } std::vector<MediaPtr> Folder::files() { static const std::string req = "SELECT * FROM " + policy::MediaTable::Name + " WHERE folder_id = ?"; return Media::fetchAll<IMedia>( m_dbConection, req, m_id ); } std::vector<std::shared_ptr<Folder>> Folder::folders() { return fetchAll( m_dbConection, m_id ); } std::shared_ptr<Folder> Folder::parent() { return fetch( m_dbConection, m_parent ); } unsigned int Folder::lastModificationDate() { return m_lastModificationDate; } bool Folder::setLastModificationDate( unsigned int lastModificationDate ) { static const std::string req = "UPDATE " + policy::FolderTable::Name + " SET last_modification_date = ? WHERE id_folder = ?"; if ( sqlite::Tools::executeUpdate( m_dbConection, req, lastModificationDate, m_id ) == false ) return false; m_lastModificationDate = lastModificationDate; return true; } unsigned int Folder::deviceId() const { return m_deviceId; } bool Folder::isPresent() const { return m_isPresent; } void Folder::computeFullPath() { if ( ( *m_deviceMountpoint.crbegin() ) != '/' ) m_deviceMountpoint += '/'; m_fullPath = m_deviceMountpoint + m_path; } std::vector<std::shared_ptr<Folder>> Folder::fetchAll( DBConnection dbConn, unsigned int parentFolderId ) { std::vector<std::shared_ptr<Folder>> res; if ( parentFolderId == 0 ) { static const std::string req = "SELECT * FROM " + policy::FolderTable::Name + " WHERE id_parent IS NULL AND is_blacklisted is NULL"; res = DatabaseHelpers::fetchAll<Folder>( dbConn, req ); } else { static const std::string req = "SELECT * FROM " + policy::FolderTable::Name + " WHERE id_parent = ? AND is_blacklisted is NULL"; res = DatabaseHelpers::fetchAll<Folder>( dbConn, req, parentFolderId ); } std::unordered_map<unsigned int, std::string> deviceMountpoints; for ( auto& f : res ) { auto it = deviceMountpoints.find( f->deviceId() ); if ( it == end( deviceMountpoints ) ) { auto device = Device::fetch( dbConn, f->deviceId() ); auto deviceFs = FsFactory->createDevice( device->uuid() ); deviceMountpoints[f->deviceId()] = deviceFs->mountpoint(); f->m_deviceMountpoint = deviceFs->mountpoint(); } else f->m_deviceMountpoint = it->second; f->computeFullPath(); } return res; }
Fix a crash when adding a non existing folder to the ignore list
Folder: Fix a crash when adding a non existing folder to the ignore list
C++
lgpl-2.1
chouquette/medialibrary,chouquette/medialibrary,chouquette/medialibrary,chouquette/medialibrary
c7d2de200ebcb50a4ca4ff1fc0fb7d1f0493e0ef
Modules/Filtering/ImageIntensity/test/itkRescaleIntensityImageFilterTest.cxx
Modules/Filtering/ImageIntensity/test/itkRescaleIntensityImageFilterTest.cxx
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include <iostream> #include "itkRescaleIntensityImageFilter.h" #include "itkRandomImageSource.h" int itkRescaleIntensityImageFilterTest(int, char* [] ) { std::cout << "itkRescaleIntensityImageFilterTest Start" << std::endl; typedef itk::Image<float,3> TestInputImage; typedef itk::Image<float,3> TestOutputImage; TestInputImage::RegionType region; TestInputImage::SizeType size; size.Fill(64); TestInputImage::IndexType index; index.Fill(0); region.SetIndex (index); region.SetSize (size); typedef itk::RescaleIntensityImageFilter<TestInputImage,TestOutputImage> FilterType; FilterType::Pointer filter = FilterType::New(); // Now generate a real image typedef itk::RandomImageSource<TestInputImage> SourceType; SourceType::Pointer source = SourceType::New(); TestInputImage::SizeValueType randomSize[3] = {17, 8, 20}; // Set up source source->SetSize(randomSize); double minValue = -128.0; double maxValue = 127.0; source->SetMin( static_cast< TestInputImage::PixelType >( minValue ) ); source->SetMax( static_cast< TestInputImage::PixelType >( maxValue ) ); filter->SetFunctor(filter->GetFunctor()); filter->SetInput(source->GetOutput()); const double desiredMinimum = -1.0; const double desiredMaximum = 1.0; filter->SetOutputMinimum( desiredMinimum ); filter->SetOutputMaximum( desiredMaximum ); try { filter->UpdateLargestPossibleRegion(); filter->SetFunctor(filter->GetFunctor()); } catch (itk::ExceptionObject& e) { std::cerr << "Exception detected: " << e; return -1; } typedef itk::MinimumMaximumImageCalculator< TestOutputImage > CalculatorType; CalculatorType::Pointer calculator = CalculatorType::New(); calculator->SetImage( filter->GetOutput() ); calculator->Compute(); const double tolerance = 1e-7; const double obtainedMinimum = calculator->GetMinimum(); const double obtainedMaximum = calculator->GetMaximum(); if( itk::Math::abs( obtainedMinimum - desiredMinimum ) > tolerance ) { std::cerr << "Error in minimum" << std::endl; std::cerr << "Expected minimum = " << desiredMinimum << std::endl; std::cerr << "Obtained minimum = " << obtainedMinimum << std::endl; return EXIT_FAILURE; } if( itk::Math::abs( obtainedMaximum - desiredMaximum ) > tolerance ) { std::cerr << "Error in minimum" << std::endl; std::cerr << "Expected minimum = " << desiredMaximum << std::endl; std::cerr << "Obtained minimum = " << obtainedMaximum << std::endl; return EXIT_FAILURE; } std::cout << "Test PASSED ! " << std::endl; return EXIT_SUCCESS; }
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include <iostream> #include "itkRescaleIntensityImageFilter.h" #include "itkRandomImageSource.h" #include "itkTestingMacros.h" #include "itkUnaryFunctorImageFilter.h" int itkRescaleIntensityImageFilterTest(int, char* [] ) { std::cout << "itkRescaleIntensityImageFilterTest Start" << std::endl; typedef itk::Image<float,3> TestInputImage; typedef itk::Image<float,3> TestOutputImage; TestInputImage::RegionType region; TestInputImage::SizeType size; size.Fill(64); TestInputImage::IndexType index; index.Fill(0); region.SetIndex (index); region.SetSize (size); typedef itk::RescaleIntensityImageFilter<TestInputImage,TestOutputImage> FilterType; FilterType::Pointer filter = FilterType::New(); EXERCISE_BASIC_OBJECT_METHODS( filter, RescaleIntensityImageFilter, UnaryFunctorImageFilter ); // Now generate a real image typedef itk::RandomImageSource<TestInputImage> SourceType; SourceType::Pointer source = SourceType::New(); TestInputImage::SizeValueType randomSize[3] = {17, 8, 20}; // Set up source source->SetSize(randomSize); double minValue = -128.0; double maxValue = 127.0; source->SetMin( static_cast< TestInputImage::PixelType >( minValue ) ); source->SetMax( static_cast< TestInputImage::PixelType >( maxValue ) ); filter->SetFunctor(filter->GetFunctor()); filter->SetInput(source->GetOutput()); const double desiredMinimum = -1.0; const double desiredMaximum = 1.0; filter->SetOutputMinimum( desiredMinimum ); filter->SetOutputMaximum( desiredMaximum ); try { filter->UpdateLargestPossibleRegion(); filter->SetFunctor(filter->GetFunctor()); } catch (itk::ExceptionObject& e) { std::cerr << "Exception detected: " << e; return -1; } typedef itk::MinimumMaximumImageCalculator< TestOutputImage > CalculatorType; CalculatorType::Pointer calculator = CalculatorType::New(); calculator->SetImage( filter->GetOutput() ); calculator->Compute(); const double tolerance = 1e-7; const double obtainedMinimum = calculator->GetMinimum(); const double obtainedMaximum = calculator->GetMaximum(); if( itk::Math::abs( obtainedMinimum - desiredMinimum ) > tolerance ) { std::cerr << "Error in minimum" << std::endl; std::cerr << "Expected minimum = " << desiredMinimum << std::endl; std::cerr << "Obtained minimum = " << obtainedMinimum << std::endl; return EXIT_FAILURE; } if( itk::Math::abs( obtainedMaximum - desiredMaximum ) > tolerance ) { std::cerr << "Error in minimum" << std::endl; std::cerr << "Expected minimum = " << desiredMaximum << std::endl; std::cerr << "Obtained minimum = " << obtainedMaximum << std::endl; return EXIT_FAILURE; } std::cout << "Test PASSED ! " << std::endl; return EXIT_SUCCESS; }
Improve RescaleIntensityImageFilter coverage.
ENH: Improve RescaleIntensityImageFilter coverage. Improve the itkRescaleIntensityImageFilter test coverage by exercising the basic object methods. Change-Id: If59cd4f36b8528f2136f49e055231d4e6834604e
C++
apache-2.0
blowekamp/ITK,blowekamp/ITK,spinicist/ITK,richardbeare/ITK,BRAINSia/ITK,spinicist/ITK,Kitware/ITK,thewtex/ITK,blowekamp/ITK,PlutoniumHeart/ITK,hjmjohnson/ITK,Kitware/ITK,malaterre/ITK,hjmjohnson/ITK,spinicist/ITK,LucasGandel/ITK,vfonov/ITK,PlutoniumHeart/ITK,fbudin69500/ITK,LucasGandel/ITK,thewtex/ITK,richardbeare/ITK,vfonov/ITK,zachary-williamson/ITK,zachary-williamson/ITK,PlutoniumHeart/ITK,thewtex/ITK,InsightSoftwareConsortium/ITK,stnava/ITK,InsightSoftwareConsortium/ITK,InsightSoftwareConsortium/ITK,InsightSoftwareConsortium/ITK,PlutoniumHeart/ITK,zachary-williamson/ITK,spinicist/ITK,LucasGandel/ITK,BRAINSia/ITK,stnava/ITK,BRAINSia/ITK,fbudin69500/ITK,blowekamp/ITK,fbudin69500/ITK,thewtex/ITK,zachary-williamson/ITK,fbudin69500/ITK,PlutoniumHeart/ITK,LucasGandel/ITK,Kitware/ITK,malaterre/ITK,fbudin69500/ITK,InsightSoftwareConsortium/ITK,malaterre/ITK,zachary-williamson/ITK,richardbeare/ITK,thewtex/ITK,vfonov/ITK,stnava/ITK,spinicist/ITK,hjmjohnson/ITK,hjmjohnson/ITK,zachary-williamson/ITK,malaterre/ITK,stnava/ITK,BRAINSia/ITK,fbudin69500/ITK,BRAINSia/ITK,thewtex/ITK,spinicist/ITK,blowekamp/ITK,malaterre/ITK,vfonov/ITK,Kitware/ITK,stnava/ITK,spinicist/ITK,stnava/ITK,malaterre/ITK,richardbeare/ITK,zachary-williamson/ITK,BRAINSia/ITK,InsightSoftwareConsortium/ITK,hjmjohnson/ITK,vfonov/ITK,thewtex/ITK,LucasGandel/ITK,malaterre/ITK,InsightSoftwareConsortium/ITK,LucasGandel/ITK,Kitware/ITK,stnava/ITK,fbudin69500/ITK,blowekamp/ITK,malaterre/ITK,hjmjohnson/ITK,stnava/ITK,richardbeare/ITK,vfonov/ITK,vfonov/ITK,richardbeare/ITK,BRAINSia/ITK,Kitware/ITK,zachary-williamson/ITK,blowekamp/ITK,PlutoniumHeart/ITK,PlutoniumHeart/ITK,LucasGandel/ITK,spinicist/ITK,Kitware/ITK,hjmjohnson/ITK,vfonov/ITK,blowekamp/ITK,LucasGandel/ITK,spinicist/ITK,richardbeare/ITK,zachary-williamson/ITK,PlutoniumHeart/ITK,vfonov/ITK,fbudin69500/ITK,stnava/ITK,malaterre/ITK
f5b1dedab2c29bd05ebc4da06db0fb3fa1083599
activemq-cpp/src/main/decaf/internal/util/concurrent/unix/PlatformThread.cpp
activemq-cpp/src/main/decaf/internal/util/concurrent/unix/PlatformThread.cpp
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <decaf/internal/util/concurrent/PlatformThread.h> #include <decaf/lang/exceptions/RuntimeException.h> #include <decaf/util/concurrent/TimeUnit.h> #include <memory> #if HAVE_ERRNO_H #include <errno.h> #endif #if HAVE_LIMITS_H #include <limits.h> #endif #if HAVE_PTHREAD_H #include <pthread.h> #endif #if HAVE_SIGNAL_H #include <signal.h> #endif #if HAVE_STRING_H #include <string.h> #endif #if HAVE_SCHED_H #include <sched.h> #endif #if HAVE_SYS_TIME_H #include <sys/time.h> #endif #if HAVE_UNISTD_H #include <unistd.h> #endif #if HAVE_TIME_H #include <time.h> #endif using namespace decaf; using namespace decaf::lang; using namespace decaf::lang::exceptions; using namespace decaf::util; using namespace decaf::util::concurrent; using namespace decaf::internal; using namespace decaf::internal::util; using namespace decaf::internal::util::concurrent; //////////////////////////////////////////////////////////////////////////////// void PlatformThread::createMutex(decaf_mutex_t* mutex) { *mutex = new pthread_mutex_t; if( pthread_mutex_init(*mutex, NULL) != 0 ) { throw RuntimeException( __FILE__, __LINE__, "Failed to create OS Mutex object." ); } } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::lockMutex(decaf_mutex_t mutex) { if (pthread_mutex_lock(mutex) != 0) { throw RuntimeException( __FILE__, __LINE__, "Failed to Lock OS Mutex" ); } } //////////////////////////////////////////////////////////////////////////////// bool PlatformThread::tryLockMutex(decaf_mutex_t mutex) { return pthread_mutex_trylock(mutex) == 0 ? true : false; } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::unlockMutex(decaf_mutex_t mutex) { if (pthread_mutex_unlock(mutex) != 0) { throw RuntimeException( __FILE__, __LINE__, "Failed to unlock OS Mutex" ); } } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::destroyMutex(decaf_mutex_t mutex) { pthread_mutex_destroy(mutex); delete mutex; } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::createRWMutex(decaf_rwmutex_t* mutex) { *mutex = new pthread_rwlock_t; if( pthread_rwlock_init(*mutex, NULL) != 0 ) { throw RuntimeException( __FILE__, __LINE__, "Failed to create OS Mutex object." ); } } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::readerLockMutex(decaf_rwmutex_t mutex) { if (pthread_rwlock_rdlock(mutex) != 0) { throw RuntimeException( __FILE__, __LINE__, "Failed to Lock OS RW Mutex" ); } } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::writerLockMutex(decaf_rwmutex_t mutex) { if (pthread_rwlock_wrlock(mutex) != 0) { throw RuntimeException( __FILE__, __LINE__, "Failed to Lock OS RW Mutex" ); } } //////////////////////////////////////////////////////////////////////////////// bool PlatformThread::tryReaderLockMutex(decaf_rwmutex_t mutex) { return pthread_rwlock_tryrdlock(mutex) == 0 ? true : false; } //////////////////////////////////////////////////////////////////////////////// bool PlatformThread::tryWriterLockMutex(decaf_rwmutex_t mutex) { return pthread_rwlock_trywrlock(mutex) == 0 ? true : false; } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::unlockRWMutex(decaf_rwmutex_t mutex) { if (pthread_rwlock_unlock(mutex) != 0) { throw RuntimeException( __FILE__, __LINE__, "Failed to Unlock OS RW Mutex" ); } } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::destroyRWMutex(decaf_rwmutex_t mutex) { pthread_rwlock_destroy(mutex); delete mutex; } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::createCondition(decaf_condition_t* condition) { *condition = new pthread_cond_t; if (pthread_cond_init(*condition, NULL) != 0) { throw RuntimeException( __FILE__, __LINE__, "Failed to initialize OS Condition object."); } } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::notify(decaf_condition_t condition) { pthread_cond_signal(condition); } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::notifyAll(decaf_condition_t condition) { pthread_cond_broadcast(condition); } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::waitOnCondition(decaf_condition_t condition, decaf_mutex_t mutex) { pthread_cond_wait(condition, mutex); } //////////////////////////////////////////////////////////////////////////////// bool PlatformThread::waitOnCondition(decaf_condition_t condition, decaf_mutex_t mutex, long long mills, int nanos) { struct timeval tv; gettimeofday( &tv, NULL ); long long timeNow = TimeUnit::SECONDS.toNanos( tv.tv_sec ) + TimeUnit::MICROSECONDS.toNanos( tv.tv_usec ); // Convert delay to nanoseconds and add it to now. long long delay = TimeUnit::MILLISECONDS.toNanos( mills ) + nanos + timeNow; struct timespec abstime; abstime.tv_sec = TimeUnit::NANOSECONDS.toSeconds( delay ); abstime.tv_nsec = delay % 1000000000; if (pthread_cond_timedwait(condition, mutex, &abstime) == ETIMEDOUT) { return true; } return false; } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::interruptibleWaitOnCondition(decaf_condition_t condition, decaf_mutex_t mutex, CompletionCondition& complete) { do { pthread_cond_wait(condition, mutex); if (complete()) { break; } } while(true); } //////////////////////////////////////////////////////////////////////////////// bool PlatformThread::interruptibleWaitOnCondition(decaf_condition_t condition, decaf_mutex_t mutex, long long mills, int nanos, CompletionCondition& complete) { struct timeval tv; gettimeofday( &tv, NULL ); long long timeNow = TimeUnit::SECONDS.toNanos( tv.tv_sec ) + TimeUnit::MICROSECONDS.toNanos( tv.tv_usec ); // Convert delay to nanoseconds and add it to now. long long delay = TimeUnit::MILLISECONDS.toNanos( mills ) + nanos + timeNow; struct timespec abstime; abstime.tv_sec = TimeUnit::NANOSECONDS.toSeconds( delay ); abstime.tv_nsec = delay % 1000000000; bool result = false; do { if (pthread_cond_timedwait(condition, mutex, &abstime) == ETIMEDOUT) { // interruption events take precedence over timeout. if (complete(true)) { break; } result = true; break; } // check if spurious wake or intentional. if (complete(false)) { break; } } while(true); return result; } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::destroyCondition(decaf_condition_t condition) { pthread_cond_destroy(condition); delete condition; } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::initPriorityMapping(int maxPriority, std::vector<int>& mapping) { int max = sched_get_priority_max(SCHED_OTHER); int min = sched_get_priority_min(SCHED_OTHER); if (max == min) { // get this thread's priority and use that for all threads. struct sched_param schedParam; int currPolicy; pthread_getschedparam(pthread_self(), &currPolicy, &schedParam); max = schedParam.sched_priority; min = max; } mapping.clear(); mapping.resize(maxPriority + 1); int tmpmax = max * 1024; int tmpmin = min * 1024; int mid = (tmpmin + tmpmax) / 2; int midrange = maxPriority / 2; mapping[0] = min; int delta = (mid - tmpmin) / midrange; for(int i = 1; i < midrange; i++) { mapping[midrange - i] = (mid - delta * i) / 1024; } int tailcount = maxPriority - midrange; delta = (tmpmax - mid) / tailcount; for(int i = 0; i < tailcount; i++) { mapping[midrange + i] = (mid + delta * i) / 1024; } mapping[maxPriority] = max; } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::createNewThread(decaf_thread_t* handle, threadMainMethod threadMain, void* threadArg, int priority, long long stackSize, long long* threadId) { pthread_attr_t attributes; struct sched_param schedData; pthread_attr_init( &attributes ); pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_JOINABLE); schedData.sched_priority = priority; if (pthread_attr_setschedparam(&attributes, &schedData) != 0) { throw RuntimeException(__FILE__, __LINE__, "Failed to set new Therad priority to value: %d", schedData.sched_priority); } if (stackSize != -1) { #ifdef LINUX if (stackSize < PTHREAD_STACK_MIN) { stackSize = PTHREAD_STACK_MIN; } #endif if (pthread_attr_setstacksize(&attributes, (size_t)stackSize) == EINVAL) { throw RuntimeException( __FILE__, __LINE__, "Failed to create new Thread due to invalid stack size setting: %d.", stackSize ); } } int result = pthread_create(handle, &attributes, threadMain, threadArg); *threadId = (long long)(&handle); pthread_attr_destroy( &attributes ); if( result != 0 ) { throw RuntimeException( __FILE__, __LINE__, "Failed to create new Thread." ); } } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::detachThread(decaf_thread_t handle) { pthread_detach(handle); } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::detachOSThread(decaf_thread_t handle DECAF_UNUSED) { // Nothing to do on Linux. } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::joinThread(decaf_thread_t handle) { void* theReturn = 0; pthread_join(handle, &theReturn); } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::exitThread() { int result = 0; pthread_exit(&result); } //////////////////////////////////////////////////////////////////////////////// decaf_thread_t PlatformThread::getCurrentThread() { return pthread_self(); } //////////////////////////////////////////////////////////////////////////////// decaf_thread_t PlatformThread::getSafeOSThreadHandle() { return pthread_self(); } //////////////////////////////////////////////////////////////////////////////// long long PlatformThread::getCurrentThreadId() { // pthread_t can be an int or struct or who knows so we use the address // of the value returned which seems to remain fixed. return (long long)&(pthread_self); } //////////////////////////////////////////////////////////////////////////////// int PlatformThread::getPriority(decaf_thread_t thread) { struct sched_param schedParam; int policy = SCHED_OTHER; pthread_getschedparam(thread, &policy, &schedParam); return schedParam.sched_priority; } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::setPriority(decaf_thread_t thread, int priority) { struct sched_param schedParam; schedParam.sched_priority = priority; pthread_setschedparam(thread, SCHED_OTHER, &schedParam); } //////////////////////////////////////////////////////////////////////////////// long long PlatformThread::getStackSize(decaf_thread_t thread DECAF_UNUSED) { pthread_attr_t attributes; pthread_attr_init( &attributes ); size_t stackSize; if (pthread_attr_getstacksize(&attributes, &stackSize) == EINVAL) { pthread_attr_destroy( &attributes ); throw RuntimeException( __FILE__, __LINE__, "Failed to get stack size setting."); } pthread_attr_destroy( &attributes ); return (long long)stackSize; } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::setStackSize(decaf_thread_t thread DECAF_UNUSED, long long stackSize) { pthread_attr_t attributes; pthread_attr_init( &attributes ); #ifdef LINUX if (stackSize < PTHREAD_STACK_MIN) { stackSize = PTHREAD_STACK_MIN; } #endif if (pthread_attr_setstacksize(&attributes, (size_t)stackSize) == EINVAL) { pthread_attr_destroy( &attributes ); throw RuntimeException( __FILE__, __LINE__, "Failed to set stack size setting: %d.", stackSize); } pthread_attr_destroy( &attributes ); } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::yeild() { #ifdef HAVE_PTHREAD_YIELD pthread_yield(); #else #ifdef HAVE_SCHED_YIELD sched_yield(); #endif #endif } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::createTlsKey(decaf_tls_key* tlsKey) { pthread_key_create(tlsKey, NULL); } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::destroyTlsKey(decaf_tls_key tlsKey) { pthread_key_delete(tlsKey); } //////////////////////////////////////////////////////////////////////////////// void* PlatformThread::getTlsValue(decaf_tls_key tlsKey) { return pthread_getspecific(tlsKey); } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::setTlsValue(decaf_tls_key tlsKey, void* value) { pthread_setspecific(tlsKey, value); }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <decaf/internal/util/concurrent/PlatformThread.h> #include <decaf/lang/exceptions/RuntimeException.h> #include <decaf/util/concurrent/TimeUnit.h> #include <memory> #if HAVE_ERRNO_H #include <errno.h> #endif #if HAVE_LIMITS_H #include <limits.h> #endif #if HAVE_PTHREAD_H #include <pthread.h> #endif #if HAVE_SIGNAL_H #include <signal.h> #endif #if HAVE_STRING_H #include <string.h> #endif #if HAVE_SCHED_H #include <sched.h> #endif #if HAVE_SYS_TIME_H #include <sys/time.h> #endif #if HAVE_UNISTD_H #include <unistd.h> #endif #if HAVE_TIME_H #include <time.h> #endif using namespace decaf; using namespace decaf::lang; using namespace decaf::lang::exceptions; using namespace decaf::util; using namespace decaf::util::concurrent; using namespace decaf::internal; using namespace decaf::internal::util; using namespace decaf::internal::util::concurrent; //////////////////////////////////////////////////////////////////////////////// void PlatformThread::createMutex(decaf_mutex_t* mutex) { *mutex = new pthread_mutex_t; if( pthread_mutex_init(*mutex, NULL) != 0 ) { throw RuntimeException( __FILE__, __LINE__, "Failed to create OS Mutex object." ); } } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::lockMutex(decaf_mutex_t mutex) { if (pthread_mutex_lock(mutex) != 0) { throw RuntimeException( __FILE__, __LINE__, "Failed to Lock OS Mutex" ); } } //////////////////////////////////////////////////////////////////////////////// bool PlatformThread::tryLockMutex(decaf_mutex_t mutex) { return pthread_mutex_trylock(mutex) == 0 ? true : false; } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::unlockMutex(decaf_mutex_t mutex) { if (pthread_mutex_unlock(mutex) != 0) { throw RuntimeException( __FILE__, __LINE__, "Failed to unlock OS Mutex" ); } } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::destroyMutex(decaf_mutex_t mutex) { pthread_mutex_destroy(mutex); delete mutex; } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::createRWMutex(decaf_rwmutex_t* mutex) { *mutex = new pthread_rwlock_t; if( pthread_rwlock_init(*mutex, NULL) != 0 ) { throw RuntimeException( __FILE__, __LINE__, "Failed to create OS Mutex object." ); } } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::readerLockMutex(decaf_rwmutex_t mutex) { if (pthread_rwlock_rdlock(mutex) != 0) { throw RuntimeException( __FILE__, __LINE__, "Failed to Lock OS RW Mutex" ); } } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::writerLockMutex(decaf_rwmutex_t mutex) { if (pthread_rwlock_wrlock(mutex) != 0) { throw RuntimeException( __FILE__, __LINE__, "Failed to Lock OS RW Mutex" ); } } //////////////////////////////////////////////////////////////////////////////// bool PlatformThread::tryReaderLockMutex(decaf_rwmutex_t mutex) { return pthread_rwlock_tryrdlock(mutex) == 0 ? true : false; } //////////////////////////////////////////////////////////////////////////////// bool PlatformThread::tryWriterLockMutex(decaf_rwmutex_t mutex) { return pthread_rwlock_trywrlock(mutex) == 0 ? true : false; } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::unlockRWMutex(decaf_rwmutex_t mutex) { if (pthread_rwlock_unlock(mutex) != 0) { throw RuntimeException( __FILE__, __LINE__, "Failed to Unlock OS RW Mutex" ); } } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::destroyRWMutex(decaf_rwmutex_t mutex) { pthread_rwlock_destroy(mutex); delete mutex; } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::createCondition(decaf_condition_t* condition) { *condition = new pthread_cond_t; if (pthread_cond_init(*condition, NULL) != 0) { throw RuntimeException( __FILE__, __LINE__, "Failed to initialize OS Condition object."); } } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::notify(decaf_condition_t condition) { pthread_cond_signal(condition); } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::notifyAll(decaf_condition_t condition) { pthread_cond_broadcast(condition); } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::waitOnCondition(decaf_condition_t condition, decaf_mutex_t mutex) { pthread_cond_wait(condition, mutex); } //////////////////////////////////////////////////////////////////////////////// bool PlatformThread::waitOnCondition(decaf_condition_t condition, decaf_mutex_t mutex, long long mills, int nanos) { struct timeval tv; gettimeofday( &tv, NULL ); long long timeNow = TimeUnit::SECONDS.toNanos( tv.tv_sec ) + TimeUnit::MICROSECONDS.toNanos( tv.tv_usec ); // Convert delay to nanoseconds and add it to now. long long delay = TimeUnit::MILLISECONDS.toNanos( mills ) + nanos + timeNow; struct timespec abstime; abstime.tv_sec = TimeUnit::NANOSECONDS.toSeconds( delay ); abstime.tv_nsec = delay % 1000000000; if (pthread_cond_timedwait(condition, mutex, &abstime) == ETIMEDOUT) { return true; } return false; } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::interruptibleWaitOnCondition(decaf_condition_t condition, decaf_mutex_t mutex, CompletionCondition& complete) { do { pthread_cond_wait(condition, mutex); if (complete()) { break; } } while(true); } //////////////////////////////////////////////////////////////////////////////// bool PlatformThread::interruptibleWaitOnCondition(decaf_condition_t condition, decaf_mutex_t mutex, long long mills, int nanos, CompletionCondition& complete) { struct timeval tv; gettimeofday( &tv, NULL ); long long timeNow = TimeUnit::SECONDS.toNanos( tv.tv_sec ) + TimeUnit::MICROSECONDS.toNanos( tv.tv_usec ); // Convert delay to nanoseconds and add it to now. long long delay = TimeUnit::MILLISECONDS.toNanos( mills ) + nanos + timeNow; struct timespec abstime; abstime.tv_sec = TimeUnit::NANOSECONDS.toSeconds( delay ); abstime.tv_nsec = delay % 1000000000; bool result = false; do { if (pthread_cond_timedwait(condition, mutex, &abstime) == ETIMEDOUT) { // interruption events take precedence over timeout. if (complete(true)) { break; } result = true; break; } // check if spurious wake or intentional. if (complete(false)) { break; } } while(true); return result; } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::destroyCondition(decaf_condition_t condition) { pthread_cond_destroy(condition); delete condition; } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::initPriorityMapping(int maxPriority, std::vector<int>& mapping) { int max = sched_get_priority_max(SCHED_OTHER); int min = sched_get_priority_min(SCHED_OTHER); if (max == min) { // get this thread's priority and use that for all threads. struct sched_param schedParam; int currPolicy; pthread_getschedparam(pthread_self(), &currPolicy, &schedParam); max = schedParam.sched_priority; min = max; } mapping.clear(); mapping.resize(maxPriority + 1); int tmpmax = max * 1024; int tmpmin = min * 1024; int mid = (tmpmin + tmpmax) / 2; int midrange = maxPriority / 2; mapping[0] = min; int delta = (mid - tmpmin) / midrange; for(int i = 1; i < midrange; i++) { mapping[midrange - i] = (mid - delta * i) / 1024; } int tailcount = maxPriority - midrange; delta = (tmpmax - mid) / tailcount; for(int i = 0; i < tailcount; i++) { mapping[midrange + i] = (mid + delta * i) / 1024; } mapping[maxPriority] = max; } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::createNewThread(decaf_thread_t* handle, threadMainMethod threadMain, void* threadArg, int priority, long long stackSize, long long* threadId) { pthread_attr_t attributes; int schedResult; int schedPolicy; schedResult = pthread_attr_init(&attributes); if (schedResult != 0) { throw RuntimeException(__FILE__, __LINE__, "Failed to initialize thread attribute, error value is: %d", schedResult); } schedResult = pthread_attr_getschedpolicy(&attributes, &schedPolicy); if (schedResult != 0) { throw RuntimeException(__FILE__, __LINE__, "Failed to get thread scheduling policy, error value is: %d.", schedResult); } // only set the priority if it's a policy that allows setting of the priority. if (SCHED_FIFO == schedPolicy || SCHED_RR == schedPolicy) { struct sched_param schedData; schedData.sched_priority = priority; schedResult = pthread_attr_setschedparam(&attributes, &schedData); if (schedResult != 0) { throw RuntimeException(__FILE__, __LINE__, "Failed to set new Thread priority to " "value: %d, error value is: %d.", schedData.sched_priority, schedResult); } } if (stackSize != -1) { #ifdef LINUX if (stackSize < PTHREAD_STACK_MIN) { stackSize = PTHREAD_STACK_MIN; } #endif if (pthread_attr_setstacksize(&attributes, (size_t)stackSize) == EINVAL) { throw RuntimeException( __FILE__, __LINE__, "Failed to create new Thread due to invalid stack size setting: %d.", stackSize); } } int result = pthread_create(handle, &attributes, threadMain, threadArg); *threadId = (long long)(&handle); pthread_attr_destroy(&attributes); if( result != 0 ) { throw RuntimeException( __FILE__, __LINE__, "Failed to create new Thread." ); } } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::detachThread(decaf_thread_t handle) { pthread_detach(handle); } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::detachOSThread(decaf_thread_t handle DECAF_UNUSED) { // Nothing to do on Linux. } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::joinThread(decaf_thread_t handle) { void* theReturn = 0; pthread_join(handle, &theReturn); } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::exitThread() { int result = 0; pthread_exit(&result); } //////////////////////////////////////////////////////////////////////////////// decaf_thread_t PlatformThread::getCurrentThread() { return pthread_self(); } //////////////////////////////////////////////////////////////////////////////// decaf_thread_t PlatformThread::getSafeOSThreadHandle() { return pthread_self(); } //////////////////////////////////////////////////////////////////////////////// long long PlatformThread::getCurrentThreadId() { // pthread_t can be an int or struct or who knows so we use the address // of the value returned which seems to remain fixed. return (long long)&(pthread_self); } //////////////////////////////////////////////////////////////////////////////// int PlatformThread::getPriority(decaf_thread_t thread) { struct sched_param schedParam; int policy = SCHED_OTHER; pthread_getschedparam(thread, &policy, &schedParam); return schedParam.sched_priority; } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::setPriority(decaf_thread_t thread, int priority) { struct sched_param schedParam; schedParam.sched_priority = priority; pthread_setschedparam(thread, SCHED_OTHER, &schedParam); } //////////////////////////////////////////////////////////////////////////////// long long PlatformThread::getStackSize(decaf_thread_t thread DECAF_UNUSED) { pthread_attr_t attributes; pthread_attr_init( &attributes ); size_t stackSize; if (pthread_attr_getstacksize(&attributes, &stackSize) == EINVAL) { pthread_attr_destroy( &attributes ); throw RuntimeException( __FILE__, __LINE__, "Failed to get stack size setting."); } pthread_attr_destroy( &attributes ); return (long long)stackSize; } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::setStackSize(decaf_thread_t thread DECAF_UNUSED, long long stackSize) { pthread_attr_t attributes; pthread_attr_init( &attributes ); #ifdef LINUX if (stackSize < PTHREAD_STACK_MIN) { stackSize = PTHREAD_STACK_MIN; } #endif if (pthread_attr_setstacksize(&attributes, (size_t)stackSize) == EINVAL) { pthread_attr_destroy( &attributes ); throw RuntimeException( __FILE__, __LINE__, "Failed to set stack size setting: %d.", stackSize); } pthread_attr_destroy( &attributes ); } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::yeild() { #ifdef HAVE_PTHREAD_YIELD pthread_yield(); #else #ifdef HAVE_SCHED_YIELD sched_yield(); #endif #endif } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::createTlsKey(decaf_tls_key* tlsKey) { pthread_key_create(tlsKey, NULL); } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::destroyTlsKey(decaf_tls_key tlsKey) { pthread_key_delete(tlsKey); } //////////////////////////////////////////////////////////////////////////////// void* PlatformThread::getTlsValue(decaf_tls_key tlsKey) { return pthread_getspecific(tlsKey); } //////////////////////////////////////////////////////////////////////////////// void PlatformThread::setTlsValue(decaf_tls_key tlsKey, void* value) { pthread_setspecific(tlsKey, value); }
fix for: https://issues.apache.org/jira/browse/AMQCPP-498
fix for: https://issues.apache.org/jira/browse/AMQCPP-498 git-svn-id: 0fb8a5a922afe2085ae9a967a0cf0864fe09ecff@1498612 13f79535-47bb-0310-9956-ffa450edef68
C++
apache-2.0
apache/activemq-cpp,apache/activemq-cpp,apache/activemq-cpp,apache/activemq-cpp
fef00615a48192090b3d7fe95a24f0e1d9944ed5
python/pythoninterpreter.cpp
python/pythoninterpreter.cpp
/*************************************************************************** * pythoninterpreter.cpp * This file is part of the KDE project * copyright (C)2004-2006 by Sebastian Sauer ([email protected]) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * You should have received a copy of the GNU Library General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. ***************************************************************************/ #include "pythoninterpreter.h" #include "pythonscript.h" #include "pythonmodule.h" //#include <kglobal.h> //#include <kstandarddirs.h> #if defined(Q_WS_WIN) #define PYPATHDELIMITER ";" #else #define PYPATHDELIMITER ":" #endif // The in krossconfig.h defined KROSS_EXPORT_INTERPRETER macro defines an // exported C function used as factory for Kross::PythonInterpreter instances. KROSS_EXPORT_INTERPRETER( Kross::PythonInterpreter ) using namespace Kross; namespace Kross { /// \internal class PythonInterpreterPrivate { public: /// The __main__ python module. PythonModule* mainmodule; PythonInterpreterPrivate() : mainmodule(0) {} }; } PythonInterpreter::PythonInterpreter(Kross::InterpreterInfo* info) : Kross::Interpreter(info) , d(new PythonInterpreterPrivate()) { // Initialize the python interpreter. initialize(); // Set name of the program. Py_SetProgramName(const_cast<char*>("Kross")); /* // Set arguments. //char* comm[0]; const char* comm = const_cast<char*>("kross"); // name. PySys_SetArgv(1, comm); */ // In the python sys.path are all module-directories are // listed in. QString path; // First import the sys-module to remember it's sys.path // list in our path QString. Py::Module sysmod( PyImport_ImportModule( (char*)"sys" ), true ); Py::Dict sysmoddict = sysmod.getDict(); Py::Object syspath = sysmoddict.getItem("path"); if(syspath.isList()) { Py::List syspathlist = syspath; for(Py::List::iterator it = syspathlist.begin(); it != syspathlist.end(); ++it) if( (*it).isString() ) path.append( QString(Py::String(*it).as_string().c_str()) + PYPATHDELIMITER ); } else path = Py_GetPath(); #if 0 // Determinate additional module-paths we like to add. // First add the global Kross modules-path. QStringList krossdirs = KGlobal::dirs()->findDirs("data", "kross/python"); for(QStringList::Iterator krossit = krossdirs.begin(); krossit != krossdirs.end(); ++krossit) path.append(*krossit + PYPATHDELIMITER); // Then add the application modules-path. QStringList appdirs = KGlobal::dirs()->findDirs("appdata", "kross/python"); for(QStringList::Iterator appit = appdirs.begin(); appit != appdirs.end(); ++appit) path.append(*appit + PYPATHDELIMITER); #endif // Set the extended sys.path. PySys_SetPath( (char*) path.toLatin1().data() ); #ifdef KROSS_PYTHON_INTERPRETER_DEBUG krossdebug(QString("Python ProgramName: %1").arg(Py_GetProgramName())); krossdebug(QString("Python ProgramFullPath: %1").arg(Py_GetProgramFullPath())); krossdebug(QString("Python Version: %1").arg(Py_GetVersion())); krossdebug(QString("Python Platform: %1").arg(Py_GetPlatform())); krossdebug(QString("Python Prefix: %1").arg(Py_GetPrefix())); krossdebug(QString("Python ExecPrefix: %1").arg(Py_GetExecPrefix())); //krossdebug(QString("Python Path: %1").arg(Py_GetPath())); //krossdebug(QString("Python System Path: %1").arg(path)); #endif // Initialize the main module. d->mainmodule = new PythonModule(this); // The main dictonary. Py::Dict moduledict = d->mainmodule->getDict(); //TODO moduledict["KrossPythonVersion"] = Py::Int(KROSS_PYTHON_VERSION); // Prepare the interpreter. QString s = //"# -*- coding: iso-8859-1 -*-\n" //"import locale\n" //"locale.setlocale(locale.LC_ALL, '')\n" //"# -*- coding: latin-1 -*\n" //"# -*- coding: utf-8 -*-\n" //"import locale\n" //"locale.setlocale(locale.LC_ALL, '')\n" //"from __future__ import absolute_import\n" "import sys\n" //"import os, os.path\n" //"sys.setdefaultencoding('latin-1')\n" // Dirty hack to get sys.argv defined. Needed for e.g. TKinter. "sys.argv = ['']\n" // On the try to read something from stdin always return an empty // string. That way such reads don't block our script. "try:\n" " import cStringIO\n" " sys.stdin = cStringIO.StringIO()\n" "except:\n" " pass\n" // Class to redirect something. We use this class e.g. to redirect // <stdout> and <stderr> to a c++ event. //"class Redirect:\n" //" def __init__(self, target):\n" //" self.target = target\n" //" def write(self, s):\n" //" self.target.call(s)\n" // Wrap builtin __import__ method. All import requests are // first redirected to our PythonModule.import method and // if the call returns None, then we call the original // python import mechanism. "import __builtin__\n" "import __main__\n" "sys.modules['_oldmain'] = sys.modules['__main__']\n" "class _Importer:\n" " def __init__(self, script):\n" " self.script = script\n" //" self.realImporter = __builtin__.__import__\n" //" __builtin__.__import__ = self._import\n" " self.realImporter = __main__.__builtin__.__import__\n" " __main__.__builtin__.__import__ = self._import\n" " def _import(self, name, globals=None, locals=None, fromlist=[]):\n" " try:\n" //" mod = __main__._import(self.script, name, globals, locals, [])\n" " mod = __main__._import(self.script, name, globals, locals, fromlist)\n" //" print \"1===========> _Importer name=%s fromlist=%s mod=%s\" % (name,fromlist,mod)\n" " if mod == None:\n" //" print \"2===========> _Importer name=%s fromlist=%s\" % (name,fromlist)\n" " mod = self.realImporter(name, globals, locals, fromlist)\n" " if mod != None:\n" //" print \"3===========> _Importer name=%s fromlist=%s\" % (name,fromlist)\n" " globals[name] = mod\n" " return mod\n" //" except ImportError:\n" " except:\n" " print \"9===========> _Importer Trying ImportError with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n" //" import karamba\n" " return None\n" /* " print \"_Importer name=%s fromlist=%s\" % (name,fromlist)\n" " if fromlist == None:\n" " mod = __main__._import(self.script, name, globals, locals, fromlist)\n" " if mod != None:\n" " print \"2===========> _Importer name=%s fromlist=%s\" % (name,fromlist)\n" " globals[name] = mod\n" " return mod\n" //" if name in sys.modules:\n" // hack to preserve module paths, needed e.g. for "import os.path" //" print \"3===========> _Importer name=%s fromlist=%s\" % (name,fromlist)\n" //" return sys.modules[name]\n" " print \"3===========> _Importer Trying realImporter with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n" " try:\n" " mod = self.realImporter(name, globals, locals, fromlist)\n" " print \"4===========> _Importer Trying realImporter with name=%s fromlist=%s insysmodules=%s module=%s\" % (name,fromlist,name in sys.modules,mod)\n" //" mod.__init__(name)\n" //" globals[name] = mod\n" //" sys.modules[name] = mod\n" " print \"5===========> _Importer Trying realImporter with name=%s fromlist=%s insysmodules=%s module=%s\" % (name,fromlist,name in sys.modules,mod)\n" " return mod\n" " except ImportError:\n" " print \"6===========> _Importer Trying ImportError with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n" " n = name.split('.')\n" " if len(n) >= 2:\n" " print \"7===========> _Importer Trying ImportError with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n" " m = self._import(\".\".join(n[:-1]),globals,locals,[n[-1],])\n" " print \"8===========> _Importer Trying ImportError with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n" " return self.realImporter(name, globals, locals, fromlist)\n" " print \"9===========> _Importer Trying ImportError with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n" " raise\n" */ ; PyObject* pyrun = PyRun_String(s.toLatin1().data(), Py_file_input, moduledict.ptr(), moduledict.ptr()); if(! pyrun) { Py::Object errobj = Py::value(Py::Exception()); // get last error setError( QString("Failed to prepare the __main__ module: %1").arg(errobj.as_string().c_str()) ); } Py_XDECREF(pyrun); // free the reference. } PythonInterpreter::~PythonInterpreter() { // Free the main module. delete d->mainmodule; d->mainmodule = 0; // Finalize the python interpreter. finalize(); // Delete the private d-pointer. delete d; } void PythonInterpreter::initialize() { // Initialize python. Py_Initialize(); /* Not needed cause we use the >= Python 2.3 GIL-mechanism. PyThreadState* d->globalthreadstate, d->threadstate; // First we have to initialize threading if python supports it. PyEval_InitThreads(); // The main thread. We don't use it later. d->globalthreadstate = PyThreadState_Swap(NULL); d->globalthreadstate = PyEval_SaveThread(); // We use an own sub-interpreter for each thread. d->threadstate = Py_NewInterpreter(); // Note that this application has multiple threads. // It maintains a separate interp (sub-interpreter) for each thread. PyThreadState_Swap(d->threadstate); // Work done, release the lock. PyEval_ReleaseLock(); */ } void PythonInterpreter::finalize() { /* Not needed cause we use the >= Python 2.3 GIL-mechanism. // Lock threads. PyEval_AcquireLock(); // Free the used thread. PyEval_ReleaseThread(d->threadstate); // Set back to rememberd main thread. PyThreadState_Swap(d->globalthreadstate); // Work done, unlock. PyEval_ReleaseLock(); */ // Finalize python. Py_Finalize(); } Kross::Script* PythonInterpreter::createScript(Kross::Action* Action) { //if(hadError()) return 0; return new PythonScript(this, Action); } PythonModule* PythonInterpreter::mainModule() const { return d->mainmodule; } void PythonInterpreter::extractException(QStringList& errorlist, int& lineno) { lineno = -1; PyObject *type, *value, *traceback; PyErr_Fetch(&type, &value, &traceback); Py_FlushLine(); PyErr_NormalizeException(&type, &value, &traceback); if(traceback) { Py::List tblist; try { Py::Module tbmodule( PyImport_Import(Py::String("traceback").ptr()), true ); Py::Dict tbdict = tbmodule.getDict(); Py::Callable tbfunc(tbdict.getItem("format_tb")); Py::Tuple args(1); args.setItem(0, Py::Object(traceback)); tblist = tbfunc.apply(args); uint length = tblist.length(); for(Py::List::size_type i = 0; i < length; ++i) errorlist.append( Py::Object(tblist[i]).as_string().c_str() ); } catch(Py::Exception& e) { QString err = Py::value(e).as_string().c_str(); e.clear(); // exception is handled. clear it now. krosswarning( QString("Kross::PythonScript::toException() Failed to fetch a traceback: %1").arg(err) ); } PyObject *next; while (traceback && traceback != Py_None) { PyFrameObject *frame = (PyFrameObject*)PyObject_GetAttrString(traceback, const_cast< char* >("tb_frame")); Py_DECREF(frame); { PyObject *getobj = PyObject_GetAttrString(traceback, const_cast< char* >("tb_lineno") ); lineno = PyInt_AsLong(getobj); Py_DECREF(getobj); } if(Py_OptimizeFlag) { PyObject *getobj = PyObject_GetAttrString(traceback, const_cast< char* >("tb_lasti") ); int lasti = PyInt_AsLong(getobj); Py_DECREF(getobj); lineno = PyCode_Addr2Line(frame->f_code, lasti); } //const char* filename = PyString_AsString(frame->f_code->co_filename); //const char* name = PyString_AsString(frame->f_code->co_name); //errorlist.append( QString("%1#%2: \"%3\"").arg(filename).arg(lineno).arg(name) ); next = PyObject_GetAttrString(traceback, const_cast< char* >("tb_next") ); Py_DECREF(traceback); traceback = next; } } if(lineno < 0 && value && PyObject_HasAttrString(value, const_cast< char* >("lineno"))) { PyObject *getobj = PyObject_GetAttrString(value, const_cast< char* >("lineno") ); if(getobj) { lineno = PyInt_AsLong(getobj); Py_DECREF(getobj); } } krossdebug( QString("PythonInterpreter::extractException: %1").arg( Py::Object(value).as_string().c_str() ) ); PyErr_Restore(type, value, traceback); }
/*************************************************************************** * pythoninterpreter.cpp * This file is part of the KDE project * copyright (C)2004-2006 by Sebastian Sauer ([email protected]) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * You should have received a copy of the GNU Library General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. ***************************************************************************/ #include "pythoninterpreter.h" #include "pythonscript.h" #include "pythonmodule.h" //#include <kglobal.h> //#include <kstandarddirs.h> #if defined(Q_WS_WIN) #define PYPATHDELIMITER ";" #else #define PYPATHDELIMITER ":" #endif // The in krossconfig.h defined KROSS_EXPORT_INTERPRETER macro defines an // exported C function used as factory for Kross::PythonInterpreter instances. KROSS_EXPORT_INTERPRETER( Kross::PythonInterpreter ) using namespace Kross; namespace Kross { /// \internal class PythonInterpreterPrivate { public: /// The __main__ python module. PythonModule* mainmodule; PythonInterpreterPrivate() : mainmodule(0) {} }; } PythonInterpreter::PythonInterpreter(Kross::InterpreterInfo* info) : Kross::Interpreter(info) , d(new PythonInterpreterPrivate()) { // Initialize the python interpreter. initialize(); // Set name of the program. Py_SetProgramName(const_cast<char*>("Kross")); /* // Set arguments. //char* comm[0]; const char* comm = const_cast<char*>("kross"); // name. PySys_SetArgv(1, comm); */ // In the python sys.path are all module-directories are // listed in. QString path; // First import the sys-module to remember it's sys.path // list in our path QString. Py::Module sysmod( PyImport_ImportModule( (char*)"sys" ), true ); Py::Dict sysmoddict = sysmod.getDict(); Py::Object syspath = sysmoddict.getItem("path"); if(syspath.isList()) { Py::List syspathlist = syspath; for(Py::List::iterator it = syspathlist.begin(); it != syspathlist.end(); ++it) if( (*it).isString() ) path.append( QString(Py::String(*it).as_string().c_str()) + PYPATHDELIMITER ); } else path = Py_GetPath(); #if 0 // Determinate additional module-paths we like to add. // First add the global Kross modules-path. QStringList krossdirs = KGlobal::dirs()->findDirs("data", "kross/python"); for(QStringList::Iterator krossit = krossdirs.begin(); krossit != krossdirs.end(); ++krossit) path.append(*krossit + PYPATHDELIMITER); // Then add the application modules-path. QStringList appdirs = KGlobal::dirs()->findDirs("appdata", "kross/python"); for(QStringList::Iterator appit = appdirs.begin(); appit != appdirs.end(); ++appit) path.append(*appit + PYPATHDELIMITER); #endif // Set the extended sys.path. PySys_SetPath( (char*) path.toLatin1().data() ); #ifdef KROSS_PYTHON_INTERPRETER_DEBUG krossdebug(QString("Python ProgramName: %1").arg(Py_GetProgramName())); krossdebug(QString("Python ProgramFullPath: %1").arg(Py_GetProgramFullPath())); krossdebug(QString("Python Version: %1").arg(Py_GetVersion())); krossdebug(QString("Python Platform: %1").arg(Py_GetPlatform())); krossdebug(QString("Python Prefix: %1").arg(Py_GetPrefix())); krossdebug(QString("Python ExecPrefix: %1").arg(Py_GetExecPrefix())); //krossdebug(QString("Python Path: %1").arg(Py_GetPath())); //krossdebug(QString("Python System Path: %1").arg(path)); #endif // Initialize the main module. d->mainmodule = new PythonModule(this); // The main dictonary. Py::Dict moduledict = d->mainmodule->getDict(); //TODO moduledict["KrossPythonVersion"] = Py::Int(KROSS_PYTHON_VERSION); // Prepare the interpreter. QString s = //"# -*- coding: iso-8859-1 -*-\n" //"import locale\n" //"locale.setlocale(locale.LC_ALL, '')\n" //"# -*- coding: latin-1 -*\n" //"# -*- coding: utf-8 -*-\n" //"import locale\n" //"locale.setlocale(locale.LC_ALL, '')\n" //"from __future__ import absolute_import\n" "import sys\n" //"import os, os.path\n" //"sys.setdefaultencoding('latin-1')\n" // Dirty hack to get sys.argv defined. Needed for e.g. TKinter. "sys.argv = ['']\n" // On the try to read something from stdin always return an empty // string. That way such reads don't block our script. "try:\n" " import cStringIO\n" " sys.stdin = cStringIO.StringIO()\n" "except:\n" " pass\n" // Class to redirect something. We use this class e.g. to redirect // <stdout> and <stderr> to a c++ event. //"class Redirect:\n" //" def __init__(self, target):\n" //" self.target = target\n" //" def write(self, s):\n" //" self.target.call(s)\n" // Wrap builtin __import__ method. All import requests are // first redirected to our PythonModule.import method and // if the call returns None, then we call the original // python import mechanism. "import __builtin__\n" "import __main__\n" "import traceback\n" "sys.modules['_oldmain'] = sys.modules['__main__']\n" "class _Importer:\n" " def __init__(self, script):\n" " self.script = script\n" " self.realImporter = __main__.__builtin__.__import__\n" " __main__.__builtin__.__import__ = self._import\n" " def _import(self, name, globals=None, locals=None, fromlist=[]):\n" " try:\n" //" print \"1===========> _Importer name=%s fromlist=%s\" % (name,fromlist)\n" " mod = __main__._import(self.script, name, globals, locals, fromlist)\n" " if mod == None:\n" //" print \"2===========> _Importer name=%s fromlist=%s\" % (name,fromlist)\n" " mod = self.realImporter(name, globals, locals, fromlist)\n" " if mod != None:\n" //" print \"3===========> _Importer name=%s fromlist=%s\" % (name,fromlist)\n" " globals[name] = mod\n" " return mod\n" //" except ImportError:\n" " except:\n" " print \"9===========> _Importer Trying ImportError with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n" " print \" \".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) )\n" " return None\n" /* " print \"_Importer name=%s fromlist=%s\" % (name,fromlist)\n" " if fromlist == None:\n" " mod = __main__._import(self.script, name, globals, locals, fromlist)\n" " if mod != None:\n" " print \"2===========> _Importer name=%s fromlist=%s\" % (name,fromlist)\n" " globals[name] = mod\n" " return mod\n" //" if name in sys.modules:\n" // hack to preserve module paths, needed e.g. for "import os.path" //" print \"3===========> _Importer name=%s fromlist=%s\" % (name,fromlist)\n" //" return sys.modules[name]\n" " print \"3===========> _Importer Trying realImporter with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n" " try:\n" " mod = self.realImporter(name, globals, locals, fromlist)\n" " print \"4===========> _Importer Trying realImporter with name=%s fromlist=%s insysmodules=%s module=%s\" % (name,fromlist,name in sys.modules,mod)\n" //" mod.__init__(name)\n" //" globals[name] = mod\n" //" sys.modules[name] = mod\n" " print \"5===========> _Importer Trying realImporter with name=%s fromlist=%s insysmodules=%s module=%s\" % (name,fromlist,name in sys.modules,mod)\n" " return mod\n" " except ImportError:\n" " print \"6===========> _Importer Trying ImportError with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n" " n = name.split('.')\n" " if len(n) >= 2:\n" " print \"7===========> _Importer Trying ImportError with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n" " m = self._import(\".\".join(n[:-1]),globals,locals,[n[-1],])\n" " print \"8===========> _Importer Trying ImportError with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n" " return self.realImporter(name, globals, locals, fromlist)\n" " print \"9===========> _Importer Trying ImportError with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n" " raise\n" */ ; PyObject* pyrun = PyRun_String(s.toLatin1().data(), Py_file_input, moduledict.ptr(), moduledict.ptr()); if(! pyrun) { Py::Object errobj = Py::value(Py::Exception()); // get last error setError( QString("Failed to prepare the __main__ module: %1").arg(errobj.as_string().c_str()) ); } Py_XDECREF(pyrun); // free the reference. } PythonInterpreter::~PythonInterpreter() { // Free the main module. delete d->mainmodule; d->mainmodule = 0; // Finalize the python interpreter. finalize(); // Delete the private d-pointer. delete d; } void PythonInterpreter::initialize() { // Initialize python. Py_Initialize(); /* Not needed cause we use the >= Python 2.3 GIL-mechanism. PyThreadState* d->globalthreadstate, d->threadstate; // First we have to initialize threading if python supports it. PyEval_InitThreads(); // The main thread. We don't use it later. d->globalthreadstate = PyThreadState_Swap(NULL); d->globalthreadstate = PyEval_SaveThread(); // We use an own sub-interpreter for each thread. d->threadstate = Py_NewInterpreter(); // Note that this application has multiple threads. // It maintains a separate interp (sub-interpreter) for each thread. PyThreadState_Swap(d->threadstate); // Work done, release the lock. PyEval_ReleaseLock(); */ } void PythonInterpreter::finalize() { /* Not needed cause we use the >= Python 2.3 GIL-mechanism. // Lock threads. PyEval_AcquireLock(); // Free the used thread. PyEval_ReleaseThread(d->threadstate); // Set back to rememberd main thread. PyThreadState_Swap(d->globalthreadstate); // Work done, unlock. PyEval_ReleaseLock(); */ // Finalize python. Py_Finalize(); } Kross::Script* PythonInterpreter::createScript(Kross::Action* Action) { //if(hadError()) return 0; return new PythonScript(this, Action); } PythonModule* PythonInterpreter::mainModule() const { return d->mainmodule; } void PythonInterpreter::extractException(QStringList& errorlist, int& lineno) { lineno = -1; PyObject *type, *value, *traceback; PyErr_Fetch(&type, &value, &traceback); Py_FlushLine(); PyErr_NormalizeException(&type, &value, &traceback); if(traceback) { Py::List tblist; try { Py::Module tbmodule( PyImport_Import(Py::String("traceback").ptr()), true ); Py::Dict tbdict = tbmodule.getDict(); Py::Callable tbfunc(tbdict.getItem("format_tb")); Py::Tuple args(1); args.setItem(0, Py::Object(traceback)); tblist = tbfunc.apply(args); uint length = tblist.length(); for(Py::List::size_type i = 0; i < length; ++i) errorlist.append( Py::Object(tblist[i]).as_string().c_str() ); } catch(Py::Exception& e) { QString err = Py::value(e).as_string().c_str(); e.clear(); // exception is handled. clear it now. krosswarning( QString("Kross::PythonScript::toException() Failed to fetch a traceback: %1").arg(err) ); } PyObject *next; while (traceback && traceback != Py_None) { PyFrameObject *frame = (PyFrameObject*)PyObject_GetAttrString(traceback, const_cast< char* >("tb_frame")); Py_DECREF(frame); { PyObject *getobj = PyObject_GetAttrString(traceback, const_cast< char* >("tb_lineno") ); lineno = PyInt_AsLong(getobj); Py_DECREF(getobj); } if(Py_OptimizeFlag) { PyObject *getobj = PyObject_GetAttrString(traceback, const_cast< char* >("tb_lasti") ); int lasti = PyInt_AsLong(getobj); Py_DECREF(getobj); lineno = PyCode_Addr2Line(frame->f_code, lasti); } //const char* filename = PyString_AsString(frame->f_code->co_filename); //const char* name = PyString_AsString(frame->f_code->co_name); //errorlist.append( QString("%1#%2: \"%3\"").arg(filename).arg(lineno).arg(name) ); next = PyObject_GetAttrString(traceback, const_cast< char* >("tb_next") ); Py_DECREF(traceback); traceback = next; } } if(lineno < 0 && value && PyObject_HasAttrString(value, const_cast< char* >("lineno"))) { PyObject *getobj = PyObject_GetAttrString(value, const_cast< char* >("lineno") ); if(getobj) { lineno = PyInt_AsLong(getobj); Py_DECREF(getobj); } } krossdebug( QString("PythonInterpreter::extractException: %1").arg( Py::Object(value).as_string().c_str() ) ); PyErr_Restore(type, value, traceback); }
print traceback on import-exception
print traceback on import-exception svn path=/trunk/KDE/kdebindings/python/krosspython/; revision=661838
C++
lgpl-2.1
KDE/kross-interpreters,KDE/kross-interpreters,KDE/kross-interpreters,KDE/kross-interpreters,KDE/kross-interpreters,KDE/kross-interpreters
5e2f85df8aa535127a8d960c70098b72fc8e4ad6
o3d/utils/cross/text_writer.cc
o3d/utils/cross/text_writer.cc
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // This file contains the definition of class TextWriter. The // tests are in string_writer_test.cc. #include <stdarg.h> #include "utils/cross/text_writer.h" #include "base/string_util.h" #include "base/stringprintf.h" using std::string; namespace o3d { TextWriter::TextWriter(NewLine new_line) : new_line_(new_line) { } TextWriter::~TextWriter() { } void TextWriter::WriteString(const string& s) { for (size_t i = 0; i != s.length(); ++i) { WriteChar(s[i]); } } void TextWriter::WriteBool(bool value) { if (value) { WriteString(string("true")); } else { WriteString(string("false")); } } void TextWriter::WriteInt(int value) { WriteString(StringPrintf("%d", value)); } void TextWriter::WriteUnsignedInt(unsigned int value) { WriteString(StringPrintf("%u", value)); } void TextWriter::WriteFloat(float value) { WriteString(StringPrintf("%g", value)); } void TextWriter::WriteFormatted(const char* format, ...) { va_list args; va_start(args, format); string formatted; base::StringAppendV(&formatted, format, args); va_end(args); WriteString(formatted); } void TextWriter::WriteNewLine() { switch (new_line_) { case CR: WriteChar('\r'); break; case CR_LF: WriteChar('\r'); WriteChar('\n'); break; case LF: WriteChar('\n'); break; } } void TextWriter::Close() { } } // namespace o3d
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // This file contains the definition of class TextWriter. The // tests are in string_writer_test.cc. #include <stdarg.h> #include "utils/cross/text_writer.h" #include "base/string_util.h" using std::string; namespace o3d { TextWriter::TextWriter(NewLine new_line) : new_line_(new_line) { } TextWriter::~TextWriter() { } void TextWriter::WriteString(const string& s) { for (size_t i = 0; i != s.length(); ++i) { WriteChar(s[i]); } } void TextWriter::WriteBool(bool value) { if (value) { WriteString(string("true")); } else { WriteString(string("false")); } } void TextWriter::WriteInt(int value) { WriteString(StringPrintf("%d", value)); } void TextWriter::WriteUnsignedInt(unsigned int value) { WriteString(StringPrintf("%u", value)); } void TextWriter::WriteFloat(float value) { WriteString(StringPrintf("%g", value)); } void TextWriter::WriteFormatted(const char* format, ...) { va_list args; va_start(args, format); string formatted; StringAppendV(&formatted, format, args); va_end(args); WriteString(formatted); } void TextWriter::WriteNewLine() { switch (new_line_) { case CR: WriteChar('\r'); break; case CR_LF: WriteChar('\r'); WriteChar('\n'); break; case LF: WriteChar('\n'); break; } } void TextWriter::Close() { } } // namespace o3d
Fix o3d build.
o3d: Fix o3d build. This reverts the changes did on http://src.chromium.org/viewvc/chrome?view=rev&revision=69785 BUG=None TEST=None Review URL: http://codereview.chromium.org/5970006 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@69793 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
dushu1203/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,dednal/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,dushu1203/chromium.src,hujiajie/pa-chromium,axinging/chromium-crosswalk,Just-D/chromium-1,hujiajie/pa-chromium,axinging/chromium-crosswalk,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,ChromiumWebApps/chromium,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,keishi/chromium,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,Just-D/chromium-1,robclark/chromium,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,ondra-novak/chromium.src,anirudhSK/chromium,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,M4sse/chromium.src,axinging/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,chuan9/chromium-crosswalk,ondra-novak/chromium.src,ChromiumWebApps/chromium,Just-D/chromium-1,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,markYoungH/chromium.src,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,rogerwang/chromium,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,M4sse/chromium.src,keishi/chromium,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,Chilledheart/chromium,M4sse/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,rogerwang/chromium,keishi/chromium,dednal/chromium.src,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,nacl-webkit/chrome_deps,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,chuan9/chromium-crosswalk,M4sse/chromium.src,dednal/chromium.src,keishi/chromium,bright-sparks/chromium-spacewalk,dednal/chromium.src,ondra-novak/chromium.src,ltilve/chromium,Just-D/chromium-1,dednal/chromium.src,ltilve/chromium,hujiajie/pa-chromium,dednal/chromium.src,dednal/chromium.src,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,rogerwang/chromium,keishi/chromium,dednal/chromium.src,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,dednal/chromium.src,zcbenz/cefode-chromium,keishi/chromium,Just-D/chromium-1,nacl-webkit/chrome_deps,Pluto-tv/chromium-crosswalk,junmin-zhu/chromium-rivertrail,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,keishi/chromium,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,jaruba/chromium.src,robclark/chromium,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,M4sse/chromium.src,dushu1203/chromium.src,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,jaruba/chromium.src,Chilledheart/chromium,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,keishi/chromium,nacl-webkit/chrome_deps,anirudhSK/chromium,dushu1203/chromium.src,Chilledheart/chromium,markYoungH/chromium.src,hgl888/chromium-crosswalk,rogerwang/chromium,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,littlstar/chromium.src,ChromiumWebApps/chromium,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,chuan9/chromium-crosswalk,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,patrickm/chromium.src,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,jaruba/chromium.src,littlstar/chromium.src,M4sse/chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,patrickm/chromium.src,littlstar/chromium.src,timopulkkinen/BubbleFish,littlstar/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,rogerwang/chromium,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,nacl-webkit/chrome_deps,robclark/chromium,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,patrickm/chromium.src,littlstar/chromium.src,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,markYoungH/chromium.src,keishi/chromium,Chilledheart/chromium,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,anirudhSK/chromium,Jonekee/chromium.src,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,dednal/chromium.src,robclark/chromium,keishi/chromium,fujunwei/chromium-crosswalk,Just-D/chromium-1,bright-sparks/chromium-spacewalk,anirudhSK/chromium,axinging/chromium-crosswalk,ondra-novak/chromium.src,littlstar/chromium.src,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,littlstar/chromium.src,dushu1203/chromium.src,zcbenz/cefode-chromium,anirudhSK/chromium,keishi/chromium,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,anirudhSK/chromium,mogoweb/chromium-crosswalk,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,krieger-od/nwjs_chromium.src,Chilledheart/chromium,dushu1203/chromium.src,littlstar/chromium.src,jaruba/chromium.src,ltilve/chromium,ltilve/chromium,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,dushu1203/chromium.src,robclark/chromium,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,rogerwang/chromium,nacl-webkit/chrome_deps,patrickm/chromium.src,ltilve/chromium,ondra-novak/chromium.src,Chilledheart/chromium,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,patrickm/chromium.src,timopulkkinen/BubbleFish,hujiajie/pa-chromium,ltilve/chromium,ltilve/chromium,rogerwang/chromium,dushu1203/chromium.src,jaruba/chromium.src,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,Jonekee/chromium.src,timopulkkinen/BubbleFish,M4sse/chromium.src,jaruba/chromium.src,ltilve/chromium,patrickm/chromium.src,ChromiumWebApps/chromium,robclark/chromium,nacl-webkit/chrome_deps,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,rogerwang/chromium,robclark/chromium,Chilledheart/chromium,robclark/chromium,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,robclark/chromium,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,rogerwang/chromium,hujiajie/pa-chromium,anirudhSK/chromium,robclark/chromium,Just-D/chromium-1,dednal/chromium.src,rogerwang/chromium,anirudhSK/chromium
5e8f2b33712647290ea03206174e61c2a2a2a408
objects/RemotePyDictObject.cpp
objects/RemotePyDictObject.cpp
#include "RemotePyDictObject.h" #include "objects.h" #include "utils/ExtHelpers.h" #include <engextcpp.hpp> #include <memory> #include <string> #include <sstream> #include <iomanip> #include <stdexcept> #include <utility> using namespace std; RemotePyDictObject::RemotePyDictObject(Offset objectAddress) : RemotePyObject(objectAddress, "PyDictObject") { } namespace { auto getEntriesTable(ExtRemoteTyped dictObj) -> ExtRemoteTyped { // Python 2 stores a pointer to the entries table right in `ma_table`. if (dictObj.HasField("ma_table")) return dictObj.Field("ma_table"); // Python <= 3.5 stores a pointer to the entries table in `ma_keys->dk_entries`. auto keys = dictObj.Field("ma_keys"); if (keys.HasField("dk_entries")) return keys.Field("dk_entries"); // Python 3.6 uses a "compact" layout where the entries appear after the `ma_keys->dk_indices` table. auto sizeField = keys.Field("dk_size"); auto size = utils::readIntegral<RemotePyObject::SSize>(sizeField); auto pointerSize = static_cast<int>(keys.GetPointerTo().GetTypeSize()); int indexSize = 0; if (size <= 0xff) { indexSize = 1; } else if (size <= 0xffff) { indexSize = 2; } else if (size <= 0xffffffff) { indexSize = 4; } else { indexSize = pointerSize; } auto entriesPtr = keys.Field("dk_indices").Field("as_1").GetPtr() + (size * indexSize); return ExtRemoteTyped("PyDictKeyEntry", entriesPtr, true); } auto getEntriesTableSize(ExtRemoteTyped dictObj) -> RemotePyObject::SSize { // Python 2. if (dictObj.HasField("ma_mask")) { auto mask = dictObj.Field("ma_mask"); return utils::readIntegral<RemotePyObject::SSize>(mask); } // Python 3. auto keys = dictObj.Field("ma_keys"); auto values = dictObj.Field("ma_values"); bool isCombined = (values.GetPtr() == 0); if (isCombined) { auto used = dictObj.Field("ma_used"); return utils::readIntegral<RemotePyObject::SSize>(used); } else { auto numEntriesField = keys.Field("dk_nentries"); return utils::readIntegral<RemotePyObject::SSize>(numEntriesField); } } auto getIsCombined(ExtRemoteTyped dictObj) -> bool { // Python 2 tables always act like Python 3 "combined" tables. if (dictObj.HasField("ma_mask")) { return true; } // Python 3. auto valuesPtr = dictObj.Field("ma_values").GetPtr(); return (valuesPtr == 0); } } auto RemotePyDictObject::pairValues() const -> vector<pair<unique_ptr<RemotePyObject>, unique_ptr<RemotePyObject>>> { vector<pair<unique_ptr<RemotePyObject>, unique_ptr<RemotePyObject>>> pairs; auto table = getEntriesTable(remoteObj()); const auto tableSize = getEntriesTableSize(remoteObj()); const bool isCombined = getIsCombined(remoteObj()); for (SSize i = 0; i <= tableSize; ++i) { auto dictEntry = table.ArrayElement(i); auto keyPtr = dictEntry.Field("me_key").GetPtr(); auto valuePtr = (isCombined) ? dictEntry.Field("me_value").GetPtr() : remoteObj().Field("ma_values").ArrayElement(i).GetPtr(); if (keyPtr == 0 || valuePtr == 0) //< The hash bucket might be empty. continue; auto key = makeRemotePyObject(keyPtr); auto value = makeRemotePyObject(valuePtr); pairs.push_back(make_pair(move(key), move(value))); } return pairs; } auto RemotePyDictObject::repr(bool pretty) const -> string { const auto elementSeparator = (pretty) ? "\n" : " "; //< Use a newline when pretty-print is on. const auto indentation = (pretty) ? "\t" : ""; //< Indent only when pretty is on. ostringstream oss; oss << '{' << elementSeparator; for (auto& pairValue : pairValues()) { //< TODO: Structured bindings. for (auto&& [key, value] : pairValues) { auto& key = pairValue.first; auto& value = pairValue.second; oss << indentation << key->repr(pretty) << ": " << value->repr(pretty) << ',' << elementSeparator; } oss << elementSeparator << '}'; return oss.str(); }
#include "RemotePyDictObject.h" #include "objects.h" #include "utils/ExtHelpers.h" #include <engextcpp.hpp> #include <memory> #include <string> #include <sstream> #include <iomanip> #include <stdexcept> #include <utility> using namespace std; RemotePyDictObject::RemotePyDictObject(Offset objectAddress) : RemotePyObject(objectAddress, "PyDictObject") { } namespace { auto getEntriesTable(ExtRemoteTyped dictObj) -> ExtRemoteTyped { // Python 2 stores a pointer to the entries table right in `ma_table`. if (dictObj.HasField("ma_table")) return dictObj.Field("ma_table"); // Python <= 3.5 stores a pointer to the entries table in `ma_keys->dk_entries`. auto keys = dictObj.Field("ma_keys"); if (keys.HasField("dk_entries")) return keys.Field("dk_entries"); // Python 3.6 uses a "compact" layout where the entries appear after the `ma_keys->dk_indices` table. auto sizeField = keys.Field("dk_size"); auto size = utils::readIntegral<RemotePyObject::SSize>(sizeField); auto pointerSize = static_cast<int>(keys.GetPointerTo().GetTypeSize()); int indexSize = 0; if (size <= 0xff) { indexSize = 1; } else if (size <= 0xffff) { indexSize = 2; } else if (size <= 0xffffffff) { indexSize = 4; } else { indexSize = pointerSize; } auto entriesPtr = keys.Field("dk_indices").Field("as_1").GetPtr() + (size * indexSize); return ExtRemoteTyped("PyDictKeyEntry", entriesPtr, true); } auto getEntriesTableSize(ExtRemoteTyped dictObj) -> RemotePyObject::SSize { // Python 2. if (dictObj.HasField("ma_mask")) { // Mask is table size (a power of 2) minus 1. auto mask = dictObj.Field("ma_mask"); return utils::readIntegral<RemotePyObject::SSize>(mask) + 1; } // Python 3. auto numEntriesField = dictObj.Field("ma_keys").Field("dk_nentries"); return utils::readIntegral<RemotePyObject::SSize>(numEntriesField); } auto getIsCombined(ExtRemoteTyped dictObj) -> bool { // Python 2 tables always act like Python 3 "combined" tables. if (dictObj.HasField("ma_mask")) { return true; } // Python 3. auto valuesPtr = dictObj.Field("ma_values").GetPtr(); return (valuesPtr == 0); } } auto RemotePyDictObject::pairValues() const -> vector<pair<unique_ptr<RemotePyObject>, unique_ptr<RemotePyObject>>> { vector<pair<unique_ptr<RemotePyObject>, unique_ptr<RemotePyObject>>> pairs; auto table = getEntriesTable(remoteObj()); const auto tableSize = getEntriesTableSize(remoteObj()); const bool isCombined = getIsCombined(remoteObj()); for (SSize i = 0; i < tableSize; ++i) { auto dictEntry = table.ArrayElement(i); auto keyPtr = dictEntry.Field("me_key").GetPtr(); auto valuePtr = (isCombined) ? dictEntry.Field("me_value").GetPtr() : remoteObj().Field("ma_values").ArrayElement(i).GetPtr(); if (keyPtr == 0 || valuePtr == 0) //< The hash bucket might be empty. continue; auto key = makeRemotePyObject(keyPtr); auto value = makeRemotePyObject(valuePtr); pairs.push_back(make_pair(move(key), move(value))); } return pairs; } auto RemotePyDictObject::repr(bool pretty) const -> string { const auto elementSeparator = (pretty) ? "\n" : " "; //< Use a newline when pretty-print is on. const auto indentation = (pretty) ? "\t" : ""; //< Indent only when pretty is on. ostringstream oss; oss << '{' << elementSeparator; for (auto& pairValue : pairValues()) { //< TODO: Structured bindings. for (auto&& [key, value] : pairValues) { auto& key = pairValue.first; auto& value = pairValue.second; oss << indentation << key->repr(pretty) << ": " << value->repr(pretty) << ',' << elementSeparator; } oss << elementSeparator << '}'; return oss.str(); }
Correct a couple issues using the wrong index when iterating over `PyDictObject`s.
Correct a couple issues using the wrong index when iterating over `PyDictObject`s.
C++
mit
SeanCline/PyExt,SeanCline/PyExt,SeanCline/PyExt
c3902d7a8a3e9c0e24f63572ba1e7a55f981ae76
vlcplugin.cpp
vlcplugin.cpp
/***************************************************************************** * vlcplugin.cpp: a VLC plugin for Mozilla ***************************************************************************** * Copyright (C) 2002-2005 the VideoLAN team * $Id$ * * Authors: Samuel Hocevar <[email protected]> * Damien Fouilleul <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ /***************************************************************************** * Preamble *****************************************************************************/ #include "config.h" #ifdef HAVE_MOZILLA_CONFIG_H # include <mozilla-config.h> #endif #include "vlcplugin.h" #include "control/npovlc.h" #include "control/npolibvlc.h" #include <ctype.h> /***************************************************************************** * VlcPlugin constructor and destructor *****************************************************************************/ VlcPlugin::VlcPlugin( NPP instance, uint16 mode ) : i_npmode(mode), b_stream(0), b_autoplay(1), psz_target(NULL), libvlc_instance(NULL), libvlc_log(NULL), p_scriptClass(NULL), p_browser(instance), psz_baseURL(NULL) #if XP_WIN ,pf_wndproc(NULL) #endif #if XP_UNIX ,i_width((unsigned)-1) ,i_height((unsigned)-1) #endif { memset(&npwindow, 0, sizeof(NPWindow)); } static bool boolValue(const char *value) { return ( !strcmp(value, "1") || !strcasecmp(value, "true") || !strcasecmp(value, "yes") ); } NPError VlcPlugin::init(int argc, char* const argn[], char* const argv[]) { /* prepare VLC command line */ char *ppsz_argv[32]; int ppsz_argc = 0; /* locate VLC module path */ #ifdef XP_MACOSX ppsz_argv[ppsz_argc++] = "--plugin-path"; ppsz_argv[ppsz_argc++] = "/Library/Internet Plug-Ins/VLC Plugin.plugin/" "Contents/MacOS/modules"; #elif defined(XP_WIN) HKEY h_key; DWORD i_type, i_data = MAX_PATH + 1; char p_data[MAX_PATH + 1]; if( RegOpenKeyEx( HKEY_LOCAL_MACHINE, "Software\\VideoLAN\\VLC", 0, KEY_READ, &h_key ) == ERROR_SUCCESS ) { if( RegQueryValueEx( h_key, "InstallDir", 0, &i_type, (LPBYTE)p_data, &i_data ) == ERROR_SUCCESS ) { if( i_type == REG_SZ ) { strcat( p_data, "\\plugins000" ); ppsz_argv[ppsz_argc++] = "--plugin-path"; ppsz_argv[ppsz_argc++] = p_data; } } RegCloseKey( h_key ); } ppsz_argv[ppsz_argc++] = "--no-one-instance"; #if 1 ppsz_argv[0] = "C:\\Cygwin\\home\\damienf\\vlc-trunk\\vlc"; #endif #endif /* XP_MACOSX */ /* common settings */ ppsz_argv[ppsz_argc++] = "-vv"; ppsz_argv[ppsz_argc++] = "--no-stats"; ppsz_argv[ppsz_argc++] = "--no-media-library"; ppsz_argv[ppsz_argc++] = "--intf"; ppsz_argv[ppsz_argc++] = "dummy"; const char *progid = NULL; /* parse plugin arguments */ for( int i = 0; i < argc ; i++ ) { fprintf(stderr, "argn=%s, argv=%s\n", argn[i], argv[i]); if( !strcmp( argn[i], "target" ) || !strcmp( argn[i], "mrl") || !strcmp( argn[i], "filename") || !strcmp( argn[i], "src") ) { psz_target = argv[i]; } else if( !strcmp( argn[i], "autoplay") || !strcmp( argn[i], "autostart") ) { b_autoplay = boolValue(argv[i]); } else if( !strcmp( argn[i], "fullscreen" ) ) { if( boolValue(argv[i]) ) { ppsz_argv[ppsz_argc++] = "--fullscreen"; } else { ppsz_argv[ppsz_argc++] = "--no-fullscreen"; } } else if( !strcmp( argn[i], "mute" ) ) { if( boolValue(argv[i]) ) { ppsz_argv[ppsz_argc++] = "--volume"; ppsz_argv[ppsz_argc++] = "0"; } } else if( !strcmp( argn[i], "loop") || !strcmp( argn[i], "autoloop") ) { if( boolValue(argv[i]) ) { ppsz_argv[ppsz_argc++] = "--loop"; } else { ppsz_argv[ppsz_argc++] = "--no-loop"; } } else if( !strcmp( argn[i], "version") || !strcmp( argn[i], "progid") ) { progid = argv[i]; } } libvlc_instance = libvlc_new(ppsz_argc, ppsz_argv, NULL); if( ! libvlc_instance ) { return NPERR_GENERIC_ERROR; } /* ** fetch plugin base URL, which is the URL of the page containing the plugin ** this URL is used for making absolute URL from relative URL that may be ** passed as an MRL argument */ NPObject *plugin; if( NPERR_NO_ERROR == NPN_GetValue(p_browser, NPNVWindowNPObject, &plugin) ) { /* ** is there a better way to get that info ? */ static const char docLocHref[] = "document.location.href"; NPString script; NPVariant result; script.utf8characters = docLocHref; script.utf8length = sizeof(docLocHref)-1; if( NPN_Evaluate(p_browser, plugin, &script, &result) ) { if( NPVARIANT_IS_STRING(result) ) { NPString &location = NPVARIANT_TO_STRING(result); psz_baseURL = new char[location.utf8length+1]; if( psz_baseURL ) { strncpy(psz_baseURL, location.utf8characters, location.utf8length); psz_baseURL[location.utf8length] = '\0'; } } NPN_ReleaseVariantValue(&result); } NPN_ReleaseObject(plugin); } if( psz_target ) { // get absolute URL from src char *psz_absurl = getAbsoluteURL(psz_target); psz_target = psz_absurl ? psz_absurl : strdup(psz_target); } /* assign plugin script root class */ if( (NULL != progid) && (!strcmp(progid, "VideoLAN.VLCPlugin.2")) ) { /* new APIs */ p_scriptClass = RuntimeNPClass<LibvlcRootNPObject>::getClass(); } else { /* legacy APIs */ p_scriptClass = RuntimeNPClass<VlcNPObject>::getClass(); } return NPERR_NO_ERROR; } #if 0 #ifdef XP_WIN /* This is really ugly but there is a deadlock when stopping a stream * (in VLC_CleanUp()) because the video output is a child of the drawable but * is in a different thread. */ static void HackStopVout( VlcPlugin* p_plugin ) { MSG msg; HWND hwnd; vlc_value_t value; int i_vlc = libvlc_get_vlc_id(p_plugin->libvlc_instance); VLC_VariableGet( i_vlc, "drawable", &value ); hwnd = FindWindowEx( (HWND)value.i_int, 0, 0, 0 ); if( !hwnd ) return; PostMessage( hwnd, WM_CLOSE, 0, 0 ); do { while( PeekMessage( &msg, (HWND)value.i_int, 0, 0, PM_REMOVE ) ) { TranslateMessage(&msg); DispatchMessage(&msg); } if( FindWindowEx( (HWND)value.i_int, 0, 0, 0 ) ) Sleep( 10 ); } while( (hwnd = FindWindowEx( (HWND)value.i_int, 0, 0, 0 )) ); } #endif /* XP_WIN */ #endif VlcPlugin::~VlcPlugin() { delete psz_baseURL; delete psz_target; if( libvlc_log ) libvlc_log_close(libvlc_log, NULL); if( libvlc_instance ) libvlc_release(libvlc_instance, NULL ); } /***************************************************************************** * VlcPlugin methods *****************************************************************************/ char *VlcPlugin::getAbsoluteURL(const char *url) { if( NULL != url ) { // check whether URL is already absolute const char *end=strchr(url, ':'); if( (NULL != end) && (end != url) ) { // validate protocol header const char *start = url; char c = *start; if( isalpha(c) ) { ++start; while( start != end ) { c = *start; if( ! (isalnum(c) || ('-' == c) || ('+' == c) || ('.' == c) || ('/' == c)) ) /* VLC uses / to allow user to specify a demuxer */ // not valid protocol header, assume relative URL goto relativeurl; ++start; } /* we have a protocol header, therefore URL is absolute */ return strdup(url); } // not a valid protocol header, assume relative URL } relativeurl: if( psz_baseURL ) { size_t baseLen = strlen(psz_baseURL); char *href = new char[baseLen+strlen(url)+1]; if( href ) { /* prepend base URL */ strcpy(href, psz_baseURL); /* ** relative url could be empty, ** in which case return base URL */ if( '\0' == *url ) return href; /* ** locate pathname part of base URL */ /* skip over protocol part */ char *pathstart = strchr(href, ':'); char *pathend; if( pathstart ) { if( '/' == *(++pathstart) ) { if( '/' == *(++pathstart) ) { ++pathstart; } } /* skip over host part */ pathstart = strchr(pathstart, '/'); pathend = href+baseLen; if( ! pathstart ) { // no path, add a / past end of url (over '\0') pathstart = pathend; *pathstart = '/'; } } else { /* baseURL is just a UNIX path */ if( '/' != *href ) { /* baseURL is not an absolute path */ return NULL; } pathstart = href; pathend = href+baseLen; } /* relative URL made of an absolute path ? */ if( '/' == *url ) { /* replace path completely */ strcpy(pathstart, url); return href; } /* find last path component and replace it */ while( '/' != *pathend) --pathend; /* ** if relative url path starts with one or more '../', ** factor them out of href so that we return a ** normalized URL */ while( pathend != pathstart ) { const char *p = url; if( '.' != *p ) break; ++p; if( '\0' == *p ) { /* relative url is just '.' */ url = p; break; } if( '/' == *p ) { /* relative url starts with './' */ url = ++p; continue; } if( '.' != *p ) break; ++p; if( '\0' == *p ) { /* relative url is '..' */ } else { if( '/' != *p ) break; /* relative url starts with '../' */ ++p; } url = p; do { --pathend; } while( '/' != *pathend ); } /* skip over '/' separator */ ++pathend; /* concatenate remaining base URL and relative URL */ strcpy(pathend, url); } return href; } } return NULL; } #if XP_UNIX int VlcPlugin::setSize(unsigned width, unsigned height) { int diff = (width != i_width) || (height != i_height); i_width = width; i_height = height; /* return size */ return diff; } #endif
/***************************************************************************** * vlcplugin.cpp: a VLC plugin for Mozilla ***************************************************************************** * Copyright (C) 2002-2005 the VideoLAN team * $Id$ * * Authors: Samuel Hocevar <[email protected]> * Damien Fouilleul <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ /***************************************************************************** * Preamble *****************************************************************************/ #include "config.h" #ifdef HAVE_MOZILLA_CONFIG_H # include <mozilla-config.h> #endif #include "vlcplugin.h" #include "control/npovlc.h" #include "control/npolibvlc.h" #include <ctype.h> /***************************************************************************** * VlcPlugin constructor and destructor *****************************************************************************/ VlcPlugin::VlcPlugin( NPP instance, uint16 mode ) : i_npmode(mode), b_stream(0), b_autoplay(1), psz_target(NULL), libvlc_instance(NULL), libvlc_log(NULL), p_scriptClass(NULL), p_browser(instance), psz_baseURL(NULL) #if XP_WIN ,pf_wndproc(NULL) #endif #if XP_UNIX ,i_width((unsigned)-1) ,i_height((unsigned)-1) #endif { memset(&npwindow, 0, sizeof(NPWindow)); } static bool boolValue(const char *value) { return ( !strcmp(value, "1") || !strcasecmp(value, "true") || !strcasecmp(value, "yes") ); } NPError VlcPlugin::init(int argc, char* const argn[], char* const argv[]) { /* prepare VLC command line */ char *ppsz_argv[32]; int ppsz_argc = 0; /* locate VLC module path */ #ifdef XP_MACOSX ppsz_argv[ppsz_argc++] = "--plugin-path"; ppsz_argv[ppsz_argc++] = "/Library/Internet Plug-Ins/VLC Plugin.plugin/" "Contents/MacOS/modules"; #elif defined(XP_WIN) HKEY h_key; DWORD i_type, i_data = MAX_PATH + 1; char p_data[MAX_PATH + 1]; if( RegOpenKeyEx( HKEY_LOCAL_MACHINE, "Software\\VideoLAN\\VLC", 0, KEY_READ, &h_key ) == ERROR_SUCCESS ) { if( RegQueryValueEx( h_key, "InstallDir", 0, &i_type, (LPBYTE)p_data, &i_data ) == ERROR_SUCCESS ) { if( i_type == REG_SZ ) { strcat( p_data, "\\plugins000" ); ppsz_argv[ppsz_argc++] = "--plugin-path"; ppsz_argv[ppsz_argc++] = p_data; } } RegCloseKey( h_key ); } ppsz_argv[ppsz_argc++] = "--no-one-instance"; #endif /* XP_MACOSX */ /* common settings */ ppsz_argv[ppsz_argc++] = "-vv"; ppsz_argv[ppsz_argc++] = "--no-stats"; ppsz_argv[ppsz_argc++] = "--no-media-library"; ppsz_argv[ppsz_argc++] = "--intf"; ppsz_argv[ppsz_argc++] = "dummy"; const char *progid = NULL; /* parse plugin arguments */ for( int i = 0; i < argc ; i++ ) { fprintf(stderr, "argn=%s, argv=%s\n", argn[i], argv[i]); if( !strcmp( argn[i], "target" ) || !strcmp( argn[i], "mrl") || !strcmp( argn[i], "filename") || !strcmp( argn[i], "src") ) { psz_target = argv[i]; } else if( !strcmp( argn[i], "autoplay") || !strcmp( argn[i], "autostart") ) { b_autoplay = boolValue(argv[i]); } else if( !strcmp( argn[i], "fullscreen" ) ) { if( boolValue(argv[i]) ) { ppsz_argv[ppsz_argc++] = "--fullscreen"; } else { ppsz_argv[ppsz_argc++] = "--no-fullscreen"; } } else if( !strcmp( argn[i], "mute" ) ) { if( boolValue(argv[i]) ) { ppsz_argv[ppsz_argc++] = "--volume"; ppsz_argv[ppsz_argc++] = "0"; } } else if( !strcmp( argn[i], "loop") || !strcmp( argn[i], "autoloop") ) { if( boolValue(argv[i]) ) { ppsz_argv[ppsz_argc++] = "--loop"; } else { ppsz_argv[ppsz_argc++] = "--no-loop"; } } else if( !strcmp( argn[i], "version") || !strcmp( argn[i], "progid") ) { progid = argv[i]; } } libvlc_instance = libvlc_new(ppsz_argc, ppsz_argv, NULL); if( ! libvlc_instance ) { return NPERR_GENERIC_ERROR; } /* ** fetch plugin base URL, which is the URL of the page containing the plugin ** this URL is used for making absolute URL from relative URL that may be ** passed as an MRL argument */ NPObject *plugin; if( NPERR_NO_ERROR == NPN_GetValue(p_browser, NPNVWindowNPObject, &plugin) ) { /* ** is there a better way to get that info ? */ static const char docLocHref[] = "document.location.href"; NPString script; NPVariant result; script.utf8characters = docLocHref; script.utf8length = sizeof(docLocHref)-1; if( NPN_Evaluate(p_browser, plugin, &script, &result) ) { if( NPVARIANT_IS_STRING(result) ) { NPString &location = NPVARIANT_TO_STRING(result); psz_baseURL = new char[location.utf8length+1]; if( psz_baseURL ) { strncpy(psz_baseURL, location.utf8characters, location.utf8length); psz_baseURL[location.utf8length] = '\0'; } } NPN_ReleaseVariantValue(&result); } NPN_ReleaseObject(plugin); } if( psz_target ) { // get absolute URL from src char *psz_absurl = getAbsoluteURL(psz_target); psz_target = psz_absurl ? psz_absurl : strdup(psz_target); } /* assign plugin script root class */ if( (NULL != progid) && (!strcmp(progid, "VideoLAN.VLCPlugin.2")) ) { /* new APIs */ p_scriptClass = RuntimeNPClass<LibvlcRootNPObject>::getClass(); } else { /* legacy APIs */ p_scriptClass = RuntimeNPClass<VlcNPObject>::getClass(); } return NPERR_NO_ERROR; } #if 0 #ifdef XP_WIN /* This is really ugly but there is a deadlock when stopping a stream * (in VLC_CleanUp()) because the video output is a child of the drawable but * is in a different thread. */ static void HackStopVout( VlcPlugin* p_plugin ) { MSG msg; HWND hwnd; vlc_value_t value; int i_vlc = libvlc_get_vlc_id(p_plugin->libvlc_instance); VLC_VariableGet( i_vlc, "drawable", &value ); hwnd = FindWindowEx( (HWND)value.i_int, 0, 0, 0 ); if( !hwnd ) return; PostMessage( hwnd, WM_CLOSE, 0, 0 ); do { while( PeekMessage( &msg, (HWND)value.i_int, 0, 0, PM_REMOVE ) ) { TranslateMessage(&msg); DispatchMessage(&msg); } if( FindWindowEx( (HWND)value.i_int, 0, 0, 0 ) ) Sleep( 10 ); } while( (hwnd = FindWindowEx( (HWND)value.i_int, 0, 0, 0 )) ); } #endif /* XP_WIN */ #endif VlcPlugin::~VlcPlugin() { delete psz_baseURL; delete psz_target; if( libvlc_log ) libvlc_log_close(libvlc_log, NULL); if( libvlc_instance ) libvlc_release(libvlc_instance, NULL ); } /***************************************************************************** * VlcPlugin methods *****************************************************************************/ char *VlcPlugin::getAbsoluteURL(const char *url) { if( NULL != url ) { // check whether URL is already absolute const char *end=strchr(url, ':'); if( (NULL != end) && (end != url) ) { // validate protocol header const char *start = url; char c = *start; if( isalpha(c) ) { ++start; while( start != end ) { c = *start; if( ! (isalnum(c) || ('-' == c) || ('+' == c) || ('.' == c) || ('/' == c)) ) /* VLC uses / to allow user to specify a demuxer */ // not valid protocol header, assume relative URL goto relativeurl; ++start; } /* we have a protocol header, therefore URL is absolute */ return strdup(url); } // not a valid protocol header, assume relative URL } relativeurl: if( psz_baseURL ) { size_t baseLen = strlen(psz_baseURL); char *href = new char[baseLen+strlen(url)+1]; if( href ) { /* prepend base URL */ strcpy(href, psz_baseURL); /* ** relative url could be empty, ** in which case return base URL */ if( '\0' == *url ) return href; /* ** locate pathname part of base URL */ /* skip over protocol part */ char *pathstart = strchr(href, ':'); char *pathend; if( pathstart ) { if( '/' == *(++pathstart) ) { if( '/' == *(++pathstart) ) { ++pathstart; } } /* skip over host part */ pathstart = strchr(pathstart, '/'); pathend = href+baseLen; if( ! pathstart ) { // no path, add a / past end of url (over '\0') pathstart = pathend; *pathstart = '/'; } } else { /* baseURL is just a UNIX path */ if( '/' != *href ) { /* baseURL is not an absolute path */ return NULL; } pathstart = href; pathend = href+baseLen; } /* relative URL made of an absolute path ? */ if( '/' == *url ) { /* replace path completely */ strcpy(pathstart, url); return href; } /* find last path component and replace it */ while( '/' != *pathend) --pathend; /* ** if relative url path starts with one or more '../', ** factor them out of href so that we return a ** normalized URL */ while( pathend != pathstart ) { const char *p = url; if( '.' != *p ) break; ++p; if( '\0' == *p ) { /* relative url is just '.' */ url = p; break; } if( '/' == *p ) { /* relative url starts with './' */ url = ++p; continue; } if( '.' != *p ) break; ++p; if( '\0' == *p ) { /* relative url is '..' */ } else { if( '/' != *p ) break; /* relative url starts with '../' */ ++p; } url = p; do { --pathend; } while( '/' != *pathend ); } /* skip over '/' separator */ ++pathend; /* concatenate remaining base URL and relative URL */ strcpy(pathend, url); } return href; } } return NULL; } #if XP_UNIX int VlcPlugin::setSize(unsigned width, unsigned height) { int diff = (width != i_width) || (height != i_height); i_width = width; i_height = height; /* return size */ return diff; } #endif
remove potentially harmful debug on win32
mozilla: remove potentially harmful debug on win32
C++
lgpl-2.1
jamesbates/npapi-vlc,jamesbates/npapi-vlc,rdp/npapi-vlc,modulexcite/npapi-vlc,modulexcite/npapi-vlc,chengsun/gtk-npapi-vlc,chengsun/gtk-npapi-vlc,rdp/npapi-vlc,modulexcite/npapi-vlc,rdp/npapi-vlc,modulexcite/npapi-vlc,rdp/npapi-vlc,chengsun/gtk-npapi-vlc,jamesbates/npapi-vlc
806a14a7ca2aeaa1a51b1d810b1158455e7f22fc
silicium/sink.hpp
silicium/sink.hpp
#ifndef SILICIUM_SINK_HPP #define SILICIUM_SINK_HPP #include <silicium/override.hpp> #include <boost/range/iterator_range.hpp> #include <boost/range/algorithm/copy.hpp> #include <boost/filesystem/path.hpp> #include <boost/container/string.hpp> #include <fstream> #include <array> #include <memory> namespace Si { template <class Element, class Error = boost::system::error_code> struct sink { typedef Element element_type; virtual ~sink() { } virtual boost::iterator_range<Element *> make_append_space(std::size_t size) = 0; virtual Error flush_append_space() = 0; virtual Error append(boost::iterator_range<Element const *> data) = 0; }; template <class Element, class Error> struct flushable_sink : sink<Element, Error> { typedef Element element_type; virtual Error flush() = 0; }; template <class Element, class Error> Error commit(sink<Element, Error> &destination, std::size_t count) { destination.make_append_space(count); return destination.flush_append_space(); } namespace detail { template <class> void default_construct(std::true_type) { } template <class T> T default_construct(std::false_type) { return T{}; } } template <class T> T default_construct() { return detail::default_construct<T>(std::is_same<T, void>()); } namespace detail { template <class Error> struct then_impl { Error operator()() const { return Error(); } template <class First, class ...Tail> Error operator()(First &&first, Tail &&...tail) const { auto error = std::forward<First>(first)(); if (error) { return error; } return (*this)(std::forward<Tail>(tail)...); } }; template <> struct then_impl<void> { void operator()() const { } template <class First, class ...Tail> void operator()(First &&first, Tail &&...tail) const { std::forward<First>(first)(); return (*this)(std::forward<Tail>(tail)...); } }; } template <class First, class ...Sequence> auto then(First &&first, Sequence &&...actions) { typedef decltype(std::forward<First>(first)()) result_type; return detail::then_impl<result_type>()(std::forward<First>(first), std::forward<Sequence>(actions)...); } template <class Element, class Error, class Buffer = std::array<Element, ((1U << 13U) / sizeof(Element))>> struct buffering_sink SILICIUM_FINAL : flushable_sink<Element, Error> { typedef Element element_type; buffering_sink() : m_destination(nullptr) { } explicit buffering_sink(sink<Element, Error> &destination, Buffer buffer = Buffer()) : m_destination(&destination) , m_fallback_buffer(std::move(buffer)) , m_buffer_used(0) { } boost::iterator_range<Element *> make_append_space(std::size_t size) SILICIUM_OVERRIDE { assert(m_destination); auto first_try = m_destination->make_append_space(size); if (!first_try.empty()) { auto const copied = (std::min<std::ptrdiff_t>)(static_cast<std::ptrdiff_t>(m_buffer_used), first_try.size()); std::copy(m_fallback_buffer.begin(), m_fallback_buffer.begin() + copied, first_try.begin()); m_buffer_used = 0; return first_try; } m_buffer_used = (std::min)(size, m_fallback_buffer.size()); return boost::make_iterator_range(m_fallback_buffer.data(), m_fallback_buffer.data() + m_buffer_used); } Error flush_append_space() SILICIUM_OVERRIDE { assert(m_destination); if (m_buffer_used) { return flush(); } else { return m_destination->flush_append_space(); } } Error append(boost::iterator_range<Element const *> data) SILICIUM_OVERRIDE { assert(m_destination); if (static_cast<size_t>(data.size()) <= (m_fallback_buffer.size() - m_buffer_used)) { boost::range::copy(data, m_fallback_buffer.begin() + m_buffer_used); m_buffer_used += data.size(); return default_construct<Error>(); } return then( [this] { return flush(); }, [this, &data] { return m_destination->append(data); }); } Error flush() SILICIUM_OVERRIDE { assert(m_destination); return then( [this] { return m_destination->append(boost::make_iterator_range(m_fallback_buffer.data(), m_fallback_buffer.data() + m_buffer_used)); }, [this] { m_buffer_used = 0; return Error(); } ); } private: sink<Element, Error> *m_destination; Buffer m_fallback_buffer; std::size_t m_buffer_used; }; template <class Element, class OutputIterator> struct iterator_sink SILICIUM_FINAL : sink<Element, void> { typedef Element element_type; explicit iterator_sink(OutputIterator out) : m_out(std::move(out)) { } virtual boost::iterator_range<Element *> make_append_space(std::size_t) SILICIUM_OVERRIDE { return {}; } virtual void flush_append_space() SILICIUM_OVERRIDE { } virtual void append(boost::iterator_range<Element const *> data) SILICIUM_OVERRIDE { boost::range::copy(data, m_out); } private: OutputIterator m_out; }; template <class Element, class OutputIterator> auto make_iterator_sink(OutputIterator out) -> iterator_sink<Element, typename std::decay<OutputIterator>::type> { return iterator_sink<Element, typename std::decay<OutputIterator>::type>(std::move(out)); } template <class Container> auto make_container_sink(Container &destination) -> iterator_sink<typename Container::value_type, std::back_insert_iterator<Container>> { return make_iterator_sink<typename Container::value_type>(std::back_inserter(destination)); } struct ostream_ref_sink SILICIUM_FINAL : flushable_sink<char, void> { ostream_ref_sink() : m_file(nullptr) { } explicit ostream_ref_sink(std::ostream &file) : m_file(&file) { } virtual boost::iterator_range<char *> make_append_space(std::size_t) SILICIUM_OVERRIDE { return {}; } virtual void flush_append_space() SILICIUM_OVERRIDE { } virtual void append(boost::iterator_range<char const *> data) SILICIUM_OVERRIDE { assert(m_file); m_file->write(data.begin(), data.size()); } virtual void flush() SILICIUM_OVERRIDE { assert(m_file); m_file->flush(); } private: std::ostream *m_file; }; struct ostream_sink SILICIUM_FINAL : flushable_sink<char, boost::system::error_code> { //unique_ptr to make ostreams movable explicit ostream_sink(std::unique_ptr<std::ostream> file) : m_file(std::move(file)) { m_file->exceptions(std::ios::failbit | std::ios::badbit); } virtual boost::iterator_range<char *> make_append_space(std::size_t) SILICIUM_OVERRIDE { return {}; } virtual boost::system::error_code flush_append_space() SILICIUM_OVERRIDE { return {}; } virtual boost::system::error_code append(boost::iterator_range<char const *> data) SILICIUM_OVERRIDE { m_file->write(data.begin(), data.size()); return {}; } virtual boost::system::error_code flush() SILICIUM_OVERRIDE { m_file->flush(); return {}; } private: std::unique_ptr<std::ostream> m_file; }; inline std::unique_ptr<flushable_sink<char, boost::system::error_code>> make_file_sink(boost::filesystem::path const &name) { std::unique_ptr<std::ostream> file(new std::ofstream(name.string(), std::ios::binary)); if (!*file) { throw std::runtime_error("Cannot open file for writing: " + name.string()); } return std::unique_ptr<flushable_sink<char, boost::system::error_code>>(new ostream_sink(std::move(file))); } template <class Element, class Error> struct auto_flush_sink SILICIUM_FINAL : sink<Element, Error> { auto_flush_sink() : m_next(nullptr) { } explicit auto_flush_sink(flushable_sink<Element, Error> &next) : m_next(&next) { } virtual boost::iterator_range<char *> make_append_space(std::size_t size) SILICIUM_OVERRIDE { assert(m_next); return m_next->make_append_space(size); } virtual Error flush_append_space() SILICIUM_OVERRIDE { assert(m_next); return then( [this] { return m_next->flush_append_space(); }, [this] { return m_next->flush(); } ); } virtual Error append(boost::iterator_range<char const *> data) SILICIUM_OVERRIDE { assert(m_next); return then( [this, &data] { return m_next->append(data); }, [this] { return m_next->flush(); } ); } private: flushable_sink<Element, Error> *m_next; }; template <class Element, class Error> auto_flush_sink<Element, Error> make_auto_flush_sink(flushable_sink<Element, Error> &next) { return auto_flush_sink<Element, Error>(next); } template <class Element, class Error> Error append(Si::sink<Element, Error> &out, std::basic_string<Element> const &str) { return out.append(boost::make_iterator_range(str.data(), str.data() + str.size())); } template <class Element, class Error> Error append(Si::sink<Element, Error> &out, boost::container::basic_string<Element> const &str) { return out.append(boost::make_iterator_range(str.data(), str.data() + str.size())); } template <class Element, class Error> Error append(Si::sink<Element, Error> &out, Element const *c_str) { return out.append(boost::make_iterator_range(c_str, c_str + std::char_traits<Element>::length(c_str))); } template <class Element, class Error> Error append(Si::sink<Element, Error> &out, Element const &single) { return out.append(boost::make_iterator_range(&single, &single + 1)); } template <class Next> struct throwing_sink : flushable_sink<typename Next::element_type, void> { typedef typename Next::element_type element_type; throwing_sink() { } explicit throwing_sink(Next next) : next(next) { } virtual boost::iterator_range<element_type *> make_append_space(std::size_t size) SILICIUM_OVERRIDE { return next.make_append_space(size); } virtual void flush_append_space() SILICIUM_OVERRIDE { auto error = next.flush_append_space(); if (error) { throw boost::system::system_error(error); } } virtual void append(boost::iterator_range<element_type const *> data) SILICIUM_OVERRIDE { auto error = next.append(data); if (error) { throw boost::system::system_error(error); } } virtual void flush() SILICIUM_OVERRIDE { auto error = next.flush(); if (error) { throw boost::system::system_error(error); } } private: Next next; }; template <class Next> auto make_throwing_sink(Next &&next) { return throwing_sink<typename std::decay<Next>::type>(std::forward<Next>(next)); } template <class Pointee> struct ptr_sink : flushable_sink<typename Pointee::element_type, boost::system::error_code> { typedef typename Pointee::element_type element_type; ptr_sink() : next(nullptr) { } explicit ptr_sink(Pointee &next) : next(&next) { } virtual boost::iterator_range<element_type *> make_append_space(std::size_t size) SILICIUM_OVERRIDE { return next->make_append_space(size); } virtual boost::system::error_code flush_append_space() SILICIUM_OVERRIDE { return next->flush_append_space(); } virtual boost::system::error_code append(boost::iterator_range<element_type const *> data) SILICIUM_OVERRIDE { return next->append(data); } virtual boost::system::error_code flush() SILICIUM_OVERRIDE { return next->flush(); } private: Pointee *next; }; template <class Pointee> auto ref_sink(Pointee &next) { return ptr_sink<Pointee>(next); } } #endif
#ifndef SILICIUM_SINK_HPP #define SILICIUM_SINK_HPP #include <silicium/override.hpp> #include <boost/range/iterator_range.hpp> #include <boost/range/algorithm/copy.hpp> #include <boost/filesystem/path.hpp> #include <boost/container/string.hpp> #include <fstream> #include <array> #include <memory> namespace Si { template <class Element, class Error = boost::system::error_code> struct sink { typedef Element element_type; virtual ~sink() { } virtual boost::iterator_range<Element *> make_append_space(std::size_t size) = 0; virtual Error flush_append_space() = 0; virtual Error append(boost::iterator_range<Element const *> data) = 0; }; template <class Element, class Error> struct flushable_sink : sink<Element, Error> { typedef Element element_type; virtual Error flush() = 0; }; template <class Element, class Error> Error commit(sink<Element, Error> &destination, std::size_t count) { destination.make_append_space(count); return destination.flush_append_space(); } namespace detail { template <class> void default_construct(std::true_type) { } template <class T> T default_construct(std::false_type) { return T{}; } } template <class T> T default_construct() { return detail::default_construct<T>(std::is_same<T, void>()); } namespace detail { template <class Error> struct then_impl { Error operator()() const { return Error(); } template <class First, class ...Tail> Error operator()(First &&first, Tail &&...tail) const { auto error = std::forward<First>(first)(); if (error) { return error; } return (*this)(std::forward<Tail>(tail)...); } }; template <> struct then_impl<void> { void operator()() const { } template <class First, class ...Tail> void operator()(First &&first, Tail &&...tail) const { std::forward<First>(first)(); return (*this)(std::forward<Tail>(tail)...); } }; } template <class First, class ...Sequence> auto then(First &&first, Sequence &&...actions) -> detail::then_impl<decltype(std::forward<First>(first)())> { typedef decltype(std::forward<First>(first)()) result_type; return detail::then_impl<result_type>()(std::forward<First>(first), std::forward<Sequence>(actions)...); } template <class Element, class Error, class Buffer = std::array<Element, ((1U << 13U) / sizeof(Element))>> struct buffering_sink SILICIUM_FINAL : flushable_sink<Element, Error> { typedef Element element_type; buffering_sink() : m_destination(nullptr) { } explicit buffering_sink(sink<Element, Error> &destination, Buffer buffer = Buffer()) : m_destination(&destination) , m_fallback_buffer(std::move(buffer)) , m_buffer_used(0) { } boost::iterator_range<Element *> make_append_space(std::size_t size) SILICIUM_OVERRIDE { assert(m_destination); auto first_try = m_destination->make_append_space(size); if (!first_try.empty()) { auto const copied = (std::min<std::ptrdiff_t>)(static_cast<std::ptrdiff_t>(m_buffer_used), first_try.size()); std::copy(m_fallback_buffer.begin(), m_fallback_buffer.begin() + copied, first_try.begin()); m_buffer_used = 0; return first_try; } m_buffer_used = (std::min)(size, m_fallback_buffer.size()); return boost::make_iterator_range(m_fallback_buffer.data(), m_fallback_buffer.data() + m_buffer_used); } Error flush_append_space() SILICIUM_OVERRIDE { assert(m_destination); if (m_buffer_used) { return flush(); } else { return m_destination->flush_append_space(); } } Error append(boost::iterator_range<Element const *> data) SILICIUM_OVERRIDE { assert(m_destination); if (static_cast<size_t>(data.size()) <= (m_fallback_buffer.size() - m_buffer_used)) { boost::range::copy(data, m_fallback_buffer.begin() + m_buffer_used); m_buffer_used += data.size(); return default_construct<Error>(); } return then( [this] { return flush(); }, [this, &data] { return m_destination->append(data); }); } Error flush() SILICIUM_OVERRIDE { assert(m_destination); return then( [this] { return m_destination->append(boost::make_iterator_range(m_fallback_buffer.data(), m_fallback_buffer.data() + m_buffer_used)); }, [this] { m_buffer_used = 0; return Error(); } ); } private: sink<Element, Error> *m_destination; Buffer m_fallback_buffer; std::size_t m_buffer_used; }; template <class Element, class OutputIterator> struct iterator_sink SILICIUM_FINAL : sink<Element, void> { typedef Element element_type; explicit iterator_sink(OutputIterator out) : m_out(std::move(out)) { } virtual boost::iterator_range<Element *> make_append_space(std::size_t) SILICIUM_OVERRIDE { return {}; } virtual void flush_append_space() SILICIUM_OVERRIDE { } virtual void append(boost::iterator_range<Element const *> data) SILICIUM_OVERRIDE { boost::range::copy(data, m_out); } private: OutputIterator m_out; }; template <class Element, class OutputIterator> auto make_iterator_sink(OutputIterator out) -> iterator_sink<Element, typename std::decay<OutputIterator>::type> { return iterator_sink<Element, typename std::decay<OutputIterator>::type>(std::move(out)); } template <class Container> auto make_container_sink(Container &destination) -> iterator_sink<typename Container::value_type, std::back_insert_iterator<Container>> { return make_iterator_sink<typename Container::value_type>(std::back_inserter(destination)); } struct ostream_ref_sink SILICIUM_FINAL : flushable_sink<char, void> { ostream_ref_sink() : m_file(nullptr) { } explicit ostream_ref_sink(std::ostream &file) : m_file(&file) { } virtual boost::iterator_range<char *> make_append_space(std::size_t) SILICIUM_OVERRIDE { return {}; } virtual void flush_append_space() SILICIUM_OVERRIDE { } virtual void append(boost::iterator_range<char const *> data) SILICIUM_OVERRIDE { assert(m_file); m_file->write(data.begin(), data.size()); } virtual void flush() SILICIUM_OVERRIDE { assert(m_file); m_file->flush(); } private: std::ostream *m_file; }; struct ostream_sink SILICIUM_FINAL : flushable_sink<char, boost::system::error_code> { //unique_ptr to make ostreams movable explicit ostream_sink(std::unique_ptr<std::ostream> file) : m_file(std::move(file)) { m_file->exceptions(std::ios::failbit | std::ios::badbit); } virtual boost::iterator_range<char *> make_append_space(std::size_t) SILICIUM_OVERRIDE { return {}; } virtual boost::system::error_code flush_append_space() SILICIUM_OVERRIDE { return {}; } virtual boost::system::error_code append(boost::iterator_range<char const *> data) SILICIUM_OVERRIDE { m_file->write(data.begin(), data.size()); return {}; } virtual boost::system::error_code flush() SILICIUM_OVERRIDE { m_file->flush(); return {}; } private: std::unique_ptr<std::ostream> m_file; }; inline std::unique_ptr<flushable_sink<char, boost::system::error_code>> make_file_sink(boost::filesystem::path const &name) { std::unique_ptr<std::ostream> file(new std::ofstream(name.string(), std::ios::binary)); if (!*file) { throw std::runtime_error("Cannot open file for writing: " + name.string()); } return std::unique_ptr<flushable_sink<char, boost::system::error_code>>(new ostream_sink(std::move(file))); } template <class Element, class Error> struct auto_flush_sink SILICIUM_FINAL : sink<Element, Error> { auto_flush_sink() : m_next(nullptr) { } explicit auto_flush_sink(flushable_sink<Element, Error> &next) : m_next(&next) { } virtual boost::iterator_range<char *> make_append_space(std::size_t size) SILICIUM_OVERRIDE { assert(m_next); return m_next->make_append_space(size); } virtual Error flush_append_space() SILICIUM_OVERRIDE { assert(m_next); return then( [this] { return m_next->flush_append_space(); }, [this] { return m_next->flush(); } ); } virtual Error append(boost::iterator_range<char const *> data) SILICIUM_OVERRIDE { assert(m_next); return then( [this, &data] { return m_next->append(data); }, [this] { return m_next->flush(); } ); } private: flushable_sink<Element, Error> *m_next; }; template <class Element, class Error> auto_flush_sink<Element, Error> make_auto_flush_sink(flushable_sink<Element, Error> &next) { return auto_flush_sink<Element, Error>(next); } template <class Element, class Error> Error append(Si::sink<Element, Error> &out, std::basic_string<Element> const &str) { return out.append(boost::make_iterator_range(str.data(), str.data() + str.size())); } template <class Element, class Error> Error append(Si::sink<Element, Error> &out, boost::container::basic_string<Element> const &str) { return out.append(boost::make_iterator_range(str.data(), str.data() + str.size())); } template <class Element, class Error> Error append(Si::sink<Element, Error> &out, Element const *c_str) { return out.append(boost::make_iterator_range(c_str, c_str + std::char_traits<Element>::length(c_str))); } template <class Element, class Error> Error append(Si::sink<Element, Error> &out, Element const &single) { return out.append(boost::make_iterator_range(&single, &single + 1)); } template <class Next> struct throwing_sink : flushable_sink<typename Next::element_type, void> { typedef typename Next::element_type element_type; throwing_sink() { } explicit throwing_sink(Next next) : next(next) { } virtual boost::iterator_range<element_type *> make_append_space(std::size_t size) SILICIUM_OVERRIDE { return next.make_append_space(size); } virtual void flush_append_space() SILICIUM_OVERRIDE { auto error = next.flush_append_space(); if (error) { throw boost::system::system_error(error); } } virtual void append(boost::iterator_range<element_type const *> data) SILICIUM_OVERRIDE { auto error = next.append(data); if (error) { throw boost::system::system_error(error); } } virtual void flush() SILICIUM_OVERRIDE { auto error = next.flush(); if (error) { throw boost::system::system_error(error); } } private: Next next; }; template <class Next> auto make_throwing_sink(Next &&next) -> throwing_sink<typename std::decay<Next>::type> { return throwing_sink<typename std::decay<Next>::type>(std::forward<Next>(next)); } template <class Pointee> struct ptr_sink : flushable_sink<typename Pointee::element_type, boost::system::error_code> { typedef typename Pointee::element_type element_type; ptr_sink() : next(nullptr) { } explicit ptr_sink(Pointee &next) : next(&next) { } virtual boost::iterator_range<element_type *> make_append_space(std::size_t size) SILICIUM_OVERRIDE { return next->make_append_space(size); } virtual boost::system::error_code flush_append_space() SILICIUM_OVERRIDE { return next->flush_append_space(); } virtual boost::system::error_code append(boost::iterator_range<element_type const *> data) SILICIUM_OVERRIDE { return next->append(data); } virtual boost::system::error_code flush() SILICIUM_OVERRIDE { return next->flush(); } private: Pointee *next; }; template <class Pointee> auto ref_sink(Pointee &next) -> ptr_sink<Pointee> { return ptr_sink<Pointee>(next); } } #endif
add a few trailing return types
add a few trailing return types
C++
mit
TyRoXx/silicium,TyRoXx/silicium
59f1b5afef6a41bd3187c00d649c8082e8436773
tensorflow/contrib/session_bundle/session_bundle.cc
tensorflow/contrib/session_bundle/session_bundle.cc
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/contrib/session_bundle/session_bundle.h" #include <string> #include <utility> #include <vector> #include "google/protobuf/any.pb.h" #include "tensorflow/contrib/session_bundle/manifest.pb.h" #include "tensorflow/core/framework/graph.pb.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/tensor_types.h" #include "tensorflow/core/framework/types.pb.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/lib/monitoring/counter.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/protobuf.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/protobuf/meta_graph.pb.h" #include "tensorflow/core/protobuf/saver.pb.h" #include "tensorflow/core/public/session_options.h" namespace tensorflow { namespace serving { namespace { auto* load_attempt = monitoring::Counter<1>::New( "/tensorflow/contrib/session_bundle/load_attempt", "model_path", "The number of times a session bundle was requested to be loaded."); auto* load_success = monitoring::Counter<1>::New( "/tensorflow/contrib/session_bundle/load_success", "model_path", "The number of times a session bundle was successfully loaded."); auto* load_latency = monitoring::Counter<1>::New( "/tensorflow/contrib/session_bundle/load_latency", "model_path", "Latency in microseconds for session bundles that were succesfully " "loaded."); // Create a session using the given options and load the graph. Status CreateSessionFromGraphDef(const SessionOptions& options, const GraphDef& graph, std::unique_ptr<Session>* session) { session->reset(NewSession(options)); return (*session)->Create(graph); } Status GetMetaGraphDefFromExport(const StringPiece export_dir, MetaGraphDef* meta_graph_def) { const string meta_graph_def_path = io::JoinPath(export_dir, kMetaGraphDefFilename); return ReadBinaryProto(Env::Default(), meta_graph_def_path, meta_graph_def); } // Creates a string tensor. Tensor CreateStringTensor(const string& value) { Tensor tensor(DT_STRING, TensorShape({})); tensor.scalar<string>()() = value; return tensor; } // Adds Assets related tensors (assets_dir and asset files) to the inputs. void AddAssetsTensorsToInputs(const StringPiece export_dir, const std::vector<AssetFile>& asset_files, std::vector<std::pair<string, Tensor>>* inputs) { if (asset_files.empty()) { return; } for (auto& asset : asset_files) { Tensor assets_file_tensor = CreateStringTensor( io::JoinPath(export_dir, kAssetsDirectory, asset.filename())); inputs->push_back( {asset.tensor_binding().tensor_name(), assets_file_tensor}); } } // Historically, model exporter(exporter.py) takes only saver with // sharded=True, and therefore always exports checkpoint in pattern file names. // In practice, instead of training from scratch and export directly, we // usually want to restore from existing checkpoints and then export directly. // To support such case, model exporter now supports reusing saver object // restored from existing checkpoint, that may have sharded=False - it will // then export checkpoint file in plain file name. // This method is to support models exported by both types of saver object. // The change is backward-compatible, therefore no changes are needed for // existing model exports. string GetVariablesFilename(const StringPiece export_dir) { const char kVariablesFilename[] = "export"; const char kVariablesFilenamePattern[] = "export-\?\?\?\?\?-of-\?\?\?\?\?"; if (Env::Default()->FileExists( io::JoinPath(export_dir, kVariablesFilename))) { return io::JoinPath(export_dir, kVariablesFilename); } else { return io::JoinPath(export_dir, kVariablesFilenamePattern); } } Status RunRestoreOp(const RunOptions& run_options, const StringPiece export_dir, const std::vector<AssetFile>& asset_files, const StringPiece restore_op_name, const StringPiece variables_filename_const_op_name, Session* session) { LOG(INFO) << "Running restore op for SessionBundle"; Tensor variables_tensor = CreateStringTensor(GetVariablesFilename(export_dir)); std::vector<std::pair<string, Tensor>> inputs = { {variables_filename_const_op_name.ToString(), variables_tensor}}; AddAssetsTensorsToInputs(export_dir, asset_files, &inputs); RunMetadata run_metadata; return session->Run(run_options, inputs, {}, {restore_op_name.ToString()}, nullptr /* outputs */, &run_metadata); } Status RunInitOp(const RunOptions& run_options, const StringPiece export_dir, const std::vector<AssetFile>& asset_files, const StringPiece init_op_name, Session* session) { LOG(INFO) << "Running init op for SessionBundle"; std::vector<std::pair<string, Tensor>> inputs; AddAssetsTensorsToInputs(export_dir, asset_files, &inputs); RunMetadata run_metadata; return session->Run(run_options, inputs, {}, {init_op_name.ToString()}, nullptr /* outputs */, &run_metadata); } } // namespace Status LoadSessionBundleFromPath(const SessionOptions& options, const StringPiece export_dir, SessionBundle* const bundle) { TF_RETURN_IF_ERROR(LoadSessionBundleFromPathUsingRunOptions( options, RunOptions(), export_dir, bundle)); return Status::OK(); } Status LoadSessionBundleFromPathUsingRunOptions(const SessionOptions& options, const RunOptions& run_options, const StringPiece export_dir, SessionBundle* const bundle) { load_attempt->GetCell(export_dir.ToString())->IncrementBy(1); LOG(INFO) << "Attempting to load a SessionBundle from: " << export_dir; LOG(INFO) << "Using RunOptions: " << DebugStringIfAvailable(run_options); const uint64 start_microseconds = Env::Default()->NowMicros(); TF_RETURN_IF_ERROR( GetMetaGraphDefFromExport(export_dir, &(bundle->meta_graph_def))); const auto& collection_def_map = bundle->meta_graph_def.collection_def(); const auto graph_it = bundle->meta_graph_def.collection_def().find(kGraphKey); if (graph_it != collection_def_map.end()) { const CollectionDef& graph_collection_def = graph_it->second; // Use serving graph_def in MetaGraphDef collection_def. if (graph_collection_def.any_list().value_size() != 1) { return errors::FailedPrecondition( "Expected exactly one serving GraphDef in : ", DebugStringIfAvailable(bundle->meta_graph_def)); } const auto& any = graph_collection_def.any_list().value(0); GraphDef graph_def; TF_RETURN_IF_ERROR(ParseAny(any, &graph_def, "tensorflow.GraphDef")); TF_RETURN_IF_ERROR( CreateSessionFromGraphDef(options, graph_def, &bundle->session)); } else { // Fallback to use the graph_def in the MetaGraphDef. const GraphDef& graph_def = bundle->meta_graph_def.graph_def(); TF_RETURN_IF_ERROR( CreateSessionFromGraphDef(options, graph_def, &bundle->session)); } std::vector<AssetFile> asset_files; const auto assets_it = collection_def_map.find(kAssetsKey); if (assets_it != collection_def_map.end()) { const auto& any_assets = assets_it->second.any_list().value(); for (const auto& any_asset : any_assets) { AssetFile asset_file; TF_RETURN_IF_ERROR( ParseAny(any_asset, &asset_file, "tensorflow.serving.AssetFile")); asset_files.push_back(asset_file); } } TF_RETURN_IF_ERROR( RunRestoreOp(run_options, export_dir, asset_files, bundle->meta_graph_def.saver_def().restore_op_name(), bundle->meta_graph_def.saver_def().filename_tensor_name(), bundle->session.get())); const auto init_op_it = collection_def_map.find(kInitOpKey); if (init_op_it != collection_def_map.end()) { if (init_op_it->second.node_list().value_size() != 1) { return errors::FailedPrecondition( strings::StrCat("Expected exactly one serving init op in : ", DebugStringIfAvailable(bundle->meta_graph_def))); } TF_RETURN_IF_ERROR(RunInitOp(run_options, export_dir, asset_files, init_op_it->second.node_list().value(0), bundle->session.get())); } const uint64 load_latency_microsecs = [&]() -> uint64 { const uint64 end_microseconds = Env::Default()->NowMicros(); // Avoid clock skew. if (end_microseconds < start_microseconds) return 0; return end_microseconds - start_microseconds; }(); LOG(INFO) << "Done loading SessionBundle. Took " << load_latency_microsecs << " microseconds."; load_success->GetCell(export_dir.ToString())->IncrementBy(1); load_latency->GetCell(export_dir.ToString()) ->IncrementBy(load_latency_microsecs); return Status::OK(); } bool IsPossibleExportDirectory(const StringPiece directory) { const string meta_graph_def_path = io::JoinPath(directory, kMetaGraphDefFilename); return Env::Default()->FileExists(meta_graph_def_path); } } // namespace serving } // namespace tensorflow
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/contrib/session_bundle/session_bundle.h" #include <string> #include <utility> #include <vector> #include "google/protobuf/any.pb.h" #include "tensorflow/contrib/session_bundle/manifest.pb.h" #include "tensorflow/core/framework/graph.pb.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/tensor_types.h" #include "tensorflow/core/framework/types.pb.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/lib/monitoring/counter.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/protobuf.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/protobuf/meta_graph.pb.h" #include "tensorflow/core/protobuf/saver.pb.h" #include "tensorflow/core/public/session_options.h" namespace tensorflow { namespace serving { namespace { auto* load_attempt_count = monitoring::Counter<2>::New( "/tensorflow/contrib/session_bundle/load_attempt_count", "model_path", "status", "The number of times a SessionBundle was requested to be loaded."); auto* load_latency = monitoring::Counter<1>::New( "/tensorflow/contrib/session_bundle/load_latency", "model_path", "Latency in microseconds for SessionBundles that were succesfully loaded."); constexpr char kLoadAttemptFail[] = "fail"; constexpr char kLoadAttemptSuccess[] = "success"; // Create a session using the given options and load the graph. Status CreateSessionFromGraphDef(const SessionOptions& options, const GraphDef& graph, std::unique_ptr<Session>* session) { session->reset(NewSession(options)); return (*session)->Create(graph); } Status GetMetaGraphDefFromExport(const StringPiece export_dir, MetaGraphDef* meta_graph_def) { const string meta_graph_def_path = io::JoinPath(export_dir, kMetaGraphDefFilename); return ReadBinaryProto(Env::Default(), meta_graph_def_path, meta_graph_def); } // Creates a string tensor. Tensor CreateStringTensor(const string& value) { Tensor tensor(DT_STRING, TensorShape({})); tensor.scalar<string>()() = value; return tensor; } // Adds Assets related tensors (assets_dir and asset files) to the inputs. void AddAssetsTensorsToInputs(const StringPiece export_dir, const std::vector<AssetFile>& asset_files, std::vector<std::pair<string, Tensor>>* inputs) { if (asset_files.empty()) { return; } for (auto& asset : asset_files) { Tensor assets_file_tensor = CreateStringTensor( io::JoinPath(export_dir, kAssetsDirectory, asset.filename())); inputs->push_back( {asset.tensor_binding().tensor_name(), assets_file_tensor}); } } // Historically, model exporter(exporter.py) takes only saver with // sharded=True, and therefore always exports checkpoint in pattern file names. // In practice, instead of training from scratch and export directly, we // usually want to restore from existing checkpoints and then export directly. // To support such case, model exporter now supports reusing saver object // restored from existing checkpoint, that may have sharded=False - it will // then export checkpoint file in plain file name. // This method is to support models exported by both types of saver object. // The change is backward-compatible, therefore no changes are needed for // existing model exports. string GetVariablesFilename(const StringPiece export_dir) { const char kVariablesFilename[] = "export"; const char kVariablesFilenamePattern[] = "export-\?\?\?\?\?-of-\?\?\?\?\?"; if (Env::Default()->FileExists( io::JoinPath(export_dir, kVariablesFilename))) { return io::JoinPath(export_dir, kVariablesFilename); } else { return io::JoinPath(export_dir, kVariablesFilenamePattern); } } Status RunRestoreOp(const RunOptions& run_options, const StringPiece export_dir, const std::vector<AssetFile>& asset_files, const StringPiece restore_op_name, const StringPiece variables_filename_const_op_name, Session* session) { LOG(INFO) << "Running restore op for SessionBundle"; Tensor variables_tensor = CreateStringTensor(GetVariablesFilename(export_dir)); std::vector<std::pair<string, Tensor>> inputs = { {variables_filename_const_op_name.ToString(), variables_tensor}}; AddAssetsTensorsToInputs(export_dir, asset_files, &inputs); RunMetadata run_metadata; return session->Run(run_options, inputs, {}, {restore_op_name.ToString()}, nullptr /* outputs */, &run_metadata); } Status RunInitOp(const RunOptions& run_options, const StringPiece export_dir, const std::vector<AssetFile>& asset_files, const StringPiece init_op_name, Session* session) { LOG(INFO) << "Running init op for SessionBundle"; std::vector<std::pair<string, Tensor>> inputs; AddAssetsTensorsToInputs(export_dir, asset_files, &inputs); RunMetadata run_metadata; return session->Run(run_options, inputs, {}, {init_op_name.ToString()}, nullptr /* outputs */, &run_metadata); } Status LoadSessionBundleFromPathUsingRunOptionsInternal( const SessionOptions& options, const RunOptions& run_options, const StringPiece export_dir, SessionBundle* const bundle) { LOG(INFO) << "Attempting to load a SessionBundle from: " << export_dir; LOG(INFO) << "Using RunOptions: " << DebugStringIfAvailable(run_options); TF_RETURN_IF_ERROR( GetMetaGraphDefFromExport(export_dir, &(bundle->meta_graph_def))); const auto& collection_def_map = bundle->meta_graph_def.collection_def(); const auto graph_it = bundle->meta_graph_def.collection_def().find(kGraphKey); if (graph_it != collection_def_map.end()) { const CollectionDef& graph_collection_def = graph_it->second; // Use serving graph_def in MetaGraphDef collection_def. if (graph_collection_def.any_list().value_size() != 1) { return errors::FailedPrecondition( "Expected exactly one serving GraphDef in : ", DebugStringIfAvailable(bundle->meta_graph_def)); } const auto& any = graph_collection_def.any_list().value(0); GraphDef graph_def; TF_RETURN_IF_ERROR(ParseAny(any, &graph_def, "tensorflow.GraphDef")); TF_RETURN_IF_ERROR( CreateSessionFromGraphDef(options, graph_def, &bundle->session)); } else { // Fallback to use the graph_def in the MetaGraphDef. const GraphDef& graph_def = bundle->meta_graph_def.graph_def(); TF_RETURN_IF_ERROR( CreateSessionFromGraphDef(options, graph_def, &bundle->session)); } std::vector<AssetFile> asset_files; const auto assets_it = collection_def_map.find(kAssetsKey); if (assets_it != collection_def_map.end()) { const auto& any_assets = assets_it->second.any_list().value(); for (const auto& any_asset : any_assets) { AssetFile asset_file; TF_RETURN_IF_ERROR( ParseAny(any_asset, &asset_file, "tensorflow.serving.AssetFile")); asset_files.push_back(asset_file); } } TF_RETURN_IF_ERROR( RunRestoreOp(run_options, export_dir, asset_files, bundle->meta_graph_def.saver_def().restore_op_name(), bundle->meta_graph_def.saver_def().filename_tensor_name(), bundle->session.get())); const auto init_op_it = collection_def_map.find(kInitOpKey); if (init_op_it != collection_def_map.end()) { if (init_op_it->second.node_list().value_size() != 1) { return errors::FailedPrecondition( strings::StrCat("Expected exactly one serving init op in : ", DebugStringIfAvailable(bundle->meta_graph_def))); } TF_RETURN_IF_ERROR(RunInitOp(run_options, export_dir, asset_files, init_op_it->second.node_list().value(0), bundle->session.get())); } return Status::OK(); } } // namespace Status LoadSessionBundleFromPath(const SessionOptions& options, const StringPiece export_dir, SessionBundle* const bundle) { TF_RETURN_IF_ERROR(LoadSessionBundleFromPathUsingRunOptions( options, RunOptions(), export_dir, bundle)); return Status::OK(); } Status LoadSessionBundleFromPathUsingRunOptions(const SessionOptions& options, const RunOptions& run_options, const StringPiece export_dir, SessionBundle* const bundle) { const uint64 start_microseconds = Env::Default()->NowMicros(); const Status status = LoadSessionBundleFromPathUsingRunOptionsInternal( options, run_options, export_dir, bundle); const uint64 load_latency_microsecs = [&]() -> uint64 { const uint64 end_microseconds = Env::Default()->NowMicros(); // Avoid clock skew. if (end_microseconds < start_microseconds) return 0; return end_microseconds - start_microseconds; }(); auto log_and_count = [&](const string& status_str) { LOG(INFO) << "Loading SessionBundle: " << status_str << ". Took " << load_latency_microsecs << " microseconds."; load_attempt_count->GetCell(export_dir.ToString(), status_str) ->IncrementBy(1); }; if (status.ok()) { log_and_count(kLoadAttemptSuccess); } else { log_and_count(kLoadAttemptFail); } load_latency->GetCell(export_dir.ToString()) ->IncrementBy(load_latency_microsecs); return status; } bool IsPossibleExportDirectory(const StringPiece directory) { const string meta_graph_def_path = io::JoinPath(directory, kMetaGraphDefFilename); return Env::Default()->FileExists(meta_graph_def_path); } } // namespace serving } // namespace tensorflow
Change metrics to accumulate load failures and successes in a single variable with labels. Change: 135717281
Change metrics to accumulate load failures and successes in a single variable with labels. Change: 135717281
C++
apache-2.0
eerwitt/tensorflow,Mistobaan/tensorflow,krikru/tensorflow-opencl,manazhao/tf_recsys,tensorflow/tensorflow-pywrap_saved_model,laszlocsomor/tensorflow,brchiu/tensorflow,dyoung418/tensorflow,tornadozou/tensorflow,scenarios/tensorflow,alsrgv/tensorflow,eadgarchen/tensorflow,theflofly/tensorflow,Intel-tensorflow/tensorflow,dancingdan/tensorflow,sandeepgupta2k4/tensorflow,hehongliang/tensorflow,meteorcloudy/tensorflow,aldian/tensorflow,hfp/tensorflow-xsmm,anilmuthineni/tensorflow,nburn42/tensorflow,girving/tensorflow,hehongliang/tensorflow,elingg/tensorflow,ZhangXinNan/tensorflow,laosiaudi/tensorflow,nanditav/15712-TensorFlow,caisq/tensorflow,JingJunYin/tensorflow,eerwitt/tensorflow,XueqingLin/tensorflow,adamtiger/tensorflow,Kongsea/tensorflow,memo/tensorflow,Xeralux/tensorflow,dendisuhubdy/tensorflow,jostep/tensorflow,av8ramit/tensorflow,pavelchristof/gomoku-ai,hsaputra/tensorflow,brchiu/tensorflow,vrv/tensorflow,vrv/tensorflow,dancingdan/tensorflow,scenarios/tensorflow,manjunaths/tensorflow,ville-k/tensorflow,sandeepdsouza93/TensorFlow-15712,laszlocsomor/tensorflow,hfp/tensorflow-xsmm,JVillella/tensorflow,allenlavoie/tensorflow,chris-chris/tensorflow,Kongsea/tensorflow,HKUST-SING/tensorflow,maciekcc/tensorflow,AnishShah/tensorflow,rabipanda/tensorflow,cancan101/tensorflow,sandeepgupta2k4/tensorflow,martinwicke/tensorflow,tensorflow/tensorflow,gojira/tensorflow,vrv/tensorflow,nightjean/Deep-Learning,tensorflow/tensorflow-experimental_link_static_libraries_once,meteorcloudy/tensorflow,MycChiu/tensorflow,ville-k/tensorflow,tillahoffmann/tensorflow,manazhao/tf_recsys,alistairlow/tensorflow,Bulochkin/tensorflow_pack,benoitsteiner/tensorflow,dancingdan/tensorflow,whn09/tensorflow,jwlawson/tensorflow,mixturemodel-flow/tensorflow,nightjean/Deep-Learning,wangyum/tensorflow,nightjean/Deep-Learning,dendisuhubdy/tensorflow,elingg/tensorflow,kevin-coder/tensorflow-fork,yaroslavvb/tensorflow,jalexvig/tensorflow,karllessard/tensorflow,pcm17/tensorflow,tiagofrepereira2012/tensorflow,meteorcloudy/tensorflow,chemelnucfin/tensorflow,kamcpp/tensorflow,alshedivat/tensorflow,suiyuan2009/tensorflow,pcm17/tensorflow,odejesush/tensorflow,JVillella/tensorflow,with-git/tensorflow,jendap/tensorflow,eadgarchen/tensorflow,guschmue/tensorflow,Intel-Corporation/tensorflow,jhaux/tensorflow,chemelnucfin/tensorflow,girving/tensorflow,tomasreimers/tensorflow-emscripten,jendap/tensorflow,annarev/tensorflow,ppwwyyxx/tensorflow,RapidApplicationDevelopment/tensorflow,mengxn/tensorflow,hsaputra/tensorflow,av8ramit/tensorflow,codrut3/tensorflow,Intel-tensorflow/tensorflow,zasdfgbnm/tensorflow,vrv/tensorflow,hfp/tensorflow-xsmm,kobejean/tensorflow,a-doumoulakis/tensorflow,cg31/tensorflow,hehongliang/tensorflow,mortada/tensorflow,ravindrapanda/tensorflow,maciekcc/tensorflow,dyoung418/tensorflow,mortada/tensorflow,DCSaunders/tensorflow,gunan/tensorflow,pierreg/tensorflow,JingJunYin/tensorflow,jhseu/tensorflow,arborh/tensorflow,davidzchen/tensorflow,code-sauce/tensorflow,theflofly/tensorflow,raymondxyang/tensorflow,AndreasMadsen/tensorflow,nanditav/15712-TensorFlow,mavenlin/tensorflow,AnishShah/tensorflow,ageron/tensorflow,gunan/tensorflow,hehongliang/tensorflow,gunan/tensorflow,lukeiwanski/tensorflow-opencl,arborh/tensorflow,jhseu/tensorflow,gnieboer/tensorflow,manazhao/tf_recsys,asadziach/tensorflow,tensorflow/tensorflow-pywrap_saved_model,manipopopo/tensorflow,ageron/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,a-doumoulakis/tensorflow,mortada/tensorflow,ppwwyyxx/tensorflow,cxxgtxy/tensorflow,arborh/tensorflow,kchodorow/tensorflow,martinwicke/tensorflow,RapidApplicationDevelopment/tensorflow,handroissuazo/tensorflow,XueqingLin/tensorflow,freedomtan/tensorflow,admcrae/tensorflow,tntnatbry/tensorflow,cg31/tensorflow,ibmsoe/tensorflow,alshedivat/tensorflow,nikste/tensorflow,kobejean/tensorflow,kamcpp/tensorflow,rabipanda/tensorflow,lukeiwanski/tensorflow-opencl,thesuperzapper/tensorflow,jeffzheng1/tensorflow,jbedorf/tensorflow,paolodedios/tensorflow,manazhao/tf_recsys,ppries/tensorflow,freedomtan/tensorflow,tornadozou/tensorflow,rabipanda/tensorflow,adit-chandra/tensorflow,HKUST-SING/tensorflow,llhe/tensorflow,alshedivat/tensorflow,abhitopia/tensorflow,chemelnucfin/tensorflow,nikste/tensorflow,tornadozou/tensorflow,Xeralux/tensorflow,pcm17/tensorflow,alisidd/tensorflow,haeusser/tensorflow,llhe/tensorflow,rdipietro/tensorflow,eadgarchen/tensorflow,memo/tensorflow,xzturn/tensorflow,laosiaudi/tensorflow,ville-k/tensorflow,JVillella/tensorflow,jbedorf/tensorflow,seaotterman/tensorflow,raymondxyang/tensorflow,tensorflow/tensorflow,nikste/tensorflow,unsiloai/syntaxnet-ops-hack,AnishShah/tensorflow,dancingdan/tensorflow,odejesush/tensorflow,dongjoon-hyun/tensorflow,krikru/tensorflow-opencl,alsrgv/tensorflow,nikste/tensorflow,mengxn/tensorflow,LUTAN/tensorflow,Intel-Corporation/tensorflow,calebfoss/tensorflow,odejesush/tensorflow,kobejean/tensorflow,asimshankar/tensorflow,Bismarrck/tensorflow,Kongsea/tensorflow,alisidd/tensorflow,dendisuhubdy/tensorflow,alsrgv/tensorflow,jalexvig/tensorflow,jostep/tensorflow,hsaputra/tensorflow,codrut3/tensorflow,tongwang01/tensorflow,thjashin/tensorflow,ppwwyyxx/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yanchen036/tensorflow,aam-at/tensorflow,ghchinoy/tensorflow,jhseu/tensorflow,maciekcc/tensorflow,chemelnucfin/tensorflow,aam-at/tensorflow,yufengg/tensorflow,asimshankar/tensorflow,Bulochkin/tensorflow_pack,zycdragonball/tensorflow,whn09/tensorflow,sarvex/tensorflow,theflofly/tensorflow,yufengg/tensorflow,av8ramit/tensorflow,haeusser/tensorflow,arborh/tensorflow,tornadozou/tensorflow,thjashin/tensorflow,cancan101/tensorflow,chenjun0210/tensorflow,strint/tensorflow,unsiloai/syntaxnet-ops-hack,a-doumoulakis/tensorflow,guschmue/tensorflow,snnn/tensorflow,hfp/tensorflow-xsmm,mortada/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,juharris/tensorflow,alivecor/tensorflow,elingg/tensorflow,lukeiwanski/tensorflow-opencl,Xeralux/tensorflow,Intel-tensorflow/tensorflow,wangyum/tensorflow,eaplatanios/tensorflow,abhitopia/tensorflow,Bismarrck/tensorflow,annarev/tensorflow,tongwang01/tensorflow,adamtiger/tensorflow,Mistobaan/tensorflow,thesuperzapper/tensorflow,apark263/tensorflow,adit-chandra/tensorflow,tiagofrepereira2012/tensorflow,yongtang/tensorflow,tensorflow/tensorflow,dyoung418/tensorflow,MoamerEncsConcordiaCa/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,andrewcmyers/tensorflow,jalexvig/tensorflow,caisq/tensorflow,Intel-Corporation/tensorflow,snnn/tensorflow,thjashin/tensorflow,odejesush/tensorflow,juharris/tensorflow,elingg/tensorflow,DavidNorman/tensorflow,andrewcmyers/tensorflow,jalexvig/tensorflow,strint/tensorflow,nburn42/tensorflow,nolanliou/tensorflow,mengxn/tensorflow,tensorflow/tensorflow-pywrap_saved_model,aam-at/tensorflow,whn09/tensorflow,memo/tensorflow,cg31/tensorflow,jalexvig/tensorflow,mdrumond/tensorflow,xzturn/tensorflow,seanli9jan/tensorflow,ville-k/tensorflow,krikru/tensorflow-opencl,benoitsteiner/tensorflow-xsmm,chris-chris/tensorflow,rdipietro/tensorflow,pavelchristof/gomoku-ai,taknevski/tensorflow-xsmm,with-git/tensorflow,alheinecke/tensorflow-xsmm,RapidApplicationDevelopment/tensorflow,ishay2b/tensorflow,memo/tensorflow,handroissuazo/tensorflow,benoitsteiner/tensorflow-opencl,admcrae/tensorflow,handroissuazo/tensorflow,ishay2b/tensorflow,renyi533/tensorflow,brchiu/tensorflow,Bismarrck/tensorflow,johndpope/tensorflow,Moriadry/tensorflow,girving/tensorflow,Kongsea/tensorflow,dancingdan/tensorflow,alheinecke/tensorflow-xsmm,anilmuthineni/tensorflow,snnn/tensorflow,yanchen036/tensorflow,AndreasMadsen/tensorflow,alsrgv/tensorflow,gunan/tensorflow,paolodedios/tensorflow,taknevski/tensorflow-xsmm,zycdragonball/tensorflow,davidzchen/tensorflow,ville-k/tensorflow,aselle/tensorflow,tillahoffmann/tensorflow,girving/tensorflow,brchiu/tensorflow,nikste/tensorflow,scenarios/tensorflow,horance-liu/tensorflow,nightjean/Deep-Learning,anilmuthineni/tensorflow,admcrae/tensorflow,scenarios/tensorflow,tillahoffmann/tensorflow,kobejean/tensorflow,krikru/tensorflow-opencl,aselle/tensorflow,adit-chandra/tensorflow,nolanliou/tensorflow,Mistobaan/tensorflow,suiyuan2009/tensorflow,snnn/tensorflow,HKUST-SING/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Mistobaan/tensorflow,alisidd/tensorflow,zasdfgbnm/tensorflow,tomasreimers/tensorflow-emscripten,aldian/tensorflow,jart/tensorflow,gunan/tensorflow,aldian/tensorflow,freedomtan/tensorflow,ppries/tensorflow,ran5515/DeepDecision,horance-liu/tensorflow,alshedivat/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,jhseu/tensorflow,asimshankar/tensorflow,aam-at/tensorflow,alsrgv/tensorflow,lukeiwanski/tensorflow,alistairlow/tensorflow,pierreg/tensorflow,whn09/tensorflow,chemelnucfin/tensorflow,LUTAN/tensorflow,brchiu/tensorflow,xodus7/tensorflow,alistairlow/tensorflow,gnieboer/tensorflow,eaplatanios/tensorflow,gibiansky/tensorflow,jeffzheng1/tensorflow,strint/tensorflow,alistairlow/tensorflow,memo/tensorflow,guschmue/tensorflow,juharris/tensorflow,seaotterman/tensorflow,vrv/tensorflow,kchodorow/tensorflow,AndreasMadsen/tensorflow,DCSaunders/tensorflow,Moriadry/tensorflow,zasdfgbnm/tensorflow,sarvex/tensorflow,horance-liu/tensorflow,scenarios/tensorflow,davidzchen/tensorflow,freedomtan/tensorflow,lakshayg/tensorflow,meteorcloudy/tensorflow,asimshankar/tensorflow,llhe/tensorflow,AnishShah/tensorflow,jhseu/tensorflow,jeffzheng1/tensorflow,manjunaths/tensorflow,gibiansky/tensorflow,admcrae/tensorflow,ravindrapanda/tensorflow,yanchen036/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,ZhangXinNan/tensorflow,anilmuthineni/tensorflow,martinwicke/tensorflow,suiyuan2009/tensorflow,drpngx/tensorflow,seaotterman/tensorflow,allenlavoie/tensorflow,jbedorf/tensorflow,bowang/tensorflow,nolanliou/tensorflow,haeusser/tensorflow,ville-k/tensorflow,kobejean/tensorflow,renyi533/tensorflow,taknevski/tensorflow-xsmm,ychfan/tensorflow,sjperkins/tensorflow,frreiss/tensorflow-fred,ville-k/tensorflow,handroissuazo/tensorflow,petewarden/tensorflow,bowang/tensorflow,raymondxyang/tensorflow,sandeepdsouza93/TensorFlow-15712,jostep/tensorflow,handroissuazo/tensorflow,ageron/tensorflow,gnieboer/tensorflow,chenjun0210/tensorflow,tillahoffmann/tensorflow,nikste/tensorflow,frreiss/tensorflow-fred,seaotterman/tensorflow,ageron/tensorflow,arborh/tensorflow,arborh/tensorflow,ZhangXinNan/tensorflow,jostep/tensorflow,lukeiwanski/tensorflow,SnakeJenny/TensorFlow,sjperkins/tensorflow,jalexvig/tensorflow,alshedivat/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_tf_optimizer,horance-liu/tensorflow,allenlavoie/tensorflow,jbedorf/tensorflow,kchodorow/tensorflow,alivecor/tensorflow,unsiloai/syntaxnet-ops-hack,sandeepgupta2k4/tensorflow,drpngx/tensorflow,jart/tensorflow,freedomtan/tensorflow,frreiss/tensorflow-fred,alheinecke/tensorflow-xsmm,alheinecke/tensorflow-xsmm,johndpope/tensorflow,nanditav/15712-TensorFlow,maciekcc/tensorflow,MycChiu/tensorflow,theflofly/tensorflow,eerwitt/tensorflow,kevin-coder/tensorflow-fork,Carmezim/tensorflow,elingg/tensorflow,tensorflow/tensorflow,jalexvig/tensorflow,markslwong/tensorflow,alivecor/tensorflow,theflofly/tensorflow,memo/tensorflow,SnakeJenny/TensorFlow,JingJunYin/tensorflow,MoamerEncsConcordiaCa/tensorflow,sandeepgupta2k4/tensorflow,anand-c-goog/tensorflow,snnn/tensorflow,laosiaudi/tensorflow,mengxn/tensorflow,ibmsoe/tensorflow,lukeiwanski/tensorflow,seanli9jan/tensorflow,SnakeJenny/TensorFlow,sjperkins/tensorflow,ghchinoy/tensorflow,SnakeJenny/TensorFlow,rdipietro/tensorflow,Bismarrck/tensorflow,AnishShah/tensorflow,XueqingLin/tensorflow,pierreg/tensorflow,jhseu/tensorflow,alisidd/tensorflow,jeffzheng1/tensorflow,aam-at/tensorflow,thjashin/tensorflow,gautam1858/tensorflow,anilmuthineni/tensorflow,Kongsea/tensorflow,cancan101/tensorflow,Moriadry/tensorflow,bowang/tensorflow,markslwong/tensorflow,ageron/tensorflow,HKUST-SING/tensorflow,anand-c-goog/tensorflow,girving/tensorflow,vrv/tensorflow,nolanliou/tensorflow,LUTAN/tensorflow,adamtiger/tensorflow,gunan/tensorflow,asadziach/tensorflow,with-git/tensorflow,gautam1858/tensorflow,adit-chandra/tensorflow,dancingdan/tensorflow,apark263/tensorflow,HKUST-SING/tensorflow,jwlawson/tensorflow,benoitsteiner/tensorflow-xsmm,kamcpp/tensorflow,kchodorow/tensorflow,gojira/tensorflow,pavelchristof/gomoku-ai,pcm17/tensorflow,av8ramit/tensorflow,aselle/tensorflow,yaroslavvb/tensorflow,cxxgtxy/tensorflow,martinwicke/tensorflow,seanli9jan/tensorflow,kchodorow/tensorflow,davidzchen/tensorflow,paolodedios/tensorflow,suiyuan2009/tensorflow,pavelchristof/gomoku-ai,annarev/tensorflow,AndreasMadsen/tensorflow,karllessard/tensorflow,anand-c-goog/tensorflow,apark263/tensorflow,code-sauce/tensorflow,eadgarchen/tensorflow,AnishShah/tensorflow,sandeepdsouza93/TensorFlow-15712,tornadozou/tensorflow,johndpope/tensorflow,lukeiwanski/tensorflow-opencl,cxxgtxy/tensorflow,horance-liu/tensorflow,ishay2b/tensorflow,gunan/tensorflow,scenarios/tensorflow,mengxn/tensorflow,alshedivat/tensorflow,gnieboer/tensorflow,dongjoon-hyun/tensorflow,benoitsteiner/tensorflow-opencl,tntnatbry/tensorflow,Mistobaan/tensorflow,gautam1858/tensorflow,benoitsteiner/tensorflow,ppries/tensorflow,ychfan/tensorflow,bowang/tensorflow,ArtsiomCh/tensorflow,xzturn/tensorflow,jbedorf/tensorflow,anand-c-goog/tensorflow,manipopopo/tensorflow,alistairlow/tensorflow,calebfoss/tensorflow,rabipanda/tensorflow,jhseu/tensorflow,gnieboer/tensorflow,johndpope/tensorflow,yanchen036/tensorflow,tntnatbry/tensorflow,cg31/tensorflow,adit-chandra/tensorflow,alheinecke/tensorflow-xsmm,jostep/tensorflow,allenlavoie/tensorflow,zasdfgbnm/tensorflow,Bismarrck/tensorflow,xodus7/tensorflow,johndpope/tensorflow,davidzchen/tensorflow,lakshayg/tensorflow,ageron/tensorflow,odejesush/tensorflow,alsrgv/tensorflow,taknevski/tensorflow-xsmm,johndpope/tensorflow,alshedivat/tensorflow,yufengg/tensorflow,ghchinoy/tensorflow,llhe/tensorflow,rabipanda/tensorflow,handroissuazo/tensorflow,jhseu/tensorflow,ArtsiomCh/tensorflow,allenlavoie/tensorflow,Mazecreator/tensorflow,tiagofrepereira2012/tensorflow,sandeepdsouza93/TensorFlow-15712,jalexvig/tensorflow,benoitsteiner/tensorflow-xsmm,jeffzheng1/tensorflow,benoitsteiner/tensorflow,zasdfgbnm/tensorflow,ishay2b/tensorflow,apark263/tensorflow,dongjoon-hyun/tensorflow,meteorcloudy/tensorflow,gautam1858/tensorflow,code-sauce/tensorflow,allenlavoie/tensorflow,pavelchristof/gomoku-ai,rabipanda/tensorflow,arborh/tensorflow,frreiss/tensorflow-fred,gojira/tensorflow,DavidNorman/tensorflow,Intel-tensorflow/tensorflow,gnieboer/tensorflow,paolodedios/tensorflow,chemelnucfin/tensorflow,AndreasMadsen/tensorflow,chenjun0210/tensorflow,petewarden/tensorflow,nolanliou/tensorflow,sarvex/tensorflow,aldian/tensorflow,haeusser/tensorflow,ZhangXinNan/tensorflow,AnishShah/tensorflow,martinwicke/tensorflow,nburn42/tensorflow,laszlocsomor/tensorflow,mixturemodel-flow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,odejesush/tensorflow,davidzchen/tensorflow,karllessard/tensorflow,lukeiwanski/tensorflow-opencl,kamcpp/tensorflow,Xeralux/tensorflow,hfp/tensorflow-xsmm,chenjun0210/tensorflow,pcm17/tensorflow,pierreg/tensorflow,memo/tensorflow,xodus7/tensorflow,alivecor/tensorflow,MoamerEncsConcordiaCa/tensorflow,cxxgtxy/tensorflow,scenarios/tensorflow,kobejean/tensorflow,ychfan/tensorflow,petewarden/tensorflow,a-doumoulakis/tensorflow,Intel-Corporation/tensorflow,JingJunYin/tensorflow,asimshankar/tensorflow,chemelnucfin/tensorflow,juharris/tensorflow,AnishShah/tensorflow,xodus7/tensorflow,nburn42/tensorflow,tongwang01/tensorflow,caisq/tensorflow,karllessard/tensorflow,apark263/tensorflow,gojira/tensorflow,ychfan/tensorflow,manjunaths/tensorflow,jart/tensorflow,girving/tensorflow,jart/tensorflow,gautam1858/tensorflow,ZhangXinNan/tensorflow,laszlocsomor/tensorflow,guschmue/tensorflow,ppwwyyxx/tensorflow,DavidNorman/tensorflow,xzturn/tensorflow,snnn/tensorflow,hehongliang/tensorflow,ravindrapanda/tensorflow,tornadozou/tensorflow,Intel-tensorflow/tensorflow,adamtiger/tensorflow,xzturn/tensorflow,jeffzheng1/tensorflow,adit-chandra/tensorflow,mdrumond/tensorflow,thesuperzapper/tensorflow,bowang/tensorflow,hsaputra/tensorflow,jwlawson/tensorflow,manipopopo/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,annarev/tensorflow,xodus7/tensorflow,tornadozou/tensorflow,gojira/tensorflow,eaplatanios/tensorflow,alsrgv/tensorflow,xodus7/tensorflow,hfp/tensorflow-xsmm,tiagofrepereira2012/tensorflow,renyi533/tensorflow,with-git/tensorflow,aselle/tensorflow,chemelnucfin/tensorflow,caisq/tensorflow,Bismarrck/tensorflow,hsaputra/tensorflow,dongjoon-hyun/tensorflow,meteorcloudy/tensorflow,sandeepgupta2k4/tensorflow,dendisuhubdy/tensorflow,mixturemodel-flow/tensorflow,with-git/tensorflow,MycChiu/tensorflow,mixturemodel-flow/tensorflow,krikru/tensorflow-opencl,llhe/tensorflow,ppries/tensorflow,chris-chris/tensorflow,frreiss/tensorflow-fred,manipopopo/tensorflow,DCSaunders/tensorflow,kamcpp/tensorflow,jwlawson/tensorflow,andrewcmyers/tensorflow,paolodedios/tensorflow,zycdragonball/tensorflow,paolodedios/tensorflow,alisidd/tensorflow,JVillella/tensorflow,benoitsteiner/tensorflow,tomasreimers/tensorflow-emscripten,raymondxyang/tensorflow,ZhangXinNan/tensorflow,Carmezim/tensorflow,haeusser/tensorflow,code-sauce/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gnieboer/tensorflow,Carmezim/tensorflow,cancan101/tensorflow,ArtsiomCh/tensorflow,yongtang/tensorflow,laosiaudi/tensorflow,cxxgtxy/tensorflow,alsrgv/tensorflow,aselle/tensorflow,codrut3/tensorflow,thesuperzapper/tensorflow,Bulochkin/tensorflow_pack,asadziach/tensorflow,yongtang/tensorflow,admcrae/tensorflow,handroissuazo/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,ychfan/tensorflow,frreiss/tensorflow-fred,JingJunYin/tensorflow,calebfoss/tensorflow,llhe/tensorflow,hsaputra/tensorflow,anilmuthineni/tensorflow,jart/tensorflow,admcrae/tensorflow,laszlocsomor/tensorflow,markslwong/tensorflow,taknevski/tensorflow-xsmm,guschmue/tensorflow,lukeiwanski/tensorflow,eaplatanios/tensorflow,brchiu/tensorflow,drpngx/tensorflow,kobejean/tensorflow,dongjoon-hyun/tensorflow,lukeiwanski/tensorflow-opencl,asimshankar/tensorflow,XueqingLin/tensorflow,Mistobaan/tensorflow,yongtang/tensorflow,aselle/tensorflow,ppries/tensorflow,Xeralux/tensorflow,AndreasMadsen/tensorflow,drpngx/tensorflow,dendisuhubdy/tensorflow,DCSaunders/tensorflow,ibmsoe/tensorflow,Bismarrck/tensorflow,dongjoon-hyun/tensorflow,llhe/tensorflow,cg31/tensorflow,eadgarchen/tensorflow,asimshankar/tensorflow,drpngx/tensorflow,yufengg/tensorflow,ZhangXinNan/tensorflow,Moriadry/tensorflow,jostep/tensorflow,kevin-coder/tensorflow-fork,jendap/tensorflow,annarev/tensorflow,pcm17/tensorflow,jendap/tensorflow,benoitsteiner/tensorflow,theflofly/tensorflow,MycChiu/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,krikru/tensorflow-opencl,with-git/tensorflow,snnn/tensorflow,Mazecreator/tensorflow,haeusser/tensorflow,jart/tensorflow,DCSaunders/tensorflow,dancingdan/tensorflow,xzturn/tensorflow,calebfoss/tensorflow,SnakeJenny/TensorFlow,gunan/tensorflow,eadgarchen/tensorflow,martinwicke/tensorflow,arborh/tensorflow,llhe/tensorflow,gojira/tensorflow,jalexvig/tensorflow,Bismarrck/tensorflow,Mistobaan/tensorflow,gautam1858/tensorflow,dendisuhubdy/tensorflow,renyi533/tensorflow,annarev/tensorflow,code-sauce/tensorflow,horance-liu/tensorflow,jwlawson/tensorflow,jbedorf/tensorflow,cg31/tensorflow,seanli9jan/tensorflow,handroissuazo/tensorflow,davidzchen/tensorflow,rabipanda/tensorflow,sjperkins/tensorflow,nikste/tensorflow,Mistobaan/tensorflow,benoitsteiner/tensorflow,guschmue/tensorflow,eaplatanios/tensorflow,petewarden/tensorflow,LUTAN/tensorflow,cxxgtxy/tensorflow,drpngx/tensorflow,wangyum/tensorflow,dancingdan/tensorflow,zasdfgbnm/tensorflow,alshedivat/tensorflow,snnn/tensorflow,jbedorf/tensorflow,thjashin/tensorflow,johndpope/tensorflow,aselle/tensorflow,meteorcloudy/tensorflow,anilmuthineni/tensorflow,xodus7/tensorflow,davidzchen/tensorflow,paolodedios/tensorflow,MoamerEncsConcordiaCa/tensorflow,gautam1858/tensorflow,kobejean/tensorflow,ran5515/DeepDecision,laszlocsomor/tensorflow,adit-chandra/tensorflow,chris-chris/tensorflow,chemelnucfin/tensorflow,LUTAN/tensorflow,pierreg/tensorflow,markslwong/tensorflow,llhe/tensorflow,pcm17/tensorflow,alheinecke/tensorflow-xsmm,vrv/tensorflow,gojira/tensorflow,suiyuan2009/tensorflow,paolodedios/tensorflow,MoamerEncsConcordiaCa/tensorflow,eaplatanios/tensorflow,whn09/tensorflow,alisidd/tensorflow,zycdragonball/tensorflow,caisq/tensorflow,Bulochkin/tensorflow_pack,jeffzheng1/tensorflow,theflofly/tensorflow,ran5515/DeepDecision,Bismarrck/tensorflow,hfp/tensorflow-xsmm,aselle/tensorflow,sjperkins/tensorflow,mdrumond/tensorflow,xzturn/tensorflow,ville-k/tensorflow,xzturn/tensorflow,dyoung418/tensorflow,alshedivat/tensorflow,alisidd/tensorflow,jostep/tensorflow,ppwwyyxx/tensorflow,sjperkins/tensorflow,alistairlow/tensorflow,gautam1858/tensorflow,nanditav/15712-TensorFlow,nightjean/Deep-Learning,yaroslavvb/tensorflow,aam-at/tensorflow,paolodedios/tensorflow,cxxgtxy/tensorflow,ran5515/DeepDecision,Carmezim/tensorflow,theflofly/tensorflow,lakshayg/tensorflow,brchiu/tensorflow,zasdfgbnm/tensorflow,rdipietro/tensorflow,maciekcc/tensorflow,benoitsteiner/tensorflow-opencl,Mazecreator/tensorflow,gibiansky/tensorflow,sjperkins/tensorflow,kobejean/tensorflow,ychfan/tensorflow,DavidNorman/tensorflow,ppwwyyxx/tensorflow,chemelnucfin/tensorflow,benoitsteiner/tensorflow-xsmm,aldian/tensorflow,Bulochkin/tensorflow_pack,Bulochkin/tensorflow_pack,ghchinoy/tensorflow,aam-at/tensorflow,karllessard/tensorflow,abhitopia/tensorflow,annarev/tensorflow,andrewcmyers/tensorflow,mengxn/tensorflow,sandeepdsouza93/TensorFlow-15712,dongjoon-hyun/tensorflow,kevin-coder/tensorflow-fork,andrewcmyers/tensorflow,Bulochkin/tensorflow_pack,hsaputra/tensorflow,thesuperzapper/tensorflow,thjashin/tensorflow,MycChiu/tensorflow,JVillella/tensorflow,alisidd/tensorflow,llhe/tensorflow,girving/tensorflow,ishay2b/tensorflow,andrewcmyers/tensorflow,sarvex/tensorflow,AndreasMadsen/tensorflow,frreiss/tensorflow-fred,jhseu/tensorflow,kevin-coder/tensorflow-fork,benoitsteiner/tensorflow-xsmm,strint/tensorflow,ravindrapanda/tensorflow,asadziach/tensorflow,jwlawson/tensorflow,ageron/tensorflow,asadziach/tensorflow,gojira/tensorflow,cancan101/tensorflow,mavenlin/tensorflow,gautam1858/tensorflow,xodus7/tensorflow,gnieboer/tensorflow,tensorflow/tensorflow,nanditav/15712-TensorFlow,wangyum/tensorflow,benoitsteiner/tensorflow-xsmm,raymondxyang/tensorflow,gunan/tensorflow,mavenlin/tensorflow,av8ramit/tensorflow,code-sauce/tensorflow,ageron/tensorflow,juharris/tensorflow,nightjean/Deep-Learning,calebfoss/tensorflow,lakshayg/tensorflow,nanditav/15712-TensorFlow,DavidNorman/tensorflow,ZhangXinNan/tensorflow,johndpope/tensorflow,benoitsteiner/tensorflow-xsmm,MycChiu/tensorflow,mortada/tensorflow,markslwong/tensorflow,bowang/tensorflow,Intel-Corporation/tensorflow,juharris/tensorflow,seaotterman/tensorflow,snnn/tensorflow,DavidNorman/tensorflow,seanli9jan/tensorflow,DCSaunders/tensorflow,gautam1858/tensorflow,codrut3/tensorflow,tongwang01/tensorflow,eerwitt/tensorflow,arborh/tensorflow,JVillella/tensorflow,nolanliou/tensorflow,Carmezim/tensorflow,Carmezim/tensorflow,apark263/tensorflow,ageron/tensorflow,av8ramit/tensorflow,anand-c-goog/tensorflow,JVillella/tensorflow,ppries/tensorflow,frreiss/tensorflow-fred,HKUST-SING/tensorflow,gibiansky/tensorflow,dyoung418/tensorflow,nolanliou/tensorflow,hfp/tensorflow-xsmm,karllessard/tensorflow,asimshankar/tensorflow,handroissuazo/tensorflow,ravindrapanda/tensorflow,yufengg/tensorflow,ibmsoe/tensorflow,snnn/tensorflow,abhitopia/tensorflow,jendap/tensorflow,ZhangXinNan/tensorflow,JingJunYin/tensorflow,seaotterman/tensorflow,sarvex/tensorflow,strint/tensorflow,ibmsoe/tensorflow,benoitsteiner/tensorflow-xsmm,haeusser/tensorflow,tiagofrepereira2012/tensorflow,manipopopo/tensorflow,hsaputra/tensorflow,odejesush/tensorflow,yaroslavvb/tensorflow,theflofly/tensorflow,nikste/tensorflow,tensorflow/tensorflow,yaroslavvb/tensorflow,codrut3/tensorflow,laosiaudi/tensorflow,Bulochkin/tensorflow_pack,girving/tensorflow,thjashin/tensorflow,laosiaudi/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yanchen036/tensorflow,kevin-coder/tensorflow-fork,zycdragonball/tensorflow,ibmsoe/tensorflow,benoitsteiner/tensorflow,markslwong/tensorflow,annarev/tensorflow,nikste/tensorflow,manazhao/tf_recsys,av8ramit/tensorflow,tntnatbry/tensorflow,jendap/tensorflow,tomasreimers/tensorflow-emscripten,cancan101/tensorflow,manipopopo/tensorflow,manjunaths/tensorflow,aselle/tensorflow,nolanliou/tensorflow,tiagofrepereira2012/tensorflow,a-doumoulakis/tensorflow,petewarden/tensorflow,aam-at/tensorflow,rabipanda/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,raymondxyang/tensorflow,wangyum/tensorflow,freedomtan/tensorflow,HKUST-SING/tensorflow,ishay2b/tensorflow,davidzchen/tensorflow,paolodedios/tensorflow,elingg/tensorflow,ArtsiomCh/tensorflow,ageron/tensorflow,theflofly/tensorflow,jhaux/tensorflow,tomasreimers/tensorflow-emscripten,sandeepgupta2k4/tensorflow,hsaputra/tensorflow,lukeiwanski/tensorflow,zasdfgbnm/tensorflow,apark263/tensorflow,tensorflow/tensorflow,Xeralux/tensorflow,ishay2b/tensorflow,av8ramit/tensorflow,suiyuan2009/tensorflow,annarev/tensorflow,lukeiwanski/tensorflow,meteorcloudy/tensorflow,tntnatbry/tensorflow,ZhangXinNan/tensorflow,DavidNorman/tensorflow,thjashin/tensorflow,manipopopo/tensorflow,DavidNorman/tensorflow,adamtiger/tensorflow,eerwitt/tensorflow,benoitsteiner/tensorflow-opencl,Moriadry/tensorflow,yufengg/tensorflow,gibiansky/tensorflow,alshedivat/tensorflow,memo/tensorflow,karllessard/tensorflow,anand-c-goog/tensorflow,alsrgv/tensorflow,calebfoss/tensorflow,vrv/tensorflow,hehongliang/tensorflow,aam-at/tensorflow,manipopopo/tensorflow,chris-chris/tensorflow,benoitsteiner/tensorflow-xsmm,taknevski/tensorflow-xsmm,alsrgv/tensorflow,hfp/tensorflow-xsmm,sandeepdsouza93/TensorFlow-15712,vrv/tensorflow,eerwitt/tensorflow,MoamerEncsConcordiaCa/tensorflow,ran5515/DeepDecision,AnishShah/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,elingg/tensorflow,laosiaudi/tensorflow,unsiloai/syntaxnet-ops-hack,jwlawson/tensorflow,XueqingLin/tensorflow,hfp/tensorflow-xsmm,DCSaunders/tensorflow,karllessard/tensorflow,thjashin/tensorflow,whn09/tensorflow,benoitsteiner/tensorflow-xsmm,asimshankar/tensorflow,ravindrapanda/tensorflow,andrewcmyers/tensorflow,calebfoss/tensorflow,dancingdan/tensorflow,mortada/tensorflow,mavenlin/tensorflow,kevin-coder/tensorflow-fork,yaroslavvb/tensorflow,alistairlow/tensorflow,jendap/tensorflow,Bulochkin/tensorflow_pack,frreiss/tensorflow-fred,renyi533/tensorflow,asadziach/tensorflow,dendisuhubdy/tensorflow,ppwwyyxx/tensorflow,alistairlow/tensorflow,hehongliang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,ychfan/tensorflow,eaplatanios/tensorflow,gibiansky/tensorflow,jwlawson/tensorflow,chris-chris/tensorflow,codrut3/tensorflow,xodus7/tensorflow,sjperkins/tensorflow,rabipanda/tensorflow,ibmsoe/tensorflow,sandeepdsouza93/TensorFlow-15712,alivecor/tensorflow,aam-at/tensorflow,Xeralux/tensorflow,whn09/tensorflow,LUTAN/tensorflow,alistairlow/tensorflow,AndreasMadsen/tensorflow,girving/tensorflow,juharris/tensorflow,drpngx/tensorflow,tongwang01/tensorflow,calebfoss/tensorflow,nburn42/tensorflow,xzturn/tensorflow,jendap/tensorflow,manazhao/tf_recsys,tomasreimers/tensorflow-emscripten,Kongsea/tensorflow,Intel-tensorflow/tensorflow,ghchinoy/tensorflow,sandeepdsouza93/TensorFlow-15712,seaotterman/tensorflow,adit-chandra/tensorflow,Bulochkin/tensorflow_pack,arborh/tensorflow,thesuperzapper/tensorflow,asadziach/tensorflow,RapidApplicationDevelopment/tensorflow,jhseu/tensorflow,mavenlin/tensorflow,jendap/tensorflow,mdrumond/tensorflow,abhitopia/tensorflow,dancingdan/tensorflow,sandeepgupta2k4/tensorflow,lakshayg/tensorflow,wangyum/tensorflow,Intel-tensorflow/tensorflow,alheinecke/tensorflow-xsmm,suiyuan2009/tensorflow,Xeralux/tensorflow,juharris/tensorflow,karllessard/tensorflow,rabipanda/tensorflow,alshedivat/tensorflow,nburn42/tensorflow,memo/tensorflow,krikru/tensorflow-opencl,petewarden/tensorflow,strint/tensorflow,mavenlin/tensorflow,drpngx/tensorflow,alsrgv/tensorflow,MoamerEncsConcordiaCa/tensorflow,Mistobaan/tensorflow,benoitsteiner/tensorflow-opencl,ghchinoy/tensorflow,freedomtan/tensorflow,sarvex/tensorflow,ageron/tensorflow,dendisuhubdy/tensorflow,XueqingLin/tensorflow,krikru/tensorflow-opencl,gibiansky/tensorflow,xodus7/tensorflow,aam-at/tensorflow,ghchinoy/tensorflow,eadgarchen/tensorflow,ArtsiomCh/tensorflow,jwlawson/tensorflow,mengxn/tensorflow,tntnatbry/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,strint/tensorflow,jeffzheng1/tensorflow,nanditav/15712-TensorFlow,ArtsiomCh/tensorflow,LUTAN/tensorflow,jalexvig/tensorflow,XueqingLin/tensorflow,freedomtan/tensorflow,yongtang/tensorflow,unsiloai/syntaxnet-ops-hack,thesuperzapper/tensorflow,martinwicke/tensorflow,Xeralux/tensorflow,nightjean/Deep-Learning,ravindrapanda/tensorflow,gunan/tensorflow,ArtsiomCh/tensorflow,codrut3/tensorflow,code-sauce/tensorflow,kamcpp/tensorflow,seanli9jan/tensorflow,eerwitt/tensorflow,xodus7/tensorflow,eadgarchen/tensorflow,dendisuhubdy/tensorflow,benoitsteiner/tensorflow-opencl,horance-liu/tensorflow,eaplatanios/tensorflow,DavidNorman/tensorflow,meteorcloudy/tensorflow,horance-liu/tensorflow,mixturemodel-flow/tensorflow,Mazecreator/tensorflow,zasdfgbnm/tensorflow,yongtang/tensorflow,RapidApplicationDevelopment/tensorflow,Bismarrck/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gojira/tensorflow,codrut3/tensorflow,strint/tensorflow,tensorflow/tensorflow-pywrap_saved_model,odejesush/tensorflow,mixturemodel-flow/tensorflow,Mazecreator/tensorflow,yaroslavvb/tensorflow,anand-c-goog/tensorflow,guschmue/tensorflow,Mazecreator/tensorflow,ppries/tensorflow,cxxgtxy/tensorflow,lukeiwanski/tensorflow-opencl,davidzchen/tensorflow,Bulochkin/tensorflow_pack,cancan101/tensorflow,tensorflow/tensorflow,jbedorf/tensorflow,chris-chris/tensorflow,AnishShah/tensorflow,raymondxyang/tensorflow,taknevski/tensorflow-xsmm,manipopopo/tensorflow,hfp/tensorflow-xsmm,brchiu/tensorflow,tensorflow/tensorflow-pywrap_saved_model,pavelchristof/gomoku-ai,sandeepdsouza93/TensorFlow-15712,manipopopo/tensorflow,yanchen036/tensorflow,freedomtan/tensorflow,mdrumond/tensorflow,kchodorow/tensorflow,nburn42/tensorflow,taknevski/tensorflow-xsmm,zycdragonball/tensorflow,ville-k/tensorflow,ghchinoy/tensorflow,chris-chris/tensorflow,kamcpp/tensorflow,av8ramit/tensorflow,guschmue/tensorflow,Carmezim/tensorflow,freedomtan/tensorflow,jhaux/tensorflow,manipopopo/tensorflow,cg31/tensorflow,thesuperzapper/tensorflow,kchodorow/tensorflow,Kongsea/tensorflow,mortada/tensorflow,lukeiwanski/tensorflow-opencl,kchodorow/tensorflow,asimshankar/tensorflow,jhaux/tensorflow,tomasreimers/tensorflow-emscripten,cg31/tensorflow,renyi533/tensorflow,raymondxyang/tensorflow,adit-chandra/tensorflow,rdipietro/tensorflow,caisq/tensorflow,jbedorf/tensorflow,manjunaths/tensorflow,renyi533/tensorflow,zasdfgbnm/tensorflow,SnakeJenny/TensorFlow,gautam1858/tensorflow,tillahoffmann/tensorflow,gunan/tensorflow,apark263/tensorflow,RapidApplicationDevelopment/tensorflow,a-doumoulakis/tensorflow,Moriadry/tensorflow,abhitopia/tensorflow,petewarden/tensorflow,asadziach/tensorflow,petewarden/tensorflow,yanchen036/tensorflow,tntnatbry/tensorflow,yongtang/tensorflow,odejesush/tensorflow,krikru/tensorflow-opencl,dongjoon-hyun/tensorflow,nanditav/15712-TensorFlow,benoitsteiner/tensorflow-xsmm,seaotterman/tensorflow,jart/tensorflow,alivecor/tensorflow,HKUST-SING/tensorflow,anand-c-goog/tensorflow,strint/tensorflow,lukeiwanski/tensorflow,tensorflow/tensorflow-pywrap_saved_model,caisq/tensorflow,whn09/tensorflow,jhaux/tensorflow,codrut3/tensorflow,av8ramit/tensorflow,jbedorf/tensorflow,jhseu/tensorflow,unsiloai/syntaxnet-ops-hack,ageron/tensorflow,ppries/tensorflow,sarvex/tensorflow,MoamerEncsConcordiaCa/tensorflow,chenjun0210/tensorflow,elingg/tensorflow,lukeiwanski/tensorflow,Intel-tensorflow/tensorflow,chenjun0210/tensorflow,ychfan/tensorflow,aldian/tensorflow,seanli9jan/tensorflow,kevin-coder/tensorflow-fork,theflofly/tensorflow,tongwang01/tensorflow,dyoung418/tensorflow,allenlavoie/tensorflow,haeusser/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,jbedorf/tensorflow,MycChiu/tensorflow,MoamerEncsConcordiaCa/tensorflow,aselle/tensorflow,ghchinoy/tensorflow,jhseu/tensorflow,yongtang/tensorflow,taknevski/tensorflow-xsmm,tongwang01/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,elingg/tensorflow,tillahoffmann/tensorflow,pierreg/tensorflow,Xeralux/tensorflow,xzturn/tensorflow,Intel-Corporation/tensorflow,SnakeJenny/TensorFlow,abhitopia/tensorflow,ppwwyyxx/tensorflow,kobejean/tensorflow,frreiss/tensorflow-fred,DCSaunders/tensorflow,ychfan/tensorflow,manazhao/tf_recsys,laszlocsomor/tensorflow,av8ramit/tensorflow,cg31/tensorflow,manjunaths/tensorflow,nightjean/Deep-Learning,sjperkins/tensorflow,kchodorow/tensorflow,gibiansky/tensorflow,kamcpp/tensorflow,aam-at/tensorflow,thesuperzapper/tensorflow,martinwicke/tensorflow,benoitsteiner/tensorflow,adamtiger/tensorflow,tillahoffmann/tensorflow,JingJunYin/tensorflow,cancan101/tensorflow,mdrumond/tensorflow,davidzchen/tensorflow,dongjoon-hyun/tensorflow,theflofly/tensorflow,xzturn/tensorflow,manjunaths/tensorflow,chris-chris/tensorflow,tomasreimers/tensorflow-emscripten,eadgarchen/tensorflow,allenlavoie/tensorflow,seanli9jan/tensorflow,with-git/tensorflow,MycChiu/tensorflow,rabipanda/tensorflow,annarev/tensorflow,ghchinoy/tensorflow,davidzchen/tensorflow,seaotterman/tensorflow,eaplatanios/tensorflow,dendisuhubdy/tensorflow,dongjoon-hyun/tensorflow,jendap/tensorflow,brchiu/tensorflow,sjperkins/tensorflow,guschmue/tensorflow,tomasreimers/tensorflow-emscripten,seanli9jan/tensorflow,Moriadry/tensorflow,tensorflow/tensorflow-pywrap_saved_model,laszlocsomor/tensorflow,petewarden/tensorflow,arborh/tensorflow,yanchen036/tensorflow,pcm17/tensorflow,nburn42/tensorflow,seanli9jan/tensorflow,asimshankar/tensorflow,DCSaunders/tensorflow,lakshayg/tensorflow,bowang/tensorflow,a-doumoulakis/tensorflow,asadziach/tensorflow,dongjoon-hyun/tensorflow,ZhangXinNan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gojira/tensorflow,yongtang/tensorflow,eaplatanios/tensorflow,Mistobaan/tensorflow,eerwitt/tensorflow,Xeralux/tensorflow,seanli9jan/tensorflow,adit-chandra/tensorflow,ghchinoy/tensorflow,ppwwyyxx/tensorflow,johndpope/tensorflow,alsrgv/tensorflow,drpngx/tensorflow,zycdragonball/tensorflow,chenjun0210/tensorflow,wangyum/tensorflow,chemelnucfin/tensorflow,alheinecke/tensorflow-xsmm,andrewcmyers/tensorflow,allenlavoie/tensorflow,markslwong/tensorflow,XueqingLin/tensorflow,dyoung418/tensorflow,kevin-coder/tensorflow-fork,anilmuthineni/tensorflow,eerwitt/tensorflow,tensorflow/tensorflow-pywrap_saved_model,laosiaudi/tensorflow,alheinecke/tensorflow-xsmm,yaroslavvb/tensorflow,ibmsoe/tensorflow,Intel-Corporation/tensorflow,nburn42/tensorflow,paolodedios/tensorflow,Kongsea/tensorflow,benoitsteiner/tensorflow,DavidNorman/tensorflow,Intel-tensorflow/tensorflow,nburn42/tensorflow,caisq/tensorflow,kamcpp/tensorflow,XueqingLin/tensorflow,petewarden/tensorflow,benoitsteiner/tensorflow-opencl,sandeepgupta2k4/tensorflow,mengxn/tensorflow,renyi533/tensorflow,DavidNorman/tensorflow,ghchinoy/tensorflow,laosiaudi/tensorflow,xzturn/tensorflow,bowang/tensorflow,jbedorf/tensorflow,kevin-coder/tensorflow-fork,pcm17/tensorflow,allenlavoie/tensorflow,LUTAN/tensorflow,eaplatanios/tensorflow,jhaux/tensorflow,admcrae/tensorflow,zasdfgbnm/tensorflow,hsaputra/tensorflow,eadgarchen/tensorflow,Mistobaan/tensorflow,lukeiwanski/tensorflow,tongwang01/tensorflow,johndpope/tensorflow,Bismarrck/tensorflow,yaroslavvb/tensorflow,adit-chandra/tensorflow,gunan/tensorflow,jhaux/tensorflow,chenjun0210/tensorflow,ppwwyyxx/tensorflow,apark263/tensorflow,meteorcloudy/tensorflow,dyoung418/tensorflow,guschmue/tensorflow,Intel-Corporation/tensorflow,Carmezim/tensorflow,lukeiwanski/tensorflow-opencl,DavidNorman/tensorflow,ppries/tensorflow,anand-c-goog/tensorflow,mixturemodel-flow/tensorflow,petewarden/tensorflow,nolanliou/tensorflow,scenarios/tensorflow,AndreasMadsen/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,snnn/tensorflow,alivecor/tensorflow,manjunaths/tensorflow,scenarios/tensorflow,with-git/tensorflow,mavenlin/tensorflow,alistairlow/tensorflow,haeusser/tensorflow,caisq/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,jart/tensorflow,tensorflow/tensorflow,ville-k/tensorflow,ibmsoe/tensorflow,renyi533/tensorflow,laszlocsomor/tensorflow,pierreg/tensorflow,laszlocsomor/tensorflow,karllessard/tensorflow,HKUST-SING/tensorflow,kobejean/tensorflow,yufengg/tensorflow,ppwwyyxx/tensorflow,manjunaths/tensorflow,chemelnucfin/tensorflow,abhitopia/tensorflow,jwlawson/tensorflow,adit-chandra/tensorflow,anilmuthineni/tensorflow,tiagofrepereira2012/tensorflow,calebfoss/tensorflow,brchiu/tensorflow,yongtang/tensorflow,SnakeJenny/TensorFlow,rdipietro/tensorflow,unsiloai/syntaxnet-ops-hack,alisidd/tensorflow,LUTAN/tensorflow,Bulochkin/tensorflow_pack,renyi533/tensorflow,Moriadry/tensorflow,RapidApplicationDevelopment/tensorflow,tiagofrepereira2012/tensorflow,benoitsteiner/tensorflow-opencl,rdipietro/tensorflow,horance-liu/tensorflow,jendap/tensorflow,code-sauce/tensorflow,horance-liu/tensorflow,wangyum/tensorflow,ran5515/DeepDecision,jeffzheng1/tensorflow,rdipietro/tensorflow,mdrumond/tensorflow,petewarden/tensorflow,DCSaunders/tensorflow,allenlavoie/tensorflow,JingJunYin/tensorflow,maciekcc/tensorflow,Mazecreator/tensorflow,mortada/tensorflow,brchiu/tensorflow,apark263/tensorflow,chenjun0210/tensorflow,mortada/tensorflow,lukeiwanski/tensorflow,jart/tensorflow,martinwicke/tensorflow,ravindrapanda/tensorflow,annarev/tensorflow,jhaux/tensorflow,adamtiger/tensorflow,jhaux/tensorflow,pierreg/tensorflow,caisq/tensorflow,nolanliou/tensorflow,mavenlin/tensorflow,codrut3/tensorflow,JingJunYin/tensorflow,tensorflow/tensorflow,maciekcc/tensorflow,pavelchristof/gomoku-ai,drpngx/tensorflow,cancan101/tensorflow,frreiss/tensorflow-fred,arborh/tensorflow,markslwong/tensorflow,MycChiu/tensorflow,renyi533/tensorflow,ravindrapanda/tensorflow,ArtsiomCh/tensorflow,kevin-coder/tensorflow-fork,freedomtan/tensorflow,alivecor/tensorflow,code-sauce/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,JingJunYin/tensorflow,ran5515/DeepDecision,nanditav/15712-TensorFlow,mdrumond/tensorflow,aldian/tensorflow,lakshayg/tensorflow,markslwong/tensorflow,lakshayg/tensorflow,jwlawson/tensorflow,girving/tensorflow,abhitopia/tensorflow,gibiansky/tensorflow,dancingdan/tensorflow,Mazecreator/tensorflow,apark263/tensorflow,RapidApplicationDevelopment/tensorflow,tntnatbry/tensorflow,jhaux/tensorflow,ppwwyyxx/tensorflow,sarvex/tensorflow,jostep/tensorflow,gojira/tensorflow,RapidApplicationDevelopment/tensorflow,jalexvig/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,wangyum/tensorflow,mixturemodel-flow/tensorflow,a-doumoulakis/tensorflow,pavelchristof/gomoku-ai,aselle/tensorflow,tornadozou/tensorflow,whn09/tensorflow,admcrae/tensorflow,tillahoffmann/tensorflow,aldian/tensorflow,Carmezim/tensorflow,mengxn/tensorflow,maciekcc/tensorflow,AnishShah/tensorflow,gnieboer/tensorflow,rdipietro/tensorflow,renyi533/tensorflow,benoitsteiner/tensorflow,tntnatbry/tensorflow,unsiloai/syntaxnet-ops-hack,admcrae/tensorflow,sandeepgupta2k4/tensorflow,jart/tensorflow,nburn42/tensorflow,mdrumond/tensorflow,girving/tensorflow,Mazecreator/tensorflow,benoitsteiner/tensorflow-opencl,freedomtan/tensorflow
c6e49568deaf973df276d5168714df0c9a2aad85
src/app/qbs-setup-toolchains/probe.cpp
src/app/qbs-setup-toolchains/probe.cpp
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qbs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "probe.h" #include "clangclprobe.h" #include "gccprobe.h" #include "iarewprobe.h" #include "keilprobe.h" #include "msvcprobe.h" #include "sdccprobe.h" #include "xcodeprobe.h" #include <logging/translator.h> #include <tools/error.h> #include <tools/hostosinfo.h> #include <tools/profile.h> #include <tools/settings.h> #include <tools/toolchains.h> #include <QtCore/qdir.h> #include <QtCore/qoperatingsystemversion.h> #include <QtCore/qtextstream.h> #ifdef Q_OS_WIN // We need defines for Windows 8. #undef _WIN32_WINNT #define _WIN32_WINNT _WIN32_WINNT_WIN8 #include <qt_windows.h> #include <ShlObj.h> #else #include <qplatformdefs.h> #endif // Q_OS_WIN using namespace qbs; using Internal::HostOsInfo; using Internal::Tr; static QTextStream qStdout(stdout); static QTextStream qStderr(stderr); QStringList systemSearchPaths() { return QString::fromLocal8Bit(qgetenv("PATH")).split(HostOsInfo::pathListSeparator()); } QString findExecutable(const QString &fileName) { QString fullFileName = fileName; if (HostOsInfo::isWindowsHost() && !fileName.endsWith(QLatin1String(".exe"), Qt::CaseInsensitive)) { fullFileName += QLatin1String(".exe"); } const auto ppaths = systemSearchPaths(); for (const QString &ppath : ppaths) { const QString fullPath = ppath + QLatin1Char('/') + fullFileName; if (QFileInfo::exists(fullPath)) return QDir::cleanPath(fullPath); } return {}; } QStringList toolchainTypeFromCompilerName(const QString &compilerName) { if (compilerName == QLatin1String("cl.exe")) return canonicalToolchain(QStringLiteral("msvc")); if (compilerName == QLatin1String("clang-cl.exe")) return canonicalToolchain(QLatin1String("clang-cl")); const auto types = { QStringLiteral("clang"), QStringLiteral("llvm"), QStringLiteral("mingw"), QStringLiteral("gcc") }; for (const auto &type : types) { if (compilerName.contains(type)) return canonicalToolchain(type); } if (compilerName == QLatin1String("g++")) return canonicalToolchain(QStringLiteral("gcc")); if (isIarCompiler(compilerName)) return canonicalToolchain(QStringLiteral("iar")); if (isKeilCompiler(compilerName)) return canonicalToolchain(QStringLiteral("keil")); if (isSdccCompiler(compilerName)) return canonicalToolchain(QStringLiteral("sdcc")); return {}; } void probe(Settings *settings) { QList<Profile> profiles; if (HostOsInfo::isWindowsHost()) { msvcProbe(settings, profiles); clangClProbe(settings, profiles); } else if (HostOsInfo::isMacosHost()) { xcodeProbe(settings, profiles); } gccProbe(settings, profiles, QStringLiteral("gcc")); gccProbe(settings, profiles, QStringLiteral("clang")); iarProbe(settings, profiles); keilProbe(settings, profiles); sdccProbe(settings, profiles); if (profiles.empty()) { qStderr << Tr::tr("Could not detect any toolchains. No profile created.") << endl; } else if (profiles.size() == 1 && settings->defaultProfile().isEmpty()) { const QString profileName = profiles.front().name(); qStdout << Tr::tr("Making profile '%1' the default.").arg(profileName) << endl; settings->setValue(QStringLiteral("defaultProfile"), profileName); } } void createProfile(const QString &profileName, const QString &toolchainType, const QString &compilerFilePath, Settings *settings) { QFileInfo compiler(compilerFilePath); if (compilerFilePath == compiler.fileName() && !compiler.exists()) compiler = QFileInfo(findExecutable(compilerFilePath)); if (!compiler.exists()) { throw qbs::ErrorInfo(Tr::tr("Compiler '%1' not found") .arg(compilerFilePath)); } QStringList toolchainTypes; if (toolchainType.isEmpty()) toolchainTypes = toolchainTypeFromCompilerName(compiler.fileName()); else toolchainTypes = canonicalToolchain(toolchainType); if (toolchainTypes.contains(QLatin1String("msvc"))) createMsvcProfile(compiler, settings, profileName); else if (toolchainTypes.contains(QLatin1String("clang-cl"))) createClangClProfile(compiler, settings, profileName); else if (toolchainTypes.contains(QLatin1String("gcc"))) createGccProfile(compiler, settings, toolchainTypes, profileName); else if (toolchainTypes.contains(QLatin1String("iar"))) createIarProfile(compiler, settings, profileName); else if (toolchainTypes.contains(QLatin1String("keil"))) createKeilProfile(compiler, settings, profileName); else if (toolchainTypes.contains(QLatin1String("sdcc"))) createSdccProfile(compiler, settings, profileName); else throw qbs::ErrorInfo(Tr::tr("Cannot create profile: Unknown toolchain type.")); } int extractVersion(const QByteArray &macroDump, const QByteArray &keyToken) { const int startIndex = macroDump.indexOf(keyToken); if (startIndex == -1) return -1; const int endIndex = macroDump.indexOf('\n', startIndex); if (endIndex == -1) return -1; const auto keyLength = keyToken.length(); const int version = macroDump.mid(startIndex + keyLength, endIndex - startIndex - keyLength) .toInt(); return version; } static QString resolveSymlinks(const QString &filePath) { QFileInfo fi(filePath); int links = 16; while (links-- && fi.isSymLink()) fi.setFile(fi.dir(), fi.symLinkTarget()); if (links <= 0) return {}; return fi.filePath(); } // Copied from qfilesystemengine_win.cpp. #ifdef Q_OS_WIN // File ID for Windows up to version 7. static inline QByteArray fileIdWin7(HANDLE handle) { BY_HANDLE_FILE_INFORMATION info; if (GetFileInformationByHandle(handle, &info)) { char buffer[sizeof "01234567:0123456701234567\0"]; qsnprintf(buffer, sizeof(buffer), "%lx:%08lx%08lx", info.dwVolumeSerialNumber, info.nFileIndexHigh, info.nFileIndexLow); return QByteArray(buffer); } return {}; } // File ID for Windows starting from version 8. static QByteArray fileIdWin8(HANDLE handle) { QByteArray result; FILE_ID_INFO infoEx = {}; if (::GetFileInformationByHandleEx( handle, static_cast<FILE_INFO_BY_HANDLE_CLASS>(18), // FileIdInfo in Windows 8 &infoEx, sizeof(FILE_ID_INFO))) { result = QByteArray::number(infoEx.VolumeSerialNumber, 16); result += ':'; // Note: MinGW-64's definition of FILE_ID_128 differs from the MSVC one. result += QByteArray(reinterpret_cast<const char *>(&infoEx.FileId), int(sizeof(infoEx.FileId))).toHex(); } return result; } static QByteArray fileIdWin(HANDLE fHandle) { return QOperatingSystemVersion::current() >= QOperatingSystemVersion::Windows8 ? fileIdWin8(HANDLE(fHandle)) : fileIdWin7(HANDLE(fHandle)); } static QByteArray fileId(const QString &filePath) { QByteArray result; const HANDLE handle = ::CreateFile( reinterpret_cast<const wchar_t*>(filePath.utf16()), 0, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); if (handle != INVALID_HANDLE_VALUE) { result = fileIdWin(handle); ::CloseHandle(handle); } return result; } static qint64 fileSize(const QString &filePath) { return QFileInfo(filePath).size(); } #else static QByteArray fileId(const QString &filePath) { QByteArray result; if (Q_UNLIKELY(filePath.isEmpty())) return {}; QT_STATBUF statResult = {}; if (QT_STAT(filePath.toLocal8Bit().constData(), &statResult)) return {}; result = QByteArray::number(quint64(statResult.st_dev), 16); result += ':'; result += QByteArray::number(quint64(statResult.st_ino)); return result; } #endif // Q_OS_WIN bool isSameExecutable(const QString &filePath1, const QString &filePath2) { if (filePath1 == filePath2) return true; if (resolveSymlinks(filePath1) == resolveSymlinks(filePath2)) return true; if (fileId(filePath1) == fileId(filePath2)) return true; #ifdef Q_OS_WIN if (fileSize(filePath1) == fileSize(filePath2)) return true; #endif return false; }
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qbs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "probe.h" #include "clangclprobe.h" #include "gccprobe.h" #include "iarewprobe.h" #include "keilprobe.h" #include "msvcprobe.h" #include "sdccprobe.h" #include "xcodeprobe.h" #include <logging/translator.h> #include <tools/error.h> #include <tools/hostosinfo.h> #include <tools/profile.h> #include <tools/settings.h> #include <tools/toolchains.h> #include <QtCore/qdir.h> #include <QtCore/qoperatingsystemversion.h> #include <QtCore/qtextstream.h> #ifdef Q_OS_WIN // We need defines for Windows 8. #undef _WIN32_WINNT #define _WIN32_WINNT _WIN32_WINNT_WIN8 #include <qt_windows.h> #include <shlobj.h> #else #include <qplatformdefs.h> #endif // Q_OS_WIN using namespace qbs; using Internal::HostOsInfo; using Internal::Tr; static QTextStream qStdout(stdout); static QTextStream qStderr(stderr); QStringList systemSearchPaths() { return QString::fromLocal8Bit(qgetenv("PATH")).split(HostOsInfo::pathListSeparator()); } QString findExecutable(const QString &fileName) { QString fullFileName = fileName; if (HostOsInfo::isWindowsHost() && !fileName.endsWith(QLatin1String(".exe"), Qt::CaseInsensitive)) { fullFileName += QLatin1String(".exe"); } const auto ppaths = systemSearchPaths(); for (const QString &ppath : ppaths) { const QString fullPath = ppath + QLatin1Char('/') + fullFileName; if (QFileInfo::exists(fullPath)) return QDir::cleanPath(fullPath); } return {}; } QStringList toolchainTypeFromCompilerName(const QString &compilerName) { if (compilerName == QLatin1String("cl.exe")) return canonicalToolchain(QStringLiteral("msvc")); if (compilerName == QLatin1String("clang-cl.exe")) return canonicalToolchain(QLatin1String("clang-cl")); const auto types = { QStringLiteral("clang"), QStringLiteral("llvm"), QStringLiteral("mingw"), QStringLiteral("gcc") }; for (const auto &type : types) { if (compilerName.contains(type)) return canonicalToolchain(type); } if (compilerName == QLatin1String("g++")) return canonicalToolchain(QStringLiteral("gcc")); if (isIarCompiler(compilerName)) return canonicalToolchain(QStringLiteral("iar")); if (isKeilCompiler(compilerName)) return canonicalToolchain(QStringLiteral("keil")); if (isSdccCompiler(compilerName)) return canonicalToolchain(QStringLiteral("sdcc")); return {}; } void probe(Settings *settings) { QList<Profile> profiles; if (HostOsInfo::isWindowsHost()) { msvcProbe(settings, profiles); clangClProbe(settings, profiles); } else if (HostOsInfo::isMacosHost()) { xcodeProbe(settings, profiles); } gccProbe(settings, profiles, QStringLiteral("gcc")); gccProbe(settings, profiles, QStringLiteral("clang")); iarProbe(settings, profiles); keilProbe(settings, profiles); sdccProbe(settings, profiles); if (profiles.empty()) { qStderr << Tr::tr("Could not detect any toolchains. No profile created.") << endl; } else if (profiles.size() == 1 && settings->defaultProfile().isEmpty()) { const QString profileName = profiles.front().name(); qStdout << Tr::tr("Making profile '%1' the default.").arg(profileName) << endl; settings->setValue(QStringLiteral("defaultProfile"), profileName); } } void createProfile(const QString &profileName, const QString &toolchainType, const QString &compilerFilePath, Settings *settings) { QFileInfo compiler(compilerFilePath); if (compilerFilePath == compiler.fileName() && !compiler.exists()) compiler = QFileInfo(findExecutable(compilerFilePath)); if (!compiler.exists()) { throw qbs::ErrorInfo(Tr::tr("Compiler '%1' not found") .arg(compilerFilePath)); } QStringList toolchainTypes; if (toolchainType.isEmpty()) toolchainTypes = toolchainTypeFromCompilerName(compiler.fileName()); else toolchainTypes = canonicalToolchain(toolchainType); if (toolchainTypes.contains(QLatin1String("msvc"))) createMsvcProfile(compiler, settings, profileName); else if (toolchainTypes.contains(QLatin1String("clang-cl"))) createClangClProfile(compiler, settings, profileName); else if (toolchainTypes.contains(QLatin1String("gcc"))) createGccProfile(compiler, settings, toolchainTypes, profileName); else if (toolchainTypes.contains(QLatin1String("iar"))) createIarProfile(compiler, settings, profileName); else if (toolchainTypes.contains(QLatin1String("keil"))) createKeilProfile(compiler, settings, profileName); else if (toolchainTypes.contains(QLatin1String("sdcc"))) createSdccProfile(compiler, settings, profileName); else throw qbs::ErrorInfo(Tr::tr("Cannot create profile: Unknown toolchain type.")); } int extractVersion(const QByteArray &macroDump, const QByteArray &keyToken) { const int startIndex = macroDump.indexOf(keyToken); if (startIndex == -1) return -1; const int endIndex = macroDump.indexOf('\n', startIndex); if (endIndex == -1) return -1; const auto keyLength = keyToken.length(); const int version = macroDump.mid(startIndex + keyLength, endIndex - startIndex - keyLength) .toInt(); return version; } static QString resolveSymlinks(const QString &filePath) { QFileInfo fi(filePath); int links = 16; while (links-- && fi.isSymLink()) fi.setFile(fi.dir(), fi.symLinkTarget()); if (links <= 0) return {}; return fi.filePath(); } // Copied from qfilesystemengine_win.cpp. #ifdef Q_OS_WIN // File ID for Windows up to version 7. static inline QByteArray fileIdWin7(HANDLE handle) { BY_HANDLE_FILE_INFORMATION info; if (GetFileInformationByHandle(handle, &info)) { char buffer[sizeof "01234567:0123456701234567\0"]; qsnprintf(buffer, sizeof(buffer), "%lx:%08lx%08lx", info.dwVolumeSerialNumber, info.nFileIndexHigh, info.nFileIndexLow); return QByteArray(buffer); } return {}; } // File ID for Windows starting from version 8. static QByteArray fileIdWin8(HANDLE handle) { QByteArray result; FILE_ID_INFO infoEx = {}; if (::GetFileInformationByHandleEx( handle, static_cast<FILE_INFO_BY_HANDLE_CLASS>(18), // FileIdInfo in Windows 8 &infoEx, sizeof(FILE_ID_INFO))) { result = QByteArray::number(infoEx.VolumeSerialNumber, 16); result += ':'; // Note: MinGW-64's definition of FILE_ID_128 differs from the MSVC one. result += QByteArray(reinterpret_cast<const char *>(&infoEx.FileId), int(sizeof(infoEx.FileId))).toHex(); } return result; } static QByteArray fileIdWin(HANDLE fHandle) { return QOperatingSystemVersion::current() >= QOperatingSystemVersion::Windows8 ? fileIdWin8(HANDLE(fHandle)) : fileIdWin7(HANDLE(fHandle)); } static QByteArray fileId(const QString &filePath) { QByteArray result; const HANDLE handle = ::CreateFile( reinterpret_cast<const wchar_t*>(filePath.utf16()), 0, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); if (handle != INVALID_HANDLE_VALUE) { result = fileIdWin(handle); ::CloseHandle(handle); } return result; } static qint64 fileSize(const QString &filePath) { return QFileInfo(filePath).size(); } #else static QByteArray fileId(const QString &filePath) { QByteArray result; if (Q_UNLIKELY(filePath.isEmpty())) return {}; QT_STATBUF statResult = {}; if (QT_STAT(filePath.toLocal8Bit().constData(), &statResult)) return {}; result = QByteArray::number(quint64(statResult.st_dev), 16); result += ':'; result += QByteArray::number(quint64(statResult.st_ino)); return result; } #endif // Q_OS_WIN bool isSameExecutable(const QString &filePath1, const QString &filePath2) { if (filePath1 == filePath2) return true; if (resolveSymlinks(filePath1) == resolveSymlinks(filePath2)) return true; if (fileId(filePath1) == fileId(filePath2)) return true; #ifdef Q_OS_WIN if (fileSize(filePath1) == fileSize(filePath2)) return true; #endif return false; }
Fix wrong capitalization of Windows-specific header file
Fix wrong capitalization of Windows-specific header file This header file is lower-case, even on Windows. But it would remain undetected because NTFS is not case-sensitive by default. Correct capitalization is required when cross-compiling with MinGW on Linux. Change-Id: I584ae7c9dcf81597a2b9b6481e95fc65ec6e125a Reviewed-by: Christian Kandeler <[email protected]> Reviewed-by: Denis Shienkov <[email protected]>
C++
lgpl-2.1
qtproject/qt-labs-qbs,qt-labs/qbs,qt-labs/qbs,qtproject/qt-labs-qbs,qt-labs/qbs,qt-labs/qbs,qt-labs/qbs,qtproject/qt-labs-qbs,qt-labs/qbs,qtproject/qt-labs-qbs,qtproject/qt-labs-qbs,qt-labs/qbs,qtproject/qt-labs-qbs,qtproject/qt-labs-qbs
04253e326bf71970ffefaa6de6924f0ff1865909
src/df_polygon_aa.cpp
src/df_polygon_aa.cpp
// Based on: // Fast Anti-Aliasing Polygon Scan Conversion by Jack Morrison from "Graphics // Gems", Academic Press, 1990. // This code renders a polygon, computing subpixel coverage at // 8 times Y and 16 times X display resolution for anti-aliasing. #include "df_polygon_aa.h" #include "df_bitmap.h" #include "df_common.h" #include <limits.h> #include <math.h> static const int SUBXRES = 16; // subpixel X resolution per pixel static const int SUBYRES = 8; // subpixel Y resolution per scanline #define MOD_Y_RES(y) ((y) & 7) // subpixel Y modulo struct SubpixelRowExtents { int left, right; }; // Array to store the start and end X values for each row of subpixels in the // current scanline. static SubpixelRowExtents subpixelRowExtents[SUBYRES]; // Min and max X values of subpixels in the current pixel. Can be found by // searching subpixelRowExtents. Only stored as an optimization. static int leftMin, rightMax; // Compute number of subpixels covered by polygon at current pixel. // x is left subpixel of pixel. static int ComputePixelCoverage(int x) { static const int MAX_AREA = SUBXRES * SUBYRES; int area = 0; x *= SUBXRES; int xr = x + SUBXRES - 1; // Right-most subpixel of pixel. for (int y = 0; y < SUBYRES; y++) { // Calc covered area for current subpixel y int partialArea = IntMin(subpixelRowExtents[y].right, xr) - IntMax(subpixelRowExtents[y].left, x) + 1; if (partialArea > 0) { area += partialArea; } } return 255 * area / MAX_AREA; } static void RenderScanline(DfBitmap *bmp, int y, DfColour col) { int x; for (x = leftMin / SUBXRES; x <= (rightMax / SUBXRES); x++) { col.a = ComputePixelCoverage(x); PutPix(bmp, x, y, col); if (col.a == 255) { break; } } int x2; for (x2 = (rightMax / SUBXRES); x2 > x; x2--) { col.a = ComputePixelCoverage(x2); PutPix(bmp, x2, y, col); if (col.a == 255) { break; } } if (x2 > x) { HLine(bmp, x, y, x2 - x, col); } } void FillPolygonAa(DfBitmap *bmp, DfVertex *verts, int numVerts, DfColour col) { // Convert the verts passed in into the format we use internally. for (int i = 0; i < numVerts; i++) { verts[i].y /= SUBXRES / SUBYRES; } // Find the max vertex y value and the vertex with minimum y. DfVertex *vertLeft = verts; int maxY = -1; for (int i = 1; i < numVerts; i++) { if (verts[i].y < vertLeft->y) { vertLeft = &verts[i]; } maxY = IntMax(maxY, verts[i].y); } DfVertex *endVert = &verts[numVerts - 1]; // Initialize scanning edges. DfVertex *nextVertLeft, *vertRight, *nextVertRight; vertRight = nextVertRight = nextVertLeft = vertLeft; #define NEXT_LEFT_EDGE() \ vertLeft = nextVertLeft; \ nextVertLeft++; \ if (nextVertLeft > endVert) nextVertLeft = verts; // Wrap. #define NEXT_RIGHT_EDGE() \ vertRight = nextVertRight; \ nextVertRight--; \ if (nextVertRight < verts) nextVertRight = endVert; // Wrap. // Skip any initial horizontal edges because they would cause a divide by // zero in the slope calculation. We know once we've got over the initial // horizontal edges that there cannot be anymore in a convex poly, other // than those that would form the bottom of the poly. We'll never // encounter those either because the main loop will terminate just before // we get to those (because y will have become equal to maxY). while (vertLeft->y == nextVertLeft->y) { NEXT_LEFT_EDGE(); } while (vertRight->y == nextVertRight->y) { NEXT_RIGHT_EDGE(); } // Initialize the extents for each row of subpixels. for (int i = 0; i < SUBYRES; i++) { subpixelRowExtents[i].left = -1; subpixelRowExtents[i].right = -1; } leftMin = INT_MAX; rightMax = -1; int leftSlope = ((nextVertLeft->x - vertLeft->x) << 16) / (nextVertLeft->y - vertLeft->y); int rightSlope = ((nextVertRight->x - vertRight->x) << 16) / (nextVertRight->y - vertRight->y);; // Consider each row of subpixels from top to bottom. for (int y = vertLeft->y; y < maxY; y++) { // Have we reached the end of the left hand edge we are following? if (y == nextVertLeft->y) { NEXT_LEFT_EDGE(); leftSlope = ((nextVertLeft->x - vertLeft->x) << 16) / (nextVertLeft->y - vertLeft->y); } // Have we reached the end of the right hand edge we are following? if (y == nextVertRight->y) { NEXT_RIGHT_EDGE(); rightSlope = ((nextVertRight->x - vertRight->x) << 16) / (nextVertRight->y - vertRight->y); } // Interpolate sub-pixel x endpoints at this y and update extremes. SubpixelRowExtents *sre = &subpixelRowExtents[MOD_Y_RES(y)]; sre->left = vertLeft->x + (((y - vertLeft->y) * leftSlope) >> 16); leftMin = IntMin(leftMin, sre->left); sre->right = vertRight->x + (((y - vertRight->y) * rightSlope) >> 16); rightMax = IntMax(rightMax, sre->right); // Is this the last row of subpixels for this scanline? if (MOD_Y_RES(y) == SUBYRES - 1) { RenderScanline(bmp, y / SUBYRES, col); leftMin = INT_MAX; rightMax = -1; } } // Mark remaining subpixel rows as empty. for (int yy = MOD_Y_RES(maxY); MOD_Y_RES(yy); yy++) { subpixelRowExtents[yy].left = subpixelRowExtents[yy].right = -1; } RenderScanline(bmp, maxY / SUBYRES, col); // Convert the verts back into the format the caller uses. for (int i = 0; i < numVerts; i++) { verts[i].y *= SUBXRES / SUBYRES; } }
// Based on: // Fast Anti-Aliasing Polygon Scan Conversion by Jack Morrison from "Graphics // Gems", Academic Press, 1990. // This code renders a polygon, computing subpixel coverage at // 8 times Y and 16 times X display resolution for anti-aliasing. #include "df_polygon_aa.h" #include "df_bitmap.h" #include "df_common.h" #include <limits.h> #include <math.h> static const int SUBXRES = 16; // subpixel X resolution per pixel static const int SUBYRES = 8; // subpixel Y resolution per scanline #define MOD_Y_RES(y) ((y) & 7) // subpixel Y modulo struct SubpixelRowExtents { int left, right; }; // Array to store the start and end X values for each row of subpixels in the // current scanline. static SubpixelRowExtents subpixelRowExtents[SUBYRES]; // Min and max X values of subpixels in the current pixel. Can be found by // searching subpixelRowExtents. Only stored as an optimization. static int leftMin, rightMax; // Compute number of subpixels covered by polygon at current pixel. // x is left subpixel of pixel. static int ComputePixelCoverage(int x) { static const int MAX_AREA = SUBXRES * SUBYRES; int area = 0; x *= SUBXRES; int xr = x + SUBXRES - 1; // Right-most subpixel of pixel. for (int y = 0; y < SUBYRES; y++) { // Calc covered area for current subpixel y int partialArea = IntMin(subpixelRowExtents[y].right, xr) - IntMax(subpixelRowExtents[y].left, x) + 1; if (partialArea > 0) { area += partialArea; } } return 255 * area / MAX_AREA; } static void RenderScanline(DfBitmap *bmp, int y, DfColour col) { int x; for (x = leftMin / SUBXRES; x <= (rightMax / SUBXRES); x++) { col.a = ComputePixelCoverage(x); PutPix(bmp, x, y, col); if (col.a == 255) { break; } } int x2; for (x2 = (rightMax / SUBXRES); x2 > x; x2--) { col.a = ComputePixelCoverage(x2); PutPix(bmp, x2, y, col); if (col.a == 255) { break; } } if (x2 > x) { HLine(bmp, x, y, x2 - x, col); } } void FillPolygonAa(DfBitmap *bmp, DfVertex *verts, int numVerts, DfColour col) { // Convert the verts passed in into the format we use internally. for (int i = 0; i < numVerts; i++) { verts[i].y /= SUBXRES / SUBYRES; } // Find the max vertex y value and the vertex with minimum y. DfVertex *vertLeft = verts; int maxY = -1; for (int i = 1; i < numVerts; i++) { if (verts[i].y < vertLeft->y) { vertLeft = &verts[i]; } maxY = IntMax(maxY, verts[i].y); } DfVertex *endVert = &verts[numVerts - 1]; // Initialize scanning edges. DfVertex *nextVertLeft, *vertRight, *nextVertRight; vertRight = nextVertRight = nextVertLeft = vertLeft; #define NEXT_LEFT_EDGE() \ vertLeft = nextVertLeft; \ nextVertLeft++; \ if (nextVertLeft > endVert) nextVertLeft = verts; // Wrap. #define NEXT_RIGHT_EDGE() \ vertRight = nextVertRight; \ nextVertRight--; \ if (nextVertRight < verts) nextVertRight = endVert; // Wrap. // Skip any initial horizontal edges because they would cause a divide by // zero in the slope calculation. We know once we've got over the initial // horizontal edges that there cannot be anymore in a convex poly, other // than those that would form the bottom of the poly. We'll never // encounter those either because the main loop will terminate just before // we get to those (because y will have become equal to maxY). while (vertLeft->y == nextVertLeft->y) { NEXT_LEFT_EDGE(); } while (vertRight->y == nextVertRight->y) { NEXT_RIGHT_EDGE(); } // Initialize the extents for each row of subpixels. for (int i = 0; i < SUBYRES; i++) { subpixelRowExtents[i].left = -1; subpixelRowExtents[i].right = -1; } leftMin = INT_MAX; rightMax = -1; int leftSlope = ((nextVertLeft->x - vertLeft->x) << 16) / (nextVertLeft->y - vertLeft->y); int rightSlope = ((nextVertRight->x - vertRight->x) << 16) / (nextVertRight->y - vertRight->y); // Consider each row of subpixels from top to bottom. for (int y = vertLeft->y; y < maxY; y++) { // Have we reached the end of the left hand edge we are following? if (y == nextVertLeft->y) { NEXT_LEFT_EDGE(); leftSlope = ((nextVertLeft->x - vertLeft->x) << 16) / (nextVertLeft->y - vertLeft->y); } // Have we reached the end of the right hand edge we are following? if (y == nextVertRight->y) { NEXT_RIGHT_EDGE(); rightSlope = ((nextVertRight->x - vertRight->x) << 16) / (nextVertRight->y - vertRight->y); } // Interpolate sub-pixel x endpoints at this y and update extremes. SubpixelRowExtents *sre = &subpixelRowExtents[MOD_Y_RES(y)]; sre->left = vertLeft->x + (((y - vertLeft->y) * leftSlope) >> 16); leftMin = IntMin(leftMin, sre->left); sre->right = vertRight->x + (((y - vertRight->y) * rightSlope) >> 16); rightMax = IntMax(rightMax, sre->right); // Is this the last row of subpixels for this scanline? if (MOD_Y_RES(y) == SUBYRES - 1) { RenderScanline(bmp, y / SUBYRES, col); leftMin = INT_MAX; rightMax = -1; } } // Mark remaining subpixel rows as empty. for (int yy = MOD_Y_RES(maxY); MOD_Y_RES(yy); yy++) { subpixelRowExtents[yy].left = subpixelRowExtents[yy].right = -1; } RenderScanline(bmp, maxY / SUBYRES, col); // Convert the verts back into the format the caller uses. for (int i = 0; i < numVerts; i++) { verts[i].y *= SUBXRES / SUBYRES; } }
Remove extraneous semi-colon.
Remove extraneous semi-colon.
C++
mit
abainbridge/deadfrog-lib,abainbridge/deadfrog-lib,abainbridge/deadfrog-lib
38e394a0a8654cc3e630ef0b61466d3ee2317f62
src/PefCMD.cpp
src/PefCMD.cpp
// // PefCMD.cpp // J3NI // // Created by Neil on 2014-03-14. // Copyright (c) 2014 Neil. All rights reserved. // #include <fstream> #include <stdlib.h> #include <time.h> #include <PefCMD.h> #include <IpmiCommandDefines.h> using namespace IpmiCommandDefines; extern std::ofstream log_file; GetPefCapabCMD::GetPefCapabCMD() : pefCapab_(0x0E) { } void GetPefCapabCMD::setPefCapab(unsigned char pefCap) { pefCapab_ = pefCap; } unsigned char GetPefCapabCMD::getPefCapab() const { return pefCapab_; } int GetPefCapabCMD::process(const unsigned char* req, int reqLength, unsigned char* resp) { log_file << "Get PEF Capabilities Command" << std::endl; resp[0] = COMP_CODE_OK; resp[1] = 0x51; resp[2] = pefCapab_; resp[3] = 0x00; return 4; } ArmPefPostponeTimerCMD::ArmPefPostponeTimerCMD() : countdownDuration(0) { setTime = time(0); } int ArmPefPostponeTimerCMD::process(const unsigned char* req, int reqLength, unsigned char* resp) { log_file << "Arm PEF Postpone Timer Command" << std::endl; time_t t = time(0); if(req[0] == 0xFE || req[0] == 0x00) { countdownDuration = 0; } else if(req[0] != 0xFF) { countdownDuration = req[0]; setTime = t; } unsigned char countdownValue = countdownDuration; if(req[0] == 0xFF) { countdownValue = (t - setTime) % countdownDuration; } resp[0] = COMP_CODE_OK; resp[1] = countdownValue; return 2; } GetPefConfigParamCMD::GetPefConfigParamCMD() { unsigned char defaultInProgress = 0x00; pefConfigMap[0x00] = new ConfigParam(1, &defaultInProgress); unsigned char defaultControl = 0x01; pefConfigMap[0x01] = new ConfigParam(1, &defaultControl); unsigned char defaultActionControl = 0x0E; pefConfigMap[0x02] = new ConfigParam(1, &defaultActionControl); unsigned char defaultStartupDelay = 0x00; pefConfigMap[0x03] = new ConfigParam(1, &defaultStartupDelay); unsigned char defaultAlertStartupDelay = 0x00; pefConfigMap[0x04] = new ConfigParam(1, &defaultAlertStartupDelay); unsigned char eventFilters = 0x00; pefConfigMap[0x05] = new ConfigParam(1, &eventFilters, true); unsigned char alertPolicyNum = 0x00; pefConfigMap[0x08] = new ConfigParam(1, &alertPolicyNum, true); // Generate or use default GUID? //pefConfigMap[0x0A] = new ConfigParam[] } GetPefConfigParamCMD::~GetPefConfigParamCMD() { for(ConfigParamMap::iterator it = pefConfigMap.begin(); it != pefConfigMap.end(); it++) { delete it->second; } pefConfigMap.clear(); } unsigned char GetPefConfigParamCMD::setMap(unsigned char param, const unsigned char* paramValue, int length) { unsigned char paramSelector = paramValue[0] & 0x7F; ConfigParamMap::iterator it = pefConfigMap.find(paramSelector); if(it == pefConfigMap.end()) { return PARAM_UNSUPPORTED; } ConfigParam* configParam = it->second; if(configParam->readOnly) { return WRITE_TO_READ_ONLY; } if((param == 0x00) && (configParam->data[0] != 0x00)) { return SET_IN_PROGRESS_FAIL; } if(configParam->length != length) { delete[] configParam->data; configParam->data = new unsigned char[length]; } for(int i = 0; i < configParam->length; i++) { configParam->data[i] = paramValue[i]; } return COMP_CODE_OK; } int GetPefConfigParamCMD::process(const unsigned char* req, int reqLength, unsigned char* resp) { log_file << "Get PEF Configuration Parameters Command" << std::endl; resp[0] = COMP_CODE_OK; resp[1] = 0x11; if((req[0] & 0x80) == 0x80) return 2; unsigned char paramSelector = req[0] & 0x7F; ConfigParamMap::iterator it = pefConfigMap.find(paramSelector); if(it == pefConfigMap.end()) { resp[0] = PARAM_UNSUPPORTED; return 2; } ConfigParam* param = it->second; int i = 0; for(; i < param->length; i++) { resp[2 + i] = param->data[i]; } return 2 + i; } SetPefConfigParamCMD::SetPefConfigParamCMD(GetPefConfigParamCMD* getPefConfigParam) { getPefConfigParam_ = getPefConfigParam; } int SetPefConfigParamCMD::process(const unsigned char* req, int reqLength, unsigned char* resp) { log_file << "Set PEF Configuration Parameters Command" << std::endl; unsigned char paramSelector = req[0] & 0x7F; resp[0] = getPefConfigParam_->setMap(paramSelector, req + 1, reqLength - 1); return 1; } GetLastProcEventIdCMD::GetLastProcEventIdCMD() : mostRecentId_(NULL), bmcRecordId_(0x0000), swRecordId_(0x0000) { timestamp_ = time(0); mostRecentId_ = &swRecordId_; } void GetLastProcEventIdCMD::setBmcRecordId(const unsigned char* recordId, int length) { if(length < 2) return; bmcRecordId_ = recordId[0] | (recordId[1] << 8); mostRecentId_ = &bmcRecordId_; timestamp_ = time(0); } void GetLastProcEventIdCMD::setSwRecordId(const unsigned char* recordId, int length) { if(length < 2) return; swRecordId_ = recordId[0] | (recordId[1] << 8); mostRecentId_ = &swRecordId_; timestamp_ = time(0); } uint16_t GetLastProcEventIdCMD::getBmcRecordId() const { return bmcRecordId_; } uint16_t GetLastProcEventIdCMD::getSwRecordId() const { return swRecordId_; } int GetLastProcEventIdCMD::process(const unsigned char* req, int reqLength, unsigned char* resp) { log_file << "Get Last Proccessed Event Id Command" << std::endl; resp[0] = COMP_CODE_OK; resp[1] = timestamp_ & 0x000000FF; resp[2] = (timestamp_ & 0x0000FF00) >> 8; resp[3] = (timestamp_ & 0x00FF0000) >> 16; resp[4] = (timestamp_ & 0xFF000000) >> 24; resp[5] = *mostRecentId_ & 0x00FF ; resp[6] = (*mostRecentId_ & 0xFF00) >> 8; resp[7] = swRecordId_ & 0x00FF ; resp[8] = (swRecordId_ & 0xFF00) >> 8; resp[9] = swRecordId_ & 0x00FF ; resp[10] = (swRecordId_ & 0xFF00) >> 8; return 11; } SetLastProcEventIdCMD::SetLastProcEventIdCMD(GetLastProcEventIdCMD* lastProcEventCmd) { lastProcEventCmd_ = lastProcEventCmd; } int SetLastProcEventIdCMD::process(const unsigned char* req, int reqLength, unsigned char* resp) { log_file << "Set Last Proccessed Event Id Command" << std::endl; resp[0] = COMP_CODE_OK; if (reqLength >= 3) { if((req[0] & 0x01) == 0x01) lastProcEventCmd_->setBmcRecordId(req + 1, 2); else lastProcEventCmd_->setSwRecordId(req + 1, 2); } return 1; }
// // PefCMD.cpp // J3NI // // Created by Neil on 2014-03-14. // Copyright (c) 2014 Neil. All rights reserved. // #include <fstream> #include <stdlib.h> #include <time.h> #include <PefCMD.h> #include <IpmiCommandDefines.h> using namespace IpmiCommandDefines; extern std::ofstream log_file; GetPefCapabCMD::GetPefCapabCMD() : pefCapab_(0x0E) { } void GetPefCapabCMD::setPefCapab(unsigned char pefCap) { pefCapab_ = pefCap; } unsigned char GetPefCapabCMD::getPefCapab() const { return pefCapab_; } int GetPefCapabCMD::process(const unsigned char* req, int reqLength, unsigned char* resp) { log_file << "Get PEF Capabilities Command" << std::endl; resp[0] = COMP_CODE_OK; resp[1] = 0x51; resp[2] = pefCapab_; resp[3] = 0x00; return 4; } ArmPefPostponeTimerCMD::ArmPefPostponeTimerCMD() : countdownDuration(0) { setTime = time(0); } int ArmPefPostponeTimerCMD::process(const unsigned char* req, int reqLength, unsigned char* resp) { log_file << "Arm PEF Postpone Timer Command" << std::endl; time_t t = time(0); if(req[0] == 0xFE || req[0] == 0x00) { countdownDuration = 0; } else if(req[0] != 0xFF) { countdownDuration = req[0]; setTime = t; } unsigned char countdownValue = countdownDuration; if(req[0] == 0xFF) { countdownValue = (t - setTime) % countdownDuration; } resp[0] = COMP_CODE_OK; resp[1] = countdownValue; return 2; } GetPefConfigParamCMD::GetPefConfigParamCMD() { unsigned char defaultInProgress = 0x00; pefConfigMap[0x00] = new ConfigParam(1, &defaultInProgress); unsigned char defaultControl = 0x01; pefConfigMap[0x01] = new ConfigParam(1, &defaultControl); unsigned char defaultActionControl = 0x0E; pefConfigMap[0x02] = new ConfigParam(1, &defaultActionControl); unsigned char defaultStartupDelay = 0x00; pefConfigMap[0x03] = new ConfigParam(1, &defaultStartupDelay); unsigned char defaultAlertStartupDelay = 0x00; pefConfigMap[0x04] = new ConfigParam(1, &defaultAlertStartupDelay); unsigned char eventFilters = 0x00; pefConfigMap[0x05] = new ConfigParam(1, &eventFilters, true); unsigned char alertPolicyNum = 0x00; pefConfigMap[0x08] = new ConfigParam(1, &alertPolicyNum, true); unsigned char* guid = new unsigned char[16]; pefConfigMap[0x0A] = new ConfigParam(16, guid); delete [] guid; } GetPefConfigParamCMD::~GetPefConfigParamCMD() { for(ConfigParamMap::iterator it = pefConfigMap.begin(); it != pefConfigMap.end(); it++) { delete it->second; } pefConfigMap.clear(); } unsigned char GetPefConfigParamCMD::setMap(unsigned char param, const unsigned char* paramValue, int length) { unsigned char paramSelector = paramValue[0] & 0x7F; ConfigParamMap::iterator it = pefConfigMap.find(paramSelector); if(it == pefConfigMap.end()) { return PARAM_UNSUPPORTED; } ConfigParam* configParam = it->second; if(configParam->readOnly) { return WRITE_TO_READ_ONLY; } if((param == 0x00) && (configParam->data[0] != 0x00)) { return SET_IN_PROGRESS_FAIL; } if(configParam->length != length) { delete[] configParam->data; configParam->data = new unsigned char[length]; } for(int i = 0; i < configParam->length; i++) { configParam->data[i] = paramValue[i]; } return COMP_CODE_OK; } int GetPefConfigParamCMD::process(const unsigned char* req, int reqLength, unsigned char* resp) { log_file << "Get PEF Configuration Parameters Command" << std::endl; resp[0] = COMP_CODE_OK; resp[1] = 0x11; if((req[0] & 0x80) == 0x80) return 2; unsigned char paramSelector = req[0] & 0x7F; ConfigParamMap::iterator it = pefConfigMap.find(paramSelector); if(it == pefConfigMap.end()) { resp[0] = PARAM_UNSUPPORTED; return 2; } ConfigParam* param = it->second; int i = 0; for(; i < param->length; i++) { resp[2 + i] = param->data[i]; } return 2 + i; } SetPefConfigParamCMD::SetPefConfigParamCMD(GetPefConfigParamCMD* getPefConfigParam) { getPefConfigParam_ = getPefConfigParam; } int SetPefConfigParamCMD::process(const unsigned char* req, int reqLength, unsigned char* resp) { log_file << "Set PEF Configuration Parameters Command" << std::endl; unsigned char paramSelector = req[0] & 0x7F; resp[0] = getPefConfigParam_->setMap(paramSelector, req + 1, reqLength - 1); return 1; } GetLastProcEventIdCMD::GetLastProcEventIdCMD() : mostRecentId_(NULL), bmcRecordId_(0x0000), swRecordId_(0x0000) { timestamp_ = time(0); mostRecentId_ = &swRecordId_; } void GetLastProcEventIdCMD::setBmcRecordId(const unsigned char* recordId, int length) { if(length < 2) return; bmcRecordId_ = recordId[0] | (recordId[1] << 8); mostRecentId_ = &bmcRecordId_; timestamp_ = time(0); } void GetLastProcEventIdCMD::setSwRecordId(const unsigned char* recordId, int length) { if(length < 2) return; swRecordId_ = recordId[0] | (recordId[1] << 8); mostRecentId_ = &swRecordId_; timestamp_ = time(0); } uint16_t GetLastProcEventIdCMD::getBmcRecordId() const { return bmcRecordId_; } uint16_t GetLastProcEventIdCMD::getSwRecordId() const { return swRecordId_; } int GetLastProcEventIdCMD::process(const unsigned char* req, int reqLength, unsigned char* resp) { log_file << "Get Last Proccessed Event Id Command" << std::endl; resp[0] = COMP_CODE_OK; resp[1] = timestamp_ & 0x000000FF; resp[2] = (timestamp_ & 0x0000FF00) >> 8; resp[3] = (timestamp_ & 0x00FF0000) >> 16; resp[4] = (timestamp_ & 0xFF000000) >> 24; resp[5] = *mostRecentId_ & 0x00FF ; resp[6] = (*mostRecentId_ & 0xFF00) >> 8; resp[7] = swRecordId_ & 0x00FF ; resp[8] = (swRecordId_ & 0xFF00) >> 8; resp[9] = swRecordId_ & 0x00FF ; resp[10] = (swRecordId_ & 0xFF00) >> 8; return 11; } SetLastProcEventIdCMD::SetLastProcEventIdCMD(GetLastProcEventIdCMD* lastProcEventCmd) { lastProcEventCmd_ = lastProcEventCmd; } int SetLastProcEventIdCMD::process(const unsigned char* req, int reqLength, unsigned char* resp) { log_file << "Set Last Proccessed Event Id Command" << std::endl; resp[0] = COMP_CODE_OK; if (reqLength >= 3) { if((req[0] & 0x01) == 0x01) lastProcEventCmd_->setBmcRecordId(req + 1, 2); else lastProcEventCmd_->setSwRecordId(req + 1, 2); } return 1; }
Add support for PEF system GUID
Add support for PEF system GUID
C++
bsd-3-clause
J3NI/J3NI,J3NI/J3NI,J3NI/J3NI
6e291d34a089a246079f9a19f131d13f66d35371
src/dlangindenter.cpp
src/dlangindenter.cpp
#include "dlangindenter.h" #include "dlangautocompleter.h" #include <texteditor/tabsettings.h> #include <texteditor/textdocumentlayout.h> #include <QTextDocument> #include <QTextBlock> #include <QTextCursor> using namespace DlangEditor; enum { INDENTER_USER_FORMAT_ID = QTextFormat::UserFormat + 1 }; DlangIndenter::DlangIndenter() { } bool DlangIndenter::isElectricCharacter(const QChar &ch) const { if (ch == QLatin1Char('{') || ch == QLatin1Char('}') || ch == QLatin1Char(':')) { return true; } return false; } class IndenterUserFormat { public: int indent; int padding; IndenterUserFormat() : indent(0), padding(0) {} }; Q_DECLARE_METATYPE(IndenterUserFormat) IndenterUserFormat calculateIndent(const QTextBlock &origBlock, int tabSize) { QTextBlock block = origBlock; QTextBlock prev = block; do { prev = prev.previous(); if (!prev.isValid()) { return IndenterUserFormat(); } } while (prev.text().trimmed().isEmpty()); IndenterUserFormat prevData = prev.blockFormat().property(INDENTER_USER_FORMAT_ID).value<IndenterUserFormat>(); int indent = 0; int padding = 0; QString text = prev.text(); const int prevLen = text.length(); int prevIndent = -1; for (int pos = 0; pos < prevLen; ++pos) { const QChar qc = text.at(pos); if (!qc.isSpace()) { if (prevIndent == -1) { prevIndent = pos; } } else { continue; } const char c = qc.toLatin1(); switch (c) { case '{': indent += tabSize; padding = 0; break; case '}': indent -= tabSize; padding = 0; break; case ':': case ';': padding = 0; break; default: padding = tabSize; break; } } if (prevIndent >= 0) { QChar c = text.at(prevIndent); if (c == QChar('}')) { indent += tabSize; } else { QChar n = prevIndent + 1 < prevLen ? text.at(prevIndent + 1) : QChar(); if ((c == QChar('*') && DdocAutoCompleter::isDdocComment(QTextCursor(prev))) || (c == QChar('/') && (n == QChar('*') || n == QChar('/')))) { padding = 0; indent = 0; } } } else { prevIndent = 0; } text = block.text().trimmed(); if (text.startsWith('}')) { indent -= tabSize; } else if (text.startsWith('{')) { padding = 0; } else if (text.endsWith(':')) { padding = -tabSize; } auto setBlockIndenterData = [](QTextBlock& block, IndenterUserFormat d) { QTextCursor c(block); auto f = c.blockFormat(); f.setProperty(INDENTER_USER_FORMAT_ID, QVariant::fromValue(d)); c.setBlockFormat(f); }; if (prevData.indent != prevIndent) { prevData.indent = prevIndent; setBlockIndenterData(prev, prevData); } IndenterUserFormat blockData; blockData.indent = indent + prevIndent - prevData.padding + padding; blockData.padding = padding; if (padding) { if (prevData.padding) { indent = prevData.indent; padding = prevData.padding; } } setBlockIndenterData(block, blockData); return blockData; } void DlangIndenter::indentBlock(QTextDocument *doc, const QTextBlock &block, const QChar &/*typedChar*/, const TextEditor::TabSettings &tabSettings) { // At beginning: Leave as is. if (block == doc->begin()) return; const auto align = calculateIndent(block, tabSettings.m_indentSize); tabSettings.indentLine(block, align.indent, align.padding); }
#include "dlangindenter.h" #include "dlangautocompleter.h" #include <texteditor/tabsettings.h> #include <texteditor/textdocumentlayout.h> #include <QTextDocument> #include <QTextBlock> #include <QTextCursor> using namespace DlangEditor; enum { INDENTER_USER_FORMAT_ID = QTextFormat::UserFormat + 1 }; DlangIndenter::DlangIndenter() { } bool DlangIndenter::isElectricCharacter(const QChar &ch) const { if (ch == QLatin1Char('{') || ch == QLatin1Char('}') || ch == QLatin1Char(':')) { return true; } return false; } class IndenterUserFormat { public: int indent; int padding; IndenterUserFormat() : indent(0), padding(0) {} }; Q_DECLARE_METATYPE(IndenterUserFormat) /** * @brief Calculate indent and padding for block * @note Real offset of block = indent + padding (differs from QtC) * @param origBlock block to indent * @param tabSize size of tab * @return indent and padding */ IndenterUserFormat calculateIndent(const QTextBlock &origBlock, int tabSize) { QTextBlock block = origBlock; QTextBlock prev = block; do { prev = prev.previous(); if (!prev.isValid()) { return IndenterUserFormat(); } } while (prev.text().trimmed().isEmpty()); IndenterUserFormat prevData = prev.blockFormat().property(INDENTER_USER_FORMAT_ID).value<IndenterUserFormat>(); int indent = 0; int padding = 0; QString text = prev.text(); const int prevLen = text.length(); int prevOffset = -1; for (int pos = 0; pos < prevLen; ++pos) { const QChar qc = text.at(pos); if (!qc.isSpace()) { if (prevOffset == -1) { prevOffset = pos; } } else { continue; } const char c = qc.toLatin1(); switch (c) { case '{': indent += tabSize; padding = 0; break; case '}': indent -= tabSize; padding = 0; break; case ':': case ';': padding = 0; break; default: padding = tabSize; break; } } if (prevOffset >= 0) { QChar c = text.at(prevOffset); if (c == QChar('}')) { indent += tabSize; } else { QChar n = prevOffset + 1 < prevLen ? text.at(prevOffset + 1) : QChar(); if ((c == QChar('*') && DdocAutoCompleter::isDdocComment(QTextCursor(prev))) || (c == QChar('/') && (n == QChar('*') || n == QChar('/')))) { padding = 0; indent = 0; } } } else { prevOffset = 0; } text = block.text().trimmed(); if (text.startsWith('}')) { padding = 0; indent -= tabSize; } else if (text.startsWith('{')) { padding = 0; } else if (text.endsWith(':')) { padding = -tabSize; } auto setBlockIndenterData = [](QTextBlock& block, IndenterUserFormat d) { QTextCursor c(block); auto f = c.blockFormat(); f.setProperty(INDENTER_USER_FORMAT_ID, QVariant::fromValue(d)); c.setBlockFormat(f); }; if (prevOffset < 0) { prevOffset = 0; } if (prevData.indent + prevData.padding != prevOffset) { prevData.indent = prevOffset; prevData.padding = 0; setBlockIndenterData(prev, prevData); } indent += prevData.indent; if (padding > 0 && prevData.padding > 0) { indent = prevData.indent; padding = prevData.padding; } IndenterUserFormat blockData; blockData.indent = indent; blockData.padding = padding; setBlockIndenterData(block, blockData); return blockData; } void DlangIndenter::indentBlock(QTextDocument *doc, const QTextBlock &block, const QChar &/*typedChar*/, const TextEditor::TabSettings &tabSettings) { // At beginning: Leave as is. if (block == doc->begin()) return; const auto align = calculateIndent(block, tabSettings.m_indentSize); tabSettings.indentLine(block, align.indent + align.padding, align.padding); }
Fix indention *Colon case
Fix indention *Colon case
C++
mit
Groterik/qtcreator-dlangeditor,Groterik/qtcreator-dlangeditor,Groterik/qtcreator-dlangeditor
d72e62066079c894d7275d60fecf4ef19f9fa01c
sfx2/inc/arrdecl.hxx
sfx2/inc/arrdecl.hxx
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SFX_ARRDECL_HXX #define _SFX_ARRDECL_HXX #include <svl/svarray.hxx> #include <sfx2/minarray.hxx> #include <vector> struct CntUpdateResult; SV_DECL_PTRARR_DEL(CntUpdateResults_Impl, CntUpdateResult*, 4, 4) class SfxObjectShell; SV_DECL_PTRARR( SfxObjectShellArr_Impl, SfxObjectShell*, 4, 4 ) class SfxViewFrame; SV_DECL_PTRARR( SfxViewFrameArr_Impl, SfxViewFrame*, 4, 4 ) class SfxViewShell; SV_DECL_PTRARR( SfxViewShellArr_Impl, SfxViewShell*, 4, 4 ) class SfxObjectFactory; typedef SfxObjectFactory* SfxObjectFactoryPtr; SV_DECL_PTRARR( SfxObjectFactoryArr_Impl, SfxObjectFactoryPtr, 3, 3 ) struct SfxTbxCtrlFactory; SV_DECL_PTRARR_DEL( SfxTbxCtrlFactArr_Impl, SfxTbxCtrlFactory*, 8, 4 ) struct SfxStbCtrlFactory; SV_DECL_PTRARR_DEL( SfxStbCtrlFactArr_Impl, SfxStbCtrlFactory*, 8, 4 ) struct SfxMenuCtrlFactory; SV_DECL_PTRARR_DEL( SfxMenuCtrlFactArr_Impl, SfxMenuCtrlFactory*, 2, 2 ) struct SfxChildWinFactory; SV_DECL_PTRARR_DEL( SfxChildWinFactArr_Impl, SfxChildWinFactory*, 2, 2 ) class SfxModule; SV_DECL_PTRARR( SfxModuleArr_Impl, SfxModule*, 2, 2 ) class SfxFilter; DECL_PTRARRAY( SfxFilterArr_Impl, SfxFilter*, 4, 4 ) class SfxFrame; typedef SfxFrame* SfxFramePtr; SV_DECL_PTRARR( SfxFrameArr_Impl, SfxFramePtr, 4, 4 ) typedef ::std::vector< SfxFilter* > SfxFilterList_Impl; struct SfxExternalLib_Impl; typedef SfxExternalLib_Impl* SfxExternalLibPtr; SV_DECL_PTRARR_DEL( SfxExternalLibArr_Impl, SfxExternalLibPtr, 2, 2 ) class SfxSlot; typedef SfxSlot* SfxSlotPtr; SV_DECL_PTRARR( SfxSlotArr_Impl, SfxSlotPtr, 20, 20 ) #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SFX_ARRDECL_HXX #define _SFX_ARRDECL_HXX #include <svl/svarray.hxx> #include <sfx2/minarray.hxx> #include <vector> class SfxObjectShell; SV_DECL_PTRARR( SfxObjectShellArr_Impl, SfxObjectShell*, 4, 4 ) class SfxViewFrame; SV_DECL_PTRARR( SfxViewFrameArr_Impl, SfxViewFrame*, 4, 4 ) class SfxViewShell; SV_DECL_PTRARR( SfxViewShellArr_Impl, SfxViewShell*, 4, 4 ) class SfxObjectFactory; typedef SfxObjectFactory* SfxObjectFactoryPtr; SV_DECL_PTRARR( SfxObjectFactoryArr_Impl, SfxObjectFactoryPtr, 3, 3 ) struct SfxTbxCtrlFactory; SV_DECL_PTRARR_DEL( SfxTbxCtrlFactArr_Impl, SfxTbxCtrlFactory*, 8, 4 ) struct SfxStbCtrlFactory; SV_DECL_PTRARR_DEL( SfxStbCtrlFactArr_Impl, SfxStbCtrlFactory*, 8, 4 ) struct SfxMenuCtrlFactory; SV_DECL_PTRARR_DEL( SfxMenuCtrlFactArr_Impl, SfxMenuCtrlFactory*, 2, 2 ) struct SfxChildWinFactory; SV_DECL_PTRARR_DEL( SfxChildWinFactArr_Impl, SfxChildWinFactory*, 2, 2 ) class SfxModule; SV_DECL_PTRARR( SfxModuleArr_Impl, SfxModule*, 2, 2 ) class SfxFilter; DECL_PTRARRAY( SfxFilterArr_Impl, SfxFilter*, 4, 4 ) class SfxFrame; typedef SfxFrame* SfxFramePtr; SV_DECL_PTRARR( SfxFrameArr_Impl, SfxFramePtr, 4, 4 ) typedef ::std::vector< SfxFilter* > SfxFilterList_Impl; struct SfxExternalLib_Impl; typedef SfxExternalLib_Impl* SfxExternalLibPtr; SV_DECL_PTRARR_DEL( SfxExternalLibArr_Impl, SfxExternalLibPtr, 2, 2 ) class SfxSlot; typedef SfxSlot* SfxSlotPtr; SV_DECL_PTRARR( SfxSlotArr_Impl, SfxSlotPtr, 20, 20 ) #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
Remove unused SV_DECL_PTRARR_DEL
Remove unused SV_DECL_PTRARR_DEL
C++
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core