text
stringlengths 54
60.6k
|
---|
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3418
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3418 to 3419<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3419
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3464
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3464 to 3465<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3465
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3420
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3420 to 3421<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3421
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3221
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3221 to 3222<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3222
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/**
* capture.cpp
*
* @date Nov 4, 2015
* @author Ryan Peach
* @version v0.1
*/
#include "capture.hpp"
#define TEST
void Capture::Frame(Mat img) {
frame = &img;
edges = NULL;
polys = NULL;
fps = NULL;
rects = NULL;
}
Mat* Capture::getEdges() {
if (edges == NULL) {
auto out = edgesCanny(*frame, etol1, etol2, eSize);
edges = &out;
}
#ifdef TEST
if (edges != NULL) {imshow("Canny",*edges);}
#endif
return edges;
}
Cnts* Capture::getPolys() {
if (polys == NULL && getEdges() != NULL) {
auto out = findPolys(*getEdges(), polyTol);
polys = &out;
}
return polys;
}
Fps* Capture::getFps() {
if (fps == NULL && getPolys() != NULL) {
auto out = findFocusPoints(*getPolys(), angleTol, distTol);
fps = &out;
}
#ifdef TEST
cout << "Fp's Found: " << (*fps).size() << endl;
#endif
return fps;
}
void Capture::set(cnt corners) {
Points cent = corners;
Point r = calcRef(corners); ref = &r;
cnt b = sortCorners(cent,*getRef()); border = &b;
}
void Capture::set(Fps corners) {
Points cent = centroids(corners);
Point r = centroid(calcRef(corners)); ref = &r;
cnt b = sortCorners(cent,*getRef()); border = &b;
}
Point* Capture::getRef() {
if (ref == NULL) {
getBorder();
}
return ref;
}
vector<cnt>* Capture::getRects() {
if (rects == NULL) {
vector<cnt> r = hasRectangles((*getPolys()).contours, angleTol, distTol);
rects = &r;
}
return rects;
}
cnt* Capture::getBorder() {
switch(sel) {
case fpcorners: {
if (border == NULL && getFps() != NULL) {
vector<Fp> corners = calcCorners(*getFps(), angleTol, distTol);
if (corners.size() == 4) {
set(corners);
}
}} break;
case strongborder: {
vector<cnt> check;
for (cnt r : (*getRects())) {
if (validRect(r)) {check.push_back(r);};
}
vector<cnt> similar = findSimilar(check, distTol);
if (!similar.empty()) {
cnt corners = largest(similar);
set(corners);
}} break;
case regular: {
vector<cnt> valid;
for (cnt r : (*getRects())) {
if (validRect(r)) {valid.push_back(r);}
}
if (!valid.empty()) {
cnt corners = largest(valid);
set(corners);
}} break;
case automatic: {
sel = fpcorners;
if (getBorder() == NULL) {sel = strongborder;}
if (getBorder() == NULL) {sel = regular;}
getBorder();
sel = automatic;
} break;
}
return border;
}
// Uses polyTol, angleTol, distTol, wSize, C;
vector<Mat*> Capture::process() {
#ifdef TEST
cout << "Running Capture::process..." << endl;
#endif
// Variable Declaration
Mat warp, drawing;
vector<Mat*> out;
if (getBorder() != NULL && getRef() != NULL) {
// Get border from focus points and warp
warp = fixPerspective(*frame, *getBorder(), *getRef());
warp = toColor(warp);
Scalar color = Scalar(255, 0, 0);
drawing = warp;
drawContours(drawing, *getBorder(), 0, color, 3, 8);
out = vector<Mat*>{&drawing, &warp};
return out;
} else {
out = vector<Mat*>{frame,NULL};
return out;
}
}
bool Capture::validRect(cnt r) {
return contourArea(r) >= sizeRatio*(*frame).cols*(*frame).rows
&& isAspectRatio(r, aspectRatio, ratioTol)
&& ((*fps).size()==0 || allInside(r, *fps));
}
<commit_msg>Added capture.cpp method running print statements.<commit_after>/**
* capture.cpp
*
* @date Nov 4, 2015
* @author Ryan Peach
* @version v0.1
*/
#include "capture.hpp"
#define TEST
void Capture::Frame(Mat img) {
#ifdef TEST
cout << "Running Capture::Frame..." << endl;
#endif
frame = &img;
edges = NULL;
polys = NULL;
fps = NULL;
rects = NULL;
}
Mat* Capture::getEdges() {
#ifdef TEST
cout << "Running Capture::getEdges..." << endl;
#endif
if (edges == NULL) {
auto out = edgesCanny(*frame, etol1, etol2, eSize);
edges = &out;
}
#ifdef TEST
if (edges != NULL) {imshow("Canny",*edges);}
#endif
return edges;
}
Cnts* Capture::getPolys() {
#ifdef TEST
cout << "Running Capture::getPolys..." << endl;
#endif
if (polys == NULL && getEdges() != NULL) {
auto out = findPolys(*getEdges(), polyTol);
polys = &out;
}
return polys;
}
Fps* Capture::getFps() {
#ifdef TEST
cout << "Running Capture::getFps..." << endl;
#endif
if (fps == NULL && getPolys() != NULL) {
auto out = findFocusPoints(*getPolys(), angleTol, distTol);
fps = &out;
}
#ifdef TEST
cout << "Fp's Found: " << (*fps).size() << endl;
#endif
return fps;
}
void Capture::set(cnt corners) {
#ifdef TEST
cout << "Running Capture::set(cnt)..." << endl;
#endif
Points cent = corners;
Point r = calcRef(corners); ref = &r;
cnt b = sortCorners(cent,*getRef()); border = &b;
}
void Capture::set(Fps corners) {
#ifdef TEST
cout << "Running Capture::set(Fps)..." << endl;
#endif
Points cent = centroids(corners);
Point r = centroid(calcRef(corners)); ref = &r;
cnt b = sortCorners(cent,*getRef()); border = &b;
}
Point* Capture::getRef() {
#ifdef TEST
cout << "Running Capture::getRef..." << endl;
#endif
if (ref == NULL) {
getBorder();
}
return ref;
}
vector<cnt>* Capture::getRects() {
#ifdef TEST
cout << "Running Capture::getRects..." << endl;
#endif
if (rects == NULL) {
vector<cnt> r = hasRectangles((*getPolys()).contours, angleTol, distTol);
rects = &r;
}
return rects;
}
cnt* Capture::getBorder() {
#ifdef TEST
cout << "Running Capture::getBorder..." << endl;
#endif
switch(sel) {
case fpcorners: {
#ifdef TEST
cout << "Capture::getBorder: fpcorners..." << endl;
#endif
if (border == NULL && getFps() != NULL) {
vector<Fp> corners = calcCorners(*getFps(), angleTol, distTol);
if (corners.size() == 4) {
set(corners);
}
}} break;
case strongborder: {
#ifdef TEST
cout << "Capture::getBorder: strongborder..." << endl;
#endif
vector<cnt> check;
for (cnt r : (*getRects())) {
if (validRect(r)) {check.push_back(r);}
}
vector<cnt> similar = findSimilar(check, distTol);
if (!similar.empty()) {
cnt corners = largest(similar);
set(corners);
}} break;
case regular: {
#ifdef TEST
cout << "Capture::getBorder: regular..." << endl;
#endif
vector<cnt> valid;
for (cnt r : (*getRects())) {
if (validRect(r)) {valid.push_back(r);}
}
if (!valid.empty()) {
cnt corners = largest(valid);
set(corners);
}} break;
case automatic: {
#ifdef TEST
cout << "Capture::getBorder: automatic..." << endl;
#endif
sel = fpcorners;
if (getBorder() == NULL) {sel = strongborder;}
if (getBorder() == NULL) {sel = regular;}
getBorder();
sel = automatic;
} break;
}
return border;
}
// Uses polyTol, angleTol, distTol, wSize, C;
vector<Mat*> Capture::process() {
#ifdef TEST
cout << "Running Capture::process..." << endl;
#endif
// Variable Declaration
Mat warp, drawing;
vector<Mat*> out;
if (getBorder() != NULL && getRef() != NULL) {
// Get border from focus points and warp
warp = fixPerspective(*frame, *getBorder(), *getRef());
warp = toColor(warp);
Scalar color = Scalar(255, 0, 0);
drawing = warp;
drawContours(drawing, *getBorder(), 0, color, 3, 8);
out = vector<Mat*>{&drawing, &warp};
return out;
} else {
out = vector<Mat*>{frame,NULL};
return out;
}
}
bool Capture::validRect(cnt r) {
#ifdef TEST
cout << "Capture::getBorder: validRect... " << endl;
#endif
bool out = sizeRatio*(*frame).cols*(*frame).rows
&& isAspectRatio(r, aspectRatio, ratioTol)
&& ((*fps).size()==0 || allInside(r, *fps));
#ifdef TEST
cout << "Capture::getBorder: validRect = " << out << endl;
#endif
return out;
}
<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
int divide(int dividend, int divisor);
int main()
{
cout << divide(2147483647,2) << endl;
cout << divide(2147483647,2) << endl;
cout << divide(2147483647,2) << endl;
cout << divide(2147483647,2) << endl;
cout << divide(2147483647,2) << endl;
cout << divide(2147483647,2) << endl;
cout << divide(2147483647,2) << endl;
return 0;
}
int divide(int dividend, int divisor) {
int symbol = 1;
long n1 = dividend, n2 = divisor;
if(n1 < 0) {symbol = symbol * -1; n1 = n1 * -1;}
if(n2 < 0) {symbol = symbol * -1; n2 = n2 * -1;}
int res = 0, count = 0;
while(true){
if(n2 == 1) return n1*symbol;
if(n1 < n2) return res*symbol;
else if(n1 == n2) return (res + 1)*symbol;
else{
while(n1 > n2){
n2 = n2 << 1;
if(count == 0) count = 1;
else count = count << 1;
}
n1 = n1 - (n2 >> 1);
n2 = divisor;
res += count;
count = 0;
}
}
}
<commit_msg>TLE was solved by a new algorithm<commit_after>class Solution {
public:
int divide(int dividend, int divisor) {
int sign = 1;
if((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)) sign = -1;
unsigned int a = dividend > 0 ? dividend : dividend * (-1);
unsigned int b = divisor > 0 ? divisor : divisor * (-1);
unsigned int d = b, i = 0, res = 0;
unsigned int nums[32];
while(d <= a && d > 0){
nums[i++] = d;
d = d << 1;
}
i --;
while(a >= b){
if(a >= nums[i]){
a = a - nums[i];
res += (1 << i);
}
i--;
}
return res*sign;
}
};
<|endoftext|> |
<commit_before>/* -*- 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 2010 Miklos Vajna.
*
* 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 _CPPUHELPER_IMPLEMENTATIONENTRY_
#include <cppuhelper/implementationentry.hxx>
#endif
#include <osl/module.hxx>
#include <tools/solar.h>
#include <RtfFilter.hxx>
#include <comphelper/mediadescriptor.hxx>
#include <dmapper/DomainMapper.hxx>
#include <rtftok/RTFDocument.hxx>
using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star;
using ::comphelper::MediaDescriptor;
RtfFilter::RtfFilter( const uno::Reference< uno::XComponentContext >& rxContext) :
m_xContext( rxContext )
{
}
RtfFilter::~RtfFilter()
{
}
sal_Bool RtfFilter::filter( const uno::Sequence< beans::PropertyValue >& aDescriptor )
throw (uno::RuntimeException)
{
OSL_TRACE("%s", OSL_THIS_FUNC);
if( m_xSrcDoc.is() )
{
uno::Reference< lang::XMultiServiceFactory > xMSF(m_xContext->getServiceManager(), uno::UNO_QUERY_THROW);
uno::Reference< uno::XInterface > xIfc( xMSF->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.RtfExport" ))), uno::UNO_QUERY_THROW);
if (!xIfc.is())
return sal_False;
uno::Reference< document::XExporter > xExprtr(xIfc, uno::UNO_QUERY_THROW);
uno::Reference< document::XFilter > xFltr(xIfc, uno::UNO_QUERY_THROW);
if (!xExprtr.is() || !xFltr.is())
return sal_False;
xExprtr->setSourceDocument(m_xSrcDoc);
return xFltr->filter(aDescriptor);
}
else if ( m_xDstDoc.is() )
{
MediaDescriptor aMediaDesc( aDescriptor );
#ifdef DEBUG_IMPORT
OUString sURL = aMediaDesc.getUnpackedValueOrDefault( MediaDescriptor::PROP_URL(), OUString() );
::std::string sURLc = OUStringToOString(sURL, RTL_TEXTENCODING_ASCII_US).getStr();
writerfilter::TagLogger::Pointer_t dmapperLogger
(writerfilter::TagLogger::getInstance("DOMAINMAPPER"));
dmapperLogger->setFileName(sURLc);
dmapperLogger->startDocument();
#endif
uno::Reference< io::XInputStream > xInputStream;
aMediaDesc.addInputStream();
aMediaDesc[ MediaDescriptor::PROP_INPUTSTREAM() ] >>= xInputStream;
writerfilter::Stream::Pointer_t pStream(
new writerfilter::dmapper::DomainMapper(m_xContext, xInputStream, m_xDstDoc, writerfilter::dmapper::DOCUMENT_RTF));
writerfilter::rtftok::RTFDocument::Pointer_t const pDocument(
writerfilter::rtftok::RTFDocumentFactory::createDocument(xInputStream) );
pDocument->resolve(*pStream);
#ifdef DEBUG_IMPORT
dmapperLogger->endDocument();
#endif
return sal_True;
}
return sal_False;
}
void RtfFilter::cancel( ) throw (uno::RuntimeException)
{
}
void RtfFilter::setSourceDocument( const uno::Reference< lang::XComponent >& xDoc )
throw (lang::IllegalArgumentException, uno::RuntimeException)
{
m_xSrcDoc = xDoc;
}
void RtfFilter::setTargetDocument( const uno::Reference< lang::XComponent >& xDoc )
throw (lang::IllegalArgumentException, uno::RuntimeException)
{
m_xDstDoc = xDoc;
}
void RtfFilter::initialize( const uno::Sequence< uno::Any >& /*aArguments*/ ) throw (uno::Exception, uno::RuntimeException)
{
// The DOCX exporter here extracts 'type' of the filter, ie 'Word' or
// 'Word Template' but we don't need it for RTF.
}
OUString RtfFilter::getImplementationName( ) throw (uno::RuntimeException)
{
return RtfFilter_getImplementationName();
}
#define SERVICE_NAME1 "com.sun.star.document.ImportFilter"
#define SERVICE_NAME2 "com.sun.star.document.ExportFilter"
sal_Bool RtfFilter::supportsService( const OUString& rServiceName ) throw (uno::RuntimeException)
{
return (rServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME1 ) ) ||
rServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME2 ) ));
}
uno::Sequence< OUString > RtfFilter::getSupportedServiceNames( ) throw (uno::RuntimeException)
{
return RtfFilter_getSupportedServiceNames();
}
/* Helpers, used by shared lib exports. */
OUString RtfFilter_getImplementationName () throw (uno::RuntimeException)
{
return OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.RtfFilter" ) );
}
uno::Sequence< OUString > RtfFilter_getSupportedServiceNames( ) throw (uno::RuntimeException)
{
uno::Sequence < OUString > aRet(2);
OUString* pArray = aRet.getArray();
pArray[0] = OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME1 ) );
pArray[1] = OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME2 ) );
return aRet;
}
#undef SERVICE_NAME1
#undef SERVICE_NAME2
uno::Reference< uno::XInterface > RtfFilter_createInstance( const uno::Reference< uno::XComponentContext >& xContext)
throw( uno::Exception )
{
return (cppu::OWeakObject*) new RtfFilter( xContext );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Make it easy to disable the new importer<commit_after>/* -*- 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 2010 Miklos Vajna.
*
* 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 _CPPUHELPER_IMPLEMENTATIONENTRY_
#include <cppuhelper/implementationentry.hxx>
#endif
#include <osl/module.hxx>
#include <tools/solar.h>
#include <RtfFilter.hxx>
#include <comphelper/mediadescriptor.hxx>
#include <dmapper/DomainMapper.hxx>
#include <rtftok/RTFDocument.hxx>
using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star;
using ::comphelper::MediaDescriptor;
RtfFilter::RtfFilter( const uno::Reference< uno::XComponentContext >& rxContext) :
m_xContext( rxContext )
{
}
RtfFilter::~RtfFilter()
{
}
sal_Bool RtfFilter::filter( const uno::Sequence< beans::PropertyValue >& aDescriptor )
throw (uno::RuntimeException)
{
OSL_TRACE("%s", OSL_THIS_FUNC);
if( m_xSrcDoc.is() )
{
uno::Reference< lang::XMultiServiceFactory > xMSF(m_xContext->getServiceManager(), uno::UNO_QUERY_THROW);
uno::Reference< uno::XInterface > xIfc( xMSF->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.RtfExport" ))), uno::UNO_QUERY_THROW);
if (!xIfc.is())
return sal_False;
uno::Reference< document::XExporter > xExprtr(xIfc, uno::UNO_QUERY_THROW);
uno::Reference< document::XFilter > xFltr(xIfc, uno::UNO_QUERY_THROW);
if (!xExprtr.is() || !xFltr.is())
return sal_False;
xExprtr->setSourceDocument(m_xSrcDoc);
return xFltr->filter(aDescriptor);
}
else if ( m_xDstDoc.is() )
{
bool bUseDomainMapper = true;
if (bUseDomainMapper)
{
MediaDescriptor aMediaDesc( aDescriptor );
#ifdef DEBUG_IMPORT
OUString sURL = aMediaDesc.getUnpackedValueOrDefault( MediaDescriptor::PROP_URL(), OUString() );
::std::string sURLc = OUStringToOString(sURL, RTL_TEXTENCODING_ASCII_US).getStr();
writerfilter::TagLogger::Pointer_t dmapperLogger
(writerfilter::TagLogger::getInstance("DOMAINMAPPER"));
dmapperLogger->setFileName(sURLc);
dmapperLogger->startDocument();
#endif
uno::Reference< io::XInputStream > xInputStream;
aMediaDesc.addInputStream();
aMediaDesc[ MediaDescriptor::PROP_INPUTSTREAM() ] >>= xInputStream;
writerfilter::Stream::Pointer_t pStream(
new writerfilter::dmapper::DomainMapper(m_xContext, xInputStream, m_xDstDoc, writerfilter::dmapper::DOCUMENT_RTF));
writerfilter::rtftok::RTFDocument::Pointer_t const pDocument(
writerfilter::rtftok::RTFDocumentFactory::createDocument(xInputStream) );
pDocument->resolve(*pStream);
#ifdef DEBUG_IMPORT
dmapperLogger->endDocument();
#endif
return sal_True;
}
// if not, then use the old importer
uno::Reference< lang::XMultiServiceFactory > xMSF(m_xContext->getServiceManager(), uno::UNO_QUERY_THROW);
uno::Reference< uno::XInterface > xIfc( xMSF->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.RtfImport" ))), uno::UNO_QUERY_THROW);
if (!xIfc.is())
return sal_False;
uno::Reference< document::XImporter > xImprtr(xIfc, uno::UNO_QUERY_THROW);
uno::Reference< document::XFilter > xFltr(xIfc, uno::UNO_QUERY_THROW);
if (!xImprtr.is() || !xFltr.is())
return sal_False;
xImprtr->setTargetDocument(m_xDstDoc);
return xFltr->filter(aDescriptor);
}
return sal_False;
}
void RtfFilter::cancel( ) throw (uno::RuntimeException)
{
}
void RtfFilter::setSourceDocument( const uno::Reference< lang::XComponent >& xDoc )
throw (lang::IllegalArgumentException, uno::RuntimeException)
{
m_xSrcDoc = xDoc;
}
void RtfFilter::setTargetDocument( const uno::Reference< lang::XComponent >& xDoc )
throw (lang::IllegalArgumentException, uno::RuntimeException)
{
m_xDstDoc = xDoc;
}
void RtfFilter::initialize( const uno::Sequence< uno::Any >& /*aArguments*/ ) throw (uno::Exception, uno::RuntimeException)
{
// The DOCX exporter here extracts 'type' of the filter, ie 'Word' or
// 'Word Template' but we don't need it for RTF.
}
OUString RtfFilter::getImplementationName( ) throw (uno::RuntimeException)
{
return RtfFilter_getImplementationName();
}
#define SERVICE_NAME1 "com.sun.star.document.ImportFilter"
#define SERVICE_NAME2 "com.sun.star.document.ExportFilter"
sal_Bool RtfFilter::supportsService( const OUString& rServiceName ) throw (uno::RuntimeException)
{
return (rServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME1 ) ) ||
rServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME2 ) ));
}
uno::Sequence< OUString > RtfFilter::getSupportedServiceNames( ) throw (uno::RuntimeException)
{
return RtfFilter_getSupportedServiceNames();
}
/* Helpers, used by shared lib exports. */
OUString RtfFilter_getImplementationName () throw (uno::RuntimeException)
{
return OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.RtfFilter" ) );
}
uno::Sequence< OUString > RtfFilter_getSupportedServiceNames( ) throw (uno::RuntimeException)
{
uno::Sequence < OUString > aRet(2);
OUString* pArray = aRet.getArray();
pArray[0] = OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME1 ) );
pArray[1] = OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME2 ) );
return aRet;
}
#undef SERVICE_NAME1
#undef SERVICE_NAME2
uno::Reference< uno::XInterface > RtfFilter_createInstance( const uno::Reference< uno::XComponentContext >& xContext)
throw( uno::Exception )
{
return (cppu::OWeakObject*) new RtfFilter( xContext );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>//===- FileCheck.cpp - Check that File's Contents match what is expected --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// FileCheck does a line-by line check of a file that validates whether it
// contains the expected content. This is useful for regression tests etc.
//
// This program exits with an error status of 2 on error, exit status of 0 if
// the file matched the expected contents, and exit status of 1 if it did not
// contain the expected contents.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Signals.h"
using namespace llvm;
static cl::opt<std::string>
CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
static cl::opt<std::string>
InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
cl::init("-"), cl::value_desc("filename"));
static cl::opt<std::string>
CheckPrefix("check-prefix", cl::init("CHECK"),
cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
static cl::opt<bool>
NoCanonicalizeWhiteSpace("strict-whitespace",
cl::desc("Do not treat all horizontal whitespace as equivalent"));
/// CheckString - This is a check that we found in the input file.
struct CheckString {
/// Str - The string to match.
std::string Str;
/// Loc - The location in the match file that the check string was specified.
SMLoc Loc;
/// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
/// to a CHECK: directive.
bool IsCheckNext;
/// NotStrings - These are all of the strings that are disallowed from
/// occurring between this match string and the previous one (or start of
/// file).
std::vector<std::pair<SMLoc, std::string> > NotStrings;
CheckString(const std::string &S, SMLoc L, bool isCheckNext)
: Str(S), Loc(L), IsCheckNext(isCheckNext) {}
};
/// ReadCheckFile - Read the check file, which specifies the sequence of
/// expected strings. The strings are added to the CheckStrings vector.
static bool ReadCheckFile(SourceMgr &SM,
std::vector<CheckString> &CheckStrings) {
// Open the check file, and tell SourceMgr about it.
std::string ErrorStr;
MemoryBuffer *F =
MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr);
if (F == 0) {
errs() << "Could not open check file '" << CheckFilename << "': "
<< ErrorStr << '\n';
return true;
}
SM.AddNewSourceBuffer(F, SMLoc());
// Find all instances of CheckPrefix followed by : in the file.
StringRef Buffer = F->getBuffer();
std::vector<std::pair<SMLoc, std::string> > NotMatches;
while (1) {
// See if Prefix occurs in the memory buffer.
Buffer = Buffer.substr(Buffer.find(CheckPrefix));
// If we didn't find a match, we're done.
if (Buffer.empty())
break;
const char *CheckPrefixStart = Buffer.data();
// When we find a check prefix, keep track of whether we find CHECK: or
// CHECK-NEXT:
bool IsCheckNext = false, IsCheckNot = false;
// Verify that the : is present after the prefix.
if (Buffer[CheckPrefix.size()] == ':') {
Buffer = Buffer.substr(CheckPrefix.size()+1);
} else if (Buffer.size() > CheckPrefix.size()+6 &&
memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
Buffer = Buffer.substr(CheckPrefix.size()+7);
IsCheckNext = true;
} else if (Buffer.size() > CheckPrefix.size()+5 &&
memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
Buffer = Buffer.substr(CheckPrefix.size()+6);
IsCheckNot = true;
} else {
Buffer = Buffer.substr(1);
continue;
}
// Okay, we found the prefix, yay. Remember the rest of the line, but
// ignore leading and trailing whitespace.
Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
// Scan ahead to the end of line.
size_t EOL = Buffer.find_first_of("\n\r");
if (EOL == StringRef::npos) EOL = Buffer.size();
// Ignore trailing whitespace.
while (EOL && (Buffer[EOL-1] == ' ' || Buffer[EOL-1] == '\t'))
--EOL;
// Check that there is something on the line.
if (EOL == 0) {
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
"found empty check string with prefix '"+CheckPrefix+":'",
"error");
return true;
}
StringRef PatternStr = Buffer.substr(0, EOL);
// Handle CHECK-NOT.
if (IsCheckNot) {
NotMatches.push_back(std::make_pair(SMLoc::getFromPointer(Buffer.data()),
PatternStr.str()));
Buffer = Buffer.substr(EOL);
continue;
}
// Verify that CHECK-NEXT lines have at least one CHECK line before them.
if (IsCheckNext && CheckStrings.empty()) {
SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
"found '"+CheckPrefix+"-NEXT:' without previous '"+
CheckPrefix+ ": line", "error");
return true;
}
// Okay, add the string we captured to the output vector and move on.
CheckStrings.push_back(CheckString(PatternStr.str(),
SMLoc::getFromPointer(Buffer.data()),
IsCheckNext));
std::swap(NotMatches, CheckStrings.back().NotStrings);
Buffer = Buffer.substr(EOL);
}
if (CheckStrings.empty()) {
errs() << "error: no check strings found with prefix '" << CheckPrefix
<< ":'\n";
return true;
}
if (!NotMatches.empty()) {
errs() << "error: '" << CheckPrefix
<< "-NOT:' not supported after last check line.\n";
return true;
}
return false;
}
// CanonicalizeCheckStrings - Replace all sequences of horizontal whitespace in
// the check strings with a single space.
static void CanonicalizeCheckStrings(std::vector<CheckString> &CheckStrings) {
for (unsigned i = 0, e = CheckStrings.size(); i != e; ++i) {
std::string &Str = CheckStrings[i].Str;
for (unsigned C = 0; C != Str.size(); ++C) {
// If C is not a horizontal whitespace, skip it.
if (Str[C] != ' ' && Str[C] != '\t')
continue;
// Replace the character with space, then remove any other space
// characters after it.
Str[C] = ' ';
while (C+1 != Str.size() &&
(Str[C+1] == ' ' || Str[C+1] == '\t'))
Str.erase(Str.begin()+C+1);
}
}
}
/// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
/// memory buffer, free it, and return a new one.
static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
SmallVector<char, 16> NewFile;
NewFile.reserve(MB->getBufferSize());
for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
Ptr != End; ++Ptr) {
// If C is not a horizontal whitespace, skip it.
if (*Ptr != ' ' && *Ptr != '\t') {
NewFile.push_back(*Ptr);
continue;
}
// Otherwise, add one space and advance over neighboring space.
NewFile.push_back(' ');
while (Ptr+1 != End &&
(Ptr[1] == ' ' || Ptr[1] == '\t'))
++Ptr;
}
// Free the old buffer and return a new one.
MemoryBuffer *MB2 =
MemoryBuffer::getMemBufferCopy(NewFile.data(),
NewFile.data() + NewFile.size(),
MB->getBufferIdentifier());
delete MB;
return MB2;
}
static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
StringRef Buffer) {
// Otherwise, we have an error, emit an error message.
SM.PrintMessage(CheckStr.Loc, "expected string not found in input",
"error");
// Print the "scanning from here" line. If the current position is at the
// end of a line, advance to the start of the next line.
Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), "scanning from here",
"note");
}
/// CountNumNewlinesBetween - Count the number of newlines in the specified
/// range.
static unsigned CountNumNewlinesBetween(StringRef Range) {
unsigned NumNewLines = 0;
while (1) {
// Scan for newline.
Range = Range.substr(Range.find_first_of("\n\r"));
if (Range.empty()) return NumNewLines;
++NumNewLines;
// Handle \n\r and \r\n as a single newline.
if (Range.size() > 1 &&
(Range[1] == '\n' || Range[1] == '\r') &&
(Range[0] != Range[1]))
Range = Range.substr(1);
Range = Range.substr(1);
}
}
int main(int argc, char **argv) {
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
cl::ParseCommandLineOptions(argc, argv);
SourceMgr SM;
// Read the expected strings from the check file.
std::vector<CheckString> CheckStrings;
if (ReadCheckFile(SM, CheckStrings))
return 2;
// Remove duplicate spaces in the check strings if requested.
if (!NoCanonicalizeWhiteSpace)
CanonicalizeCheckStrings(CheckStrings);
// Open the file to check and add it to SourceMgr.
std::string ErrorStr;
MemoryBuffer *F =
MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr);
if (F == 0) {
errs() << "Could not open input file '" << InputFilename << "': "
<< ErrorStr << '\n';
return true;
}
// Remove duplicate spaces in the input file if requested.
if (!NoCanonicalizeWhiteSpace)
F = CanonicalizeInputFile(F);
SM.AddNewSourceBuffer(F, SMLoc());
// Check that we have all of the expected strings, in order, in the input
// file.
StringRef Buffer = F->getBuffer();
const char *LastMatch = Buffer.data();
for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
const CheckString &CheckStr = CheckStrings[StrNo];
StringRef SearchFrom = Buffer;
// Find StrNo in the file.
Buffer = Buffer.substr(Buffer.find(CheckStr.Str));
// If we didn't find a match, reject the input.
if (Buffer.empty()) {
PrintCheckFailed(SM, CheckStr, SearchFrom);
return 1;
}
StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch);
// If this check is a "CHECK-NEXT", verify that the previous match was on
// the previous line (i.e. that there is one newline between them).
if (CheckStr.IsCheckNext) {
// Count the number of newlines between the previous match and this one.
assert(LastMatch != F->getBufferStart() &&
"CHECK-NEXT can't be the first check in a file");
unsigned NumNewLines = CountNumNewlinesBetween(SkippedRegion);
if (NumNewLines == 0) {
SM.PrintMessage(CheckStr.Loc,
CheckPrefix+"-NEXT: is on the same line as previous match",
"error");
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
"'next' match was here", "note");
SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
"previous match was here", "note");
return 1;
}
if (NumNewLines != 1) {
SM.PrintMessage(CheckStr.Loc,
CheckPrefix+
"-NEXT: is not on the line after the previous match",
"error");
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
"'next' match was here", "note");
SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
"previous match was here", "note");
return 1;
}
}
// If this match had "not strings", verify that they don't exist in the
// skipped region.
for (unsigned i = 0, e = CheckStr.NotStrings.size(); i != e; ++i) {
size_t Pos = SkippedRegion.find(CheckStr.NotStrings[i].second);
if (Pos == StringRef::npos) continue;
SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos),
CheckPrefix+"-NOT: string occurred!", "error");
SM.PrintMessage(CheckStr.NotStrings[i].first,
CheckPrefix+"-NOT: pattern specified here", "note");
return 1;
}
// Otherwise, everything is good. Remember this as the last match and move
// on to the next one.
LastMatch = Buffer.data();
Buffer = Buffer.substr(CheckStr.Str.size());
}
return 0;
}
<commit_msg>fix a FileCheck bug where:<commit_after>//===- FileCheck.cpp - Check that File's Contents match what is expected --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// FileCheck does a line-by line check of a file that validates whether it
// contains the expected content. This is useful for regression tests etc.
//
// This program exits with an error status of 2 on error, exit status of 0 if
// the file matched the expected contents, and exit status of 1 if it did not
// contain the expected contents.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Signals.h"
using namespace llvm;
static cl::opt<std::string>
CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
static cl::opt<std::string>
InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
cl::init("-"), cl::value_desc("filename"));
static cl::opt<std::string>
CheckPrefix("check-prefix", cl::init("CHECK"),
cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
static cl::opt<bool>
NoCanonicalizeWhiteSpace("strict-whitespace",
cl::desc("Do not treat all horizontal whitespace as equivalent"));
/// CheckString - This is a check that we found in the input file.
struct CheckString {
/// Str - The string to match.
std::string Str;
/// Loc - The location in the match file that the check string was specified.
SMLoc Loc;
/// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
/// to a CHECK: directive.
bool IsCheckNext;
/// NotStrings - These are all of the strings that are disallowed from
/// occurring between this match string and the previous one (or start of
/// file).
std::vector<std::pair<SMLoc, std::string> > NotStrings;
CheckString(const std::string &S, SMLoc L, bool isCheckNext)
: Str(S), Loc(L), IsCheckNext(isCheckNext) {}
};
/// ReadCheckFile - Read the check file, which specifies the sequence of
/// expected strings. The strings are added to the CheckStrings vector.
static bool ReadCheckFile(SourceMgr &SM,
std::vector<CheckString> &CheckStrings) {
// Open the check file, and tell SourceMgr about it.
std::string ErrorStr;
MemoryBuffer *F =
MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr);
if (F == 0) {
errs() << "Could not open check file '" << CheckFilename << "': "
<< ErrorStr << '\n';
return true;
}
SM.AddNewSourceBuffer(F, SMLoc());
// Find all instances of CheckPrefix followed by : in the file.
StringRef Buffer = F->getBuffer();
std::vector<std::pair<SMLoc, std::string> > NotMatches;
while (1) {
// See if Prefix occurs in the memory buffer.
Buffer = Buffer.substr(Buffer.find(CheckPrefix));
// If we didn't find a match, we're done.
if (Buffer.empty())
break;
const char *CheckPrefixStart = Buffer.data();
// When we find a check prefix, keep track of whether we find CHECK: or
// CHECK-NEXT:
bool IsCheckNext = false, IsCheckNot = false;
// Verify that the : is present after the prefix.
if (Buffer[CheckPrefix.size()] == ':') {
Buffer = Buffer.substr(CheckPrefix.size()+1);
} else if (Buffer.size() > CheckPrefix.size()+6 &&
memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
Buffer = Buffer.substr(CheckPrefix.size()+7);
IsCheckNext = true;
} else if (Buffer.size() > CheckPrefix.size()+5 &&
memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
Buffer = Buffer.substr(CheckPrefix.size()+6);
IsCheckNot = true;
} else {
Buffer = Buffer.substr(1);
continue;
}
// Okay, we found the prefix, yay. Remember the rest of the line, but
// ignore leading and trailing whitespace.
Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
// Scan ahead to the end of line.
size_t EOL = Buffer.find_first_of("\n\r");
if (EOL == StringRef::npos) EOL = Buffer.size();
// Ignore trailing whitespace.
while (EOL && (Buffer[EOL-1] == ' ' || Buffer[EOL-1] == '\t'))
--EOL;
// Check that there is something on the line.
if (EOL == 0) {
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
"found empty check string with prefix '"+CheckPrefix+":'",
"error");
return true;
}
StringRef PatternStr = Buffer.substr(0, EOL);
// Handle CHECK-NOT.
if (IsCheckNot) {
NotMatches.push_back(std::make_pair(SMLoc::getFromPointer(Buffer.data()),
PatternStr.str()));
Buffer = Buffer.substr(EOL);
continue;
}
// Verify that CHECK-NEXT lines have at least one CHECK line before them.
if (IsCheckNext && CheckStrings.empty()) {
SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
"found '"+CheckPrefix+"-NEXT:' without previous '"+
CheckPrefix+ ": line", "error");
return true;
}
// Okay, add the string we captured to the output vector and move on.
CheckStrings.push_back(CheckString(PatternStr.str(),
SMLoc::getFromPointer(Buffer.data()),
IsCheckNext));
std::swap(NotMatches, CheckStrings.back().NotStrings);
Buffer = Buffer.substr(EOL);
}
if (CheckStrings.empty()) {
errs() << "error: no check strings found with prefix '" << CheckPrefix
<< ":'\n";
return true;
}
if (!NotMatches.empty()) {
errs() << "error: '" << CheckPrefix
<< "-NOT:' not supported after last check line.\n";
return true;
}
return false;
}
// CanonicalizeCheckStrings - Replace all sequences of horizontal whitespace in
// the check strings with a single space.
static void CanonicalizeCheckStrings(std::vector<CheckString> &CheckStrings) {
for (unsigned i = 0, e = CheckStrings.size(); i != e; ++i) {
std::string &Str = CheckStrings[i].Str;
for (unsigned C = 0; C != Str.size(); ++C) {
// If C is not a horizontal whitespace, skip it.
if (Str[C] != ' ' && Str[C] != '\t')
continue;
// Replace the character with space, then remove any other space
// characters after it.
Str[C] = ' ';
while (C+1 != Str.size() &&
(Str[C+1] == ' ' || Str[C+1] == '\t'))
Str.erase(Str.begin()+C+1);
}
}
}
/// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
/// memory buffer, free it, and return a new one.
static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
SmallVector<char, 16> NewFile;
NewFile.reserve(MB->getBufferSize());
for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
Ptr != End; ++Ptr) {
// If C is not a horizontal whitespace, skip it.
if (*Ptr != ' ' && *Ptr != '\t') {
NewFile.push_back(*Ptr);
continue;
}
// Otherwise, add one space and advance over neighboring space.
NewFile.push_back(' ');
while (Ptr+1 != End &&
(Ptr[1] == ' ' || Ptr[1] == '\t'))
++Ptr;
}
// Free the old buffer and return a new one.
MemoryBuffer *MB2 =
MemoryBuffer::getMemBufferCopy(NewFile.data(),
NewFile.data() + NewFile.size(),
MB->getBufferIdentifier());
delete MB;
return MB2;
}
static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
StringRef Buffer) {
// Otherwise, we have an error, emit an error message.
SM.PrintMessage(CheckStr.Loc, "expected string not found in input",
"error");
// Print the "scanning from here" line. If the current position is at the
// end of a line, advance to the start of the next line.
Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), "scanning from here",
"note");
}
/// CountNumNewlinesBetween - Count the number of newlines in the specified
/// range.
static unsigned CountNumNewlinesBetween(StringRef Range) {
unsigned NumNewLines = 0;
while (1) {
// Scan for newline.
Range = Range.substr(Range.find_first_of("\n\r"));
if (Range.empty()) return NumNewLines;
++NumNewLines;
// Handle \n\r and \r\n as a single newline.
if (Range.size() > 1 &&
(Range[1] == '\n' || Range[1] == '\r') &&
(Range[0] != Range[1]))
Range = Range.substr(1);
Range = Range.substr(1);
}
}
int main(int argc, char **argv) {
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
cl::ParseCommandLineOptions(argc, argv);
SourceMgr SM;
// Read the expected strings from the check file.
std::vector<CheckString> CheckStrings;
if (ReadCheckFile(SM, CheckStrings))
return 2;
// Remove duplicate spaces in the check strings if requested.
if (!NoCanonicalizeWhiteSpace)
CanonicalizeCheckStrings(CheckStrings);
// Open the file to check and add it to SourceMgr.
std::string ErrorStr;
MemoryBuffer *F =
MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr);
if (F == 0) {
errs() << "Could not open input file '" << InputFilename << "': "
<< ErrorStr << '\n';
return true;
}
// Remove duplicate spaces in the input file if requested.
if (!NoCanonicalizeWhiteSpace)
F = CanonicalizeInputFile(F);
SM.AddNewSourceBuffer(F, SMLoc());
// Check that we have all of the expected strings, in order, in the input
// file.
StringRef Buffer = F->getBuffer();
const char *LastMatch = Buffer.data();
for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
const CheckString &CheckStr = CheckStrings[StrNo];
StringRef SearchFrom = Buffer;
// Find StrNo in the file.
Buffer = Buffer.substr(Buffer.find(CheckStr.Str));
// If we didn't find a match, reject the input.
if (Buffer.empty()) {
PrintCheckFailed(SM, CheckStr, SearchFrom);
return 1;
}
StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch);
// If this check is a "CHECK-NEXT", verify that the previous match was on
// the previous line (i.e. that there is one newline between them).
if (CheckStr.IsCheckNext) {
// Count the number of newlines between the previous match and this one.
assert(LastMatch != F->getBufferStart() &&
"CHECK-NEXT can't be the first check in a file");
unsigned NumNewLines = CountNumNewlinesBetween(SkippedRegion);
if (NumNewLines == 0) {
SM.PrintMessage(CheckStr.Loc,
CheckPrefix+"-NEXT: is on the same line as previous match",
"error");
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
"'next' match was here", "note");
SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
"previous match was here", "note");
return 1;
}
if (NumNewLines != 1) {
SM.PrintMessage(CheckStr.Loc,
CheckPrefix+
"-NEXT: is not on the line after the previous match",
"error");
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
"'next' match was here", "note");
SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
"previous match was here", "note");
return 1;
}
}
// If this match had "not strings", verify that they don't exist in the
// skipped region.
for (unsigned i = 0, e = CheckStr.NotStrings.size(); i != e; ++i) {
size_t Pos = SkippedRegion.find(CheckStr.NotStrings[i].second);
if (Pos == StringRef::npos) continue;
SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos),
CheckPrefix+"-NOT: string occurred!", "error");
SM.PrintMessage(CheckStr.NotStrings[i].first,
CheckPrefix+"-NOT: pattern specified here", "note");
return 1;
}
// Otherwise, everything is good. Step over the matched text and remember
// the position after the match as the end of the last match.
Buffer = Buffer.substr(CheckStr.Str.size());
LastMatch = Buffer.data();
}
return 0;
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_OPENCL_IS_MATRIX_CL_HPP
#define STAN_MATH_OPENCL_IS_MATRIX_CL_HPP
#ifdef STAN_OPENCL
#include <stan/math/prim/meta.hpp>
#include <type_traits>
namespace stan {
namespace math {
/**
* Dummy class to instantiate matrix_cl to enable for specific types.
* @ingroup matrix_cl_group
*/
template <typename T, typename = void>
class matrix_cl {
public:
using Scalar = T;
using type = T;
};
} // namespace math
namespace internal {
/** \ingroup type_traits
* @internal
* This underlying implementation is used when the type is not an std vector.
*/
template <typename T>
struct is_matrix_cl_impl : std::false_type {};
/** \ingroup type_traits
* @internal
* This specialization implementation has a static member named value when the
* template type is an std vector.
*/
template <typename... Args>
struct is_matrix_cl_impl<stan::math::matrix_cl<Args...>> : std::true_type {};
} // namespace internal
template <typename T, typename = void>
struct is_matrix_cl : std::false_type {};
/** \ingroup type_traits
* Checks if the decayed type of T is a matrix_cl.
*/
template <typename T>
struct is_matrix_cl<
T, std::enable_if_t<internal::is_matrix_cl_impl<std::decay_t<T>>::value>>
: std::true_type {};
STAN_ADD_REQUIRE_UNARY(matrix_cl, is_matrix_cl, matrix_cl_group);
STAN_ADD_REQUIRE_CONTAINER(matrix_cl, is_matrix_cl, matrix_cl_group);
} // namespace stan
#endif
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0<commit_after>#ifndef STAN_MATH_OPENCL_IS_MATRIX_CL_HPP
#define STAN_MATH_OPENCL_IS_MATRIX_CL_HPP
#ifdef STAN_OPENCL
#include <stan/math/prim/meta.hpp>
#include <type_traits>
namespace stan {
namespace math {
/**
* Dummy class to instantiate matrix_cl to enable for specific types.
* @ingroup matrix_cl_group
*/
template <typename T, typename = void>
class matrix_cl {
public:
using Scalar = T;
using type = T;
};
} // namespace math
namespace internal {
/** \ingroup type_traits
* @internal
* This underlying implementation is used when the type is not an std vector.
*/
template <typename T>
struct is_matrix_cl_impl : std::false_type {};
/** \ingroup type_traits
* @internal
* This specialization implementation has a static member named value when the
* template type is an std vector.
*/
template <typename... Args>
struct is_matrix_cl_impl<stan::math::matrix_cl<Args...>> : std::true_type {};
} // namespace internal
template <typename T, typename = void>
struct is_matrix_cl : std::false_type {};
/** \ingroup type_traits
* Checks if the decayed type of T is a matrix_cl.
*/
template <typename T>
struct is_matrix_cl<
T, std::enable_if_t<internal::is_matrix_cl_impl<std::decay_t<T>>::value>>
: std::true_type {};
STAN_ADD_REQUIRE_UNARY(matrix_cl, is_matrix_cl, matrix_cl_group);
STAN_ADD_REQUIRE_CONTAINER(matrix_cl, is_matrix_cl, matrix_cl_group);
} // namespace stan
#endif
#endif
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_OPENCL_REV_MULTIPLY_HPP
#define STAN_MATH_OPENCL_REV_MULTIPLY_HPP
#ifdef STAN_OPENCL
#include <stan/math/prim/meta/is_kernel_expression.hpp>
#include <stan/math/opencl/prim/multiply.hpp>
#include <stan/math/opencl/matrix_cl.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/fun/value_of.hpp>
#include <stan/math/rev/core/reverse_pass_callback.hpp>
#include <stan/math/prim/fun/value_of.hpp>
namespace stan {
namespace math {
/**
* Matrix multiplication of two reverse mode matrices and/or kernel generator
* expressions.
* @tparam T_a type of first expression
* @tparam T_b type of second expression
* @param a first expression
* @param b second expression
* @return Matrix product of given arguments
*/
template <
typename T_a, typename T_b,
require_all_nonscalar_prim_or_rev_kernel_expression_t<T_a, T_b>* = nullptr,
require_any_var_t<T_a, T_b>* = nullptr>
inline auto multiply(const T_a& a, const T_b& b) {
check_size_match("multiply ((OpenCL))", "A.cols()", a.cols(), "B.rows()",
b.rows());
const arena_t<T_a>& a_arena = a;
const arena_t<T_b>& b_arena = b;
var_value<matrix_cl<double>> res = value_of(a_arena) * value_of(b_arena);
reverse_pass_callback([a_arena, b_arena, res]() mutable {
if (!is_constant<T_a>::value) {
auto& a_adj = forward_as<var_value<matrix_cl<double>>>(a_arena).adj();
a_adj = a_adj + res.adj() * transpose(value_of(b_arena));
}
if (!is_constant<T_b>::value) {
auto& b_adj = forward_as<var_value<matrix_cl<double>>>(b_arena).adj();
b_adj = b_adj + transpose(value_of(a_arena)) * res.adj();
}
});
return res;
}
/**
* Matrix multiplication of two reverse mode matrices and/or kernel generator
* expressions.
* @tparam T_a type of first expression
* @tparam T_b type of second expression
* @param a first expression
* @param b second expression
* @return Matrix product of given arguments
*/
template <
typename T_a, typename T_b,
require_all_nonscalar_prim_or_rev_kernel_expression_t<T_a, T_b>* = nullptr,
require_any_var_t<T_a, T_b>* = nullptr>
inline auto operator*(const T_a& a, const T_b& b) {
return multiply(a, b);
}
/**
* Return matrix multiplied by a scalar.
*
* @tparam T1 type of the scalar
* @tparam T2 type of the matrix or expression
*
* @param a scalar
* @param b matrix
* @return product of matrix and scalar
*/
template <typename T1, typename T2, require_stan_scalar_t<T1>* = nullptr,
require_all_nonscalar_prim_or_rev_kernel_expression_t<T2>* = nullptr,
require_any_var_t<T1, T2>* = nullptr>
inline auto multiply(const T1& a, const T2& b) {
const arena_t<T1>& a_arena = a;
const arena_t<T2>& b_arena = b;
var_value<matrix_cl<double>> res = value_of(a_arena) * value_of(b_arena);
reverse_pass_callback([a_arena, b_arena, res]() mutable {
if (!is_constant<T1>::value) {
auto& a_adj = forward_as<var_value<double>>(a_arena).adj();
a_adj = a_adj + sum(elt_multiply(res.adj(), value_of(b_arena)));
}
if (!is_constant<T2>::value) {
auto& b_adj = forward_as<var_value<matrix_cl<double>>>(b_arena).adj();
b_adj = b_adj + value_of(a_arena) * res.adj();
}
});
return res;
}
/**
* Return matrix multiplied by a scalar.
*
* @tparam T1 type of the matrix or expression
* @tparam T2 type of the scalar
*
* @param a matrix
* @param b scalar
* @return product of matrix and scalar
*/
template <typename T1, typename T2, require_stan_scalar_t<T2>* = nullptr,
require_all_nonscalar_prim_or_rev_kernel_expression_t<T1>* = nullptr,
require_any_var_t<T1, T2>* = nullptr>
inline auto multiply(const T1& A, const T2& B) {
return multiply(B, A);
}
} // namespace math
} // namespace stan
#endif
#endif
<commit_msg>fix capitalization<commit_after>#ifndef STAN_MATH_OPENCL_REV_MULTIPLY_HPP
#define STAN_MATH_OPENCL_REV_MULTIPLY_HPP
#ifdef STAN_OPENCL
#include <stan/math/prim/meta/is_kernel_expression.hpp>
#include <stan/math/opencl/prim/multiply.hpp>
#include <stan/math/opencl/matrix_cl.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/fun/value_of.hpp>
#include <stan/math/rev/core/reverse_pass_callback.hpp>
#include <stan/math/prim/fun/value_of.hpp>
namespace stan {
namespace math {
/**
* Matrix multiplication of two reverse mode matrices and/or kernel generator
* expressions.
* @tparam T_a type of first expression
* @tparam T_b type of second expression
* @param a first expression
* @param b second expression
* @return Matrix product of given arguments
*/
template <
typename T_a, typename T_b,
require_all_nonscalar_prim_or_rev_kernel_expression_t<T_a, T_b>* = nullptr,
require_any_var_t<T_a, T_b>* = nullptr>
inline auto multiply(const T_a& a, const T_b& b) {
check_size_match("multiply ((OpenCL))", "A.cols()", a.cols(), "B.rows()",
b.rows());
const arena_t<T_a>& a_arena = a;
const arena_t<T_b>& b_arena = b;
var_value<matrix_cl<double>> res = value_of(a_arena) * value_of(b_arena);
reverse_pass_callback([a_arena, b_arena, res]() mutable {
if (!is_constant<T_a>::value) {
auto& a_adj = forward_as<var_value<matrix_cl<double>>>(a_arena).adj();
a_adj = a_adj + res.adj() * transpose(value_of(b_arena));
}
if (!is_constant<T_b>::value) {
auto& b_adj = forward_as<var_value<matrix_cl<double>>>(b_arena).adj();
b_adj = b_adj + transpose(value_of(a_arena)) * res.adj();
}
});
return res;
}
/**
* Matrix multiplication of two reverse mode matrices and/or kernel generator
* expressions.
* @tparam T_a type of first expression
* @tparam T_b type of second expression
* @param a first expression
* @param b second expression
* @return Matrix product of given arguments
*/
template <
typename T_a, typename T_b,
require_all_nonscalar_prim_or_rev_kernel_expression_t<T_a, T_b>* = nullptr,
require_any_var_t<T_a, T_b>* = nullptr>
inline auto operator*(const T_a& a, const T_b& b) {
return multiply(a, b);
}
/**
* Return matrix multiplied by a scalar.
*
* @tparam T1 type of the scalar
* @tparam T2 type of the matrix or expression
*
* @param a scalar
* @param b matrix
* @return product of matrix and scalar
*/
template <typename T1, typename T2, require_stan_scalar_t<T1>* = nullptr,
require_all_nonscalar_prim_or_rev_kernel_expression_t<T2>* = nullptr,
require_any_var_t<T1, T2>* = nullptr>
inline auto multiply(const T1& a, const T2& b) {
const arena_t<T1>& a_arena = a;
const arena_t<T2>& b_arena = b;
var_value<matrix_cl<double>> res = value_of(a_arena) * value_of(b_arena);
reverse_pass_callback([a_arena, b_arena, res]() mutable {
if (!is_constant<T1>::value) {
auto& a_adj = forward_as<var_value<double>>(a_arena).adj();
a_adj = a_adj + sum(elt_multiply(res.adj(), value_of(b_arena)));
}
if (!is_constant<T2>::value) {
auto& b_adj = forward_as<var_value<matrix_cl<double>>>(b_arena).adj();
b_adj = b_adj + value_of(a_arena) * res.adj();
}
});
return res;
}
/**
* Return matrix multiplied by a scalar.
*
* @tparam T1 type of the matrix or expression
* @tparam T2 type of the scalar
*
* @param a matrix
* @param b scalar
* @return product of matrix and scalar
*/
template <typename T1, typename T2, require_stan_scalar_t<T2>* = nullptr,
require_all_nonscalar_prim_or_rev_kernel_expression_t<T1>* = nullptr,
require_any_var_t<T1, T2>* = nullptr>
inline auto multiply(const T1& a, const T2& b) {
return multiply(b, a);
}
} // namespace math
} // namespace stan
#endif
#endif
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_REV_FUN_LOG_SUM_EXP_HPP
#define STAN_MATH_REV_FUN_LOG_SUM_EXP_HPP
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/fun/typedefs.hpp>
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/inv_logit.hpp>
#include <stan/math/prim/fun/log_sum_exp.hpp>
#include <cmath>
#include <vector>
namespace stan {
namespace math {
namespace internal {
class log_sum_exp_vv_vari : public op_vv_vari {
public:
log_sum_exp_vv_vari(vari* avi, vari* bvi)
: op_vv_vari(log_sum_exp(avi->val_, bvi->val_), avi, bvi) {}
void chain() {
avi_->adj_ += adj_ * inv_logit(avi_->val_ - bvi_->val_);
bvi_->adj_ += adj_ * inv_logit(bvi_->val_ - avi_->val_);
}
};
class log_sum_exp_vd_vari : public op_vd_vari {
public:
log_sum_exp_vd_vari(vari* avi, double b)
: op_vd_vari(log_sum_exp(avi->val_, b), avi, b) {}
void chain() {
if (val_ == NEGATIVE_INFTY) {
avi_->adj_ += adj_;
} else {
avi_->adj_ += adj_ * inv_logit(avi_->val_ - bd_);
}
}
};
} // namespace internal
/**
* Returns the log sum of exponentials.
*/
inline var log_sum_exp(const var& a, const var& b) {
return var(new internal::log_sum_exp_vv_vari(a.vi_, b.vi_));
}
/**
* Returns the log sum of exponentials.
*/
inline var log_sum_exp(const var& a, double b) {
return var(new internal::log_sum_exp_vd_vari(a.vi_, b));
}
/**
* Returns the log sum of exponentials.
*/
inline var log_sum_exp(double a, const var& b) {
return var(new internal::log_sum_exp_vd_vari(b.vi_, a));
}
/**
* Returns the log sum of exponentials.
*
* @tparam T Type of input vector or matrix.
* @param x matrix
*/
template <typename T, require_container_st<is_var, T>* = nullptr>
inline auto log_sum_exp(const T& x) {
return apply_vector_unary<T>::reduce(x, [](const auto& v) {
arena_t<decltype(v)> arena_v = v;
var res = log_sum_exp(arena_v.val());
reverse_pass_callback([arena_v, res]() mutable {
arena_v.adj()
+= res.adj() * (arena_v.array().val() - res.val()).exp().matrix();
});
return res;
});
}
} // namespace math
} // namespace stan
#endif
<commit_msg>pull out values for log_sum_exp<commit_after>#ifndef STAN_MATH_REV_FUN_LOG_SUM_EXP_HPP
#define STAN_MATH_REV_FUN_LOG_SUM_EXP_HPP
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/fun/typedefs.hpp>
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/inv_logit.hpp>
#include <stan/math/prim/fun/log_sum_exp.hpp>
#include <cmath>
#include <vector>
namespace stan {
namespace math {
namespace internal {
class log_sum_exp_vv_vari : public op_vv_vari {
public:
log_sum_exp_vv_vari(vari* avi, vari* bvi)
: op_vv_vari(log_sum_exp(avi->val_, bvi->val_), avi, bvi) {}
void chain() {
avi_->adj_ += adj_ * inv_logit(avi_->val_ - bvi_->val_);
bvi_->adj_ += adj_ * inv_logit(bvi_->val_ - avi_->val_);
}
};
class log_sum_exp_vd_vari : public op_vd_vari {
public:
log_sum_exp_vd_vari(vari* avi, double b)
: op_vd_vari(log_sum_exp(avi->val_, b), avi, b) {}
void chain() {
if (val_ == NEGATIVE_INFTY) {
avi_->adj_ += adj_;
} else {
avi_->adj_ += adj_ * inv_logit(avi_->val_ - bd_);
}
}
};
} // namespace internal
/**
* Returns the log sum of exponentials.
*/
inline var log_sum_exp(const var& a, const var& b) {
return var(new internal::log_sum_exp_vv_vari(a.vi_, b.vi_));
}
/**
* Returns the log sum of exponentials.
*/
inline var log_sum_exp(const var& a, double b) {
return var(new internal::log_sum_exp_vd_vari(a.vi_, b));
}
/**
* Returns the log sum of exponentials.
*/
inline var log_sum_exp(double a, const var& b) {
return var(new internal::log_sum_exp_vd_vari(b.vi_, a));
}
/**
* Returns the log sum of exponentials.
*
* @tparam T Type of input vector or matrix.
* @param x matrix
*/
template <typename T, require_container_st<is_var, T>* = nullptr>
inline auto log_sum_exp(const T& x) {
return apply_vector_unary<T>::reduce(x, [](const auto& v) {
arena_t<decltype(v)> arena_v = v;
arena_t<decltype(v.val())> arena_v_val = v.val();
var res = log_sum_exp(arena_v_val);
reverse_pass_callback([arena_v, arena_v_val, res]() mutable {
arena_v.adj()
+= res.adj() * (arena_v_val.array().val() - res.val()).exp().matrix();
});
return res;
});
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
#include <sstream>
// StdAir
#include <stdair/stdair_types.hpp>
#include <stdair/basic/BasChronometer.hpp>
#include <stdair/bom/BomManager.hpp>
#include <stdair/bom/BomDisplay.hpp>
#include <stdair/bom/BomRoot.hpp>
#include <stdair/bom/EventQueue.hpp>
#include <stdair/bom/EventStruct.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/command/CmdBomManager.hpp>
#include <stdair/service/FacSupervisor.hpp>
#include <stdair/service/FacSTDAIRServiceContext.hpp>
#include <stdair/service/STDAIR_ServiceContext.hpp>
#include <stdair/service/Logger.hpp>
#include <stdair/service/DBSessionManager.hpp>
#include <stdair/STDAIR_Service.hpp>
namespace stdair {
// //////////////////////////////////////////////////////////////////////
STDAIR_Service::STDAIR_Service() : _stdairServiceContext (NULL) {
// Initialise the service context
initServiceContext();
// Initialise the (remaining of the) context
init();
}
// //////////////////////////////////////////////////////////////////////
STDAIR_Service::STDAIR_Service (const STDAIR_Service& iService)
: _stdairServiceContext (NULL) {
assert (false);
}
// //////////////////////////////////////////////////////////////////////
STDAIR_Service::STDAIR_Service (const BasLogParams& iLogParams)
: _stdairServiceContext (NULL) {
// Initialise the service context
initServiceContext();
// Set the log file
logInit (iLogParams);
// Initialise the (remaining of the) context
init();
}
// //////////////////////////////////////////////////////////////////////
STDAIR_Service::STDAIR_Service (const BasLogParams& iLogParams,
const BasDBParams& iDBParams)
: _stdairServiceContext (NULL) {
// Initialise the service context
initServiceContext();
// Set the log file
logInit (iLogParams);
// Create a database session
dbInit (iDBParams);
// Initialise the (remaining of the) context
init();
}
// //////////////////////////////////////////////////////////////////////
STDAIR_Service::~STDAIR_Service() {
// Delete/Clean all the objects from memory
finalise();
}
// //////////////////////////////////////////////////////////////////////
void STDAIR_Service::initServiceContext() {
// Initialise the service context
STDAIR_ServiceContext& lSTDAIR_ServiceContext =
FacSTDAIRServiceContext::instance().create();
// Store the stdair service context
_stdairServiceContext = &lSTDAIR_ServiceContext;
}
// //////////////////////////////////////////////////////////////////////
void STDAIR_Service::logInit (const BasLogParams& iLogParams) {
Logger::init (iLogParams);
}
// //////////////////////////////////////////////////////////////////////
void STDAIR_Service::dbInit (const BasDBParams& iDBParams) {
DBSessionManager::init (iDBParams);
// Store the database parameters into the StdAir service context
assert (_stdairServiceContext != NULL);
STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
lSTDAIR_ServiceContext.setDBParams (iDBParams);
}
// //////////////////////////////////////////////////////////////////////
void STDAIR_Service::init() {
}
// //////////////////////////////////////////////////////////////////////
BomRoot& STDAIR_Service::getBomRoot() const {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
const STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
return lSTDAIR_ServiceContext.getBomRoot();
}
// //////////////////////////////////////////////////////////////////////
EventQueue& STDAIR_Service::getEventQueue() const {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
const STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
return lSTDAIR_ServiceContext.getEventQueue();
}
// //////////////////////////////////////////////////////////////////////
BasLogParams STDAIR_Service::getLogParams() const {
return Logger::getLogParams();
}
// //////////////////////////////////////////////////////////////////////
const BasDBParams& STDAIR_Service::getDBParams() const {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
const STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
return lSTDAIR_ServiceContext.getDBParams();
}
// //////////////////////////////////////////////////////////////////////
void STDAIR_Service::buildSampleBom (const bool isForRMOL,
const CabinCapacity_T iCabinCapacity ) {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
const STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
// Retrieve the BOM tree root
BomRoot& lBomRoot = lSTDAIR_ServiceContext.getBomRoot();
// Build a sample BOM tree
if (isForRMOL == true) {
CmdBomManager::buildSampleBomForRMOL (lBomRoot, iCabinCapacity);
} else {
CmdBomManager::buildSampleBom (lBomRoot);
}
}
// //////////////////////////////////////////////////////////////////////
void STDAIR_Service::buildSampleBomForFareQuoter () {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
const STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
// Retrieve the BOM tree root
BomRoot& lBomRoot = lSTDAIR_ServiceContext.getBomRoot();
// Build a sample BOM tree
CmdBomManager::buildSampleBomForFareQuoter (lBomRoot);
}
// //////////////////////////////////////////////////////////////////////
void STDAIR_Service::
buildSampleTravelSolutionForPricing (TravelSolutionList_T& ioTravelSolutionList) {
// Build a sample list of travel solution structures
CmdBomManager::buildSampleTravelSolutionForPricing (ioTravelSolutionList);
}
// //////////////////////////////////////////////////////////////////////
void STDAIR_Service::
buildSampleTravelSolutions (TravelSolutionList_T& ioTravelSolutionList) {
// Build a sample list of travel solution structures
CmdBomManager::buildSampleTravelSolutions (ioTravelSolutionList);
}
// //////////////////////////////////////////////////////////////////////
BookingRequestStruct STDAIR_Service::
buildSampleBookingRequest (const bool isForCRS) {
// Build a sample booking request structure
if (isForCRS == true) {
return CmdBomManager::buildSampleBookingRequestForCRS();
}
return CmdBomManager::buildSampleBookingRequest();
}
// //////////////////////////////////////////////////////////////////////
std::string STDAIR_Service::csvDisplay() const {
std::ostringstream oStr;
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
const STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
// Retrieve the BOM tree root
BomRoot& lBomRoot = lSTDAIR_ServiceContext.getBomRoot();
// Dump the content of the whole BOM tree into the string
BomDisplay::csvDisplay (oStr, lBomRoot);
return oStr.str();
}
// //////////////////////////////////////////////////////////////////////
std::string STDAIR_Service::
csvDisplay (const TravelSolutionList_T& iTravelSolutionList) const {
std::ostringstream oStr;
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
const STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
// Dump the content of the whole list of travel solutions into the string
BomDisplay::csvDisplay (oStr, iTravelSolutionList);
return oStr.str();
}
// //////////////////////////////////////////////////////////////////////
void STDAIR_Service::finalise() {
// Clean all the objects
FacSupervisor::cleanAll();
}
// ////////////////////////////////////////////////////////////////////
const Count_T& STDAIR_Service::
getExpectedTotalNumberOfEventsToBeGenerated() const {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
// Retrieve the event queue object instance
const EventQueue& lQueue = lSTDAIR_ServiceContext.getEventQueue();
// Delegate the call to the dedicated command
const Count_T& oExpectedTotalNumberOfEventsToBeGenerated =
lQueue.getExpectedTotalNbOfEvents();
//
return oExpectedTotalNumberOfEventsToBeGenerated;
}
// ////////////////////////////////////////////////////////////////////
const Count_T& STDAIR_Service::
getExpectedTotalNumberOfEventsToBeGenerated (const EventType::EN_EventType& iType) const {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
// Retrieve the event queue object instance
const EventQueue& lQueue = lSTDAIR_ServiceContext.getEventQueue();
// Delegate the call to the dedicated command
const Count_T& oExpectedTotalNumberOfEventsToBeGenerated =
lQueue.getExpectedTotalNbOfEvents (iType);
//
return oExpectedTotalNumberOfEventsToBeGenerated;
}
// ////////////////////////////////////////////////////////////////////
const Count_T& STDAIR_Service::
getActualTotalNumberOfEventsToBeGenerated() const {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
// Retrieve the event queue object instance
const EventQueue& lQueue = lSTDAIR_ServiceContext.getEventQueue();
// Delegate the call to the dedicated command
const Count_T& oActualTotalNumberOfEventsToBeGenerated =
lQueue.getActualTotalNbOfEvents();
//
return oActualTotalNumberOfEventsToBeGenerated;
}
// ////////////////////////////////////////////////////////////////////
const Count_T& STDAIR_Service::
getActualTotalNumberOfEventsToBeGenerated (const EventType::EN_EventType& iType) const {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
// Retrieve the event queue object instance
const EventQueue& lQueue = lSTDAIR_ServiceContext.getEventQueue();
// Delegate the call to the dedicated command
const Count_T& oActualTotalNumberOfEventsToBeGenerated =
lQueue.getActualTotalNbOfEvents (iType);
//
return oActualTotalNumberOfEventsToBeGenerated;
}
// ////////////////////////////////////////////////////////////////////
EventStruct STDAIR_Service::popEvent() const {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
// Retrieve the event queue object instance
EventQueue& lQueue = lSTDAIR_ServiceContext.getEventQueue();
// Extract the next event from the queue
const EventStruct& oEventStruct = lQueue.popEvent();
//
return oEventStruct;
}
// ////////////////////////////////////////////////////////////////////
bool STDAIR_Service::isQueueDone() const {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
// Retrieve the event queue object instance
const EventQueue& lQueue = lSTDAIR_ServiceContext.getEventQueue();
// Calculates whether the event queue has been fully emptied
const bool isQueueDone = lQueue.isQueueDone();
//
return isQueueDone;
}
// ////////////////////////////////////////////////////////////////////
void STDAIR_Service::reset() const {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
// Retrieve the event queue object instance
EventQueue& lQueue = lSTDAIR_ServiceContext.getEventQueue();
// Delegate the call to the event queue object
lQueue.reset();
}
}
<commit_msg>[Dev] Removed unused (STDAIR_Service) variable.<commit_after>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
#include <sstream>
// StdAir
#include <stdair/stdair_types.hpp>
#include <stdair/basic/BasChronometer.hpp>
#include <stdair/bom/BomManager.hpp>
#include <stdair/bom/BomDisplay.hpp>
#include <stdair/bom/BomRoot.hpp>
#include <stdair/bom/EventQueue.hpp>
#include <stdair/bom/EventStruct.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/command/CmdBomManager.hpp>
#include <stdair/service/FacSupervisor.hpp>
#include <stdair/service/FacSTDAIRServiceContext.hpp>
#include <stdair/service/STDAIR_ServiceContext.hpp>
#include <stdair/service/Logger.hpp>
#include <stdair/service/DBSessionManager.hpp>
#include <stdair/STDAIR_Service.hpp>
namespace stdair {
// //////////////////////////////////////////////////////////////////////
STDAIR_Service::STDAIR_Service() : _stdairServiceContext (NULL) {
// Initialise the service context
initServiceContext();
// Initialise the (remaining of the) context
init();
}
// //////////////////////////////////////////////////////////////////////
STDAIR_Service::STDAIR_Service (const STDAIR_Service& iService)
: _stdairServiceContext (NULL) {
assert (false);
}
// //////////////////////////////////////////////////////////////////////
STDAIR_Service::STDAIR_Service (const BasLogParams& iLogParams)
: _stdairServiceContext (NULL) {
// Initialise the service context
initServiceContext();
// Set the log file
logInit (iLogParams);
// Initialise the (remaining of the) context
init();
}
// //////////////////////////////////////////////////////////////////////
STDAIR_Service::STDAIR_Service (const BasLogParams& iLogParams,
const BasDBParams& iDBParams)
: _stdairServiceContext (NULL) {
// Initialise the service context
initServiceContext();
// Set the log file
logInit (iLogParams);
// Create a database session
dbInit (iDBParams);
// Initialise the (remaining of the) context
init();
}
// //////////////////////////////////////////////////////////////////////
STDAIR_Service::~STDAIR_Service() {
// Delete/Clean all the objects from memory
finalise();
}
// //////////////////////////////////////////////////////////////////////
void STDAIR_Service::initServiceContext() {
// Initialise the service context
STDAIR_ServiceContext& lSTDAIR_ServiceContext =
FacSTDAIRServiceContext::instance().create();
// Store the stdair service context
_stdairServiceContext = &lSTDAIR_ServiceContext;
}
// //////////////////////////////////////////////////////////////////////
void STDAIR_Service::logInit (const BasLogParams& iLogParams) {
Logger::init (iLogParams);
}
// //////////////////////////////////////////////////////////////////////
void STDAIR_Service::dbInit (const BasDBParams& iDBParams) {
DBSessionManager::init (iDBParams);
// Store the database parameters into the StdAir service context
assert (_stdairServiceContext != NULL);
STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
lSTDAIR_ServiceContext.setDBParams (iDBParams);
}
// //////////////////////////////////////////////////////////////////////
void STDAIR_Service::init() {
}
// //////////////////////////////////////////////////////////////////////
BomRoot& STDAIR_Service::getBomRoot() const {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
const STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
return lSTDAIR_ServiceContext.getBomRoot();
}
// //////////////////////////////////////////////////////////////////////
EventQueue& STDAIR_Service::getEventQueue() const {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
const STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
return lSTDAIR_ServiceContext.getEventQueue();
}
// //////////////////////////////////////////////////////////////////////
BasLogParams STDAIR_Service::getLogParams() const {
return Logger::getLogParams();
}
// //////////////////////////////////////////////////////////////////////
const BasDBParams& STDAIR_Service::getDBParams() const {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
const STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
return lSTDAIR_ServiceContext.getDBParams();
}
// //////////////////////////////////////////////////////////////////////
void STDAIR_Service::buildSampleBom (const bool isForRMOL,
const CabinCapacity_T iCabinCapacity ) {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
const STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
// Retrieve the BOM tree root
BomRoot& lBomRoot = lSTDAIR_ServiceContext.getBomRoot();
// Build a sample BOM tree
if (isForRMOL == true) {
CmdBomManager::buildSampleBomForRMOL (lBomRoot, iCabinCapacity);
} else {
CmdBomManager::buildSampleBom (lBomRoot);
}
}
// //////////////////////////////////////////////////////////////////////
void STDAIR_Service::buildSampleBomForFareQuoter () {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
const STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
// Retrieve the BOM tree root
BomRoot& lBomRoot = lSTDAIR_ServiceContext.getBomRoot();
// Build a sample BOM tree
CmdBomManager::buildSampleBomForFareQuoter (lBomRoot);
}
// //////////////////////////////////////////////////////////////////////
void STDAIR_Service::
buildSampleTravelSolutionForPricing (TravelSolutionList_T& ioTravelSolutionList) {
// Build a sample list of travel solution structures
CmdBomManager::buildSampleTravelSolutionForPricing (ioTravelSolutionList);
}
// //////////////////////////////////////////////////////////////////////
void STDAIR_Service::
buildSampleTravelSolutions (TravelSolutionList_T& ioTravelSolutionList) {
// Build a sample list of travel solution structures
CmdBomManager::buildSampleTravelSolutions (ioTravelSolutionList);
}
// //////////////////////////////////////////////////////////////////////
BookingRequestStruct STDAIR_Service::
buildSampleBookingRequest (const bool isForCRS) {
// Build a sample booking request structure
if (isForCRS == true) {
return CmdBomManager::buildSampleBookingRequestForCRS();
}
return CmdBomManager::buildSampleBookingRequest();
}
// //////////////////////////////////////////////////////////////////////
std::string STDAIR_Service::csvDisplay() const {
std::ostringstream oStr;
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
const STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
// Retrieve the BOM tree root
BomRoot& lBomRoot = lSTDAIR_ServiceContext.getBomRoot();
// Dump the content of the whole BOM tree into the string
BomDisplay::csvDisplay (oStr, lBomRoot);
return oStr.str();
}
// //////////////////////////////////////////////////////////////////////
std::string STDAIR_Service::
csvDisplay (const TravelSolutionList_T& iTravelSolutionList) const {
// Dump the content of the whole list of travel solutions into the string
std::ostringstream oStr;
BomDisplay::csvDisplay (oStr, iTravelSolutionList);
return oStr.str();
}
// //////////////////////////////////////////////////////////////////////
void STDAIR_Service::finalise() {
// Clean all the objects
FacSupervisor::cleanAll();
}
// ////////////////////////////////////////////////////////////////////
const Count_T& STDAIR_Service::
getExpectedTotalNumberOfEventsToBeGenerated() const {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
// Retrieve the event queue object instance
const EventQueue& lQueue = lSTDAIR_ServiceContext.getEventQueue();
// Delegate the call to the dedicated command
const Count_T& oExpectedTotalNumberOfEventsToBeGenerated =
lQueue.getExpectedTotalNbOfEvents();
//
return oExpectedTotalNumberOfEventsToBeGenerated;
}
// ////////////////////////////////////////////////////////////////////
const Count_T& STDAIR_Service::
getExpectedTotalNumberOfEventsToBeGenerated (const EventType::EN_EventType& iType) const {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
// Retrieve the event queue object instance
const EventQueue& lQueue = lSTDAIR_ServiceContext.getEventQueue();
// Delegate the call to the dedicated command
const Count_T& oExpectedTotalNumberOfEventsToBeGenerated =
lQueue.getExpectedTotalNbOfEvents (iType);
//
return oExpectedTotalNumberOfEventsToBeGenerated;
}
// ////////////////////////////////////////////////////////////////////
const Count_T& STDAIR_Service::
getActualTotalNumberOfEventsToBeGenerated() const {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
// Retrieve the event queue object instance
const EventQueue& lQueue = lSTDAIR_ServiceContext.getEventQueue();
// Delegate the call to the dedicated command
const Count_T& oActualTotalNumberOfEventsToBeGenerated =
lQueue.getActualTotalNbOfEvents();
//
return oActualTotalNumberOfEventsToBeGenerated;
}
// ////////////////////////////////////////////////////////////////////
const Count_T& STDAIR_Service::
getActualTotalNumberOfEventsToBeGenerated (const EventType::EN_EventType& iType) const {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
// Retrieve the event queue object instance
const EventQueue& lQueue = lSTDAIR_ServiceContext.getEventQueue();
// Delegate the call to the dedicated command
const Count_T& oActualTotalNumberOfEventsToBeGenerated =
lQueue.getActualTotalNbOfEvents (iType);
//
return oActualTotalNumberOfEventsToBeGenerated;
}
// ////////////////////////////////////////////////////////////////////
EventStruct STDAIR_Service::popEvent() const {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
// Retrieve the event queue object instance
EventQueue& lQueue = lSTDAIR_ServiceContext.getEventQueue();
// Extract the next event from the queue
const EventStruct& oEventStruct = lQueue.popEvent();
//
return oEventStruct;
}
// ////////////////////////////////////////////////////////////////////
bool STDAIR_Service::isQueueDone() const {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
// Retrieve the event queue object instance
const EventQueue& lQueue = lSTDAIR_ServiceContext.getEventQueue();
// Calculates whether the event queue has been fully emptied
const bool isQueueDone = lQueue.isQueueDone();
//
return isQueueDone;
}
// ////////////////////////////////////////////////////////////////////
void STDAIR_Service::reset() const {
// Retrieve the StdAir service context
assert (_stdairServiceContext != NULL);
STDAIR_ServiceContext& lSTDAIR_ServiceContext = *_stdairServiceContext;
// Retrieve the event queue object instance
EventQueue& lQueue = lSTDAIR_ServiceContext.getEventQueue();
// Delegate the call to the event queue object
lQueue.reset();
}
}
<|endoftext|> |
<commit_before>#include <CppUTest/TestHarness.h>
#include <CppUTestExt/MockSupport.h>
#include "../can_datagram.h"
#include "../config.h"
#include "mocks/can_interface_mock.h"
#include "../can_interface.h"
#include "../command.h"
#include <cstdio>
void read_eval(can_datagram_t *input, can_datagram_t *output, bootloader_config_t *config, command_t *commands, int command_len)
{
uint32_t message_id;
uint8_t message[8];
int len, i;
len = can_interface_read_message(&message_id, message);
for (i = 0; i < len; ++i) {
can_datagram_input_byte(input, message[i]);
}
if (can_datagram_is_valid(input)) {
for (i = 0; i < input->destination_nodes_len; ++i) {
if (input->destination_nodes[i] == config->ID){
len = protocol_execute_command((char *)input->data, input->data_len, commands, command_len, (char *)output->data, output->data_len, config);
/* Checks if there was any error. */
if (len < 0) {
return;
}
output->data_len = len;
}
}
if (output->data_len > 0) {
output->destination_nodes_len = 1;
output->crc = can_datagram_compute_crc(output);
}
}
}
static void mock_command(int argc, cmp_ctx_t *arg_context, cmp_ctx_t *out_context, bootloader_config_t *config)
{
mock().actualCall("command");
}
TEST_GROUP(IntegrationTesting)
{
can_datagram_t input_datagram;
uint8_t input_datagram_destinations[10];
uint8_t input_datagram_data[1000];
can_datagram_t output_datagram;
uint8_t output_datagram_destinations[10];
uint8_t output_datagram_data[1000];
bootloader_config_t config;
command_t commands[1];
void setup(void)
{
can_datagram_init(&input_datagram);
can_datagram_set_address_buffer(&input_datagram, input_datagram_destinations);
can_datagram_set_data_buffer(&input_datagram, input_datagram_data, sizeof input_datagram_data);
can_datagram_init(&output_datagram);
can_datagram_set_address_buffer(&output_datagram, output_datagram_destinations);
can_datagram_set_data_buffer(&output_datagram, output_datagram_data, sizeof output_datagram_data);
// Loads default config for testing
config.ID = 0x01;
commands[0].index = 1;
commands[0].callback = mock_command;
}
void teardown(void)
{
mock().clear();
}
};
TEST(IntegrationTesting, CanReadWholeDatagram)
{
uint8_t message[] = {
0x01,
0x9e, 0x5b, 0x06, 0xb8,// CRC
0x01,
0x01, // dest nodes
0x0, 0x0, 0x0, 0x1,
0x1 // data
};
can_mock_message(0x0, &message[0], 8);
read_eval(&input_datagram, &output_datagram, &config, NULL, 0);
mock().checkExpectations();
can_mock_message(0x0, &message[8], 4);
read_eval(&input_datagram, &output_datagram, &config, NULL, 0);
mock().checkExpectations();
CHECK_TRUE(can_datagram_is_valid(&input_datagram));
}
TEST(IntegrationTesting, ExecutesCommand)
{
uint8_t message[] = {
0x01, // protocol version
0x62, 0x67, 0x01, 0xfa,
0x01,
0x01, // dest nodes
0x0, 0x0, 0x0, 0x2,
0x1, 0x1 // data
};
can_mock_message(0x0, &message[0], 8);
read_eval(&input_datagram, &output_datagram, &config, commands, 1);
mock().checkExpectations();
can_mock_message(0x0, &message[8], 5);
mock().expectOneCall("command");
read_eval(&input_datagram, &output_datagram, &config, commands, 1);
mock().checkExpectations();
}
TEST(IntegrationTesting, ExecutesIfWeAreInMultiCast)
{
uint8_t message[] = {
0x01, // protocol version
0x99, 0x8c, 0x64, 0xe8,
0x02,
0x01, 0x12, // dest nodes
0x0, 0x0, 0x0, 0x2,
0x1, 0x1 // data
};
config.ID = 0x12;
can_mock_message(0x0, &message[0], 8);
read_eval(&input_datagram, &output_datagram, &config, commands, 1);
mock().checkExpectations();
can_mock_message(0x0, &message[8], 6);
mock().expectOneCall("command");
read_eval(&input_datagram, &output_datagram, &config, commands, 1);
mock().checkExpectations();
}
static void command_output(int argc, cmp_ctx_t *arg_context, cmp_ctx_t *out_context, bootloader_config_t *config)
{
cmp_write_str(out_context, "hello", 5);
}
TEST(IntegrationTesting, OutputDatagramIsValid)
{
uint8_t message[] = {
0x01,
0x62, 0x67, 0x01, 0xfa,// CRC
0x01,
0x01, // dest nodes
0x0, 0x0, 0x0, 0x2,
0x1, 0x1 // data
};
commands[0].callback = command_output;
can_mock_message(0x0, &message[0], 8);
read_eval(&input_datagram, &output_datagram, &config, commands, 1);
can_mock_message(0x0, &message[8], 5);
read_eval(&input_datagram, &output_datagram, &config, commands, 1);
// Check that the data lenght is correct
CHECK_EQUAL(6, output_datagram.data_len);
CHECK_TRUE(can_datagram_is_valid(&output_datagram));
}
<commit_msg>Bypass CRC check in integration testing<commit_after>#include <CppUTest/TestHarness.h>
#include <CppUTestExt/MockSupport.h>
#include "../can_datagram.h"
#include "../config.h"
#include "mocks/can_interface_mock.h"
#include "../can_interface.h"
#include "../command.h"
#include <cstdio>
void read_eval(can_datagram_t *input, can_datagram_t *output, bootloader_config_t *config, command_t *commands, int command_len)
{
uint32_t message_id;
uint8_t message[8];
int len, i;
len = can_interface_read_message(&message_id, message);
for (i = 0; i < len; ++i) {
can_datagram_input_byte(input, message[i]);
}
// Bypass CRC check
input->crc = can_datagram_compute_crc(input);
if (can_datagram_is_valid(input)) {
for (i = 0; i < input->destination_nodes_len; ++i) {
if (input->destination_nodes[i] == config->ID){
len = protocol_execute_command((char *)input->data, input->data_len, commands, command_len, (char *)output->data, output->data_len, config);
/* Checks if there was any error. */
if (len < 0) {
return;
}
output->data_len = len;
}
}
if (output->data_len > 0) {
output->destination_nodes_len = 1;
output->crc = can_datagram_compute_crc(output);
}
}
}
static void mock_command(int argc, cmp_ctx_t *arg_context, cmp_ctx_t *out_context, bootloader_config_t *config)
{
mock().actualCall("command");
}
TEST_GROUP(IntegrationTesting)
{
can_datagram_t input_datagram;
uint8_t input_datagram_destinations[10];
uint8_t input_datagram_data[1000];
can_datagram_t output_datagram;
uint8_t output_datagram_destinations[10];
uint8_t output_datagram_data[1000];
bootloader_config_t config;
command_t commands[1];
void setup(void)
{
can_datagram_init(&input_datagram);
can_datagram_set_address_buffer(&input_datagram, input_datagram_destinations);
can_datagram_set_data_buffer(&input_datagram, input_datagram_data, sizeof input_datagram_data);
can_datagram_init(&output_datagram);
can_datagram_set_address_buffer(&output_datagram, output_datagram_destinations);
can_datagram_set_data_buffer(&output_datagram, output_datagram_data, sizeof output_datagram_data);
// Loads default config for testing
config.ID = 0x01;
commands[0].index = 1;
commands[0].callback = mock_command;
}
void teardown(void)
{
mock().clear();
}
};
TEST(IntegrationTesting, CanReadWholeDatagram)
{
uint8_t message[] = {
0x01,
0x00, 0x00, 0x00, 0x00, // CRC
0x01,
0x01, // dest nodes
0x0, 0x0, 0x0, 0x1,
0x1 // data
};
can_mock_message(0x0, &message[0], 8);
read_eval(&input_datagram, &output_datagram, &config, NULL, 0);
mock().checkExpectations();
can_mock_message(0x0, &message[8], 4);
read_eval(&input_datagram, &output_datagram, &config, NULL, 0);
mock().checkExpectations();
CHECK_TRUE(can_datagram_is_valid(&input_datagram));
}
TEST(IntegrationTesting, ExecutesCommand)
{
uint8_t message[] = {
0x01, // protocol version
0x00, 0x00, 0x00, 0x00, // CRC
0x01,
0x01, // dest nodes
0x0, 0x0, 0x0, 0x2,
0x1, 0x1 // data
};
can_mock_message(0x0, &message[0], 8);
read_eval(&input_datagram, &output_datagram, &config, commands, 1);
mock().checkExpectations();
can_mock_message(0x0, &message[8], 5);
mock().expectOneCall("command");
read_eval(&input_datagram, &output_datagram, &config, commands, 1);
mock().checkExpectations();
}
TEST(IntegrationTesting, ExecutesIfWeAreInMultiCast)
{
uint8_t message[] = {
0x01, // protocol version
0x00, 0x00, 0x00, 0x00, // CRC
0x02,
0x01, 0x12, // dest nodes
0x0, 0x0, 0x0, 0x2,
0x1, 0x1 // data
};
config.ID = 0x12;
can_mock_message(0x0, &message[0], 8);
read_eval(&input_datagram, &output_datagram, &config, commands, 1);
mock().checkExpectations();
can_mock_message(0x0, &message[8], 6);
mock().expectOneCall("command");
read_eval(&input_datagram, &output_datagram, &config, commands, 1);
mock().checkExpectations();
}
static void command_output(int argc, cmp_ctx_t *arg_context, cmp_ctx_t *out_context, bootloader_config_t *config)
{
cmp_write_str(out_context, "hello", 5);
}
TEST(IntegrationTesting, OutputDatagramIsValid)
{
uint8_t message[] = {
0x01,
0x00, 0x00, 0x00, 0x00, // CRC
0x01,
0x01, // dest nodes
0x0, 0x0, 0x0, 0x2,
0x1, 0x1 // data
};
commands[0].callback = command_output;
can_mock_message(0x0, &message[0], 8);
read_eval(&input_datagram, &output_datagram, &config, commands, 1);
can_mock_message(0x0, &message[8], 5);
read_eval(&input_datagram, &output_datagram, &config, commands, 1);
// Check that the data lenght is correct
CHECK_EQUAL(6, output_datagram.data_len);
CHECK_TRUE(can_datagram_is_valid(&output_datagram));
}
<|endoftext|> |
<commit_before>#define _BSD_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ptrace.h>
#include <sys/uio.h>
#include <unistd.h>
#include "ptbox.h"
pt_debugger::pt_debugger() : on_return_callback(NULL) {}
#if PTBOX_FREEBSD
bool pt_debugger::use_peekdata = true;
#else
bool pt_debugger::use_peekdata = false;
#endif
bool has_null(char *buf, unsigned long size) {
for (unsigned long i = 0; i < size; ++i) {
if (buf[i] == '\0')
return true;
}
return false;
}
void pt_debugger::set_process(pt_process *proc) {
process = proc;
}
void pt_debugger::new_process() {
#if PTBOX_FREEBSD
tid = process->getpid();
#endif
}
#if PTBOX_FREEBSD
void pt_debugger::update_syscall(struct ptrace_lwpinfo *info) {
struct reg bsd_regs;
ptrace(PT_GETREGS, tid, (caddr_t) &bsd_regs, 0);
map_regs_to_linux(&bsd_regs, &bsd_converted_regs);
if (info->pl_flags & PL_FLAG_SCX)
bsd_converted_regs.orig_rax = syscall_[info->pl_lwpid];
// Not available on all kernels.
// bsd_converted_regs.orig_rax = info->pl_syscall_code;
else if (info->pl_flags & PL_FLAG_SCE)
syscall_[info->pl_lwpid] = bsd_converted_regs.rax;
}
void pt_debugger::setpid(pid_t pid) {
this->tid = pid;
}
#else
void pt_debugger::settid(pid_t tid) {
this->tid = tid;
if (!syscall_.count(tid)) syscall_[tid] = 0;
syscall_[tid] ^= 1;
}
#endif
#ifdef PTBOX_NEED_PRE_POST_SYSCALL
void pt_debugger::pre_syscall() {}
void pt_debugger::post_syscall() {}
#endif
long pt_debugger::peek_reg(int idx) {
#if PTBOX_FREEBSD
return ((reg_type*)&bsd_converted_regs)[idx];
#else
long res;
errno = 0;
res = ptrace(PTRACE_PEEKUSER, tid, sizeof(long) * idx, 0);
if (res == -1 && errno)
perror("ptrace(PTRACE_PEEKUSER)");
return res;
#endif
}
void pt_debugger::poke_reg(int idx, long data) {
#if PTBOX_FREEBSD
((reg_type*)&bsd_converted_regs)[idx] = data;
struct reg bsd_regs;
// Update bsd_regs with latest regs, since not all are mapped by map_regs_from_linux and we don't want
// garbage to be written to the other registers.
// Alternatively we could be mapping them in map_regs, but that'd be more fragile and less easy (there are
// some registers, like r_trapno on FreeBSD, that have no real equivalent on Linux, and vice-versa).
ptrace(PT_GETREGS, tid, (caddr_t) &bsd_regs, 0);
map_regs_from_linux(&bsd_regs, &bsd_converted_regs);
ptrace(PT_SETREGS, tid, (caddr_t) &bsd_regs, 0);
#else
ptrace(PTRACE_POKEUSER, tid, sizeof(long) * idx, data);
#endif
}
#if PTBOX_FREEBSD
typedef int ptrace_read_t;
#else
typedef long ptrace_read_t;
#ifndef SYS_process_vm_readv
#define SYS_process_vm_readv 270
#endif
ssize_t __attribute__((weak)) process_vm_readv(
pid_t pid, const struct iovec *lvec, unsigned long liovcnt,
const struct iovec *rvec, unsigned long riovcnt, unsigned long flags
) {
return syscall(SYS_process_vm_readv, (long) pid, lvec, liovcnt, rvec, riovcnt, flags);
}
#endif
char *pt_debugger::readstr(unsigned long addr, size_t max_size) {
#if PTBOX_FREEBSD
return readstr_peekdata(addr, max_size);
#else
static unsigned long page_size = -sysconf(_SC_PAGESIZE);
static unsigned long page_mask = (unsigned long) page_size;
char *buf;
unsigned long remain, read = 0;
struct iovec local, remote;
if (use_peekdata)
return readstr_peekdata(addr, max_size);
remain = addr - (addr & page_mask);
buf = (char *) malloc(max_size + 1);
while (read < max_size) {
local.iov_base = (void *) (buf + read);
local.iov_len = remain;
remote.iov_base = (void *) (addr + read);
remote.iov_len = remain;
if (process_vm_readv(tid, &local, 1, &remote, 1, 0) > 0) {
if (memchr(buf + read, '\0', remain))
return buf;
read += remain;
} else if (errno == ENOSYS || errno == EPERM) {
perror("process_vm_readv");
use_peekdata = true;
free(buf);
return readstr_peekdata(addr, max_size);
} else {
if (errno != EFAULT && errno != EIO)
perror("process_vm_readv");
buf[read] = 0;
return buf;
}
remain = page_size < max_size - read ? page_size : max_size - read;
}
buf[max_size] = 0;
return buf;
#endif
}
char *pt_debugger::readstr_peekdata(unsigned long addr, size_t max_size) {
size_t size = 4096, read = 0;
char *buf = (char *) malloc(size);
union {
ptrace_read_t val;
char byte[sizeof(ptrace_read_t)];
} data;
while (true) {
if (read + sizeof(ptrace_read_t) > size) {
if (max_size && size >= max_size) {
buf[max_size-1] = 0;
break;
}
size += 4096;
if (max_size && size > max_size)
size = max_size;
void *nbuf = realloc(buf, size);
if (!nbuf) {
buf[size-4097] = 0;
break;
}
buf = (char *) nbuf;
}
#if PTBOX_FREEBSD
// TODO: we could use PT_IO to speed up this entire function by reading chunks rather than byte
data.val = ptrace(PT_READ_D, tid, (caddr_t) (addr + read), 0);
#else
errno = 0;
data.val = ptrace(PTRACE_PEEKDATA, tid, addr + read, NULL);
if (data.val == -1 && errno)
perror("ptrace(PTRACE_PEEKDATA)");
#endif
memcpy(buf + read, data.byte, sizeof(ptrace_read_t));
if (has_null(data.byte, sizeof(ptrace_read_t)))
break;
read += sizeof(ptrace_read_t);
}
return buf;
}
void pt_debugger::freestr(char *buf) {
free(buf);
}
pt_debugger::~pt_debugger() {}
<commit_msg>Stop false reporting zero byte reads; #300<commit_after>#define _BSD_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ptrace.h>
#include <sys/uio.h>
#include <unistd.h>
#include "ptbox.h"
pt_debugger::pt_debugger() : on_return_callback(NULL) {}
#if PTBOX_FREEBSD
bool pt_debugger::use_peekdata = true;
#else
bool pt_debugger::use_peekdata = false;
#endif
bool has_null(char *buf, unsigned long size) {
for (unsigned long i = 0; i < size; ++i) {
if (buf[i] == '\0')
return true;
}
return false;
}
void pt_debugger::set_process(pt_process *proc) {
process = proc;
}
void pt_debugger::new_process() {
#if PTBOX_FREEBSD
tid = process->getpid();
#endif
}
#if PTBOX_FREEBSD
void pt_debugger::update_syscall(struct ptrace_lwpinfo *info) {
struct reg bsd_regs;
ptrace(PT_GETREGS, tid, (caddr_t) &bsd_regs, 0);
map_regs_to_linux(&bsd_regs, &bsd_converted_regs);
if (info->pl_flags & PL_FLAG_SCX)
bsd_converted_regs.orig_rax = syscall_[info->pl_lwpid];
// Not available on all kernels.
// bsd_converted_regs.orig_rax = info->pl_syscall_code;
else if (info->pl_flags & PL_FLAG_SCE)
syscall_[info->pl_lwpid] = bsd_converted_regs.rax;
}
void pt_debugger::setpid(pid_t pid) {
this->tid = pid;
}
#else
void pt_debugger::settid(pid_t tid) {
this->tid = tid;
if (!syscall_.count(tid)) syscall_[tid] = 0;
syscall_[tid] ^= 1;
}
#endif
#ifdef PTBOX_NEED_PRE_POST_SYSCALL
void pt_debugger::pre_syscall() {}
void pt_debugger::post_syscall() {}
#endif
long pt_debugger::peek_reg(int idx) {
#if PTBOX_FREEBSD
return ((reg_type*)&bsd_converted_regs)[idx];
#else
long res;
errno = 0;
res = ptrace(PTRACE_PEEKUSER, tid, sizeof(long) * idx, 0);
if (res == -1 && errno)
perror("ptrace(PTRACE_PEEKUSER)");
return res;
#endif
}
void pt_debugger::poke_reg(int idx, long data) {
#if PTBOX_FREEBSD
((reg_type*)&bsd_converted_regs)[idx] = data;
struct reg bsd_regs;
// Update bsd_regs with latest regs, since not all are mapped by map_regs_from_linux and we don't want
// garbage to be written to the other registers.
// Alternatively we could be mapping them in map_regs, but that'd be more fragile and less easy (there are
// some registers, like r_trapno on FreeBSD, that have no real equivalent on Linux, and vice-versa).
ptrace(PT_GETREGS, tid, (caddr_t) &bsd_regs, 0);
map_regs_from_linux(&bsd_regs, &bsd_converted_regs);
ptrace(PT_SETREGS, tid, (caddr_t) &bsd_regs, 0);
#else
ptrace(PTRACE_POKEUSER, tid, sizeof(long) * idx, data);
#endif
}
#if PTBOX_FREEBSD
typedef int ptrace_read_t;
#else
typedef long ptrace_read_t;
#ifndef SYS_process_vm_readv
#define SYS_process_vm_readv 270
#endif
ssize_t __attribute__((weak)) process_vm_readv(
pid_t pid, const struct iovec *lvec, unsigned long liovcnt,
const struct iovec *rvec, unsigned long riovcnt, unsigned long flags
) {
return syscall(SYS_process_vm_readv, (long) pid, lvec, liovcnt, rvec, riovcnt, flags);
}
#endif
char *pt_debugger::readstr(unsigned long addr, size_t max_size) {
#if PTBOX_FREEBSD
return readstr_peekdata(addr, max_size);
#else
static unsigned long page_size = -sysconf(_SC_PAGESIZE);
static unsigned long page_mask = (unsigned long) page_size;
char *buf;
unsigned long remain, read = 0;
struct iovec local, remote;
if (use_peekdata)
return readstr_peekdata(addr, max_size);
remain = addr - (addr & page_mask);
buf = (char *) malloc(max_size + 1);
while (read < max_size) {
local.iov_base = (void *) (buf + read);
local.iov_len = remain;
remote.iov_base = (void *) (addr + read);
remote.iov_len = remain;
errno = 0;
if (process_vm_readv(tid, &local, 1, &remote, 1, 0) > 0) {
if (memchr(buf + read, '\0', remain))
return buf;
read += remain;
} else if (errno == ENOSYS || errno == EPERM) {
perror("process_vm_readv");
use_peekdata = true;
free(buf);
return readstr_peekdata(addr, max_size);
} else {
if (errno && errno != EFAULT && errno != EIO)
perror("process_vm_readv");
buf[read] = 0;
return buf;
}
remain = page_size < max_size - read ? page_size : max_size - read;
}
buf[max_size] = 0;
return buf;
#endif
}
char *pt_debugger::readstr_peekdata(unsigned long addr, size_t max_size) {
size_t size = 4096, read = 0;
char *buf = (char *) malloc(size);
union {
ptrace_read_t val;
char byte[sizeof(ptrace_read_t)];
} data;
while (true) {
if (read + sizeof(ptrace_read_t) > size) {
if (max_size && size >= max_size) {
buf[max_size-1] = 0;
break;
}
size += 4096;
if (max_size && size > max_size)
size = max_size;
void *nbuf = realloc(buf, size);
if (!nbuf) {
buf[size-4097] = 0;
break;
}
buf = (char *) nbuf;
}
#if PTBOX_FREEBSD
// TODO: we could use PT_IO to speed up this entire function by reading chunks rather than byte
data.val = ptrace(PT_READ_D, tid, (caddr_t) (addr + read), 0);
#else
errno = 0;
data.val = ptrace(PTRACE_PEEKDATA, tid, addr + read, NULL);
if (data.val == -1 && errno)
perror("ptrace(PTRACE_PEEKDATA)");
#endif
memcpy(buf + read, data.byte, sizeof(ptrace_read_t));
if (has_null(data.byte, sizeof(ptrace_read_t)))
break;
read += sizeof(ptrace_read_t);
}
return buf;
}
void pt_debugger::freestr(char *buf) {
free(buf);
}
pt_debugger::~pt_debugger() {}
<|endoftext|> |
<commit_before>//CODEIMGAME
#include "../graphics.hpp"
#include "sstream"
#include "vector"
#include "stdlib.h"
#include "time.h"
#include "math.h"
using namespace genv;
using namespace std;
const int kx = 1330;
const int ky = 600;
struct Sboxok
{
int x;
int y;
int vx;
int vy;
unsigned char rr,gg,bb;
int elet;
Sboxok (int ex, int ey, int szin)
{
x = ex;
y = ey;
vx=rand() % 10 -5;
vy=-(rand() % 10 +5);
elet = 100;
if (szin<255) {rr=255-(szin-0*255); gg=(szin-0*255); bb=000;} else
if (szin>255 and szin<2*255) {rr=000; gg=255-(szin-1*255); bb=(szin-1*255);} else
if (szin>2*255) {rr=(szin-2*255); gg=000; bb=255-(szin-2*255);}
}
void supdate();
void srajzol();
};
void Sboxok::supdate()
{
x+=vx;
y+=vy;
if (x>=kx or x<0) {vx=-vx; x+=vx;}
if (y>=ky or y<0) {vy=-floor(vy/2); y+=vy;}
vy++;
elet--;
}
void Sboxok::srajzol()
{
if (x>=kx or x<0) return;
if (y>=ky or y<0) return;
gout << color(rr,gg,bb)
<< move_to(x,y)
<< box(10,10);
}
std::vector<Sboxok> v;
int szin = 0;
void updatedraw()
{
for (vector<Sboxok>::iterator i=v.begin(); i!=v.end();)
{
i->supdate();
i->srajzol();
if(i->elet<=0) i = v.erase(i);
else ++i;
}
}
int main()
{
srand (time(NULL));
gout.open(kx,ky,true);
gout.showmouse(false);
gin.timer(20);
event ev;
while(gin >> ev and ev.keycode!=key_escape) {
if (ev.type==ev_timer) {
gout << color(000,000,000)
<< move_to(0,0)
<< box_to(1329,599);
updatedraw();
gout << refresh;
}
if (ev.type==ev_mouse)
{
Sboxok b(ev.pos_x,ev.pos_y,szin);
szin++; if (szin>3*255) szin=0;
v.push_back(b);
}
}
return 0;
}
<commit_msg>Asztali<commit_after>//CODEINGAME
#include "../graphics.hpp"
#include "sstream"
#include "vector"
#include "stdlib.h"
#include "time.h"
#include "math.h"
using namespace genv;
using namespace std;
const int kx = 1330;
const int ky = 600;
struct Sboxok
{
int x;
int y;
int vx;
int vy;
unsigned char rr,gg,bb;
int elet;
Sboxok (int ex, int ey, int szin)
{
x = ex;
y = ey;
vx=rand() % 10 -5;
vy=-(rand() % 10 +5);
elet = 100;
if (szin<255) {rr=255-(szin-0*255); gg=(szin-0*255); bb=000;} else
if (szin>255 and szin<2*255) {rr=000; gg=255-(szin-1*255); bb=(szin-1*255);} else
if (szin>2*255) {rr=(szin-2*255); gg=000; bb=255-(szin-2*255);}
}
void supdate();
void srajzol();
};
void Sboxok::supdate()
{
x+=vx;
y+=vy;
if (x>=kx or x<0) {vx=-vx; x+=vx;}
if (y>=ky or y<0) {vy=-floor(vy/2); y+=vy;}
vy++;
elet--;
}
void Sboxok::srajzol()
{
if (x>=kx or x<0) return;
if (y>=ky or y<0) return;
gout << color(rr,gg,bb)
<< move_to(x,y)
<< box(10,10);
}
std::vector<Sboxok> v;
int szin = 0;
void updatedraw()
{
for (vector<Sboxok>::iterator i=v.begin(); i!=v.end();)
{
i->supdate();
i->srajzol();
if(i->elet<=0) i = v.erase(i);
else ++i;
}
}
int main()
{
srand (time(NULL));
gout.open(kx,ky,true);
gout.showmouse(false);
gin.timer(20);
event ev;
while(gin >> ev and ev.keycode!=key_escape) {
if (ev.type==ev_timer) {
gout << color(000,000,000)
<< move_to(0,0)
<< box_to(1329,599);
updatedraw();
gout << refresh;
}
if (ev.type==ev_mouse)
{
Sboxok b(ev.pos_x,ev.pos_y,szin);
szin++; if (szin>3*255) szin=0;
v.push_back(b);
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include "map.h"
using worker::Entity;
using worker::List;
using shoveler::TilemapTilesTile;
static const int halfMapWidth = 100;
static const int halfMapHeight = 100;
static ChunkData createChunk(int x, int y, int chunkSize);
List<ChunkData> generateMapChunks(int chunkSize)
{
List<ChunkData> chunks;
for(int x = -halfMapWidth; x < halfMapWidth; x += chunkSize) {
for(int z = -halfMapHeight; z < halfMapHeight; z += chunkSize) {
chunks.emplace_back(createChunk(x, z, chunkSize));
}
}
return chunks;
}
static ChunkData createChunk(int x, int z, int chunkSize)
{
ChunkData chunk;
chunk.position = {x + chunkSize / 2.0, 0.0, z + chunkSize / 2.0};
int rockSeedModulo = 5 + (rand() % 100);
int bushSeedModulo = 5 + (rand() % 25);
int treeSeedModulo = 5 + (rand() % 50);
for(int i = 0; i < chunkSize; i++) {
for(int j = 0; j < chunkSize; j++) {
TilemapTilesTile backgroundTile;
TilemapTilesTile foregroundTile;
foregroundTile.set_tileset_column(0);
foregroundTile.set_tileset_row(0);
foregroundTile.set_tileset_id(0);
foregroundTile.set_colliding(false);
// fill background with grass
int grassColumn = rand() % 3;
int grassRow = rand() % 2;
backgroundTile.set_tileset_column(grassColumn);
backgroundTile.set_tileset_row(grassRow);
backgroundTile.set_tileset_id(2);
foregroundTile.set_colliding(false);
// place rocks
int rockSeed = rand() % rockSeedModulo;
if(rockSeed == 0) {
backgroundTile.set_tileset_column(5);
backgroundTile.set_tileset_row(0);
backgroundTile.set_colliding(true);
}
// place bushes
int bushSeed = rand() % bushSeedModulo;
if(bushSeed == 0) {
backgroundTile.set_tileset_column(5);
backgroundTile.set_tileset_row(1);
backgroundTile.set_colliding(true);
}
// place trees
do {
if(i > 0) {
const TilemapTilesTile& previousRow = chunk.backgroundTiles[(i - 1) * chunkSize + j];
// complete left part of tree
if(previousRow.tileset_column() == 3 && previousRow.tileset_row() == 0) {
foregroundTile.set_tileset_column(3);
foregroundTile.set_tileset_row(1);
foregroundTile.set_tileset_id(2);
break;
}
// complete right part of tree
if(previousRow.tileset_column() == 4 && previousRow.tileset_row() == 0) {
foregroundTile.set_tileset_column(4);
foregroundTile.set_tileset_row(1);
foregroundTile.set_tileset_id(2);
break;
}
}
if(j > 0) {
const TilemapTilesTile &previousTile = *chunk.backgroundTiles.rbegin();
// complete bottom part of tree
if (previousTile.tileset_column() == 3 && previousTile.tileset_row() == 0) {
backgroundTile.set_tileset_column(4);
backgroundTile.set_tileset_row(0);
backgroundTile.set_colliding(true);
break;
}
}
if(i > 0 && j < chunkSize - 1) {
const TilemapTilesTile& previousRowNext = chunk.backgroundTiles[(i - 1) * chunkSize + j + 1];
// reject positions that already have a tree starting on the bottom right neighbor tile
if (previousRowNext.tileset_column() == 3 && previousRowNext.tileset_row() == 0) {
break;
}
}
// reject positions that don't fit into the chunk
if(i == chunkSize - 1 || j == chunkSize - 1) {
break;
}
// start new tree
int treeSeed = rand() % treeSeedModulo;
if(treeSeed == 0) {
backgroundTile.set_tileset_column(3);
backgroundTile.set_tileset_row(0);
backgroundTile.set_colliding(true);
}
} while (false);
chunk.backgroundTiles.emplace_back(backgroundTile);
chunk.foregroundTiles.emplace_back(foregroundTile);
}
}
return chunk;
}
<commit_msg>added startig area for tiles map<commit_after>#include <cstdlib>
#include "map.h"
using worker::Entity;
using worker::List;
using shoveler::TilemapTilesTile;
static const int halfMapWidth = 100;
static const int halfMapHeight = 100;
static ChunkData createStartingAreaBottomLeft(int chunkSize);
static ChunkData createStartingAreaBottomRight(int chunkSize);
static ChunkData createStartingAreaTopLeft(int chunkSize);
static ChunkData createStartingAreaTopRight(int chunkSize);
static ChunkData createChunk(int x, int y, int chunkSize);
List<ChunkData> generateMapChunks(int chunkSize)
{
List<ChunkData> chunks;
for(int x = -halfMapWidth; x < halfMapWidth; x += chunkSize) {
for(int z = -halfMapHeight; z < halfMapHeight; z += chunkSize) {
if(x == -chunkSize && z == -chunkSize) {
chunks.emplace_back(createStartingAreaBottomLeft(chunkSize));
} else if(x == 0 && z == -chunkSize) {
chunks.emplace_back(createStartingAreaBottomRight(chunkSize));
} else if(x == -chunkSize && z == 0) {
chunks.emplace_back(createStartingAreaTopLeft(chunkSize));
} else if(x == 0 && z == 0) {
chunks.emplace_back(createStartingAreaTopRight(chunkSize));
} else {
chunks.emplace_back(createChunk(x, z, chunkSize));
}
}
}
return chunks;
}
static ChunkData createStartingAreaBottomLeft(int chunkSize)
{
ChunkData chunk;
chunk.position = {-chunkSize / 2.0, 0.0, -chunkSize / 2.0};
for(int i = 0; i < chunkSize; i++) {
for(int j = 0; j < chunkSize; j++) {
TilemapTilesTile backgroundTile;
TilemapTilesTile foregroundTile;
foregroundTile.set_tileset_column(0);
foregroundTile.set_tileset_row(0);
foregroundTile.set_tileset_id(0);
foregroundTile.set_colliding(false);
// fill background with grass
int grassColumn = rand() % 3;
int grassRow = rand() % 2;
backgroundTile.set_tileset_column(grassColumn);
backgroundTile.set_tileset_row(grassRow);
backgroundTile.set_tileset_id(2);
foregroundTile.set_colliding(false);
// place boundary rocks
if((i == 0 || j == 0) && i != chunkSize - 1 && j != chunkSize - 1) {
backgroundTile.set_tileset_column(5);
backgroundTile.set_tileset_row(0);
backgroundTile.set_colliding(true);
}
chunk.backgroundTiles.emplace_back(backgroundTile);
chunk.foregroundTiles.emplace_back(foregroundTile);
}
}
return chunk;
}
static ChunkData createStartingAreaBottomRight(int chunkSize)
{
ChunkData chunk;
chunk.position = {chunkSize / 2.0, 0.0, -chunkSize / 2.0};
for(int i = 0; i < chunkSize; i++) {
for(int j = 0; j < chunkSize; j++) {
TilemapTilesTile backgroundTile;
TilemapTilesTile foregroundTile;
foregroundTile.set_tileset_column(0);
foregroundTile.set_tileset_row(0);
foregroundTile.set_tileset_id(0);
foregroundTile.set_colliding(false);
// fill background with grass
int grassColumn = rand() % 3;
int grassRow = rand() % 2;
backgroundTile.set_tileset_column(grassColumn);
backgroundTile.set_tileset_row(grassRow);
backgroundTile.set_tileset_id(2);
foregroundTile.set_colliding(false);
// place boundary rocks
if((i == 0 || j == chunkSize - 1) && i != chunkSize - 1 && j != 0) {
backgroundTile.set_tileset_column(5);
backgroundTile.set_tileset_row(0);
backgroundTile.set_colliding(true);
}
chunk.backgroundTiles.emplace_back(backgroundTile);
chunk.foregroundTiles.emplace_back(foregroundTile);
}
}
return chunk;
}
static ChunkData createStartingAreaTopLeft(int chunkSize)
{
ChunkData chunk;
chunk.position = {-chunkSize / 2.0, 0.0, chunkSize / 2.0};
for(int i = 0; i < chunkSize; i++) {
for(int j = 0; j < chunkSize; j++) {
TilemapTilesTile backgroundTile;
TilemapTilesTile foregroundTile;
foregroundTile.set_tileset_column(0);
foregroundTile.set_tileset_row(0);
foregroundTile.set_tileset_id(0);
foregroundTile.set_colliding(false);
// fill background with grass
int grassColumn = rand() % 3;
int grassRow = rand() % 2;
backgroundTile.set_tileset_column(grassColumn);
backgroundTile.set_tileset_row(grassRow);
backgroundTile.set_tileset_id(2);
foregroundTile.set_colliding(false);
// place boundary rocks
if((i == chunkSize - 1 || j == 0) && i != 0 && j != chunkSize - 1) {
backgroundTile.set_tileset_column(5);
backgroundTile.set_tileset_row(0);
backgroundTile.set_colliding(true);
}
chunk.backgroundTiles.emplace_back(backgroundTile);
chunk.foregroundTiles.emplace_back(foregroundTile);
}
}
return chunk;
}
static ChunkData createStartingAreaTopRight(int chunkSize)
{
ChunkData chunk;
chunk.position = {chunkSize / 2.0, 0.0, chunkSize / 2.0};
for(int i = 0; i < chunkSize; i++) {
for(int j = 0; j < chunkSize; j++) {
TilemapTilesTile backgroundTile;
TilemapTilesTile foregroundTile;
foregroundTile.set_tileset_column(0);
foregroundTile.set_tileset_row(0);
foregroundTile.set_tileset_id(0);
foregroundTile.set_colliding(false);
// fill background with grass
int grassColumn = rand() % 3;
int grassRow = rand() % 2;
backgroundTile.set_tileset_column(grassColumn);
backgroundTile.set_tileset_row(grassRow);
backgroundTile.set_tileset_id(2);
foregroundTile.set_colliding(false);
// place boundary rocks
if((i == chunkSize - 1 || j == chunkSize - 1) && i != 0 && j != 0) {
backgroundTile.set_tileset_column(5);
backgroundTile.set_tileset_row(0);
backgroundTile.set_colliding(true);
}
chunk.backgroundTiles.emplace_back(backgroundTile);
chunk.foregroundTiles.emplace_back(foregroundTile);
}
}
return chunk;
}
static ChunkData createChunk(int x, int z, int chunkSize)
{
ChunkData chunk;
chunk.position = {x + chunkSize / 2.0, 0.0, z + chunkSize / 2.0};
int rockSeedModulo = 5 + (rand() % 100);
int bushSeedModulo = 5 + (rand() % 25);
int treeSeedModulo = 5 + (rand() % 50);
for(int i = 0; i < chunkSize; i++) {
for(int j = 0; j < chunkSize; j++) {
TilemapTilesTile backgroundTile;
TilemapTilesTile foregroundTile;
foregroundTile.set_tileset_column(0);
foregroundTile.set_tileset_row(0);
foregroundTile.set_tileset_id(0);
foregroundTile.set_colliding(false);
// fill background with grass
int grassColumn = rand() % 3;
int grassRow = rand() % 2;
backgroundTile.set_tileset_column(grassColumn);
backgroundTile.set_tileset_row(grassRow);
backgroundTile.set_tileset_id(2);
foregroundTile.set_colliding(false);
// place rocks
int rockSeed = rand() % rockSeedModulo;
if(rockSeed == 0) {
backgroundTile.set_tileset_column(5);
backgroundTile.set_tileset_row(0);
backgroundTile.set_colliding(true);
}
// place bushes
int bushSeed = rand() % bushSeedModulo;
if(bushSeed == 0) {
backgroundTile.set_tileset_column(5);
backgroundTile.set_tileset_row(1);
backgroundTile.set_colliding(true);
}
// place trees
do {
if(i > 0) {
const TilemapTilesTile& previousRow = chunk.backgroundTiles[(i - 1) * chunkSize + j];
// complete left part of tree
if(previousRow.tileset_column() == 3 && previousRow.tileset_row() == 0) {
foregroundTile.set_tileset_column(3);
foregroundTile.set_tileset_row(1);
foregroundTile.set_tileset_id(2);
break;
}
// complete right part of tree
if(previousRow.tileset_column() == 4 && previousRow.tileset_row() == 0) {
foregroundTile.set_tileset_column(4);
foregroundTile.set_tileset_row(1);
foregroundTile.set_tileset_id(2);
break;
}
}
if(j > 0) {
const TilemapTilesTile &previousTile = *chunk.backgroundTiles.rbegin();
// complete bottom part of tree
if (previousTile.tileset_column() == 3 && previousTile.tileset_row() == 0) {
backgroundTile.set_tileset_column(4);
backgroundTile.set_tileset_row(0);
backgroundTile.set_colliding(true);
break;
}
}
if(i > 0 && j < chunkSize - 1) {
const TilemapTilesTile& previousRowNext = chunk.backgroundTiles[(i - 1) * chunkSize + j + 1];
// reject positions that already have a tree starting on the bottom right neighbor tile
if (previousRowNext.tileset_column() == 3 && previousRowNext.tileset_row() == 0) {
break;
}
}
// reject positions that don't fit into the chunk
if(i == chunkSize - 1 || j == chunkSize - 1) {
break;
}
// start new tree
int treeSeed = rand() % treeSeedModulo;
if(treeSeed == 0) {
backgroundTile.set_tileset_column(3);
backgroundTile.set_tileset_row(0);
backgroundTile.set_colliding(true);
}
} while (false);
chunk.backgroundTiles.emplace_back(backgroundTile);
chunk.foregroundTiles.emplace_back(foregroundTile);
}
}
return chunk;
}
<|endoftext|> |
<commit_before>#include <reactive/bridge.hpp>
#include <reactive/consume.hpp>
#include <boost/optional.hpp>
#include <boost/test/unit_test.hpp>
#include <lua.hpp>
namespace Si
{
struct lua_deleter
{
void operator()(lua_State *L) const
{
lua_close(L);
}
};
std::unique_ptr<lua_State, lua_deleter> open_lua()
{
auto L = std::unique_ptr<lua_State, lua_deleter>(luaL_newstate());
if (!L)
{
throw std::bad_alloc();
}
return L;
}
typedef rx::observer<int> yield_destination;
static int yield(lua_State *L)
{
yield_destination &dest = *static_cast<yield_destination *>(lua_touserdata(L, lua_upvalueindex(1)));
int element = lua_tointeger(L, 1);
dest.got_element(element);
return lua_yield(L, 0);
}
BOOST_AUTO_TEST_CASE(lua)
{
auto L = open_lua();
// src
BOOST_REQUIRE_EQUAL(0, luaL_loadstring(L.get(), "return function (yield) yield(4) end"));
// fn
if (0 != lua_pcall(L.get(), 0, 1, 0))
{
throw std::runtime_error(lua_tostring(L.get(), -1));
}
lua_State * const coro = lua_newthread(L.get());
lua_xmove(L.get(), coro, 1);
rx::bridge<int> yielded;
// fn &yielded
lua_pushlightuserdata(coro, &static_cast<yield_destination &>(yielded));
// fn yield[&yielded]
lua_pushcclosure(coro, yield, 1);
boost::optional<int> got;
auto consumer = rx::consume<int>([&got](boost::optional<int> element)
{
BOOST_REQUIRE(element);
got = element;
});
yielded.async_get_one(consumer);
if (LUA_YIELD != lua_resume(L.get(), 1))
{
throw std::runtime_error(lua_tostring(coro, -1));
}
BOOST_CHECK_EQUAL(boost::make_optional(4), got);
}
}
<commit_msg>fix the lua thread test<commit_after>#include <reactive/bridge.hpp>
#include <reactive/consume.hpp>
#include <boost/optional.hpp>
#include <boost/test/unit_test.hpp>
#include <lua.hpp>
namespace Si
{
struct lua_deleter
{
void operator()(lua_State *L) const
{
lua_close(L);
}
};
std::unique_ptr<lua_State, lua_deleter> open_lua()
{
auto L = std::unique_ptr<lua_State, lua_deleter>(luaL_newstate());
if (!L)
{
throw std::bad_alloc();
}
return L;
}
typedef rx::observer<int> yield_destination;
static int yield(lua_State *L)
{
yield_destination &dest = *static_cast<yield_destination *>(lua_touserdata(L, lua_upvalueindex(1)));
int element = lua_tointeger(L, 1);
dest.got_element(element);
return lua_yield(L, 0);
}
BOOST_AUTO_TEST_CASE(lua)
{
auto L = open_lua();
lua_State * const coro = lua_newthread(L.get());
BOOST_REQUIRE_EQUAL(0, luaL_loadstring(coro, "return function (yield) yield(4) yield(5) end"));
if (0 != lua_pcall(coro, 0, 1, 0))
{
throw std::runtime_error(lua_tostring(L.get(), -1));
}
rx::bridge<int> yielded;
// fn &yielded
lua_pushlightuserdata(coro, &static_cast<yield_destination &>(yielded));
// fn yield[&yielded]
lua_pushcclosure(coro, yield, 1);
boost::optional<int> got;
auto consumer = rx::consume<int>([&got](boost::optional<int> element)
{
BOOST_REQUIRE(element);
got = element;
});
{
yielded.async_get_one(consumer);
int rc = lua_resume(coro, 1);
if (LUA_YIELD != rc)
{
throw std::runtime_error(lua_tostring(coro, -1));
}
BOOST_CHECK_EQUAL(boost::make_optional(4), got);
}
{
yielded.async_get_one(consumer);
int rc = lua_resume(coro, 1);
if (LUA_YIELD != rc)
{
throw std::runtime_error(lua_tostring(coro, -1));
}
BOOST_CHECK_EQUAL(boost::make_optional(5), got);
}
}
}
<|endoftext|> |
<commit_before>#include "InputMesh.h"
#include <maya/MFnMesh.h>
#include <maya/MDataBlock.h>
#include <maya/MFloatArray.h>
#include <maya/MFloatPointArray.h>
#include <maya/MFloatVectorArray.h>
#include <maya/MIntArray.h>
#include <maya/MMatrix.h>
#include "util.h"
InputMesh::InputMesh(int assetId, int inputIdx) :
Input(assetId, inputIdx),
myInputObjectId(-1),
myInputGeoId(-1)
{
CHECK_HAPI(HAPI_CreateInputAsset(&myInputAssetId, NULL));
Util::statusCheckLoop();
myInputObjectId = 0;
myInputGeoId = 0;
CHECK_HAPI(HAPI_ConnectAssetGeometry(
myInputAssetId, myInputObjectId,
myAssetId, myInputIdx
));
}
InputMesh::~InputMesh()
{
CHECK_HAPI(HAPI_DestroyAsset(myInputAssetId));
}
Input::AssetInputType
InputMesh::assetInputType() const
{
return Input::AssetInputType_Mesh;
}
void
InputMesh::setInputTransform(MDataHandle &dataHandle)
{
MMatrix transformMatrix = dataHandle.asMatrix();
float matrix[16];
transformMatrix.get(reinterpret_cast<float(*)[4]>(matrix));
HAPI_TransformEuler transformEuler;
HAPI_ConvertMatrixToEuler(matrix, HAPI_SRT, HAPI_XYZ, &transformEuler);
HAPI_SetObjectTransform(
myInputAssetId, myInputObjectId,
&transformEuler
);
}
void
InputMesh::setInputGeo(
MDataBlock &dataBlock,
const MPlug &plug
)
{
MDataHandle dataHandle = dataBlock.inputValue(plug);
// extract mesh data from Maya
MObject meshObj = dataHandle.asMesh();
MFnMesh meshFn(meshObj);
// get face data
MIntArray faceCounts;
MIntArray vertexList;
meshFn.getVertices(faceCounts, vertexList);
Util::reverseWindingOrder(vertexList, faceCounts);
// set up part info
HAPI_PartInfo partInfo;
HAPI_PartInfo_Init(&partInfo);
partInfo.id = 0;
partInfo.faceCount = faceCounts.length();
partInfo.vertexCount = vertexList.length();
partInfo.pointCount = meshFn.numVertices();
// copy data to arrays
int * vl = new int[partInfo.vertexCount];
int * fc = new int[partInfo.faceCount];
vertexList.get(vl);
faceCounts.get(fc);
// Set the data
HAPI_SetPartInfo(
myInputAssetId, myInputObjectId, myInputGeoId,
&partInfo
);
HAPI_SetFaceCounts(
myInputAssetId, myInputObjectId, myInputGeoId,
fc, 0, partInfo.faceCount
);
HAPI_SetVertexList(
myInputAssetId, myInputObjectId, myInputGeoId,
vl, 0, partInfo.vertexCount
);
// Set position attributes.
HAPI_AttributeInfo pos_attr_info;
pos_attr_info.exists = true;
pos_attr_info.owner = HAPI_ATTROWNER_POINT;
pos_attr_info.storage = HAPI_STORAGETYPE_FLOAT;
pos_attr_info.count = meshFn.numVertices();
pos_attr_info.tupleSize = 3;
HAPI_AddAttribute(
myInputAssetId, myInputObjectId, myInputGeoId,
"P", &pos_attr_info
);
HAPI_SetAttributeFloatData(
myInputAssetId, myInputObjectId, myInputGeoId,
"P", &pos_attr_info,
meshFn.getRawPoints(NULL), 0, meshFn.numVertices()
);
// normals
{
// get normal IDs
MIntArray normalCounts;
MIntArray normalIds;
meshFn.getNormalIds(normalCounts, normalIds);
if(normalIds.length())
{
// reverse winding order
Util::reverseWindingOrder(normalIds, faceCounts);
// get normal values
const float* rawNormals = meshFn.getRawNormals(NULL);
// build the per-vertex normals
std::vector<float> vertexNormals;
vertexNormals.reserve(normalIds.length() * 3);
for(unsigned int i = 0; i < normalIds.length(); ++i)
{
vertexNormals.push_back(rawNormals[normalIds[i] * 3 + 0]);
vertexNormals.push_back(rawNormals[normalIds[i] * 3 + 1]);
vertexNormals.push_back(rawNormals[normalIds[i] * 3 + 2]);
}
// add and set it to HAPI
HAPI_AttributeInfo attributeInfo;
attributeInfo.exists = true;
attributeInfo.owner = HAPI_ATTROWNER_VERTEX;
attributeInfo.storage = HAPI_STORAGETYPE_FLOAT;
attributeInfo.count = normalIds.length();
attributeInfo.tupleSize = 3;
HAPI_AddAttribute(
myInputAssetId, myInputObjectId, myInputGeoId,
"N", &attributeInfo
);
HAPI_SetAttributeFloatData(myInputAssetId, myInputObjectId, myInputGeoId,
"N", &attributeInfo,
&vertexNormals.front(), 0, normalIds.length()
);
}
}
// UVs
{
// get UV IDs
MIntArray uvCounts;
MIntArray uvIds;
meshFn.getAssignedUVs(uvCounts, uvIds);
// if there's UVs
if(uvIds.length())
{
// reverse winding order
Util::reverseWindingOrder(uvIds, uvCounts);
// get UV values
MFloatArray uArray;
MFloatArray vArray;
meshFn.getUVs(uArray, vArray);
// build the per-vertex UVs
std::vector<float> vertexUVs;
vertexUVs.reserve(vertexList.length() * 3);
unsigned int uvIdIndex = 0;
for(unsigned int i = 0; i < uvCounts.length(); ++i)
{
if(uvCounts[i] == faceCounts[i])
{
// has UVs assigned
for(int j = 0; j < uvCounts[i]; ++j)
{
vertexUVs.push_back(uArray[uvIds[uvIdIndex]]);
vertexUVs.push_back(vArray[uvIds[uvIdIndex]]);
vertexUVs.push_back(0);
uvIdIndex++;
}
}
else
{
// no UVs assigned
for(int j = 0; j < faceCounts[i]; ++j)
{
vertexUVs.push_back(0);
vertexUVs.push_back(0);
vertexUVs.push_back(0);
}
}
}
// add and set it to HAPI
HAPI_AttributeInfo attributeInfo;
attributeInfo.exists = true;
attributeInfo.owner = HAPI_ATTROWNER_VERTEX;
attributeInfo.storage = HAPI_STORAGETYPE_FLOAT;
attributeInfo.count = vertexList.length();
attributeInfo.tupleSize = 3;
HAPI_AddAttribute(
myInputAssetId, myInputObjectId, myInputGeoId,
"uv", &attributeInfo
);
HAPI_SetAttributeFloatData(
myInputAssetId, myInputObjectId, myInputGeoId,
"uv", &attributeInfo,
&vertexUVs.front(), 0, vertexList.length()
);
}
}
// Commit it
HAPI_CommitGeo(myInputAssetId, myInputObjectId, myInputGeoId);
delete[] vl;
delete[] fc;
}
<commit_msg>Add color sets support for input mesh<commit_after>#include "InputMesh.h"
#include <maya/MFnMesh.h>
#include <maya/MDataBlock.h>
#include <maya/MFloatArray.h>
#include <maya/MFloatPointArray.h>
#include <maya/MFloatVectorArray.h>
#include <maya/MIntArray.h>
#include <maya/MMatrix.h>
#include "util.h"
InputMesh::InputMesh(int assetId, int inputIdx) :
Input(assetId, inputIdx),
myInputObjectId(-1),
myInputGeoId(-1)
{
CHECK_HAPI(HAPI_CreateInputAsset(&myInputAssetId, NULL));
Util::statusCheckLoop();
myInputObjectId = 0;
myInputGeoId = 0;
CHECK_HAPI(HAPI_ConnectAssetGeometry(
myInputAssetId, myInputObjectId,
myAssetId, myInputIdx
));
}
InputMesh::~InputMesh()
{
CHECK_HAPI(HAPI_DestroyAsset(myInputAssetId));
}
Input::AssetInputType
InputMesh::assetInputType() const
{
return Input::AssetInputType_Mesh;
}
void
InputMesh::setInputTransform(MDataHandle &dataHandle)
{
MMatrix transformMatrix = dataHandle.asMatrix();
float matrix[16];
transformMatrix.get(reinterpret_cast<float(*)[4]>(matrix));
HAPI_TransformEuler transformEuler;
HAPI_ConvertMatrixToEuler(matrix, HAPI_SRT, HAPI_XYZ, &transformEuler);
HAPI_SetObjectTransform(
myInputAssetId, myInputObjectId,
&transformEuler
);
}
void
InputMesh::setInputGeo(
MDataBlock &dataBlock,
const MPlug &plug
)
{
MDataHandle dataHandle = dataBlock.inputValue(plug);
// extract mesh data from Maya
MObject meshObj = dataHandle.asMesh();
MFnMesh meshFn(meshObj);
// get face data
MIntArray faceCounts;
MIntArray vertexList;
meshFn.getVertices(faceCounts, vertexList);
Util::reverseWindingOrder(vertexList, faceCounts);
// set up part info
HAPI_PartInfo partInfo;
HAPI_PartInfo_Init(&partInfo);
partInfo.id = 0;
partInfo.faceCount = faceCounts.length();
partInfo.vertexCount = vertexList.length();
partInfo.pointCount = meshFn.numVertices();
// copy data to arrays
int * vl = new int[partInfo.vertexCount];
int * fc = new int[partInfo.faceCount];
vertexList.get(vl);
faceCounts.get(fc);
// Set the data
HAPI_SetPartInfo(
myInputAssetId, myInputObjectId, myInputGeoId,
&partInfo
);
HAPI_SetFaceCounts(
myInputAssetId, myInputObjectId, myInputGeoId,
fc, 0, partInfo.faceCount
);
HAPI_SetVertexList(
myInputAssetId, myInputObjectId, myInputGeoId,
vl, 0, partInfo.vertexCount
);
// Set position attributes.
HAPI_AttributeInfo pos_attr_info;
pos_attr_info.exists = true;
pos_attr_info.owner = HAPI_ATTROWNER_POINT;
pos_attr_info.storage = HAPI_STORAGETYPE_FLOAT;
pos_attr_info.count = meshFn.numVertices();
pos_attr_info.tupleSize = 3;
HAPI_AddAttribute(
myInputAssetId, myInputObjectId, myInputGeoId,
"P", &pos_attr_info
);
HAPI_SetAttributeFloatData(
myInputAssetId, myInputObjectId, myInputGeoId,
"P", &pos_attr_info,
meshFn.getRawPoints(NULL), 0, meshFn.numVertices()
);
// normals
{
// get normal IDs
MIntArray normalCounts;
MIntArray normalIds;
meshFn.getNormalIds(normalCounts, normalIds);
if(normalIds.length())
{
// reverse winding order
Util::reverseWindingOrder(normalIds, faceCounts);
// get normal values
const float* rawNormals = meshFn.getRawNormals(NULL);
// build the per-vertex normals
std::vector<float> vertexNormals;
vertexNormals.reserve(normalIds.length() * 3);
for(unsigned int i = 0; i < normalIds.length(); ++i)
{
vertexNormals.push_back(rawNormals[normalIds[i] * 3 + 0]);
vertexNormals.push_back(rawNormals[normalIds[i] * 3 + 1]);
vertexNormals.push_back(rawNormals[normalIds[i] * 3 + 2]);
}
// add and set it to HAPI
HAPI_AttributeInfo attributeInfo;
attributeInfo.exists = true;
attributeInfo.owner = HAPI_ATTROWNER_VERTEX;
attributeInfo.storage = HAPI_STORAGETYPE_FLOAT;
attributeInfo.count = normalIds.length();
attributeInfo.tupleSize = 3;
HAPI_AddAttribute(
myInputAssetId, myInputObjectId, myInputGeoId,
"N", &attributeInfo
);
HAPI_SetAttributeFloatData(myInputAssetId, myInputObjectId, myInputGeoId,
"N", &attributeInfo,
&vertexNormals.front(), 0, normalIds.length()
);
}
}
// UVs
{
// get UV IDs
MIntArray uvCounts;
MIntArray uvIds;
meshFn.getAssignedUVs(uvCounts, uvIds);
// if there's UVs
if(uvIds.length())
{
// reverse winding order
Util::reverseWindingOrder(uvIds, uvCounts);
// get UV values
MFloatArray uArray;
MFloatArray vArray;
meshFn.getUVs(uArray, vArray);
// build the per-vertex UVs
std::vector<float> vertexUVs;
vertexUVs.reserve(vertexList.length() * 3);
unsigned int uvIdIndex = 0;
for(unsigned int i = 0; i < uvCounts.length(); ++i)
{
if(uvCounts[i] == faceCounts[i])
{
// has UVs assigned
for(int j = 0; j < uvCounts[i]; ++j)
{
vertexUVs.push_back(uArray[uvIds[uvIdIndex]]);
vertexUVs.push_back(vArray[uvIds[uvIdIndex]]);
vertexUVs.push_back(0);
uvIdIndex++;
}
}
else
{
// no UVs assigned
for(int j = 0; j < faceCounts[i]; ++j)
{
vertexUVs.push_back(0);
vertexUVs.push_back(0);
vertexUVs.push_back(0);
}
}
}
// add and set it to HAPI
HAPI_AttributeInfo attributeInfo;
attributeInfo.exists = true;
attributeInfo.owner = HAPI_ATTROWNER_VERTEX;
attributeInfo.storage = HAPI_STORAGETYPE_FLOAT;
attributeInfo.count = vertexList.length();
attributeInfo.tupleSize = 3;
HAPI_AddAttribute(
myInputAssetId, myInputObjectId, myInputGeoId,
"uv", &attributeInfo
);
HAPI_SetAttributeFloatData(
myInputAssetId, myInputObjectId, myInputGeoId,
"uv", &attributeInfo,
&vertexUVs.front(), 0, vertexList.length()
);
}
}
// Colors and Alphas
{
MString currentColorSetName;
currentColorSetName = meshFn.currentColorSetName();
MStringArray colorSetNames;
meshFn.getColorSetNames(colorSetNames);
MColor defaultUnsetColor;
MColorArray colors;
std::vector<float> buffer;
for(unsigned int i = 0; i < colorSetNames.length(); i++)
{
const MString colorSetName = colorSetNames[i];
MString colorAttributeName;
MString alphaAttributeName;
if(colorSetName == currentColorSetName)
{
colorAttributeName = "Cd";
alphaAttributeName = "Alpha";
}
else
{
colorAttributeName = colorSetName;
alphaAttributeName = colorSetName + "Alpha";
}
bool hasColor = false;
bool hasAlpha = false;
{
MFnMesh::MColorRepresentation colorSetRepresentation =
meshFn.getColorRepresentation(colorSetName);
switch(colorSetRepresentation)
{
case MFnMesh::kAlpha:
hasAlpha = true;
break;
case MFnMesh::kRGB:
hasColor = true;
break;
case MFnMesh::kRGBA:
hasColor = true;
hasAlpha = true;
break;
}
}
CHECK_MSTATUS(meshFn.getFaceVertexColors(
colors,
&colorSetName,
&defaultUnsetColor
));
// reverse winding order
Util::reverseWindingOrder(colors, faceCounts);
if(hasColor)
{
buffer.resize(3 * vertexList.length());
for(unsigned int j = 0; j < vertexList.length(); j++)
{
buffer[j * 3 + 0] = colors[j].r;
buffer[j * 3 + 1] = colors[j].g;
buffer[j * 3 + 2] = colors[j].b;
}
// add and set Cd
HAPI_AttributeInfo colorAttributeInfo;
colorAttributeInfo.exists = true;
colorAttributeInfo.owner = HAPI_ATTROWNER_VERTEX;
colorAttributeInfo.storage = HAPI_STORAGETYPE_FLOAT;
colorAttributeInfo.count = vertexList.length();
colorAttributeInfo.tupleSize = 3;
HAPI_AddAttribute(
myInputAssetId, myInputObjectId, myInputGeoId,
colorAttributeName.asChar(), &colorAttributeInfo
);
HAPI_SetAttributeFloatData(
myInputAssetId, myInputObjectId, myInputGeoId,
colorAttributeName.asChar(), &colorAttributeInfo,
&buffer.front(), 0, vertexList.length()
);
}
if(hasAlpha)
{
buffer.resize(vertexList.length());
for(unsigned int j = 0; j < vertexList.length(); j++)
{
buffer[j] = colors[j].a;
}
// add and set Alpha
HAPI_AttributeInfo alphaAttributeInfo;
alphaAttributeInfo.exists = true;
alphaAttributeInfo.owner = HAPI_ATTROWNER_VERTEX;
alphaAttributeInfo.storage = HAPI_STORAGETYPE_FLOAT;
alphaAttributeInfo.count = vertexList.length();
alphaAttributeInfo.tupleSize = 1;
HAPI_AddAttribute(
myInputAssetId, myInputObjectId, myInputGeoId,
alphaAttributeName.asChar(), &alphaAttributeInfo
);
HAPI_SetAttributeFloatData(
myInputAssetId, myInputObjectId, myInputGeoId,
alphaAttributeName.asChar(), &alphaAttributeInfo,
&buffer.front(), 0, vertexList.length()
);
}
}
}
// Commit it
HAPI_CommitGeo(myInputAssetId, myInputObjectId, myInputGeoId);
delete[] vl;
delete[] fc;
}
<|endoftext|> |
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2013-2019 Winlin
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 <srs_utest_app.hpp>
using namespace std;
#include <srs_kernel_error.hpp>
#include <srs_app_fragment.hpp>
// Disable coroutine test for OSX.
#if !defined(SRS_OSX)
#include <srs_app_st.hpp>
VOID TEST(AppCoroutineTest, Dummy)
{
SrsDummyCoroutine dc;
if (true) {
EXPECT_EQ(0, dc.cid());
srs_error_t err = dc.pull();
EXPECT_TRUE(err != srs_success);
EXPECT_TRUE(ERROR_THREAD_DUMMY == srs_error_code(err));
srs_freep(err);
err = dc.start();
EXPECT_TRUE(err != srs_success);
EXPECT_TRUE(ERROR_THREAD_DUMMY == srs_error_code(err));
srs_freep(err);
}
if (true) {
dc.stop();
EXPECT_EQ(0, dc.cid());
srs_error_t err = dc.pull();
EXPECT_TRUE(err != srs_success);
EXPECT_TRUE(ERROR_THREAD_DUMMY == srs_error_code(err));
srs_freep(err);
err = dc.start();
EXPECT_TRUE(err != srs_success);
EXPECT_TRUE(ERROR_THREAD_DUMMY == srs_error_code(err));
srs_freep(err);
}
if (true) {
dc.interrupt();
EXPECT_EQ(0, dc.cid());
srs_error_t err = dc.pull();
EXPECT_TRUE(err != srs_success);
EXPECT_TRUE(ERROR_THREAD_DUMMY == srs_error_code(err));
srs_freep(err);
err = dc.start();
EXPECT_TRUE(err != srs_success);
EXPECT_TRUE(ERROR_THREAD_DUMMY == srs_error_code(err));
srs_freep(err);
}
}
class MockCoroutineHandler : public ISrsCoroutineHandler {
public:
SrsSTCoroutine* trd;
srs_error_t err;
srs_cond_t running;
srs_cond_t exited;
int cid;
// Quit without error.
bool quit;
public:
MockCoroutineHandler() : trd(NULL), err(srs_success), cid(0), quit(false) {
running = srs_cond_new();
exited = srs_cond_new();
}
virtual ~MockCoroutineHandler() {
srs_cond_destroy(running);
srs_cond_destroy(exited);
}
public:
virtual srs_error_t cycle() {
srs_error_t r0 = srs_success;
srs_cond_signal(running);
cid = _srs_context->get_id();
while (!quit && (r0 = trd->pull()) == srs_success && err == srs_success) {
srs_usleep(10 * SRS_UTIME_MILLISECONDS);
}
srs_cond_signal(exited);
if (err != srs_success) {
srs_freep(r0);
return err;
}
return r0;
}
};
VOID TEST(AppCoroutineTest, StartStop)
{
if (true) {
MockCoroutineHandler ch;
SrsSTCoroutine sc("test", &ch);
ch.trd = ≻
EXPECT_EQ(0, sc.cid());
// Thread stop after created.
sc.stop();
EXPECT_EQ(0, sc.cid());
srs_error_t err = sc.pull();
EXPECT_TRUE(srs_success != err);
EXPECT_TRUE(ERROR_THREAD_TERMINATED == srs_error_code(err));
srs_freep(err);
// Should never reuse a disposed thread.
err = sc.start();
EXPECT_TRUE(srs_success != err);
EXPECT_TRUE(ERROR_THREAD_DISPOSED == srs_error_code(err));
srs_freep(err);
}
if (true) {
MockCoroutineHandler ch;
SrsSTCoroutine sc("test", &ch);
ch.trd = ≻
EXPECT_EQ(0, sc.cid());
EXPECT_TRUE(srs_success == sc.start());
EXPECT_TRUE(srs_success == sc.pull());
srs_cond_timedwait(ch.running, 100 * SRS_UTIME_MILLISECONDS);
EXPECT_TRUE(sc.cid() > 0);
// Thread stop after started.
sc.stop();
srs_error_t err = sc.pull();
EXPECT_TRUE(srs_success != err);
EXPECT_TRUE(ERROR_THREAD_INTERRUPED == srs_error_code(err));
srs_freep(err);
// Should never reuse a disposed thread.
err = sc.start();
EXPECT_TRUE(srs_success != err);
EXPECT_TRUE(ERROR_THREAD_DISPOSED == srs_error_code(err));
srs_freep(err);
}
if (true) {
MockCoroutineHandler ch;
SrsSTCoroutine sc("test", &ch);
ch.trd = ≻
EXPECT_EQ(0, sc.cid());
EXPECT_TRUE(srs_success == sc.start());
EXPECT_TRUE(srs_success == sc.pull());
// Error when start multiple times.
srs_error_t err = sc.start();
EXPECT_TRUE(srs_success != err);
EXPECT_TRUE(ERROR_THREAD_STARTED == srs_error_code(err));
srs_freep(err);
err = sc.pull();
EXPECT_TRUE(srs_success != err);
EXPECT_TRUE(ERROR_THREAD_STARTED == srs_error_code(err));
srs_freep(err);
}
}
VOID TEST(AppCoroutineTest, Cycle)
{
if (true) {
MockCoroutineHandler ch;
SrsSTCoroutine sc("test", &ch);
ch.trd = ≻
EXPECT_TRUE(srs_success == sc.start());
EXPECT_TRUE(srs_success == sc.pull());
// Set cycle to error.
ch.err = srs_error_new(-1, "cycle");
srs_cond_timedwait(ch.running, 100 * SRS_UTIME_MILLISECONDS);
// The cycle error should be pulled.
srs_error_t err = sc.pull();
EXPECT_TRUE(srs_success != err);
EXPECT_TRUE(-1 == srs_error_code(err));
srs_freep(err);
}
if (true) {
MockCoroutineHandler ch;
SrsSTCoroutine sc("test", &ch, 250);
ch.trd = ≻
EXPECT_EQ(250, sc.cid());
EXPECT_TRUE(srs_success == sc.start());
EXPECT_TRUE(srs_success == sc.pull());
// After running, the cid in cycle should equal to the thread.
srs_cond_timedwait(ch.running, 100 * SRS_UTIME_MILLISECONDS);
EXPECT_EQ(250, ch.cid);
}
if (true) {
MockCoroutineHandler ch;
SrsSTCoroutine sc("test", &ch);
ch.trd = ≻
EXPECT_TRUE(srs_success == sc.start());
EXPECT_TRUE(srs_success == sc.pull());
srs_cond_timedwait(ch.running, 100 * SRS_UTIME_MILLISECONDS);
// Interrupt thread, set err to interrupted.
sc.interrupt();
// Set cycle to error.
ch.err = srs_error_new(-1, "cycle");
// When thread terminated, thread will get its error.
srs_cond_timedwait(ch.exited, 100 * SRS_UTIME_MILLISECONDS);
// Override the error by cycle error.
sc.stop();
// Should be cycle error.
srs_error_t err = sc.pull();
EXPECT_TRUE(srs_success != err);
EXPECT_TRUE(-1 == srs_error_code(err));
srs_freep(err);
}
if (true) {
MockCoroutineHandler ch;
SrsSTCoroutine sc("test", &ch);
ch.trd = ≻
EXPECT_TRUE(srs_success == sc.start());
EXPECT_TRUE(srs_success == sc.pull());
// Quit without error.
ch.quit = true;
// Wait for thread to done.
srs_cond_timedwait(ch.exited, 100 * SRS_UTIME_MILLISECONDS);
// Override the error by cycle error.
sc.stop();
// Should be cycle error.
srs_error_t err = sc.pull();
EXPECT_TRUE(srs_success == err);
srs_freep(err);
}
}
void* mock_st_thread_create(void *(*/*start*/)(void *arg), void */*arg*/, int /*joinable*/, int /*stack_size*/) {
return NULL;
}
VOID TEST(AppCoroutineTest, StartThread)
{
MockCoroutineHandler ch;
SrsSTCoroutine sc("test", &ch);
ch.trd = ≻
_ST_THREAD_CREATE_PFN ov = _pfn_st_thread_create;
_pfn_st_thread_create = (_ST_THREAD_CREATE_PFN)mock_st_thread_create;
srs_error_t err = sc.start();
_pfn_st_thread_create = ov;
EXPECT_TRUE(srs_success != err);
EXPECT_TRUE(ERROR_ST_CREATE_CYCLE_THREAD == srs_error_code(err));
srs_freep(err);
}
#endif
VOID TEST(AppFragmentTest, CheckDuration)
{
if (true) {
SrsFragment frg;
EXPECT_EQ(-1, frg.start_dts);
EXPECT_EQ(0, frg.dur);
EXPECT_FALSE(frg.sequence_header);
}
if (true) {
SrsFragment frg;
frg.append(0);
EXPECT_EQ(0, frg.duration());
frg.append(10);
EXPECT_EQ(10 * SRS_UTIME_MILLISECONDS, frg.duration());
frg.append(99);
EXPECT_EQ(99 * SRS_UTIME_MILLISECONDS, frg.duration());
frg.append(0x7fffffffLL);
EXPECT_EQ(0x7fffffffLL * SRS_UTIME_MILLISECONDS, frg.duration());
frg.append(0xffffffffLL);
EXPECT_EQ(0xffffffffLL * SRS_UTIME_MILLISECONDS, frg.duration());
frg.append(0x20c49ba5e353f7LL);
EXPECT_EQ(0x20c49ba5e353f7LL * SRS_UTIME_MILLISECONDS, frg.duration());
}
if (true) {
SrsFragment frg;
frg.append(0);
EXPECT_EQ(0, frg.duration());
frg.append(0x7fffffffffffffffLL);
EXPECT_EQ(0, frg.duration());
}
if (true) {
SrsFragment frg;
frg.append(100);
EXPECT_EQ(0, frg.duration());
frg.append(10);
EXPECT_EQ(0, frg.duration());
frg.append(100);
EXPECT_EQ(90 * SRS_UTIME_MILLISECONDS, frg.duration());
}
if (true) {
SrsFragment frg;
frg.append(-10);
EXPECT_EQ(0, frg.duration());
frg.append(-5);
EXPECT_EQ(0, frg.duration());
frg.append(10);
EXPECT_EQ(10 * SRS_UTIME_MILLISECONDS, frg.duration());
}
}
<commit_msg>Add utest for tcp server<commit_after>/*
The MIT License (MIT)
Copyright (c) 2013-2019 Winlin
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 <srs_utest_app.hpp>
using namespace std;
#include <srs_kernel_error.hpp>
#include <srs_app_fragment.hpp>
// Disable coroutine test for OSX.
#if !defined(SRS_OSX)
#include <srs_app_st.hpp>
VOID TEST(AppCoroutineTest, Dummy)
{
SrsDummyCoroutine dc;
if (true) {
EXPECT_EQ(0, dc.cid());
srs_error_t err = dc.pull();
EXPECT_TRUE(err != srs_success);
EXPECT_TRUE(ERROR_THREAD_DUMMY == srs_error_code(err));
srs_freep(err);
err = dc.start();
EXPECT_TRUE(err != srs_success);
EXPECT_TRUE(ERROR_THREAD_DUMMY == srs_error_code(err));
srs_freep(err);
}
if (true) {
dc.stop();
EXPECT_EQ(0, dc.cid());
srs_error_t err = dc.pull();
EXPECT_TRUE(err != srs_success);
EXPECT_TRUE(ERROR_THREAD_DUMMY == srs_error_code(err));
srs_freep(err);
err = dc.start();
EXPECT_TRUE(err != srs_success);
EXPECT_TRUE(ERROR_THREAD_DUMMY == srs_error_code(err));
srs_freep(err);
}
if (true) {
dc.interrupt();
EXPECT_EQ(0, dc.cid());
srs_error_t err = dc.pull();
EXPECT_TRUE(err != srs_success);
EXPECT_TRUE(ERROR_THREAD_DUMMY == srs_error_code(err));
srs_freep(err);
err = dc.start();
EXPECT_TRUE(err != srs_success);
EXPECT_TRUE(ERROR_THREAD_DUMMY == srs_error_code(err));
srs_freep(err);
}
}
class MockCoroutineHandler : public ISrsCoroutineHandler {
public:
SrsSTCoroutine* trd;
srs_error_t err;
srs_cond_t running;
srs_cond_t exited;
int cid;
// Quit without error.
bool quit;
public:
MockCoroutineHandler() : trd(NULL), err(srs_success), cid(0), quit(false) {
running = srs_cond_new();
exited = srs_cond_new();
}
virtual ~MockCoroutineHandler() {
srs_cond_destroy(running);
srs_cond_destroy(exited);
}
public:
virtual srs_error_t cycle() {
srs_error_t r0 = srs_success;
srs_cond_signal(running);
cid = _srs_context->get_id();
while (!quit && (r0 = trd->pull()) == srs_success && err == srs_success) {
srs_usleep(10 * SRS_UTIME_MILLISECONDS);
}
srs_cond_signal(exited);
if (err != srs_success) {
srs_freep(r0);
return err;
}
return r0;
}
};
VOID TEST(AppCoroutineTest, StartStop)
{
if (true) {
MockCoroutineHandler ch;
SrsSTCoroutine sc("test", &ch);
ch.trd = ≻
EXPECT_EQ(0, sc.cid());
// Thread stop after created.
sc.stop();
EXPECT_EQ(0, sc.cid());
srs_error_t err = sc.pull();
EXPECT_TRUE(srs_success != err);
EXPECT_TRUE(ERROR_THREAD_TERMINATED == srs_error_code(err));
srs_freep(err);
// Should never reuse a disposed thread.
err = sc.start();
EXPECT_TRUE(srs_success != err);
EXPECT_TRUE(ERROR_THREAD_DISPOSED == srs_error_code(err));
srs_freep(err);
}
if (true) {
MockCoroutineHandler ch;
SrsSTCoroutine sc("test", &ch);
ch.trd = ≻
EXPECT_EQ(0, sc.cid());
EXPECT_TRUE(srs_success == sc.start());
EXPECT_TRUE(srs_success == sc.pull());
srs_cond_timedwait(ch.running, 100 * SRS_UTIME_MILLISECONDS);
EXPECT_TRUE(sc.cid() > 0);
// Thread stop after started.
sc.stop();
srs_error_t err = sc.pull();
EXPECT_TRUE(srs_success != err);
EXPECT_TRUE(ERROR_THREAD_INTERRUPED == srs_error_code(err));
srs_freep(err);
// Should never reuse a disposed thread.
err = sc.start();
EXPECT_TRUE(srs_success != err);
EXPECT_TRUE(ERROR_THREAD_DISPOSED == srs_error_code(err));
srs_freep(err);
}
if (true) {
MockCoroutineHandler ch;
SrsSTCoroutine sc("test", &ch);
ch.trd = ≻
EXPECT_EQ(0, sc.cid());
EXPECT_TRUE(srs_success == sc.start());
EXPECT_TRUE(srs_success == sc.pull());
// Error when start multiple times.
srs_error_t err = sc.start();
EXPECT_TRUE(srs_success != err);
EXPECT_TRUE(ERROR_THREAD_STARTED == srs_error_code(err));
srs_freep(err);
err = sc.pull();
EXPECT_TRUE(srs_success != err);
EXPECT_TRUE(ERROR_THREAD_STARTED == srs_error_code(err));
srs_freep(err);
}
}
VOID TEST(AppCoroutineTest, Cycle)
{
if (true) {
MockCoroutineHandler ch;
SrsSTCoroutine sc("test", &ch);
ch.trd = ≻
EXPECT_TRUE(srs_success == sc.start());
EXPECT_TRUE(srs_success == sc.pull());
// Set cycle to error.
ch.err = srs_error_new(-1, "cycle");
srs_cond_timedwait(ch.running, 100 * SRS_UTIME_MILLISECONDS);
// The cycle error should be pulled.
srs_error_t err = sc.pull();
EXPECT_TRUE(srs_success != err);
EXPECT_TRUE(-1 == srs_error_code(err));
srs_freep(err);
}
if (true) {
MockCoroutineHandler ch;
SrsSTCoroutine sc("test", &ch, 250);
ch.trd = ≻
EXPECT_EQ(250, sc.cid());
EXPECT_TRUE(srs_success == sc.start());
EXPECT_TRUE(srs_success == sc.pull());
// After running, the cid in cycle should equal to the thread.
srs_cond_timedwait(ch.running, 100 * SRS_UTIME_MILLISECONDS);
EXPECT_EQ(250, ch.cid);
}
if (true) {
MockCoroutineHandler ch;
SrsSTCoroutine sc("test", &ch);
ch.trd = ≻
EXPECT_TRUE(srs_success == sc.start());
EXPECT_TRUE(srs_success == sc.pull());
srs_cond_timedwait(ch.running, 100 * SRS_UTIME_MILLISECONDS);
// Interrupt thread, set err to interrupted.
sc.interrupt();
// Set cycle to error.
ch.err = srs_error_new(-1, "cycle");
// When thread terminated, thread will get its error.
srs_cond_timedwait(ch.exited, 100 * SRS_UTIME_MILLISECONDS);
// Override the error by cycle error.
sc.stop();
// Should be cycle error.
srs_error_t err = sc.pull();
EXPECT_TRUE(srs_success != err);
EXPECT_TRUE(-1 == srs_error_code(err));
srs_freep(err);
}
if (true) {
MockCoroutineHandler ch;
SrsSTCoroutine sc("test", &ch);
ch.trd = ≻
EXPECT_TRUE(srs_success == sc.start());
EXPECT_TRUE(srs_success == sc.pull());
// Quit without error.
ch.quit = true;
// Wait for thread to done.
srs_cond_timedwait(ch.exited, 100 * SRS_UTIME_MILLISECONDS);
// Override the error by cycle error.
sc.stop();
// Should be cycle error.
srs_error_t err = sc.pull();
EXPECT_TRUE(srs_success == err);
srs_freep(err);
}
}
void* mock_st_thread_create(void *(*/*start*/)(void *arg), void */*arg*/, int /*joinable*/, int /*stack_size*/) {
return NULL;
}
VOID TEST(AppCoroutineTest, StartThread)
{
MockCoroutineHandler ch;
SrsSTCoroutine sc("test", &ch);
ch.trd = ≻
_ST_THREAD_CREATE_PFN ov = _pfn_st_thread_create;
_pfn_st_thread_create = (_ST_THREAD_CREATE_PFN)mock_st_thread_create;
srs_error_t err = sc.start();
_pfn_st_thread_create = ov;
EXPECT_TRUE(srs_success != err);
EXPECT_TRUE(ERROR_ST_CREATE_CYCLE_THREAD == srs_error_code(err));
srs_freep(err);
}
#endif
VOID TEST(AppFragmentTest, CheckDuration)
{
if (true) {
SrsFragment frg;
EXPECT_EQ(-1, frg.start_dts);
EXPECT_EQ(0, frg.dur);
EXPECT_FALSE(frg.sequence_header);
}
if (true) {
SrsFragment frg;
frg.append(0);
EXPECT_EQ(0, frg.duration());
frg.append(10);
EXPECT_EQ(10 * SRS_UTIME_MILLISECONDS, frg.duration());
frg.append(99);
EXPECT_EQ(99 * SRS_UTIME_MILLISECONDS, frg.duration());
frg.append(0x7fffffffLL);
EXPECT_EQ(0x7fffffffLL * SRS_UTIME_MILLISECONDS, frg.duration());
frg.append(0xffffffffLL);
EXPECT_EQ(0xffffffffLL * SRS_UTIME_MILLISECONDS, frg.duration());
frg.append(0x20c49ba5e353f7LL);
EXPECT_EQ(0x20c49ba5e353f7LL * SRS_UTIME_MILLISECONDS, frg.duration());
}
if (true) {
SrsFragment frg;
frg.append(0);
EXPECT_EQ(0, frg.duration());
frg.append(0x7fffffffffffffffLL);
EXPECT_EQ(0, frg.duration());
}
if (true) {
SrsFragment frg;
frg.append(100);
EXPECT_EQ(0, frg.duration());
frg.append(10);
EXPECT_EQ(0, frg.duration());
frg.append(100);
EXPECT_EQ(90 * SRS_UTIME_MILLISECONDS, frg.duration());
}
if (true) {
SrsFragment frg;
frg.append(-10);
EXPECT_EQ(0, frg.duration());
frg.append(-5);
EXPECT_EQ(0, frg.duration());
frg.append(10);
EXPECT_EQ(10 * SRS_UTIME_MILLISECONDS, frg.duration());
}
}
#define MOCK_LISTEN_PORT 11935
VOID TEST(TCPServerTest, PingPong)
{
}
<|endoftext|> |
<commit_before>// Open a FITS file whose primary array represents
// a spectrum (flux vs wavelength)
void FITS_tutorial5()
{
TVectorD *v;
printf("\n\n--------------------------------\n");
printf("WELCOME TO FITS tutorial #5 !!!!\n");
printf("--------------------------------\n");
printf("We're gonna open a FITS file that contains a\n");
printf("table with 9 rows and 8 columns. Column 4 has name\n");
printf("'mag' and contains a vector of 6 numeric components.\n");
printf("The values of vectors in rows 1 and 2 (column 4) are:\n");
printf("Row1: (99.0, 24.768, 23.215, 21.68, 21.076, 20.857)\n");
printf("Row2: (99.0, 21.689, 20.206, 18.86, 18.32 , 18.128 )\n");
printf("WARNING: when coding, row and column indices start from 0\n");
if (!gROOT->IsBatch()) {
printf("Press ENTER to start..."); getchar();
printf("\n");
}
//Open the table
TFITSHDU *hdu = new TFITSHDU("sample4.fits[1]");
if (hdu == 0) {
printf("ERROR: could not access the HDU\n"); return;
}
//Read vectors at rows 1 and 2 (indices 0 and 1)
TVectorD *vecs[2];
vecs[0] = hdu->GetTabRealVectorCell(0, "mag");
vecs[1] = hdu->GetTabRealVectorCell(1, "mag");
for (int iVec=0; iVec < 2; iVec++) {
printf("Vector %d = (", iVec+1);
v = vecs[iVec];
for(int i=0; i < v->GetNoElements(); i++) {
if (i>0) printf(", ");
printf("%lg", (*v)[i]); //NOTE: the asterisk is for using the overloaded [] operator of the TVectorD object
}
printf(")\n");
}
printf("\nBONUS EXAMPLE: we're gonna dump all rows using\n");
printf("the function GetTabRealVectorCells()\n");
printf("Press ENTER to continue..."); getchar();
TObjArray *vectorCollection = hdu->GetTabRealVectorCells("mag");
for (int iVec=0; iVec < vectorCollection->GetEntriesFast(); iVec++) {
printf("Vector %d = (", iVec+1);
v = (TVectorD *) (*vectorCollection)[iVec]; //NOTE: the asterisk is for using the overloaded [] operator of the TObjArray object
for(int i=0; i < v->GetNoElements(); i++) {
if (i>0) printf(", ");
printf("%lg", (*v)[i]); //NOTE: the asterisk is for using the overloaded [] operator of the TVectorD object
}
printf(")\n");
}
//Clean up
delete vecs[0];
delete vecs[1];
delete vectorCollection;
delete hdu;
}
<commit_msg>no more getchar() so auto doc generation does not fail.<commit_after>// Open a FITS file whose primary array represents
// a spectrum (flux vs wavelength)
void FITS_tutorial5()
{
TVectorD *v;
printf("\n\n--------------------------------\n");
printf("WELCOME TO FITS tutorial #5 !!!!\n");
printf("--------------------------------\n");
printf("We're gonna open a FITS file that contains a\n");
printf("table with 9 rows and 8 columns. Column 4 has name\n");
printf("'mag' and contains a vector of 6 numeric components.\n");
printf("The values of vectors in rows 1 and 2 (column 4) are:\n");
printf("Row1: (99.0, 24.768, 23.215, 21.68, 21.076, 20.857)\n");
printf("Row2: (99.0, 21.689, 20.206, 18.86, 18.32 , 18.128 )\n");
printf("WARNING: when coding, row and column indices start from 0\n");
if (!gROOT->IsBatch()) {
//printf("Press ENTER to start..."); getchar();
//printf("\n");
}
//Open the table
TFITSHDU *hdu = new TFITSHDU("sample4.fits[1]");
if (hdu == 0) {
printf("ERROR: could not access the HDU\n"); return;
}
//Read vectors at rows 1 and 2 (indices 0 and 1)
TVectorD *vecs[2];
vecs[0] = hdu->GetTabRealVectorCell(0, "mag");
vecs[1] = hdu->GetTabRealVectorCell(1, "mag");
for (int iVec=0; iVec < 2; iVec++) {
printf("Vector %d = (", iVec+1);
v = vecs[iVec];
for(int i=0; i < v->GetNoElements(); i++) {
if (i>0) printf(", ");
printf("%lg", (*v)[i]); //NOTE: the asterisk is for using the overloaded [] operator of the TVectorD object
}
printf(")\n");
}
printf("\nBONUS EXAMPLE: we're gonna dump all rows using\n");
printf("the function GetTabRealVectorCells()\n");
//printf("Press ENTER to continue..."); getchar();
TObjArray *vectorCollection = hdu->GetTabRealVectorCells("mag");
for (int iVec=0; iVec < vectorCollection->GetEntriesFast(); iVec++) {
printf("Vector %d = (", iVec+1);
v = (TVectorD *) (*vectorCollection)[iVec]; //NOTE: the asterisk is for using the overloaded [] operator of the TObjArray object
for(int i=0; i < v->GetNoElements(); i++) {
if (i>0) printf(", ");
printf("%lg", (*v)[i]); //NOTE: the asterisk is for using the overloaded [] operator of the TVectorD object
}
printf(")\n");
}
//Clean up
delete vecs[0];
delete vecs[1];
delete vectorCollection;
delete hdu;
}
<|endoftext|> |
<commit_before>// 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 "util/codec.h"
#include <boost/assign/list_of.hpp>
#include "util/compress.h"
#include "util/decompress.h"
#include "gen-cpp/Descriptors_types.h"
#include "gen-cpp/Descriptors_constants.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace impala;
const char* const Codec::DEFAULT_COMPRESSION =
"org.apache.hadoop.io.compress.DefaultCodec";
const char* const Codec::GZIP_COMPRESSION =
"org.apache.hadoop.io.compress.GzipCodec";
const char* const Codec::BZIP2_COMPRESSION =
"org.apache.hadoop.io.compress.BZip2Codec";
const char* const Codec::SNAPPY_COMPRESSION =
"org.apache.hadoop.io.compress.SnappyCodec";
const Codec::CodecMap Codec::CODEC_MAP = map_list_of
("", THdfsCompression::NONE)
(Codec::DEFAULT_COMPRESSION, THdfsCompression::DEFAULT)
(Codec::GZIP_COMPRESSION, THdfsCompression::GZIP)
(Codec::BZIP2_COMPRESSION, THdfsCompression::BZIP2)
(Codec::SNAPPY_COMPRESSION, THdfsCompression::SNAPPY_BLOCKED);
string Codec::GetCodecName(THdfsCompression::type type) {
map<const string, THdfsCompression::type>::const_iterator im;
for (im = g_Descriptors_constants.COMPRESSION_MAP.begin();
im != g_Descriptors_constants.COMPRESSION_MAP.end(); ++im) {
if (im->second == type) return im->first;
}
DCHECK(im != g_Descriptors_constants.COMPRESSION_MAP.end());
return "INVALID";
}
Status Codec::CreateCompressor(RuntimeState* runtime_state, MemPool* mem_pool,
bool reuse, const string& codec,
scoped_ptr<Codec>* compressor) {
map<const string, const THdfsCompression::type>::const_iterator
type = CODEC_MAP.find(codec);
if (type == CODEC_MAP.end()) {
stringstream ss;
ss << "Unknown Codec: " << codec;
return Status(ss.str());
}
Codec* comp;
RETURN_IF_ERROR(
CreateCompressor(runtime_state, mem_pool, reuse, type->second, &comp));
compressor->reset(comp);
return Status::OK;
}
Status Codec::CreateCompressor(RuntimeState* runtime_state, MemPool* mem_pool,
bool reuse, THdfsCompression::type format,
scoped_ptr<Codec>* compressor) {
Codec* comp;
RETURN_IF_ERROR(
CreateCompressor(runtime_state, mem_pool, reuse, format, &comp));
compressor->reset(comp);
return Status::OK;
}
Status Codec::CreateCompressor(RuntimeState* runtime_state, MemPool* mem_pool,
bool reuse, THdfsCompression::type format,
Codec** compressor) {
switch (format) {
case THdfsCompression::NONE:
*compressor = NULL;
return Status::OK;
case THdfsCompression::GZIP:
*compressor = new GzipCompressor(GzipCompressor::GZIP, mem_pool, reuse);
break;
case THdfsCompression::DEFAULT:
*compressor = new GzipCompressor(GzipCompressor::ZLIB, mem_pool, reuse);
break;
case THdfsCompression::DEFLATE:
*compressor = new GzipCompressor(GzipCompressor::DEFLATE, mem_pool, reuse);
break;
case THdfsCompression::BZIP2:
*compressor = new BzipCompressor(mem_pool, reuse);
break;
case THdfsCompression::SNAPPY_BLOCKED:
*compressor = new SnappyBlockCompressor(mem_pool, reuse);
break;
case THdfsCompression::SNAPPY:
*compressor = new SnappyCompressor(mem_pool, reuse);
break;
}
return (*compressor)->Init();
}
Status Codec::CreateDecompressor(RuntimeState* runtime_state, MemPool* mem_pool,
bool reuse, const string& codec,
scoped_ptr<Codec>* decompressor) {
map<const string, const THdfsCompression::type>::const_iterator
type = CODEC_MAP.find(codec);
if (type == CODEC_MAP.end()) {
stringstream ss;
ss << "Unknown Codec: " << codec;
return Status(ss.str());
}
Codec* decom;
RETURN_IF_ERROR(
CreateDecompressor(runtime_state, mem_pool, reuse, type->second, &decom));
decompressor->reset(decom);
return Status::OK;
}
Status Codec::CreateDecompressor(RuntimeState* runtime_state, MemPool* mem_pool,
bool reuse, THdfsCompression::type format,
scoped_ptr<Codec>* decompressor) {
Codec* decom;
RETURN_IF_ERROR(
CreateDecompressor(runtime_state, mem_pool, reuse, format, &decom));
decompressor->reset(decom);
return Status::OK;
}
Status Codec::CreateDecompressor(RuntimeState* runtime_state, MemPool* mem_pool,
bool reuse, THdfsCompression::type format,
Codec** decompressor) {
switch (format) {
case THdfsCompression::NONE:
*decompressor = NULL;
return Status::OK;
case THdfsCompression::DEFAULT:
case THdfsCompression::GZIP:
*decompressor = new GzipDecompressor(mem_pool, reuse, false);
break;
case THdfsCompression::DEFLATE:
*decompressor = new GzipDecompressor(mem_pool, reuse, true);
break;
case THdfsCompression::BZIP2:
*decompressor = new BzipDecompressor(mem_pool, reuse);
break;
case THdfsCompression::SNAPPY_BLOCKED:
*decompressor = new SnappyBlockDecompressor(mem_pool, reuse);
break;
case THdfsCompression::SNAPPY:
*decompressor = new SnappyDecompressor(mem_pool, reuse);
break;
}
return (*decompressor)->Init();
}
Codec::Codec(MemPool* mem_pool, bool reuse_buffer)
: memory_pool_(mem_pool),
reuse_buffer_(reuse_buffer),
out_buffer_(NULL),
buffer_length_(0) {
}
<commit_msg>Make unsupported codec message a little clearer.<commit_after>// 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 "util/codec.h"
#include <boost/assign/list_of.hpp>
#include "util/compress.h"
#include "util/decompress.h"
#include "gen-cpp/Descriptors_types.h"
#include "gen-cpp/Descriptors_constants.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace impala;
const char* const Codec::DEFAULT_COMPRESSION =
"org.apache.hadoop.io.compress.DefaultCodec";
const char* const Codec::GZIP_COMPRESSION =
"org.apache.hadoop.io.compress.GzipCodec";
const char* const Codec::BZIP2_COMPRESSION =
"org.apache.hadoop.io.compress.BZip2Codec";
const char* const Codec::SNAPPY_COMPRESSION =
"org.apache.hadoop.io.compress.SnappyCodec";
const char* const UNKNOWN_CODEC_ERROR =
"This compression codec is currently unsupported: ";
const Codec::CodecMap Codec::CODEC_MAP = map_list_of
("", THdfsCompression::NONE)
(Codec::DEFAULT_COMPRESSION, THdfsCompression::DEFAULT)
(Codec::GZIP_COMPRESSION, THdfsCompression::GZIP)
(Codec::BZIP2_COMPRESSION, THdfsCompression::BZIP2)
(Codec::SNAPPY_COMPRESSION, THdfsCompression::SNAPPY_BLOCKED);
string Codec::GetCodecName(THdfsCompression::type type) {
map<const string, THdfsCompression::type>::const_iterator im;
for (im = g_Descriptors_constants.COMPRESSION_MAP.begin();
im != g_Descriptors_constants.COMPRESSION_MAP.end(); ++im) {
if (im->second == type) return im->first;
}
DCHECK(im != g_Descriptors_constants.COMPRESSION_MAP.end());
return "INVALID";
}
Status Codec::CreateCompressor(RuntimeState* runtime_state, MemPool* mem_pool,
bool reuse, const string& codec,
scoped_ptr<Codec>* compressor) {
map<const string, const THdfsCompression::type>::const_iterator
type = CODEC_MAP.find(codec);
if (type == CODEC_MAP.end()) {
stringstream ss;
ss << UNKNOWN_CODEC_ERROR << codec;
return Status(ss.str());
}
Codec* comp;
RETURN_IF_ERROR(
CreateCompressor(runtime_state, mem_pool, reuse, type->second, &comp));
compressor->reset(comp);
return Status::OK;
}
Status Codec::CreateCompressor(RuntimeState* runtime_state, MemPool* mem_pool,
bool reuse, THdfsCompression::type format,
scoped_ptr<Codec>* compressor) {
Codec* comp;
RETURN_IF_ERROR(
CreateCompressor(runtime_state, mem_pool, reuse, format, &comp));
compressor->reset(comp);
return Status::OK;
}
Status Codec::CreateCompressor(RuntimeState* runtime_state, MemPool* mem_pool,
bool reuse, THdfsCompression::type format,
Codec** compressor) {
switch (format) {
case THdfsCompression::NONE:
*compressor = NULL;
return Status::OK;
case THdfsCompression::GZIP:
*compressor = new GzipCompressor(GzipCompressor::GZIP, mem_pool, reuse);
break;
case THdfsCompression::DEFAULT:
*compressor = new GzipCompressor(GzipCompressor::ZLIB, mem_pool, reuse);
break;
case THdfsCompression::DEFLATE:
*compressor = new GzipCompressor(GzipCompressor::DEFLATE, mem_pool, reuse);
break;
case THdfsCompression::BZIP2:
*compressor = new BzipCompressor(mem_pool, reuse);
break;
case THdfsCompression::SNAPPY_BLOCKED:
*compressor = new SnappyBlockCompressor(mem_pool, reuse);
break;
case THdfsCompression::SNAPPY:
*compressor = new SnappyCompressor(mem_pool, reuse);
break;
}
return (*compressor)->Init();
}
Status Codec::CreateDecompressor(RuntimeState* runtime_state, MemPool* mem_pool,
bool reuse, const string& codec,
scoped_ptr<Codec>* decompressor) {
map<const string, const THdfsCompression::type>::const_iterator
type = CODEC_MAP.find(codec);
if (type == CODEC_MAP.end()) {
stringstream ss;
ss << UNKNOWN_CODEC_ERROR << codec;
return Status(ss.str());
}
Codec* decom;
RETURN_IF_ERROR(
CreateDecompressor(runtime_state, mem_pool, reuse, type->second, &decom));
decompressor->reset(decom);
return Status::OK;
}
Status Codec::CreateDecompressor(RuntimeState* runtime_state, MemPool* mem_pool,
bool reuse, THdfsCompression::type format,
scoped_ptr<Codec>* decompressor) {
Codec* decom;
RETURN_IF_ERROR(
CreateDecompressor(runtime_state, mem_pool, reuse, format, &decom));
decompressor->reset(decom);
return Status::OK;
}
Status Codec::CreateDecompressor(RuntimeState* runtime_state, MemPool* mem_pool,
bool reuse, THdfsCompression::type format,
Codec** decompressor) {
switch (format) {
case THdfsCompression::NONE:
*decompressor = NULL;
return Status::OK;
case THdfsCompression::DEFAULT:
case THdfsCompression::GZIP:
*decompressor = new GzipDecompressor(mem_pool, reuse, false);
break;
case THdfsCompression::DEFLATE:
*decompressor = new GzipDecompressor(mem_pool, reuse, true);
break;
case THdfsCompression::BZIP2:
*decompressor = new BzipDecompressor(mem_pool, reuse);
break;
case THdfsCompression::SNAPPY_BLOCKED:
*decompressor = new SnappyBlockDecompressor(mem_pool, reuse);
break;
case THdfsCompression::SNAPPY:
*decompressor = new SnappyDecompressor(mem_pool, reuse);
break;
}
return (*decompressor)->Init();
}
Codec::Codec(MemPool* mem_pool, bool reuse_buffer)
: memory_pool_(mem_pool),
reuse_buffer_(reuse_buffer),
out_buffer_(NULL),
buffer_length_(0) {
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dbaobjectex.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2005-09-23 11:58:40 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SVX_DBAOBJECTEX_HXX
#include "dbaobjectex.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#endif
#ifndef _SVX_FMPROP_HRC
#include "fmprop.hrc"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _SOT_FORMATS_HXX
#include <sot/formats.hxx>
#endif
#ifndef _SOT_EXCHANGE_HXX
#include <sot/exchange.hxx>
#endif
#ifndef _COMPHELPER_PROPERTSETINFO_HXX_
#include <comphelper/propertysetinfo.hxx>
#endif
#ifndef _SVX_FMPROP_HRC
#include "fmprop.hrc"
#endif
//........................................................................
namespace svx
{
//........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::ucb;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::datatransfer;
using namespace ::svxform;
using namespace ::comphelper;
//====================================================================
//= OComponentTransferable
//====================================================================
//--------------------------------------------------------------------
OComponentTransferable::OComponentTransferable(const ::rtl::OUString& _rDatasourceOrLocation
,const Reference< XContent>& _xContent)
{
m_aDescriptor.setDataSource(_rDatasourceOrLocation);
m_aDescriptor[daComponent] <<= _xContent;
}
//--------------------------------------------------------------------
sal_uInt32 OComponentTransferable::getDescriptorFormatId(sal_Bool _bExtractForm)
{
static sal_uInt32 s_nReportFormat = (sal_uInt32)-1;
static sal_uInt32 s_nFormFormat = (sal_uInt32)-1;
if ( _bExtractForm && (sal_uInt32)-1 == s_nFormFormat )
{
s_nFormFormat = SotExchange::RegisterFormatName(String::CreateFromAscii("application/x-openoffice;windows_formatname=\"dbaccess.FormComponentDescriptorTransfer\"" ));
OSL_ENSURE((sal_uInt32)-1 != s_nFormFormat, "OComponentTransferable::getDescriptorFormatId: bad exchange id!");
}
else if ( !_bExtractForm && (sal_uInt32)-1 == s_nReportFormat)
{
s_nReportFormat = SotExchange::RegisterFormatName(String::CreateFromAscii("application/x-openoffice;windows_formatname=\"dbaccess.ReportComponentDescriptorTransfer\""));
OSL_ENSURE((sal_uInt32)-1 != s_nReportFormat, "OComponentTransferable::getDescriptorFormatId: bad exchange id!");
}
return _bExtractForm ? s_nFormFormat : s_nReportFormat;
}
//--------------------------------------------------------------------
void OComponentTransferable::AddSupportedFormats()
{
sal_Bool bForm = sal_True;
try
{
Reference<XPropertySet> xProp;
m_aDescriptor[daComponent] >>= xProp;
if ( xProp.is() )
xProp->getPropertyValue(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("IsForm"))) >>= bForm;
}
catch(Exception)
{}
AddFormat(getDescriptorFormatId(bForm));
}
//--------------------------------------------------------------------
sal_Bool OComponentTransferable::GetData( const DataFlavor& _rFlavor )
{
const sal_uInt32 nFormatId = SotExchange::GetFormat(_rFlavor);
if ( nFormatId == getDescriptorFormatId(sal_True) || nFormatId == getDescriptorFormatId(sal_False) )
return SetAny( makeAny( m_aDescriptor.createPropertyValueSequence() ), _rFlavor );
return sal_False;
}
//--------------------------------------------------------------------
sal_Bool OComponentTransferable::canExtractComponentDescriptor(const DataFlavorExVector& _rFlavors,sal_Bool _bForm )
{
DataFlavorExVector::const_iterator aEnd = _rFlavors.end();
for ( DataFlavorExVector::const_iterator aCheck = _rFlavors.begin();
aCheck != aEnd;
++aCheck
)
{
if ( getDescriptorFormatId(_bForm) == aCheck->mnSotId )
return sal_True;
}
return sal_False;
}
//--------------------------------------------------------------------
ODataAccessDescriptor OComponentTransferable::extractComponentDescriptor(const TransferableDataHelper& _rData)
{
sal_Bool bForm;
if ( (bForm = _rData.HasFormat(getDescriptorFormatId(sal_True))) || _rData.HasFormat(getDescriptorFormatId(sal_False)) )
{
// the object has a real descriptor object (not just the old compatible format)
// extract the any from the transferable
DataFlavor aFlavor;
#if OSL_DEBUG_LEVEL > 0
sal_Bool bSuccess =
#endif
SotExchange::GetFormatDataFlavor(getDescriptorFormatId(bForm), aFlavor);
OSL_ENSURE(bSuccess, "OComponentTransferable::extractColumnDescriptor: invalid data format (no flavor)!");
Any aDescriptor = _rData.GetAny(aFlavor);
// extract the property value sequence
Sequence< PropertyValue > aDescriptorProps;
#if OSL_DEBUG_LEVEL > 0
bSuccess =
#endif
aDescriptor >>= aDescriptorProps;
OSL_ENSURE(bSuccess, "OComponentTransferable::extractColumnDescriptor: invalid clipboard format!");
// build the real descriptor
return ODataAccessDescriptor(aDescriptorProps);
}
return ODataAccessDescriptor();
}
//--------------------------------------------------------------------
sal_Bool OComponentTransferable::extractComponentDescriptor(const TransferableDataHelper& _rData
,sal_Bool _bExtractForm
, ::rtl::OUString& _rDatasourceOrLocation
, ::com::sun::star::uno::Reference< XContent>& _xContent)
{
if ( _rData.HasFormat( getDescriptorFormatId(_bExtractForm)) )
{
ODataAccessDescriptor aDescriptor = extractComponentDescriptor(_rData);
_rDatasourceOrLocation = aDescriptor.getDataSource();
aDescriptor[daComponent] >>= _xContent;
return sal_True;
}
return sal_False;
}
//........................................................................
} // namespace svx
//........................................................................
<commit_msg>INTEGRATION: CWS pchfix02 (1.4.516); FILE MERGED 2006/09/01 17:46:45 kaib 1.4.516.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dbaobjectex.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-17 05:00:46 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#ifndef SVX_DBAOBJECTEX_HXX
#include "dbaobjectex.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#endif
#ifndef _SVX_FMPROP_HRC
#include "fmprop.hrc"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _SOT_FORMATS_HXX
#include <sot/formats.hxx>
#endif
#ifndef _SOT_EXCHANGE_HXX
#include <sot/exchange.hxx>
#endif
#ifndef _COMPHELPER_PROPERTSETINFO_HXX_
#include <comphelper/propertysetinfo.hxx>
#endif
#ifndef _SVX_FMPROP_HRC
#include "fmprop.hrc"
#endif
//........................................................................
namespace svx
{
//........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::ucb;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::datatransfer;
using namespace ::svxform;
using namespace ::comphelper;
//====================================================================
//= OComponentTransferable
//====================================================================
//--------------------------------------------------------------------
OComponentTransferable::OComponentTransferable(const ::rtl::OUString& _rDatasourceOrLocation
,const Reference< XContent>& _xContent)
{
m_aDescriptor.setDataSource(_rDatasourceOrLocation);
m_aDescriptor[daComponent] <<= _xContent;
}
//--------------------------------------------------------------------
sal_uInt32 OComponentTransferable::getDescriptorFormatId(sal_Bool _bExtractForm)
{
static sal_uInt32 s_nReportFormat = (sal_uInt32)-1;
static sal_uInt32 s_nFormFormat = (sal_uInt32)-1;
if ( _bExtractForm && (sal_uInt32)-1 == s_nFormFormat )
{
s_nFormFormat = SotExchange::RegisterFormatName(String::CreateFromAscii("application/x-openoffice;windows_formatname=\"dbaccess.FormComponentDescriptorTransfer\"" ));
OSL_ENSURE((sal_uInt32)-1 != s_nFormFormat, "OComponentTransferable::getDescriptorFormatId: bad exchange id!");
}
else if ( !_bExtractForm && (sal_uInt32)-1 == s_nReportFormat)
{
s_nReportFormat = SotExchange::RegisterFormatName(String::CreateFromAscii("application/x-openoffice;windows_formatname=\"dbaccess.ReportComponentDescriptorTransfer\""));
OSL_ENSURE((sal_uInt32)-1 != s_nReportFormat, "OComponentTransferable::getDescriptorFormatId: bad exchange id!");
}
return _bExtractForm ? s_nFormFormat : s_nReportFormat;
}
//--------------------------------------------------------------------
void OComponentTransferable::AddSupportedFormats()
{
sal_Bool bForm = sal_True;
try
{
Reference<XPropertySet> xProp;
m_aDescriptor[daComponent] >>= xProp;
if ( xProp.is() )
xProp->getPropertyValue(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("IsForm"))) >>= bForm;
}
catch(Exception)
{}
AddFormat(getDescriptorFormatId(bForm));
}
//--------------------------------------------------------------------
sal_Bool OComponentTransferable::GetData( const DataFlavor& _rFlavor )
{
const sal_uInt32 nFormatId = SotExchange::GetFormat(_rFlavor);
if ( nFormatId == getDescriptorFormatId(sal_True) || nFormatId == getDescriptorFormatId(sal_False) )
return SetAny( makeAny( m_aDescriptor.createPropertyValueSequence() ), _rFlavor );
return sal_False;
}
//--------------------------------------------------------------------
sal_Bool OComponentTransferable::canExtractComponentDescriptor(const DataFlavorExVector& _rFlavors,sal_Bool _bForm )
{
DataFlavorExVector::const_iterator aEnd = _rFlavors.end();
for ( DataFlavorExVector::const_iterator aCheck = _rFlavors.begin();
aCheck != aEnd;
++aCheck
)
{
if ( getDescriptorFormatId(_bForm) == aCheck->mnSotId )
return sal_True;
}
return sal_False;
}
//--------------------------------------------------------------------
ODataAccessDescriptor OComponentTransferable::extractComponentDescriptor(const TransferableDataHelper& _rData)
{
sal_Bool bForm;
if ( (bForm = _rData.HasFormat(getDescriptorFormatId(sal_True))) || _rData.HasFormat(getDescriptorFormatId(sal_False)) )
{
// the object has a real descriptor object (not just the old compatible format)
// extract the any from the transferable
DataFlavor aFlavor;
#if OSL_DEBUG_LEVEL > 0
sal_Bool bSuccess =
#endif
SotExchange::GetFormatDataFlavor(getDescriptorFormatId(bForm), aFlavor);
OSL_ENSURE(bSuccess, "OComponentTransferable::extractColumnDescriptor: invalid data format (no flavor)!");
Any aDescriptor = _rData.GetAny(aFlavor);
// extract the property value sequence
Sequence< PropertyValue > aDescriptorProps;
#if OSL_DEBUG_LEVEL > 0
bSuccess =
#endif
aDescriptor >>= aDescriptorProps;
OSL_ENSURE(bSuccess, "OComponentTransferable::extractColumnDescriptor: invalid clipboard format!");
// build the real descriptor
return ODataAccessDescriptor(aDescriptorProps);
}
return ODataAccessDescriptor();
}
//--------------------------------------------------------------------
sal_Bool OComponentTransferable::extractComponentDescriptor(const TransferableDataHelper& _rData
,sal_Bool _bExtractForm
, ::rtl::OUString& _rDatasourceOrLocation
, ::com::sun::star::uno::Reference< XContent>& _xContent)
{
if ( _rData.HasFormat( getDescriptorFormatId(_bExtractForm)) )
{
ODataAccessDescriptor aDescriptor = extractComponentDescriptor(_rData);
_rDatasourceOrLocation = aDescriptor.getDataSource();
aDescriptor[daComponent] >>= _xContent;
return sal_True;
}
return sal_False;
}
//........................................................................
} // namespace svx
//........................................................................
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: atrfld.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2004-03-17 12:16:04 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include "doc.hxx" // Update fuer UserFields
#include "fldbas.hxx" // fuer FieldType
#ifndef _FMTFLD_HXX //autogen
#include <fmtfld.hxx>
#endif
#ifndef _TXTFLD_HXX //autogen
#include <txtfld.hxx>
#endif
#include "reffld.hxx"
#include "ddefld.hxx"
#include "usrfld.hxx"
#include "expfld.hxx"
#include "swfont.hxx" // fuer GetFldsColor
#include "ndtxt.hxx" // SwTxtNode
#include "calc.hxx" // Update fuer UserFields
#include "hints.hxx"
TYPEINIT2( SwFmtFld, SfxPoolItem, SwClient )
/****************************************************************************
*
* class SwFmtFld
*
****************************************************************************/
// Konstruktor fuers Default vom Attribut-Pool
SwFmtFld::SwFmtFld()
: SfxPoolItem( RES_TXTATR_FIELD ),
SwClient( 0 ),
pField( 0 ),
pTxtAttr( 0 )
{
}
SwFmtFld::SwFmtFld( const SwField &rFld )
: SfxPoolItem( RES_TXTATR_FIELD ),
SwClient( rFld.GetTyp() ),
pTxtAttr( 0 )
{
pField = rFld.Copy();
}
// #i24434#
// Since Items are used in ItemPool and in default constructed ItemSets with
// full pool range, all items need to be clonable. Thus, this one needed to be
// corrected
SwFmtFld::SwFmtFld( const SwFmtFld& rAttr )
: SfxPoolItem( RES_TXTATR_FIELD ),
pTxtAttr( 0 ),
pField( 0 )
{
if(rAttr.GetFld())
{
rAttr.GetFld()->GetTyp()->Add(this);
pField = rAttr.GetFld()->Copy();
}
}
SwFmtFld::~SwFmtFld()
{
SwFieldType* pType = pField ? pField->GetTyp() : 0;
if (pType && pType->Which() == RES_DBFLD)
pType = 0; // DB-Feldtypen zerstoeren sich selbst
delete pField;
// bei einige FeldTypen muessen wir den FeldTypen noch loeschen
if( pType && pType->IsLastDepend() )
{
BOOL bDel = FALSE;
switch( pType->Which() )
{
case RES_USERFLD:
bDel = ((SwUserFieldType*)pType)->IsDeleted();
break;
case RES_SETEXPFLD:
bDel = ((SwSetExpFieldType*)pType)->IsDeleted();
break;
case RES_DDEFLD:
bDel = ((SwDDEFieldType*)pType)->IsDeleted();
break;
}
if( bDel )
{
// vorm loeschen erstmal austragen
pType->Remove( this );
delete pType;
}
}
}
int SwFmtFld::operator==( const SfxPoolItem& rAttr ) const
{
ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" );
return pField->GetTyp() == ((SwFmtFld&)rAttr).GetFld()->GetTyp() &&
pField->GetFormat() == ((SwFmtFld&)rAttr).GetFld()->GetFormat();
}
SfxPoolItem* SwFmtFld::Clone( SfxItemPool* ) const
{
return new SwFmtFld( *this );
}
void SwFmtFld::Modify( SfxPoolItem* pOld, SfxPoolItem* pNew )
{
if( !pTxtAttr )
return;
SwTxtNode* pTxtNd = (SwTxtNode*)&pTxtAttr->GetTxtNode();
ASSERT( pTxtNd, "wo ist denn mein Node?" );
if( pNew )
{
switch( pNew->Which() )
{
case RES_TXTATR_FLDCHG:
// "Farbe hat sich geaendert !"
// this, this fuer "nur Painten"
pTxtNd->Modify( this, this );
return;
case RES_REFMARKFLD_UPDATE:
// GetReferenz-Felder aktualisieren
if( RES_GETREFFLD == GetFld()->GetTyp()->Which() )
((SwGetRefField*)GetFld())->UpdateField();
break;
case RES_DOCPOS_UPDATE:
// Je nach DocPos aktualisieren (SwTxtFrm::Modify())
pTxtNd->Modify( pNew, this );
return;
case RES_ATTRSET_CHG:
case RES_FMT_CHG:
pTxtNd->Modify( pOld, pNew );
return;
}
}
switch (GetFld()->GetTyp()->Which())
{
case RES_HIDDENPARAFLD:
if( !pOld || RES_HIDDENPARA_PRINT != pOld->Which() )
break;
case RES_DBSETNUMBERFLD:
case RES_DBNUMSETFLD:
case RES_DBNEXTSETFLD:
case RES_DBNAMEFLD:
pTxtNd->Modify( 0, pNew);
return;
}
if( RES_USERFLD == GetFld()->GetTyp()->Which() )
{
SwUserFieldType* pType = (SwUserFieldType*)GetFld()->GetTyp();
if(!pType->IsValid())
{
SwCalc aCalc( *pTxtNd->GetDoc() );
pType->GetValue( aCalc );
}
}
pTxtAttr->Expand();
}
BOOL SwFmtFld::GetInfo( SfxPoolItem& rInfo ) const
{
const SwTxtNode* pTxtNd;
if( RES_AUTOFMT_DOCNODE != rInfo.Which() ||
!pTxtAttr || 0 == ( pTxtNd = pTxtAttr->GetpTxtNode() ) ||
&pTxtNd->GetNodes() != ((SwAutoFmtGetDocNode&)rInfo).pNodes )
return TRUE;
((SwAutoFmtGetDocNode&)rInfo).pCntntNode = pTxtNd;
return FALSE;
}
BOOL SwFmtFld::IsFldInDoc() const
{
const SwTxtNode* pTxtNd;
return pTxtAttr && 0 != ( pTxtNd = pTxtAttr->GetpTxtNode() ) &&
pTxtNd->GetNodes().IsDocNodes();
}
BOOL SwFmtFld::IsProtect() const
{
const SwTxtNode* pTxtNd;
return pTxtAttr && 0 != ( pTxtNd = pTxtAttr->GetpTxtNode() ) &&
pTxtNd->IsProtect();
}
/*************************************************************************
|*
|* SwTxtFld::SwTxtFld()
|*
|* Beschreibung Attribut fuer automatischen Text, Ctor
|* Ersterstellung BP 30.04.92
|* Letzte Aenderung JP 15.08.94
|*
*************************************************************************/
SwTxtFld::SwTxtFld( const SwFmtFld& rAttr, xub_StrLen nStart )
: SwTxtAttr( rAttr, nStart ),
aExpand( rAttr.GetFld()->Expand() ),
pMyTxtNd( 0 )
{
((SwFmtFld&)rAttr).pTxtAttr = this;
}
SwTxtFld::~SwTxtFld( )
{
}
/*************************************************************************
|*
|* SwTxtFld::Expand()
|*
|* Beschreibung exandiert das Feld und tauscht den Text im Node
|* Ersterstellung BP 30.04.92
|* Letzte Aenderung JP 15.08.94
|*
*************************************************************************/
void SwTxtFld::Expand() const
{
// Wenn das expandierte Feld sich nicht veraendert hat, wird returnt
ASSERT( pMyTxtNd, "wo ist denn mein Node?" );
const SwField* pFld = GetFld().GetFld();
XubString aNewExpand( pFld->Expand() );
if( aNewExpand == aExpand )
{
// Bei Seitennummernfeldern
const USHORT nWhich = pFld->GetTyp()->Which();
if( RES_CHAPTERFLD != nWhich && RES_PAGENUMBERFLD != nWhich &&
RES_REFPAGEGETFLD != nWhich &&
( RES_GETEXPFLD != nWhich ||
((SwGetExpField*)pFld)->IsInBodyTxt() ) )
{
// BP: das muesste man noch optimieren!
//JP 12.06.97: stimmt, man sollte auf jedenfall eine Status-
// aenderung an die Frames posten
if( pMyTxtNd->CalcHiddenParaField() )
pMyTxtNd->Modify( 0, 0 );
return;
}
}
aExpand = aNewExpand;
// 0, this fuer Formatieren
pMyTxtNd->Modify( 0, (SfxPoolItem*)&GetFld() );
}
/*************************************************************************
* SwTxtFld::CopyFld()
*************************************************************************/
void SwTxtFld::CopyFld( SwTxtFld *pDest ) const
{
ASSERT( pMyTxtNd, "wo ist denn mein Node?" );
ASSERT( pDest->pMyTxtNd, "wo ist denn mein Node?" );
SwDoc *pDoc = pMyTxtNd->GetDoc();
SwDoc *pDestDoc = pDest->pMyTxtNd->GetDoc();
SwFmtFld& rFmtFld = (SwFmtFld&)pDest->GetFld();
const USHORT nFldWhich = rFmtFld.GetFld()->GetTyp()->Which();
if( pDoc != pDestDoc )
{
// Die Hints stehen in unterschiedlichen Dokumenten,
// der Feldtyp muss im neuen Dokument angemeldet werden.
// Z.B: Kopieren ins ClipBoard.
SwFieldType* pFldType;
if( nFldWhich != RES_DBFLD && nFldWhich != RES_USERFLD &&
nFldWhich != RES_SETEXPFLD && nFldWhich != RES_DDEFLD &&
RES_AUTHORITY != nFldWhich )
pFldType = pDestDoc->GetSysFldType( (const RES_FIELDS)nFldWhich );
else
pFldType = pDestDoc->InsertFldType( *rFmtFld.GetFld()->GetTyp() );
// Sonderbehandlung fuer DDE-Felder
if( RES_DDEFLD == nFldWhich )
{
if( rFmtFld.GetTxtFld() )
((SwDDEFieldType*)rFmtFld.GetFld()->GetTyp())->DecRefCnt();
((SwDDEFieldType*)pFldType)->IncRefCnt();
}
ASSERT( pFldType, "unbekannter FieldType" );
pFldType->Add( &rFmtFld ); // ummelden
rFmtFld.GetFld()->ChgTyp( pFldType );
}
// Expressionfelder Updaten
if( nFldWhich == RES_SETEXPFLD || nFldWhich == RES_GETEXPFLD ||
nFldWhich == RES_HIDDENTXTFLD )
{
SwTxtFld* pFld = (SwTxtFld*)this;
pDestDoc->UpdateExpFlds( pFld );
}
// Tabellenfelder auf externe Darstellung
else if( RES_TABLEFLD == nFldWhich &&
((SwTblField*)rFmtFld.GetFld())->IsIntrnlName() )
{
// erzeuge aus der internen (fuer CORE) die externe (fuer UI) Formel
const SwTableNode* pTblNd = pMyTxtNd->FindTableNode();
if( pTblNd ) // steht in einer Tabelle
((SwTblField*)rFmtFld.GetFld())->PtrToBoxNm( &pTblNd->GetTable() );
}
}
<commit_msg>INTEGRATION: CWS swundo01 (1.2.126); FILE MERGED 2004/04/19 10:24:01 hbrinkm 1.2.126.2: RESYNC: (1.2-1.5); FILE MERGED 2004/01/06 15:37:11 hbrinkm 1.2.126.1: #111840#<commit_after>/*************************************************************************
*
* $RCSfile: atrfld.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kz $ $Date: 2004-05-18 14:04:55 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include "doc.hxx" // Update fuer UserFields
#include "fldbas.hxx" // fuer FieldType
#ifndef _FMTFLD_HXX //autogen
#include <fmtfld.hxx>
#endif
#ifndef _TXTFLD_HXX //autogen
#include <txtfld.hxx>
#endif
#include "reffld.hxx"
#include "ddefld.hxx"
#include "usrfld.hxx"
#include "expfld.hxx"
#include "swfont.hxx" // fuer GetFldsColor
#include "ndtxt.hxx" // SwTxtNode
#include "calc.hxx" // Update fuer UserFields
#include "hints.hxx"
TYPEINIT2( SwFmtFld, SfxPoolItem, SwClient )
/****************************************************************************
*
* class SwFmtFld
*
****************************************************************************/
// Konstruktor fuers Default vom Attribut-Pool
SwFmtFld::SwFmtFld()
: SfxPoolItem( RES_TXTATR_FIELD ),
SwClient( 0 ),
pField( 0 ),
pTxtAttr( 0 )
{
}
SwFmtFld::SwFmtFld( const SwField &rFld )
: SfxPoolItem( RES_TXTATR_FIELD ),
SwClient( rFld.GetTyp() ),
pTxtAttr( 0 )
{
pField = rFld.Copy();
}
// #i24434#
// Since Items are used in ItemPool and in default constructed ItemSets with
// full pool range, all items need to be clonable. Thus, this one needed to be
// corrected
SwFmtFld::SwFmtFld( const SwFmtFld& rAttr )
: SfxPoolItem( RES_TXTATR_FIELD ),
pTxtAttr( 0 ),
pField( 0 )
{
if(rAttr.GetFld())
{
rAttr.GetFld()->GetTyp()->Add(this);
pField = rAttr.GetFld()->Copy();
}
}
SwFmtFld::~SwFmtFld()
{
SwFieldType* pType = pField ? pField->GetTyp() : 0;
if (pType && pType->Which() == RES_DBFLD)
pType = 0; // DB-Feldtypen zerstoeren sich selbst
delete pField;
// bei einige FeldTypen muessen wir den FeldTypen noch loeschen
if( pType && pType->IsLastDepend() )
{
BOOL bDel = FALSE;
switch( pType->Which() )
{
case RES_USERFLD:
bDel = ((SwUserFieldType*)pType)->IsDeleted();
break;
case RES_SETEXPFLD:
bDel = ((SwSetExpFieldType*)pType)->IsDeleted();
break;
case RES_DDEFLD:
bDel = ((SwDDEFieldType*)pType)->IsDeleted();
break;
}
if( bDel )
{
// vorm loeschen erstmal austragen
pType->Remove( this );
delete pType;
}
}
}
// #111840#
void SwFmtFld::SetFld(SwField * _pField)
{
if (NULL != pField)
delete pField;
pField = _pField;
}
int SwFmtFld::operator==( const SfxPoolItem& rAttr ) const
{
ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" );
return pField->GetTyp() == ((SwFmtFld&)rAttr).GetFld()->GetTyp() &&
pField->GetFormat() == ((SwFmtFld&)rAttr).GetFld()->GetFormat();
}
SfxPoolItem* SwFmtFld::Clone( SfxItemPool* ) const
{
return new SwFmtFld( *this );
}
void SwFmtFld::Modify( SfxPoolItem* pOld, SfxPoolItem* pNew )
{
if( !pTxtAttr )
return;
SwTxtNode* pTxtNd = (SwTxtNode*)&pTxtAttr->GetTxtNode();
ASSERT( pTxtNd, "wo ist denn mein Node?" );
if( pNew )
{
switch( pNew->Which() )
{
case RES_TXTATR_FLDCHG:
// "Farbe hat sich geaendert !"
// this, this fuer "nur Painten"
pTxtNd->Modify( this, this );
return;
case RES_REFMARKFLD_UPDATE:
// GetReferenz-Felder aktualisieren
if( RES_GETREFFLD == GetFld()->GetTyp()->Which() )
((SwGetRefField*)GetFld())->UpdateField();
break;
case RES_DOCPOS_UPDATE:
// Je nach DocPos aktualisieren (SwTxtFrm::Modify())
pTxtNd->Modify( pNew, this );
return;
case RES_ATTRSET_CHG:
case RES_FMT_CHG:
pTxtNd->Modify( pOld, pNew );
return;
}
}
switch (GetFld()->GetTyp()->Which())
{
case RES_HIDDENPARAFLD:
if( !pOld || RES_HIDDENPARA_PRINT != pOld->Which() )
break;
case RES_DBSETNUMBERFLD:
case RES_DBNUMSETFLD:
case RES_DBNEXTSETFLD:
case RES_DBNAMEFLD:
pTxtNd->Modify( 0, pNew);
return;
}
if( RES_USERFLD == GetFld()->GetTyp()->Which() )
{
SwUserFieldType* pType = (SwUserFieldType*)GetFld()->GetTyp();
if(!pType->IsValid())
{
SwCalc aCalc( *pTxtNd->GetDoc() );
pType->GetValue( aCalc );
}
}
pTxtAttr->Expand();
}
BOOL SwFmtFld::GetInfo( SfxPoolItem& rInfo ) const
{
const SwTxtNode* pTxtNd;
if( RES_AUTOFMT_DOCNODE != rInfo.Which() ||
!pTxtAttr || 0 == ( pTxtNd = pTxtAttr->GetpTxtNode() ) ||
&pTxtNd->GetNodes() != ((SwAutoFmtGetDocNode&)rInfo).pNodes )
return TRUE;
((SwAutoFmtGetDocNode&)rInfo).pCntntNode = pTxtNd;
return FALSE;
}
BOOL SwFmtFld::IsFldInDoc() const
{
const SwTxtNode* pTxtNd;
return pTxtAttr && 0 != ( pTxtNd = pTxtAttr->GetpTxtNode() ) &&
pTxtNd->GetNodes().IsDocNodes();
}
BOOL SwFmtFld::IsProtect() const
{
const SwTxtNode* pTxtNd;
return pTxtAttr && 0 != ( pTxtNd = pTxtAttr->GetpTxtNode() ) &&
pTxtNd->IsProtect();
}
/*************************************************************************
|*
|* SwTxtFld::SwTxtFld()
|*
|* Beschreibung Attribut fuer automatischen Text, Ctor
|* Ersterstellung BP 30.04.92
|* Letzte Aenderung JP 15.08.94
|*
*************************************************************************/
SwTxtFld::SwTxtFld( const SwFmtFld& rAttr, xub_StrLen nStart )
: SwTxtAttr( rAttr, nStart ),
aExpand( rAttr.GetFld()->Expand() ),
pMyTxtNd( 0 )
{
((SwFmtFld&)rAttr).pTxtAttr = this;
}
SwTxtFld::~SwTxtFld( )
{
}
/*************************************************************************
|*
|* SwTxtFld::Expand()
|*
|* Beschreibung exandiert das Feld und tauscht den Text im Node
|* Ersterstellung BP 30.04.92
|* Letzte Aenderung JP 15.08.94
|*
*************************************************************************/
void SwTxtFld::Expand() const
{
// Wenn das expandierte Feld sich nicht veraendert hat, wird returnt
ASSERT( pMyTxtNd, "wo ist denn mein Node?" );
const SwField* pFld = GetFld().GetFld();
XubString aNewExpand( pFld->Expand() );
if( aNewExpand == aExpand )
{
// Bei Seitennummernfeldern
const USHORT nWhich = pFld->GetTyp()->Which();
if( RES_CHAPTERFLD != nWhich && RES_PAGENUMBERFLD != nWhich &&
RES_REFPAGEGETFLD != nWhich &&
( RES_GETEXPFLD != nWhich ||
((SwGetExpField*)pFld)->IsInBodyTxt() ) )
{
// BP: das muesste man noch optimieren!
//JP 12.06.97: stimmt, man sollte auf jedenfall eine Status-
// aenderung an die Frames posten
if( pMyTxtNd->CalcHiddenParaField() )
pMyTxtNd->Modify( 0, 0 );
return;
}
}
aExpand = aNewExpand;
// 0, this fuer Formatieren
pMyTxtNd->Modify( 0, (SfxPoolItem*)&GetFld() );
}
/*************************************************************************
* SwTxtFld::CopyFld()
*************************************************************************/
void SwTxtFld::CopyFld( SwTxtFld *pDest ) const
{
ASSERT( pMyTxtNd, "wo ist denn mein Node?" );
ASSERT( pDest->pMyTxtNd, "wo ist denn mein Node?" );
SwDoc *pDoc = pMyTxtNd->GetDoc();
SwDoc *pDestDoc = pDest->pMyTxtNd->GetDoc();
SwFmtFld& rFmtFld = (SwFmtFld&)pDest->GetFld();
const USHORT nFldWhich = rFmtFld.GetFld()->GetTyp()->Which();
if( pDoc != pDestDoc )
{
// Die Hints stehen in unterschiedlichen Dokumenten,
// der Feldtyp muss im neuen Dokument angemeldet werden.
// Z.B: Kopieren ins ClipBoard.
SwFieldType* pFldType;
if( nFldWhich != RES_DBFLD && nFldWhich != RES_USERFLD &&
nFldWhich != RES_SETEXPFLD && nFldWhich != RES_DDEFLD &&
RES_AUTHORITY != nFldWhich )
pFldType = pDestDoc->GetSysFldType( (const RES_FIELDS)nFldWhich );
else
pFldType = pDestDoc->InsertFldType( *rFmtFld.GetFld()->GetTyp() );
// Sonderbehandlung fuer DDE-Felder
if( RES_DDEFLD == nFldWhich )
{
if( rFmtFld.GetTxtFld() )
((SwDDEFieldType*)rFmtFld.GetFld()->GetTyp())->DecRefCnt();
((SwDDEFieldType*)pFldType)->IncRefCnt();
}
ASSERT( pFldType, "unbekannter FieldType" );
pFldType->Add( &rFmtFld ); // ummelden
rFmtFld.GetFld()->ChgTyp( pFldType );
}
// Expressionfelder Updaten
if( nFldWhich == RES_SETEXPFLD || nFldWhich == RES_GETEXPFLD ||
nFldWhich == RES_HIDDENTXTFLD )
{
SwTxtFld* pFld = (SwTxtFld*)this;
pDestDoc->UpdateExpFlds( pFld );
}
// Tabellenfelder auf externe Darstellung
else if( RES_TABLEFLD == nFldWhich &&
((SwTblField*)rFmtFld.GetFld())->IsIntrnlName() )
{
// erzeuge aus der internen (fuer CORE) die externe (fuer UI) Formel
const SwTableNode* pTblNd = pMyTxtNd->FindTableNode();
if( pTblNd ) // steht in einer Tabelle
((SwTblField*)rFmtFld.GetFld())->PtrToBoxNm( &pTblNd->GetTable() );
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: ascatr.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2003-04-17 14:48:33 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef _SVSTDARR_HXX
#define _SVSTDARR_USHORTS
#include <svtools/svstdarr.hxx>
#endif
#ifndef _SVX_FONTITEM_HXX
#include <svx/fontitem.hxx>
#endif
#ifndef _PAM_HXX
#include <pam.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx>
#endif
#ifndef _WRTASC_HXX
#include <wrtasc.hxx>
#endif
#ifndef _TXATBASE_HXX
#include <txatbase.hxx>
#endif
#ifndef _FCHRFMT_HXX
#include <fchrfmt.hxx>
#endif
#ifndef _TXTFLD_HXX
#include <txtfld.hxx>
#endif
#ifndef _TXTATR_HXX
#include <txtatr.hxx>
#endif
#ifndef _FMTFTN_HXX
#include <fmtftn.hxx>
#endif
#ifndef _CHARFMT_HXX
#include <charfmt.hxx>
#endif
#ifndef _FMTFLD_HXX
#include <fmtfld.hxx>
#endif
#ifndef _FLDBAS_HXX
#include <fldbas.hxx>
#endif
#ifndef _FTNINFO_HXX //autogen
#include <ftninfo.hxx>
#endif
/*
* Dieses File enthaelt alle Ausgabe-Funktionen des ASCII-Writers;
* fuer alle Nodes, Attribute, Formate und Chars.
*/
class SwASC_AttrIter
{
SwASCWriter& rWrt;
const SwTxtNode& rNd;
xub_StrLen nAktSwPos;
xub_StrLen SearchNext( xub_StrLen nStartPos );
public:
SwASC_AttrIter( SwASCWriter& rWrt, const SwTxtNode& rNd, xub_StrLen nStt );
void NextPos() { nAktSwPos = SearchNext( nAktSwPos + 1 ); }
xub_StrLen WhereNext() const { return nAktSwPos; }
BOOL OutAttr( xub_StrLen nSwPos );
};
SwASC_AttrIter::SwASC_AttrIter( SwASCWriter& rWr, const SwTxtNode& rTxtNd,
xub_StrLen nStt )
: rWrt( rWr ), rNd( rTxtNd ), nAktSwPos( 0 )
{
nAktSwPos = SearchNext( nStt + 1 );
}
xub_StrLen SwASC_AttrIter::SearchNext( xub_StrLen nStartPos )
{
register xub_StrLen nMinPos = STRING_MAXLEN;
const SwpHints* pTxtAttrs = rNd.GetpSwpHints();
if( pTxtAttrs )
{
register USHORT i;
register xub_StrLen nPos;
const xub_StrLen * pPos;
// kann noch optimiert werden, wenn ausgenutzt wird, dass die TxtAttrs
// nach der Anfangsposition geordnet sind. Dann muessten
// allerdings noch 2 Indices gemerkt werden
for( i = 0; i < pTxtAttrs->Count(); i++ )
{
const SwTxtAttr* pHt = (*pTxtAttrs)[i];
nPos = *pHt->GetStart(); // gibt erstes Attr-Zeichen
pPos = pHt->GetEnd();
if( !pPos )
{
if( nPos >= nStartPos && nPos <= nMinPos )
nMinPos = nPos;
if( ( ++nPos ) >= nStartPos && nPos < nMinPos )
nMinPos = nPos;
}
}
}
return nMinPos;
}
BOOL SwASC_AttrIter::OutAttr( xub_StrLen nSwPos )
{
BOOL bRet = FALSE;
const SwpHints* pTxtAttrs = rNd.GetpSwpHints();
if( pTxtAttrs )
{
register USHORT i;
for( i = 0; i < pTxtAttrs->Count(); i++ )
{
const SwTxtAttr* pHt = (*pTxtAttrs)[i];
const xub_StrLen * pEnd = pHt->GetEnd();
if( !pEnd && nSwPos == *pHt->GetStart() )
{
bRet = TRUE;
String sOut;
switch( pHt->Which() )
{
case RES_TXTATR_FIELD:
sOut = ((SwTxtFld*)pHt)->GetFld().GetFld()->Expand();
break;
case RES_TXTATR_HARDBLANK:
sOut = ((SwTxtHardBlank*)pHt)->GetChar();
break;
case RES_TXTATR_FTN:
{
const SwFmtFtn& rFtn = pHt->GetFtn();
if( rFtn.GetNumStr().Len() )
sOut = rFtn.GetNumStr();
else if( rFtn.IsEndNote() )
sOut = rWrt.pDoc->GetEndNoteInfo().aFmt.
GetNumStr( rFtn.GetNumber() );
else
sOut = rWrt.pDoc->GetFtnInfo().aFmt.
GetNumStr( rFtn.GetNumber() );
}
break;
}
if( sOut.Len() )
rWrt.Strm().WriteUnicodeOrByteText( sOut );
}
else if( nSwPos < *pHt->GetStart() )
break;
}
}
return bRet;
}
//------------------------
/* Ausgabe der Nodes */
//------------------------
static Writer& OutASC_SwTxtNode( Writer& rWrt, SwCntntNode& rNode )
{
const SwTxtNode& rNd = (SwTxtNode&)rNode;
xub_StrLen nStrPos = rWrt.pCurPam->GetPoint()->nContent.GetIndex();
xub_StrLen nNodeEnde = rNd.Len(), nEnde = nNodeEnde;
BOOL bLastNd = rWrt.pCurPam->GetPoint()->nNode == rWrt.pCurPam->GetMark()->nNode;
if( bLastNd )
nEnde = rWrt.pCurPam->GetMark()->nContent.GetIndex();
SwASC_AttrIter aAttrIter( (SwASCWriter&)rWrt, rNd, nStrPos );
if( !nStrPos )
rWrt.Strm().WriteUnicodeOrByteText( rNd.GetNumString() );
String aStr( rNd.GetTxt() );
if( rWrt.bASCII_ParaAsBlanc )
aStr.SearchAndReplaceAll( 0x0A, ' ' );
do {
xub_StrLen nNextAttr = aAttrIter.WhereNext();
if( nNextAttr > nEnde )
nNextAttr = nEnde;
if( !aAttrIter.OutAttr( nStrPos ))
rWrt.Strm().WriteUnicodeOrByteText(
aStr.Copy( nStrPos, nNextAttr - nStrPos ));
nStrPos = nNextAttr;
aAttrIter.NextPos();
} while( nStrPos < nEnde );
if( !bLastNd ||
( !rWrt.bWriteClipboardDoc && !rWrt.bASCII_NoLastLineEnd )
&& !nStrPos && nEnde == nNodeEnde )
rWrt.Strm().WriteUnicodeOrByteText( ((SwASCWriter&)rWrt).GetLineEnd());
return rWrt;
}
/*
* lege hier jetzt die Tabellen fuer die ASCII-Funktions-Pointer auf
* die Ausgabe-Funktionen an.
* Es sind lokale Strukturen, die nur innerhalb der ASCII-DLL
* bekannt sein muessen.
*/
SwNodeFnTab aASCNodeFnTab = {
/* RES_TXTNODE */ OutASC_SwTxtNode,
/* RES_GRFNODE */ 0,
/* RES_OLENODE */ 0
};
<commit_msg>INTEGRATION: CWS mullingarfilterteam18 (1.4.278); FILE MERGED 2003/11/19 09:14:55 cmc 1.4.278.1: #i9055# clean warnings from ascii dir<commit_after>/*************************************************************************
*
* $RCSfile: ascatr.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2004-01-13 16:36:19 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef _SVSTDARR_HXX
#define _SVSTDARR_USHORTS
#include <svtools/svstdarr.hxx>
#endif
#ifndef _SVX_FONTITEM_HXX
#include <svx/fontitem.hxx>
#endif
#ifndef _PAM_HXX
#include <pam.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx>
#endif
#ifndef _WRTASC_HXX
#include <wrtasc.hxx>
#endif
#ifndef _TXATBASE_HXX
#include <txatbase.hxx>
#endif
#ifndef _FCHRFMT_HXX
#include <fchrfmt.hxx>
#endif
#ifndef _TXTFLD_HXX
#include <txtfld.hxx>
#endif
#ifndef _TXTATR_HXX
#include <txtatr.hxx>
#endif
#ifndef _FMTFTN_HXX
#include <fmtftn.hxx>
#endif
#ifndef _CHARFMT_HXX
#include <charfmt.hxx>
#endif
#ifndef _FMTFLD_HXX
#include <fmtfld.hxx>
#endif
#ifndef _FLDBAS_HXX
#include <fldbas.hxx>
#endif
#ifndef _FTNINFO_HXX //autogen
#include <ftninfo.hxx>
#endif
/*
* Dieses File enthaelt alle Ausgabe-Funktionen des ASCII-Writers;
* fuer alle Nodes, Attribute, Formate und Chars.
*/
class SwASC_AttrIter
{
SwASCWriter& rWrt;
const SwTxtNode& rNd;
xub_StrLen nAktSwPos;
xub_StrLen SearchNext( xub_StrLen nStartPos );
public:
SwASC_AttrIter( SwASCWriter& rWrt, const SwTxtNode& rNd, xub_StrLen nStt );
void NextPos() { nAktSwPos = SearchNext( nAktSwPos + 1 ); }
xub_StrLen WhereNext() const { return nAktSwPos; }
BOOL OutAttr( xub_StrLen nSwPos );
};
SwASC_AttrIter::SwASC_AttrIter( SwASCWriter& rWr, const SwTxtNode& rTxtNd,
xub_StrLen nStt )
: rWrt( rWr ), rNd( rTxtNd ), nAktSwPos( 0 )
{
nAktSwPos = SearchNext( nStt + 1 );
}
xub_StrLen SwASC_AttrIter::SearchNext( xub_StrLen nStartPos )
{
register xub_StrLen nMinPos = STRING_MAXLEN;
const SwpHints* pTxtAttrs = rNd.GetpSwpHints();
if( pTxtAttrs )
{
register USHORT i;
register xub_StrLen nPos;
const xub_StrLen * pPos;
// kann noch optimiert werden, wenn ausgenutzt wird, dass die TxtAttrs
// nach der Anfangsposition geordnet sind. Dann muessten
// allerdings noch 2 Indices gemerkt werden
for( i = 0; i < pTxtAttrs->Count(); i++ )
{
const SwTxtAttr* pHt = (*pTxtAttrs)[i];
nPos = *pHt->GetStart(); // gibt erstes Attr-Zeichen
pPos = pHt->GetEnd();
if( !pPos )
{
if( nPos >= nStartPos && nPos <= nMinPos )
nMinPos = nPos;
if( ( ++nPos ) >= nStartPos && nPos < nMinPos )
nMinPos = nPos;
}
}
}
return nMinPos;
}
BOOL SwASC_AttrIter::OutAttr( xub_StrLen nSwPos )
{
BOOL bRet = FALSE;
const SwpHints* pTxtAttrs = rNd.GetpSwpHints();
if( pTxtAttrs )
{
register USHORT i;
for( i = 0; i < pTxtAttrs->Count(); i++ )
{
const SwTxtAttr* pHt = (*pTxtAttrs)[i];
const xub_StrLen * pEnd = pHt->GetEnd();
if( !pEnd && nSwPos == *pHt->GetStart() )
{
bRet = TRUE;
String sOut;
switch( pHt->Which() )
{
case RES_TXTATR_FIELD:
sOut = ((SwTxtFld*)pHt)->GetFld().GetFld()->Expand();
break;
case RES_TXTATR_HARDBLANK:
sOut = ((SwTxtHardBlank*)pHt)->GetChar();
break;
case RES_TXTATR_FTN:
{
const SwFmtFtn& rFtn = pHt->GetFtn();
if( rFtn.GetNumStr().Len() )
sOut = rFtn.GetNumStr();
else if( rFtn.IsEndNote() )
sOut = rWrt.pDoc->GetEndNoteInfo().aFmt.
GetNumStr( rFtn.GetNumber() );
else
sOut = rWrt.pDoc->GetFtnInfo().aFmt.
GetNumStr( rFtn.GetNumber() );
}
break;
}
if( sOut.Len() )
rWrt.Strm().WriteUnicodeOrByteText( sOut );
}
else if( nSwPos < *pHt->GetStart() )
break;
}
}
return bRet;
}
//------------------------
/* Ausgabe der Nodes */
//------------------------
static Writer& OutASC_SwTxtNode( Writer& rWrt, SwCntntNode& rNode )
{
const SwTxtNode& rNd = (SwTxtNode&)rNode;
xub_StrLen nStrPos = rWrt.pCurPam->GetPoint()->nContent.GetIndex();
xub_StrLen nNodeEnde = rNd.Len(), nEnde = nNodeEnde;
BOOL bLastNd = rWrt.pCurPam->GetPoint()->nNode == rWrt.pCurPam->GetMark()->nNode;
if( bLastNd )
nEnde = rWrt.pCurPam->GetMark()->nContent.GetIndex();
SwASC_AttrIter aAttrIter( (SwASCWriter&)rWrt, rNd, nStrPos );
if( !nStrPos )
rWrt.Strm().WriteUnicodeOrByteText( rNd.GetNumString() );
String aStr( rNd.GetTxt() );
if( rWrt.bASCII_ParaAsBlanc )
aStr.SearchAndReplaceAll( 0x0A, ' ' );
do {
xub_StrLen nNextAttr = aAttrIter.WhereNext();
if( nNextAttr > nEnde )
nNextAttr = nEnde;
if( !aAttrIter.OutAttr( nStrPos ))
rWrt.Strm().WriteUnicodeOrByteText(
aStr.Copy( nStrPos, nNextAttr - nStrPos ));
nStrPos = nNextAttr;
aAttrIter.NextPos();
} while( nStrPos < nEnde );
if( !bLastNd ||
( !rWrt.bWriteClipboardDoc && !rWrt.bASCII_NoLastLineEnd )
&& !nStrPos && nEnde == nNodeEnde )
rWrt.Strm().WriteUnicodeOrByteText( ((SwASCWriter&)rWrt).GetLineEnd());
return rWrt;
}
/*
* lege hier jetzt die Tabellen fuer die ASCII-Funktions-Pointer auf
* die Ausgabe-Funktionen an.
* Es sind lokale Strukturen, die nur innerhalb der ASCII-DLL
* bekannt sein muessen.
*/
SwNodeFnTab aASCNodeFnTab = {
/* RES_TXTNODE */ OutASC_SwTxtNode,
/* RES_GRFNODE */ 0,
/* RES_OLENODE */ 0
};
<|endoftext|> |
<commit_before>// RUN: %clangxx_asan -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os --check-prefix=CHECK
// RUN: %clangxx_asan -O1 %s -o %t && not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os --check-prefix=CHECK
// RUN: %clangxx_asan -O2 %s -o %t && not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os --check-prefix=CHECK
// RUN: %clangxx_asan -O3 %s -o %t && not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os --check-prefix=CHECK
__attribute__((noinline))
static void NullDeref(int *ptr) {
// CHECK: ERROR: AddressSanitizer: SEGV on unknown address
// CHECK: {{0x0*000.. .*pc 0x.*}}
ptr[10]++; // BOOM
// atos on Mac cannot extract the symbol name correctly.
// CHECK-Linux: {{ #0 0x.* in NullDeref.*null_deref.cc:}}[[@LINE-2]]
// CHECK-Darwin: {{ #0 0x.* in .*NullDeref.*null_deref.cc:}}[[@LINE-3]]
}
int main() {
NullDeref((int*)0);
// CHECK: {{ #1 0x.* in main.*null_deref.cc:}}[[@LINE-1]]
// CHECK: AddressSanitizer can not provide additional info.
}
<commit_msg>Add FreeBSD support to the address sanitizer's null_deref.cc test case Differential Revision: http://reviews.llvm.org/D4421<commit_after>// RUN: %clangxx_asan -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O1 %s -o %t && not %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O2 %s -o %t && not %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O3 %s -o %t && not %run %t 2>&1 | FileCheck %s
__attribute__((noinline))
static void NullDeref(int *ptr) {
// CHECK: ERROR: AddressSanitizer: SEGV on unknown address
// CHECK: {{0x0*000.. .*pc 0x.*}}
ptr[10]++; // BOOM
// atos on Mac cannot extract the symbol name correctly. Also, on FreeBSD 9.2
// the demangling function rejects local names with 'L' in front of them.
// CHECK: {{ #0 0x.* in .*NullDeref.*null_deref.cc:}}[[@LINE-3]]
}
int main() {
NullDeref((int*)0);
// CHECK: {{ #1 0x.* in main.*null_deref.cc:}}[[@LINE-1]]
// CHECK: AddressSanitizer can not provide additional info.
}
<|endoftext|> |
<commit_before>/*
*
* Copyright 2019 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "src/core/lib/iomgr/executor/mpmcqueue.h"
#include <grpc/grpc.h>
#include "src/core/lib/gprpp/thd.h"
#include "test/core/util/test_config.h"
#define THREAD_LARGE_ITERATION 10000
// Testing items for queue
struct WorkItem {
int index;
bool done;
WorkItem(int i) : index(i) { done = false; }
};
// Thread for put items into queue
class ProducerThread {
public:
ProducerThread(grpc_core::InfLenFIFOQueue* queue, int start_index,
int num_items)
: start_index_(start_index), num_items_(num_items), queue_(queue) {
items_ = nullptr;
thd_ = grpc_core::Thread(
"mpmcq_test_mt_put_thd",
[](void* th) { static_cast<ProducerThread*>(th)->Run(); }, this);
}
~ProducerThread() {
for (int i = 0; i < num_items_; ++i) {
GPR_ASSERT(items_[i]->done);
grpc_core::Delete(items_[i]);
}
gpr_free(items_);
}
void Start() { thd_.Start(); }
void Join() { thd_.Join(); }
private:
void Run() {
items_ = static_cast<WorkItem**>(gpr_zalloc(num_items_));
for (int i = 0; i < num_items_; ++i) {
items_[i] = grpc_core::New<WorkItem>(start_index_ + i);
queue_->Put(items_[i]);
}
}
int start_index_;
int num_items_;
grpc_core::InfLenFIFOQueue* queue_;
grpc_core::Thread thd_;
WorkItem** items_;
};
static void ConsumerThread(void* args) {
grpc_core::InfLenFIFOQueue* queue =
static_cast<grpc_core::InfLenFIFOQueue*>(args);
// count number of Get() called in this thread
int count = 0;
WorkItem* item;
while ((item = static_cast<WorkItem*>(queue->Get())) != nullptr) {
count++;
GPR_ASSERT(!item->done);
item->done = true;
}
gpr_log(GPR_DEBUG, "ConsumerThread: %d times of Get() called.", count);
}
static void test_get_empty(void) {
gpr_log(GPR_INFO, "test_get_empty");
grpc_core::InfLenFIFOQueue queue;
GPR_ASSERT(queue.count() == 0);
const int num_threads = 10;
grpc_core::Thread thds[num_threads];
// Fork threads. Threads should block at the beginning since queue is empty.
for (int i = 0; i < num_threads; ++i) {
thds[i] = grpc_core::Thread("mpmcq_test_ge_thd", ConsumerThread, &queue);
thds[i].Start();
}
WorkItem** items =
static_cast<WorkItem**>(gpr_zalloc(THREAD_LARGE_ITERATION));
for (int i = 0; i < THREAD_LARGE_ITERATION; ++i) {
items[i] = grpc_core::New<WorkItem>(i);
queue.Put(static_cast<void*>(items[i]));
}
gpr_log(GPR_DEBUG, "Terminating threads...");
for (int i = 0; i < num_threads; ++i) {
queue.Put(nullptr);
}
for (int i = 0; i < num_threads; ++i) {
thds[i].Join();
}
gpr_log(GPR_DEBUG, "Checking and Cleaning Up...");
for (int i = 0; i < THREAD_LARGE_ITERATION; ++i) {
GPR_ASSERT(items[i]->done);
grpc_core::Delete(items[i]);
}
gpr_free(items);
gpr_log(GPR_DEBUG, "Done.");
}
static void test_FIFO(void) {
gpr_log(GPR_INFO, "test_FIFO");
grpc_core::InfLenFIFOQueue large_queue;
for (int i = 0; i < THREAD_LARGE_ITERATION; ++i) {
large_queue.Put(static_cast<void*>(grpc_core::New<WorkItem>(i)));
}
GPR_ASSERT(large_queue.count() == THREAD_LARGE_ITERATION);
for (int i = 0; i < THREAD_LARGE_ITERATION; ++i) {
WorkItem* item = static_cast<WorkItem*>(large_queue.Get());
GPR_ASSERT(i == item->index);
grpc_core::Delete(item);
}
}
static void test_many_thread(void) {
gpr_log(GPR_INFO, "test_many_thread");
const int num_work_thd = 10;
const int num_get_thd = 20;
grpc_core::InfLenFIFOQueue queue;
ProducerThread** work_thds =
static_cast<ProducerThread**>(gpr_zalloc(num_work_thd));
grpc_core::Thread get_thds[num_get_thd];
gpr_log(GPR_DEBUG, "Fork ProducerThread...");
for (int i = 0; i < num_work_thd; ++i) {
work_thds[i] = grpc_core::New<ProducerThread>(
&queue, i * THREAD_LARGE_ITERATION, THREAD_LARGE_ITERATION);
work_thds[i]->Start();
}
gpr_log(GPR_DEBUG, "ProducerThread Started.");
gpr_log(GPR_DEBUG, "Fork Getter Thread...");
for (int i = 0; i < num_get_thd; ++i) {
get_thds[i] =
grpc_core::Thread("mpmcq_test_mt_get_thd", ConsumerThread, &queue);
get_thds[i].Start();
}
gpr_log(GPR_DEBUG, "Getter Thread Started.");
gpr_log(GPR_DEBUG, "Waiting ProducerThread to finish...");
for (int i = 0; i < num_work_thd; ++i) {
work_thds[i]->Join();
}
gpr_log(GPR_DEBUG, "All ProducerThread Terminated.");
gpr_log(GPR_DEBUG, "Terminating Getter Thread...");
for (int i = 0; i < num_get_thd; ++i) {
queue.Put(nullptr);
}
for (int i = 0; i < num_get_thd; ++i) {
get_thds[i].Join();
}
gpr_log(GPR_DEBUG, "All Getter Thread Terminated.");
gpr_log(GPR_DEBUG, "Checking WorkItems and Cleaning Up...");
for (int i = 0; i < num_work_thd; ++i) {
grpc_core::Delete(work_thds[i]);
}
gpr_free(work_thds);
gpr_log(GPR_DEBUG, "Done.");
}
int main(int argc, char** argv) {
grpc::testing::TestEnvironment env(argc, argv);
grpc_init();
gpr_set_log_verbosity(GPR_LOG_SEVERITY_DEBUG);
test_get_empty();
test_FIFO();
test_many_thread();
grpc_shutdown();
return 0;
}
<commit_msg>Change to malloc<commit_after>/*
*
* Copyright 2019 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "src/core/lib/iomgr/executor/mpmcqueue.h"
#include <grpc/grpc.h>
#include "src/core/lib/gprpp/thd.h"
#include "test/core/util/test_config.h"
#define THREAD_LARGE_ITERATION 10000
// Testing items for queue
struct WorkItem {
int index;
bool done;
WorkItem(int i) : index(i) { done = false; }
};
// Thread for put items into queue
class ProducerThread {
public:
ProducerThread(grpc_core::InfLenFIFOQueue* queue, int start_index,
int num_items)
: start_index_(start_index), num_items_(num_items), queue_(queue) {
items_ = nullptr;
thd_ = grpc_core::Thread(
"mpmcq_test_put_thd",
[](void* th) { static_cast<ProducerThread*>(th)->Run(); }, this);
}
~ProducerThread() {
for (int i = 0; i < num_items_; ++i) {
GPR_ASSERT(items_[i]->done);
grpc_core::Delete(items_[i]);
}
gpr_free(items_);
}
void Start() { thd_.Start(); }
void Join() { thd_.Join(); }
private:
void Run() {
items_ =
static_cast<WorkItem**>(gpr_malloc(num_items_ * sizeof(WorkItem*)));
for (int i = 0; i < num_items_; ++i) {
items_[i] = grpc_core::New<WorkItem>(start_index_ + i);
queue_->Put(items_[i]);
}
}
int start_index_;
int num_items_;
grpc_core::InfLenFIFOQueue* queue_;
grpc_core::Thread thd_;
WorkItem** items_;
};
static void ConsumerThread(void* args) {
grpc_core::InfLenFIFOQueue* queue =
static_cast<grpc_core::InfLenFIFOQueue*>(args);
// count number of Get() called in this thread
int count = 0;
WorkItem* item;
while ((item = static_cast<WorkItem*>(queue->Get())) != nullptr) {
count++;
GPR_ASSERT(!item->done);
item->done = true;
}
gpr_log(GPR_DEBUG, "ConsumerThread: %d times of Get() called.", count);
}
static void test_get_empty(void) {
gpr_log(GPR_INFO, "test_get_empty");
grpc_core::InfLenFIFOQueue queue;
GPR_ASSERT(queue.count() == 0);
const int num_threads = 10;
grpc_core::Thread thds[num_threads];
// Fork threads. Threads should block at the beginning since queue is empty.
for (int i = 0; i < num_threads; ++i) {
thds[i] = grpc_core::Thread("mpmcq_test_ge_thd", ConsumerThread, &queue);
thds[i].Start();
}
WorkItem** items = static_cast<WorkItem**>(
gpr_malloc(THREAD_LARGE_ITERATION * sizeof(WorkItem*)));
for (int i = 0; i < THREAD_LARGE_ITERATION; ++i) {
items[i] = grpc_core::New<WorkItem>(i);
queue.Put(static_cast<void*>(items[i]));
}
gpr_log(GPR_DEBUG, "Terminating threads...");
for (int i = 0; i < num_threads; ++i) {
queue.Put(nullptr);
}
for (int i = 0; i < num_threads; ++i) {
thds[i].Join();
}
gpr_log(GPR_DEBUG, "Checking and Cleaning Up...");
for (int i = 0; i < THREAD_LARGE_ITERATION; ++i) {
GPR_ASSERT(items[i]->done);
grpc_core::Delete(items[i]);
}
gpr_free(items);
gpr_log(GPR_DEBUG, "Done.");
}
static void test_FIFO(void) {
gpr_log(GPR_INFO, "test_FIFO");
grpc_core::InfLenFIFOQueue large_queue;
for (int i = 0; i < THREAD_LARGE_ITERATION; ++i) {
large_queue.Put(static_cast<void*>(grpc_core::New<WorkItem>(i)));
}
GPR_ASSERT(large_queue.count() == THREAD_LARGE_ITERATION);
for (int i = 0; i < THREAD_LARGE_ITERATION; ++i) {
WorkItem* item = static_cast<WorkItem*>(large_queue.Get());
GPR_ASSERT(i == item->index);
grpc_core::Delete(item);
}
}
static void test_many_thread(void) {
gpr_log(GPR_INFO, "test_many_thread");
const int num_work_thd = 10;
const int num_get_thd = 20;
grpc_core::InfLenFIFOQueue queue;
ProducerThread** work_thds = static_cast<ProducerThread**>(
gpr_malloc(num_work_thd * sizeof(ProducerThread*)));
grpc_core::Thread get_thds[num_get_thd];
gpr_log(GPR_DEBUG, "Fork ProducerThread...");
for (int i = 0; i < num_work_thd; ++i) {
work_thds[i] = grpc_core::New<ProducerThread>(
&queue, i * THREAD_LARGE_ITERATION, THREAD_LARGE_ITERATION);
work_thds[i]->Start();
}
gpr_log(GPR_DEBUG, "ProducerThread Started.");
gpr_log(GPR_DEBUG, "Fork Getter Thread...");
for (int i = 0; i < num_get_thd; ++i) {
get_thds[i] =
grpc_core::Thread("mpmcq_test_mt_get_thd", ConsumerThread, &queue);
get_thds[i].Start();
}
gpr_log(GPR_DEBUG, "Getter Thread Started.");
gpr_log(GPR_DEBUG, "Waiting ProducerThread to finish...");
for (int i = 0; i < num_work_thd; ++i) {
work_thds[i]->Join();
}
gpr_log(GPR_DEBUG, "All ProducerThread Terminated.");
gpr_log(GPR_DEBUG, "Terminating Getter Thread...");
for (int i = 0; i < num_get_thd; ++i) {
queue.Put(nullptr);
}
for (int i = 0; i < num_get_thd; ++i) {
get_thds[i].Join();
}
gpr_log(GPR_DEBUG, "All Getter Thread Terminated.");
gpr_log(GPR_DEBUG, "Checking WorkItems and Cleaning Up...");
for (int i = 0; i < num_work_thd; ++i) {
grpc_core::Delete(work_thds[i]);
}
gpr_free(work_thds);
gpr_log(GPR_DEBUG, "Done.");
}
int main(int argc, char** argv) {
grpc::testing::TestEnvironment env(argc, argv);
grpc_init();
gpr_set_log_verbosity(GPR_LOG_SEVERITY_DEBUG);
test_get_empty();
test_FIFO();
test_many_thread();
grpc_shutdown();
return 0;
}
<|endoftext|> |
<commit_before>#include "ai.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace BWAPI;
using namespace Filter;
// Global variables.
bool supplyNeeded;
int infantryBuildingCheckTimer;
int infantryBuildingCost;
int infantryBuildingLimit;
int infantryCost;
int resourceDepotBuildingCheckTimer;
int resourceDepotBuildingCost;
int resourceDepotBuildingLimit;
int savingMinerals;
int supplyCheckTimer;
int workerLimit;
Race playerRace;
static int infantryBuildingChecked;
static int resourceDepotBuildingChecked;
static int supplyChecked;
UnitType infantryBuilding;
UnitType infantryType;
UnitType resourceDepotBuilding;
UnitType supplyProviderType;
UnitType workerType;
void ai::onEnd(bool isWinner){
}
void ai::onFrame(){
int frameCount = Broodwar->getFrameCount();
if(!Broodwar->self()
|| frameCount % Broodwar->getLatencyFrames() != 0
|| Broodwar->isPaused()
|| Broodwar->isReplay()){
return;
}
int infantryBuildingCount = Broodwar->self()->allUnitCount(infantryBuilding);
int minerals = Broodwar->self()->minerals();
int resourceDepotBuildingCount = Broodwar->self()->allUnitCount(resourceDepotBuilding);
int supplyTotal = Broodwar->self()->supplyTotal();
int supplyUsed = Broodwar->self()->supplyUsed();
int workerCount = Broodwar->self()->allUnitCount(workerType);
int supplyCutoff = (int)(supplyUsed / 10);
if(supplyCutoff < 4){
supplyCutoff = 4;
}
if(supplyTotal < 400
&& supplyTotal - supplyUsed <= supplyCutoff
&& Broodwar->self()->incompleteUnitCount(supplyProviderType) == 0){
savingMinerals = 100;
supplyNeeded = true;
}else{
savingMinerals = 0;
supplyNeeded = false;
}
if(minerals >= infantryBuildingCost
&& infantryBuildingCount < infantryBuildingLimit){
savingMinerals += infantryBuildingCost;
}
if(minerals >= resourceDepotBuildingCost
&& resourceDepotBuildingCount < resourceDepotBuildingLimit){
savingMinerals += resourceDepotBuildingCost;
}
for(auto &unit : Broodwar->self()->getUnits()){
if(!unit->exists()
|| !unit->isCompleted()
|| unit->isConstructing()
|| unit->isLoaded()
|| unit->isLockedDown()
|| unit->isMaelstrommed()
|| !unit->isPowered()
|| unit->isStasised()
|| unit->isStuck()){
continue;
}
// Setup unit information variables.
bool unitIsIdle = unit->isIdle();
UnitType unitType = unit->getType();
// Handle workers.
if(unitType.isWorker()){
// Handle insufficient supply by building Pylon or building Supply Depot.
if(playerRace != Races::Zerg
&& supplyNeeded
&& minerals >= 100
&& supplyChecked + supplyCheckTimer < frameCount){
supplyChecked = frameCount;
Unit supplyBuilder = unit->getClosestUnit(GetType == supplyProviderType.whatBuilds().first
&& (IsIdle || IsGatheringMinerals)
&& IsOwned);
buildBuilding(
supplyBuilder,
supplyProviderType
);
// Build Command Centers, Hatcheries, and Nexuses.
}else if(resourceDepotBuildingCount < resourceDepotBuildingLimit
&& minerals >= resourceDepotBuildingCost
&& resourceDepotBuildingChecked + resourceDepotBuildingCheckTimer < frameCount){
resourceDepotBuildingChecked = frameCount;
buildBuilding(
unit,
resourceDepotBuilding
);
// Build Barracks/Gateway/Spawning Pool.
}else if(infantryBuildingCount < infantryBuildingLimit
&& minerals >= infantryBuildingCost
&& infantryBuildingChecked + infantryBuildingCheckTimer < frameCount){
infantryBuildingChecked = frameCount;
buildBuilding(
unit,
infantryBuilding
);
}else if(unitIsIdle){
// Return resources.
if(unit->isCarryingMinerals()
|| unit->isCarryingGas()){
unit->returnCargo();
// Gather resources.
}else{
unit->gather(unit->getClosestUnit(IsMineralField || IsRefinery));
}
}
}else if(unitIsIdle){
// Handle Command Centers, Hatcheries, and Nexuses.
if(unitType.isResourceDepot()){
if(playerRace == Races::Zerg
&& supplyNeeded
&& playerRace == Races::Zerg
&& minerals >= 100
&& supplyChecked + supplyCheckTimer < frameCount){
supplyChecked = frameCount;
// Train Overlords.
unit->train(supplyProviderType);
}else if(workerCount < workerLimit
&& minerals >= savingMinerals + 50){
// Train workers.
unit->train(workerType);
}else if(playerRace == Races::Zerg
&& minerals >= savingMinerals + infantryCost){
// Train Zerglings.
unit->train(infantryType);
}
// Handle Barracks and Gateways.
}else if(playerRace != Races::Zerg
&& unit->canTrain(infantryType)){
if(minerals >= savingMinerals + infantryCost){
// Train Marines and Zealots.
unit->train(infantryType);
}
// Everything else should attack-move scout.
}else{
Position position = unit->getPosition();
position.x += rand() % 501 - 250;
position.y += rand() % 501 - 250;
if(!unit->attack(position)){
unit->move(position);
}
}
}
}
}
void ai::onNukeDetect(BWAPI::Position target){
}
void ai::onPlayerLeft(BWAPI::Player player){
}
void ai::onReceiveText(BWAPI::Player player, std::string text){
}
void ai::onSaveGame(std::string gameName){
}
void ai::onSendText(std::string text){
Broodwar->sendText("%s", text.c_str());
}
void ai::onStart(){
Broodwar->setCommandOptimizationLevel(1);
srand(time(NULL));
// Setup global variables.
infantryBuildingChecked = 0;
infantryBuildingCheckTimer = 1900;
playerRace = Broodwar->self()->getRace();
resourceDepotBuildingChecked = 0;
resourceDepotBuildingCheckTimer = 1900;
savingMinerals = 0;
supplyChecked = 0;
supplyCheckTimer = 500;
supplyNeeded = false;
supplyProviderType = playerRace.getSupplyProvider();
workerLimit = 25;
workerType = playerRace.getWorker();
// Handle race-specific stuff.
if(playerRace == Races::Zerg){
infantryBuilding = UnitTypes::Zerg_Spawning_Pool;
infantryBuildingCost = 200;
infantryBuildingLimit = 1;
infantryCost = 50;
infantryType = UnitTypes::Zerg_Zergling;
resourceDepotBuilding = UnitTypes::Zerg_Hatchery;
resourceDepotBuildingCost = 300;
resourceDepotBuildingLimit = 5;
}else if(playerRace == Races::Terran){
infantryBuilding = UnitTypes::Terran_Barracks;
infantryBuildingCost = 150;
infantryBuildingLimit = 5;
infantryCost = 50;
infantryType = UnitTypes::Terran_Marine;
resourceDepotBuilding = UnitTypes::Terran_Command_Center;
resourceDepotBuildingCost = 400;
resourceDepotBuildingLimit = 1;
}else{
infantryBuilding = UnitTypes::Protoss_Gateway;
infantryBuildingCost = 200;
infantryBuildingLimit = 5;
infantryCost = 100;
infantryType = UnitTypes::Protoss_Zealot;
resourceDepotBuilding = UnitTypes::Protoss_Nexus;
resourceDepotBuildingCost = 400;
resourceDepotBuildingLimit = 1;
}
Broodwar->sendText("glhf");
}
void ai::onUnitComplete(BWAPI::Unit unit){
}
void ai::onUnitCreate(BWAPI::Unit unit){
}
void ai::onUnitDestroy(BWAPI::Unit unit){
}
void ai::onUnitDiscover(BWAPI::Unit unit){
}
void ai::onUnitEvade(BWAPI::Unit unit){
}
void ai::onUnitHide(BWAPI::Unit unit){
}
void ai::onUnitMorph(BWAPI::Unit unit){
}
void ai::onUnitRenegade(BWAPI::Unit unit){
}
void ai::onUnitShow(BWAPI::Unit unit){
}
bool buildBuilding(Unit builder, UnitType building){
TilePosition targetBuildLocation = Broodwar->getBuildLocation(
builing,
builder->getTilePosition()
);
if(targetBuildLocation){
return builder->build(
building,
targetBuildLocation
);
}
return false;
}
<commit_msg>replaced hardcoded supply cost with savingMinerals check<commit_after>#include "ai.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace BWAPI;
using namespace Filter;
// Global variables.
bool supplyNeeded;
int infantryBuildingCheckTimer;
int infantryBuildingCost;
int infantryBuildingLimit;
int infantryCost;
int resourceDepotBuildingCheckTimer;
int resourceDepotBuildingCost;
int resourceDepotBuildingLimit;
int savingMinerals;
int supplyCheckTimer;
int workerLimit;
Race playerRace;
static int infantryBuildingChecked;
static int resourceDepotBuildingChecked;
static int supplyChecked;
UnitType infantryBuilding;
UnitType infantryType;
UnitType resourceDepotBuilding;
UnitType supplyProviderType;
UnitType workerType;
void ai::onEnd(bool isWinner){
}
void ai::onFrame(){
int frameCount = Broodwar->getFrameCount();
if(!Broodwar->self()
|| frameCount % Broodwar->getLatencyFrames() != 0
|| Broodwar->isPaused()
|| Broodwar->isReplay()){
return;
}
int infantryBuildingCount = Broodwar->self()->allUnitCount(infantryBuilding);
int minerals = Broodwar->self()->minerals();
int resourceDepotBuildingCount = Broodwar->self()->allUnitCount(resourceDepotBuilding);
int supplyTotal = Broodwar->self()->supplyTotal();
int supplyUsed = Broodwar->self()->supplyUsed();
int workerCount = Broodwar->self()->allUnitCount(workerType);
int supplyCutoff = (int)(supplyUsed / 10);
if(supplyCutoff < 4){
supplyCutoff = 4;
}
if(supplyTotal < 400
&& supplyTotal - supplyUsed <= supplyCutoff
&& Broodwar->self()->incompleteUnitCount(supplyProviderType) == 0){
savingMinerals = 100;
supplyNeeded = true;
}else{
savingMinerals = 0;
supplyNeeded = false;
}
if(minerals >= infantryBuildingCost
&& infantryBuildingCount < infantryBuildingLimit){
savingMinerals += infantryBuildingCost;
}
if(minerals >= resourceDepotBuildingCost
&& resourceDepotBuildingCount < resourceDepotBuildingLimit){
savingMinerals += resourceDepotBuildingCost;
}
for(auto &unit : Broodwar->self()->getUnits()){
if(!unit->exists()
|| !unit->isCompleted()
|| unit->isConstructing()
|| unit->isLoaded()
|| unit->isLockedDown()
|| unit->isMaelstrommed()
|| !unit->isPowered()
|| unit->isStasised()
|| unit->isStuck()){
continue;
}
// Setup unit information variables.
bool unitIsIdle = unit->isIdle();
UnitType unitType = unit->getType();
// Handle workers.
if(unitType.isWorker()){
// Handle insufficient supply by building Pylon or building Supply Depot.
if(playerRace != Races::Zerg
&& supplyNeeded
&& minerals >= savingMinerals
&& supplyChecked + supplyCheckTimer < frameCount){
supplyChecked = frameCount;
Unit supplyBuilder = unit->getClosestUnit(GetType == supplyProviderType.whatBuilds().first
&& (IsIdle || IsGatheringMinerals)
&& IsOwned);
buildBuilding(
supplyBuilder,
supplyProviderType
);
// Build Command Centers, Hatcheries, and Nexuses.
}else if(resourceDepotBuildingCount < resourceDepotBuildingLimit
&& minerals >= resourceDepotBuildingCost
&& resourceDepotBuildingChecked + resourceDepotBuildingCheckTimer < frameCount){
resourceDepotBuildingChecked = frameCount;
buildBuilding(
unit,
resourceDepotBuilding
);
// Build Barracks/Gateway/Spawning Pool.
}else if(infantryBuildingCount < infantryBuildingLimit
&& minerals >= infantryBuildingCost
&& infantryBuildingChecked + infantryBuildingCheckTimer < frameCount){
infantryBuildingChecked = frameCount;
buildBuilding(
unit,
infantryBuilding
);
}else if(unitIsIdle){
// Return resources.
if(unit->isCarryingMinerals()
|| unit->isCarryingGas()){
unit->returnCargo();
// Gather resources.
}else{
unit->gather(unit->getClosestUnit(IsMineralField || IsRefinery));
}
}
}else if(unitIsIdle){
// Handle Command Centers, Hatcheries, and Nexuses.
if(unitType.isResourceDepot()){
if(playerRace == Races::Zerg
&& supplyNeeded
&& playerRace == Races::Zerg
&& minerals >= savingMinerals
&& supplyChecked + supplyCheckTimer < frameCount){
supplyChecked = frameCount;
// Train Overlords.
unit->train(supplyProviderType);
}else if(workerCount < workerLimit
&& minerals >= savingMinerals + 50){
// Train workers.
unit->train(workerType);
}else if(playerRace == Races::Zerg
&& minerals >= savingMinerals + infantryCost){
// Train Zerglings.
unit->train(infantryType);
}
// Handle Barracks and Gateways.
}else if(playerRace != Races::Zerg
&& unit->canTrain(infantryType)){
if(minerals >= savingMinerals + infantryCost){
// Train Marines and Zealots.
unit->train(infantryType);
}
// Everything else should attack-move scout.
}else{
Position position = unit->getPosition();
position.x += rand() % 501 - 250;
position.y += rand() % 501 - 250;
if(!unit->attack(position)){
unit->move(position);
}
}
}
}
}
void ai::onNukeDetect(BWAPI::Position target){
}
void ai::onPlayerLeft(BWAPI::Player player){
}
void ai::onReceiveText(BWAPI::Player player, std::string text){
}
void ai::onSaveGame(std::string gameName){
}
void ai::onSendText(std::string text){
Broodwar->sendText("%s", text.c_str());
}
void ai::onStart(){
Broodwar->setCommandOptimizationLevel(1);
srand(time(NULL));
// Setup global variables.
infantryBuildingChecked = 0;
infantryBuildingCheckTimer = 1900;
playerRace = Broodwar->self()->getRace();
resourceDepotBuildingChecked = 0;
resourceDepotBuildingCheckTimer = 1900;
savingMinerals = 0;
supplyChecked = 0;
supplyCheckTimer = 500;
supplyNeeded = false;
supplyProviderType = playerRace.getSupplyProvider();
workerLimit = 25;
workerType = playerRace.getWorker();
// Handle race-specific stuff.
if(playerRace == Races::Zerg){
infantryBuilding = UnitTypes::Zerg_Spawning_Pool;
infantryBuildingCost = 200;
infantryBuildingLimit = 1;
infantryCost = 50;
infantryType = UnitTypes::Zerg_Zergling;
resourceDepotBuilding = UnitTypes::Zerg_Hatchery;
resourceDepotBuildingCost = 300;
resourceDepotBuildingLimit = 5;
}else if(playerRace == Races::Terran){
infantryBuilding = UnitTypes::Terran_Barracks;
infantryBuildingCost = 150;
infantryBuildingLimit = 5;
infantryCost = 50;
infantryType = UnitTypes::Terran_Marine;
resourceDepotBuilding = UnitTypes::Terran_Command_Center;
resourceDepotBuildingCost = 400;
resourceDepotBuildingLimit = 1;
}else{
infantryBuilding = UnitTypes::Protoss_Gateway;
infantryBuildingCost = 200;
infantryBuildingLimit = 5;
infantryCost = 100;
infantryType = UnitTypes::Protoss_Zealot;
resourceDepotBuilding = UnitTypes::Protoss_Nexus;
resourceDepotBuildingCost = 400;
resourceDepotBuildingLimit = 1;
}
Broodwar->sendText("glhf");
}
void ai::onUnitComplete(BWAPI::Unit unit){
}
void ai::onUnitCreate(BWAPI::Unit unit){
}
void ai::onUnitDestroy(BWAPI::Unit unit){
}
void ai::onUnitDiscover(BWAPI::Unit unit){
}
void ai::onUnitEvade(BWAPI::Unit unit){
}
void ai::onUnitHide(BWAPI::Unit unit){
}
void ai::onUnitMorph(BWAPI::Unit unit){
}
void ai::onUnitRenegade(BWAPI::Unit unit){
}
void ai::onUnitShow(BWAPI::Unit unit){
}
bool buildBuilding(Unit builder, UnitType building){
TilePosition targetBuildLocation = Broodwar->getBuildLocation(
builing,
builder->getTilePosition()
);
if(targetBuildLocation){
return builder->build(
building,
targetBuildLocation
);
}
return false;
}
<|endoftext|> |
<commit_before>#include "ai.h"
#include <iostream>
using namespace BWAPI;
using namespace Filter;
void ai::onEnd(bool isWinner){
}
void ai::onFrame(){
if(!Broodwar->self()
|| Broodwar->getFrameCount() % Broodwar->getLatencyFrames() != 0
|| Broodwar->isPaused()
|| Broodwar->isReplay()){
return;
}
for(auto &u : Broodwar->self()->getUnits()){
if(!u->exists()
|| !u->isCompleted()
|| u->isConstructing()
|| u->isLoaded()
|| u->isLockedDown()
|| u->isMaelstrommed()
|| !u->isPowered()
|| u->isStasised()
|| u->isStuck()){
continue;
}
// Handle workers.
if(u->getType().isWorker()){
if(u->isIdle()){
if(u->isCarryingMinerals()
|| u->isCarryingGas()){
u->returnCargo();
}else{
u->gather(u->getClosestUnit(IsMineralField || IsRefinery));
}
}
// Handle Command Centers, Hatcheries, and Nexuses.
}else if(u->getType().isResourceDepot()){
// Build workers.
if(u->isIdle()){
u->train(u->getType().getRace().getWorker());
}
}
}
}
void ai::onNukeDetect(BWAPI::Position target){
}
void ai::onPlayerLeft(BWAPI::Player player){
}
void ai::onReceiveText(BWAPI::Player player, std::string text){
}
void ai::onSaveGame(std::string gameName){
}
void ai::onSendText(std::string text){
Broodwar->sendText("%s", text.c_str());
}
void ai::onStart(){
Broodwar->setCommandOptimizationLevel(2);
Broodwar->sendText("iterami/SC-AI.cpp vs");
}
void ai::onUnitComplete(BWAPI::Unit unit){
}
void ai::onUnitCreate(BWAPI::Unit unit){
}
void ai::onUnitDestroy(BWAPI::Unit unit){
}
void ai::onUnitDiscover(BWAPI::Unit unit){
}
void ai::onUnitEvade(BWAPI::Unit unit){
}
void ai::onUnitHide(BWAPI::Unit unit){
}
void ai::onUnitMorph(BWAPI::Unit unit){
}
void ai::onUnitRenegade(BWAPI::Unit unit){
}
void ai::onUnitShow(BWAPI::Unit unit){
}
<commit_msg>improved formatting<commit_after>#include "ai.h"
#include <iostream>
using namespace BWAPI;
using namespace Filter;
void ai::onEnd(bool isWinner){
}
void ai::onFrame(){
if(!Broodwar->self()
|| Broodwar->getFrameCount() % Broodwar->getLatencyFrames() != 0
|| Broodwar->isPaused()
|| Broodwar->isReplay()){
return;
}
for(auto &u : Broodwar->self()->getUnits()){
if(!u->exists()
|| !u->isCompleted()
|| u->isConstructing()
|| u->isLoaded()
|| u->isLockedDown()
|| u->isMaelstrommed()
|| !u->isPowered()
|| u->isStasised()
|| u->isStuck()){
continue;
}
// Handle workers.
if(u->getType().isWorker()){
if(!u->isIdle()){
continue;
}
if(u->isCarryingMinerals()
|| u->isCarryingGas()){
u->returnCargo();
}else{
u->gather(u->getClosestUnit(IsMineralField || IsRefinery));
}
// Handle Command Centers, Hatcheries, and Nexuses.
}else if(u->getType().isResourceDepot()){
if(!u->isIdle()){
continue
}
// Build workers.
u->train(u->getType().getRace().getWorker());
}
}
}
void ai::onNukeDetect(BWAPI::Position target){
}
void ai::onPlayerLeft(BWAPI::Player player){
}
void ai::onReceiveText(BWAPI::Player player, std::string text){
}
void ai::onSaveGame(std::string gameName){
}
void ai::onSendText(std::string text){
Broodwar->sendText("%s", text.c_str());
}
void ai::onStart(){
Broodwar->setCommandOptimizationLevel(2);
Broodwar->sendText("iterami/SC-AI.cpp vs");
}
void ai::onUnitComplete(BWAPI::Unit unit){
}
void ai::onUnitCreate(BWAPI::Unit unit){
}
void ai::onUnitDestroy(BWAPI::Unit unit){
}
void ai::onUnitDiscover(BWAPI::Unit unit){
}
void ai::onUnitEvade(BWAPI::Unit unit){
}
void ai::onUnitHide(BWAPI::Unit unit){
}
void ai::onUnitMorph(BWAPI::Unit unit){
}
void ai::onUnitRenegade(BWAPI::Unit unit){
}
void ai::onUnitShow(BWAPI::Unit unit){
}
<|endoftext|> |
<commit_before>#include "helpers/read_test_entries.h"
#include <assert.h>
#include <string>
#include <regex>
#include "helpers/file_helpers.h"
using std::move;
using std::regex;
using std::regex_search;
using std::regex_replace;
using std::regex_constants::extended;
using std::smatch;
using std::string;
using std::vector;
static string trim_output(const string &input) {
string result(input);
result = regex_replace(result, regex("[\n\t ]+", extended), string(" "));
result = regex_replace(result, regex("^ ", extended), string(""));
result = regex_replace(result, regex(" $", extended), string(""));
result = regex_replace(result, regex("\\) \\)", extended), string("))"));
return result;
}
static vector<TestEntry> parse_test_entries(string content) {
regex header_pattern("(^|\n)===+\n" "([^=]+)\n" "===+\n", extended);
regex separator_pattern("---+\r?\n", extended);
vector<string> descriptions;
vector<string> bodies;
for (;;) {
smatch matches;
if (!regex_search(content, matches, header_pattern) || matches.empty())
break;
string description = matches[1].str();
descriptions.push_back(description);
if (!bodies.empty())
bodies.back().erase(matches.position());
content.erase(0, matches.position() + matches[0].length());
bodies.push_back(content);
}
vector<TestEntry> result;
for (size_t i = 0; i < descriptions.size(); i++) {
string body = bodies[i];
smatch matches;
if (regex_search(body, matches, separator_pattern)) {
result.push_back({
descriptions[i],
body.substr(0, matches.position() - 1),
trim_output(body.substr(matches.position() + matches[0].length()))
});
} else {
puts(("Invalid corpus entry with description: " + descriptions[i]).c_str());
abort();
}
}
return result;
}
vector<TestEntry> read_real_language_corpus(string language_name) {
vector<TestEntry> result;
string corpus_directory = join_path({"test", "fixtures", "grammars", language_name, "corpus"});
for (string &test_filename : list_directory(corpus_directory)) {
for (TestEntry &entry : parse_test_entries(read_file(join_path({corpus_directory, test_filename})))) {
result.push_back(entry);
}
}
string error_test_filename = join_path({"test", "fixtures", "error_corpus", language_name + "_errors.txt"});
for (TestEntry &entry : parse_test_entries(read_file(error_test_filename))) {
result.push_back(entry);
}
return result;
}
vector<TestEntry> read_test_language_corpus(string language_name) {
vector<TestEntry> result;
string test_directory = join_path({"test", "fixtures", "test_grammars", language_name});
for (string &test_filename : list_directory(test_directory)) {
for (TestEntry &entry : parse_test_entries(read_file(join_path({test_directory, test_filename})))) {
result.push_back(entry);
}
}
return result;
}
vector<ExampleEntry> examples_for_language(string language_name) {
vector<ExampleEntry> result;
string examples_directory = join_path({"test", "fixtures", "grammars", language_name, "examples"});
for (string &filename : list_directory(examples_directory)) {
auto content = read_file(join_path({examples_directory, filename}));
if (!content.empty()) {
result.push_back({filename, move(content)});
}
}
return result;
}
<commit_msg>Fix capture of corpus descriptions in integration tests<commit_after>#include "helpers/read_test_entries.h"
#include <assert.h>
#include <string>
#include <regex>
#include "helpers/file_helpers.h"
using std::move;
using std::regex;
using std::regex_search;
using std::regex_replace;
using std::regex_constants::extended;
using std::smatch;
using std::string;
using std::vector;
static string trim_output(const string &input) {
string result(input);
result = regex_replace(result, regex("[\n\t ]+", extended), string(" "));
result = regex_replace(result, regex("^ ", extended), string(""));
result = regex_replace(result, regex(" $", extended), string(""));
result = regex_replace(result, regex("\\) \\)", extended), string("))"));
return result;
}
static vector<TestEntry> parse_test_entries(string content) {
regex header_pattern("(^|\n)===+\n" "([^=]+)\n" "===+\n", extended);
regex separator_pattern("---+\r?\n", extended);
vector<string> descriptions;
vector<string> bodies;
for (;;) {
smatch matches;
if (!regex_search(content, matches, header_pattern) || matches.empty())
break;
string description = matches[2].str();
descriptions.push_back(description);
if (!bodies.empty())
bodies.back().erase(matches.position());
content.erase(0, matches.position() + matches[0].length());
bodies.push_back(content);
}
vector<TestEntry> result;
for (size_t i = 0; i < descriptions.size(); i++) {
string body = bodies[i];
smatch matches;
if (regex_search(body, matches, separator_pattern)) {
result.push_back({
descriptions[i],
body.substr(0, matches.position() - 1),
trim_output(body.substr(matches.position() + matches[0].length()))
});
} else {
puts(("Invalid corpus entry with description: " + descriptions[i]).c_str());
abort();
}
}
return result;
}
vector<TestEntry> read_real_language_corpus(string language_name) {
vector<TestEntry> result;
string corpus_directory = join_path({"test", "fixtures", "grammars", language_name, "corpus"});
for (string &test_filename : list_directory(corpus_directory)) {
for (TestEntry &entry : parse_test_entries(read_file(join_path({corpus_directory, test_filename})))) {
result.push_back(entry);
}
}
string error_test_filename = join_path({"test", "fixtures", "error_corpus", language_name + "_errors.txt"});
for (TestEntry &entry : parse_test_entries(read_file(error_test_filename))) {
result.push_back(entry);
}
return result;
}
vector<TestEntry> read_test_language_corpus(string language_name) {
vector<TestEntry> result;
string test_directory = join_path({"test", "fixtures", "test_grammars", language_name});
for (string &test_filename : list_directory(test_directory)) {
for (TestEntry &entry : parse_test_entries(read_file(join_path({test_directory, test_filename})))) {
result.push_back(entry);
}
}
return result;
}
vector<ExampleEntry> examples_for_language(string language_name) {
vector<ExampleEntry> result;
string examples_directory = join_path({"test", "fixtures", "grammars", language_name, "examples"});
for (string &filename : list_directory(examples_directory)) {
auto content = read_file(join_path({examples_directory, filename}));
if (!content.empty()) {
result.push_back({filename, move(content)});
}
}
return result;
}
<|endoftext|> |
<commit_before>
#include "TestGlobals.h"
#include "ChunkBuffer.h"
int main(int argc, char** argv)
{
{
cChunkBuffer buffer;
// Empty chunks
buffer.SetBlock(0,0,0, 0xAB);
testassert(buffer.GetBlock(0,0,0) == 0xAB);
buffer.SetMeta(0,16,0, 0xC);
testassert(buffer.GetMeta(0,16,0) == 0xC);
// loaded but not written segments
testassert(buffer.GetBlock(1,0,0) == 0x0);
testassert(buffer.GetMeta(1,16,0) == 0x0);
// Notloaded segments
testassert(buffer.GetBlock(0,32,0) == 0x0);
testassert(buffer.GetMeta(0,48,0) == 0x0);
// Out of Range
CheckAsserts(
buffer.SetBlock(-1, 0, 0, 0);
);
CheckAsserts(
buffer.SetBlock(0, -1, 0, 0);
);
CheckAsserts(
buffer.SetBlock(0, 0, -1, 0);
);
CheckAsserts(
buffer.SetBlock(256, 0, 0, 0);
);
CheckAsserts(
buffer.SetBlock(0, 256, 0, 0);
);
CheckAsserts(
buffer.SetBlock(0, 0, 256, 0);
);
// Out of Range
CheckAsserts(
buffer.GetBlock(-1, 0, 0);
);
CheckAsserts(
buffer.GetBlock(0, -1, 0);
);
CheckAsserts(
buffer.GetBlock(0, 0, -1);
);
CheckAsserts(
buffer.GetBlock(256, 0, 0);
);
CheckAsserts(
buffer.GetBlock(0, 256, 0);
);
CheckAsserts(
buffer.GetBlock(0, 0, 256);
);
// Out of Range
CheckAsserts(
buffer.SetMeta(-1, 0, 0, 0);
);
CheckAsserts(
buffer.SetMeta(0, -1, 0, 0);
);
CheckAsserts(
buffer.SetMeta(0, 0, -1, 0);
);
CheckAsserts(
buffer.SetMeta(256, 0, 0, 0);
);
CheckAsserts(
buffer.SetMeta(0, 256, 0, 0);
);
CheckAsserts(
buffer.SetMeta(0, 0, 256, 0);
);
// Out of Range
CheckAsserts(
buffer.GetMeta(-1, 0, 0);
);
CheckAsserts(
buffer.GetMeta(0, -1, 0);
);
CheckAsserts(
buffer.GetMeta(0, 0, -1);
);
CheckAsserts(
buffer.GetMeta(256, 0, 0);
);
CheckAsserts(
buffer.GetMeta(0, 256, 0);
);
CheckAsserts(
buffer.GetMeta(0, 0, 256);
);
}
{
cChunkBuffer buffer;
// Zero's
buffer.SetBlock(0,0,0, 0x0);
buffer.SetBlock(0,0,1, 0xAB);
testassert(buffer.GetBlock(0,0,0) == 0x0);
testassert(buffer.GetBlock(0,0,1) == 0xAB);
buffer.SetMeta(0,16,0, 0x0);
buffer.SetMeta(0,16,1, 0xC);
testassert(buffer.GetMeta(0,16,0) == 0x0);
testassert(buffer.GetMeta(0,16,1) == 0xC);
}
{
// Operator =
cChunkBuffer buffer;
buffer.SetBlock(0,0,0,0x42);
cChunkBuffer copy;
copy = std::move(buffer);
testassert(copy.GetBlock(0,0,0) == 0x42);
copy = std::move(copy);
testassert(copy.GetBlock(0,0,0) == 0x42);
}
return 0;
}
<commit_msg>C++11<commit_after>
#include "TestGlobals.h"
#include "ChunkBuffer.h"
int main(int argc, char** argv)
{
{
cChunkBuffer buffer;
// Empty chunks
buffer.SetBlock(0,0,0, 0xAB);
testassert(buffer.GetBlock(0,0,0) == 0xAB);
buffer.SetMeta(0,16,0, 0xC);
testassert(buffer.GetMeta(0,16,0) == 0xC);
// loaded but not written segments
testassert(buffer.GetBlock(1,0,0) == 0x0);
testassert(buffer.GetMeta(1,16,0) == 0x0);
// Notloaded segments
testassert(buffer.GetBlock(0,32,0) == 0x0);
testassert(buffer.GetMeta(0,48,0) == 0x0);
// Out of Range
CheckAsserts(
buffer.SetBlock(-1, 0, 0, 0);
);
CheckAsserts(
buffer.SetBlock(0, -1, 0, 0);
);
CheckAsserts(
buffer.SetBlock(0, 0, -1, 0);
);
CheckAsserts(
buffer.SetBlock(256, 0, 0, 0);
);
CheckAsserts(
buffer.SetBlock(0, 256, 0, 0);
);
CheckAsserts(
buffer.SetBlock(0, 0, 256, 0);
);
// Out of Range
CheckAsserts(
buffer.GetBlock(-1, 0, 0);
);
CheckAsserts(
buffer.GetBlock(0, -1, 0);
);
CheckAsserts(
buffer.GetBlock(0, 0, -1);
);
CheckAsserts(
buffer.GetBlock(256, 0, 0);
);
CheckAsserts(
buffer.GetBlock(0, 256, 0);
);
CheckAsserts(
buffer.GetBlock(0, 0, 256);
);
// Out of Range
CheckAsserts(
buffer.SetMeta(-1, 0, 0, 0);
);
CheckAsserts(
buffer.SetMeta(0, -1, 0, 0);
);
CheckAsserts(
buffer.SetMeta(0, 0, -1, 0);
);
CheckAsserts(
buffer.SetMeta(256, 0, 0, 0);
);
CheckAsserts(
buffer.SetMeta(0, 256, 0, 0);
);
CheckAsserts(
buffer.SetMeta(0, 0, 256, 0);
);
// Out of Range
CheckAsserts(
buffer.GetMeta(-1, 0, 0);
);
CheckAsserts(
buffer.GetMeta(0, -1, 0);
);
CheckAsserts(
buffer.GetMeta(0, 0, -1);
);
CheckAsserts(
buffer.GetMeta(256, 0, 0);
);
CheckAsserts(
buffer.GetMeta(0, 256, 0);
);
CheckAsserts(
buffer.GetMeta(0, 0, 256);
);
}
{
cChunkBuffer buffer;
// Zero's
buffer.SetBlock(0,0,0, 0x0);
buffer.SetBlock(0,0,1, 0xAB);
testassert(buffer.GetBlock(0,0,0) == 0x0);
testassert(buffer.GetBlock(0,0,1) == 0xAB);
buffer.SetMeta(0,16,0, 0x0);
buffer.SetMeta(0,16,1, 0xC);
testassert(buffer.GetMeta(0,16,0) == 0x0);
testassert(buffer.GetMeta(0,16,1) == 0xC);
}
{
// Operator =
cChunkBuffer buffer;
buffer.SetBlock(0,0,0,0x42);
cChunkBuffer copy;
#if __cplusplus < 201103L
copy = buffer;
#else
copy = std::move(buffer);
#endif
testassert(copy.GetBlock(0,0,0) == 0x42);
#if __cplusplus < 201103L
copy = copy;
#else
copy = std::move(copy);
#endif
testassert(copy.GetBlock(0,0,0) == 0x42);
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkFrontBufferedStream.h"
#include "SkRefCnt.h"
#include "SkStream.h"
#include "SkTypes.h"
#include "Test.h"
static void test_read(skiatest::Reporter* reporter, SkStream* bufferedStream,
const void* expectations, size_t bytesToRead) {
// output for reading bufferedStream.
SkAutoMalloc storage(bytesToRead);
const size_t bytesRead = bufferedStream->read(storage.get(), bytesToRead);
REPORTER_ASSERT(reporter, bytesRead == bytesToRead || bufferedStream->isAtEnd());
REPORTER_ASSERT(reporter, memcmp(storage.get(), expectations, bytesRead) == 0);
}
static void test_rewind(skiatest::Reporter* reporter,
SkStream* bufferedStream, bool shouldSucceed) {
const bool success = bufferedStream->rewind();
REPORTER_ASSERT(reporter, success == shouldSucceed);
}
// Test that hasLength() returns the correct value, based on the stream
// being wrapped. A length can only be known if the wrapped stream has a
// length and it has a position (so its initial position can be taken into
// account when computing the length).
static void test_hasLength(skiatest::Reporter* reporter,
const SkStream& bufferedStream,
const SkStream& streamBeingBuffered) {
if (streamBeingBuffered.hasLength() && streamBeingBuffered.hasPosition()) {
REPORTER_ASSERT(reporter, bufferedStream.hasLength());
} else {
REPORTER_ASSERT(reporter, !bufferedStream.hasLength());
}
}
// All tests will buffer this string, and compare output to the original.
// The string is long to ensure that all of our lengths being tested are
// smaller than the string length.
const char gAbcs[] = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx";
// Tests reading the stream across boundaries of what has been buffered so far and what
// the total buffer size is.
static void test_incremental_buffering(skiatest::Reporter* reporter, size_t bufferSize) {
SkMemoryStream memStream(gAbcs, strlen(gAbcs), false);
SkAutoTUnref<SkStream> bufferedStream(SkFrontBufferedStream::Create(&memStream, bufferSize));
test_hasLength(reporter, *bufferedStream.get(), memStream);
// First, test reading less than the max buffer size.
test_read(reporter, bufferedStream, gAbcs, bufferSize / 2);
// Now test rewinding back to the beginning and reading less than what was
// already buffered.
test_rewind(reporter, bufferedStream, true);
test_read(reporter, bufferedStream, gAbcs, bufferSize / 4);
// Now test reading part of what was buffered, and buffering new data.
test_read(reporter, bufferedStream, gAbcs + bufferedStream->getPosition(), bufferSize / 2);
// Now test reading what was buffered, buffering new data, and
// reading directly from the stream.
test_rewind(reporter, bufferedStream, true);
test_read(reporter, bufferedStream, gAbcs, bufferSize << 1);
// We have reached the end of the buffer, so rewinding will fail.
// This test assumes that the stream is larger than the buffer; otherwise the
// result of rewind should be true.
test_rewind(reporter, bufferedStream, false);
}
static void test_perfectly_sized_buffer(skiatest::Reporter* reporter, size_t bufferSize) {
SkMemoryStream memStream(gAbcs, strlen(gAbcs), false);
SkAutoTUnref<SkStream> bufferedStream(SkFrontBufferedStream::Create(&memStream, bufferSize));
test_hasLength(reporter, *bufferedStream.get(), memStream);
// Read exactly the amount that fits in the buffer.
test_read(reporter, bufferedStream, gAbcs, bufferSize);
// Rewinding should succeed.
test_rewind(reporter, bufferedStream, true);
// Once again reading buffered info should succeed
test_read(reporter, bufferedStream, gAbcs, bufferSize);
// Read past the size of the buffer. At this point, we cannot return.
test_read(reporter, bufferedStream, gAbcs + bufferedStream->getPosition(), 1);
test_rewind(reporter, bufferedStream, false);
}
static void test_skipping(skiatest::Reporter* reporter, size_t bufferSize) {
SkMemoryStream memStream(gAbcs, strlen(gAbcs), false);
SkAutoTUnref<SkStream> bufferedStream(SkFrontBufferedStream::Create(&memStream, bufferSize));
test_hasLength(reporter, *bufferedStream.get(), memStream);
// Skip half the buffer.
bufferedStream->skip(bufferSize / 2);
// Rewind, then read part of the buffer, which should have been read.
test_rewind(reporter, bufferedStream, true);
test_read(reporter, bufferedStream, gAbcs, bufferSize / 4);
// Now skip beyond the buffered piece, but still within the total buffer.
bufferedStream->skip(bufferSize / 2);
// Test that reading will still work.
test_read(reporter, bufferedStream, gAbcs + bufferedStream->getPosition(), bufferSize / 4);
test_rewind(reporter, bufferedStream, true);
test_read(reporter, bufferedStream, gAbcs, bufferSize);
}
// A custom class whose isAtEnd behaves the way Android's stream does - since it is an adaptor to a
// Java InputStream, it does not know that it is at the end until it has attempted to read beyond
// the end and failed. Used by test_read_beyond_buffer.
class AndroidLikeMemoryStream : public SkMemoryStream {
public:
AndroidLikeMemoryStream(void* data, size_t size, bool ownMemory)
: INHERITED(data, size, ownMemory)
, fIsAtEnd(false) {}
size_t read(void* dst, size_t requested) SK_OVERRIDE {
size_t bytesRead = this->INHERITED::read(dst, requested);
if (bytesRead < requested) {
fIsAtEnd = true;
}
return bytesRead;
}
bool isAtEnd() const SK_OVERRIDE {
return fIsAtEnd;
}
private:
bool fIsAtEnd;
typedef SkMemoryStream INHERITED;
};
// This test ensures that buffering the exact length of the stream and attempting to read beyond it
// does not invalidate the buffer.
static void test_read_beyond_buffer(skiatest::Reporter* reporter, size_t bufferSize) {
// Use a stream that behaves like Android's stream.
AndroidLikeMemoryStream memStream((void*)gAbcs, bufferSize, false);
// Create a buffer that matches the length of the stream.
SkAutoTUnref<SkStream> bufferedStream(SkFrontBufferedStream::Create(&memStream, bufferSize));
test_hasLength(reporter, *bufferedStream.get(), memStream);
// Attempt to read one more than the bufferSize
test_read(reporter, bufferedStream.get(), gAbcs, bufferSize + 1);
test_rewind(reporter, bufferedStream.get(), true);
// Ensure that the initial read did not invalidate the buffer.
test_read(reporter, bufferedStream, gAbcs, bufferSize);
}
// Dummy stream that optionally has a length and/or position. Tests that FrontBufferedStream's
// length depends on the stream it's buffering having a length and position.
class LengthOptionalStream : public SkStream {
public:
LengthOptionalStream(bool hasLength, bool hasPosition)
: fHasLength(hasLength)
, fHasPosition(hasPosition)
{}
virtual bool hasLength() const SK_OVERRIDE {
return fHasLength;
}
virtual bool hasPosition() const SK_OVERRIDE {
return fHasPosition;
}
virtual size_t read(void*, size_t) SK_OVERRIDE {
return 0;
}
virtual bool isAtEnd() const SK_OVERRIDE {
return true;
}
private:
const bool fHasLength;
const bool fHasPosition;
};
// Test all possible combinations of the wrapped stream having a length and a position.
static void test_length_combos(skiatest::Reporter* reporter, size_t bufferSize) {
for (int hasLen = 0; hasLen <= 1; hasLen++) {
for (int hasPos = 0; hasPos <= 1; hasPos++) {
LengthOptionalStream stream((bool) hasLen, (bool) hasPos);
SkAutoTUnref<SkStream> buffered(SkFrontBufferedStream::Create(&stream, bufferSize));
test_hasLength(reporter, *buffered.get(), stream);
}
}
}
// Test using a stream with an initial offset.
static void test_initial_offset(skiatest::Reporter* reporter, size_t bufferSize) {
SkMemoryStream memStream(gAbcs, strlen(gAbcs), false);
// Skip a few characters into the memStream, so that bufferedStream represents an offset into
// the stream it wraps.
const size_t arbitraryOffset = 17;
memStream.skip(arbitraryOffset);
SkAutoTUnref<SkStream> bufferedStream(SkFrontBufferedStream::Create(&memStream, bufferSize));
// Since SkMemoryStream has a length and a position, bufferedStream must also.
REPORTER_ASSERT(reporter, bufferedStream->hasLength());
const size_t amountToRead = 10;
const size_t bufferedLength = bufferedStream->getLength();
size_t currentPosition = bufferedStream->getPosition();
REPORTER_ASSERT(reporter, 0 == currentPosition);
// Read the stream in chunks. After each read, the position must match currentPosition,
// which sums the amount attempted to read, unless the end of the stream has been reached.
// Importantly, the end should not have been reached until currentPosition == bufferedLength.
while (currentPosition < bufferedLength) {
REPORTER_ASSERT(reporter, !bufferedStream->isAtEnd());
test_read(reporter, bufferedStream, gAbcs + arbitraryOffset + currentPosition,
amountToRead);
currentPosition = SkTMin(currentPosition + amountToRead, bufferedLength);
REPORTER_ASSERT(reporter, bufferedStream->getPosition() == currentPosition);
}
REPORTER_ASSERT(reporter, bufferedStream->isAtEnd());
REPORTER_ASSERT(reporter, bufferedLength == currentPosition);
}
static void test_buffers(skiatest::Reporter* reporter, size_t bufferSize) {
test_incremental_buffering(reporter, bufferSize);
test_perfectly_sized_buffer(reporter, bufferSize);
test_skipping(reporter, bufferSize);
test_read_beyond_buffer(reporter, bufferSize);
test_length_combos(reporter, bufferSize);
test_initial_offset(reporter, bufferSize);
}
DEF_TEST(FrontBufferedStream, reporter) {
// Test 6 and 64, which are used by Android, as well as another arbitrary length.
test_buffers(reporter, 6);
test_buffers(reporter, 15);
test_buffers(reporter, 64);
}
<commit_msg>Use SkToBool to fix a warning.<commit_after>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkFrontBufferedStream.h"
#include "SkRefCnt.h"
#include "SkStream.h"
#include "SkTypes.h"
#include "Test.h"
static void test_read(skiatest::Reporter* reporter, SkStream* bufferedStream,
const void* expectations, size_t bytesToRead) {
// output for reading bufferedStream.
SkAutoMalloc storage(bytesToRead);
const size_t bytesRead = bufferedStream->read(storage.get(), bytesToRead);
REPORTER_ASSERT(reporter, bytesRead == bytesToRead || bufferedStream->isAtEnd());
REPORTER_ASSERT(reporter, memcmp(storage.get(), expectations, bytesRead) == 0);
}
static void test_rewind(skiatest::Reporter* reporter,
SkStream* bufferedStream, bool shouldSucceed) {
const bool success = bufferedStream->rewind();
REPORTER_ASSERT(reporter, success == shouldSucceed);
}
// Test that hasLength() returns the correct value, based on the stream
// being wrapped. A length can only be known if the wrapped stream has a
// length and it has a position (so its initial position can be taken into
// account when computing the length).
static void test_hasLength(skiatest::Reporter* reporter,
const SkStream& bufferedStream,
const SkStream& streamBeingBuffered) {
if (streamBeingBuffered.hasLength() && streamBeingBuffered.hasPosition()) {
REPORTER_ASSERT(reporter, bufferedStream.hasLength());
} else {
REPORTER_ASSERT(reporter, !bufferedStream.hasLength());
}
}
// All tests will buffer this string, and compare output to the original.
// The string is long to ensure that all of our lengths being tested are
// smaller than the string length.
const char gAbcs[] = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx";
// Tests reading the stream across boundaries of what has been buffered so far and what
// the total buffer size is.
static void test_incremental_buffering(skiatest::Reporter* reporter, size_t bufferSize) {
SkMemoryStream memStream(gAbcs, strlen(gAbcs), false);
SkAutoTUnref<SkStream> bufferedStream(SkFrontBufferedStream::Create(&memStream, bufferSize));
test_hasLength(reporter, *bufferedStream.get(), memStream);
// First, test reading less than the max buffer size.
test_read(reporter, bufferedStream, gAbcs, bufferSize / 2);
// Now test rewinding back to the beginning and reading less than what was
// already buffered.
test_rewind(reporter, bufferedStream, true);
test_read(reporter, bufferedStream, gAbcs, bufferSize / 4);
// Now test reading part of what was buffered, and buffering new data.
test_read(reporter, bufferedStream, gAbcs + bufferedStream->getPosition(), bufferSize / 2);
// Now test reading what was buffered, buffering new data, and
// reading directly from the stream.
test_rewind(reporter, bufferedStream, true);
test_read(reporter, bufferedStream, gAbcs, bufferSize << 1);
// We have reached the end of the buffer, so rewinding will fail.
// This test assumes that the stream is larger than the buffer; otherwise the
// result of rewind should be true.
test_rewind(reporter, bufferedStream, false);
}
static void test_perfectly_sized_buffer(skiatest::Reporter* reporter, size_t bufferSize) {
SkMemoryStream memStream(gAbcs, strlen(gAbcs), false);
SkAutoTUnref<SkStream> bufferedStream(SkFrontBufferedStream::Create(&memStream, bufferSize));
test_hasLength(reporter, *bufferedStream.get(), memStream);
// Read exactly the amount that fits in the buffer.
test_read(reporter, bufferedStream, gAbcs, bufferSize);
// Rewinding should succeed.
test_rewind(reporter, bufferedStream, true);
// Once again reading buffered info should succeed
test_read(reporter, bufferedStream, gAbcs, bufferSize);
// Read past the size of the buffer. At this point, we cannot return.
test_read(reporter, bufferedStream, gAbcs + bufferedStream->getPosition(), 1);
test_rewind(reporter, bufferedStream, false);
}
static void test_skipping(skiatest::Reporter* reporter, size_t bufferSize) {
SkMemoryStream memStream(gAbcs, strlen(gAbcs), false);
SkAutoTUnref<SkStream> bufferedStream(SkFrontBufferedStream::Create(&memStream, bufferSize));
test_hasLength(reporter, *bufferedStream.get(), memStream);
// Skip half the buffer.
bufferedStream->skip(bufferSize / 2);
// Rewind, then read part of the buffer, which should have been read.
test_rewind(reporter, bufferedStream, true);
test_read(reporter, bufferedStream, gAbcs, bufferSize / 4);
// Now skip beyond the buffered piece, but still within the total buffer.
bufferedStream->skip(bufferSize / 2);
// Test that reading will still work.
test_read(reporter, bufferedStream, gAbcs + bufferedStream->getPosition(), bufferSize / 4);
test_rewind(reporter, bufferedStream, true);
test_read(reporter, bufferedStream, gAbcs, bufferSize);
}
// A custom class whose isAtEnd behaves the way Android's stream does - since it is an adaptor to a
// Java InputStream, it does not know that it is at the end until it has attempted to read beyond
// the end and failed. Used by test_read_beyond_buffer.
class AndroidLikeMemoryStream : public SkMemoryStream {
public:
AndroidLikeMemoryStream(void* data, size_t size, bool ownMemory)
: INHERITED(data, size, ownMemory)
, fIsAtEnd(false) {}
size_t read(void* dst, size_t requested) SK_OVERRIDE {
size_t bytesRead = this->INHERITED::read(dst, requested);
if (bytesRead < requested) {
fIsAtEnd = true;
}
return bytesRead;
}
bool isAtEnd() const SK_OVERRIDE {
return fIsAtEnd;
}
private:
bool fIsAtEnd;
typedef SkMemoryStream INHERITED;
};
// This test ensures that buffering the exact length of the stream and attempting to read beyond it
// does not invalidate the buffer.
static void test_read_beyond_buffer(skiatest::Reporter* reporter, size_t bufferSize) {
// Use a stream that behaves like Android's stream.
AndroidLikeMemoryStream memStream((void*)gAbcs, bufferSize, false);
// Create a buffer that matches the length of the stream.
SkAutoTUnref<SkStream> bufferedStream(SkFrontBufferedStream::Create(&memStream, bufferSize));
test_hasLength(reporter, *bufferedStream.get(), memStream);
// Attempt to read one more than the bufferSize
test_read(reporter, bufferedStream.get(), gAbcs, bufferSize + 1);
test_rewind(reporter, bufferedStream.get(), true);
// Ensure that the initial read did not invalidate the buffer.
test_read(reporter, bufferedStream, gAbcs, bufferSize);
}
// Dummy stream that optionally has a length and/or position. Tests that FrontBufferedStream's
// length depends on the stream it's buffering having a length and position.
class LengthOptionalStream : public SkStream {
public:
LengthOptionalStream(bool hasLength, bool hasPosition)
: fHasLength(hasLength)
, fHasPosition(hasPosition)
{}
virtual bool hasLength() const SK_OVERRIDE {
return fHasLength;
}
virtual bool hasPosition() const SK_OVERRIDE {
return fHasPosition;
}
virtual size_t read(void*, size_t) SK_OVERRIDE {
return 0;
}
virtual bool isAtEnd() const SK_OVERRIDE {
return true;
}
private:
const bool fHasLength;
const bool fHasPosition;
};
// Test all possible combinations of the wrapped stream having a length and a position.
static void test_length_combos(skiatest::Reporter* reporter, size_t bufferSize) {
for (int hasLen = 0; hasLen <= 1; hasLen++) {
for (int hasPos = 0; hasPos <= 1; hasPos++) {
LengthOptionalStream stream(SkToBool(hasLen), SkToBool(hasPos));
SkAutoTUnref<SkStream> buffered(SkFrontBufferedStream::Create(&stream, bufferSize));
test_hasLength(reporter, *buffered.get(), stream);
}
}
}
// Test using a stream with an initial offset.
static void test_initial_offset(skiatest::Reporter* reporter, size_t bufferSize) {
SkMemoryStream memStream(gAbcs, strlen(gAbcs), false);
// Skip a few characters into the memStream, so that bufferedStream represents an offset into
// the stream it wraps.
const size_t arbitraryOffset = 17;
memStream.skip(arbitraryOffset);
SkAutoTUnref<SkStream> bufferedStream(SkFrontBufferedStream::Create(&memStream, bufferSize));
// Since SkMemoryStream has a length and a position, bufferedStream must also.
REPORTER_ASSERT(reporter, bufferedStream->hasLength());
const size_t amountToRead = 10;
const size_t bufferedLength = bufferedStream->getLength();
size_t currentPosition = bufferedStream->getPosition();
REPORTER_ASSERT(reporter, 0 == currentPosition);
// Read the stream in chunks. After each read, the position must match currentPosition,
// which sums the amount attempted to read, unless the end of the stream has been reached.
// Importantly, the end should not have been reached until currentPosition == bufferedLength.
while (currentPosition < bufferedLength) {
REPORTER_ASSERT(reporter, !bufferedStream->isAtEnd());
test_read(reporter, bufferedStream, gAbcs + arbitraryOffset + currentPosition,
amountToRead);
currentPosition = SkTMin(currentPosition + amountToRead, bufferedLength);
REPORTER_ASSERT(reporter, bufferedStream->getPosition() == currentPosition);
}
REPORTER_ASSERT(reporter, bufferedStream->isAtEnd());
REPORTER_ASSERT(reporter, bufferedLength == currentPosition);
}
static void test_buffers(skiatest::Reporter* reporter, size_t bufferSize) {
test_incremental_buffering(reporter, bufferSize);
test_perfectly_sized_buffer(reporter, bufferSize);
test_skipping(reporter, bufferSize);
test_read_beyond_buffer(reporter, bufferSize);
test_length_combos(reporter, bufferSize);
test_initial_offset(reporter, bufferSize);
}
DEF_TEST(FrontBufferedStream, reporter) {
// Test 6 and 64, which are used by Android, as well as another arbitrary length.
test_buffers(reporter, 6);
test_buffers(reporter, 15);
test_buffers(reporter, 64);
}
<|endoftext|> |
<commit_before>#include "catch.hpp"
#include "PermutationSequence.hpp"
using namespace std;
TEST_CASE("Permutation Sequence") {
PermutationSequence s;
SECTION("Sample tests") {
vector<string> expected{"123", "132", "213", "231", "312", "321"};
for (int k = 1; k <= 6; k++)
REQUIRE(s.getPermutation(3, k) == expected[k - 1]);
}
}
<commit_msg>Refine Problem 60. Permutation Sequence<commit_after>#include "catch.hpp"
#include "PermutationSequence.hpp"
TEST_CASE("Permutation Sequence") {Permutation Sequence
PermutationSequence s;
SECTION("Sample tests") {
vector<string> expected{"123", "132", "213", "231", "312", "321"};
for (int k = 1; k <= 6; k++)
REQUIRE(s.getPermutation(3, k) == expected[k - 1]);
}
}
<|endoftext|> |
<commit_before>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <CompositeTransformation.h>
#include <MetaEvent.h>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
namespace test {
using namespace std;
using ::testing::_;
using ::testing::Return;
using ::testing::AtLeast;
using ::testing::UnorderedElementsAre;
using boost::filesystem::ofstream;
using boost::filesystem::current_path;
using boost::filesystem::path;
MATCHER(EqPtrContent, "") {
return *get<0>(arg)==*get<1>(arg);
}
struct CompositeTransformSuite : public ::testing::Test {
using EventTypes = Transformer::EventTypes;
using TransPtr = Transformation::TransPtr;
static bool comp(const MetaEvent* const a, const MetaEvent* const b) {
return *a==*b;
}
struct TestTransformer : public Transformer {
string name;
TestTransformer(const string& name, const EventType& out, const EventTypes& in,
map<string, TestTransformer*>& trans)
: Transformer(out, in), name(name) {
trans[name]=this;
}
MOCK_CONST_METHOD1(check, bool(const MetaEvent&));
MOCK_CONST_METHOD1(call, Events(const MetaEvent&));
virtual Events operator()(const MetaEvent& e) { return call(e); }
virtual void print(ostream& o) const { o << name; }
};
struct TestTransformation : public Transformation {
string name;
TestTransformation(const string& name, size_t arity)
: Transformation(Type::attribute, arity, EventID::any), name(name) { }
MOCK_CONST_METHOD3(in, EventTypes(const EventType& goal, const EventType& provided, const MetaFilter& filter));
MOCK_CONST_METHOD2(in, EventIDs(EventID goal, const MetaFilter& filter));
MOCK_CONST_METHOD4(create, TransPtr(const EventType& out, const EventTypes& in, const AbstractPolicy& policy, const MetaFilter& filter));
virtual void print(ostream& o) const { o << name; }
};
map<string, TestTransformer*> trans;
TestTransformation a, c, d;
CompositeTransformation compTrans, compTrans2;
shared_ptr<const TestTransformation> b;
EventType goal, provided, provided2, intermediate, intermediate2;
struct Test0: public ::id::attribute::Base {
static constexpr const ::id::attribute::ID value() { return 251; }
};
struct Test1: public ::id::attribute::Base {
static constexpr const ::id::attribute::ID value() { return 252; }
};
CompositeTransformSuite()
: a("a", 1), c("c", 2), d("d", 1), b(new TestTransformation("b", 1))
{}
void SetUp() {
ValueType goalVT(id::type::Float::value(), 1, 1, false);
AttributeType goalAT(Test0::value(), goalVT, Scale<>(), Dimensionless());
AttributeType int2AT(Test1::value(), goalVT, Scale<std::ratio<1, 1000>>(), Dimensionless());
AttributeType intAT = goalAT;
AttributeType provAT = intAT;
AttributeType prov2AT = int2AT;
intAT.scale().denom(1000);
provAT.scale().denom(1000);
provAT.value().typeId(id::type::Int32::value());
prov2AT.value().typeId(id::type::Int32::value());
goal.add(goalAT);
intermediate.add(intAT);
provided.add(provAT);
intermediate2.add(int2AT);
provided2.add(prov2AT);
ASSERT_NE(b, nullptr);
EXPECT_CALL(a, in(goal, provided, _))
.Times(1).WillOnce(Return(EventTypes({intermediate})));
EXPECT_CALL(*b, in(intermediate, provided, _))
.Times(AtLeast(1)).WillRepeatedly(Return(EventTypes({provided})));
EXPECT_CALL(c, in(goal, _, _))
.Times(1).WillOnce(Return(EventTypes({intermediate, intermediate2})));
EXPECT_CALL(d, in(intermediate2, provided2, _))
.Times(1).WillOnce(Return(EventTypes({provided2})));
auto r0 = compTrans.add(&a, goal, provided);
ASSERT_TRUE(r0.second);
auto r1 = compTrans.add(b.get(), r0.first, intermediate, provided);
ASSERT_TRUE(r1.second);
ofstream out(current_path()/"doc"/"linTransformation.dot");
out << compTrans;
auto r2 = compTrans2.add(&c, goal, EventType());
ASSERT_TRUE(r2.second);
auto r3 = compTrans2.add(b.get(), r2.first, intermediate, provided);
ASSERT_TRUE(r3.second);
auto r4 = compTrans2.add(&d, r2.first, intermediate2, provided2);
ASSERT_TRUE(r4.second);
out.close();
out.open(current_path()/"doc"/"treeTransformation.dot");
out << compTrans2;
}
};
TEST_F(CompositeTransformSuite, linearTest) {
using Graph = CompositeTransformation::Graph;
using Vertex = CompositeTransformation::Vertex;
using Edge = Graph::edge_descriptor;
const Graph& g = compTrans.graph();
ASSERT_EQ(boost::num_vertices(g), 2U);
auto v = boost::vertices(g);
Vertex testAV = *v.first;
const Transformation& testA = *g[testAV].trans();
EXPECT_EQ(testA, a);
auto out = out_edges(testAV, g);
ASSERT_NE(out.first, out.second);
Edge testBE = *out.first;
Vertex testBV = target(testBE, g);
const Transformation& testB = *g[testBV].trans();
ASSERT_NE(b, nullptr);
EXPECT_EQ(testB, *b);
}
TEST_F(CompositeTransformSuite, linearInTest) {
auto result = compTrans.in();
EXPECT_EQ(result, EventTypes({provided}));
}
TEST_F(CompositeTransformSuite, treeTest) {
using Graph = CompositeTransformation::Graph;
using Vertex = CompositeTransformation::Vertex;
using Edge = Graph::edge_descriptor;
const Graph& g = compTrans2.graph();
ASSERT_EQ(boost::num_vertices(g), 3U);
auto v = boost::vertices(g);
Vertex testCV = *v.first;
const Transformation& testC = *g[testCV].trans();
EXPECT_EQ(testC, c);
auto out = out_edges(testCV, g);
ASSERT_NE(out.first, out.second);
Edge testBE = *out.first;
Vertex testBV = target(testBE, g);
const Transformation& testB = *g[testBV].trans();
ASSERT_NE(b, nullptr);
EXPECT_EQ(testB, *b);
Edge testDE = *++out.first;
Vertex testDV = target(testDE, g);
const Transformation& testD = *g[testDV].trans();
ASSERT_NE(b, nullptr);
EXPECT_EQ(testD, d);
}
TEST_F(CompositeTransformSuite, treeInTest) {
auto result = compTrans2.in();
ASSERT_FALSE(result.empty());
EXPECT_EQ(result, EventTypes({provided, provided2}));
}
TEST_F(CompositeTransformSuite, linearCreateTest) {
using Events = Transformer::Events;
EXPECT_CALL(a, create(goal, EventTypes({intermediate}), _, _))
.Times(1).WillOnce(Return(TransPtr(new TestTransformer("a", goal, EventTypes({intermediate}), trans))));
ASSERT_NE(b, nullptr);
EXPECT_CALL(*b, create(intermediate, EventTypes({provided}), _, _))
.Times(1).WillOnce(Return(TransPtr(new TestTransformer("b", intermediate, EventTypes({provided}),trans))));
TransPtr result = compTrans.create(AbstractPolicy());
ASSERT_NE(result, nullptr);
path file = current_path()/"doc"/"linearTransformer.dot";
ofstream out(file);
out << *result;
MetaEvent eA(provided);
eA.attribute(Test0::value())->value().set(0, 0, {1.1f});
MetaEvent eB(intermediate);
eB.attribute(Test0::value())->value().set(0, 0, {1100.0f});
MetaEvent eC(goal);
eC.attribute(Test0::value())->value().set(0, 0, {1100});
EXPECT_CALL(*trans["b"], call(eA))
.Times(1).WillOnce(Return(Events{eB}));
EXPECT_CALL(*trans["a"], call(_))
.WillRepeatedly(Return(Events{}));
EXPECT_CALL(*trans["a"], call(eB))
.Times(1).WillOnce(Return(Events{eC}));
Events res0 = (*result)(eA);
ASSERT_GE(res0.size(), 1U) << "No events generated";
EXPECT_EQ(res0.front(), eC);
}
TEST_F(CompositeTransformSuite, treeCreateTest) {
using Events = Transformer::Events;
EXPECT_CALL(c, create(goal, EventTypes({intermediate, intermediate2}), _, _))
.Times(1).WillOnce(Return(TransPtr(new TestTransformer("c", goal, EventTypes({intermediate, intermediate2}), trans))));
ASSERT_NE(b, nullptr);
EXPECT_CALL(*b, create(intermediate, EventTypes({provided}), _, _))
.Times(1).WillOnce(Return(TransPtr(new TestTransformer("b", intermediate, EventTypes({provided}),trans))));
EXPECT_CALL(d, create(intermediate2, EventTypes({provided2}), _, _))
.Times(1).WillOnce(Return(TransPtr(new TestTransformer("d", intermediate2, EventTypes({provided2}), trans))));
TransPtr result = compTrans2.create(AbstractPolicy());
ASSERT_NE(result, nullptr);
path file = current_path()/"doc"/"treeTransformer.dot";
ofstream out(file);
out << *result;
MetaEvent eA(provided);
eA.attribute(Test0::value())->value().set(0, 0, {1.0f});
MetaEvent eB(provided2);
eB.attribute(Test1::value())->value().set(0, 0, {2.0f});
MetaEvent eC(intermediate);
eC.attribute(Test0::value())->value().set(0, 0, {3.0f});
MetaEvent eD(intermediate2);
eD.attribute(Test1::value())->value().set(0, 0, {4.0f});
MetaEvent eE(goal);
eE.attribute(Test0::value())->value().set(0, 0, {5.0f});
EXPECT_CALL(*trans["b"], call(_))
.WillRepeatedly(Return(Events{}));
EXPECT_CALL(*trans["b"], call(eA))
.Times(1).WillOnce(Return(Events{eC}));
EXPECT_CALL(*trans["d"], call(_))
.WillRepeatedly(Return(Events{}));
EXPECT_CALL(*trans["d"], call(eB))
.Times(1).WillOnce(Return(Events{eD}));
EXPECT_CALL(*trans["c"], call(_))
.WillRepeatedly(Return(Events{}));
EXPECT_CALL(*trans["c"], call(eD))
.Times(1);
EXPECT_CALL(*trans["c"], call(eC))
.Times(1).WillOnce(Return(Events{eE}));
Events res0 = (*result)(eA);
Events res1 = (*result)(eB);
move(res1.begin(), res1.end(), back_inserter(res0));
ASSERT_GE(res0.size(), 1U) << "No events generated";
EXPECT_EQ(res0.front(), eE);
}
TEST_F(CompositeTransformSuite, insertTest) {
using Vertex = CompositeTransformation::Vertex;
auto edges = boost::edges(compTrans.graph());
ASSERT_NE(edges.first, edges.second);
Vertex insertPoint = boost::target(*edges.first, compTrans.graph());
ASSERT_NO_THROW(compTrans.add(move(compTrans2), insertPoint, compTrans.in().at(0)));
path file = current_path()/"doc"/"insertCompTrans.dot";
ofstream out(file);
out << compTrans;
ASSERT_EQ(out_degree(insertPoint, compTrans.graph()), 1U);
auto outEdges = boost::out_edges(insertPoint, compTrans.graph());
Vertex cV = boost::target(*outEdges.first, compTrans.graph());
ASSERT_EQ(out_degree(cV, compTrans.graph()), 2U);
outEdges = boost::out_edges(cV, compTrans.graph());
Vertex bV = boost::target(*outEdges.first, compTrans.graph());
Vertex dV = boost::target(*++outEdges.first, compTrans.graph());
EXPECT_EQ(compTrans.graph()[cV].trans(), &c);
EXPECT_EQ(compTrans.graph()[bV].trans(), b.get());
EXPECT_EQ(compTrans.graph()[dV].trans(), &d);
EXPECT_THAT(compTrans.in(), UnorderedElementsAre(provided, provided2));
}
}
<commit_msg>Doc: add documentation for Unit-Tests of CompositeTransformation<commit_after>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <CompositeTransformation.h>
#include <MetaEvent.h>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
/** \class CompositeTransformation
*
* \test CompositeTransformSuite testing creation of linear and tree-like
* CompositeTransformations. Additionally checks correctness of input
* EventTypes and created CompositeTransformers. Finally tests correct merging
* of two CompositeTransformations in ::tests::compTrans
**/
namespace tests {
/** \brief CompositeTransformation Tests **/
namespace compTrans {
using namespace std;
using ::testing::_;
using ::testing::Return;
using ::testing::AtLeast;
using ::testing::UnorderedElementsAre;
using boost::filesystem::ofstream;
using boost::filesystem::current_path;
using boost::filesystem::path;
/** \brief Fixture for all CompositeTransformation UnitTests **/
struct CompositeTransformSuite : public ::testing::Test {
/** \brief forward declaration of EventTypes **/
using EventTypes = Transformer::EventTypes;
/** \brief forward declaration of TransPtr **/
using TransPtr = Transformation::TransPtr;
/** \brief helper function to compare MetaEvents based on their pointers
* \param a first MetaEvent pointer
* \param b second MetaEvent pointer
* \return true if equal according to MetaEvent::operator==, false otherwise
**/
static bool comp(const MetaEvent* const a, const MetaEvent* const b) {
return *a==*b;
}
/// Mock-Implementation of Unary Transformer
struct TestTransformer : public Transformer {
/// Name of this Mock-Object
string name;
/** \brief Create Mock-Transformer
* \param name Name of this Mock-Object
* \param out Goal EventType
* \param in single elementary vector of input EventTypes
* \param trans Transformer lookup structure to register this instance
**/
TestTransformer(const string& name, const EventType& out, const EventTypes& in,
map<string, TestTransformer*>& trans)
: Transformer(out, in), name(name) {
trans[name]=this;
}
MOCK_CONST_METHOD1(check, bool(const MetaEvent&));
MOCK_CONST_METHOD1(call, Events(const MetaEvent&));
virtual Events operator()(const MetaEvent& e) { return call(e); }
virtual void print(ostream& o) const { o << name; }
};
/// Mock-Implementation of Unary Transformation
struct TestTransformation : public Transformation {
/// Name of this Mock-Object
string name;
/** \brief Create Mock-Transformation
* \param name Name of this Mock-Object
* \param arity Arity of transformation
**/
TestTransformation(const string& name, size_t arity)
: Transformation(Type::attribute, arity, EventID::any), name(name) { }
MOCK_CONST_METHOD3(in, EventTypes(const EventType& goal, const EventType& provided, const MetaFilter& filter));
MOCK_CONST_METHOD2(in, EventIDs(EventID goal, const MetaFilter& filter));
MOCK_CONST_METHOD4(create, TransPtr(const EventType& out, const EventTypes& in, const AbstractPolicy& policy, const MetaFilter& filter));
virtual void print(ostream& o) const { o << name; }
};
/// Lookup structure to map TestTransformation names to instances
map<string, TestTransformer*> trans;
/// Statically allocated unary TestTransformations
TestTransformation a, c, d;
/// Linear CompositeTransformation containing a and b
CompositeTransformation compTrans;
/// Tree-like CompositeTransformation containing c, b and d
CompositeTransformation compTrans2;
/// Dynamically allocated unary TestTransformation
shared_ptr<const TestTransformation> b;
/// Final goal EventType: single Attribute Test0 of certain 1x1 float
EventType goal;
/// Provided EventType: single Attribute Test0 of certain 1x1 int with scale 1/1000
EventType provided;
/// Provided EventType: single Attribute Test1 of certain 1x1 int with scale 1/1000
EventType provided2;
/// Intermediate EventType: single Attribute Test0 of certain 1x1 float with scale 1/1000
EventType intermediate;
/// Intermediate EventType: single Attribute Test1 of certain 1x1 float with scale 1/1000
EventType intermediate2;
/// Definition of non-static AttrID used only testing
using Test0 = ::id::attribute::AttrID<251>;
/// Definition of non-static AttrID used only testing
using Test1 = ::id::attribute::AttrID<252>;
/// Create four TestTransformations
CompositeTransformSuite()
: a("a", 1), c("c", 2), d("d", 1), b(new TestTransformation("b", 1))
{}
/// Create CompositeTransformations compTrans and compTrans2
void SetUp() {
ValueType goalVT(id::type::Float::value(), 1, 1, false);
AttributeType goalAT(Test0::value(), goalVT, Scale<>(), Dimensionless());
AttributeType int2AT(Test1::value(), goalVT, Scale<std::ratio<1, 1000>>(), Dimensionless());
AttributeType intAT = goalAT;
AttributeType provAT = intAT;
AttributeType prov2AT = int2AT;
intAT.scale().denom(1000);
provAT.scale().denom(1000);
provAT.value().typeId(id::type::Int32::value());
prov2AT.value().typeId(id::type::Int32::value());
goal.add(goalAT);
intermediate.add(intAT);
provided.add(provAT);
intermediate2.add(int2AT);
provided2.add(prov2AT);
ASSERT_NE(b, nullptr);
EXPECT_CALL(a, in(goal, provided, _))
.Times(1).WillOnce(Return(EventTypes({intermediate})));
EXPECT_CALL(*b, in(intermediate, provided, _))
.Times(AtLeast(1)).WillRepeatedly(Return(EventTypes({provided})));
EXPECT_CALL(c, in(goal, _, _))
.Times(1).WillOnce(Return(EventTypes({intermediate, intermediate2})));
EXPECT_CALL(d, in(intermediate2, provided2, _))
.Times(1).WillOnce(Return(EventTypes({provided2})));
auto r0 = compTrans.add(&a, goal, provided);
ASSERT_TRUE(r0.second);
auto r1 = compTrans.add(b.get(), r0.first, intermediate, provided);
ASSERT_TRUE(r1.second);
ofstream out(current_path()/"doc"/"linTransformation.dot");
out << compTrans;
auto r2 = compTrans2.add(&c, goal, EventType());
ASSERT_TRUE(r2.second);
auto r3 = compTrans2.add(b.get(), r2.first, intermediate, provided);
ASSERT_TRUE(r3.second);
auto r4 = compTrans2.add(&d, r2.first, intermediate2, provided2);
ASSERT_TRUE(r4.second);
out.close();
out.open(current_path()/"doc"/"treeTransformation.dot");
out << compTrans2;
}
};
/** \brief Unit-Test testing creation of a linear CompositeTransformation **/
TEST_F(CompositeTransformSuite, linearTest) {
using Graph = CompositeTransformation::Graph;
using Vertex = CompositeTransformation::Vertex;
using Edge = Graph::edge_descriptor;
const Graph& g = compTrans.graph();
ASSERT_EQ(boost::num_vertices(g), 2U);
auto v = boost::vertices(g);
Vertex testAV = *v.first;
const Transformation& testA = *g[testAV].trans();
EXPECT_EQ(testA, a);
auto out = out_edges(testAV, g);
ASSERT_NE(out.first, out.second);
Edge testBE = *out.first;
Vertex testBV = target(testBE, g);
const Transformation& testB = *g[testBV].trans();
ASSERT_NE(b, nullptr);
EXPECT_EQ(testB, *b);
}
/** \brief Unit-Test checking correctness of input EventTypes of a linear CompositeTransformation**/
TEST_F(CompositeTransformSuite, linearInTest) {
auto result = compTrans.in();
EXPECT_EQ(result, EventTypes({provided}));
}
/** \brief Unit-Test testing creation of a tree-like CompositeTransformation **/
TEST_F(CompositeTransformSuite, treeTest) {
using Graph = CompositeTransformation::Graph;
using Vertex = CompositeTransformation::Vertex;
using Edge = Graph::edge_descriptor;
const Graph& g = compTrans2.graph();
ASSERT_EQ(boost::num_vertices(g), 3U);
auto v = boost::vertices(g);
Vertex testCV = *v.first;
const Transformation& testC = *g[testCV].trans();
EXPECT_EQ(testC, c);
auto out = out_edges(testCV, g);
ASSERT_NE(out.first, out.second);
Edge testBE = *out.first;
Vertex testBV = target(testBE, g);
const Transformation& testB = *g[testBV].trans();
ASSERT_NE(b, nullptr);
EXPECT_EQ(testB, *b);
Edge testDE = *++out.first;
Vertex testDV = target(testDE, g);
const Transformation& testD = *g[testDV].trans();
ASSERT_NE(b, nullptr);
EXPECT_EQ(testD, d);
}
/** \brief Unit-Test checking correctness of input EventTypes of a tree-like CompositeTransformation**/
TEST_F(CompositeTransformSuite, treeInTest) {
auto result = compTrans2.in();
ASSERT_FALSE(result.empty());
EXPECT_EQ(result, EventTypes({provided, provided2}));
}
/** \brief Unit-Test checking correct creation of CompositeTransformer from linear CompositeTransformation **/
TEST_F(CompositeTransformSuite, linearCreateTest) {
using Events = Transformer::Events;
EXPECT_CALL(a, create(goal, EventTypes({intermediate}), _, _))
.Times(1).WillOnce(Return(TransPtr(new TestTransformer("a", goal, EventTypes({intermediate}), trans))));
ASSERT_NE(b, nullptr);
EXPECT_CALL(*b, create(intermediate, EventTypes({provided}), _, _))
.Times(1).WillOnce(Return(TransPtr(new TestTransformer("b", intermediate, EventTypes({provided}),trans))));
TransPtr result = compTrans.create(AbstractPolicy());
ASSERT_NE(result, nullptr);
path file = current_path()/"doc"/"linearTransformer.dot";
ofstream out(file);
out << *result;
MetaEvent eA(provided);
eA.attribute(Test0::value())->value().set(0, 0, {1.1f});
MetaEvent eB(intermediate);
eB.attribute(Test0::value())->value().set(0, 0, {1100.0f});
MetaEvent eC(goal);
eC.attribute(Test0::value())->value().set(0, 0, {1100});
EXPECT_CALL(*trans["b"], call(eA))
.Times(1).WillOnce(Return(Events{eB}));
EXPECT_CALL(*trans["a"], call(_))
.WillRepeatedly(Return(Events{}));
EXPECT_CALL(*trans["a"], call(eB))
.Times(1).WillOnce(Return(Events{eC}));
Events res0 = (*result)(eA);
ASSERT_GE(res0.size(), 1U) << "No events generated";
EXPECT_EQ(res0.front(), eC);
}
/** \brief Unit-Test checking correct creation of CompositeTransformer from tree-like CompositeTransformation **/
TEST_F(CompositeTransformSuite, treeCreateTest) {
using Events = Transformer::Events;
EXPECT_CALL(c, create(goal, EventTypes({intermediate, intermediate2}), _, _))
.Times(1).WillOnce(Return(TransPtr(new TestTransformer("c", goal, EventTypes({intermediate, intermediate2}), trans))));
ASSERT_NE(b, nullptr);
EXPECT_CALL(*b, create(intermediate, EventTypes({provided}), _, _))
.Times(1).WillOnce(Return(TransPtr(new TestTransformer("b", intermediate, EventTypes({provided}),trans))));
EXPECT_CALL(d, create(intermediate2, EventTypes({provided2}), _, _))
.Times(1).WillOnce(Return(TransPtr(new TestTransformer("d", intermediate2, EventTypes({provided2}), trans))));
TransPtr result = compTrans2.create(AbstractPolicy());
ASSERT_NE(result, nullptr);
path file = current_path()/"doc"/"treeTransformer.dot";
ofstream out(file);
out << *result;
MetaEvent eA(provided);
eA.attribute(Test0::value())->value().set(0, 0, {1.0f});
MetaEvent eB(provided2);
eB.attribute(Test1::value())->value().set(0, 0, {2.0f});
MetaEvent eC(intermediate);
eC.attribute(Test0::value())->value().set(0, 0, {3.0f});
MetaEvent eD(intermediate2);
eD.attribute(Test1::value())->value().set(0, 0, {4.0f});
MetaEvent eE(goal);
eE.attribute(Test0::value())->value().set(0, 0, {5.0f});
EXPECT_CALL(*trans["b"], call(_))
.WillRepeatedly(Return(Events{}));
EXPECT_CALL(*trans["b"], call(eA))
.Times(1).WillOnce(Return(Events{eC}));
EXPECT_CALL(*trans["d"], call(_))
.WillRepeatedly(Return(Events{}));
EXPECT_CALL(*trans["d"], call(eB))
.Times(1).WillOnce(Return(Events{eD}));
EXPECT_CALL(*trans["c"], call(_))
.WillRepeatedly(Return(Events{}));
EXPECT_CALL(*trans["c"], call(eD))
.Times(1);
EXPECT_CALL(*trans["c"], call(eC))
.Times(1).WillOnce(Return(Events{eE}));
Events res0 = (*result)(eA);
Events res1 = (*result)(eB);
move(res1.begin(), res1.end(), back_inserter(res0));
ASSERT_GE(res0.size(), 1U) << "No events generated";
EXPECT_EQ(res0.front(), eE);
}
/** \brief Unit-Test checking correct merging of linear and tree-like CompositeTransformation **/
TEST_F(CompositeTransformSuite, insertTest) {
using Vertex = CompositeTransformation::Vertex;
auto edges = boost::edges(compTrans.graph());
ASSERT_NE(edges.first, edges.second);
Vertex insertPoint = boost::target(*edges.first, compTrans.graph());
ASSERT_NO_THROW(compTrans.add(move(compTrans2), insertPoint, compTrans.in().at(0)));
path file = current_path()/"doc"/"insertCompTrans.dot";
ofstream out(file);
out << compTrans;
ASSERT_EQ(out_degree(insertPoint, compTrans.graph()), 1U);
auto outEdges = boost::out_edges(insertPoint, compTrans.graph());
Vertex cV = boost::target(*outEdges.first, compTrans.graph());
ASSERT_EQ(out_degree(cV, compTrans.graph()), 2U);
outEdges = boost::out_edges(cV, compTrans.graph());
Vertex bV = boost::target(*outEdges.first, compTrans.graph());
Vertex dV = boost::target(*++outEdges.first, compTrans.graph());
EXPECT_EQ(compTrans.graph()[cV].trans(), &c);
EXPECT_EQ(compTrans.graph()[bV].trans(), b.get());
EXPECT_EQ(compTrans.graph()[dV].trans(), &d);
EXPECT_THAT(compTrans.in(), UnorderedElementsAre(provided, provided2));
}
}}
<|endoftext|> |
<commit_before>/*! @file zerocrossings.cc
* @brief Tests for SoundFeatureExtraction::Transforms::ZeroCrossings.
* @author Markovtsev Vadim <[email protected]>
* @version 1.0
*
* @section Notes
* This code partially conforms to <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml">Google C++ Style Guide</a>.
*
* @section Copyright
* Copyright 2013 Samsung R&D Institute Russia
*/
#include <gtest/gtest.h>
#include <math.h>
#include "src/transforms/zerocrossings.h"
using SoundFeatureExtraction::Formats::WindowF;
using SoundFeatureExtraction::Formats::WindowFormatF;
using SoundFeatureExtraction::BuffersBase;
using SoundFeatureExtraction::Transforms::ZeroCrossings;
class ZeroCrossingsTest : public ZeroCrossings, public testing::Test {
public:
BuffersBase<WindowF> Input;
BuffersBase<int32_t> Output;
int Size;
virtual void SetUp() {
Size = 450;
Input.Initialize(1, Size);
for (int i = 0; i < Size; i++) {
// Always liked exotic functions
Input[0]->Data.get()[i] = sinf(i * M_PI / 2);
}
Input[0]->Data.get()[Size - 1] = 0;
Input[0]->Data.get()[Size - 2] = 0;
auto format = std::make_shared<WindowFormatF>(Size * 1000 / 18000, 18000);
SetInputFormat(format);
InitializeBuffers(Input, &Output);
}
};
TEST_F(ZeroCrossingsTest, Do) {
Do(Input, &Output);
ASSERT_EQ(Size / 2 + 1, *Output[0]);
}
#define CLASS_NAME ZeroCrossingsTest
#define ITER_COUNT 400000
#define NO_OUTPUT
#include "src/primitives/energy.h"
#include "tests/transforms/benchmark.inc"
#include "tests/google/src/gtest_main.cc"
<commit_msg>Added non-SIMD test to ZeroCrossings<commit_after>/*! @file zerocrossings.cc
* @brief Tests for SoundFeatureExtraction::Transforms::ZeroCrossings.
* @author Markovtsev Vadim <[email protected]>
* @version 1.0
*
* @section Notes
* This code partially conforms to <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml">Google C++ Style Guide</a>.
*
* @section Copyright
* Copyright 2013 Samsung R&D Institute Russia
*/
#include <gtest/gtest.h>
#include <math.h>
#include "src/transforms/zerocrossings.h"
using SoundFeatureExtraction::Formats::WindowF;
using SoundFeatureExtraction::Formats::WindowFormatF;
using SoundFeatureExtraction::BuffersBase;
using SoundFeatureExtraction::Transforms::ZeroCrossings;
class ZeroCrossingsTest : public ZeroCrossings, public testing::Test {
public:
BuffersBase<WindowF> Input;
BuffersBase<int32_t> Output;
int Size;
virtual void SetUp() {
Size = 450;
Input.Initialize(1, Size);
for (int i = 0; i < Size; i++) {
// Always liked exotic functions
Input[0]->Data.get()[i] = sinf(i * M_PI / 2);
}
Input[0]->Data.get()[Size - 1] = 0;
Input[0]->Data.get()[Size - 2] = 0;
auto format = std::make_shared<WindowFormatF>(Size * 1000 / 18000, 18000);
SetInputFormat(format);
InitializeBuffers(Input, &Output);
}
};
TEST_F(ZeroCrossingsTest, Do) {
Do(Input, &Output);
ASSERT_EQ(Size / 2 + 1, *Output[0]);
int slowres = Do(false, Input[0]->Data.get(), Size);
ASSERT_EQ(Size / 2 + 1, slowres);
}
#define CLASS_NAME ZeroCrossingsTest
#define ITER_COUNT 400000
#define NO_OUTPUT
#include "src/primitives/energy.h"
#include "tests/transforms/benchmark.inc"
#include "tests/google/src/gtest_main.cc"
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: versionhelper.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-09 12:08:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <stdlib.h>
#include "versionhelper.hxx"
#include <rtl/ustring.hxx>
#include <rtl/string.hxx>
// -----------------------------------------------------------------------------
VersionHelper::VersionHelper(rtl::OUString const& _sDLLName, GetOpt & _aOptions)
:DynamicLibraryHelper(_sDLLName, _aOptions),
m_pInfo(NULL)
{
// try to get the entry pointer
FktGetVersionInfoPtr pFunc = (FktGetVersionInfoPtr) m_pModule->getSymbol( rtl::OUString::createFromAscii( "GetVersionInfo" ) );
if (pFunc)
{
const VersionInfo *pVersion = (pFunc)();
m_pInfo = pVersion;
}
}
//# void VersionHelper::print(std::ostream &stream)
//# {
//# stream << " Time:" << getTime() << std::endl;
//# stream << " Date:" << getDate() << std::endl;
//# stream << " Upd:" << getUpd() << std::endl;
//# stream << " Minor:" << getMinor() << std::endl;
//# stream << " Build:" << getBuild() << std::endl;
//# stream << "Inpath:" << getInpath() << std::endl;
//# }
//#
//# std::ostream & operator <<( std::ostream &stream, VersionHelper &_aVersion )
//# {
//# _aVersion.print (stream);
//# return stream;
//# }
//#
// -----------------------------------------------------------------------------
bool VersionHelper::isOk() const
{
if (m_pInfo != NULL) return true;
return false;
}
rtl::OString VersionHelper::getTime() const
{
return m_pInfo->pTime;
}
rtl::OString VersionHelper::getDate() const
{
return m_pInfo->pDate;
}
rtl::OString VersionHelper::getUpd() const
{
return m_pInfo->pUpd;
}
rtl::OString VersionHelper::getMinor() const
{
return m_pInfo->pMinor;
}
rtl::OString VersionHelper::getBuild() const
{
return m_pInfo->pBuild;
}
rtl::OString VersionHelper::getInpath() const
{
return m_pInfo->pInpath;
}
void VersionHelper::printall(FILE * out)
{
if (isOk())
{
rtl::OString aStr = getTime();
fprintf(out, " Time:%s\n", aStr.getStr() );
fprintf(out, " Date:%s\n", getDate().getStr() );
fprintf(out, " Upd:%s\n", getUpd().getStr() );
fprintf(out, " Minor:%s\n", getMinor().getStr() );
fprintf(out, " Build:%s\n", getBuild().getStr() );
fprintf(out, "Inpath:%s\n", getInpath().getStr());
fflush(out);
}
else
{
fprintf(stderr, "error: No version info found.\n");
}
}
<commit_msg>INTEGRATION: CWS warnings01 (1.6.50); FILE MERGED 2005/09/22 22:38:44 sb 1.6.50.2: RESYNC: (1.6-1.7); FILE MERGED 2005/09/14 10:21:53 sb 1.6.50.1: #i53898# Made code warning-free.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: versionhelper.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: hr $ $Date: 2006-06-20 02:28:57 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <stdlib.h>
#include "versionhelper.hxx"
#include <rtl/ustring.hxx>
#include <rtl/string.hxx>
// -----------------------------------------------------------------------------
VersionHelper::VersionHelper(rtl::OUString const& _sDLLName, GetOpt & _aOptions)
:DynamicLibraryHelper(_sDLLName, _aOptions),
m_pInfo(NULL)
{
// try to get the entry pointer
FktGetVersionInfoPtr pFunc = (FktGetVersionInfoPtr)
m_pModule->getFunctionSymbol(
rtl::OUString::createFromAscii( "GetVersionInfo" ) );
if (pFunc)
{
const VersionInfo *pVersion = (pFunc)();
m_pInfo = pVersion;
}
}
//# void VersionHelper::print(std::ostream &stream)
//# {
//# stream << " Time:" << getTime() << std::endl;
//# stream << " Date:" << getDate() << std::endl;
//# stream << " Upd:" << getUpd() << std::endl;
//# stream << " Minor:" << getMinor() << std::endl;
//# stream << " Build:" << getBuild() << std::endl;
//# stream << "Inpath:" << getInpath() << std::endl;
//# }
//#
//# std::ostream & operator <<( std::ostream &stream, VersionHelper &_aVersion )
//# {
//# _aVersion.print (stream);
//# return stream;
//# }
//#
// -----------------------------------------------------------------------------
bool VersionHelper::isOk() const
{
if (m_pInfo != NULL) return true;
return false;
}
rtl::OString VersionHelper::getTime() const
{
return m_pInfo->pTime;
}
rtl::OString VersionHelper::getDate() const
{
return m_pInfo->pDate;
}
rtl::OString VersionHelper::getUpd() const
{
return m_pInfo->pUpd;
}
rtl::OString VersionHelper::getMinor() const
{
return m_pInfo->pMinor;
}
rtl::OString VersionHelper::getBuild() const
{
return m_pInfo->pBuild;
}
rtl::OString VersionHelper::getInpath() const
{
return m_pInfo->pInpath;
}
void VersionHelper::printall(FILE * out)
{
if (isOk())
{
rtl::OString aStr = getTime();
fprintf(out, " Time:%s\n", aStr.getStr() );
fprintf(out, " Date:%s\n", getDate().getStr() );
fprintf(out, " Upd:%s\n", getUpd().getStr() );
fprintf(out, " Minor:%s\n", getMinor().getStr() );
fprintf(out, " Build:%s\n", getBuild().getStr() );
fprintf(out, "Inpath:%s\n", getInpath().getStr());
fflush(out);
}
else
{
fprintf(stderr, "error: No version info found.\n");
}
}
<|endoftext|> |
<commit_before>#ifndef __FUTURE_HPP__
#define __FUTURE_HPP__
#include "latch.hpp"
namespace process {
template <typename T>
class Promise;
template <typename T>
class Future
{
public:
Future();
Future(const T& _t);
Future(const Future<T>& that);
Future<T>& operator = (const Future<T>& that);
virtual ~Future();
bool ready() const;
bool await(double secs = 0) const;
T get() const;
operator T () const;
private:
friend class Promise<T>;
void set(const T& _t);
int* refs;
T** t;
Latch* latch;
};
template <typename T>
Future<T>::Future()
{
refs = new int;
*refs = 1;
t = new T*;
*t = NULL;
latch = new Latch();
}
template <typename T>
Future<T>::Future(const T& _t)
{
refs = new int;
*refs = 1;
t = new T*;
*t = NULL;
latch = new Latch();
set(_t);
}
template <typename T>
Future<T>::Future(const Future<T>& that)
{
assert(that.refs > 0);
__sync_fetch_and_add(that.refs, 1);
refs = that.refs;
t = that.t;
latch = that.latch;
}
template <typename T>
Future<T>& Future<T>::operator = (const Future<T>& that)
{
if (this != &that) {
// Destructor ...
assert(refs != NULL);
if (__sync_sub_and_fetch(refs, 1) == 0) {
delete refs;
assert(t != NULL);
if (*t != NULL)
delete *t;
assert(latch != NULL);
delete latch;
}
// Copy constructor ...
assert(that.refs > 0);
__sync_fetch_and_add(that.refs, 1);
refs = that.refs;
t = that.t;
latch = that.latch;
}
}
template <typename T>
Future<T>::~Future()
{
assert(refs != NULL);
if (__sync_sub_and_fetch(refs, 1) == 0) {
delete refs;
assert(t != NULL);
if (*t != NULL)
delete *t;
assert(latch != NULL);
delete latch;
}
}
template <typename T>
bool Future<T>::ready() const
{
assert(t != NULL);
if (*t != NULL)
return true;
return false;
}
template <typename T>
bool Future<T>::await(double secs) const
{
if (ready())
return true;
assert(latch != NULL);
return latch->await(secs);
}
template <typename T>
T Future<T>::get() const
{
if (ready())
return **t;
await();
assert(t != NULL && *t != NULL);
return **t;
}
template <typename T>
Future<T>::operator T () const
{
return get();
}
template <typename T>
void Future<T>::set(const T& _t)
{
assert(t != NULL && *t == NULL);
*t = new T(_t);
latch->trigger();
}
} // namespace process {
#endif // __FUTURE_HPP__
<commit_msg>Added support for creating a Future out of a Promise.<commit_after>#ifndef __FUTURE_HPP__
#define __FUTURE_HPP__
#include "latch.hpp"
namespace process {
template <typename T>
class Promise;
template <typename T>
class Future
{
public:
Future();
Future(Promise<T>* promise);
Future(const T& _t);
Future(const Future<T>& that);
Future<T>& operator = (const Future<T>& that);
virtual ~Future();
bool ready() const;
bool await(double secs = 0) const;
T get() const;
operator T () const;
private:
friend class Promise<T>;
void set(const T& _t);
int* refs;
T** t;
Latch* latch;
};
template <typename T>
Future<T>::Future()
{
refs = new int;
*refs = 1;
t = new T*;
*t = NULL;
latch = new Latch();
}
template <typename T>
Future<T>::Future(Promise<T>* promise)
{
refs = new int;
*refs = 1;
t = new T*;
*t = NULL;
latch = new Latch();
assert(promise != NULL);
promise->associate(*this);
}
template <typename T>
Future<T>::Future(const T& _t)
{
refs = new int;
*refs = 1;
t = new T*;
*t = NULL;
latch = new Latch();
set(_t);
}
template <typename T>
Future<T>::Future(const Future<T>& that)
{
assert(that.refs > 0);
__sync_fetch_and_add(that.refs, 1);
refs = that.refs;
t = that.t;
latch = that.latch;
}
template <typename T>
Future<T>& Future<T>::operator = (const Future<T>& that)
{
if (this != &that) {
// Destructor ...
assert(refs != NULL);
if (__sync_sub_and_fetch(refs, 1) == 0) {
delete refs;
assert(t != NULL);
if (*t != NULL)
delete *t;
assert(latch != NULL);
delete latch;
}
// Copy constructor ...
assert(that.refs > 0);
__sync_fetch_and_add(that.refs, 1);
refs = that.refs;
t = that.t;
latch = that.latch;
}
}
template <typename T>
Future<T>::~Future()
{
assert(refs != NULL);
if (__sync_sub_and_fetch(refs, 1) == 0) {
delete refs;
assert(t != NULL);
if (*t != NULL)
delete *t;
assert(latch != NULL);
delete latch;
}
}
template <typename T>
bool Future<T>::ready() const
{
assert(t != NULL);
if (*t != NULL)
return true;
return false;
}
template <typename T>
bool Future<T>::await(double secs) const
{
if (ready())
return true;
assert(latch != NULL);
return latch->await(secs);
}
template <typename T>
T Future<T>::get() const
{
if (ready())
return **t;
await();
assert(t != NULL && *t != NULL);
return **t;
}
template <typename T>
Future<T>::operator T () const
{
return get();
}
template <typename T>
void Future<T>::set(const T& _t)
{
assert(t != NULL && *t == NULL);
*t = new T(_t);
latch->trigger();
}
} // namespace process {
#endif // __FUTURE_HPP__
<|endoftext|> |
<commit_before>/*
Copyright (c) 2006 - 2007 Volker Krause <[email protected]>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "notificationcollector.h"
#include "storage/datastore.h"
#include "storage/entity.h"
#include "handlerhelper.h"
#include <QtCore/QDebug>
using namespace Akonadi;
NotificationCollector::NotificationCollector(QObject* parent) :
QObject( parent ),
mDb( 0 )
{
}
Akonadi::NotificationCollector::NotificationCollector(DataStore * db) :
QObject( db ),
mDb( db )
{
connect( db, SIGNAL(transactionCommitted()), SLOT(transactionCommitted()) );
connect( db, SIGNAL(transactionRolledBack()), SLOT(transactionRolledBack()) );
}
Akonadi::NotificationCollector::~NotificationCollector()
{
}
void Akonadi::NotificationCollector::itemAdded( const PimItem &item,
const Collection &collection,
const QString & mimeType,
const QByteArray & resource )
{
itemNotification( NotificationMessage::Add, item, collection, Collection(), mimeType, resource );
}
void Akonadi::NotificationCollector::itemChanged( const PimItem &item,
const QSet<QByteArray> &changedParts,
const Collection &collection,
const QString & mimeType,
const QByteArray & resource )
{
itemNotification( NotificationMessage::Modify, item, collection, Collection(), mimeType, resource, changedParts );
}
void Akonadi::NotificationCollector::itemMoved( const PimItem &item,
const Collection &collectionSrc,
const Collection &collectionDest,
const QString &mimeType,
const QByteArray &sourceResource )
{
itemNotification( NotificationMessage::Move, item, collectionSrc, collectionDest, mimeType, sourceResource );
}
void Akonadi::NotificationCollector::itemRemoved( const PimItem &item,
const Collection &collection,
const QString & mimeType,
const QByteArray & resource )
{
itemNotification( NotificationMessage::Remove, item, collection, Collection(), mimeType, resource );
}
void NotificationCollector::itemLinked(const PimItem & item, const Collection & collection)
{
itemNotification( NotificationMessage::Link, item, collection, Collection(), QString(), QByteArray() );
}
void NotificationCollector::itemUnlinked(const PimItem & item, const Collection & collection)
{
itemNotification( NotificationMessage::Unlink, item, collection, Collection(), QString(), QByteArray() );
}
void Akonadi::NotificationCollector::collectionAdded( const Collection &collection,
const QByteArray &resource )
{
collectionNotification( NotificationMessage::Add, collection, collection.parentId(), -1, resource );
}
void Akonadi::NotificationCollector::collectionChanged( const Collection &collection,
const QList<QByteArray> &changes,
const QByteArray &resource )
{
collectionNotification( NotificationMessage::Modify, collection, collection.parentId(), -1, resource, changes.toSet() );
}
void NotificationCollector::collectionMoved( const Collection &collection,
const Collection &source,
const QByteArray &resource,
const QByteArray &destResource )
{
collectionNotification( NotificationMessage::Move, collection, source.id(), collection.parentId(), resource, QSet<QByteArray>(), destResource );
}
void Akonadi::NotificationCollector::collectionRemoved( const Collection &collection,
const QByteArray &resource )
{
collectionNotification( NotificationMessage::Remove, collection, collection.parentId(), -1, resource );
}
void NotificationCollector::collectionSubscribed( const Collection& collection,
const QByteArray& resource )
{
collectionNotification( NotificationMessage::Subscribe, collection, collection.parentId(), -1, resource, QSet<QByteArray>() );
}
void NotificationCollector::collectionUnsubscribed( const Collection& collection,
const QByteArray& resource )
{
collectionNotification( NotificationMessage::Unsubscribe, collection, collection.parentId(), -1, resource, QSet<QByteArray>() );
}
void Akonadi::NotificationCollector::transactionCommitted()
{
dispatchNotifications();
}
void Akonadi::NotificationCollector::transactionRolledBack()
{
clear();
}
void Akonadi::NotificationCollector::clear()
{
mNotifications.clear();
}
void NotificationCollector::setSessionId(const QByteArray &sessionId)
{
mSessionId = sessionId;
}
void NotificationCollector::itemNotification( NotificationMessage::Operation op,
const PimItem & item,
const Collection & collection,
const Collection & collectionDest,
const QString & mimeType,
const QByteArray & resource,
const QSet<QByteArray> &parts )
{
NotificationMessage msg;
msg.setSessionId( mSessionId );
msg.setType( NotificationMessage::Item );
msg.setOperation( op );
msg.setUid( item.id() );
msg.setRemoteId( item.remoteId() );
msg.setItemParts( parts );
//HACK: store remoteRevision in itemparts for deletion
if ( op == NotificationMessage::Remove )
msg.setItemParts( QSet<QByteArray>() << item.remoteRevision().toUtf8() );
msg.setDestinationResource( collectionDest.resource().name().toLatin1() );
Collection col = collection;
if ( !col.isValid() )
col = item.collection();
msg.setParentCollection( col.id() );
// will be valid if it is a move message
msg.setParentDestCollection( collectionDest.id() );
QString mt = mimeType;
if ( mt.isEmpty() )
mt = item.mimeType().name();
msg.setMimeType( mt );
QByteArray res = resource;
if ( res.isEmpty() )
res = col.resource().name().toLatin1();
msg.setResource( res );
dispatchNotification( msg );
}
void NotificationCollector::collectionNotification( NotificationMessage::Operation op,
const Collection & collection,
Collection::Id source,
Collection::Id destination,
const QByteArray & resource,
const QSet<QByteArray> &changes,
const QByteArray & destResource )
{
NotificationMessage msg;
msg.setType( NotificationMessage::Collection );
msg.setOperation( op );
msg.setSessionId( mSessionId );
msg.setUid( collection.id() );
msg.setRemoteId( collection.remoteId() );
msg.setParentCollection( source );
msg.setParentDestCollection( destination );
msg.setDestinationResource( destResource );
msg.setItemParts( changes );
//HACK: store remoteRevision in itemparts for deletion
if ( op == NotificationMessage::Remove )
msg.setItemParts( QSet<QByteArray>() << collection.remoteRevision().toUtf8() );
QByteArray res = resource;
if ( res.isEmpty() )
res = collection.resource().name().toLatin1();
msg.setResource( res );
dispatchNotification( msg );
}
void NotificationCollector::dispatchNotification(const NotificationMessage & msg)
{
if ( !mDb || mDb->inTransaction() ) {
NotificationMessage::appendAndCompress( mNotifications, msg );
} else {
NotificationMessage::List l;
l << msg;
emit notify( l );
}
}
void NotificationCollector::dispatchNotifications()
{
emit notify( mNotifications );
clear();
}
#include "notificationcollector.moc"
<commit_msg>Only set the destination resource if we are moving.<commit_after>/*
Copyright (c) 2006 - 2007 Volker Krause <[email protected]>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "notificationcollector.h"
#include "storage/datastore.h"
#include "storage/entity.h"
#include "handlerhelper.h"
#include <QtCore/QDebug>
using namespace Akonadi;
NotificationCollector::NotificationCollector(QObject* parent) :
QObject( parent ),
mDb( 0 )
{
}
Akonadi::NotificationCollector::NotificationCollector(DataStore * db) :
QObject( db ),
mDb( db )
{
connect( db, SIGNAL(transactionCommitted()), SLOT(transactionCommitted()) );
connect( db, SIGNAL(transactionRolledBack()), SLOT(transactionRolledBack()) );
}
Akonadi::NotificationCollector::~NotificationCollector()
{
}
void Akonadi::NotificationCollector::itemAdded( const PimItem &item,
const Collection &collection,
const QString & mimeType,
const QByteArray & resource )
{
itemNotification( NotificationMessage::Add, item, collection, Collection(), mimeType, resource );
}
void Akonadi::NotificationCollector::itemChanged( const PimItem &item,
const QSet<QByteArray> &changedParts,
const Collection &collection,
const QString & mimeType,
const QByteArray & resource )
{
itemNotification( NotificationMessage::Modify, item, collection, Collection(), mimeType, resource, changedParts );
}
void Akonadi::NotificationCollector::itemMoved( const PimItem &item,
const Collection &collectionSrc,
const Collection &collectionDest,
const QString &mimeType,
const QByteArray &sourceResource )
{
itemNotification( NotificationMessage::Move, item, collectionSrc, collectionDest, mimeType, sourceResource );
}
void Akonadi::NotificationCollector::itemRemoved( const PimItem &item,
const Collection &collection,
const QString & mimeType,
const QByteArray & resource )
{
itemNotification( NotificationMessage::Remove, item, collection, Collection(), mimeType, resource );
}
void NotificationCollector::itemLinked(const PimItem & item, const Collection & collection)
{
itemNotification( NotificationMessage::Link, item, collection, Collection(), QString(), QByteArray() );
}
void NotificationCollector::itemUnlinked(const PimItem & item, const Collection & collection)
{
itemNotification( NotificationMessage::Unlink, item, collection, Collection(), QString(), QByteArray() );
}
void Akonadi::NotificationCollector::collectionAdded( const Collection &collection,
const QByteArray &resource )
{
collectionNotification( NotificationMessage::Add, collection, collection.parentId(), -1, resource );
}
void Akonadi::NotificationCollector::collectionChanged( const Collection &collection,
const QList<QByteArray> &changes,
const QByteArray &resource )
{
collectionNotification( NotificationMessage::Modify, collection, collection.parentId(), -1, resource, changes.toSet() );
}
void NotificationCollector::collectionMoved( const Collection &collection,
const Collection &source,
const QByteArray &resource,
const QByteArray &destResource )
{
collectionNotification( NotificationMessage::Move, collection, source.id(), collection.parentId(), resource, QSet<QByteArray>(), destResource );
}
void Akonadi::NotificationCollector::collectionRemoved( const Collection &collection,
const QByteArray &resource )
{
collectionNotification( NotificationMessage::Remove, collection, collection.parentId(), -1, resource );
}
void NotificationCollector::collectionSubscribed( const Collection& collection,
const QByteArray& resource )
{
collectionNotification( NotificationMessage::Subscribe, collection, collection.parentId(), -1, resource, QSet<QByteArray>() );
}
void NotificationCollector::collectionUnsubscribed( const Collection& collection,
const QByteArray& resource )
{
collectionNotification( NotificationMessage::Unsubscribe, collection, collection.parentId(), -1, resource, QSet<QByteArray>() );
}
void Akonadi::NotificationCollector::transactionCommitted()
{
dispatchNotifications();
}
void Akonadi::NotificationCollector::transactionRolledBack()
{
clear();
}
void Akonadi::NotificationCollector::clear()
{
mNotifications.clear();
}
void NotificationCollector::setSessionId(const QByteArray &sessionId)
{
mSessionId = sessionId;
}
void NotificationCollector::itemNotification( NotificationMessage::Operation op,
const PimItem & item,
const Collection & collection,
const Collection & collectionDest,
const QString & mimeType,
const QByteArray & resource,
const QSet<QByteArray> &parts )
{
NotificationMessage msg;
msg.setSessionId( mSessionId );
msg.setType( NotificationMessage::Item );
msg.setOperation( op );
msg.setUid( item.id() );
msg.setRemoteId( item.remoteId() );
msg.setItemParts( parts );
//HACK: store remoteRevision in itemparts for deletion
if ( op == NotificationMessage::Remove )
msg.setItemParts( QSet<QByteArray>() << item.remoteRevision().toUtf8() );
if ( collectionDest.isValid() ) // only relevant for moves
msg.setDestinationResource( collectionDest.resource().name().toLatin1() );
Collection col = collection;
if ( !col.isValid() )
col = item.collection();
msg.setParentCollection( col.id() );
// will be valid if it is a move message
msg.setParentDestCollection( collectionDest.id() );
QString mt = mimeType;
if ( mt.isEmpty() )
mt = item.mimeType().name();
msg.setMimeType( mt );
QByteArray res = resource;
if ( res.isEmpty() )
res = col.resource().name().toLatin1();
msg.setResource( res );
dispatchNotification( msg );
}
void NotificationCollector::collectionNotification( NotificationMessage::Operation op,
const Collection & collection,
Collection::Id source,
Collection::Id destination,
const QByteArray & resource,
const QSet<QByteArray> &changes,
const QByteArray & destResource )
{
NotificationMessage msg;
msg.setType( NotificationMessage::Collection );
msg.setOperation( op );
msg.setSessionId( mSessionId );
msg.setUid( collection.id() );
msg.setRemoteId( collection.remoteId() );
msg.setParentCollection( source );
msg.setParentDestCollection( destination );
msg.setDestinationResource( destResource );
msg.setItemParts( changes );
//HACK: store remoteRevision in itemparts for deletion
if ( op == NotificationMessage::Remove )
msg.setItemParts( QSet<QByteArray>() << collection.remoteRevision().toUtf8() );
QByteArray res = resource;
if ( res.isEmpty() )
res = collection.resource().name().toLatin1();
msg.setResource( res );
dispatchNotification( msg );
}
void NotificationCollector::dispatchNotification(const NotificationMessage & msg)
{
if ( !mDb || mDb->inTransaction() ) {
NotificationMessage::appendAndCompress( mNotifications, msg );
} else {
NotificationMessage::List l;
l << msg;
emit notify( l );
}
}
void NotificationCollector::dispatchNotifications()
{
emit notify( mNotifications );
clear();
}
#include "notificationcollector.moc"
<|endoftext|> |
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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.
*/
/*
* Description:
* a simple version of meta state service for development
*
* Revision history:
* 2015-11-04, @imzhenyu ([email protected]), setup the sketch
* 2015-11-11, Tianyi WANG, first version done
* xxxx-xx-xx, author, fix bug about xxx
*/
# include "meta_state_service_simple.h"
# include <dsn/internal/task.h>
# include <stack>
# include <utility>
namespace dsn
{
namespace dist
{
// path: /, /n1/n2, /n1/n2/, /n2/n2/n3
std::string meta_state_service_simple::normalize_path(const std::string& s)
{
if (s.empty() || s[0] != '/')
return "";
if (s.length() > 1 && *s.rbegin() == '/')
return s.substr(0, s.length() - 1);
return s;
}
error_code meta_state_service_simple::extract_name_parent_from_path(
const std::string& s,
/*out*/ std::string& name,
/*out*/ std::string& parent
)
{
auto pos = s.find_last_of('/');
if (pos == std::string::npos)
return ERR_INVALID_PARAMETERS;
name = s.substr(pos + 1);
if (pos > 0)
parent = s.substr(0, pos);
else
parent = "/";
return ERR_OK;
}
static void __err_cb_bind_and_enqueue(
task_ptr lock_task,
error_code err,
int delay_milliseconds = 0
)
{
auto t = dynamic_cast<safe_late_task<meta_state_service::err_callback>*>(lock_task.get());
t->bind_and_enqueue(
[&](meta_state_service::err_callback& cb)
{
return bind(cb, err);
},
delay_milliseconds
);
}
void meta_state_service_simple::write_log(blob&& log_blob, std::function<error_code()> internal_operation, task_ptr task)
{
_log_lock.lock();
uint64_t log_offset = _offset;
_offset += log_blob.length();
auto continuation_task = std::unique_ptr<operation>(new operation(false, [=](bool log_succeed)
{
dassert(log_succeed, "we cannot handle logging failure now");
__err_cb_bind_and_enqueue(task, internal_operation(), 0);
}));
auto continuation_task_ptr = continuation_task.get();
_task_queue.emplace(move(continuation_task));
_log_lock.unlock();
file::write(
_log,
log_blob.buffer_ptr(),
log_blob.length(),
log_offset,
LPC_META_STATE_SERVICE_SIMPLE_INTERNAL,
this,
[=](error_code err, size_t bytes)
{
dassert(err == ERR_OK && bytes == log_blob.length(), "we cannot handle logging failure now");
_log_lock.lock();
continuation_task_ptr->done = true;
while (!_task_queue.empty())
{
if (!_task_queue.front()->done)
{
break;
}
_task_queue.front()->cb(true);
_task_queue.pop();
}
_log_lock.unlock();
}
);
}
error_code meta_state_service_simple::create_node_internal(const std::string& node, const blob& value)
{
auto path = normalize_path(node);
zauto_lock _(_state_lock);
auto me_it = _quick_map.find(path);
if (me_it != _quick_map.end())
return ERR_NODE_ALREADY_EXIST;
std::string name, parent;
auto err = extract_name_parent_from_path(path, name, parent);
if (err != ERR_OK)
{
return err;
}
auto parent_it = _quick_map.find(parent);
if (parent_it == _quick_map.end())
return ERR_OBJECT_NOT_FOUND;
state_node* n = new state_node(name, parent_it->second, value);
parent_it->second->children.insert(quick_map::value_type(name, n));
_quick_map.insert(quick_map::value_type(path, n));
return ERR_OK;
}
error_code meta_state_service_simple::delete_node_internal(const std::string& node, bool recursive)
{
auto path = normalize_path(node);
if (path == "/")
return ERR_INVALID_PARAMETERS; // cannot delete root
zauto_lock _(_state_lock);
auto me_it = _quick_map.find(path);
if (me_it == _quick_map.end())
return ERR_OBJECT_NOT_FOUND;
if (!recursive && !me_it->second->children.empty())
return ERR_INVALID_PARAMETERS;
struct delete_state
{
std::string path;
state_node *node;
decltype(state_node::children)::iterator next_child_to_delete;
};
std::stack<delete_state> delete_stack;
delete_stack.push({ path, me_it->second, me_it->second->children.begin() });
for (; !delete_stack.empty();)
{
auto &node_pair = delete_stack.top();
if (node_pair.node->children.end() == node_pair.next_child_to_delete)
{
auto delnum = _quick_map.erase(node_pair.path);
dassert(delnum == 1, "inconsistent state between quick map and tree");
delete node_pair.node;
delete_stack.pop();
}
else
{
auto child_it = node_pair.next_child_to_delete;
delete_stack.push({ node_pair.path + "/" + child_it->second->name, child_it->second, child_it->second->children.begin() });
++node_pair.next_child_to_delete;
}
}
std::string name, parent;
auto err = extract_name_parent_from_path(path, name, parent);
if (err != ERR_OK)
{
return err;
}
auto parent_it = _quick_map.find(parent);
dassert(parent_it != _quick_map.end(), "unable to find parent node");
//XXX we cannot delete root, right?
auto erase_num = parent_it->second->children.erase(name);
dassert(erase_num == 1, "inconsistent state between quick map and tree");
return ERR_OK;
}
error_code meta_state_service_simple::set_data_internal(const std::string& node, const blob& value)
{
auto path = normalize_path(node);
zauto_lock _(_state_lock);
auto it = _quick_map.find(path);
if (it == _quick_map.end())
return ERR_OBJECT_NOT_FOUND;
it->second->data = value;
return ERR_OK;
}
error_code meta_state_service_simple::initialize(const char* dir)
{
_offset = 0;
std::string log_path = dsn::utils::filesystem::path_combine(dir, "meta_state_service.log");
if (utils::filesystem::file_exists(log_path))
{
if (FILE* fd = fopen(log_path.c_str(), "rb"))
{
for (;;)
{
log_header header;
if (fread(&header, sizeof(log_header), 1, fd) != 1)
{
break;
}
if (header.magic != log_header::default_magic)
{
break;
}
std::shared_ptr<char> buffer(new char[header.size]);
if (fread(buffer.get(), header.size, 1, fd) != 1)
{
break;
}
_offset += sizeof(header) + header.size;
blob blob_wrapper(buffer, (int)header.size);
binary_reader reader(blob_wrapper);
int op_type;
unmarshall(reader, op_type);
switch (static_cast<operation_type>(op_type))
{
case operation_type::create_node:
{
std::string node;
blob data;
create_node_log::parse(reader, node, data);
create_node_internal(node, data).end_tracking();
break;
}
case operation_type::delete_node:
{
std::string node;
bool recursively_delete;
delete_node_log::parse(reader, node, recursively_delete);
delete_node_internal(node, recursively_delete).end_tracking();
break;
}
case operation_type::set_data:
{
std::string node;
blob data;
set_data_log::parse(reader, node, data);
set_data_internal(node, data).end_tracking();
break;
}
default:
//The log is complete but its content is modified by cosmic ray. This is unacceptable
dassert(false, "meta state server log corrupted");
}
}
fclose(fd);
}
}
_log = dsn_file_open(log_path.c_str(), O_RDWR | O_CREAT | O_BINARY, 0666);
if (!_log)
{
derror("open file failed: %s", log_path.c_str());
return ERR_FILE_OPERATION_FAILED;
}
return ERR_OK;
}
task_ptr meta_state_service_simple::create_node(
const std::string& node,
task_code cb_code,
const err_callback& cb_create,
const blob& value,
clientlet* tracker )
{
auto task = tasking::create_late_task(cb_code, cb_create, 0, tracker);
write_log(
create_node_log::get_log(node, value),
[=]{
return create_node_internal(node, value);
},
task
);
return task;
}
task_ptr meta_state_service_simple::delete_node(
const std::string& node,
bool recursively_delete,
task_code cb_code,
const err_callback& cb_delete,
clientlet* tracker)
{
auto task = tasking::create_late_task(cb_code, cb_delete, 0, tracker);
write_log(
delete_node_log::get_log(node, recursively_delete),
[=] {
return delete_node_internal(node, recursively_delete);
},
task
);
return task;
}
task_ptr meta_state_service_simple::node_exist(
const std::string& node,
task_code cb_code,
const err_callback& cb_exist,
clientlet* tracker)
{
error_code err;
{
zauto_lock _(_state_lock);
err = _quick_map.find(normalize_path(node)) != _quick_map.end() ? ERR_OK : ERR_PATH_NOT_FOUND;
}
return tasking::enqueue(
cb_code,
tracker,
[=]()
{
cb_exist(err);
}
);
}
task_ptr meta_state_service_simple::get_data(
const std::string& node,
task_code cb_code,
const err_value_callback& cb_get_data,
clientlet* tracker)
{
auto path = normalize_path(node);
zauto_lock _(_state_lock);
auto me_it = _quick_map.find(path);
if (me_it == _quick_map.end())
{
return tasking::enqueue(
cb_code,
tracker,
[=]()
{
cb_get_data(ERR_OBJECT_NOT_FOUND, {});
}
);
}
else
{
auto data_copy = me_it->second->data;
return tasking::enqueue(
cb_code,
tracker,
[=]() mutable
{
cb_get_data(ERR_OK, std::move(data_copy));
}
);
}
}
task_ptr meta_state_service_simple::set_data(
const std::string& node,
const blob& value,
task_code cb_code,
const err_callback& cb_set_data,
clientlet* tracker)
{
auto task = tasking::create_late_task(cb_code, cb_set_data, 0, tracker);
write_log(
set_data_log::get_log(node, value),
[=] {
return set_data_internal(node, value);
},
task
);
return task;
}
task_ptr meta_state_service_simple::get_children(
const std::string& node,
task_code cb_code,
const err_stringv_callback& cb_get_children,
clientlet* tracker)
{
auto path = normalize_path(node);
zauto_lock _(_state_lock);
auto me_it = _quick_map.find(path);
if (me_it == _quick_map.end())
{
return tasking::enqueue(
cb_code,
tracker,
[=]()
{
cb_get_children(ERR_OBJECT_NOT_FOUND, {});
}
);
}
else
{
std::vector<std::string> result;
for (auto &child_pair : me_it->second->children)
{
result.push_back(child_pair.first);
}
return tasking::enqueue(
cb_code,
tracker,
[=]() mutable
{
cb_get_children(ERR_OK, move(result));
}
);
}
}
meta_state_service_simple::~meta_state_service_simple()
{
dsn_file_close(_log);
}
}
}
<commit_msg>fix bug: new created task should be received into ptr, or it may be destroyed before return<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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.
*/
/*
* Description:
* a simple version of meta state service for development
*
* Revision history:
* 2015-11-04, @imzhenyu ([email protected]), setup the sketch
* 2015-11-11, Tianyi WANG, first version done
* xxxx-xx-xx, author, fix bug about xxx
*/
# include "meta_state_service_simple.h"
# include <dsn/internal/task.h>
# include <stack>
# include <utility>
namespace dsn
{
namespace dist
{
// path: /, /n1/n2, /n1/n2/, /n2/n2/n3
std::string meta_state_service_simple::normalize_path(const std::string& s)
{
if (s.empty() || s[0] != '/')
return "";
if (s.length() > 1 && *s.rbegin() == '/')
return s.substr(0, s.length() - 1);
return s;
}
error_code meta_state_service_simple::extract_name_parent_from_path(
const std::string& s,
/*out*/ std::string& name,
/*out*/ std::string& parent
)
{
auto pos = s.find_last_of('/');
if (pos == std::string::npos)
return ERR_INVALID_PARAMETERS;
name = s.substr(pos + 1);
if (pos > 0)
parent = s.substr(0, pos);
else
parent = "/";
return ERR_OK;
}
static void __err_cb_bind_and_enqueue(
task_ptr lock_task,
error_code err,
int delay_milliseconds = 0
)
{
auto t = dynamic_cast<safe_late_task<meta_state_service::err_callback>*>(lock_task.get());
t->bind_and_enqueue(
[&](meta_state_service::err_callback& cb)
{
return bind(cb, err);
},
delay_milliseconds
);
}
void meta_state_service_simple::write_log(blob&& log_blob, std::function<error_code()> internal_operation, task_ptr task)
{
_log_lock.lock();
uint64_t log_offset = _offset;
_offset += log_blob.length();
auto continuation_task = std::unique_ptr<operation>(new operation(false, [=](bool log_succeed)
{
dassert(log_succeed, "we cannot handle logging failure now");
__err_cb_bind_and_enqueue(task, internal_operation(), 0);
}));
auto continuation_task_ptr = continuation_task.get();
_task_queue.emplace(move(continuation_task));
_log_lock.unlock();
file::write(
_log,
log_blob.buffer_ptr(),
log_blob.length(),
log_offset,
LPC_META_STATE_SERVICE_SIMPLE_INTERNAL,
this,
[=](error_code err, size_t bytes)
{
dassert(err == ERR_OK && bytes == log_blob.length(), "we cannot handle logging failure now");
_log_lock.lock();
continuation_task_ptr->done = true;
while (!_task_queue.empty())
{
if (!_task_queue.front()->done)
{
break;
}
_task_queue.front()->cb(true);
_task_queue.pop();
}
_log_lock.unlock();
}
);
}
error_code meta_state_service_simple::create_node_internal(const std::string& node, const blob& value)
{
auto path = normalize_path(node);
zauto_lock _(_state_lock);
auto me_it = _quick_map.find(path);
if (me_it != _quick_map.end())
return ERR_NODE_ALREADY_EXIST;
std::string name, parent;
auto err = extract_name_parent_from_path(path, name, parent);
if (err != ERR_OK)
{
return err;
}
auto parent_it = _quick_map.find(parent);
if (parent_it == _quick_map.end())
return ERR_OBJECT_NOT_FOUND;
state_node* n = new state_node(name, parent_it->second, value);
parent_it->second->children.insert(quick_map::value_type(name, n));
_quick_map.insert(quick_map::value_type(path, n));
return ERR_OK;
}
error_code meta_state_service_simple::delete_node_internal(const std::string& node, bool recursive)
{
auto path = normalize_path(node);
if (path == "/")
return ERR_INVALID_PARAMETERS; // cannot delete root
zauto_lock _(_state_lock);
auto me_it = _quick_map.find(path);
if (me_it == _quick_map.end())
return ERR_OBJECT_NOT_FOUND;
if (!recursive && !me_it->second->children.empty())
return ERR_INVALID_PARAMETERS;
struct delete_state
{
std::string path;
state_node *node;
decltype(state_node::children)::iterator next_child_to_delete;
};
std::stack<delete_state> delete_stack;
delete_stack.push({ path, me_it->second, me_it->second->children.begin() });
for (; !delete_stack.empty();)
{
auto &node_pair = delete_stack.top();
if (node_pair.node->children.end() == node_pair.next_child_to_delete)
{
auto delnum = _quick_map.erase(node_pair.path);
dassert(delnum == 1, "inconsistent state between quick map and tree");
delete node_pair.node;
delete_stack.pop();
}
else
{
auto child_it = node_pair.next_child_to_delete;
delete_stack.push({ node_pair.path + "/" + child_it->second->name, child_it->second, child_it->second->children.begin() });
++node_pair.next_child_to_delete;
}
}
std::string name, parent;
auto err = extract_name_parent_from_path(path, name, parent);
if (err != ERR_OK)
{
return err;
}
auto parent_it = _quick_map.find(parent);
dassert(parent_it != _quick_map.end(), "unable to find parent node");
//XXX we cannot delete root, right?
auto erase_num = parent_it->second->children.erase(name);
dassert(erase_num == 1, "inconsistent state between quick map and tree");
return ERR_OK;
}
error_code meta_state_service_simple::set_data_internal(const std::string& node, const blob& value)
{
auto path = normalize_path(node);
zauto_lock _(_state_lock);
auto it = _quick_map.find(path);
if (it == _quick_map.end())
return ERR_OBJECT_NOT_FOUND;
it->second->data = value;
return ERR_OK;
}
error_code meta_state_service_simple::initialize(const char* dir)
{
_offset = 0;
std::string log_path = dsn::utils::filesystem::path_combine(dir, "meta_state_service.log");
if (utils::filesystem::file_exists(log_path))
{
if (FILE* fd = fopen(log_path.c_str(), "rb"))
{
for (;;)
{
log_header header;
if (fread(&header, sizeof(log_header), 1, fd) != 1)
{
break;
}
if (header.magic != log_header::default_magic)
{
break;
}
std::shared_ptr<char> buffer(new char[header.size]);
if (fread(buffer.get(), header.size, 1, fd) != 1)
{
break;
}
_offset += sizeof(header) + header.size;
blob blob_wrapper(buffer, (int)header.size);
binary_reader reader(blob_wrapper);
int op_type;
unmarshall(reader, op_type);
switch (static_cast<operation_type>(op_type))
{
case operation_type::create_node:
{
std::string node;
blob data;
create_node_log::parse(reader, node, data);
create_node_internal(node, data).end_tracking();
break;
}
case operation_type::delete_node:
{
std::string node;
bool recursively_delete;
delete_node_log::parse(reader, node, recursively_delete);
delete_node_internal(node, recursively_delete).end_tracking();
break;
}
case operation_type::set_data:
{
std::string node;
blob data;
set_data_log::parse(reader, node, data);
set_data_internal(node, data).end_tracking();
break;
}
default:
//The log is complete but its content is modified by cosmic ray. This is unacceptable
dassert(false, "meta state server log corrupted");
}
}
fclose(fd);
}
}
_log = dsn_file_open(log_path.c_str(), O_RDWR | O_CREAT | O_BINARY, 0666);
if (!_log)
{
derror("open file failed: %s", log_path.c_str());
return ERR_FILE_OPERATION_FAILED;
}
return ERR_OK;
}
task_ptr meta_state_service_simple::create_node(
const std::string& node,
task_code cb_code,
const err_callback& cb_create,
const blob& value,
clientlet* tracker )
{
task_ptr task = tasking::create_late_task(cb_code, cb_create, 0, tracker);
write_log(
create_node_log::get_log(node, value),
[=]{
return create_node_internal(node, value);
},
task
);
return task;
}
task_ptr meta_state_service_simple::delete_node(
const std::string& node,
bool recursively_delete,
task_code cb_code,
const err_callback& cb_delete,
clientlet* tracker)
{
task_ptr task = tasking::create_late_task(cb_code, cb_delete, 0, tracker);
write_log(
delete_node_log::get_log(node, recursively_delete),
[=] {
return delete_node_internal(node, recursively_delete);
},
task
);
return task;
}
task_ptr meta_state_service_simple::node_exist(
const std::string& node,
task_code cb_code,
const err_callback& cb_exist,
clientlet* tracker)
{
error_code err;
{
zauto_lock _(_state_lock);
err = _quick_map.find(normalize_path(node)) != _quick_map.end() ? ERR_OK : ERR_PATH_NOT_FOUND;
}
return tasking::enqueue(
cb_code,
tracker,
[=]()
{
cb_exist(err);
}
);
}
task_ptr meta_state_service_simple::get_data(
const std::string& node,
task_code cb_code,
const err_value_callback& cb_get_data,
clientlet* tracker)
{
auto path = normalize_path(node);
zauto_lock _(_state_lock);
auto me_it = _quick_map.find(path);
if (me_it == _quick_map.end())
{
return tasking::enqueue(
cb_code,
tracker,
[=]()
{
cb_get_data(ERR_OBJECT_NOT_FOUND, {});
}
);
}
else
{
auto data_copy = me_it->second->data;
return tasking::enqueue(
cb_code,
tracker,
[=]() mutable
{
cb_get_data(ERR_OK, std::move(data_copy));
}
);
}
}
task_ptr meta_state_service_simple::set_data(
const std::string& node,
const blob& value,
task_code cb_code,
const err_callback& cb_set_data,
clientlet* tracker)
{
task_ptr task = tasking::create_late_task(cb_code, cb_set_data, 0, tracker);
write_log(
set_data_log::get_log(node, value),
[=] {
return set_data_internal(node, value);
},
task
);
return task;
}
task_ptr meta_state_service_simple::get_children(
const std::string& node,
task_code cb_code,
const err_stringv_callback& cb_get_children,
clientlet* tracker)
{
auto path = normalize_path(node);
zauto_lock _(_state_lock);
auto me_it = _quick_map.find(path);
if (me_it == _quick_map.end())
{
return tasking::enqueue(
cb_code,
tracker,
[=]()
{
cb_get_children(ERR_OBJECT_NOT_FOUND, {});
}
);
}
else
{
std::vector<std::string> result;
for (auto &child_pair : me_it->second->children)
{
result.push_back(child_pair.first);
}
return tasking::enqueue(
cb_code,
tracker,
[=]() mutable
{
cb_get_children(ERR_OK, move(result));
}
);
}
}
meta_state_service_simple::~meta_state_service_simple()
{
dsn_file_close(_log);
}
}
}
<|endoftext|> |
<commit_before>#ifdef _WIN32
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "framework/data.h"
#include "framework/framework.h"
#include "framework/fs.h"
#include "framework/logger.h"
#include "framework/trace.h"
#include <physfs.h>
#ifdef _WIN32
#define _CRT_SECURE_NO_WARNINGS
#endif
#ifdef ANDROID
#define be16toh(x) htobe16(x)
#define be32toh(x) htobe32(x)
#define be64toh(x) htobe64(x)
#define le16toh(x) htole16(x)
#define le32toh(x) htole32(x)
#define le64toh(x) htole64(x)
#elif defined(_DEFAULT_SOURCE) || defined(_BSD_SOURCE)
#include <endian.h>
#else
/* We assume all other platforms are little endian for now */
static inline uint16_t le16toh(uint16_t val) { return val; }
static inline uint32_t le32toh(uint32_t val) { return val; }
#endif
#include "fs/physfs_archiver_cue.h"
namespace
{
using namespace OpenApoc;
class PhysfsIFileImpl : public std::streambuf, public IFileImpl
{
public:
size_t bufferSize;
std::unique_ptr<char[]> buffer;
UString systemPath;
UString suppliedPath;
PHYSFS_File *file;
PhysfsIFileImpl(const UString &path, size_t bufferSize = 512)
: bufferSize(bufferSize), buffer(new char[bufferSize]), suppliedPath(path)
{
file = PHYSFS_openRead(path.cStr());
if (!file)
{
LogError("Failed to open file \"%s\" : \"%s\"", path.cStr(), PHYSFS_getLastError());
return;
}
systemPath = PHYSFS_getRealDir(path.cStr());
systemPath += "/" + path;
}
~PhysfsIFileImpl() override
{
if (file)
PHYSFS_close(file);
}
int_type underflow() override
{
if (PHYSFS_eof(file))
{
return traits_type::eof();
}
size_t bytesRead = PHYSFS_readBytes(file, buffer.get(), bufferSize);
if (bytesRead < 1)
{
return traits_type::eof();
}
setg(buffer.get(), buffer.get(), buffer.get() + bytesRead);
return static_cast<unsigned char>(*gptr());
}
pos_type seekoff(off_type pos, std::ios_base::seekdir dir,
std::ios_base::openmode mode) override
{
switch (dir)
{
case std::ios_base::beg:
PHYSFS_seek(file, pos);
break;
case std::ios_base::cur:
PHYSFS_seek(file, (PHYSFS_tell(file) + pos) - (egptr() - gptr()));
break;
case std::ios_base::end:
PHYSFS_seek(file, PHYSFS_fileLength(file) + pos);
break;
default:
LogError("Unknown direction in seekoff (%d)", dir);
LogAssert(0);
}
if (mode & std::ios_base::in)
{
setg(egptr(), egptr(), egptr());
}
if (mode & std::ios_base::out)
{
LogError("ios::out set on read-only IFile \"%s\"", this->systemPath.cStr());
LogAssert(0);
setp(buffer.get(), buffer.get());
}
return PHYSFS_tell(file);
}
pos_type seekpos(pos_type pos, std::ios_base::openmode mode) override
{
PHYSFS_seek(file, pos);
if (mode & std::ios_base::in)
{
setg(egptr(), egptr(), egptr());
}
if (mode & std::ios_base::out)
{
LogError("ios::out set on read-only IFile \"%s\"", this->systemPath.cStr());
LogAssert(0);
setp(buffer.get(), buffer.get());
}
return PHYSFS_tell(file);
}
int_type overflow(int_type) override
{
LogError("overflow called on read-only IFile \"%s\"", this->systemPath.cStr());
LogAssert(0);
return 0;
}
};
} // anonymous namespace
namespace OpenApoc
{
IFile::IFile() : std::istream(nullptr) {}
// FIXME: MSVC needs this, GCC fails with it?
#ifdef _WIN32
IFile::IFile(IFile &&other) : std::istream(std::move(other))
{
this->f = std::move(other.f);
rdbuf(other.rdbuf());
other.rdbuf(nullptr);
}
#endif
IFileImpl::~IFileImpl() = default;
bool IFile::readule16(uint16_t &val)
{
this->read(reinterpret_cast<char *>(&val), sizeof(val));
val = le16toh(val);
return !!(*this);
}
bool IFile::readule32(uint32_t &val)
{
this->read(reinterpret_cast<char *>(&val), sizeof(val));
val = le32toh(val);
return !!(*this);
}
size_t IFile::size() const
{
if (this->f)
return PHYSFS_fileLength(dynamic_cast<PhysfsIFileImpl *>(f.get())->file);
return 0;
}
const UString &IFile::fileName() const
{
static const UString emptyString = "";
if (this->f)
return dynamic_cast<PhysfsIFileImpl *>(f.get())->suppliedPath;
return emptyString;
}
const UString &IFile::systemPath() const
{
static const UString emptyString = "";
if (this->f)
return dynamic_cast<PhysfsIFileImpl *>(f.get())->systemPath;
return emptyString;
}
std::unique_ptr<char[]> IFile::readAll()
{
auto memsize = this->size();
std::unique_ptr<char[]> mem(new char[memsize]);
if (!mem)
{
LogError("Failed to allocate memory for %llu bytes",
static_cast<long long unsigned>(memsize));
return nullptr;
}
// We don't want this to change the state (such as the offset) of the file
// stream so store off the current pos and restore it after the read
auto currentPos = this->tellg();
this->seekg(0, this->beg);
this->read(mem.get(), memsize);
this->seekg(currentPos);
return mem;
}
IFile::~IFile() = default;
FileSystem::FileSystem(std::vector<UString> paths)
{
// FIXME: Is this the right thing to do that?
LogInfo("Registering external archivers...");
PHYSFS_registerArchiver(getCueArchiver());
// Paths are supplied in inverse-search order (IE the last in 'paths' should be the first
// searched)
for (auto &p : paths)
{
if (!PHYSFS_mount(p.cStr(), "/", 0))
{
LogInfo("Failed to add resource dir \"%s\", error: %s", p.cStr(),
PHYSFS_getLastError());
continue;
}
else
LogInfo("Resource dir \"%s\" mounted to \"%s\"", p.cStr(),
PHYSFS_getMountPoint(p.cStr()));
}
this->writeDir = PHYSFS_getPrefDir(PROGRAM_ORGANISATION, PROGRAM_NAME);
LogInfo("Setting write directory to \"%s\"", this->writeDir.cStr());
PHYSFS_setWriteDir(this->writeDir.cStr());
// Finally, the write directory trumps all
PHYSFS_mount(this->writeDir.cStr(), "/", 0);
}
FileSystem::~FileSystem() = default;
IFile FileSystem::open(const UString &path)
{
TRACE_FN_ARGS1("PATH", path);
IFile f;
auto lowerPath = path.toLower();
if (path != lowerPath)
{
LogError("Path \"%s\" contains CAPITAL - cut it out!", path.cStr());
}
if (!PHYSFS_exists(path.cStr()))
{
LogInfo("Failed to find \"%s\"", path.cStr());
LogAssert(!f);
return f;
}
f.f.reset(new PhysfsIFileImpl(path));
f.rdbuf(dynamic_cast<PhysfsIFileImpl *>(f.f.get()));
LogInfo("Loading \"%s\" from \"%s\"", path.cStr(), f.systemPath().cStr());
return f;
}
std::list<UString> FileSystem::enumerateDirectory(const UString &basePath,
const UString &extension) const
{
std::list<UString> result;
bool filterByExtension = !extension.empty();
char **elements = PHYSFS_enumerateFiles(basePath.cStr());
for (char **element = elements; *element != NULL; element++)
{
if (!filterByExtension)
{
result.push_back(*element);
}
else
{
const UString elementString = (*element);
if (elementString.endsWith(extension))
{
result.push_back(elementString);
}
}
}
PHYSFS_freeList(elements);
return result;
}
static std::list<UString> recursiveFindFilesInDirectory(UString path, const UString &extension)
{
std::list<UString> foundFiles;
auto list = fw().data->fs.enumerateDirectory(path, "");
for (auto &entry : list)
{
if (entry.endsWith(extension))
{
foundFiles.push_back(path + "/" + entry);
}
else
{
auto subdirFiles = recursiveFindFilesInDirectory(path + "/" + entry, extension);
foundFiles.insert(foundFiles.end(), subdirFiles.begin(), subdirFiles.end());
}
}
return foundFiles;
}
std::list<UString> FileSystem::enumerateDirectoryRecursive(const UString &basePath,
const UString &extension) const
{
return recursiveFindFilesInDirectory(basePath, extension);
}
} // namespace OpenApoc
<commit_msg>Fix crash due to readAliases() being called before fw()->data is set<commit_after>#ifdef _WIN32
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "framework/data.h"
#include "framework/framework.h"
#include "framework/fs.h"
#include "framework/logger.h"
#include "framework/trace.h"
#include <physfs.h>
#ifdef _WIN32
#define _CRT_SECURE_NO_WARNINGS
#endif
#ifdef ANDROID
#define be16toh(x) htobe16(x)
#define be32toh(x) htobe32(x)
#define be64toh(x) htobe64(x)
#define le16toh(x) htole16(x)
#define le32toh(x) htole32(x)
#define le64toh(x) htole64(x)
#elif defined(_DEFAULT_SOURCE) || defined(_BSD_SOURCE)
#include <endian.h>
#else
/* We assume all other platforms are little endian for now */
static inline uint16_t le16toh(uint16_t val) { return val; }
static inline uint32_t le32toh(uint32_t val) { return val; }
#endif
#include "fs/physfs_archiver_cue.h"
namespace
{
using namespace OpenApoc;
class PhysfsIFileImpl : public std::streambuf, public IFileImpl
{
public:
size_t bufferSize;
std::unique_ptr<char[]> buffer;
UString systemPath;
UString suppliedPath;
PHYSFS_File *file;
PhysfsIFileImpl(const UString &path, size_t bufferSize = 512)
: bufferSize(bufferSize), buffer(new char[bufferSize]), suppliedPath(path)
{
file = PHYSFS_openRead(path.cStr());
if (!file)
{
LogError("Failed to open file \"%s\" : \"%s\"", path.cStr(), PHYSFS_getLastError());
return;
}
systemPath = PHYSFS_getRealDir(path.cStr());
systemPath += "/" + path;
}
~PhysfsIFileImpl() override
{
if (file)
PHYSFS_close(file);
}
int_type underflow() override
{
if (PHYSFS_eof(file))
{
return traits_type::eof();
}
size_t bytesRead = PHYSFS_readBytes(file, buffer.get(), bufferSize);
if (bytesRead < 1)
{
return traits_type::eof();
}
setg(buffer.get(), buffer.get(), buffer.get() + bytesRead);
return static_cast<unsigned char>(*gptr());
}
pos_type seekoff(off_type pos, std::ios_base::seekdir dir,
std::ios_base::openmode mode) override
{
switch (dir)
{
case std::ios_base::beg:
PHYSFS_seek(file, pos);
break;
case std::ios_base::cur:
PHYSFS_seek(file, (PHYSFS_tell(file) + pos) - (egptr() - gptr()));
break;
case std::ios_base::end:
PHYSFS_seek(file, PHYSFS_fileLength(file) + pos);
break;
default:
LogError("Unknown direction in seekoff (%d)", dir);
LogAssert(0);
}
if (mode & std::ios_base::in)
{
setg(egptr(), egptr(), egptr());
}
if (mode & std::ios_base::out)
{
LogError("ios::out set on read-only IFile \"%s\"", this->systemPath.cStr());
LogAssert(0);
setp(buffer.get(), buffer.get());
}
return PHYSFS_tell(file);
}
pos_type seekpos(pos_type pos, std::ios_base::openmode mode) override
{
PHYSFS_seek(file, pos);
if (mode & std::ios_base::in)
{
setg(egptr(), egptr(), egptr());
}
if (mode & std::ios_base::out)
{
LogError("ios::out set on read-only IFile \"%s\"", this->systemPath.cStr());
LogAssert(0);
setp(buffer.get(), buffer.get());
}
return PHYSFS_tell(file);
}
int_type overflow(int_type) override
{
LogError("overflow called on read-only IFile \"%s\"", this->systemPath.cStr());
LogAssert(0);
return 0;
}
};
} // anonymous namespace
namespace OpenApoc
{
IFile::IFile() : std::istream(nullptr) {}
// FIXME: MSVC needs this, GCC fails with it?
#ifdef _WIN32
IFile::IFile(IFile &&other) : std::istream(std::move(other))
{
this->f = std::move(other.f);
rdbuf(other.rdbuf());
other.rdbuf(nullptr);
}
#endif
IFileImpl::~IFileImpl() = default;
bool IFile::readule16(uint16_t &val)
{
this->read(reinterpret_cast<char *>(&val), sizeof(val));
val = le16toh(val);
return !!(*this);
}
bool IFile::readule32(uint32_t &val)
{
this->read(reinterpret_cast<char *>(&val), sizeof(val));
val = le32toh(val);
return !!(*this);
}
size_t IFile::size() const
{
if (this->f)
return PHYSFS_fileLength(dynamic_cast<PhysfsIFileImpl *>(f.get())->file);
return 0;
}
const UString &IFile::fileName() const
{
static const UString emptyString = "";
if (this->f)
return dynamic_cast<PhysfsIFileImpl *>(f.get())->suppliedPath;
return emptyString;
}
const UString &IFile::systemPath() const
{
static const UString emptyString = "";
if (this->f)
return dynamic_cast<PhysfsIFileImpl *>(f.get())->systemPath;
return emptyString;
}
std::unique_ptr<char[]> IFile::readAll()
{
auto memsize = this->size();
std::unique_ptr<char[]> mem(new char[memsize]);
if (!mem)
{
LogError("Failed to allocate memory for %llu bytes",
static_cast<long long unsigned>(memsize));
return nullptr;
}
// We don't want this to change the state (such as the offset) of the file
// stream so store off the current pos and restore it after the read
auto currentPos = this->tellg();
this->seekg(0, this->beg);
this->read(mem.get(), memsize);
this->seekg(currentPos);
return mem;
}
IFile::~IFile() = default;
FileSystem::FileSystem(std::vector<UString> paths)
{
// FIXME: Is this the right thing to do that?
LogInfo("Registering external archivers...");
PHYSFS_registerArchiver(getCueArchiver());
// Paths are supplied in inverse-search order (IE the last in 'paths' should be the first
// searched)
for (auto &p : paths)
{
if (!PHYSFS_mount(p.cStr(), "/", 0))
{
LogInfo("Failed to add resource dir \"%s\", error: %s", p.cStr(),
PHYSFS_getLastError());
continue;
}
else
LogInfo("Resource dir \"%s\" mounted to \"%s\"", p.cStr(),
PHYSFS_getMountPoint(p.cStr()));
}
this->writeDir = PHYSFS_getPrefDir(PROGRAM_ORGANISATION, PROGRAM_NAME);
LogInfo("Setting write directory to \"%s\"", this->writeDir.cStr());
PHYSFS_setWriteDir(this->writeDir.cStr());
// Finally, the write directory trumps all
PHYSFS_mount(this->writeDir.cStr(), "/", 0);
}
FileSystem::~FileSystem() = default;
IFile FileSystem::open(const UString &path)
{
TRACE_FN_ARGS1("PATH", path);
IFile f;
auto lowerPath = path.toLower();
if (path != lowerPath)
{
LogError("Path \"%s\" contains CAPITAL - cut it out!", path.cStr());
}
if (!PHYSFS_exists(path.cStr()))
{
LogInfo("Failed to find \"%s\"", path.cStr());
LogAssert(!f);
return f;
}
f.f.reset(new PhysfsIFileImpl(path));
f.rdbuf(dynamic_cast<PhysfsIFileImpl *>(f.f.get()));
LogInfo("Loading \"%s\" from \"%s\"", path.cStr(), f.systemPath().cStr());
return f;
}
std::list<UString> FileSystem::enumerateDirectory(const UString &basePath,
const UString &extension) const
{
std::list<UString> result;
bool filterByExtension = !extension.empty();
char **elements = PHYSFS_enumerateFiles(basePath.cStr());
for (char **element = elements; *element != NULL; element++)
{
if (!filterByExtension)
{
result.push_back(*element);
}
else
{
const UString elementString = (*element);
if (elementString.endsWith(extension))
{
result.push_back(elementString);
}
}
}
PHYSFS_freeList(elements);
return result;
}
static std::list<UString> recursiveFindFilesInDirectory(const FileSystem &fs, UString path,
const UString &extension)
{
std::list<UString> foundFiles;
auto list = fs.enumerateDirectory(path, "");
for (auto &entry : list)
{
if (entry.endsWith(extension))
{
foundFiles.push_back(path + "/" + entry);
}
else
{
auto subdirFiles = recursiveFindFilesInDirectory(fs, path + "/" + entry, extension);
foundFiles.insert(foundFiles.end(), subdirFiles.begin(), subdirFiles.end());
}
}
return foundFiles;
}
std::list<UString> FileSystem::enumerateDirectoryRecursive(const UString &basePath,
const UString &extension) const
{
return recursiveFindFilesInDirectory(*this, basePath, extension);
}
} // namespace OpenApoc
<|endoftext|> |
<commit_before>//
// IsingTest.cpp
// jdemon
//
// Created by Mark Larus on 3/4/13.
// Copyright (c) 2013 Kenyon College. All rights reserved.
//
#include <boost/test/unit_test.hpp>
#include <set>
#include <algorithm>
#include <stack>
#include "Ising.h"
#include "Utilities.h"
#include "TestFixtures.h"
#include "MockObjects.h"
class TransitionRuleTestFixture : \
public DefaultTransitionRuleTestFixture, \
public ValidStatesTestFixture \
{};
BOOST_FIXTURE_TEST_SUITE(TransitionRuleTest, TransitionRuleTestFixture);
BOOST_AUTO_TEST_CASE ( testTableSize ) {
for (TransitionRule::iterator it = defaultRule.begin(); it!=defaultRule.end(); ++it) {
BOOST_REQUIRE(it->second.size() == 8 && "Transition table size should be 8");
}
}
BOOST_AUTO_TEST_CASE ( testTableDeadEnds ) {
typedef TransitionRule::iterator RuleIterator;
typedef TransitionTable::iterator TableIterator;
for (RuleIterator currentRuleIterator = defaultRule.begin(); \
currentRuleIterator!=defaultRule.end(); ++currentRuleIterator) {
TransitionTable currentRule = currentRuleIterator->second;
for (TableIterator currentTableIterator = currentRule.begin();\
currentTableIterator != currentRule.end(); ++currentTableIterator) {
BOOST_CHECK(currentTableIterator->second);
}
}
}
BOOST_AUTO_TEST_CASE ( testValidTargetStates ) {
typedef TransitionRule::iterator RuleIterator;
typedef TransitionTable::iterator TableIterator;
for (RuleIterator currentRuleIterator = defaultRule.begin(); \
currentRuleIterator!=defaultRule.end(); ++currentRuleIterator) {
TransitionTable currentRule = currentRuleIterator->second;
for (TableIterator currentTableIterator = currentRule.begin();\
currentTableIterator != currentRule.end(); ++currentTableIterator) {
SystemState *targetState = currentTableIterator->second;
BOOST_CHECK(validStates.count(targetState));
}
}
}
BOOST_AUTO_TEST_SUITE_END()
class IsingReservoirTestFixture : \
public RandomNumberTestFixture,
public ConstantsTestFixture,
public ValidStatesTestFixture
{};
BOOST_FIXTURE_TEST_SUITE(IsingReservoirTest, IsingReservoirTestFixture);
BOOST_AUTO_TEST_CASE ( testWheelStep ) {
IsingReservoir reservoir(rng,c,6,6);
Reservoir::InteractionResult result;
BOOST_REQUIRE_NO_THROW(reservoir.wheelStep(result));
}
BOOST_AUTO_TEST_CASE ( testEmptyTransitionRule ) {
TransitionRule emptyRule;
IsingReservoir reservoir(rng,c,6,6,emptyRule);
Reservoir::InteractionResult result;
BOOST_REQUIRE_THROW(reservoir.wheelStep(result), EmptyTransitionRuleError);
}
BOOST_AUTO_TEST_CASE ( testDeadEndTransitionRule ) {
TransitionRule deadEndRule;
TransitionTable emptyTable;
for (char k=0; k<8; k++) {
emptyTable[k] = NULL;
}
Reservoir::InteractionResult result;
for (StateSet::iterator it = validStates.begin(); it!=validStates.end(); ++it) {
deadEndRule[*it] = emptyTable;
}
IsingReservoir reservoir(rng,c,6,6,deadEndRule);
BOOST_REQUIRE_THROW(reservoir.wheelStep(result),TransitionDeadEndError);
}
BOOST_AUTO_TEST_CASE ( testTooSmallTransitionTable ) {
TransitionRule invalidRule;
TransitionTable tooSmallTable;
for (char k=0; k<3; k++) {
tooSmallTable[k] = NULL;
}
for (StateSet::iterator it = validStates.begin(); it!=validStates.end(); ++it) {
invalidRule[*it] = tooSmallTable;
}
IsingReservoir reservoir(rng,c,6,6,invalidRule);
Reservoir::InteractionResult result;
BOOST_REQUIRE_THROW(reservoir.wheelStep(result),InvalidTableSizeError);
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE(IsingUtilityTest)
BOOST_AUTO_TEST_CASE( testNonbinaryParity ) {
int inputState = Ising::s(0,0,157);
BOOST_REQUIRE(inputState == 1);
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_FIXTURE_TEST_SUITE(ClusterMethodTest, GridOperationTestFixture)
BOOST_AUTO_TEST_CASE( includeNoCells ) {
Ising::Cell *startingPoint = grid[5];
MockRandomnessDelegate delegate(false,0);
ClusterMethodAgent agent(&delegate,1);
agent.performMethodAtCell(startingPoint);
std::set<Ising::Cell *> expectedCells;
expectedCells.insert(startingPoint);
std::set<Ising::Cell *> actualCells = changedCells();
BOOST_REQUIRE_EQUAL_COLLECTIONS(expectedCells.begin(), expectedCells.end(), actualCells.begin(), actualCells.end());
}
BOOST_AUTO_TEST_CASE( includeAllCells ) {
// This breaks if the default cell value is non-zero.
Ising::Cell *startingPoint = grid[5];
MockRandomnessDelegate delegate(true,0);
ClusterMethodAgent agent(&delegate,2);
agent.performMethodAtCell(startingPoint);
std::set<Ising::Cell *> expectedCells;
expectedCells.insert(grid.begin(),grid.end());
std::set<Ising::Cell *> actualCells = changedCells();
BOOST_REQUIRE_EQUAL_COLLECTIONS(expectedCells.begin(), expectedCells.end(), actualCells.begin(), actualCells.end());
}
BOOST_AUTO_TEST_CASE( includeSomeCells ) {
Ising::Cell *startingPoint = grid[5];
std::set<Ising::Cell *> expectedCells;
std::stack<Ising::Cell *> stack;
stack.push(startingPoint);
size_t size = 12;
while (expectedCells.size()!=size) {
if (stack.empty()) {
BOOST_FAIL("Stack should not be empty.");
}
Ising::Cell *currentCell = stack.top();
stack.pop();
Ising::Cell::Neighbors neighbors = currentCell->getNeighbors();
for (Ising::Cell::Neighbors::iterator it = neighbors.begin(); it!=neighbors.end(); ++it) {
if (!expectedCells.count(*it)) {
stack.push(*it);
}
}
expectedCells.insert(currentCell);
}
BOOST_REQUIRE_EQUAL(expectedCells.size(),size);
for (Ising::Grid::iterator it = grid.begin(); it!=grid.end(); ++it) {
if (expectedCells.count(*it)) {
(*it)->setValue(1);
} else {
(*it)->setValue(0);
}
}
resetInitialValues();
MockRandomnessDelegate delegate(true,0);
ClusterMethodAgent agent(&delegate,1);
agent.performMethodAtCell(startingPoint);
std::set<Ising::Cell *> actualCells = changedCells();
BOOST_REQUIRE_EQUAL_COLLECTIONS(expectedCells.begin(), expectedCells.end(), actualCells.begin(), actualCells.end());
}
BOOST_AUTO_TEST_CASE( testInclusionProbability ) {
BOOST_CHECK_THROW(ClusterMethodAgent(NULL,-0.01), InvalidProbabilityError);
BOOST_CHECK_THROW(ClusterMethodAgent(NULL,1.01), InvalidProbabilityError);
}
BOOST_AUTO_TEST_SUITE_END()<commit_msg>Fix error in ClusterMethodAgent unit test.<commit_after>//
// IsingTest.cpp
// jdemon
//
// Created by Mark Larus on 3/4/13.
// Copyright (c) 2013 Kenyon College. All rights reserved.
//
#include <boost/test/unit_test.hpp>
#include <set>
#include <algorithm>
#include <stack>
#include "Ising.h"
#include "Utilities.h"
#include "TestFixtures.h"
#include "MockObjects.h"
class TransitionRuleTestFixture : \
public DefaultTransitionRuleTestFixture, \
public ValidStatesTestFixture \
{};
BOOST_FIXTURE_TEST_SUITE(TransitionRuleTest, TransitionRuleTestFixture);
BOOST_AUTO_TEST_CASE ( testTableSize ) {
for (TransitionRule::iterator it = defaultRule.begin(); it!=defaultRule.end(); ++it) {
BOOST_REQUIRE(it->second.size() == 8 && "Transition table size should be 8");
}
}
BOOST_AUTO_TEST_CASE ( testTableDeadEnds ) {
typedef TransitionRule::iterator RuleIterator;
typedef TransitionTable::iterator TableIterator;
for (RuleIterator currentRuleIterator = defaultRule.begin(); \
currentRuleIterator!=defaultRule.end(); ++currentRuleIterator) {
TransitionTable currentRule = currentRuleIterator->second;
for (TableIterator currentTableIterator = currentRule.begin();\
currentTableIterator != currentRule.end(); ++currentTableIterator) {
BOOST_CHECK(currentTableIterator->second);
}
}
}
BOOST_AUTO_TEST_CASE ( testValidTargetStates ) {
typedef TransitionRule::iterator RuleIterator;
typedef TransitionTable::iterator TableIterator;
for (RuleIterator currentRuleIterator = defaultRule.begin(); \
currentRuleIterator!=defaultRule.end(); ++currentRuleIterator) {
TransitionTable currentRule = currentRuleIterator->second;
for (TableIterator currentTableIterator = currentRule.begin();\
currentTableIterator != currentRule.end(); ++currentTableIterator) {
SystemState *targetState = currentTableIterator->second;
BOOST_CHECK(validStates.count(targetState));
}
}
}
BOOST_AUTO_TEST_SUITE_END()
class IsingReservoirTestFixture : \
public RandomNumberTestFixture,
public ConstantsTestFixture,
public ValidStatesTestFixture
{};
BOOST_FIXTURE_TEST_SUITE(IsingReservoirTest, IsingReservoirTestFixture);
BOOST_AUTO_TEST_CASE ( testWheelStep ) {
IsingReservoir reservoir(rng,c,6,6);
Reservoir::InteractionResult result;
BOOST_REQUIRE_NO_THROW(reservoir.wheelStep(result));
}
BOOST_AUTO_TEST_CASE ( testEmptyTransitionRule ) {
TransitionRule emptyRule;
IsingReservoir reservoir(rng,c,6,6,emptyRule);
Reservoir::InteractionResult result;
BOOST_REQUIRE_THROW(reservoir.wheelStep(result), EmptyTransitionRuleError);
}
BOOST_AUTO_TEST_CASE ( testDeadEndTransitionRule ) {
TransitionRule deadEndRule;
TransitionTable emptyTable;
for (char k=0; k<8; k++) {
emptyTable[k] = NULL;
}
Reservoir::InteractionResult result;
for (StateSet::iterator it = validStates.begin(); it!=validStates.end(); ++it) {
deadEndRule[*it] = emptyTable;
}
IsingReservoir reservoir(rng,c,6,6,deadEndRule);
BOOST_REQUIRE_THROW(reservoir.wheelStep(result),TransitionDeadEndError);
}
BOOST_AUTO_TEST_CASE ( testTooSmallTransitionTable ) {
TransitionRule invalidRule;
TransitionTable tooSmallTable;
for (char k=0; k<3; k++) {
tooSmallTable[k] = NULL;
}
for (StateSet::iterator it = validStates.begin(); it!=validStates.end(); ++it) {
invalidRule[*it] = tooSmallTable;
}
IsingReservoir reservoir(rng,c,6,6,invalidRule);
Reservoir::InteractionResult result;
BOOST_REQUIRE_THROW(reservoir.wheelStep(result),InvalidTableSizeError);
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE(IsingUtilityTest)
BOOST_AUTO_TEST_CASE( testNonbinaryParity ) {
int inputState = Ising::s(0,0,157);
BOOST_REQUIRE(inputState == 1);
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_FIXTURE_TEST_SUITE(ClusterMethodTest, GridOperationTestFixture)
BOOST_AUTO_TEST_CASE( includeNoCells ) {
Ising::Cell *startingPoint = grid[5];
MockRandomnessDelegate delegate(false,0);
ClusterMethodAgent agent(&delegate,1);
agent.performMethodAtCell(startingPoint);
std::set<Ising::Cell *> expectedCells;
expectedCells.insert(startingPoint);
std::set<Ising::Cell *> actualCells = changedCells();
BOOST_REQUIRE_EQUAL_COLLECTIONS(expectedCells.begin(), expectedCells.end(), actualCells.begin(), actualCells.end());
}
BOOST_AUTO_TEST_CASE( includeAllCells ) {
// This breaks if the default cell value is non-zero.
Ising::Cell *startingPoint = grid[5];
MockRandomnessDelegate delegate(true,0);
ClusterMethodAgent agent(&delegate,1);
agent.performMethodAtCell(startingPoint);
std::set<Ising::Cell *> expectedCells;
expectedCells.insert(grid.begin(),grid.end());
std::set<Ising::Cell *> actualCells = changedCells();
BOOST_REQUIRE_EQUAL_COLLECTIONS(expectedCells.begin(), expectedCells.end(), actualCells.begin(), actualCells.end());
}
BOOST_AUTO_TEST_CASE( includeSomeCells ) {
Ising::Cell *startingPoint = grid[5];
std::set<Ising::Cell *> expectedCells;
std::stack<Ising::Cell *> stack;
stack.push(startingPoint);
size_t size = 12;
while (expectedCells.size()!=size) {
if (stack.empty()) {
BOOST_FAIL("Stack should not be empty.");
}
Ising::Cell *currentCell = stack.top();
stack.pop();
Ising::Cell::Neighbors neighbors = currentCell->getNeighbors();
for (Ising::Cell::Neighbors::iterator it = neighbors.begin(); it!=neighbors.end(); ++it) {
if (!expectedCells.count(*it)) {
stack.push(*it);
}
}
expectedCells.insert(currentCell);
}
BOOST_REQUIRE_EQUAL(expectedCells.size(),size);
for (Ising::Grid::iterator it = grid.begin(); it!=grid.end(); ++it) {
if (expectedCells.count(*it)) {
(*it)->setValue(1);
} else {
(*it)->setValue(0);
}
}
resetInitialValues();
MockRandomnessDelegate delegate(true,0);
ClusterMethodAgent agent(&delegate,1);
agent.performMethodAtCell(startingPoint);
std::set<Ising::Cell *> actualCells = changedCells();
BOOST_REQUIRE_EQUAL_COLLECTIONS(expectedCells.begin(), expectedCells.end(), actualCells.begin(), actualCells.end());
}
BOOST_AUTO_TEST_CASE( testInclusionProbability ) {
BOOST_CHECK_THROW(ClusterMethodAgent(NULL,-0.01), InvalidProbabilityError);
BOOST_CHECK_THROW(ClusterMethodAgent(NULL,1.01), InvalidProbabilityError);
}
BOOST_AUTO_TEST_SUITE_END()<|endoftext|> |
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*-
uiserver/decryptverifywizard.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2007 Klarälvdalens Datakonsult AB
Kleopatra 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.
Kleopatra 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
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "decryptverifywizard.h"
#include "decryptverifyoperationwidget.h"
#include "decryptverifyresultwidget.h"
#include <utils/filenamerequester.h>
#include <utils/stl_util.h>
#include <KLocale>
#include <QScrollArea>
#include <QWizardPage>
#include <QLayout>
#include <QLabel>
#include <QEventLoop>
#include <QPointer>
#include <QAbstractButton>
#include <QScrollBar>
#include <boost/bind.hpp>
#include <vector>
#include <cassert>
using namespace Kleo;
using namespace boost;
namespace {
static QSize getMinimumSizeHint( const QWidget * w ) {
return w ? w->minimumSizeHint() : QSize( 0, 0 );
}
static QSize getSizeHint( const QWidget * w ) {
return w ? w->sizeHint() : QSize( 0, 0 );
}
class ScrollArea : public QScrollArea {
Q_OBJECT
public:
explicit ScrollArea( QWidget * p=0 )
: QScrollArea( p )
{
setWidget( new QWidget );
new QVBoxLayout( widget() );
setWidgetResizable( true );
}
~ScrollArea() {}
/* reimp */ QSize minimumSizeHint() const {
return QSize( getMinimumSizeHint( widget() ).width() + getSizeHint( verticalScrollBar() ).width() + 2*frameWidth(), 0 )
.expandedTo( QScrollArea::minimumSizeHint() );
}
/* reimp */ QSize sizeHint() const {
const QSize widgetSizeHint = getSizeHint( widget() );
const int fw = frameWidth();
return QScrollArea::sizeHint().expandedTo( widgetSizeHint + QSize( 2*fw, 2*fw ) + QSize( getSizeHint( verticalScrollBar() ).width(), 0 ) );
}
};
class HLine : public QFrame {
Q_OBJECT
public:
explicit HLine( QWidget * p=0, Qt::WindowFlags f=0 )
: QFrame( p, f )
{
setFrameStyle( QFrame::HLine|QFrame::Sunken );
}
};
class OperationsPage : public QWizardPage {
Q_OBJECT
public:
explicit OperationsPage( QWidget * p=0 );
~OperationsPage();
void setOutputDirectory( const QString & dir ) {
m_ui.outputDirectoryFNR.setFileName( dir );
}
QString outputDirectory() const {
return m_ui.outputDirectoryFNR.fileName();
}
void ensureIndexAvailable( unsigned int idx );
DecryptVerifyOperationWidget * widget( unsigned int idx ) {
return m_widgets.at( idx );
}
private:
std::vector<DecryptVerifyOperationWidget*> m_widgets;
struct UI {
QLabel outputDirectoryLB;
FileNameRequester outputDirectoryFNR;
ScrollArea scrollArea; // ### replace with KDScrollArea when done
QVBoxLayout vlay;
QHBoxLayout hlay;
explicit UI( OperationsPage * q );
} m_ui;
};
class ResultPage : public QWizardPage {
Q_OBJECT
public:
explicit ResultPage( QWidget * p=0 );
~ResultPage();
void ensureIndexAvailable( unsigned int idx );
DecryptVerifyResultWidget * widget( unsigned int idx ) {
return m_widgets.at( idx );
}
private Q_SLOTS:
void slotMaybeNoMoreProgress() {
wizard()->button( QWizard::CancelButton )
->setEnabled( kdtools::any( m_widgets.begin(), m_widgets.end(),
bind( &DecryptVerifyResultWidget::operationInProgress, _1 ) ) );
}
private:
std::vector<DecryptVerifyResultWidget*> m_widgets;
struct UI {
ScrollArea scrollArea; // ### replace with KDScrollArea when done
QVBoxLayout vlay;
explicit UI( ResultPage * q );
} m_ui;
};
}
class DecryptVerifyWizard::Private {
friend class ::Kleo::DecryptVerifyWizard;
DecryptVerifyWizard * const q;
public:
Private( DecryptVerifyWizard * qq );
~Private();
void ensureIndexAvailable( unsigned int idx ) {
operationsPage.ensureIndexAvailable( idx );
resultPage.ensureIndexAvailable( idx );
}
private:
OperationsPage operationsPage;
ResultPage resultPage;
};
DecryptVerifyWizard::DecryptVerifyWizard( QWidget * p, Qt::WindowFlags f )
: QWizard( p, f ), d( new Private( this ) )
{
}
DecryptVerifyWizard::~DecryptVerifyWizard() {}
void DecryptVerifyWizard::setOutputDirectory( const QString & dir ) {
d->operationsPage.setOutputDirectory( dir );
}
QString DecryptVerifyWizard::outputDirectory() const {
return d->operationsPage.outputDirectory();
}
DecryptVerifyOperationWidget * DecryptVerifyWizard::operationWidget( unsigned int idx ) {
d->ensureIndexAvailable( idx );
return d->operationsPage.widget( idx );
}
DecryptVerifyResultWidget * DecryptVerifyWizard::resultWidget( unsigned int idx ) {
d->ensureIndexAvailable( idx );
return d->resultPage.widget( idx );
}
bool DecryptVerifyWizard::waitForOperationSelection() {
if ( !isVisible() )
return true;
assert( button( NextButton ) );
assert( button( CancelButton ) );
QEventLoop loop;
QPointer<QObject> that = this;
connect( this, SIGNAL(currentIdChanged(int)), &loop, SLOT(quit()) );
connect( this, SIGNAL(finished(int)), &loop, SLOT(quit()) );
loop.exec();
return that && currentPage() == &d->resultPage ;
}
DecryptVerifyWizard::Private::Private( DecryptVerifyWizard * qq )
: q( qq ),
operationsPage( q ),
resultPage( q )
{
q->addPage( &operationsPage );
q->addPage( &resultPage );
}
DecryptVerifyWizard::Private::~Private() {}
OperationsPage::OperationsPage( QWidget * p )
: QWizardPage( p ), m_widgets(), m_ui( this )
{
setTitle( i18n("FIXME Choose operations to be performed") );
setSubTitle( i18n("FIXME Here, you can check and, if needed, override "
"the operations Kleopatra detected for the input given.") );
setCommitPage( true );
}
OperationsPage::~OperationsPage() {}
OperationsPage::UI::UI( OperationsPage * q )
: outputDirectoryLB( i18n("&Output directory:"), q ),
outputDirectoryFNR( q ),
scrollArea( q ),
vlay( q ),
hlay()
{
KDAB_SET_OBJECT_NAME( outputDirectoryLB );
KDAB_SET_OBJECT_NAME( outputDirectoryFNR );
KDAB_SET_OBJECT_NAME( scrollArea );
KDAB_SET_OBJECT_NAME( vlay );
KDAB_SET_OBJECT_NAME( hlay );
assert( qobject_cast<QBoxLayout*>(scrollArea.widget()->layout()) );
static_cast<QBoxLayout*>(scrollArea.widget()->layout())->addStretch( 1 );
outputDirectoryLB.setBuddy( &outputDirectoryFNR );
hlay.setMargin( 0 );
vlay.addWidget( &scrollArea, 1 );
vlay.addLayout( &hlay );
hlay.addWidget( &outputDirectoryLB );
hlay.addWidget( &outputDirectoryFNR );
}
void OperationsPage::ensureIndexAvailable( unsigned int idx ) {
if ( idx < m_widgets.size() )
return;
assert( m_ui.scrollArea.widget() );
assert( qobject_cast<QBoxLayout*>( m_ui.scrollArea.widget()->layout() ) );
QBoxLayout & blay = *static_cast<QBoxLayout*>( m_ui.scrollArea.widget()->layout() );
for ( unsigned int i = m_widgets.size() ; i < idx+1 ; ++i ) {
if ( i )
blay.insertWidget( blay.count()-1, new HLine( m_ui.scrollArea.widget() ) );
DecryptVerifyOperationWidget * w = new DecryptVerifyOperationWidget( m_ui.scrollArea.widget() );
blay.insertWidget( blay.count()-1, w );
w->show();
m_widgets.push_back( w );
}
}
ResultPage::ResultPage( QWidget * p )
: QWizardPage( p ), m_widgets(), m_ui( this )
{
setTitle( i18n("Results") );
setSubTitle( i18n("FIXME") );
setButtonText( QWizard::FinishButton, i18n("&OK") );
}
ResultPage::~ResultPage() {}
ResultPage::UI::UI( ResultPage * q )
: scrollArea( q ),
vlay( q )
{
KDAB_SET_OBJECT_NAME( scrollArea );
KDAB_SET_OBJECT_NAME( vlay );
assert( qobject_cast<QBoxLayout*>(scrollArea.widget()->layout()) );
static_cast<QBoxLayout*>(scrollArea.widget()->layout())->addStretch( 1 );
vlay.addWidget( &scrollArea );
}
void ResultPage::ensureIndexAvailable( unsigned int idx ) {
if ( idx < m_widgets.size() )
return;
assert( m_ui.scrollArea.widget() );
assert( qobject_cast<QBoxLayout*>( m_ui.scrollArea.widget()->layout() ) );
QBoxLayout & blay = *static_cast<QBoxLayout*>( m_ui.scrollArea.widget()->layout() );
for ( unsigned int i = m_widgets.size() ; i < idx+1 ; ++i ) {
if ( i )
blay.insertWidget( blay.count()-1, new HLine( m_ui.scrollArea.widget() ) );
DecryptVerifyResultWidget * w = new DecryptVerifyResultWidget( m_ui.scrollArea.widget() );
connect( w, SIGNAL(operationStateChanged()), this, SLOT(slotMaybeNoMoreProgress()) );
blay.insertWidget( blay.count()-1, w );
w->show();
m_widgets.push_back( w );
}
}
#include "decryptverifywizard.moc"
#include "moc_decryptverifywizard.cpp"
<commit_msg>Fine-tuning<commit_after>/* -*- mode: c++; c-basic-offset:4 -*-
uiserver/decryptverifywizard.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2007 Klarälvdalens Datakonsult AB
Kleopatra 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.
Kleopatra 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
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "decryptverifywizard.h"
#include "decryptverifyoperationwidget.h"
#include "decryptverifyresultwidget.h"
#include <utils/filenamerequester.h>
#include <utils/stl_util.h>
#include <KLocale>
#include <QScrollArea>
#include <QWizardPage>
#include <QLayout>
#include <QLabel>
#include <QEventLoop>
#include <QPointer>
#include <QAbstractButton>
#include <QScrollBar>
#include <boost/bind.hpp>
#include <vector>
#include <cassert>
using namespace Kleo;
using namespace boost;
namespace {
static QSize getMinimumSizeHint( const QWidget * w ) {
return w ? w->minimumSizeHint() : QSize( 0, 0 );
}
static QSize getSizeHint( const QWidget * w ) {
return w ? w->sizeHint() : QSize( 0, 0 );
}
class ScrollArea : public QScrollArea {
Q_OBJECT
public:
explicit ScrollArea( QWidget * p=0 )
: QScrollArea( p )
{
setWidget( new QWidget );
new QVBoxLayout( widget() );
setWidgetResizable( true );
}
~ScrollArea() {}
/* reimp */ QSize minimumSizeHint() const {
return QSize( getMinimumSizeHint( widget() ).width() + getSizeHint( verticalScrollBar() ).width() + 2*frameWidth(), 0 )
.expandedTo( QScrollArea::minimumSizeHint() );
}
/* reimp */ QSize sizeHint() const {
const QSize widgetSizeHint = getSizeHint( widget() );
const int fw = frameWidth();
return QScrollArea::sizeHint().expandedTo( widgetSizeHint + QSize( 2*fw, 2*fw ) + QSize( getSizeHint( verticalScrollBar() ).width(), 0 ) );
}
};
class HLine : public QFrame {
Q_OBJECT
public:
explicit HLine( QWidget * p=0, Qt::WindowFlags f=0 )
: QFrame( p, f )
{
setFrameStyle( QFrame::HLine|QFrame::Sunken );
}
};
class OperationsPage : public QWizardPage {
Q_OBJECT
public:
explicit OperationsPage( QWidget * p=0 );
~OperationsPage();
void setOutputDirectory( const QString & dir ) {
m_ui.outputDirectoryFNR.setFileName( dir );
}
QString outputDirectory() const {
return m_ui.outputDirectoryFNR.fileName();
}
void ensureIndexAvailable( unsigned int idx );
DecryptVerifyOperationWidget * widget( unsigned int idx ) {
return m_widgets.at( idx );
}
private:
std::vector<DecryptVerifyOperationWidget*> m_widgets;
struct UI {
QLabel outputDirectoryLB;
FileNameRequester outputDirectoryFNR;
ScrollArea scrollArea; // ### replace with KDScrollArea when done
QVBoxLayout vlay;
QHBoxLayout hlay;
explicit UI( OperationsPage * q );
} m_ui;
};
class ResultPage : public QWizardPage {
Q_OBJECT
public:
explicit ResultPage( QWidget * p=0 );
~ResultPage();
void ensureIndexAvailable( unsigned int idx );
DecryptVerifyResultWidget * widget( unsigned int idx ) {
return m_widgets.at( idx );
}
private Q_SLOTS:
void slotMaybeNoMoreProgress() {
wizard()->button( QWizard::CancelButton )
->setEnabled( kdtools::any( m_widgets.begin(), m_widgets.end(),
bind( &DecryptVerifyResultWidget::operationInProgress, _1 ) ) );
}
private:
std::vector<DecryptVerifyResultWidget*> m_widgets;
struct UI {
ScrollArea scrollArea; // ### replace with KDScrollArea when done
QVBoxLayout vlay;
explicit UI( ResultPage * q );
} m_ui;
};
}
class DecryptVerifyWizard::Private {
friend class ::Kleo::DecryptVerifyWizard;
DecryptVerifyWizard * const q;
public:
Private( DecryptVerifyWizard * qq );
~Private();
void ensureIndexAvailable( unsigned int idx ) {
operationsPage.ensureIndexAvailable( idx );
resultPage.ensureIndexAvailable( idx );
}
private:
OperationsPage operationsPage;
ResultPage resultPage;
};
DecryptVerifyWizard::DecryptVerifyWizard( QWidget * p, Qt::WindowFlags f )
: QWizard( p, f ), d( new Private( this ) )
{
}
DecryptVerifyWizard::~DecryptVerifyWizard() {}
void DecryptVerifyWizard::setOutputDirectory( const QString & dir ) {
d->operationsPage.setOutputDirectory( dir );
}
QString DecryptVerifyWizard::outputDirectory() const {
return d->operationsPage.outputDirectory();
}
DecryptVerifyOperationWidget * DecryptVerifyWizard::operationWidget( unsigned int idx ) {
d->ensureIndexAvailable( idx );
return d->operationsPage.widget( idx );
}
DecryptVerifyResultWidget * DecryptVerifyWizard::resultWidget( unsigned int idx ) {
d->ensureIndexAvailable( idx );
return d->resultPage.widget( idx );
}
bool DecryptVerifyWizard::waitForOperationSelection() {
if ( !isVisible() )
return true;
assert( button( NextButton ) );
assert( button( CancelButton ) );
QEventLoop loop;
QPointer<QObject> that = this;
connect( this, SIGNAL(currentIdChanged(int)), &loop, SLOT(quit()) );
connect( this, SIGNAL(finished(int)), &loop, SLOT(quit()) );
loop.exec();
return that && currentPage() == &d->resultPage ;
}
DecryptVerifyWizard::Private::Private( DecryptVerifyWizard * qq )
: q( qq ),
operationsPage( q ),
resultPage( q )
{
q->setOptions( q->options() | NoBackButtonOnStartPage | NoBackButtonOnLastPage );
q->addPage( &operationsPage );
q->addPage( &resultPage );
}
DecryptVerifyWizard::Private::~Private() {}
OperationsPage::OperationsPage( QWidget * p )
: QWizardPage( p ), m_widgets(), m_ui( this )
{
setTitle( i18n("FIXME Choose operations to be performed") );
setSubTitle( i18n("FIXME Here, you can check and, if needed, override "
"the operations Kleopatra detected for the input given.") );
setCommitPage( true );
setButtonText( QWizard::CommitButton, i18n("&Decrypt/Verify") );
}
OperationsPage::~OperationsPage() {}
OperationsPage::UI::UI( OperationsPage * q )
: outputDirectoryLB( i18n("&Output directory:"), q ),
outputDirectoryFNR( q ),
scrollArea( q ),
vlay( q ),
hlay()
{
KDAB_SET_OBJECT_NAME( outputDirectoryLB );
KDAB_SET_OBJECT_NAME( outputDirectoryFNR );
KDAB_SET_OBJECT_NAME( scrollArea );
KDAB_SET_OBJECT_NAME( vlay );
KDAB_SET_OBJECT_NAME( hlay );
assert( qobject_cast<QBoxLayout*>(scrollArea.widget()->layout()) );
static_cast<QBoxLayout*>(scrollArea.widget()->layout())->addStretch( 1 );
outputDirectoryLB.setBuddy( &outputDirectoryFNR );
hlay.setMargin( 0 );
vlay.addWidget( &scrollArea, 1 );
vlay.addLayout( &hlay );
hlay.addWidget( &outputDirectoryLB );
hlay.addWidget( &outputDirectoryFNR );
}
void OperationsPage::ensureIndexAvailable( unsigned int idx ) {
if ( idx < m_widgets.size() )
return;
assert( m_ui.scrollArea.widget() );
assert( qobject_cast<QBoxLayout*>( m_ui.scrollArea.widget()->layout() ) );
QBoxLayout & blay = *static_cast<QBoxLayout*>( m_ui.scrollArea.widget()->layout() );
for ( unsigned int i = m_widgets.size() ; i < idx+1 ; ++i ) {
if ( i )
blay.insertWidget( blay.count()-1, new HLine( m_ui.scrollArea.widget() ) );
DecryptVerifyOperationWidget * w = new DecryptVerifyOperationWidget( m_ui.scrollArea.widget() );
blay.insertWidget( blay.count()-1, w );
w->show();
m_widgets.push_back( w );
}
}
ResultPage::ResultPage( QWidget * p )
: QWizardPage( p ), m_widgets(), m_ui( this )
{
setTitle( i18n("Results") );
setSubTitle( i18n("FIXME") );
setButtonText( QWizard::FinishButton, i18n("&OK") );
}
ResultPage::~ResultPage() {}
ResultPage::UI::UI( ResultPage * q )
: scrollArea( q ),
vlay( q )
{
KDAB_SET_OBJECT_NAME( scrollArea );
KDAB_SET_OBJECT_NAME( vlay );
assert( qobject_cast<QBoxLayout*>(scrollArea.widget()->layout()) );
static_cast<QBoxLayout*>(scrollArea.widget()->layout())->addStretch( 1 );
vlay.addWidget( &scrollArea );
}
void ResultPage::ensureIndexAvailable( unsigned int idx ) {
if ( idx < m_widgets.size() )
return;
assert( m_ui.scrollArea.widget() );
assert( qobject_cast<QBoxLayout*>( m_ui.scrollArea.widget()->layout() ) );
QBoxLayout & blay = *static_cast<QBoxLayout*>( m_ui.scrollArea.widget()->layout() );
for ( unsigned int i = m_widgets.size() ; i < idx+1 ; ++i ) {
if ( i )
blay.insertWidget( blay.count()-1, new HLine( m_ui.scrollArea.widget() ) );
DecryptVerifyResultWidget * w = new DecryptVerifyResultWidget( m_ui.scrollArea.widget() );
connect( w, SIGNAL(operationStateChanged()), this, SLOT(slotMaybeNoMoreProgress()) );
blay.insertWidget( blay.count()-1, w );
w->show();
m_widgets.push_back( w );
}
}
#include "decryptverifywizard.moc"
#include "moc_decryptverifywizard.cpp"
<|endoftext|> |
<commit_before>// Ignore unused parameter warnings coming from cppuint headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>
#include <libmesh/equation_systems.h>
#include <libmesh/mesh.h>
#include <libmesh/mesh_generation.h>
#include <libmesh/edge_edge2.h>
#include <libmesh/face_quad4.h>
#include <libmesh/cell_hex8.h>
#include <libmesh/dof_map.h>
#include <libmesh/linear_implicit_system.h>
#include <libmesh/mesh_refinement.h>
#include "test_comm.h"
using namespace libMesh;
class SlitFunc : public FEMFunctionBase<Number>
{
public:
SlitFunc() {}
~SlitFunc () {}
virtual void init_context (const FEMContext &) libmesh_override {}
virtual UniquePtr<FEMFunctionBase<Number> >
clone () const libmesh_override
{
return UniquePtr<FEMFunctionBase<Number> > (new SlitFunc());
}
virtual Number operator() (const FEMContext & c,
const Point & p,
const Real /*time*/ = 0.)
libmesh_override
{
const Real & x = p(0);
const Real & y = p(1);
const Point centroid = c.get_elem().centroid();
const Real sign = centroid(1)/std::abs(centroid(1));
return (1 - std::abs(1-x)) * (1-std::abs(y)) * sign;
}
virtual void operator() (const FEMContext & c,
const Point & p,
const Real time,
DenseVector<Number> & output)
libmesh_override
{
for (unsigned int i=0; i != output.size(); ++i)
output(i) = (*this)(c, p, time);
}
};
class SlitMeshTest : public CppUnit::TestCase {
/**
* The goal of this test is to ensure that a 2D mesh with nodes overlapping
* on opposite sides of an internal, "slit" edge is useable.
*/
public:
CPPUNIT_TEST_SUITE( SlitMeshTest );
CPPUNIT_TEST( testMesh );
CPPUNIT_TEST_SUITE_END();
protected:
Mesh* _mesh;
void build_mesh()
{
_mesh = new Mesh(*TestCommWorld);
/*
(0,1) (1,1) (2,1)
x---------------x---------------x
| | |
| | |
| | |
| | |
| | |
x---------------x---------------x
(0,0) (1,0) (2,0)
| | |
| | |
| | |
| | |
x---------------x---------------x
(0,-1) (1,-1) (2,-1)
*/
_mesh->set_mesh_dimension(2);
_mesh->add_point( Point(0.0, 0.0), 0 );
_mesh->add_point( Point(1.0, 0.0), 1 );
_mesh->add_point( Point(1.0, 1.0), 2 );
_mesh->add_point( Point(0.0, 1.0), 3 );
_mesh->add_point( Point(0.0,-1.0), 4 );
_mesh->add_point( Point(1.0,-1.0), 5 );
_mesh->add_point( Point(1.0, 0.0), 6 );
_mesh->add_point( Point(2.0, 0.0), 7 );
_mesh->add_point( Point(2.0, 1.0), 8 );
_mesh->add_point( Point(2.0,-1.0), 9 );
{
Elem* elem_top_left = new Quad4;
elem_top_left->set_node(0) = _mesh->node_ptr(0);
elem_top_left->set_node(1) = _mesh->node_ptr(1);
elem_top_left->set_node(2) = _mesh->node_ptr(2);
elem_top_left->set_node(3) = _mesh->node_ptr(3);
elem_top_left->set_id() = 0;
_mesh->add_elem(elem_top_left);
Elem* elem_bottom_left = new Quad4;
elem_bottom_left->set_node(0) = _mesh->node_ptr(4);
elem_bottom_left->set_node(1) = _mesh->node_ptr(5);
elem_bottom_left->set_node(2) = _mesh->node_ptr(6);
elem_bottom_left->set_node(3) = _mesh->node_ptr(0);
elem_bottom_left->set_id() = 1;
_mesh->add_elem(elem_bottom_left);
Elem* elem_top_right = new Quad4;
elem_top_right->set_node(0) = _mesh->node_ptr(1);
elem_top_right->set_node(1) = _mesh->node_ptr(7);
elem_top_right->set_node(2) = _mesh->node_ptr(8);
elem_top_right->set_node(3) = _mesh->node_ptr(2);
elem_top_right->set_id() = 2;
_mesh->add_elem(elem_top_right);
Elem* elem_bottom_right = new Quad4;
elem_bottom_right->set_node(0) = _mesh->node_ptr(5);
elem_bottom_right->set_node(1) = _mesh->node_ptr(9);
elem_bottom_right->set_node(2) = _mesh->node_ptr(7);
elem_bottom_right->set_node(3) = _mesh->node_ptr(6);
elem_bottom_right->set_id() = 3;
_mesh->add_elem(elem_bottom_right);
}
// libMesh shouldn't renumber, or our based-on-initial-id
// assertions later may fail.
_mesh->allow_renumbering(false);
_mesh->prepare_for_use();
}
public:
void setUp()
{
this->build_mesh();
}
void tearDown()
{
delete _mesh;
}
void testMesh()
{
// There'd better be 4 elements
CPPUNIT_ASSERT_EQUAL( (dof_id_type)4, _mesh->n_elem() );
// There'd better still be a full 10 nodes
CPPUNIT_ASSERT_EQUAL( (dof_id_type)10, _mesh->n_nodes() );
/* The middle nodes should still be distinct between the top and
* bottom elements */
if (_mesh->query_elem_ptr(0) && _mesh->query_elem_ptr(1))
CPPUNIT_ASSERT( _mesh->elem_ref(0).node_id(1) != _mesh->elem_ref(1).node_id(2) );
if (_mesh->query_elem_ptr(2) && _mesh->query_elem_ptr(3))
CPPUNIT_ASSERT( _mesh->elem_ref(2).node_id(0) != _mesh->elem_ref(3).node_id(3) );
/* The middle nodes should still be shared between left and right
* elements on top and bottom */
if (_mesh->query_elem_ptr(0) && _mesh->query_elem_ptr(2))
CPPUNIT_ASSERT_EQUAL( _mesh->elem_ref(0).node_id(1),
_mesh->elem_ref(2).node_id(0) );
if (_mesh->query_elem_ptr(1) && _mesh->query_elem_ptr(3))
CPPUNIT_ASSERT_EQUAL( _mesh->elem_ref(1).node_id(2),
_mesh->elem_ref(3).node_id(3) );
}
};
class SlitMeshRefinedMeshTest : public SlitMeshTest {
/**
* The goal of this test is the same as the previous, but now we do a
* uniform refinement and make sure the result mesh is consistent. i.e.
* the new node shared between the 1D elements is the same as the node
* shared on the underlying quads, and so on.
*/
public:
CPPUNIT_TEST_SUITE( SlitMeshRefinedMeshTest );
CPPUNIT_TEST( testMesh );
CPPUNIT_TEST_SUITE_END();
// Yes, this is necessary. Somewhere in those macros is a protected/private
public:
void setUp()
{
this->build_mesh();
#ifdef LIBMESH_ENABLE_AMR
MeshRefinement(*_mesh).uniformly_refine(1);
#endif
}
void testMesh()
{
#ifdef LIBMESH_ENABLE_AMR
// We should have 20 total and 16 active elements.
CPPUNIT_ASSERT_EQUAL( (dof_id_type)20, _mesh->n_elem() );
CPPUNIT_ASSERT_EQUAL( (dof_id_type)16, _mesh->n_active_elem() );
// We should have 28 nodes, not 25 or 26
CPPUNIT_ASSERT_EQUAL( (dof_id_type)28, _mesh->n_nodes() );
#endif
}
};
class SlitMeshRefinedSystemTest : public SlitMeshTest {
/**
* The goal of this test is the same as the previous, but now we
* create a system and set dof values to make sure they are properly
* interpolated after refinement.
*/
public:
CPPUNIT_TEST_SUITE( SlitMeshRefinedSystemTest );
CPPUNIT_TEST( testMesh );
CPPUNIT_TEST( testSystem );
#ifdef LIBMESH_ENABLE_UNIQUE_ID
CPPUNIT_TEST( testRestart );
#endif
CPPUNIT_TEST_SUITE_END();
protected:
System* _sys;
EquationSystems* _es;
public:
void setUp()
{
this->build_mesh();
// libMesh *should* renumber now, or a ParallelMesh might not have
// contiguous ids, which is a requirement to write xda files.
_mesh->allow_renumbering(true);
_es = new EquationSystems(*_mesh);
_sys = &_es->add_system<System> ("SimpleSystem");
_sys->add_variable("u", FIRST);
_es->init();
SlitFunc slitfunc;
_sys->project_solution(&slitfunc);
#ifdef LIBMESH_ENABLE_AMR
MeshRefinement(*_mesh).uniformly_refine(1);
_es->reinit();
MeshRefinement(*_mesh).uniformly_refine(1);
_es->reinit();
#endif
}
void tearDown()
{
delete _es;
// _sys is owned by _es
delete _mesh;
}
void testMesh()
{
#ifdef LIBMESH_ENABLE_AMR
// We should have 84 total and 64 active elements.
CPPUNIT_ASSERT_EQUAL( (dof_id_type)(4+16+64), _mesh->n_elem() );
CPPUNIT_ASSERT_EQUAL( (dof_id_type)64, _mesh->n_active_elem() );
// We should have 88 nodes
CPPUNIT_ASSERT_EQUAL( (dof_id_type)88, _mesh->n_nodes() );
#endif
}
void testSystem()
{
SlitFunc slitfunc;
unsigned int dim = 2;
CPPUNIT_ASSERT_EQUAL( _sys->n_vars(), 1u );
FEMContext context(*_sys);
FEBase * fe = NULL;
context.get_element_fe( 0, fe, dim );
const std::vector<Point> & xyz = fe->get_xyz();
fe->get_phi();
MeshBase::const_element_iterator el =
_mesh->active_local_elements_begin();
const MeshBase::const_element_iterator end_el =
_mesh->active_local_elements_end();
for (; el != end_el; ++el)
{
const Elem * elem = *el;
context.pre_fe_reinit(*_sys, elem);
context.elem_fe_reinit();
const unsigned int n_qp = xyz.size();
for (unsigned int qp=0; qp != n_qp; ++qp)
{
const Number exact_val = slitfunc(context, xyz[qp]);
const Number discrete_val = context.interior_value(0, qp);
CPPUNIT_ASSERT_DOUBLES_EQUAL(libmesh_real(exact_val),
libmesh_real(discrete_val),
TOLERANCE*TOLERANCE);
}
}
}
void testRestart()
{
SlitFunc slitfunc;
_mesh->write("slit_mesh.xda");
_es->write("slit_solution.xda",
EquationSystems::WRITE_DATA |
EquationSystems::WRITE_SERIAL_FILES);
Mesh mesh2(*TestCommWorld);
mesh2.read("slit_mesh.xda");
EquationSystems es2(mesh2);
es2.read("slit_solution.xda");
System & sys2 = es2.get_system<System> ("SimpleSystem");
unsigned int dim = 2;
CPPUNIT_ASSERT_EQUAL( sys2.n_vars(), 1u );
FEMContext context(sys2);
FEBase * fe = NULL;
context.get_element_fe( 0, fe, dim );
const std::vector<Point> & xyz = fe->get_xyz();
fe->get_phi();
MeshBase::const_element_iterator el =
mesh2.active_local_elements_begin();
const MeshBase::const_element_iterator end_el =
mesh2.active_local_elements_end();
for (; el != end_el; ++el)
{
const Elem * elem = *el;
context.pre_fe_reinit(sys2, elem);
context.elem_fe_reinit();
const unsigned int n_qp = xyz.size();
for (unsigned int qp=0; qp != n_qp; ++qp)
{
const Number exact_val = slitfunc(context, xyz[qp]);
const Number discrete_val = context.interior_value(0, qp);
CPPUNIT_ASSERT_DOUBLES_EQUAL(libmesh_real(exact_val),
libmesh_real(discrete_val),
TOLERANCE*TOLERANCE);
}
}
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( SlitMeshTest );
CPPUNIT_TEST_SUITE_REGISTRATION( SlitMeshRefinedMeshTest );
CPPUNIT_TEST_SUITE_REGISTRATION( SlitMeshRefinedSystemTest );
<commit_msg>Heavier test coverage of unique_id() reads<commit_after>// Ignore unused parameter warnings coming from cppuint headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>
#include <libmesh/equation_systems.h>
#include <libmesh/mesh.h>
#include <libmesh/mesh_generation.h>
#include <libmesh/edge_edge2.h>
#include <libmesh/face_quad4.h>
#include <libmesh/cell_hex8.h>
#include <libmesh/dof_map.h>
#include <libmesh/linear_implicit_system.h>
#include <libmesh/mesh_refinement.h>
#include "test_comm.h"
using namespace libMesh;
class SlitFunc : public FEMFunctionBase<Number>
{
public:
SlitFunc() {}
~SlitFunc () {}
virtual void init_context (const FEMContext &) libmesh_override {}
virtual UniquePtr<FEMFunctionBase<Number> >
clone () const libmesh_override
{
return UniquePtr<FEMFunctionBase<Number> > (new SlitFunc());
}
virtual Number operator() (const FEMContext & c,
const Point & p,
const Real /*time*/ = 0.)
libmesh_override
{
const Real & x = p(0);
const Real & y = p(1);
const Point centroid = c.get_elem().centroid();
const Real sign = centroid(1)/std::abs(centroid(1));
return (1 - std::abs(1-x)) * (1-std::abs(y)) * sign;
}
virtual void operator() (const FEMContext & c,
const Point & p,
const Real time,
DenseVector<Number> & output)
libmesh_override
{
for (unsigned int i=0; i != output.size(); ++i)
output(i) = (*this)(c, p, time);
}
};
class SlitMeshTest : public CppUnit::TestCase {
/**
* The goal of this test is to ensure that a 2D mesh with nodes overlapping
* on opposite sides of an internal, "slit" edge is useable.
*/
public:
CPPUNIT_TEST_SUITE( SlitMeshTest );
CPPUNIT_TEST( testMesh );
CPPUNIT_TEST_SUITE_END();
protected:
Mesh* _mesh;
void build_mesh()
{
_mesh = new Mesh(*TestCommWorld);
/*
(0,1) (1,1) (2,1)
x---------------x---------------x
| | |
| | |
| | |
| | |
| | |
x---------------x---------------x
(0,0) (1,0) (2,0)
| | |
| | |
| | |
| | |
x---------------x---------------x
(0,-1) (1,-1) (2,-1)
*/
_mesh->set_mesh_dimension(2);
_mesh->add_point( Point(0.0, 0.0), 0 );
_mesh->add_point( Point(1.0, 0.0), 1 );
_mesh->add_point( Point(1.0, 1.0), 2 );
_mesh->add_point( Point(0.0, 1.0), 3 );
_mesh->add_point( Point(0.0,-1.0), 4 );
_mesh->add_point( Point(1.0,-1.0), 5 );
_mesh->add_point( Point(1.0, 0.0), 6 );
_mesh->add_point( Point(2.0, 0.0), 7 );
_mesh->add_point( Point(2.0, 1.0), 8 );
_mesh->add_point( Point(2.0,-1.0), 9 );
{
Elem* elem_top_left = new Quad4;
elem_top_left->set_node(0) = _mesh->node_ptr(0);
elem_top_left->set_node(1) = _mesh->node_ptr(1);
elem_top_left->set_node(2) = _mesh->node_ptr(2);
elem_top_left->set_node(3) = _mesh->node_ptr(3);
elem_top_left->set_id() = 0;
_mesh->add_elem(elem_top_left);
Elem* elem_bottom_left = new Quad4;
elem_bottom_left->set_node(0) = _mesh->node_ptr(4);
elem_bottom_left->set_node(1) = _mesh->node_ptr(5);
elem_bottom_left->set_node(2) = _mesh->node_ptr(6);
elem_bottom_left->set_node(3) = _mesh->node_ptr(0);
elem_bottom_left->set_id() = 1;
_mesh->add_elem(elem_bottom_left);
Elem* elem_top_right = new Quad4;
elem_top_right->set_node(0) = _mesh->node_ptr(1);
elem_top_right->set_node(1) = _mesh->node_ptr(7);
elem_top_right->set_node(2) = _mesh->node_ptr(8);
elem_top_right->set_node(3) = _mesh->node_ptr(2);
elem_top_right->set_id() = 2;
_mesh->add_elem(elem_top_right);
Elem* elem_bottom_right = new Quad4;
elem_bottom_right->set_node(0) = _mesh->node_ptr(5);
elem_bottom_right->set_node(1) = _mesh->node_ptr(9);
elem_bottom_right->set_node(2) = _mesh->node_ptr(7);
elem_bottom_right->set_node(3) = _mesh->node_ptr(6);
elem_bottom_right->set_id() = 3;
_mesh->add_elem(elem_bottom_right);
}
// libMesh shouldn't renumber, or our based-on-initial-id
// assertions later may fail.
_mesh->allow_renumbering(false);
_mesh->prepare_for_use();
}
public:
void setUp()
{
this->build_mesh();
}
void tearDown()
{
delete _mesh;
}
void testMesh()
{
// There'd better be 4 elements
CPPUNIT_ASSERT_EQUAL( (dof_id_type)4, _mesh->n_elem() );
// There'd better still be a full 10 nodes
CPPUNIT_ASSERT_EQUAL( (dof_id_type)10, _mesh->n_nodes() );
/* The middle nodes should still be distinct between the top and
* bottom elements */
if (_mesh->query_elem_ptr(0) && _mesh->query_elem_ptr(1))
CPPUNIT_ASSERT( _mesh->elem_ref(0).node_id(1) != _mesh->elem_ref(1).node_id(2) );
if (_mesh->query_elem_ptr(2) && _mesh->query_elem_ptr(3))
CPPUNIT_ASSERT( _mesh->elem_ref(2).node_id(0) != _mesh->elem_ref(3).node_id(3) );
/* The middle nodes should still be shared between left and right
* elements on top and bottom */
if (_mesh->query_elem_ptr(0) && _mesh->query_elem_ptr(2))
CPPUNIT_ASSERT_EQUAL( _mesh->elem_ref(0).node_id(1),
_mesh->elem_ref(2).node_id(0) );
if (_mesh->query_elem_ptr(1) && _mesh->query_elem_ptr(3))
CPPUNIT_ASSERT_EQUAL( _mesh->elem_ref(1).node_id(2),
_mesh->elem_ref(3).node_id(3) );
}
};
class SlitMeshRefinedMeshTest : public SlitMeshTest {
/**
* The goal of this test is the same as the previous, but now we do a
* uniform refinement and make sure the result mesh is consistent. i.e.
* the new node shared between the 1D elements is the same as the node
* shared on the underlying quads, and so on.
*/
public:
CPPUNIT_TEST_SUITE( SlitMeshRefinedMeshTest );
CPPUNIT_TEST( testMesh );
CPPUNIT_TEST_SUITE_END();
// Yes, this is necessary. Somewhere in those macros is a protected/private
public:
void setUp()
{
this->build_mesh();
#ifdef LIBMESH_ENABLE_AMR
MeshRefinement(*_mesh).uniformly_refine(1);
#endif
}
void testMesh()
{
#ifdef LIBMESH_ENABLE_AMR
// We should have 20 total and 16 active elements.
CPPUNIT_ASSERT_EQUAL( (dof_id_type)20, _mesh->n_elem() );
CPPUNIT_ASSERT_EQUAL( (dof_id_type)16, _mesh->n_active_elem() );
// We should have 28 nodes, not 25 or 26
CPPUNIT_ASSERT_EQUAL( (dof_id_type)28, _mesh->n_nodes() );
#endif
}
};
class SlitMeshRefinedSystemTest : public SlitMeshTest {
/**
* The goal of this test is the same as the previous, but now we
* create a system and set dof values to make sure they are properly
* interpolated after refinement.
*/
public:
CPPUNIT_TEST_SUITE( SlitMeshRefinedSystemTest );
CPPUNIT_TEST( testMesh );
CPPUNIT_TEST( testSystem );
#ifdef LIBMESH_ENABLE_UNIQUE_ID
CPPUNIT_TEST( testRestart );
#endif
CPPUNIT_TEST_SUITE_END();
protected:
System* _sys;
EquationSystems* _es;
public:
void setUp()
{
this->build_mesh();
// libMesh *should* renumber now, or a ParallelMesh might not have
// contiguous ids, which is a requirement to write xda files.
_mesh->allow_renumbering(true);
_es = new EquationSystems(*_mesh);
_sys = &_es->add_system<System> ("SimpleSystem");
_sys->add_variable("u", FIRST);
_es->init();
SlitFunc slitfunc;
_sys->project_solution(&slitfunc);
#ifdef LIBMESH_ENABLE_AMR
MeshRefinement(*_mesh).uniformly_refine(1);
_es->reinit();
MeshRefinement(*_mesh).uniformly_refine(1);
_es->reinit();
#endif
}
void tearDown()
{
delete _es;
// _sys is owned by _es
delete _mesh;
}
void testMesh()
{
#ifdef LIBMESH_ENABLE_AMR
// We should have 84 total and 64 active elements.
CPPUNIT_ASSERT_EQUAL( (dof_id_type)(4+16+64), _mesh->n_elem() );
CPPUNIT_ASSERT_EQUAL( (dof_id_type)64, _mesh->n_active_elem() );
// We should have 88 nodes
CPPUNIT_ASSERT_EQUAL( (dof_id_type)88, _mesh->n_nodes() );
#endif
}
void testSystem()
{
SlitFunc slitfunc;
unsigned int dim = 2;
CPPUNIT_ASSERT_EQUAL( _sys->n_vars(), 1u );
FEMContext context(*_sys);
FEBase * fe = NULL;
context.get_element_fe( 0, fe, dim );
const std::vector<Point> & xyz = fe->get_xyz();
fe->get_phi();
MeshBase::const_element_iterator el =
_mesh->active_local_elements_begin();
const MeshBase::const_element_iterator end_el =
_mesh->active_local_elements_end();
for (; el != end_el; ++el)
{
const Elem * elem = *el;
context.pre_fe_reinit(*_sys, elem);
context.elem_fe_reinit();
const unsigned int n_qp = xyz.size();
for (unsigned int qp=0; qp != n_qp; ++qp)
{
const Number exact_val = slitfunc(context, xyz[qp]);
const Number discrete_val = context.interior_value(0, qp);
CPPUNIT_ASSERT_DOUBLES_EQUAL(libmesh_real(exact_val),
libmesh_real(discrete_val),
TOLERANCE*TOLERANCE);
}
}
}
void testRestart()
{
SlitFunc slitfunc;
_mesh->write("slit_mesh.xda");
_es->write("slit_solution.xda",
EquationSystems::WRITE_DATA |
EquationSystems::WRITE_SERIAL_FILES);
Mesh mesh2(*TestCommWorld);
mesh2.read("slit_mesh.xda");
EquationSystems es2(mesh2);
es2.read("slit_solution.xda");
System & sys2 = es2.get_system<System> ("SimpleSystem");
unsigned int dim = 2;
CPPUNIT_ASSERT_EQUAL( sys2.n_vars(), 1u );
FEMContext context(sys2);
FEBase * fe = NULL;
context.get_element_fe( 0, fe, dim );
const std::vector<Point> & xyz = fe->get_xyz();
fe->get_phi();
// While we're in the middle of a unique id based test case, let's
// make sure our unique ids were all read in correctly too.
UniquePtr<PointLocatorBase> locator = _mesh->sub_point_locator();
MeshBase::const_element_iterator el =
mesh2.active_local_elements_begin();
const MeshBase::const_element_iterator end_el =
mesh2.active_local_elements_end();
for (; el != end_el; ++el)
{
const Elem * elem = *el;
const Elem * mesh1_elem = (*locator)(elem->centroid());
if (mesh1_elem)
{
CPPUNIT_ASSERT_EQUAL( elem->unique_id(),
mesh1_elem->unique_id() );
for (unsigned int n=0; n != elem->n_nodes(); ++n)
{
Node & node = elem->node_ref(n);
Node & mesh1_node = mesh1_elem->node_ref(n);
CPPUNIT_ASSERT_EQUAL( node.unique_id(),
mesh1_node.unique_id() );
}
}
context.pre_fe_reinit(sys2, elem);
context.elem_fe_reinit();
const unsigned int n_qp = xyz.size();
for (unsigned int qp=0; qp != n_qp; ++qp)
{
const Number exact_val = slitfunc(context, xyz[qp]);
const Number discrete_val = context.interior_value(0, qp);
CPPUNIT_ASSERT_DOUBLES_EQUAL(libmesh_real(exact_val),
libmesh_real(discrete_val),
TOLERANCE*TOLERANCE);
}
}
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( SlitMeshTest );
CPPUNIT_TEST_SUITE_REGISTRATION( SlitMeshRefinedMeshTest );
CPPUNIT_TEST_SUITE_REGISTRATION( SlitMeshRefinedSystemTest );
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2012 Désiré Nuentsa-Wakam <[email protected]>
//
// Eigen 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 3 of the License, or (at your option) any later version.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "sparse_solver.h"
#include <Eigen/SparseLU>
#include <unsupported/Eigen/SparseExtra>
template<typename T> void test_metis_T()
{
SparseLU<SparseMatrix<T, ColMajor>, COLAMDOrdering<int> > sparselu_metis;
check_sparse_square_solving(sparselu_metis);
}
void test_metis_support()
{
CALL_SUBTEST_1(test_metis_T<double>());
}
<commit_msg>Fix test for Metis<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2012 Désiré Nuentsa-Wakam <[email protected]>
//
// Eigen 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 3 of the License, or (at your option) any later version.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "sparse_solver.h"
#include <Eigen/SparseLU>
#include <Eigen/MetisSupport>
#include <unsupported/Eigen/SparseExtra>
template<typename T> void test_metis_T()
{
SparseLU<SparseMatrix<T, ColMajor>, MetisOrdering<int> > sparselu_metis;
check_sparse_square_solving(sparselu_metis);
}
void test_metis_support()
{
CALL_SUBTEST_1(test_metis_T<double>());
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2015-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS 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 <hip/hip_runtime.h>
#include "hip_internal.hpp"
#include "hip_platform.hpp"
#include "platform/runtime.hpp"
#include "utils/flags.hpp"
#include "utils/versions.hpp"
std::vector<hip::Device*> g_devices;
namespace hip {
thread_local Device* g_device = nullptr;
thread_local std::stack<Device*> g_ctxtStack;
thread_local hipError_t g_lastError = hipSuccess;
std::once_flag g_ihipInitialized;
Device* host_device = nullptr;
void init() {
if (!amd::Runtime::initialized()) {
amd::IS_HIP = true;
GPU_NUM_MEM_DEPENDENCY = 0;
AMD_DIRECT_DISPATCH = flagIsDefault(AMD_DIRECT_DISPATCH) ? 1 : AMD_DIRECT_DISPATCH;
amd::Runtime::init();
}
const std::vector<amd::Device*>& devices = amd::Device::getDevices(CL_DEVICE_TYPE_GPU, false);
for (unsigned int i=0; i<devices.size(); i++) {
const std::vector<amd::Device*> device(1, devices[i]);
amd::Context* context = new amd::Context(device, amd::Context::Info());
if (!context) return;
// Enable active wait on the device by default
devices[i]->SetActiveWait(true);
if (context && CL_SUCCESS != context->create(nullptr)) {
context->release();
} else {
g_devices.push_back(new Device(context, i));
}
}
amd::Context* hContext = new amd::Context(devices, amd::Context::Info());
if (!hContext) return;
if (CL_SUCCESS != hContext->create(nullptr)) {
hContext->release();
}
host_device = new Device(hContext, -1);
PlatformState::instance().init();
}
Device* getCurrentDevice() {
return g_device;
}
void setCurrentDevice(unsigned int index) {
assert(index<g_devices.size());
g_device = g_devices[index];
}
amd::HostQueue* getQueue(hipStream_t stream) {
if (stream == nullptr) {
return getNullStream();
} else {
constexpr bool WaitNullStreamOnly = true;
amd::HostQueue* queue = reinterpret_cast<hip::Stream*>(stream)->asHostQueue();
if (!(reinterpret_cast<hip::Stream*>(stream)->Flags() & hipStreamNonBlocking)) {
iHipWaitActiveStreams(queue, WaitNullStreamOnly);
}
return queue;
}
}
// ================================================================================================
amd::HostQueue* getNullStream(amd::Context& ctx) {
for (auto& it : g_devices) {
if (it->asContext() == &ctx) {
return it->NullStream();
}
}
// If it's a pure SVM allocation with system memory access, then it shouldn't matter which device
// runtime selects by default
if (hip::host_device->asContext() == &ctx) {
// Return current...
return getNullStream();
}
return nullptr;
}
// ================================================================================================
amd::HostQueue* getNullStream() {
Device* device = getCurrentDevice();
return device ? device->NullStream() : nullptr;
}
};
using namespace hip;
hipError_t hipInit(unsigned int flags) {
HIP_INIT_API(hipInit, flags);
HIP_RETURN(hipSuccess);
}
hipError_t hipCtxCreate(hipCtx_t *ctx, unsigned int flags, hipDevice_t device) {
HIP_INIT_API(hipCtxCreate, ctx, flags, device);
if (static_cast<size_t>(device) >= g_devices.size()) {
HIP_RETURN(hipErrorInvalidValue);
}
*ctx = reinterpret_cast<hipCtx_t>(g_devices[device]);
// Increment ref count for device primary context
g_devices[device]->retain();
g_ctxtStack.push(g_devices[device]);
HIP_RETURN(hipSuccess);
}
hipError_t hipCtxSetCurrent(hipCtx_t ctx) {
HIP_INIT_API(hipCtxSetCurrent, ctx);
if (ctx == nullptr) {
if(!g_ctxtStack.empty()) {
g_ctxtStack.pop();
}
} else {
hip::g_device = reinterpret_cast<hip::Device*>(ctx);
if(!g_ctxtStack.empty()) {
g_ctxtStack.pop();
}
g_ctxtStack.push(hip::getCurrentDevice());
}
HIP_RETURN(hipSuccess);
}
hipError_t hipCtxGetCurrent(hipCtx_t* ctx) {
HIP_INIT_API(hipCtxGetCurrent, ctx);
*ctx = reinterpret_cast<hipCtx_t>(hip::getCurrentDevice());
HIP_RETURN(hipSuccess);
}
hipError_t hipCtxGetSharedMemConfig(hipSharedMemConfig* pConfig) {
HIP_INIT_API(hipCtxGetSharedMemConfig, pConfig);
*pConfig = hipSharedMemBankSizeFourByte;
HIP_RETURN(hipSuccess);
}
hipError_t hipRuntimeGetVersion(int *runtimeVersion) {
HIP_INIT_API(hipRuntimeGetVersion, runtimeVersion);
if (!runtimeVersion) {
HIP_RETURN(hipErrorInvalidValue);
}
// HIP_VERSION = HIP_VERSION_MAJOR*100 + HIP_MINOR_VERSION
*runtimeVersion = HIP_VERSION;
HIP_RETURN(hipSuccess);
}
hipError_t hipCtxDestroy(hipCtx_t ctx) {
HIP_INIT_API(hipCtxDestroy, ctx);
hip::Device* dev = reinterpret_cast<hip::Device*>(ctx);
if (dev == nullptr) {
HIP_RETURN(hipErrorInvalidValue);
}
// Need to remove the ctx of calling thread if its the top one
if (!g_ctxtStack.empty() && g_ctxtStack.top() == dev) {
g_ctxtStack.pop();
}
// Remove context from global context list
for (unsigned int i = 0; i < g_devices.size(); i++) {
if (g_devices[i] == dev) {
// Decrement ref count for device primary context
dev->release();
}
}
HIP_RETURN(hipSuccess);
}
hipError_t hipCtxPopCurrent(hipCtx_t* ctx) {
HIP_INIT_API(hipCtxPopCurrent, ctx);
hip::Device** dev = reinterpret_cast<hip::Device**>(ctx);
if (!g_ctxtStack.empty()) {
if (dev != nullptr) {
*dev = g_ctxtStack.top();
}
g_ctxtStack.pop();
} else {
DevLogError("Context Stack empty \n");
HIP_RETURN(hipErrorInvalidContext);
}
HIP_RETURN(hipSuccess);
}
hipError_t hipCtxPushCurrent(hipCtx_t ctx) {
HIP_INIT_API(hipCtxPushCurrent, ctx);
hip::Device* dev = reinterpret_cast<hip::Device*>(ctx);
if (dev == nullptr) {
HIP_RETURN(hipErrorInvalidContext);
}
hip::g_device = dev;
g_ctxtStack.push(hip::getCurrentDevice());
HIP_RETURN(hipSuccess);
}
hipError_t hipDriverGetVersion(int* driverVersion) {
HIP_INIT_API(hipDriverGetVersion, driverVersion);
auto* deviceHandle = g_devices[0]->devices()[0];
const auto& info = deviceHandle->info();
if (driverVersion) {
*driverVersion = AMD_PLATFORM_BUILD_NUMBER * 100 +
AMD_PLATFORM_REVISION_NUMBER;
} else {
HIP_RETURN(hipErrorInvalidValue);
}
HIP_RETURN(hipSuccess);
}
hipError_t hipCtxGetDevice(hipDevice_t* device) {
HIP_INIT_API(hipCtxGetDevice, device);
if (device != nullptr) {
*device = hip::getCurrentDevice()->deviceId();
HIP_RETURN(hipSuccess);
} else {
HIP_RETURN(hipErrorInvalidValue);
}
HIP_RETURN(hipErrorInvalidContext);
}
hipError_t hipCtxGetApiVersion(hipCtx_t ctx, int* apiVersion) {
HIP_INIT_API(hipCtxGetApiVersion, apiVersion);
assert(0 && "Unimplemented");
HIP_RETURN(hipErrorNotSupported);
}
hipError_t hipCtxGetCacheConfig(hipFuncCache_t* cacheConfig) {
HIP_INIT_API(hipCtxGetCacheConfig, cacheConfig);
assert(0 && "Unimplemented");
HIP_RETURN(hipErrorNotSupported);
}
hipError_t hipCtxSetCacheConfig(hipFuncCache_t cacheConfig) {
HIP_INIT_API(hipCtxSetCacheConfig, cacheConfig);
assert(0 && "Unimplemented");
HIP_RETURN(hipErrorNotSupported);
}
hipError_t hipCtxSetSharedMemConfig(hipSharedMemConfig config) {
HIP_INIT_API(hipCtxSetSharedMemConfig, config);
assert(0 && "Unimplemented");
HIP_RETURN(hipErrorNotSupported);
}
hipError_t hipCtxSynchronize(void) {
HIP_INIT_API(hipCtxSynchronize, 1);
assert(0 && "Unimplemented");
HIP_RETURN(hipErrorNotSupported);
}
hipError_t hipCtxGetFlags(unsigned int* flags) {
HIP_INIT_API(hipCtxGetFlags, flags);
assert(0 && "Unimplemented");
HIP_RETURN(hipErrorNotSupported);
}
hipError_t hipDevicePrimaryCtxGetState(hipDevice_t dev, unsigned int* flags, int* active) {
HIP_INIT_API(hipDevicePrimaryCtxGetState, dev, flags, active);
if (static_cast<unsigned int>(dev) >= g_devices.size()) {
HIP_RETURN(hipErrorInvalidDevice);
}
if (flags != nullptr) {
*flags = 0;
}
if (active != nullptr) {
*active = (g_devices[dev] == hip::getCurrentDevice())? 1 : 0;
}
HIP_RETURN(hipSuccess);
}
hipError_t hipDevicePrimaryCtxRelease(hipDevice_t dev) {
HIP_INIT_API(hipDevicePrimaryCtxRelease, dev);
if (static_cast<unsigned int>(dev) >= g_devices.size()) {
HIP_RETURN(hipErrorInvalidDevice);
}
HIP_RETURN(hipSuccess);
}
hipError_t hipDevicePrimaryCtxRetain(hipCtx_t* pctx, hipDevice_t dev) {
HIP_INIT_API(hipDevicePrimaryCtxRetain, pctx, dev);
if (static_cast<unsigned int>(dev) >= g_devices.size()) {
HIP_RETURN(hipErrorInvalidDevice);
}
if (pctx == nullptr) {
HIP_RETURN(hipErrorInvalidValue);
}
*pctx = reinterpret_cast<hipCtx_t>(g_devices[dev]);
HIP_RETURN(hipSuccess);
}
hipError_t hipDevicePrimaryCtxReset(hipDevice_t dev) {
HIP_INIT_API(hipDevicePrimaryCtxReset, dev);
HIP_RETURN(hipSuccess);
}
hipError_t hipDevicePrimaryCtxSetFlags(hipDevice_t dev, unsigned int flags) {
HIP_INIT_API(hipDevicePrimaryCtxSetFlags, dev, flags);
if (static_cast<unsigned int>(dev) >= g_devices.size()) {
HIP_RETURN(hipErrorInvalidDevice);
} else {
HIP_RETURN(hipErrorContextAlreadyInUse);
}
}
<commit_msg>SWDEV-244287 - Keep direct dispatch for Linux only<commit_after>/* Copyright (c) 2015-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS 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 <hip/hip_runtime.h>
#include "hip_internal.hpp"
#include "hip_platform.hpp"
#include "platform/runtime.hpp"
#include "utils/flags.hpp"
#include "utils/versions.hpp"
std::vector<hip::Device*> g_devices;
namespace hip {
thread_local Device* g_device = nullptr;
thread_local std::stack<Device*> g_ctxtStack;
thread_local hipError_t g_lastError = hipSuccess;
std::once_flag g_ihipInitialized;
Device* host_device = nullptr;
void init() {
if (!amd::Runtime::initialized()) {
amd::IS_HIP = true;
GPU_NUM_MEM_DEPENDENCY = 0;
AMD_DIRECT_DISPATCH = flagIsDefault(AMD_DIRECT_DISPATCH) ? IS_LINUX : AMD_DIRECT_DISPATCH;
amd::Runtime::init();
}
const std::vector<amd::Device*>& devices = amd::Device::getDevices(CL_DEVICE_TYPE_GPU, false);
for (unsigned int i=0; i<devices.size(); i++) {
const std::vector<amd::Device*> device(1, devices[i]);
amd::Context* context = new amd::Context(device, amd::Context::Info());
if (!context) return;
// Enable active wait on the device by default
devices[i]->SetActiveWait(true);
if (context && CL_SUCCESS != context->create(nullptr)) {
context->release();
} else {
g_devices.push_back(new Device(context, i));
}
}
amd::Context* hContext = new amd::Context(devices, amd::Context::Info());
if (!hContext) return;
if (CL_SUCCESS != hContext->create(nullptr)) {
hContext->release();
}
host_device = new Device(hContext, -1);
PlatformState::instance().init();
}
Device* getCurrentDevice() {
return g_device;
}
void setCurrentDevice(unsigned int index) {
assert(index<g_devices.size());
g_device = g_devices[index];
}
amd::HostQueue* getQueue(hipStream_t stream) {
if (stream == nullptr) {
return getNullStream();
} else {
constexpr bool WaitNullStreamOnly = true;
amd::HostQueue* queue = reinterpret_cast<hip::Stream*>(stream)->asHostQueue();
if (!(reinterpret_cast<hip::Stream*>(stream)->Flags() & hipStreamNonBlocking)) {
iHipWaitActiveStreams(queue, WaitNullStreamOnly);
}
return queue;
}
}
// ================================================================================================
amd::HostQueue* getNullStream(amd::Context& ctx) {
for (auto& it : g_devices) {
if (it->asContext() == &ctx) {
return it->NullStream();
}
}
// If it's a pure SVM allocation with system memory access, then it shouldn't matter which device
// runtime selects by default
if (hip::host_device->asContext() == &ctx) {
// Return current...
return getNullStream();
}
return nullptr;
}
// ================================================================================================
amd::HostQueue* getNullStream() {
Device* device = getCurrentDevice();
return device ? device->NullStream() : nullptr;
}
};
using namespace hip;
hipError_t hipInit(unsigned int flags) {
HIP_INIT_API(hipInit, flags);
HIP_RETURN(hipSuccess);
}
hipError_t hipCtxCreate(hipCtx_t *ctx, unsigned int flags, hipDevice_t device) {
HIP_INIT_API(hipCtxCreate, ctx, flags, device);
if (static_cast<size_t>(device) >= g_devices.size()) {
HIP_RETURN(hipErrorInvalidValue);
}
*ctx = reinterpret_cast<hipCtx_t>(g_devices[device]);
// Increment ref count for device primary context
g_devices[device]->retain();
g_ctxtStack.push(g_devices[device]);
HIP_RETURN(hipSuccess);
}
hipError_t hipCtxSetCurrent(hipCtx_t ctx) {
HIP_INIT_API(hipCtxSetCurrent, ctx);
if (ctx == nullptr) {
if(!g_ctxtStack.empty()) {
g_ctxtStack.pop();
}
} else {
hip::g_device = reinterpret_cast<hip::Device*>(ctx);
if(!g_ctxtStack.empty()) {
g_ctxtStack.pop();
}
g_ctxtStack.push(hip::getCurrentDevice());
}
HIP_RETURN(hipSuccess);
}
hipError_t hipCtxGetCurrent(hipCtx_t* ctx) {
HIP_INIT_API(hipCtxGetCurrent, ctx);
*ctx = reinterpret_cast<hipCtx_t>(hip::getCurrentDevice());
HIP_RETURN(hipSuccess);
}
hipError_t hipCtxGetSharedMemConfig(hipSharedMemConfig* pConfig) {
HIP_INIT_API(hipCtxGetSharedMemConfig, pConfig);
*pConfig = hipSharedMemBankSizeFourByte;
HIP_RETURN(hipSuccess);
}
hipError_t hipRuntimeGetVersion(int *runtimeVersion) {
HIP_INIT_API(hipRuntimeGetVersion, runtimeVersion);
if (!runtimeVersion) {
HIP_RETURN(hipErrorInvalidValue);
}
// HIP_VERSION = HIP_VERSION_MAJOR*100 + HIP_MINOR_VERSION
*runtimeVersion = HIP_VERSION;
HIP_RETURN(hipSuccess);
}
hipError_t hipCtxDestroy(hipCtx_t ctx) {
HIP_INIT_API(hipCtxDestroy, ctx);
hip::Device* dev = reinterpret_cast<hip::Device*>(ctx);
if (dev == nullptr) {
HIP_RETURN(hipErrorInvalidValue);
}
// Need to remove the ctx of calling thread if its the top one
if (!g_ctxtStack.empty() && g_ctxtStack.top() == dev) {
g_ctxtStack.pop();
}
// Remove context from global context list
for (unsigned int i = 0; i < g_devices.size(); i++) {
if (g_devices[i] == dev) {
// Decrement ref count for device primary context
dev->release();
}
}
HIP_RETURN(hipSuccess);
}
hipError_t hipCtxPopCurrent(hipCtx_t* ctx) {
HIP_INIT_API(hipCtxPopCurrent, ctx);
hip::Device** dev = reinterpret_cast<hip::Device**>(ctx);
if (!g_ctxtStack.empty()) {
if (dev != nullptr) {
*dev = g_ctxtStack.top();
}
g_ctxtStack.pop();
} else {
DevLogError("Context Stack empty \n");
HIP_RETURN(hipErrorInvalidContext);
}
HIP_RETURN(hipSuccess);
}
hipError_t hipCtxPushCurrent(hipCtx_t ctx) {
HIP_INIT_API(hipCtxPushCurrent, ctx);
hip::Device* dev = reinterpret_cast<hip::Device*>(ctx);
if (dev == nullptr) {
HIP_RETURN(hipErrorInvalidContext);
}
hip::g_device = dev;
g_ctxtStack.push(hip::getCurrentDevice());
HIP_RETURN(hipSuccess);
}
hipError_t hipDriverGetVersion(int* driverVersion) {
HIP_INIT_API(hipDriverGetVersion, driverVersion);
auto* deviceHandle = g_devices[0]->devices()[0];
const auto& info = deviceHandle->info();
if (driverVersion) {
*driverVersion = AMD_PLATFORM_BUILD_NUMBER * 100 +
AMD_PLATFORM_REVISION_NUMBER;
} else {
HIP_RETURN(hipErrorInvalidValue);
}
HIP_RETURN(hipSuccess);
}
hipError_t hipCtxGetDevice(hipDevice_t* device) {
HIP_INIT_API(hipCtxGetDevice, device);
if (device != nullptr) {
*device = hip::getCurrentDevice()->deviceId();
HIP_RETURN(hipSuccess);
} else {
HIP_RETURN(hipErrorInvalidValue);
}
HIP_RETURN(hipErrorInvalidContext);
}
hipError_t hipCtxGetApiVersion(hipCtx_t ctx, int* apiVersion) {
HIP_INIT_API(hipCtxGetApiVersion, apiVersion);
assert(0 && "Unimplemented");
HIP_RETURN(hipErrorNotSupported);
}
hipError_t hipCtxGetCacheConfig(hipFuncCache_t* cacheConfig) {
HIP_INIT_API(hipCtxGetCacheConfig, cacheConfig);
assert(0 && "Unimplemented");
HIP_RETURN(hipErrorNotSupported);
}
hipError_t hipCtxSetCacheConfig(hipFuncCache_t cacheConfig) {
HIP_INIT_API(hipCtxSetCacheConfig, cacheConfig);
assert(0 && "Unimplemented");
HIP_RETURN(hipErrorNotSupported);
}
hipError_t hipCtxSetSharedMemConfig(hipSharedMemConfig config) {
HIP_INIT_API(hipCtxSetSharedMemConfig, config);
assert(0 && "Unimplemented");
HIP_RETURN(hipErrorNotSupported);
}
hipError_t hipCtxSynchronize(void) {
HIP_INIT_API(hipCtxSynchronize, 1);
assert(0 && "Unimplemented");
HIP_RETURN(hipErrorNotSupported);
}
hipError_t hipCtxGetFlags(unsigned int* flags) {
HIP_INIT_API(hipCtxGetFlags, flags);
assert(0 && "Unimplemented");
HIP_RETURN(hipErrorNotSupported);
}
hipError_t hipDevicePrimaryCtxGetState(hipDevice_t dev, unsigned int* flags, int* active) {
HIP_INIT_API(hipDevicePrimaryCtxGetState, dev, flags, active);
if (static_cast<unsigned int>(dev) >= g_devices.size()) {
HIP_RETURN(hipErrorInvalidDevice);
}
if (flags != nullptr) {
*flags = 0;
}
if (active != nullptr) {
*active = (g_devices[dev] == hip::getCurrentDevice())? 1 : 0;
}
HIP_RETURN(hipSuccess);
}
hipError_t hipDevicePrimaryCtxRelease(hipDevice_t dev) {
HIP_INIT_API(hipDevicePrimaryCtxRelease, dev);
if (static_cast<unsigned int>(dev) >= g_devices.size()) {
HIP_RETURN(hipErrorInvalidDevice);
}
HIP_RETURN(hipSuccess);
}
hipError_t hipDevicePrimaryCtxRetain(hipCtx_t* pctx, hipDevice_t dev) {
HIP_INIT_API(hipDevicePrimaryCtxRetain, pctx, dev);
if (static_cast<unsigned int>(dev) >= g_devices.size()) {
HIP_RETURN(hipErrorInvalidDevice);
}
if (pctx == nullptr) {
HIP_RETURN(hipErrorInvalidValue);
}
*pctx = reinterpret_cast<hipCtx_t>(g_devices[dev]);
HIP_RETURN(hipSuccess);
}
hipError_t hipDevicePrimaryCtxReset(hipDevice_t dev) {
HIP_INIT_API(hipDevicePrimaryCtxReset, dev);
HIP_RETURN(hipSuccess);
}
hipError_t hipDevicePrimaryCtxSetFlags(hipDevice_t dev, unsigned int flags) {
HIP_INIT_API(hipDevicePrimaryCtxSetFlags, dev, flags);
if (static_cast<unsigned int>(dev) >= g_devices.size()) {
HIP_RETURN(hipErrorInvalidDevice);
} else {
HIP_RETURN(hipErrorContextAlreadyInUse);
}
}
<|endoftext|> |
<commit_before>// $Id$
//
// Copyright (C) 2003-2011 Greg Landrum and Rational Discovery LLC
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#define NO_IMPORT_ARRAY
#include <boost/python.hpp>
#include <string>
//ours
#include <GraphMol/FileParsers/MolWriters.h>
#include <GraphMol/RDKitBase.h>
#include "rdchem.h"
#include <RDBoost/PySequenceHolder.h>
#include <RDBoost/python_streambuf.h>
namespace python = boost::python;
using boost_adaptbx::python::streambuf;
namespace RDKit {
SDWriter *getSDWriter(python::object &fileobj){
// FIX: minor leak here
streambuf *sb=new streambuf(fileobj);
streambuf::ostream *ost=new streambuf::ostream(*sb);
return new SDWriter(ost,true);
}
void SetSDWriterProps(SDWriter &writer, python::object props) {
// convert the python list to a STR_VECT
STR_VECT propNames;
PySequenceHolder<std::string> seq(props);
for (unsigned int i = 0; i < seq.size(); i++) {
propNames.push_back(seq[i]);
}
writer.setProps(propNames);
}
void WriteMolToSD(SDWriter &writer, ROMol &mol, int confId) {
writer.write(mol, confId);
}
struct sdwriter_wrap {
static void wrap() {
std::string docStr="A class for writing molecules to SD files.\n\
\n\
Usage examples:\n\
\n\
1) writing to a named file:\n\
>>> writer = SDWriter('out.sdf')\n\
>>> for mol in list_of_mols:\n\
... writer.write(mol)\n\
\n\
2) writing to a file-like object: \n\
>>> import gzip\n\
>>> outf=gzip.open('out.sdf.gz','w+')\n\
>>> writer = ForwardSDMolSupplier(outf)\n\
>>> for mol in list_of_mols:\n \
... writer.write(mol)\n\
\n\
By default all non-private molecular properties are written to the SD file.\n\
This can be changed using the SetProps method:\n\
>>> writer = SDWriter('out.sdf')\n\
>>> writer.SetProps(['prop1','prop2'])\n\
\n";
python::class_<SDWriter,
boost::noncopyable>("SDWriter",
docStr.c_str(),
python::no_init)
.def("__init__", python::make_constructor(&getSDWriter))
.def(python::init<std::string>(python::args("fileName"),
"Constructor.\n\n"
" If a string argument is provided, it will be treated as the name of the output file.\n"
" If a file-like object is provided, output will be sent there.\n\n"))
.def("SetProps", SetSDWriterProps,
"Sets the properties to be written to the output file\n\n"
" ARGUMENTS:\n\n"
" - props: a list or tuple of property names\n\n")
.def("write", WriteMolToSD,
(python::arg("self"), python::arg("mol"), python::arg("confId")=-1),
"Writes a molecule to the output file.\n\n"
" ARGUMENTS:\n\n"
" - mol: the Mol to be written\n"
" - confId: (optional) ID of the conformation to write\n\n")
.def("flush", &SDWriter::flush,
"Flushes the output file (forces the disk file to be updated).\n\n"
)
.def("close", &SDWriter::close,
"Flushes the output file and closes it. The Writer cannot be used after this.\n\n"
)
.def("NumMols", &SDWriter::numMols,
"Returns the number of molecules written so far.\n\n"
)
;
};
};
}
void wrap_sdwriter() {
RDKit::sdwriter_wrap::wrap();
}
<commit_msg>docs fix<commit_after>// $Id$
//
// Copyright (C) 2003-2011 Greg Landrum and Rational Discovery LLC
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#define NO_IMPORT_ARRAY
#include <boost/python.hpp>
#include <string>
//ours
#include <GraphMol/FileParsers/MolWriters.h>
#include <GraphMol/RDKitBase.h>
#include "rdchem.h"
#include <RDBoost/PySequenceHolder.h>
#include <RDBoost/python_streambuf.h>
namespace python = boost::python;
using boost_adaptbx::python::streambuf;
namespace RDKit {
SDWriter *getSDWriter(python::object &fileobj){
// FIX: minor leak here
streambuf *sb=new streambuf(fileobj);
streambuf::ostream *ost=new streambuf::ostream(*sb);
return new SDWriter(ost,true);
}
void SetSDWriterProps(SDWriter &writer, python::object props) {
// convert the python list to a STR_VECT
STR_VECT propNames;
PySequenceHolder<std::string> seq(props);
for (unsigned int i = 0; i < seq.size(); i++) {
propNames.push_back(seq[i]);
}
writer.setProps(propNames);
}
void WriteMolToSD(SDWriter &writer, ROMol &mol, int confId) {
writer.write(mol, confId);
}
struct sdwriter_wrap {
static void wrap() {
std::string docStr="A class for writing molecules to SD files.\n\
\n\
Usage examples:\n\
\n\
1) writing to a named file:\n\
>>> writer = SDWriter('out.sdf')\n\
>>> for mol in list_of_mols:\n\
... writer.write(mol)\n\
\n\
2) writing to a file-like object: \n\
>>> import gzip\n\
>>> outf=gzip.open('out.sdf.gz','w+')\n\
>>> writer = SDWriter(outf)\n\
>>> for mol in list_of_mols:\n \
... writer.write(mol)\n\
>>> writer.close()\n\
>>> outf.close()\n\
\n\
By default all non-private molecular properties are written to the SD file.\n\
This can be changed using the SetProps method:\n\
>>> writer = SDWriter('out.sdf')\n\
>>> writer.SetProps(['prop1','prop2'])\n\
\n";
python::class_<SDWriter,
boost::noncopyable>("SDWriter",
docStr.c_str(),
python::no_init)
.def("__init__", python::make_constructor(&getSDWriter))
.def(python::init<std::string>(python::args("fileName"),
"Constructor.\n\n"
" If a string argument is provided, it will be treated as the name of the output file.\n"
" If a file-like object is provided, output will be sent there.\n\n"))
.def("SetProps", SetSDWriterProps,
"Sets the properties to be written to the output file\n\n"
" ARGUMENTS:\n\n"
" - props: a list or tuple of property names\n\n")
.def("write", WriteMolToSD,
(python::arg("self"), python::arg("mol"), python::arg("confId")=-1),
"Writes a molecule to the output file.\n\n"
" ARGUMENTS:\n\n"
" - mol: the Mol to be written\n"
" - confId: (optional) ID of the conformation to write\n\n")
.def("flush", &SDWriter::flush,
"Flushes the output file (forces the disk file to be updated).\n\n"
)
.def("close", &SDWriter::close,
"Flushes the output file and closes it. The Writer cannot be used after this.\n\n"
)
.def("NumMols", &SDWriter::numMols,
"Returns the number of molecules written so far.\n\n"
)
;
};
};
}
void wrap_sdwriter() {
RDKit::sdwriter_wrap::wrap();
}
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- *
* OpenSenseUtilities.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2019 Stanford University and the Authors *
* Author(s): OpenSim Team *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain a *
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0. *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* -------------------------------------------------------------------------- */
#include <OpenSim/Common/STOFileAdapter.h>
#include <OpenSim/Simulation/Model/Model.h>
#include <OpenSim/Simulation/MarkersReference.h>
#include <OpenSim/Simulation/InverseKinematicsSolver.h>
#include "OpenSenseUtilities.h"
using namespace OpenSim;
using namespace SimTK;
using namespace std;
TimeSeriesTable_<SimTK::Rotation> OpenSenseUtilities::
convertQuaternionsToRotations(
const TimeSeriesTableQuaternion& qauternionsTable,
std::tuple<size_t, size_t> startEnd)
{
// Fixed transform to rotate sensor orientations in world with Z up into the
// OpenSim ground reference frame with Y up and X forward.
SimTK::Rotation R_XG = SimTK::Rotation(
SimTK::BodyOrSpaceType::BodyRotationSequence,
-SimTK_PI / 2, SimTK::XAxis,
0, SimTK::YAxis,
0, SimTK::ZAxis);
// OpenSim to the local reference frame of the pelvis (back)
//SimTK::Rotation R_XG(SimTK::BodyOrSpaceType::BodyRotationSequence,
// SimTK::Pi / 2, SimTK::ZAxis,
// SimTK::Pi / 2, SimTK::XAxis,
// 0., SimTK::ZAxis);
//SimTK::Vec3 grav(9.807, 0., 0.);
//double theta = acos(avg_accel.transpose() * grav / (avg_accel.norm() * grav.norm()));
//SimTK::Vec3 C = SimTK::cross(avg_accel, grav);
//C = C / C.norm();
//SimTK::Rotation tilt_correction = SimTK::Rotation(axisAngleToRotation(C, theta));
//R_XG = R_XG * tilt_correction;
int nc = int(qauternionsTable.getNumColumns());
const auto& times = qauternionsTable.getIndependentColumn();
size_t nt = std::get<1>(startEnd) - std::get<0>(startEnd) + 1;
std::vector<double> newTimes(nt, SimTK::NaN);
SimTK::Matrix_<SimTK::Rotation> matrix(int(nt), nc, Rotation());
int cnt = 0;
for (size_t i = std::get<0>(startEnd); i <= std::get<1>(startEnd); ++i) {
newTimes[cnt] = times[i];
const auto& quatRow = qauternionsTable.getRowAtIndex(i);
for (int j = 0; j < nc; ++j) {
const Quaternion& quatO = quatRow[j];
matrix.updElt(cnt, j) = R_XG*Rotation(quatO);
}
cnt++;
}
TimeSeriesTable_<SimTK::Rotation> orientationTable(newTimes,
matrix,
qauternionsTable.getColumnLabels());
orientationTable.updTableMetaData() = qauternionsTable.getTableMetaData();
orientationTable.setDependentsMetaData(qauternionsTable.getDependentsMetaData());
// Base will rotate to match <base>_imu, so we must first remove the base
// rotation from the other IMUs to get their orientation with respect to
// individual model bodies and thereby compute correct offsets unbiased by the
// initial base orientation.
auto imuLabels = orientationTable.getColumnLabels();
auto pix = distance(imuLabels.begin(), std::find(imuLabels.begin(), imuLabels.end(), "pelvis_imu")); //torso_imu
auto startRow = orientationTable.getRowAtIndex(0);
const Rotation& base_R = startRow.getElt(0, int(pix));
//// Heading direction of the base IMU in this case the pelvis_imu heading is its ZAxis
UnitVec3 pelvisHeading = base_R(SimTK::ZAxis);
UnitVec3 groundX = UnitVec3(1, 0, 0);
SimTK::Real angularDifference = acos(~pelvisHeading*groundX);
// If the forward axis actually is the backward axis, change direction by 180 degrees
if (angularDifference >= SimTK_PI / 2) {
if (angularDifference >= 0) {
angularDifference -= SimTK_PI;
}
else if (angularDifference <= -SimTK_PI / 2) {
angularDifference += SimTK_PI;
}
}
std::cout << "Heading correction computed to be "
<< angularDifference * SimTK_RADIAN_TO_DEGREE
<< "degs about ground Y" << std::endl;
SimTK::Rotation R_HG = SimTK::Rotation(
SimTK::BodyOrSpaceType::SpaceRotationSequence,
0, SimTK::XAxis,
angularDifference, SimTK::YAxis,
0, SimTK::ZAxis
);
for (size_t i = 0; i < orientationTable.getNumRows(); ++i) {
auto& rotationsRow = orientationTable.updRowAtIndex(i);
for (int j = 0; j < nc; ++j) {
rotationsRow[j] = R_HG*rotationsRow[j];
}
}
return orientationTable;
}
<commit_msg>Fix compilatopn error in gcc<commit_after>/* -------------------------------------------------------------------------- *
* OpenSenseUtilities.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2019 Stanford University and the Authors *
* Author(s): OpenSim Team *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain a *
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0. *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* -------------------------------------------------------------------------- */
#include <OpenSim/Common/STOFileAdapter.h>
#include <OpenSim/Simulation/Model/Model.h>
#include <OpenSim/Simulation/MarkersReference.h>
#include <OpenSim/Simulation/InverseKinematicsSolver.h>
#include "OpenSenseUtilities.h"
using namespace OpenSim;
using namespace SimTK;
using namespace std;
TimeSeriesTable_<SimTK::Rotation> OpenSenseUtilities::
convertQuaternionsToRotations(
const TimeSeriesTableQuaternion& qauternionsTable,
std::tuple<size_t, size_t> startEnd)
{
// Fixed transform to rotate sensor orientations in world with Z up into the
// OpenSim ground reference frame with Y up and X forward.
SimTK::Rotation R_XG = SimTK::Rotation(
SimTK::BodyOrSpaceType::BodyRotationSequence,
-SimTK_PI / 2, SimTK::XAxis,
0, SimTK::YAxis,
0, SimTK::ZAxis);
// OpenSim to the local reference frame of the pelvis (back)
//SimTK::Rotation R_XG(SimTK::BodyOrSpaceType::BodyRotationSequence,
// SimTK::Pi / 2, SimTK::ZAxis,
// SimTK::Pi / 2, SimTK::XAxis,
// 0., SimTK::ZAxis);
//SimTK::Vec3 grav(9.807, 0., 0.);
//double theta = acos(avg_accel.transpose() * grav / (avg_accel.norm() * grav.norm()));
//SimTK::Vec3 C = SimTK::cross(avg_accel, grav);
//C = C / C.norm();
//SimTK::Rotation tilt_correction = SimTK::Rotation(axisAngleToRotation(C, theta));
//R_XG = R_XG * tilt_correction;
int nc = int(qauternionsTable.getNumColumns());
const auto& times = qauternionsTable.getIndependentColumn();
size_t nt = std::get<1>(startEnd) - std::get<0>(startEnd) + 1;
std::vector<double> newTimes(nt, SimTK::NaN);
SimTK::Matrix_<SimTK::Rotation> matrix(int(nt), nc, Rotation());
int cnt = 0;
for (size_t i = std::get<0>(startEnd); i <= std::get<1>(startEnd); ++i) {
newTimes[cnt] = times[i];
const auto& quatRow = qauternionsTable.getRowAtIndex(i);
for (int j = 0; j < nc; ++j) {
const Quaternion& quatO = quatRow[j];
matrix.updElt(cnt, j) = R_XG*Rotation(quatO);
}
cnt++;
}
TimeSeriesTable_<SimTK::Rotation> orientationTable(newTimes,
matrix,
qauternionsTable.getColumnLabels());
orientationTable.updTableMetaData() = qauternionsTable.getTableMetaData();
orientationTable.setDependentsMetaData(qauternionsTable.getDependentsMetaData());
// Base will rotate to match <base>_imu, so we must first remove the base
// rotation from the other IMUs to get their orientation with respect to
// individual model bodies and thereby compute correct offsets unbiased by the
// initial base orientation.
auto imuLabels = orientationTable.getColumnLabels();
auto pix = distance(imuLabels.begin(), std::find(imuLabels.begin(), imuLabels.end(), "pelvis_imu")); //torso_imu
auto startRow = orientationTable.getRowAtIndex(0);
const Rotation& base_R = startRow.getElt(0, int(pix));
//// Heading direction of the base IMU in this case the pelvis_imu heading is its ZAxis
UnitVec3 pelvisHeading = base_R(SimTK::ZAxis);
UnitVec3 groundX = UnitVec3(1, 0, 0);
SimTK::Real angularDifference = acos(~pelvisHeading*groundX);
// If the forward axis actually is the backward axis, change direction by 180 degrees
if (angularDifference >= SimTK_PI / 2) {
if (angularDifference >= 0) {
angularDifference -= SimTK_PI;
}
else if (angularDifference <= -SimTK_PI / 2) {
angularDifference += SimTK_PI;
}
}
std::cout << "Heading correction computed to be "
<< angularDifference * SimTK_RADIAN_TO_DEGREE
<< "degs about ground Y" << std::endl;
SimTK::Rotation R_HG = SimTK::Rotation(
SimTK::BodyOrSpaceType::SpaceRotationSequence,
0, SimTK::XAxis,
angularDifference, SimTK::YAxis,
0, SimTK::ZAxis
);
for (size_t i = 0; i < orientationTable.getNumRows(); ++i) {
RowVectorView_<SimTK::Rotation>& rotationsRow = orientationTable.updRowAtIndex(i);
for (int j = 0; j < nc; ++j) {
rotationsRow[j] = R_HG*rotationsRow[j];
}
}
return orientationTable;
}
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2013 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the
** following disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
#include "VComment.h"
#include "VCommentBrowser.h"
#include "VCommentImage.h"
#include "VisualizationBase/src/items/Line.h"
#include "VisualizationBase/src/items/ItemStyle.h"
#include "VisualizationBase/src/items/Text.h"
#include "VisualizationBase/src/declarative/DeclarativeItemDef.h"
using namespace Visualization;
namespace Comments {
ITEM_COMMON_DEFINITIONS(VComment, "item")
VComment::VComment(Item* parent, NodeType* node) : Super(parent, node, itemStyles().get())
{
// import existing diagrams
for(auto diagram : *node->diagrams())
{
diagrams_[diagram->name()] = diagram;
}
editing_ = node->lines()->size() == 0 || (node->lines()->size() == 1 && node->lines()->at(0)->get().isEmpty());
parseLines();
}
// split up user-provided text into single elements
void VComment::parseLines()
{
clearChildren();
bool isHTML = false;
QSet<QString> diagramNames{};
int listCount = -1;
for(auto nodeLine : *node()->lines())
{
QRegExp rx("^={3,}|-{3,}|\\.{3,}$");
QString line = nodeLine->get();
// is this a new enumeration item?
if(line.left(3) == " * ")
{
listCount++;
// does this create a new list?
if(listCount == 0)
{
pushTextLine("<ol><li>");
line = line.mid(3);
}
// otherwise, just add another list item
else
{
pushTextLine("</li><li>");
line = line.mid(3);
}
}
// or is this extending an existing list?
else if(line.left(3) == " " && listCount > -1)
{
line = line.mid(3);
}
// if this is not an enumeration item, reset listCount
else if(listCount > -1 && line.left(3) != " * " && line.left(3) != " ")
{
pushTextLine("</li></ol>");
listCount = -1;
}
// is this HTML?
if(line == "<html>")
{
popLineBuffer();
isHTML = true;
continue;
}
else if(isHTML)
{
if(line == "</html>")
{
isHTML = false;
popLineBuffer(true);
}
else
{
pushTextLine(line);
}
// don't process further
continue;
}
if(rx.exactMatch(line))
{
// A line consists of one of . - = that is repeated three times or more
// The used character defines the strength of the header, i.e. one of three levels
QString style;
switch(line[0].toAscii())
{
default:
case '.': style = "single"; break;
case '-': style = "double"; break;
case '=': style = "triple"; break;
}
addChildItem(new Line(this, Line::itemStyles().get(style)));
continue;
}
// is this a header? replace it right away with the appropriate tag
rx.setPattern("^(#+)([^#].*)");
// allow headers h1 to h6
if(rx.exactMatch(line) && rx.cap(1).length() <= 6)
{
QString len = QString::number(rx.cap(1).length());
pushTextLine("<h" + len + ">" + rx.cap(2).simplified() + "</h" + len + ">");
}
// is this a diagram? format: [diagram#diagramName]
else if(line.left(9) == "[diagram#" && line.right(1) == "]" && line.size() > 9+1)
{
QString diagramName = line.mid(9,line.size()-9-1);
diagramNames << diagramName;
CommentDiagram* diagram = diagrams_.value(diagramName, nullptr);
if(diagram == nullptr)
{
diagram = new CommentDiagram(nullptr, diagramName);
diagrams_[diagramName] = diagram;
}
auto item = renderer()->render(this, diagram);
addChildItem(item);
}
// urls are specified as [browser#http://www.google.com]
else if(line.left(9) == "[browser#" && line.right(1) == "]" && line.size() > 9+1)
{
QString mid = line.mid(9, line.size()-9-1);
// read width and height, if specified
auto items = parseMarkdownArguments(mid);
QString url = items->at(0).second;
auto browser = new VCommentBrowser(this, QUrl(url));
if(items->size() > 1)
{
QSize size = parseSize(items->at(1).second);
browser->updateSize(size);
}
addChildItem(browser);
delete items;
}
// images are specified as
// [image#/home/user/image.png]
// [image#image.png|300x300] to specify a size
else if(line.left(7) == "[image#" && line.right(1) == "]" && line.size() > 7+1)
{
QString mid = line.mid(7, line.size()-7-1);
// read width and height, if specified
auto items = parseMarkdownArguments(mid);
QString path = items->at(0).second;
QSize size(0,0);
if(items->size() > 1)
size = parseSize(items->at(1).second);
addChildItem(new VCommentImage(this, items->at(0).second, size));
delete items;
}
else
{
pushTextLine(line);
}
}
popLineBuffer();
synchroniseDiagrams(diagramNames);
}
void VComment::synchroniseDiagrams(QSet<QString> itemDiagramNames)
{
// get all diagrams from the node
auto nodeDiagrams = node()->diagrams();
// gather all names from the node diagrams for easier comparison
QSet<QString> nodeDiagramNames{};
for(auto diagram : *nodeDiagrams)
nodeDiagramNames << diagram->name();
// get intersection of two sets
QSet<QString> intersection(itemDiagramNames);
intersection.intersect(nodeDiagramNames);
// new diagrams were already constructed inside of parseLines(),
// they also need to be added to the model now
auto newDiagramNames = itemDiagramNames - intersection;
if(newDiagramNames.size() > 0)
{
node()->model()->beginModification(node(), "Adding new diagrams");
for(auto diagramName : newDiagramNames)
{
auto diagram = diagrams_.value(diagramName);
node()->diagrams()->append(diagram);
}
node()->model()->endModification();
}
// diagrams that are no longer referenced need to be removed from the model
auto oldDiagramNames = nodeDiagramNames - intersection;
if(oldDiagramNames.size() > 0)
{
node()->model()->beginModification(node(), "Removing unreferenced diagrams");
for(auto diagramName : oldDiagramNames)
{
auto diagram = diagrams_.value(diagramName);
node()->diagrams()->remove(diagram);
diagrams_.remove(diagramName);
}
node()->model()->endModification();
}
}
QMap<QString, CommentDiagram*> VComment::diagrams() const
{
return diagrams_;
}
QSize VComment::parseSize(const QString& str)
{
int index = str.indexOf('x');
bool ok{};
int width = str.left(index).toInt(&ok);
if(index > 0 && !ok)
qDebug() << "Invalid width specified in size string:" << str;
int height = str.mid(index+1).toInt(&ok);
if(index+1 < str.size()-1 && !ok)
qDebug() << "Invalid height specified in size string:" << str;
return QSize(width, height);
}
QVector<QPair<QString,QString>>* VComment::parseMarkdownArguments(const QString& argString)
{
// split string on all pipes
auto lines = argString.split('|');
// TODO: get rid of escaped pipes \| e.g. in case an url contains one
auto pairs = new QVector<QPair<QString,QString>>();
// read key/value pairs
QRegExp rx("^[a-zA-Z]{,15}=");
for(auto line : lines)
{
int index = rx.indexIn(line);
if(index == -1)
pairs->push_back(qMakePair(QString(), line));
else
pairs->push_back(qMakePair(line.left(index), line.mid(index+1)));
}
return pairs;
}
QString VComment::replaceMarkdown(QString str)
{
QRegExp rx;
rx.setPattern("\\*\\*([^\\*]+)\\*\\*");
str.replace(rx, "<i>\\1</i>");
rx.setPattern("\\*([^\\*]+)\\*");
str.replace(rx, "<b>\\1</b>");
return str;
}
void VComment::pushTextLine(QString text)
{
lineBuffer_.push_back(text);
}
void VComment::popLineBuffer(bool asHtml)
{
if(lineBuffer_.size() > 0)
{
auto joined = lineBuffer_.join("\n");
if(asHtml)
{
auto browser = new VCommentBrowser(this, joined);
children_.push_back(browser);
}
else
{
auto text = new Text(this, Text::itemStyles().get("comment"), replaceMarkdown(joined));
text->setTextFormat(Qt::RichText);
children_.push_back(text);
}
lineBuffer_.clear();
}
}
void VComment::addChildItem(Visualization::Item* item)
{
popLineBuffer();
children_.push_back(item);
}
void VComment::toggleEditing()
{
if(node()->lines()->size() == 0)
editing_ = true;
else
editing_ = !editing_;
if(!editing_)
parseLines();
setUpdateNeeded(StandardUpdate);
}
bool VComment::editing() const
{
return editing_;
}
void VComment::initializeForms()
{
addForm((new SequentialLayoutFormElement())
->setVertical()
->setListOfItems([](Item* i) {
auto vc = static_cast<VComment*>(i);
return vc->children_;
}
));
addForm(item(&I::editLabel_, [](I* v){
return v->node()->lines();
}));
}
int VComment::determineForm()
{
return editing_ ? 1 : 0;
}
} /* namespace Comments */
<commit_msg>Follow Markdown guidelines for italic and bold text.<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2013 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the
** following disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
#include "VComment.h"
#include "VCommentBrowser.h"
#include "VCommentImage.h"
#include "VisualizationBase/src/items/Line.h"
#include "VisualizationBase/src/items/ItemStyle.h"
#include "VisualizationBase/src/items/Text.h"
#include "VisualizationBase/src/declarative/DeclarativeItemDef.h"
using namespace Visualization;
namespace Comments {
ITEM_COMMON_DEFINITIONS(VComment, "item")
VComment::VComment(Item* parent, NodeType* node) : Super(parent, node, itemStyles().get())
{
// import existing diagrams
for(auto diagram : *node->diagrams())
{
diagrams_[diagram->name()] = diagram;
}
editing_ = node->lines()->size() == 0 || (node->lines()->size() == 1 && node->lines()->at(0)->get().isEmpty());
parseLines();
}
// split up user-provided text into single elements
void VComment::parseLines()
{
clearChildren();
bool isHTML = false;
QSet<QString> diagramNames{};
int listCount = -1;
for(auto nodeLine : *node()->lines())
{
QRegExp rx("^={3,}|-{3,}|\\.{3,}$");
QString line = nodeLine->get();
// is this a new enumeration item?
if(line.left(3) == " * ")
{
listCount++;
// does this create a new list?
if(listCount == 0)
{
pushTextLine("<ol><li>");
line = line.mid(3);
}
// otherwise, just add another list item
else
{
pushTextLine("</li><li>");
line = line.mid(3);
}
}
// or is this extending an existing list?
else if(line.left(3) == " " && listCount > -1)
{
line = line.mid(3);
}
// if this is not an enumeration item, reset listCount
else if(listCount > -1 && line.left(3) != " * " && line.left(3) != " ")
{
pushTextLine("</li></ol>");
listCount = -1;
}
// is this HTML?
if(line == "<html>")
{
popLineBuffer();
isHTML = true;
continue;
}
else if(isHTML)
{
if(line == "</html>")
{
isHTML = false;
popLineBuffer(true);
}
else
{
pushTextLine(line);
}
// don't process further
continue;
}
if(rx.exactMatch(line))
{
// A line consists of one of . - = that is repeated three times or more
// The used character defines the strength of the header, i.e. one of three levels
QString style;
switch(line[0].toAscii())
{
default:
case '.': style = "single"; break;
case '-': style = "double"; break;
case '=': style = "triple"; break;
}
addChildItem(new Line(this, Line::itemStyles().get(style)));
continue;
}
// is this a header? replace it right away with the appropriate tag
rx.setPattern("^(#+)([^#].*)");
// allow headers h1 to h6
if(rx.exactMatch(line) && rx.cap(1).length() <= 6)
{
QString len = QString::number(rx.cap(1).length());
pushTextLine("<h" + len + ">" + rx.cap(2).simplified() + "</h" + len + ">");
}
// is this a diagram? format: [diagram#diagramName]
else if(line.left(9) == "[diagram#" && line.right(1) == "]" && line.size() > 9+1)
{
QString diagramName = line.mid(9,line.size()-9-1);
diagramNames << diagramName;
CommentDiagram* diagram = diagrams_.value(diagramName, nullptr);
if(diagram == nullptr)
{
diagram = new CommentDiagram(nullptr, diagramName);
diagrams_[diagramName] = diagram;
}
auto item = renderer()->render(this, diagram);
addChildItem(item);
}
// urls are specified as [browser#http://www.google.com]
else if(line.left(9) == "[browser#" && line.right(1) == "]" && line.size() > 9+1)
{
QString mid = line.mid(9, line.size()-9-1);
// read width and height, if specified
auto items = parseMarkdownArguments(mid);
QString url = items->at(0).second;
auto browser = new VCommentBrowser(this, QUrl(url));
if(items->size() > 1)
{
QSize size = parseSize(items->at(1).second);
browser->updateSize(size);
}
addChildItem(browser);
delete items;
}
// images are specified as
// [image#/home/user/image.png]
// [image#image.png|300x300] to specify a size
else if(line.left(7) == "[image#" && line.right(1) == "]" && line.size() > 7+1)
{
QString mid = line.mid(7, line.size()-7-1);
// read width and height, if specified
auto items = parseMarkdownArguments(mid);
QString path = items->at(0).second;
QSize size(0,0);
if(items->size() > 1)
size = parseSize(items->at(1).second);
addChildItem(new VCommentImage(this, items->at(0).second, size));
delete items;
}
else
{
pushTextLine(line);
}
}
popLineBuffer();
synchroniseDiagrams(diagramNames);
}
void VComment::synchroniseDiagrams(QSet<QString> itemDiagramNames)
{
// get all diagrams from the node
auto nodeDiagrams = node()->diagrams();
// gather all names from the node diagrams for easier comparison
QSet<QString> nodeDiagramNames{};
for(auto diagram : *nodeDiagrams)
nodeDiagramNames << diagram->name();
// get intersection of two sets
QSet<QString> intersection(itemDiagramNames);
intersection.intersect(nodeDiagramNames);
// new diagrams were already constructed inside of parseLines(),
// they also need to be added to the model now
auto newDiagramNames = itemDiagramNames - intersection;
if(newDiagramNames.size() > 0)
{
node()->model()->beginModification(node(), "Adding new diagrams");
for(auto diagramName : newDiagramNames)
{
auto diagram = diagrams_.value(diagramName);
node()->diagrams()->append(diagram);
}
node()->model()->endModification();
}
// diagrams that are no longer referenced need to be removed from the model
auto oldDiagramNames = nodeDiagramNames - intersection;
if(oldDiagramNames.size() > 0)
{
node()->model()->beginModification(node(), "Removing unreferenced diagrams");
for(auto diagramName : oldDiagramNames)
{
auto diagram = diagrams_.value(diagramName);
node()->diagrams()->remove(diagram);
diagrams_.remove(diagramName);
}
node()->model()->endModification();
}
}
QMap<QString, CommentDiagram*> VComment::diagrams() const
{
return diagrams_;
}
QSize VComment::parseSize(const QString& str)
{
int index = str.indexOf('x');
bool ok{};
int width = str.left(index).toInt(&ok);
if(index > 0 && !ok)
qDebug() << "Invalid width specified in size string:" << str;
int height = str.mid(index+1).toInt(&ok);
if(index+1 < str.size()-1 && !ok)
qDebug() << "Invalid height specified in size string:" << str;
return QSize(width, height);
}
QVector<QPair<QString,QString>>* VComment::parseMarkdownArguments(const QString& argString)
{
// split string on all pipes
auto lines = argString.split('|');
// TODO: get rid of escaped pipes \| e.g. in case an url contains one
auto pairs = new QVector<QPair<QString,QString>>();
// read key/value pairs
QRegExp rx("^[a-zA-Z]{,15}=");
for(auto line : lines)
{
int index = rx.indexIn(line);
if(index == -1)
pairs->push_back(qMakePair(QString(), line));
else
pairs->push_back(qMakePair(line.left(index), line.mid(index+1)));
}
return pairs;
}
QString VComment::replaceMarkdown(QString str)
{
QRegExp rx;
rx.setPattern("\\*\\*([^\\*]+)\\*\\*");
str.replace(rx, "<b>\\1</b>");
rx.setPattern("\\*([^\\*]+)\\*");
str.replace(rx, "<i>\\1</i>");
return str;
}
void VComment::pushTextLine(QString text)
{
lineBuffer_.push_back(text);
}
void VComment::popLineBuffer(bool asHtml)
{
if(lineBuffer_.size() > 0)
{
auto joined = lineBuffer_.join("\n");
if(asHtml)
{
auto browser = new VCommentBrowser(this, joined);
children_.push_back(browser);
}
else
{
auto text = new Text(this, Text::itemStyles().get("comment"), replaceMarkdown(joined));
text->setTextFormat(Qt::RichText);
children_.push_back(text);
}
lineBuffer_.clear();
}
}
void VComment::addChildItem(Visualization::Item* item)
{
popLineBuffer();
children_.push_back(item);
}
void VComment::toggleEditing()
{
if(node()->lines()->size() == 0)
editing_ = true;
else
editing_ = !editing_;
if(!editing_)
parseLines();
setUpdateNeeded(StandardUpdate);
}
bool VComment::editing() const
{
return editing_;
}
void VComment::initializeForms()
{
addForm((new SequentialLayoutFormElement())
->setVertical()
->setListOfItems([](Item* i) {
auto vc = static_cast<VComment*>(i);
return vc->children_;
}
));
addForm(item(&I::editLabel_, [](I* v){
return v->node()->lines();
}));
}
int VComment::determineForm()
{
return editing_ ? 1 : 0;
}
} /* namespace Comments */
<|endoftext|> |
<commit_before>/*
* AddTask macro for class
* Redmer Alexander Bertens, [email protected]
* Utrecht University, Utrecht, Netherlands
*
* Note: this macro is pretty much a copy of AddTaskEmcalJetSample.C
*
*/
AliAnalysisTaskRhoVnModulation* AddTaskRhoVnModulation(
const char *ntracks = "Tracks",
const char *nclusters = "",
const char *njets = "Jets",
const char *nrho = "Rho",
Double_t jetradius = 0.2,
Double_t jetptcut = 1,
Double_t jetareacut = 0.557,
const char* type = "TPC",
Int_t leadhadtype = 0,
const char *taskname = "AliAnalysisTaskRhoVnModulation",
UInt_t runMode = AliAnalysisTaskRhoVnModulation::kGrid,
Bool_t fillQA = kTRUE,
TString fitOpts = "WLQI",
UInt_t fitType = AliAnalysisTaskRhoVnModulation::kFourierSeries,
TArrayI *centralities = 0x0,
TRandom3 *randomizer = 0x0,
Double_t trackptcut = .15
)
{
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskEmcalJetSample", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskEmcalJetSample", "This task requires an input event handler");
return NULL;
}
//-------------------------------------------------------
// Init the task and do settings
//-------------------------------------------------------
TString name(taskname);
if (strcmp(njets,"")) {
name += "_";
name += njets;
}
if (strcmp(nrho,"")) {
name += "_";
name += nrho;
}
if (!strcmp(type, "TPC"))
name += "_TPC";
else if (!strcmp(type, "EMCAL"))
name += "_EMCAL";
else if (!strcmp(type, "USER"))
name += "_USER";
AliAnalysisTaskRhoVnModulation* jetTask = new AliAnalysisTaskRhoVnModulation(name, runMode);
// inherited setters
AliParticleContainer* partCont = jetTask->AddParticleContainer(ntracks);
if(partCont) {
partCont->SetName("Tracks");
partCont->SetParticlePtCut(trackptcut);
}
AliJetContainer* jetCont = jetTask->AddJetContainer(njets, type, jetradius);
if(jetCont) {
jetCont->SetName("Jets");
jetCont->SetPercAreaCut(jetareacut);
jetCont->SetRhoName(nrho);
jetCont->ConnectParticleContainer(partCont);
}
// task specific setters
jetTask->SetFillQAHistograms(fillQA);
jetTask->SetDebugMode(-1);
jetTask->SetModulationFitType(fitType);
jetTask->SetModulationFitOptions(fitOpts);
jetTask->SetModulationFitMinMaxP(.001, 1);
jetTask->SetRandomConeRadius(jetradius);
// if centralities haven't been specified use defaults
if(!centralities) {
Int_t c[] = {0, 10, 30, 50, 70, 90};
jetTask->SetCentralityClasses(new TArrayI(sizeof(c)/sizeof(c[0]), c));
}
// if a randomized hasn't specified use a safe default
if(!randomizer) jetTask->SetRandomSeed(new TRandom3(0));
//-------------------------------------------------------
// Final settings, pass to manager and set the containers
//-------------------------------------------------------
mgr->AddTask(jetTask);
// Create containers for input/output
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer() ;
TString contname(name);
contname+="_PWGJE";
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contname.Data(),
TList::Class(),AliAnalysisManager::kOutputContainer,
Form("%s", AliAnalysisManager::GetCommonFileName()));
mgr->ConnectInput (jetTask, 0, cinput1 );
mgr->ConnectOutput (jetTask, 1, coutput1 );
switch (runMode) {
case AliAnalysisTaskRhoVnModulation::kLocal : {
gStyle->SetOptFit(1);
AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(Form("good_fits_%s", name.Data()),
TList::Class(),AliAnalysisManager::kOutputContainer,
Form("%s", AliAnalysisManager::GetCommonFileName()));
AliAnalysisDataContainer *coutput3 = mgr->CreateContainer(Form("bad_fits_%s", name.Data()),
TList::Class(),AliAnalysisManager::kOutputContainer,
Form("%s", AliAnalysisManager::GetCommonFileName()));
mgr->ConnectOutput (jetTask, 2, coutput2);
mgr->ConnectOutput (jetTask, 3, coutput3);
} break;
default: break;
}
return jetTask;
}
<commit_msg> bugfix add task (changed int into double in task but forgot to update addtask)<commit_after>/*
* AddTask macro for class
* Redmer Alexander Bertens, [email protected]
* Utrecht University, Utrecht, Netherlands
*
* Note: this macro is pretty much a copy of AddTaskEmcalJetSample.C
*
*/
AliAnalysisTaskRhoVnModulation* AddTaskRhoVnModulation(
const char *ntracks = "Tracks",
const char *nclusters = "",
const char *njets = "Jets",
const char *nrho = "Rho",
Double_t jetradius = 0.2,
Double_t jetptcut = 1,
Double_t jetareacut = 0.557,
const char* type = "TPC",
Int_t leadhadtype = 0,
const char *taskname = "AliAnalysisTaskRhoVnModulation",
UInt_t runMode = AliAnalysisTaskRhoVnModulation::kGrid,
Bool_t fillQA = kTRUE,
TString fitOpts = "WLQI",
UInt_t fitType = AliAnalysisTaskRhoVnModulation::kFourierSeries,
TArrayD *centralities = 0x0,
TRandom3 *randomizer = 0x0,
Double_t trackptcut = .15
)
{
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskEmcalJetSample", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskEmcalJetSample", "This task requires an input event handler");
return NULL;
}
//-------------------------------------------------------
// Init the task and do settings
//-------------------------------------------------------
TString name(taskname);
if (strcmp(njets,"")) {
name += "_";
name += njets;
}
if (strcmp(nrho,"")) {
name += "_";
name += nrho;
}
if (!strcmp(type, "TPC"))
name += "_TPC";
else if (!strcmp(type, "EMCAL"))
name += "_EMCAL";
else if (!strcmp(type, "USER"))
name += "_USER";
AliAnalysisTaskRhoVnModulation* jetTask = new AliAnalysisTaskRhoVnModulation(name, runMode);
// inherited setters
AliParticleContainer* partCont = jetTask->AddParticleContainer(ntracks);
if(partCont) {
partCont->SetName("Tracks");
partCont->SetParticlePtCut(trackptcut);
}
AliJetContainer* jetCont = jetTask->AddJetContainer(njets, type, jetradius);
if(jetCont) {
jetCont->SetName("Jets");
jetCont->SetPercAreaCut(jetareacut);
jetCont->SetRhoName(nrho);
jetCont->ConnectParticleContainer(partCont);
}
// task specific setters
jetTask->SetFillQAHistograms(fillQA);
jetTask->SetDebugMode(-1);
jetTask->SetModulationFitType(fitType);
jetTask->SetModulationFitOptions(fitOpts);
jetTask->SetModulationFitMinMaxP(.001, 1);
jetTask->SetRandomConeRadius(jetradius);
// if centralities haven't been specified use defaults
if(!centralities) {
Double_t c[] = {0., 10., 30., 50., 70., 90.};
jetTask->SetCentralityClasses(new TArrayD(sizeof(c)/sizeof(c[0]), c));
}
// if a randomized hasn't specified use a safe default
if(!randomizer) jetTask->SetRandomSeed(new TRandom3(0));
//-------------------------------------------------------
// Final settings, pass to manager and set the containers
//-------------------------------------------------------
mgr->AddTask(jetTask);
// Create containers for input/output
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer() ;
TString contname(name);
contname+="_PWGJE";
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contname.Data(),
TList::Class(),AliAnalysisManager::kOutputContainer,
Form("%s", AliAnalysisManager::GetCommonFileName()));
mgr->ConnectInput (jetTask, 0, cinput1 );
mgr->ConnectOutput (jetTask, 1, coutput1 );
switch (runMode) {
case AliAnalysisTaskRhoVnModulation::kLocal : {
gStyle->SetOptFit(1);
AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(Form("good_fits_%s", name.Data()),
TList::Class(),AliAnalysisManager::kOutputContainer,
Form("%s", AliAnalysisManager::GetCommonFileName()));
AliAnalysisDataContainer *coutput3 = mgr->CreateContainer(Form("bad_fits_%s", name.Data()),
TList::Class(),AliAnalysisManager::kOutputContainer,
Form("%s", AliAnalysisManager::GetCommonFileName()));
mgr->ConnectOutput (jetTask, 2, coutput2);
mgr->ConnectOutput (jetTask, 3, coutput3);
} break;
default: break;
}
return jetTask;
}
<|endoftext|> |
<commit_before>#include <Halide.h>
#include <stdio.h>
#include <stdlib.h>
#include <functional>
using namespace Halide;
int test_per_channel_select() {
Func gpu("gpu"), cpu("cpu");
Var x("x"), y("y"), c("c");
gpu(x, y, c) = cast<uint8_t>(select(c == 0, 128,
c == 1, x,
c == 2, y,
x*y));
gpu.bound(c, 0, 4);
gpu.glsl(x, y, c);
gpu.compute_root();
cpu(x, y, c) = gpu(x, y, c);
Image<uint8_t> out(10, 10, 4);
cpu.realize(out);
// Verify the result
for (int y=0; y!=out.height(); ++y) {
for (int x=0; x!=out.width(); ++x) {
for (int c=0; c!=out.channels(); ++c) {
uint8_t expected;
switch (c) {
case 0: expected = 128; break;
case 1: expected = x; break;
case 2: expected = y; break;
default: expected = x*y; break;
}
uint8_t actual = out(x,y,c);
if (expected != actual) {
fprintf(stderr, "Incorrect pixel (%d, %d, %d, %d) at x=%d y=%d.\n",
out(x, y, 0), out(x, y, 1), out(x, y, 2), out(x, y, 3),
x, y);
return 1;
}
}
}
}
return 0;
}
int test_flag_scalar_select() {
Func gpu("gpu"), cpu("cpu");
Var x("x"), y("y"), c("c");
int flag_value = 0;
Param<int> flag("flag");
flag.set(flag_value);
gpu(x, y, c) = cast<uint8_t>(select(flag != 0, 128,
255));
gpu.bound(c, 0, 4);
gpu.glsl(x, y, c);
gpu.compute_root();
// This should trigger a copy_to_host operation
cpu(x, y, c) = gpu(x, y, c);
Image<uint8_t> out(10, 10, 4);
cpu.realize(out);
// Verify the result
for (int y=0; y!=out.height(); ++y) {
for (int x=0; x!=out.width(); ++x) {
for (int c=0; c!=out.channels(); ++c) {
uint8_t expected = !flag_value ? 255 : 128;
uint8_t actual = out(x,y,c);
if (expected != actual) {
fprintf(stderr, "Incorrect pixel (%d, %d, %d, %d) at x=%d y=%d.\n",
out(x, y, 0), out(x, y, 1), out(x, y, 2), out(x, y, 3),
x, y);
return 1;
}
}
}
}
return 0;
}
int test_flag_pixel_select() {
Func gpu("gpu"), cpu("cpu");
Var x("x"), y("y"), c("c");
int flag_value = 0;
Param<int> flag("flag");
flag.set(flag_value);
Image<uint8_t> image(10, 10, 4);
for (int y=0; y<image.height(); y++) {
for (int x=0; x<image.width(); x++) {
for (int c=0; c<image.channels(); c++) {
image(x, y, c) = 128;
}
}
}
gpu(x, y, c) = cast<uint8_t>(select(flag != 0, image(x,y,c),
255));
gpu.bound(c, 0, 4);
gpu.glsl(x, y, c);
gpu.compute_root();
// This should trigger a copy_to_host operation
cpu(x, y, c) = gpu(x, y, c);
Image<uint8_t> out(10, 10, 4);
cpu.realize(out);
// Verify the result
for (int y=0; y!=out.height(); ++y) {
for (int x=0; x!=out.width(); ++x) {
for (int c=0; c!=out.channels(); ++c) {
uint8_t expected = !flag_value ? 255 : 128;
uint8_t actual = out(x,y,c);
if (expected != actual) {
fprintf(stderr, "Incorrect pixel (%d, %d, %d, %d) at x=%d y=%d.\n",
out(x, y, 0), out(x, y, 1), out(x, y, 2), out(x, y, 3),
x, y);
return 1;
}
}
}
}
return 0;
}
int main() {
// This test must be run with an OpenGL target
const Target &target = get_jit_target_from_environment();
if (!target.has_feature(Target::OpenGL)) {
fprintf(stderr,"ERROR: This test must be run with an OpenGL target, e.g. by setting HL_JIT_TARGET=host-opengl.\n");
return 1;
}
int err = 0;
err |= test_per_channel_select();
err |= test_flag_scalar_select();
err |= test_flag_pixel_select();
if (err) {
printf("FAILED\n");
return 1;
}
printf("Success!\n");
return 0;
}
<commit_msg>Removed unnecessary include<commit_after>#include <Halide.h>
#include <stdio.h>
#include <stdlib.h>
using namespace Halide;
int test_per_channel_select() {
Func gpu("gpu"), cpu("cpu");
Var x("x"), y("y"), c("c");
gpu(x, y, c) = cast<uint8_t>(select(c == 0, 128,
c == 1, x,
c == 2, y,
x*y));
gpu.bound(c, 0, 4);
gpu.glsl(x, y, c);
gpu.compute_root();
cpu(x, y, c) = gpu(x, y, c);
Image<uint8_t> out(10, 10, 4);
cpu.realize(out);
// Verify the result
for (int y=0; y!=out.height(); ++y) {
for (int x=0; x!=out.width(); ++x) {
for (int c=0; c!=out.channels(); ++c) {
uint8_t expected;
switch (c) {
case 0: expected = 128; break;
case 1: expected = x; break;
case 2: expected = y; break;
default: expected = x*y; break;
}
uint8_t actual = out(x,y,c);
if (expected != actual) {
fprintf(stderr, "Incorrect pixel (%d, %d, %d, %d) at x=%d y=%d.\n",
out(x, y, 0), out(x, y, 1), out(x, y, 2), out(x, y, 3),
x, y);
return 1;
}
}
}
}
return 0;
}
int test_flag_scalar_select() {
Func gpu("gpu"), cpu("cpu");
Var x("x"), y("y"), c("c");
int flag_value = 0;
Param<int> flag("flag");
flag.set(flag_value);
gpu(x, y, c) = cast<uint8_t>(select(flag != 0, 128,
255));
gpu.bound(c, 0, 4);
gpu.glsl(x, y, c);
gpu.compute_root();
// This should trigger a copy_to_host operation
cpu(x, y, c) = gpu(x, y, c);
Image<uint8_t> out(10, 10, 4);
cpu.realize(out);
// Verify the result
for (int y=0; y!=out.height(); ++y) {
for (int x=0; x!=out.width(); ++x) {
for (int c=0; c!=out.channels(); ++c) {
uint8_t expected = !flag_value ? 255 : 128;
uint8_t actual = out(x,y,c);
if (expected != actual) {
fprintf(stderr, "Incorrect pixel (%d, %d, %d, %d) at x=%d y=%d.\n",
out(x, y, 0), out(x, y, 1), out(x, y, 2), out(x, y, 3),
x, y);
return 1;
}
}
}
}
return 0;
}
int test_flag_pixel_select() {
Func gpu("gpu"), cpu("cpu");
Var x("x"), y("y"), c("c");
int flag_value = 0;
Param<int> flag("flag");
flag.set(flag_value);
Image<uint8_t> image(10, 10, 4);
for (int y=0; y<image.height(); y++) {
for (int x=0; x<image.width(); x++) {
for (int c=0; c<image.channels(); c++) {
image(x, y, c) = 128;
}
}
}
gpu(x, y, c) = cast<uint8_t>(select(flag != 0, image(x,y,c),
255));
gpu.bound(c, 0, 4);
gpu.glsl(x, y, c);
gpu.compute_root();
// This should trigger a copy_to_host operation
cpu(x, y, c) = gpu(x, y, c);
Image<uint8_t> out(10, 10, 4);
cpu.realize(out);
// Verify the result
for (int y=0; y!=out.height(); ++y) {
for (int x=0; x!=out.width(); ++x) {
for (int c=0; c!=out.channels(); ++c) {
uint8_t expected = !flag_value ? 255 : 128;
uint8_t actual = out(x,y,c);
if (expected != actual) {
fprintf(stderr, "Incorrect pixel (%d, %d, %d, %d) at x=%d y=%d.\n",
out(x, y, 0), out(x, y, 1), out(x, y, 2), out(x, y, 3),
x, y);
return 1;
}
}
}
}
return 0;
}
int main() {
// This test must be run with an OpenGL target
const Target &target = get_jit_target_from_environment();
if (!target.has_feature(Target::OpenGL)) {
fprintf(stderr,"ERROR: This test must be run with an OpenGL target, e.g. by setting HL_JIT_TARGET=host-opengl.\n");
return 1;
}
int err = 0;
err |= test_per_channel_select();
err |= test_flag_scalar_select();
err |= test_flag_pixel_select();
if (err) {
printf("FAILED\n");
return 1;
}
printf("Success!\n");
return 0;
}
<|endoftext|> |
<commit_before>#ifndef QUEUES_H_INCLUDED
#define QUEUES_H_INCLUDED
#include <wiz/global.h>
#include <wiz/wizardError.h>
#include <wiz/newarrays.h>
/// #define QUEUES_DEBUG
namespace wiz{
class QueueEmptyError : public wiz::Error
{
public:
QueueEmptyError() : wiz::Error( "queueEmptyError" )
{
}
};
class QueueFullError : public wiz::Error
{
public:
QueueFullError() : wiz::Error( "queueFullError" )
{
}
};
// check array Queue, array stack?
template <typename T>
class Queue //: public wizObject
{
private:
class Element
{
public:
Element* next;
T data;
public:
explicit Element( const T d = T() )
{
data = d;
next = nullptr;
}
};
private:
Element* Head; //
Element* Rear; //
public:
explicit Queue() : Head( nullptr ), Rear( nullptr ) { Head = new Element(); Rear = Head; }
virtual ~Queue(){
clear();
delete Head; Head = Rear = nullptr;
}
void clear()
{
while( !isEmpty() ){
deleteq();
}
}
bool isEmpty() const
{
return nullptr == Head->next; /// size == 0, empty..
}
bool empty() const { return isEmpty(); }
//
void addq( const T& p ) /// push
{
Element* temp = new Element(p); //
//
Rear->next = temp;//
temp->next = nullptr;// auto look def of Element
Rear = Rear->next; //
}//
void push( const T& p ) { addq( p ); }
T deleteq(){ /// pop
if( isEmpty() )
{
throw QueueEmptyError();
}
//
Element* temp = Head->next;//
Head->next = temp->next;
//Rear 처리
if( nullptr == Head->next )
Rear = Head;
T returnTemp = temp->data;
delete temp;
return returnTemp;
}
T pop() { return deleteq(); }
Queue& operator<<( const T& p ){
addq( p ); //
return *this;
}
private:
void copy( const Queue<T>& q )
{
//this->clear();
Element* qTemp = q.Head->next;
while( qTemp != nullptr )
{
addq( qTemp->data );
qTemp = qTemp->next;
}
}
public:
//
Queue( const Queue<T>& q ) : Head( nullptr ), Rear( nullptr )
{// clear();
Head = new Element(); Rear = Head;
copy( q );
}
Queue& operator=( const Queue<T>& q )
{
if( Head == q.Head ) { return *this; }
clear();
// head, rear reser..!!
copy( q );
return *this;
}
Queue( Queue<T>&& q )
{
Head->next = q.Head->next;
Rear = q.Rear;
/// do-empty..
q.Head->next = nullptr;
q.Rear = q.Head;
}
Queue<T>& operator=( Queue<T>&& q )
{
if( Head == q.Head ) { return *this; }
this->clear();
Head->next = q.Head->next;
Rear = q.Rear;
q.Head->next = nullptr;
q.Rear = q.Head;
return *this;
}
};
// Queue using Array
template <class T>
class ArrayQueue
{
public:
ArrayQueue(const ArrayQueue<T>& aq)
:que(aq.que), start(aq.start), num(aq.num)
{
//
}
ArrayQueue(ArrayQueue<T>&& aq)
{
que = std::move(aq.que);
start = aq.start;
num = aq.num;
aq.que = Array<T>(2);
aq.start = 0;
aq.num = 0;
}
ArrayQueue<T>& operator=(ArrayQueue<T>&& aq)
{
if (que == aq.que) { return *this; }
this->que.DoEmpty();
que = std::move(aq.que);
start = aq.start;
num = aq.num;
aq.que = Array<T>(2);
aq.start = 0;
aq.num = 0;
return *this;
}
ArrayQueue<T>& operator=(const ArrayQueue<T>& aq)
{
if (que == aq.que) { return *this; }
que.DoEmpty();
this->que = aq.que;
this->start = aq.start;
this->num = aq.num;
return *this;
}
private:
Array<T> que;
int start;
int num;
public:
explicit ArrayQueue(const int max = 2) : start(0), num(0)
{
#ifdef QUEUES_DEBUG
// max > 0
wiz::checkUnderError(0, max, 1);
#endif
que = Array<T>(max);
}
virtual ~ArrayQueue()
{
}
public:
const T& operator[](const int idx) const
{
return que[(start + idx) & (que.size() - 1)];
}
T& operator[](const int idx)
{
return que[(start + idx) & (que.size() - 1)];
}
public:
void push(const ArrayQueue<T>& val) {
if (val.empty()) { return; }
int newSize = this->que.size();
while (newSize - num < val.size()) {
newSize = newSize * 2;
}
if (newSize != this->que.size()) {
// expand array queue.
ArrayQueue<T> temp(newSize);
temp.start = 0;
//
for (int i = 0; i < this->size(); ++i) {
temp[i] = std::move((*this)[i]);
}
const int iend = val.num;
for (int i = 0; i < iend; ++i) {
temp[i + this->num] = val[i];
}
temp.num = this->num + val.num;
*this = std::move(temp);
}
else {
for (int i = 0; i < val.size(); ++i) {
this->push(val.que[i]);
}
}
}
void push(ArrayQueue<T>&& val) { // chk..
if (val.empty()) { return; }
int newSize = this->que.size();
while (newSize - num < val.size()) {
newSize = newSize * 2;
}
if (newSize != this->que.size()) {
// expand array queue.
ArrayQueue temp(newSize);
temp.start = 0;
//
for (int i = 0; i < this->size(); ++i) {
temp[i] = std::move((*this)[i]);
}
const int iend = val.num;
for (int i = 0; i < iend; ++i) {
temp[i + this->num] = std::move(val[i]);
}
temp.num = this->num + val.num;
*this = std::move(temp);
}
else {
for (int i = 0; i < val.size(); ++i) {
this->push(std::move(val[i]));
}
}
}
void push( const T& val )
{
if( isFull() )
{
// expand array queue.
ArrayQueue temp( que.size() * 2 );
//
for (int i = 0; i < que.size(); ++i) {
temp[i] = std::move(que[(start + i) & (que.size()-1)]);
}
temp.start = 0;
temp.num = que.size();
*this = std::move( temp );
}
que[(start+num) & (que.size()-1)] = val;
num++;
}
void push(T&& val)
{
if (isFull())
{
// expand array queue.
ArrayQueue temp(que.size() * 2);
//
for (int i = 0; i < que.size(); ++i) {
temp[i] = std::move(que[(start + i) & (que.size()-1)]);
}
temp.start = 0;
temp.num = que.size();
*this = std::move(temp);
}
que[(start + num) & (que.size()-1)] = std::move(val);
num++;
}
void pop(T* t = nullptr) {
if (isEmpty()) { throw QueueEmptyError(); }
T temp = std::move(que[start]);
//que[start] = T();
start = (start + 1) & (que.size() - 1); // % que.size(), 2^n.
num--;
if (nullptr != t) {
*t = move(temp);
}
}
T pop_back()
{
if (isEmpty()) { throw QueueEmptyError(); }
T temp = std::move((*this)[num - 1]);
//(*this)[num - 1] = T();
num--;
return temp;
}
bool isFull()const
{
return num >= ( que.size() );
}
bool isEmpty()const
{
return 0 == num;
}
int size()const{ return num; }
bool empty()const { return isEmpty(); }
int getNumMax()const { return que.size(); }
int getNum()const { return num; }
Array<T> toArray()const
{
Array<T> temp;
if( num > 0 )
{
temp = Array<T>( num );
int count=0;
for( int i=0; i < num; i++ )
{
temp[i] = que[ ( start + i ) % (que.size()) ];
}
}
return temp;
}
ArrayQueue<T>& operator<<( const T& data )
{
push( data );
return *this;
}
};
}
#endif // QUEUES_H_INCLUDED
<commit_msg>Delete QUEUES.H<commit_after><|endoftext|> |
<commit_before>// @(#)root/utils:$Name: $:$Id: rlibmap.cxx,v 1.12 2004/05/17 17:40:00 rdm Exp $
// Author: Fons Rademakers 05/12/2003
/*************************************************************************
* Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
// This program generates a map between class name and shared library.
// Its output is in TEnv format.
// Usage: rlibmap [-f] [-o <mapfile>] -l <sofile> -d <depsofiles>
// -c <linkdeffiles>
// -f: output full library path name (not needed when ROOT library
// search path is used)
// -o: write output to specified file, otherwise to stdout
// -r: replace existing entries in the specified file
// -l: library containing the classes in the specified linkdef files
// -d: libraries on which the -l library depends
// -c: linkdef files containing the list of classes defined in the -l library
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string>
#include <vector>
#ifndef WIN32
# include <unistd.h>
#else
# define ssize_t int
# include <io.h>
# include <sys/types.h>
#endif
#ifdef __APPLE__
#include <AvailabilityMacros.h>
#endif
#if (defined(__FreeBSD__) && (__FreeBSD__ < 4)) || \
(defined(__APPLE__) && (!defined(MAC_OS_X_VERSION_10_3) || \
(MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_3)))
#include <sys/file.h>
#define lockf(fd, op, sz) flock((fd), (op))
#ifndef F_LOCK
#define F_LOCK (LOCK_EX | LOCK_NB)
#endif
#ifndef F_ULOCK
#define F_ULOCK LOCK_UN
#endif
#endif
#if defined(__CYGWIN__) && defined(__GNUC__)
#define F_LOCK F_WRLCK
#define F_ULOCK F_UNLCK
static int fcntl_lockf(int fd, int op, off_t off)
{
flock fl;
fl.l_whence = SEEK_SET;
fl.l_start = off;
fl.l_len = 0; // whole file
fl.l_pid = getpid();
fl.l_type = op;
return fcntl(fd, F_SETLK, &fl);
}
#define lockf fcntl_lockf
#endif
const char *usage = "Usage: %s [-f] [<-r|-o> <mapfile>] -l <sofile> -d <depsofiles> -c <linkdeffiles>\n";
namespace std {}
using namespace std;
#ifdef WIN32
#include <windows.h>
#define ftruncate(fd, size) win32_ftruncate(fd, size)
//______________________________________________________________________________
int win32_ftruncate(int fd, ssize_t size)
{
HANDLE hfile;
int curpos;
if (fd < 0) return -1;
hfile = (HANDLE) _get_osfhandle(fd);
curpos = ::SetFilePointer(hfile, 0, 0, FILE_CURRENT);
if (curpos == 0xFFFFFFFF ||
::SetFilePointer(hfile, size, 0, FILE_BEGIN) == 0xFFFFFFFF ||
!::SetEndOfFile(hfile)) {
int error = ::GetLastError();
switch (error) {
case ERROR_INVALID_HANDLE:
errno = EBADF;
break;
default:
errno = EIO;
break;
}
return -1;
}
return 0;
}
#endif // WIN32
//______________________________________________________________________________
char *Compress(const char *str)
{
// Remove all blanks from the string str. The returned string has to be
// deleted by the user.
if (!str) return 0;
const char *p = str;
// allocate 20 extra characters in case of eg, vector<vector<T>>
char *s, *s1 = new char[strlen(str)+20];
s = s1;
while (*p) {
if (*p != ' ')
*s++ = *p;
p++;
}
*s = '\0';
return s1;
}
//______________________________________________________________________________
int RemoveLib(const string &solib, bool fullpath, FILE *fp)
{
// Remove entries from the map file for the specified solib.
fseek(fp, 0, SEEK_SET);
// get file size
struct stat sbuf;
fstat(fileno(fp), &sbuf);
size_t siz = sbuf.st_size;
if (!siz) return 0;
const char *libbase = solib.c_str();
if (!fullpath) {
if ((libbase = strrchr(libbase, '/')))
libbase++;
}
// read file and remove lines matching specified libs
char *fbuf = new char[siz+1];
char *fptr = fbuf;
while (fgets(fptr, siz - size_t(fptr-fbuf), fp)) {
char *line = new char[strlen(fptr)+1];
strcpy(line, fptr);
strtok(line, " ");
char *lib = strtok(0, " \n");
if (lib && strcmp(lib, libbase)) {
fptr += strlen(fptr);
if (*(fptr-1) != '\n') {
*fptr = '\n';
fptr++;
}
}
delete [] line;
// fgets() should return 0 in this case but doesn't
if (siz - size_t(fptr - fbuf) <= 0)
break;
}
ftruncate(fileno(fp), 0);
// write remaining lines back
if (fptr != fbuf) {
fseek(fp, 0, SEEK_SET);
fwrite(fbuf, 1, size_t(fptr-fbuf), fp);
}
delete [] fbuf;
fseek(fp, 0, SEEK_END);
return 0;
}
//______________________________________________________________________________
int LibMap(const string &solib, const vector<string> &solibdeps,
const vector<string> &linkdefs, bool fullpath, FILE *fp)
{
// Write libmap. Returns -1 in case of error.
vector<string> classes;
vector<string>::const_iterator lk;
for (lk = linkdefs.begin(); lk != linkdefs.end(); lk++) {
const char *linkdef = lk->c_str();
FILE *lfp;
char pragma[1024];
if ((lfp = fopen(linkdef, "r"))) {
while (fgets(pragma, 1024, lfp)) {
if (!strcmp(strtok(pragma, " "), "#pragma") &&
!strcmp(strtok(0, " "), "link") &&
!strcmp(strtok(0, " "), "C++") &&
!strcmp(strtok(0, " "), "class")) {
char *cls = strtok(0, "-!+;");
// just in case remove trailing space and tab
while (*cls == ' ') cls++;
int len = strlen(cls) - 1;
while (cls[len] == ' ' || cls[len] == '\t')
cls[len--] = '\0';
//no space between tmpl arguments allowed
cls = Compress(cls);
// don't include "vector<string>" and "std::pair<" classes
if (!strncmp(cls, "vector<string>", 14) ||
!strncmp(cls, "std::pair<", 10))
continue;
// replace "::" by "@@" since TEnv uses ":" as delimeter
char *s = cls;
while (*s) {
if (*s == ':') *s = '@';
s++;
}
classes.push_back(cls);
}
}
fclose(lfp);
} else {
fprintf(stderr, "cannot open linkdef file %s\n", linkdef);
}
}
const char *libbase = solib.c_str();
if (!fullpath) {
if ((libbase = strrchr(libbase, '/')))
libbase++;
}
vector<string>::const_iterator it;
for (it = classes.begin(); it != classes.end(); it++) {
fprintf(fp, "Library.%-35s %s", ((*it)+":").c_str(), libbase);
if (solibdeps.size() > 0) {
vector<string>::const_iterator depit;
for (depit = solibdeps.begin(); depit != solibdeps.end(); depit++) {
const char *deplib = depit->c_str();
if (!fullpath) {
if ((deplib = strrchr(deplib, '/')))
deplib++;
}
fprintf(fp, " %s", deplib);
}
}
fprintf(fp, "\n");
}
return 0;
}
//______________________________________________________________________________
int main(int argc, char **argv)
{
string solib;
vector<string> solibdeps;
vector<string> linkdefs;
bool fullpath = false;
bool replace = false;
FILE *fp = stdout;
if (argc > 1) {
int ic = 1;
if (!strcmp(argv[ic], "-?") || !strcmp(argv[ic], "-h")) {
fprintf(stderr, usage, argv[0]);
return 1;
}
if (!strcmp(argv[ic], "-f")) {
fullpath = true;
ic++;
}
if (!strcmp(argv[ic], "-o")) {
ic++;
fp = fopen(argv[ic], "w");
if (!fp) {
fprintf(stderr, "cannot open output file %s\n", argv[ic]);
return 1;
}
ic++;
}
if (!strcmp(argv[ic], "-r")) {
replace = true;
ic++;
fp = fopen(argv[ic], "a+");
if (!fp) {
fprintf(stderr, "cannot open output file %s\n", argv[ic]);
return 1;
}
ic++;
}
if (!strcmp(argv[ic], "-l")) {
ic++;
solib = argv[ic];
#ifdef __APPLE__
string::size_type i = solib.find(".dylib");
if (i != string::npos)
solib.replace(i, 6, ".so");
#endif
ic++;
}
if (!strcmp(argv[ic], "-d")) {
ic++;
for (int i = ic; i < argc && argv[i][0] != '-'; i++) {
string dl = argv[i];
#ifdef __APPLE__
string::size_type i = dl.find(".dylib");
if (i != string::npos)
dl.replace(i, 6, ".so");
#endif
solibdeps.push_back(dl);
ic++;
}
}
if (!strcmp(argv[ic], "-c")) {
ic++;
for (int i = ic; i < argc; i++) {
linkdefs.push_back(argv[i]);
ic++;
}
}
} else {
fprintf(stderr, usage, argv[0]);
return 1;
}
if (replace) {
#if !defined(WIN32) && !defined(__CYGWIN__)
// lock file
if (lockf(fileno(fp), F_LOCK, (off_t)1) == -1) {
fprintf(stderr, "rlibmap: error locking output file\n");
fclose(fp);
return 1;
}
#endif
// remove entries for solib to be processed
RemoveLib(solib, fullpath, fp);
}
LibMap(solib, solibdeps, linkdefs, fullpath, fp);
if (replace) {
#if !defined(WIN32) && !defined(__CYGWIN__)
// remove lock
lseek(fileno(fp), 0, SEEK_SET);
if (lockf(fileno(fp), F_ULOCK, (off_t)1) == -1) {
fprintf(stderr, "rlibmap: error unlocking output file\n");
fclose(fp);
return 1;
}
#endif
}
if (fp != stdout)
fclose(fp);
return 0;
}
<commit_msg>disable use of lockf on FreeBSD.<commit_after>// @(#)root/utils:$Name: $:$Id: rlibmap.cxx,v 1.13 2004/05/19 16:12:58 rdm Exp $
// Author: Fons Rademakers 05/12/2003
/*************************************************************************
* Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
// This program generates a map between class name and shared library.
// Its output is in TEnv format.
// Usage: rlibmap [-f] [-o <mapfile>] -l <sofile> -d <depsofiles>
// -c <linkdeffiles>
// -f: output full library path name (not needed when ROOT library
// search path is used)
// -o: write output to specified file, otherwise to stdout
// -r: replace existing entries in the specified file
// -l: library containing the classes in the specified linkdef files
// -d: libraries on which the -l library depends
// -c: linkdef files containing the list of classes defined in the -l library
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string>
#include <vector>
#ifndef WIN32
# include <unistd.h>
#else
# define ssize_t int
# include <io.h>
# include <sys/types.h>
#endif
#ifdef __APPLE__
#include <AvailabilityMacros.h>
#endif
#if (defined(__FreeBSD__) && (__FreeBSD__ < 4)) || \
(defined(__APPLE__) && (!defined(MAC_OS_X_VERSION_10_3) || \
(MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_3)))
#include <sys/file.h>
#define lockf(fd, op, sz) flock((fd), (op))
#ifndef F_LOCK
#define F_LOCK (LOCK_EX | LOCK_NB)
#endif
#ifndef F_ULOCK
#define F_ULOCK LOCK_UN
#endif
#endif
#if defined(__CYGWIN__) && defined(__GNUC__)
#define F_LOCK F_WRLCK
#define F_ULOCK F_UNLCK
static int fcntl_lockf(int fd, int op, off_t off)
{
flock fl;
fl.l_whence = SEEK_SET;
fl.l_start = off;
fl.l_len = 0; // whole file
fl.l_pid = getpid();
fl.l_type = op;
return fcntl(fd, F_SETLK, &fl);
}
#define lockf fcntl_lockf
#endif
const char *usage = "Usage: %s [-f] [<-r|-o> <mapfile>] -l <sofile> -d <depsofiles> -c <linkdeffiles>\n";
namespace std {}
using namespace std;
#ifdef WIN32
#include <windows.h>
#define ftruncate(fd, size) win32_ftruncate(fd, size)
//______________________________________________________________________________
int win32_ftruncate(int fd, ssize_t size)
{
HANDLE hfile;
int curpos;
if (fd < 0) return -1;
hfile = (HANDLE) _get_osfhandle(fd);
curpos = ::SetFilePointer(hfile, 0, 0, FILE_CURRENT);
if (curpos == 0xFFFFFFFF ||
::SetFilePointer(hfile, size, 0, FILE_BEGIN) == 0xFFFFFFFF ||
!::SetEndOfFile(hfile)) {
int error = ::GetLastError();
switch (error) {
case ERROR_INVALID_HANDLE:
errno = EBADF;
break;
default:
errno = EIO;
break;
}
return -1;
}
return 0;
}
#endif // WIN32
//______________________________________________________________________________
char *Compress(const char *str)
{
// Remove all blanks from the string str. The returned string has to be
// deleted by the user.
if (!str) return 0;
const char *p = str;
// allocate 20 extra characters in case of eg, vector<vector<T>>
char *s, *s1 = new char[strlen(str)+20];
s = s1;
while (*p) {
if (*p != ' ')
*s++ = *p;
p++;
}
*s = '\0';
return s1;
}
//______________________________________________________________________________
int RemoveLib(const string &solib, bool fullpath, FILE *fp)
{
// Remove entries from the map file for the specified solib.
fseek(fp, 0, SEEK_SET);
// get file size
struct stat sbuf;
fstat(fileno(fp), &sbuf);
size_t siz = sbuf.st_size;
if (!siz) return 0;
const char *libbase = solib.c_str();
if (!fullpath) {
if ((libbase = strrchr(libbase, '/')))
libbase++;
}
// read file and remove lines matching specified libs
char *fbuf = new char[siz+1];
char *fptr = fbuf;
while (fgets(fptr, siz - size_t(fptr-fbuf), fp)) {
char *line = new char[strlen(fptr)+1];
strcpy(line, fptr);
strtok(line, " ");
char *lib = strtok(0, " \n");
if (lib && strcmp(lib, libbase)) {
fptr += strlen(fptr);
if (*(fptr-1) != '\n') {
*fptr = '\n';
fptr++;
}
}
delete [] line;
// fgets() should return 0 in this case but doesn't
if (siz - size_t(fptr - fbuf) <= 0)
break;
}
ftruncate(fileno(fp), 0);
// write remaining lines back
if (fptr != fbuf) {
fseek(fp, 0, SEEK_SET);
fwrite(fbuf, 1, size_t(fptr-fbuf), fp);
}
delete [] fbuf;
fseek(fp, 0, SEEK_END);
return 0;
}
//______________________________________________________________________________
int LibMap(const string &solib, const vector<string> &solibdeps,
const vector<string> &linkdefs, bool fullpath, FILE *fp)
{
// Write libmap. Returns -1 in case of error.
vector<string> classes;
vector<string>::const_iterator lk;
for (lk = linkdefs.begin(); lk != linkdefs.end(); lk++) {
const char *linkdef = lk->c_str();
FILE *lfp;
char pragma[1024];
if ((lfp = fopen(linkdef, "r"))) {
while (fgets(pragma, 1024, lfp)) {
if (!strcmp(strtok(pragma, " "), "#pragma") &&
!strcmp(strtok(0, " "), "link") &&
!strcmp(strtok(0, " "), "C++") &&
!strcmp(strtok(0, " "), "class")) {
char *cls = strtok(0, "-!+;");
// just in case remove trailing space and tab
while (*cls == ' ') cls++;
int len = strlen(cls) - 1;
while (cls[len] == ' ' || cls[len] == '\t')
cls[len--] = '\0';
//no space between tmpl arguments allowed
cls = Compress(cls);
// don't include "vector<string>" and "std::pair<" classes
if (!strncmp(cls, "vector<string>", 14) ||
!strncmp(cls, "std::pair<", 10))
continue;
// replace "::" by "@@" since TEnv uses ":" as delimeter
char *s = cls;
while (*s) {
if (*s == ':') *s = '@';
s++;
}
classes.push_back(cls);
}
}
fclose(lfp);
} else {
fprintf(stderr, "cannot open linkdef file %s\n", linkdef);
}
}
const char *libbase = solib.c_str();
if (!fullpath) {
if ((libbase = strrchr(libbase, '/')))
libbase++;
}
vector<string>::const_iterator it;
for (it = classes.begin(); it != classes.end(); it++) {
fprintf(fp, "Library.%-35s %s", ((*it)+":").c_str(), libbase);
if (solibdeps.size() > 0) {
vector<string>::const_iterator depit;
for (depit = solibdeps.begin(); depit != solibdeps.end(); depit++) {
const char *deplib = depit->c_str();
if (!fullpath) {
if ((deplib = strrchr(deplib, '/')))
deplib++;
}
fprintf(fp, " %s", deplib);
}
}
fprintf(fp, "\n");
}
return 0;
}
//______________________________________________________________________________
int main(int argc, char **argv)
{
string solib;
vector<string> solibdeps;
vector<string> linkdefs;
bool fullpath = false;
bool replace = false;
FILE *fp = stdout;
if (argc > 1) {
int ic = 1;
if (!strcmp(argv[ic], "-?") || !strcmp(argv[ic], "-h")) {
fprintf(stderr, usage, argv[0]);
return 1;
}
if (!strcmp(argv[ic], "-f")) {
fullpath = true;
ic++;
}
if (!strcmp(argv[ic], "-o")) {
ic++;
fp = fopen(argv[ic], "w");
if (!fp) {
fprintf(stderr, "cannot open output file %s\n", argv[ic]);
return 1;
}
ic++;
}
if (!strcmp(argv[ic], "-r")) {
replace = true;
ic++;
fp = fopen(argv[ic], "a+");
if (!fp) {
fprintf(stderr, "cannot open output file %s\n", argv[ic]);
return 1;
}
ic++;
}
if (!strcmp(argv[ic], "-l")) {
ic++;
solib = argv[ic];
#ifdef __APPLE__
string::size_type i = solib.find(".dylib");
if (i != string::npos)
solib.replace(i, 6, ".so");
#endif
ic++;
}
if (!strcmp(argv[ic], "-d")) {
ic++;
for (int i = ic; i < argc && argv[i][0] != '-'; i++) {
string dl = argv[i];
#ifdef __APPLE__
string::size_type i = dl.find(".dylib");
if (i != string::npos)
dl.replace(i, 6, ".so");
#endif
solibdeps.push_back(dl);
ic++;
}
}
if (!strcmp(argv[ic], "-c")) {
ic++;
for (int i = ic; i < argc; i++) {
linkdefs.push_back(argv[i]);
ic++;
}
}
} else {
fprintf(stderr, usage, argv[0]);
return 1;
}
if (replace) {
#if !defined(WIN32) && !defined(__CYGWIN__) && !defined(__FreeBSD__)
// lock file
if (lockf(fileno(fp), F_LOCK, (off_t)1) == -1) {
fprintf(stderr, "rlibmap: error locking output file\n");
fclose(fp);
return 1;
}
#endif
// remove entries for solib to be processed
RemoveLib(solib, fullpath, fp);
}
LibMap(solib, solibdeps, linkdefs, fullpath, fp);
if (replace) {
#if !defined(WIN32) && !defined(__CYGWIN__) && !defined(__FreeBSD__)
// remove lock
lseek(fileno(fp), 0, SEEK_SET);
if (lockf(fileno(fp), F_ULOCK, (off_t)1) == -1) {
fprintf(stderr, "rlibmap: error unlocking output file\n");
fclose(fp);
return 1;
}
#endif
}
if (fp != stdout)
fclose(fp);
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>bool improvements<commit_after><|endoftext|> |
<commit_before>#include "core/generator_maze.h"
#include "core/generator_cell.h"
#include "core/random.h"
#include "core/imageops.h"
#include "core/debug.h"
#include <iostream>
// later when doing floodfill
// #include "core/colorbrewer.h"
void maze()
{
auto random = Random {};
auto maze = generator::Maze::FromWidthHeight(30, 10);
auto gen = generator::RecursiveBacktracker{};
gen.maze = &maze;
gen.random = &random;
gen.Setup();
auto drawer = generator::Drawer {};
drawer.maze = &maze;
drawer.tracker = &gen;
drawer.cell_size = 1;
drawer.wall_size = 1;
while(gen.HasMoreWork())
{
gen.Work();
}
drawer.Draw();
debug::MemoryChunkToFile(drawer.image.Write(ImageWriteFormat::PNG), "maze.png");
auto table = ImageToStringTable(drawer.image,
{
{'#', drawer.wall_color},
{'/', drawer.cell_color},
{' ', drawer.wall_color},
{' ', drawer.cell_visited_color},
{'O', drawer.unit_color}
}
);
for(int r=0; r<table.Height(); r+=1)
{
for(int c=0; c<table.Width(); c+=1)
{
std::cout << table.Value(c, r);
}
std::cout << "\n";
}
}
void cell()
{
auto random = Random {};
auto world = generator::World::FromWidthHeight(80, 80);
generator::CellularAutomata cell;
cell.world = &world;
cell.random = &random;
cell.Setup();
auto drawer = generator::CellularAutomataDrawer {};
drawer.world = &world;
while(cell.HasMoreWork())
{
cell.Work();
}
drawer.Draw();
debug::MemoryChunkToFile(drawer.image.Write(ImageWriteFormat::PNG), "maze.png");
}
void main()
{
// maze();
cell();
}
<commit_msg>return value on main<commit_after>#include "core/generator_maze.h"
#include "core/generator_cell.h"
#include "core/random.h"
#include "core/imageops.h"
#include "core/debug.h"
#include <iostream>
// later when doing floodfill
// #include "core/colorbrewer.h"
void maze()
{
auto random = Random {};
auto maze = generator::Maze::FromWidthHeight(30, 10);
auto gen = generator::RecursiveBacktracker{};
gen.maze = &maze;
gen.random = &random;
gen.Setup();
auto drawer = generator::Drawer {};
drawer.maze = &maze;
drawer.tracker = &gen;
drawer.cell_size = 1;
drawer.wall_size = 1;
while(gen.HasMoreWork())
{
gen.Work();
}
drawer.Draw();
debug::MemoryChunkToFile(drawer.image.Write(ImageWriteFormat::PNG), "maze.png");
auto table = ImageToStringTable(drawer.image,
{
{'#', drawer.wall_color},
{'/', drawer.cell_color},
{' ', drawer.wall_color},
{' ', drawer.cell_visited_color},
{'O', drawer.unit_color}
}
);
for(int r=0; r<table.Height(); r+=1)
{
for(int c=0; c<table.Width(); c+=1)
{
std::cout << table.Value(c, r);
}
std::cout << "\n";
}
}
void cell()
{
auto random = Random {};
auto world = generator::World::FromWidthHeight(80, 80);
generator::CellularAutomata cell;
cell.world = &world;
cell.random = &random;
cell.Setup();
auto drawer = generator::CellularAutomataDrawer {};
drawer.world = &world;
while(cell.HasMoreWork())
{
cell.Work();
}
drawer.Draw();
debug::MemoryChunkToFile(drawer.image.Write(ImageWriteFormat::PNG), "maze.png");
}
int main()
{
// maze();
cell();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/globals.h"
#if defined(TARGET_OS_MACOS)
#include "vm/os.h"
#include <errno.h> // NOLINT
#include <limits.h> // NOLINT
#include <mach/mach.h> // NOLINT
#include <mach/clock.h> // NOLINT
#include <mach/mach_time.h> // NOLINT
#include <sys/time.h> // NOLINT
#include <sys/resource.h> // NOLINT
#include <unistd.h> // NOLINT
#if TARGET_OS_IOS
#include <sys/sysctl.h> // NOLINT
#include <syslog.h> // NOLINT
#endif
#include "platform/utils.h"
#include "vm/isolate.h"
#include "vm/zone.h"
namespace dart {
const char* OS::Name() {
return "macos";
}
intptr_t OS::ProcessId() {
return static_cast<intptr_t>(getpid());
}
static bool LocalTime(int64_t seconds_since_epoch, tm* tm_result) {
time_t seconds = static_cast<time_t>(seconds_since_epoch);
if (seconds != seconds_since_epoch) return false;
struct tm* error_code = localtime_r(&seconds, tm_result);
return error_code != NULL;
}
const char* OS::GetTimeZoneName(int64_t seconds_since_epoch) {
tm decomposed;
bool succeeded = LocalTime(seconds_since_epoch, &decomposed);
// If unsuccessful, return an empty string like V8 does.
return (succeeded && (decomposed.tm_zone != NULL)) ? decomposed.tm_zone : "";
}
int OS::GetTimeZoneOffsetInSeconds(int64_t seconds_since_epoch) {
tm decomposed;
bool succeeded = LocalTime(seconds_since_epoch, &decomposed);
// Even if the offset was 24 hours it would still easily fit into 32 bits.
// If unsuccessful, return zero like V8 does.
return succeeded ? static_cast<int>(decomposed.tm_gmtoff) : 0;
}
int OS::GetLocalTimeZoneAdjustmentInSeconds() {
// TODO(floitsch): avoid excessive calls to tzset?
tzset();
// Even if the offset was 24 hours it would still easily fit into 32 bits.
// Note that Unix and Dart disagree on the sign.
return static_cast<int>(-timezone);
}
int64_t OS::GetCurrentTimeMillis() {
return GetCurrentTimeMicros() / 1000;
}
int64_t OS::GetCurrentTimeMicros() {
// gettimeofday has microsecond resolution.
struct timeval tv;
if (gettimeofday(&tv, NULL) < 0) {
UNREACHABLE();
return 0;
}
return (static_cast<int64_t>(tv.tv_sec) * 1000000) + tv.tv_usec;
}
int64_t OS::GetCurrentTraceMicros() {
#if TARGET_OS_IOS
// On iOS mach_absolute_time stops while the device is sleeping. Instead use
// now - KERN_BOOTTIME to get a time difference that is not impacted by clock
// changes. KERN_BOOTTIME will be updated by the system whenever the system
// clock change.
struct timeval boottime;
int mib[2] = {CTL_KERN, KERN_BOOTTIME};
size_t size = sizeof(boottime);
int kr = sysctl(mib, sizeof(mib) / sizeof(mib[0]), &boottime, &size, NULL, 0);
ASSERT(KERN_SUCCESS == kr);
int64_t now = GetCurrentTimeMicros();
int64_t origin = boottime.tv_sec * kMicrosecondsPerSecond;
origin += boottime.tv_usec;
return now - origin;
#else
static mach_timebase_info_data_t timebase_info;
if (timebase_info.denom == 0) {
// Zero-initialization of statics guarantees that denom will be 0 before
// calling mach_timebase_info. mach_timebase_info will never set denom to
// 0 as that would be invalid, so the zero-check can be used to determine
// whether mach_timebase_info has already been called. This is
// recommended by Apple's QA1398.
kern_return_t kr = mach_timebase_info(&timebase_info);
ASSERT(KERN_SUCCESS == kr);
}
// timebase_info converts absolute time tick units into nanoseconds. Convert
// to microseconds.
int64_t result = mach_absolute_time() / kNanosecondsPerMicrosecond;
result *= timebase_info.numer;
result /= timebase_info.denom;
return result;
#endif // TARGET_OS_IOS
}
void* OS::AlignedAllocate(intptr_t size, intptr_t alignment) {
const int kMinimumAlignment = 16;
ASSERT(Utils::IsPowerOfTwo(alignment));
ASSERT(alignment >= kMinimumAlignment);
// Temporary workaround until xcode is upgraded.
// Mac guarantees malloc returns a 16 byte aligned memory chunk.
// Currently we only allocate with 16-bye alignment.
ASSERT(alignment == 16);
// TODO(johnmccutchan): Remove hack and switch to posix_memalign.
return malloc(size);
}
void OS::AlignedFree(void* ptr) {
free(ptr);
}
intptr_t OS::ActivationFrameAlignment() {
#if TARGET_OS_IOS
#if TARGET_ARCH_ARM
// Even if we generate code that maintains a stronger alignment, we cannot
// assert the stronger stack alignment because C++ code will not maintain it.
return 8;
#elif TARGET_ARCH_ARM64
return 16;
#endif
#else // TARGET_OS_IOS
// OS X activation frames must be 16 byte-aligned; see "Mac OS X ABI
// Function Call Guide".
return 16;
#endif // TARGET_OS_IOS
}
intptr_t OS::PreferredCodeAlignment() {
ASSERT(32 <= OS::kMaxPreferredCodeAlignment);
return 32;
}
bool OS::AllowStackFrameIteratorFromAnotherThread() {
return false;
}
int OS::NumberOfAvailableProcessors() {
return sysconf(_SC_NPROCESSORS_ONLN);
}
void OS::Sleep(int64_t millis) {
int64_t micros = millis * kMicrosecondsPerMillisecond;
SleepMicros(micros);
}
void OS::SleepMicros(int64_t micros) {
struct timespec req; // requested.
struct timespec rem; // remainder.
int64_t seconds = micros / kMicrosecondsPerSecond;
if (seconds > kMaxInt32) {
// Avoid truncation of overly large sleep values.
seconds = kMaxInt32;
}
micros = micros - seconds * kMicrosecondsPerSecond;
int64_t nanos = micros * kNanosecondsPerMicrosecond;
req.tv_sec = static_cast<int32_t>(seconds);
req.tv_nsec = static_cast<long>(nanos); // NOLINT (long used in timespec).
while (true) {
int r = nanosleep(&req, &rem);
if (r == 0) {
break;
}
// We should only ever see an interrupt error.
ASSERT(errno == EINTR);
// Copy remainder into requested and repeat.
req = rem;
}
}
void OS::DebugBreak() {
__builtin_trap();
}
char* OS::StrNDup(const char* s, intptr_t n) {
// strndup has only been added to Mac OS X in 10.7. We are supplying
// our own copy here if needed.
#if !defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) || \
__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ <= 1060
intptr_t len = strlen(s);
if ((n < 0) || (len < 0)) {
return NULL;
}
if (n < len) {
len = n;
}
char* result = reinterpret_cast<char*>(malloc(len + 1));
if (result == NULL) {
return NULL;
}
result[len] = '\0';
return reinterpret_cast<char*>(memmove(result, s, len));
#else // !defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) || ...
return strndup(s, n);
#endif // !defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) || ...
}
void OS::Print(const char* format, ...) {
#if TARGET_OS_IOS
va_list args;
va_start(args, format);
vsyslog(LOG_INFO, format, args);
va_end(args);
#else
va_list args;
va_start(args, format);
VFPrint(stdout, format, args);
va_end(args);
#endif
}
void OS::VFPrint(FILE* stream, const char* format, va_list args) {
vfprintf(stream, format, args);
fflush(stream);
}
int OS::SNPrint(char* str, size_t size, const char* format, ...) {
va_list args;
va_start(args, format);
int retval = VSNPrint(str, size, format, args);
va_end(args);
return retval;
}
int OS::VSNPrint(char* str, size_t size, const char* format, va_list args) {
int retval = vsnprintf(str, size, format, args);
if (retval < 0) {
FATAL1("Fatal error in OS::VSNPrint with format '%s'", format);
}
return retval;
}
char* OS::SCreate(Zone* zone, const char* format, ...) {
va_list args;
va_start(args, format);
char* buffer = VSCreate(zone, format, args);
va_end(args);
return buffer;
}
char* OS::VSCreate(Zone* zone, const char* format, va_list args) {
// Measure.
va_list measure_args;
va_copy(measure_args, args);
intptr_t len = VSNPrint(NULL, 0, format, measure_args);
va_end(measure_args);
char* buffer;
if (zone) {
buffer = zone->Alloc<char>(len + 1);
} else {
buffer = reinterpret_cast<char*>(malloc(len + 1));
}
ASSERT(buffer != NULL);
// Print.
va_list print_args;
va_copy(print_args, args);
VSNPrint(buffer, len + 1, format, print_args);
va_end(print_args);
return buffer;
}
bool OS::StringToInt64(const char* str, int64_t* value) {
ASSERT(str != NULL && strlen(str) > 0 && value != NULL);
int32_t base = 10;
char* endptr;
int i = 0;
if (str[0] == '-') {
i = 1;
}
if ((str[i] == '0') &&
(str[i + 1] == 'x' || str[i + 1] == 'X') &&
(str[i + 2] != '\0')) {
base = 16;
}
errno = 0;
*value = strtoll(str, &endptr, base);
return ((errno == 0) && (endptr != str) && (*endptr == 0));
}
void OS::RegisterCodeObservers() {
}
void OS::PrintErr(const char* format, ...) {
#if TARGET_OS_IOS
va_list args;
va_start(args, format);
vsyslog(LOG_ERR, format, args);
va_end(args);
#else
va_list args;
va_start(args, format);
VFPrint(stderr, format, args);
va_end(args);
#endif
}
void OS::InitOnce() {
// TODO(5411554): For now we check that initonce is called only once,
// Once there is more formal mechanism to call InitOnce we can move
// this check there.
static bool init_once_called = false;
ASSERT(init_once_called == false);
init_once_called = true;
}
void OS::Shutdown() {
}
void OS::Abort() {
abort();
}
void OS::Exit(int code) {
exit(code);
}
} // namespace dart
#endif // defined(TARGET_OS_MACOS)
<commit_msg>Return correct ActivationFrameAlignment for iOS simulator variants<commit_after>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/globals.h"
#if defined(TARGET_OS_MACOS)
#include "vm/os.h"
#include <errno.h> // NOLINT
#include <limits.h> // NOLINT
#include <mach/mach.h> // NOLINT
#include <mach/clock.h> // NOLINT
#include <mach/mach_time.h> // NOLINT
#include <sys/time.h> // NOLINT
#include <sys/resource.h> // NOLINT
#include <unistd.h> // NOLINT
#if TARGET_OS_IOS
#include <sys/sysctl.h> // NOLINT
#include <syslog.h> // NOLINT
#endif
#include "platform/utils.h"
#include "vm/isolate.h"
#include "vm/zone.h"
namespace dart {
const char* OS::Name() {
return "macos";
}
intptr_t OS::ProcessId() {
return static_cast<intptr_t>(getpid());
}
static bool LocalTime(int64_t seconds_since_epoch, tm* tm_result) {
time_t seconds = static_cast<time_t>(seconds_since_epoch);
if (seconds != seconds_since_epoch) return false;
struct tm* error_code = localtime_r(&seconds, tm_result);
return error_code != NULL;
}
const char* OS::GetTimeZoneName(int64_t seconds_since_epoch) {
tm decomposed;
bool succeeded = LocalTime(seconds_since_epoch, &decomposed);
// If unsuccessful, return an empty string like V8 does.
return (succeeded && (decomposed.tm_zone != NULL)) ? decomposed.tm_zone : "";
}
int OS::GetTimeZoneOffsetInSeconds(int64_t seconds_since_epoch) {
tm decomposed;
bool succeeded = LocalTime(seconds_since_epoch, &decomposed);
// Even if the offset was 24 hours it would still easily fit into 32 bits.
// If unsuccessful, return zero like V8 does.
return succeeded ? static_cast<int>(decomposed.tm_gmtoff) : 0;
}
int OS::GetLocalTimeZoneAdjustmentInSeconds() {
// TODO(floitsch): avoid excessive calls to tzset?
tzset();
// Even if the offset was 24 hours it would still easily fit into 32 bits.
// Note that Unix and Dart disagree on the sign.
return static_cast<int>(-timezone);
}
int64_t OS::GetCurrentTimeMillis() {
return GetCurrentTimeMicros() / 1000;
}
int64_t OS::GetCurrentTimeMicros() {
// gettimeofday has microsecond resolution.
struct timeval tv;
if (gettimeofday(&tv, NULL) < 0) {
UNREACHABLE();
return 0;
}
return (static_cast<int64_t>(tv.tv_sec) * 1000000) + tv.tv_usec;
}
int64_t OS::GetCurrentTraceMicros() {
#if TARGET_OS_IOS
// On iOS mach_absolute_time stops while the device is sleeping. Instead use
// now - KERN_BOOTTIME to get a time difference that is not impacted by clock
// changes. KERN_BOOTTIME will be updated by the system whenever the system
// clock change.
struct timeval boottime;
int mib[2] = {CTL_KERN, KERN_BOOTTIME};
size_t size = sizeof(boottime);
int kr = sysctl(mib, sizeof(mib) / sizeof(mib[0]), &boottime, &size, NULL, 0);
ASSERT(KERN_SUCCESS == kr);
int64_t now = GetCurrentTimeMicros();
int64_t origin = boottime.tv_sec * kMicrosecondsPerSecond;
origin += boottime.tv_usec;
return now - origin;
#else
static mach_timebase_info_data_t timebase_info;
if (timebase_info.denom == 0) {
// Zero-initialization of statics guarantees that denom will be 0 before
// calling mach_timebase_info. mach_timebase_info will never set denom to
// 0 as that would be invalid, so the zero-check can be used to determine
// whether mach_timebase_info has already been called. This is
// recommended by Apple's QA1398.
kern_return_t kr = mach_timebase_info(&timebase_info);
ASSERT(KERN_SUCCESS == kr);
}
// timebase_info converts absolute time tick units into nanoseconds. Convert
// to microseconds.
int64_t result = mach_absolute_time() / kNanosecondsPerMicrosecond;
result *= timebase_info.numer;
result /= timebase_info.denom;
return result;
#endif // TARGET_OS_IOS
}
void* OS::AlignedAllocate(intptr_t size, intptr_t alignment) {
const int kMinimumAlignment = 16;
ASSERT(Utils::IsPowerOfTwo(alignment));
ASSERT(alignment >= kMinimumAlignment);
// Temporary workaround until xcode is upgraded.
// Mac guarantees malloc returns a 16 byte aligned memory chunk.
// Currently we only allocate with 16-bye alignment.
ASSERT(alignment == 16);
// TODO(johnmccutchan): Remove hack and switch to posix_memalign.
return malloc(size);
}
void OS::AlignedFree(void* ptr) {
free(ptr);
}
intptr_t OS::ActivationFrameAlignment() {
#if TARGET_OS_IOS
#if TARGET_ARCH_ARM
// Even if we generate code that maintains a stronger alignment, we cannot
// assert the stronger stack alignment because C++ code will not maintain it.
return 8;
#elif TARGET_ARCH_ARM64
return 16;
#elif TARGET_ARCH_IA32
return 16; // iOS simulator
#elif TARGET_ARCH_X64
return 16; // iOS simulator
#else
#error Unimplemented
#endif
#else // TARGET_OS_IOS
// OS X activation frames must be 16 byte-aligned; see "Mac OS X ABI
// Function Call Guide".
return 16;
#endif // TARGET_OS_IOS
}
intptr_t OS::PreferredCodeAlignment() {
ASSERT(32 <= OS::kMaxPreferredCodeAlignment);
return 32;
}
bool OS::AllowStackFrameIteratorFromAnotherThread() {
return false;
}
int OS::NumberOfAvailableProcessors() {
return sysconf(_SC_NPROCESSORS_ONLN);
}
void OS::Sleep(int64_t millis) {
int64_t micros = millis * kMicrosecondsPerMillisecond;
SleepMicros(micros);
}
void OS::SleepMicros(int64_t micros) {
struct timespec req; // requested.
struct timespec rem; // remainder.
int64_t seconds = micros / kMicrosecondsPerSecond;
if (seconds > kMaxInt32) {
// Avoid truncation of overly large sleep values.
seconds = kMaxInt32;
}
micros = micros - seconds * kMicrosecondsPerSecond;
int64_t nanos = micros * kNanosecondsPerMicrosecond;
req.tv_sec = static_cast<int32_t>(seconds);
req.tv_nsec = static_cast<long>(nanos); // NOLINT (long used in timespec).
while (true) {
int r = nanosleep(&req, &rem);
if (r == 0) {
break;
}
// We should only ever see an interrupt error.
ASSERT(errno == EINTR);
// Copy remainder into requested and repeat.
req = rem;
}
}
void OS::DebugBreak() {
__builtin_trap();
}
char* OS::StrNDup(const char* s, intptr_t n) {
// strndup has only been added to Mac OS X in 10.7. We are supplying
// our own copy here if needed.
#if !defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) || \
__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ <= 1060
intptr_t len = strlen(s);
if ((n < 0) || (len < 0)) {
return NULL;
}
if (n < len) {
len = n;
}
char* result = reinterpret_cast<char*>(malloc(len + 1));
if (result == NULL) {
return NULL;
}
result[len] = '\0';
return reinterpret_cast<char*>(memmove(result, s, len));
#else // !defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) || ...
return strndup(s, n);
#endif // !defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) || ...
}
void OS::Print(const char* format, ...) {
#if TARGET_OS_IOS
va_list args;
va_start(args, format);
vsyslog(LOG_INFO, format, args);
va_end(args);
#else
va_list args;
va_start(args, format);
VFPrint(stdout, format, args);
va_end(args);
#endif
}
void OS::VFPrint(FILE* stream, const char* format, va_list args) {
vfprintf(stream, format, args);
fflush(stream);
}
int OS::SNPrint(char* str, size_t size, const char* format, ...) {
va_list args;
va_start(args, format);
int retval = VSNPrint(str, size, format, args);
va_end(args);
return retval;
}
int OS::VSNPrint(char* str, size_t size, const char* format, va_list args) {
int retval = vsnprintf(str, size, format, args);
if (retval < 0) {
FATAL1("Fatal error in OS::VSNPrint with format '%s'", format);
}
return retval;
}
char* OS::SCreate(Zone* zone, const char* format, ...) {
va_list args;
va_start(args, format);
char* buffer = VSCreate(zone, format, args);
va_end(args);
return buffer;
}
char* OS::VSCreate(Zone* zone, const char* format, va_list args) {
// Measure.
va_list measure_args;
va_copy(measure_args, args);
intptr_t len = VSNPrint(NULL, 0, format, measure_args);
va_end(measure_args);
char* buffer;
if (zone) {
buffer = zone->Alloc<char>(len + 1);
} else {
buffer = reinterpret_cast<char*>(malloc(len + 1));
}
ASSERT(buffer != NULL);
// Print.
va_list print_args;
va_copy(print_args, args);
VSNPrint(buffer, len + 1, format, print_args);
va_end(print_args);
return buffer;
}
bool OS::StringToInt64(const char* str, int64_t* value) {
ASSERT(str != NULL && strlen(str) > 0 && value != NULL);
int32_t base = 10;
char* endptr;
int i = 0;
if (str[0] == '-') {
i = 1;
}
if ((str[i] == '0') &&
(str[i + 1] == 'x' || str[i + 1] == 'X') &&
(str[i + 2] != '\0')) {
base = 16;
}
errno = 0;
*value = strtoll(str, &endptr, base);
return ((errno == 0) && (endptr != str) && (*endptr == 0));
}
void OS::RegisterCodeObservers() {
}
void OS::PrintErr(const char* format, ...) {
#if TARGET_OS_IOS
va_list args;
va_start(args, format);
vsyslog(LOG_ERR, format, args);
va_end(args);
#else
va_list args;
va_start(args, format);
VFPrint(stderr, format, args);
va_end(args);
#endif
}
void OS::InitOnce() {
// TODO(5411554): For now we check that initonce is called only once,
// Once there is more formal mechanism to call InitOnce we can move
// this check there.
static bool init_once_called = false;
ASSERT(init_once_called == false);
init_once_called = true;
}
void OS::Shutdown() {
}
void OS::Abort() {
abort();
}
void OS::Exit(int code) {
exit(code);
}
} // namespace dart
#endif // defined(TARGET_OS_MACOS)
<|endoftext|> |
<commit_before><commit_msg>sal: fix build with clang and --enable-crashdump<commit_after><|endoftext|> |
<commit_before>/*! CreditMetrics.cpp : Defines the entry point for the console application.
Note: The given .csv files are not formatted consistently. The .csv parsers below are
designed to handle the inconsistencies present in the files in a somewhat
general manner by removing extra characters and white space.
*/
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
#include <boost/numeric/ublas/matrix.hpp>
using namespace std;
static inline string& trim(string& s) {
//left
s.erase(s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace))));
//right
s.erase(find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end());
return s;
}
static inline int convertInt(string strInt)
{
trim(strInt);
return ::atoi(strInt.c_str());
}
static inline double convertDouble(string strDouble)
{
trim(strDouble);
return ::atof(strDouble.c_str());
}
static inline double convertPercent(string strPercent)
{
replace(strPercent.begin(), strPercent.end(), '%', ' ');
return convertDouble(strPercent) / 100;
}
template <class R> class CSV : public vector<R>
{
public:
CSV(const string& filename, size_t skipLines)
{
ifstream file(filename);
if (!file.good())
{
throw runtime_error("File does not exist");
}
while (!file.eof())
{
string strline;
getline(file, strline);
if (skipLines > 0)
{
skipLines--;
continue;
}
if (strline.empty())
{
continue;
}
stringstream streamline(strline);
vector<string> cells;
while (!streamline.eof())
{
string cell;
getline(streamline, cell, ',');
if (cell != "")
{
cells.push_back(cell);
}
}
if (cells.empty())
{
continue;
}
push_back(R(cells));
}
}
const string toString()
{
string ret;
for (size_t i = 0, n = size(); i < n; i++)
ret = ret + at(i).toString() + "\n";
return ret;
}
};
class IssuerEntry
{
public:
IssuerEntry(const vector<string>& cells):
name(cells.at(0)),
rating(cells.at(1)),
industry(cells.at(2))
{}
const string name;
const string rating;
const string industry;
const string toString() const
{
return string()
+ name + "," + rating + "," + industry;
}
};
class IssuerData : public CSV<IssuerEntry>
{
public:
IssuerData() : CSV("issuers.csv", 1) { }
IssuerEntry* getByName(string name)
{
for (size_t i = 0, n = size(); i < n; i++)
{
IssuerEntry& issuer = at(i);
if(issuer.name == name)
return &issuer;
}
return nullptr;
}
};
class PortfolioEntry
{
public:
PortfolioEntry(const vector<string>& cells) :
name(cells.at(0)),
instrumentType(cells.at(1)),
cusip(cells.at(2)),
notional(convertNotional(cells.at(3))),
maturity(cells.at(4)),
coupon(convertPercent(cells.at(5))),
couponsPerYear(convertInt(cells.at(6))),
price(convertPrice(cells.at(7))),
yield(convertPercent(cells.at(8))),
cleanPrice(convertPrice(cells.at(9))),
exprr(convertPercent(cells.at(10)))
{}
const string name, instrumentType, cusip, maturity;
const int notional, couponsPerYear;
const double coupon, price, yield, cleanPrice,exprr;
const string toString() const
{
return string()
+ name + "," + instrumentType + ","
+ cusip + "," + to_string(notional) + ","
+ maturity + "," + to_string(coupon) + ","
+ to_string(couponsPerYear) + "," + to_string(price) + ","
+ to_string(yield) + "," + to_string(cleanPrice) + ","
+ to_string(exprr);
}
private:
int convertNotional(string strNotional)
{
return convertInt(strNotional);
}
double convertPrice(string strPrice)
{
replace(strPrice.begin(), strPrice.end(), '$', ' ');
return convertDouble(strPrice);
}
};
class PortfolioData : public CSV<PortfolioEntry>
{
public:
PortfolioData() : CSV("portfolio_for_project.csv", 1) { }
PortfolioEntry* getByName(string name)
{
for (size_t i = 0, n = size(); i < n; i++)
{
PortfolioEntry& issuer = at(i);
if (issuer.name == name)
return &issuer;
}
return nullptr;
}
/*! Response for Part B, Step 2) Reported Value
\return The reported value of the portfolio in millions of dollars
*/
double getReportedValue()
{
double marketValue = 0;
for (size_t i = 0, n = size(); i < n; i++)
{
PortfolioEntry& row = at(i);
double targetValue;
if (row.instrumentType == "CDS")
targetValue = row.cleanPrice;
else
targetValue = row.price;
marketValue = marketValue + (row.notional*targetValue / 100);
}
return marketValue;
}
/*! Response for Part B, Step 2) Theoretical Value
\return The theoretical value of the portfolio in millions of dollars
*/
double getTheorValue()
{
double theorValue = 0;
for (size_t i = 0, n = size(); i < n; i++)
{
PortfolioEntry& row = at(i);
theorValue = theorValue + (row.notional*row.cleanPrice / 100);
}
return theorValue;
}
};
class YieldEntry
{
public:
YieldEntry(const vector<string>& cells):
term(convertDouble(cells.at(0))),
aaa(convertPercent(cells.at(1))),
aa(convertPercent(cells.at(2))),
a(convertPercent(cells.at(3))),
bbb(convertPercent(cells.at(4))),
bb(convertPercent(cells.at(5))),
b(convertPercent(cells.at(6))),
ccc(convertPercent(cells.at(7))),
govt(convertPercent(cells.at(8)))
{}
const double term, aaa, aa, a, bbb, bb, b, ccc, govt;
const string toString() const
{
return string()
+ to_string(term) + "," + to_string(aaa) + ","
+ to_string(aa) + "," + to_string(a) + ","
+ to_string(bbb) + "," + to_string(bb) + ","
+ to_string(b) + "," + to_string(ccc) + ","
+ to_string(govt);
}
};
class YieldData : public CSV<YieldEntry>
{
public:
YieldData() : CSV("yield_curve_for_project.csv", 1) { }
YieldEntry* getByTerm(double term)
{
for (size_t i = 0, n = size(); i < n; i++)
{
YieldEntry& yield = at(i);
if (yield.term == term)
return &yield;
}
return nullptr;
}
};
class MatrixRow : public vector<double>
{
public:
MatrixRow(const vector<string>& cells)
{
for (size_t i = 1, n = cells.size(); i < n; i++)
{
push_back(convertDouble(cells.at(i)));
}
}
using vector::vector;
string toString()
{
string ret;
for (size_t i = 0, n = size(); i < n; i++)
{
if (i > 0)
ret = ret + ",";
ret = ret + to_string(at(i));
}
return ret;
}
};
class Matrix : public CSV<MatrixRow>
{
public:
Matrix(const string& filename, size_t skipLines) : CSV(filename, skipLines) {}
};
int main(int argc, char* argv[])
{
try
{
IssuerData issuerData;
// cout << issuerData.toString();
PortfolioData portfolioData;
// cout << portfolioData.toString();
YieldData yieldData;
// cout << yieldData.toString();
Matrix correlationMatrix("correlation_matrix_for_project.csv", 1);
// cout << correlationMatrix.toString();
Matrix transitionMatrix("transition_matrix_for_project.csv", 3);
MatrixRow row{ 0,0,0,0,0,0,0,1 };
transitionMatrix.push_back(row);
// cout << transitionMatrix.toString();
cout << portfolioData.getReportedValue() << "\n";
cout << portfolioData.getTheorValue();
}
catch (const exception &e)
{
cerr << "error: " << e.what() << "\n";
}
getchar();
}<commit_msg>Created routine to produce matrix of possible prices for each instrument<commit_after>/*! CreditMetrics.cpp : Defines the entry point for the console application.
Note: The given .csv files are not formatted consistently. The .csv parsers below are
designed to handle the inconsistencies present in the files in a somewhat
general manner by removing extra characters and white space.
*/
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
#include <random>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
using namespace std;
static inline string& trim(string& s) {
//left
s.erase(s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace))));
//right
s.erase(find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end());
return s;
}
static inline int convertInt(string strInt)
{
trim(strInt);
return ::atoi(strInt.c_str());
}
static inline double convertDouble(string strDouble)
{
trim(strDouble);
return ::atof(strDouble.c_str());
}
static inline double convertPercent(string strPercent)
{
replace(strPercent.begin(), strPercent.end(), '%', ' ');
return convertDouble(strPercent) / 100;
}
template <class R> class CSV : public vector<R>
{
public:
CSV(const string& filename, size_t skipLines)
{
ifstream file(filename);
if (!file.good())
{
throw runtime_error("File does not exist");
}
while (!file.eof())
{
string strline;
getline(file, strline);
if (skipLines > 0)
{
skipLines--;
continue;
}
if (strline.empty())
{
continue;
}
stringstream streamline(strline);
vector<string> cells;
while (!streamline.eof())
{
string cell;
getline(streamline, cell, ',');
if (cell != "")
{
cells.push_back(cell);
}
}
if (cells.empty())
{
continue;
}
push_back(R(cells));
}
}
const string toString()
{
string ret;
for (size_t i = 0, n = size(); i < n; i++)
ret = ret + at(i).toString() + "\n";
return ret;
}
};
class IssuerEntry
{
public:
IssuerEntry(const vector<string>& cells):
name(cells.at(0)),
rating(cells.at(1)),
industry(cells.at(2))
{}
const string name;
const string rating;
const string industry;
const string toString() const
{
return string()
+ name + "," + rating + "," + industry;
}
};
class IssuerData : public CSV<IssuerEntry>
{
public:
IssuerData() : CSV("issuers.csv", 1) { }
IssuerEntry* getByName(string name)
{
for (size_t i = 0, n = size(); i < n; i++)
{
IssuerEntry& issuer = at(i);
if(issuer.name == name)
return &issuer;
}
return nullptr;
}
};
class PortfolioEntry
{
public:
PortfolioEntry(const vector<string>& cells) :
name(cells.at(0)),
instrumentType(cells.at(1)),
cusip(cells.at(2)),
notional(convertNotional(cells.at(3))),
maturity(cells.at(4)),
coupon(convertPercent(cells.at(5))),
couponsPerYear(convertInt(cells.at(6))),
price(convertPrice(cells.at(7))),
yield(convertPercent(cells.at(8))),
cleanPrice(convertPrice(cells.at(9))),
exprr(convertPercent(cells.at(10)))
{}
const string name, instrumentType, cusip, maturity;
const int notional, couponsPerYear;
const double coupon, price, yield, cleanPrice,exprr;
const string toString() const
{
return string()
+ name + "," + instrumentType + ","
+ cusip + "," + to_string(notional) + ","
+ maturity + "," + to_string(coupon) + ","
+ to_string(couponsPerYear) + "," + to_string(price) + ","
+ to_string(yield) + "," + to_string(cleanPrice) + ","
+ to_string(exprr);
}
private:
int convertNotional(string strNotional)
{
return convertInt(strNotional);
}
double convertPrice(string strPrice)
{
replace(strPrice.begin(), strPrice.end(), '$', ' ');
return convertDouble(strPrice);
}
};
class PortfolioData : public CSV<PortfolioEntry>
{
public:
PortfolioData() : CSV("portfolio_for_project.csv", 1) { }
PortfolioEntry* getByName(string name)
{
for (size_t i = 0, n = size(); i < n; i++)
{
PortfolioEntry& issuer = at(i);
if (issuer.name == name)
return &issuer;
}
return nullptr;
}
/*! Response for Part B, Step 2) Reported Value
\return The reported value of the portfolio in millions of dollars
*/
double getReportedValue()
{
double marketValue = 0;
for (size_t i = 0, n = size(); i < n; i++)
{
PortfolioEntry& row = at(i);
double targetValue;
if (row.instrumentType == "CDS")
targetValue = row.cleanPrice;
else
targetValue = row.price;
marketValue = marketValue + (row.notional*targetValue / 100);
}
return marketValue;
}
/*! Response for Part B, Step 2) Theoretical Value
\return The theoretical value of the portfolio in millions of dollars
*/
double getTheorValue()
{
double theorValue = 0;
for (size_t i = 0, n = size(); i < n; i++)
{
PortfolioEntry& row = at(i);
theorValue = theorValue + (row.notional*row.cleanPrice / 100);
}
return theorValue;
}
};
class YieldEntry
{
public:
YieldEntry(const vector<string>& cells):
term(convertDouble(cells.at(0))),
aaa(convertPercent(cells.at(1))),
aa(convertPercent(cells.at(2))),
a(convertPercent(cells.at(3))),
bbb(convertPercent(cells.at(4))),
bb(convertPercent(cells.at(5))),
b(convertPercent(cells.at(6))),
ccc(convertPercent(cells.at(7))),
govt(convertPercent(cells.at(8)))
{}
const double term, aaa, aa, a, bbb, bb, b, ccc, govt;
const string toString() const
{
return string()
+ to_string(term) + "," + to_string(aaa) + ","
+ to_string(aa) + "," + to_string(a) + ","
+ to_string(bbb) + "," + to_string(bb) + ","
+ to_string(b) + "," + to_string(ccc) + ","
+ to_string(govt);
}
};
class YieldData : public CSV<YieldEntry>
{
public:
YieldData() : CSV("yield_curve_for_project.csv", 1) { }
YieldEntry* getByTerm(double term)
{
for (size_t i = 0, n = size(); i < n; i++)
{
YieldEntry& yield = at(i);
if (yield.term == term)
return &yield;
}
return nullptr;
}
};
class MatrixRow : public vector<double>
{
public:
MatrixRow(const vector<string>& cells)
{
for (size_t i = 1, n = cells.size(); i < n; i++)
{
push_back(convertDouble(cells.at(i)));
}
}
using vector::vector;
string toString()
{
string ret;
for (size_t i = 0, n = size(); i < n; i++)
{
if (i > 0)
ret = ret + ",";
ret = ret + to_string(at(i));
}
return ret;
}
};
class Matrix : public CSV<MatrixRow>
{
public:
Matrix(const string& filename, size_t skipLines) : CSV(filename, skipLines) {}
};
int main(int argc, char* argv[])
{
try
{
random_device rd;
mt19937 gen(rd());
uniform_real_distribution<> dis(0, 1);
IssuerData issuerData;
// cout << issuerData.toString();
PortfolioData portfolioData;
// cout << portfolioData.toString();
YieldData yieldData;
// cout << yieldData.toString();
Matrix correlationMatrix("correlation_matrix_for_project.csv", 1);
// cout << correlationMatrix.toString();
Matrix transitionMatrix("transition_matrix_for_project.csv", 3);
MatrixRow row{ 0,0,0,0,0,0,0,1 };
transitionMatrix.push_back(row);
// cout << transitionMatrix.toString();
cout << portfolioData.getReportedValue() << endl;
cout << portfolioData.getTheorValue() << endl;
boost::numeric::ublas::matrix<double> m(portfolioData.size(), 8);
for (size_t i = 0, n1 = m.size1(); i < n1; i++)
{
PortfolioEntry& row = portfolioData.at(i);
// To do: clean this up?
if (row.instrumentType == "CDS")
{
for (size_t j = 0, n2 = m.size2() - 1; j < n2; j++)
m(i, j) = dis(gen);
}
else
{
for (size_t j = 0, n2 = m.size2() - 1; j < n2; j++)
m(i, j) = row.cleanPrice;
}
m(i, m.size2() - 1) = row.exprr * 100;
}
cout << m << endl;
}
catch (const exception &e)
{
cerr << "error: " << e.what() << "\n";
}
getchar();
}<|endoftext|> |
<commit_before>#include "Main.h"
//获取基本信息
void handlerGetDeviceBaseInfo(struct bufferevent * bufEvent,Json::Value &data){
char buffer[100];
//获取内存大小
struct sysinfo memInfo;
sysinfo(&memInfo);
//获取磁盘大小
struct statfs diskInfo;
statfs(DISK_SIZE_PATH, &diskInfo);
//格式化数据
double totalMemSize = (double)memInfo.totalram/(1024.0*1024.0);
double usedMemSize = (double)(memInfo.totalram-memInfo.freeram)/(1024.0*1024.0);
double totalDiskSize = (double)(diskInfo.f_bsize*diskInfo.f_blocks)/(1024.0*1024.0);
double usedDiskSize = (double)(diskInfo.f_bsize*diskInfo.f_blocks-diskInfo.f_bsize*diskInfo.f_bfree)/(1024.0*1024.0);
//构造返回JSON
Json::Value root;
Json::Value re_data;
root["is_app"] = false;
root["protocol"] = API_DEVICE_BASE_INFO;
//总内存大小
sprintf(buffer,"%.2f",totalMemSize);
re_data["mem_total"] = string(buffer);
memset(buffer,0,100);
//使用内存
sprintf(buffer,"%.2f",usedMemSize);
re_data["mem_used"] = string(buffer);
memset(buffer,0,100);
//总硬盘大小
sprintf(buffer,"%.2f",totalDiskSize);
re_data["disk_total"] = string(buffer);
memset(buffer,0,100);
//使用硬盘大小
sprintf(buffer,"%.2f",usedDiskSize);
re_data["disk_used"] = string(buffer);
memset(buffer,0,100);
//返回数据
root["data"] = re_data;
bufferevent_write(bufEvent, root.toStyledString().c_str(), root.toStyledString().length());
}
//键盘按下
void handlerKeyDown(struct bufferevent * bufEvent,Json::Value &data){
Json::Value key_map = data["data"];
int key;
stringstream stream;
stream << key_map["key"].toStyledString();
stream >> key;
switch(key){
case 119://W
case 115://S
case 97://A
case 100://D
case 105://I
case 107://K
case 106://J
case 108://L
printf("key down:%d\n", key);
break;
default:
printf("key not find:%d\n", key);
break;
}
}
//获取MAC地址
string getMacAddress(){
char buff[32];
memset (buff ,'\0', sizeof(buff));
string cmd = "ip addr |grep -A 2 "+network_card_name+" | awk 'NR>1'|awk 'NR<2'|awk '{print $2}'";
// 通过管道来回去系统命令返回的值
FILE *fstream = popen(cmd.c_str(), "r");
if(fstream == NULL) {
perror("popen");
exit(0);
}
if(NULL == fgets(buff, sizeof(buff), fstream)){
printf("not find mac address !!!\n");
exit(0);
}
pclose(fstream);
string mac;
mac = string(buff);
mac = mac.substr(0, mac.length()-1);
return mac;
}
//调用方法
void callFunc(struct bufferevent * bufEvent,Json::Value &request_data,const string func){
if(func.length() == 0){
return;
}
if (client_api_list.count(func)) {
(*(client_api_list[func]))(bufEvent,request_data);
}
}
void sendDeviceInfo(struct bufferevent * bufEvent){
Json::Value root;
Json::Value data;
//获取MAC地址
data["mac"] = getMacAddress();
data["name"] = device_name;
root["protocol"] = API_DEVICE_INFO;
root["is_app"] = false;
root["data"] = data;
string json = root.toStyledString();
bufferevent_write(bufEvent, json.c_str(), json.length());
}
//读操作
void ReadEventCb(struct bufferevent *bufEvent, void *args){
Json::Reader reader;
Json::Value data;
//获取输入缓存
struct evbuffer * pInput = bufferevent_get_input(bufEvent);
//获取输入缓存数据的长度
int len = evbuffer_get_length(pInput);
//获取数据
char* body = new char[len+1];
memset(body,0,sizeof(char)*(len+1));
evbuffer_remove(pInput, body, len);
if(reader.parse(body, data)){
string func = data["protocol"].asString();
callFunc(bufEvent,data,func);
}
delete[] body;
return ;
}
//写操作
void WriteEventCb(struct bufferevent *bufEvent, void *args){
}
//关闭
void SignalEventCb(struct bufferevent * bufEvent, short sEvent, void * args){
//请求的连接过程已经完成
if(BEV_EVENT_CONNECTED == sEvent){
bufferevent_enable(bufEvent, EV_READ);
//设置读超时时间 10s
struct timeval tTimeout = {10, 0};
bufferevent_set_timeouts( bufEvent, &tTimeout, NULL);
string mac = getMacAddress();
if(mac.length() == 0){
printf("MAC地址获取错误请检查网卡配置\n");
event_base_loopexit(baseEvent, NULL);
exit(0);
}
//发送基本信息
sendDeviceInfo(bufEvent);
}
//写操作发生事件
if(BEV_EVENT_WRITING & sEvent){}
//操作时发生错误
if (sEvent & BEV_EVENT_ERROR){
perror("event");
event_base_loopexit(baseEvent, NULL);
}
//结束指示
if (sEvent & BEV_EVENT_EOF){
perror("event");
event_base_loopexit(baseEvent, NULL);
}
//读取发生事件或者超时处理
if(0 != (sEvent & (BEV_EVENT_TIMEOUT|BEV_EVENT_READING)) ){
//发送心跳包
//
//重新注册可读事件
bufferevent_enable(bufEvent, EV_READ);
}
return ;
}
//设置配置文件
void setConfig(const char* config_path){
Config config;
//检测配置文件是否存在
if(!config.FileExist(config_path)){
printf("config: not find config file\n");
exit(0);
}
//读取配置
config.ReadFile(config_path);
api_host = config.Read("SERVER_HOST", api_host);
api_port = config.Read("API_PORT", api_port);
network_card_name = config.Read("NETWORK_CARD", network_card_name);
device_name = config.Read("DEVICE_NAME", device_name);
}
//开始
void startRun(const char* ip,int port){
//创建事件驱动句柄
baseEvent = event_base_new();
//创建socket类型的bufferevent
struct bufferevent* bufferEvent = bufferevent_socket_new(baseEvent, -1, 0);
//构造服务器地址
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(api_host.c_str());
sin.sin_port = htons(api_port);
//连接服务器
if( bufferevent_socket_connect(bufferEvent, (struct sockaddr*)&sin, sizeof(sin)) < 0){
perror("socket");
return;
}
//设置回调函数, 及回调函数的参数
bufferevent_setcb(bufferEvent, ReadEventCb, WriteEventCb, SignalEventCb,NULL);
//开始事件循环
event_base_dispatch(baseEvent);
//事件循环结束 资源清理
bufferevent_free(bufferEvent);
event_base_free(baseEvent);
}
//初始化API列表
void initApiList() {
client_api_list[API_DEVICE_BASE_INFO] = &handlerGetDeviceBaseInfo;
client_api_list[API_DEVICE_KEY_DOWN] = &handlerKeyDown;
}
int main(){
//加载API列表
initApiList();
//加载配置文件
setConfig(CONFIG_PATH);
//启动sockt
startRun(api_host.c_str(),api_port);
return 0;
}
<commit_msg>String to int<commit_after>#include "Main.h"
//获取基本信息
void handlerGetDeviceBaseInfo(struct bufferevent * bufEvent,Json::Value &data){
char buffer[100];
//获取内存大小
struct sysinfo memInfo;
sysinfo(&memInfo);
//获取磁盘大小
struct statfs diskInfo;
statfs(DISK_SIZE_PATH, &diskInfo);
//格式化数据
double totalMemSize = (double)memInfo.totalram/(1024.0*1024.0);
double usedMemSize = (double)(memInfo.totalram-memInfo.freeram)/(1024.0*1024.0);
double totalDiskSize = (double)(diskInfo.f_bsize*diskInfo.f_blocks)/(1024.0*1024.0);
double usedDiskSize = (double)(diskInfo.f_bsize*diskInfo.f_blocks-diskInfo.f_bsize*diskInfo.f_bfree)/(1024.0*1024.0);
//构造返回JSON
Json::Value root;
Json::Value re_data;
root["is_app"] = false;
root["protocol"] = API_DEVICE_BASE_INFO;
//总内存大小
sprintf(buffer,"%.2f",totalMemSize);
re_data["mem_total"] = string(buffer);
memset(buffer,0,100);
//使用内存
sprintf(buffer,"%.2f",usedMemSize);
re_data["mem_used"] = string(buffer);
memset(buffer,0,100);
//总硬盘大小
sprintf(buffer,"%.2f",totalDiskSize);
re_data["disk_total"] = string(buffer);
memset(buffer,0,100);
//使用硬盘大小
sprintf(buffer,"%.2f",usedDiskSize);
re_data["disk_used"] = string(buffer);
memset(buffer,0,100);
//返回数据
root["data"] = re_data;
bufferevent_write(bufEvent, root.toStyledString().c_str(), root.toStyledString().length());
}
//键盘按下
void handlerKeyDown(struct bufferevent * bufEvent,Json::Value &data){
Json::Value key_map = data["data"];
string key = key_map["key"].toStyledString();
if(key.compare("119") == 0){
printf("key down:%s\n", key.c_str());
}else if(key.compare("115") == 0){
printf("key down:%s\n", key.c_str());
}else if(key.compare("97") == 0){
printf("key down:%s\n", key.c_str());
}else if(key.compare("100") == 0){
printf("key down:%s\n", key.c_str());
}else if(key.compare("105") == 0){
printf("key down:%s\n", key.c_str());
}else if(key.compare("107") == 0){
printf("key down:%s\n", key.c_str());
}else if(key.compare("106") == 0){
printf("key down:%s\n", key.c_str());
}else if(key.compare("108") == 0){
printf("key down:%s\n", key.c_str());
}else{
printf("key not find:%s\n", key.c_str());
}
}
//获取MAC地址
string getMacAddress(){
char buff[32];
memset (buff ,'\0', sizeof(buff));
string cmd = "ip addr |grep -A 2 "+network_card_name+" | awk 'NR>1'|awk 'NR<2'|awk '{print $2}'";
// 通过管道来回去系统命令返回的值
FILE *fstream = popen(cmd.c_str(), "r");
if(fstream == NULL) {
perror("popen");
exit(0);
}
if(NULL == fgets(buff, sizeof(buff), fstream)){
printf("not find mac address !!!\n");
exit(0);
}
pclose(fstream);
string mac;
mac = string(buff);
mac = mac.substr(0, mac.length()-1);
return mac;
}
//调用方法
void callFunc(struct bufferevent * bufEvent,Json::Value &request_data,const string func){
if(func.length() == 0){
return;
}
if (client_api_list.count(func)) {
(*(client_api_list[func]))(bufEvent,request_data);
}
}
void sendDeviceInfo(struct bufferevent * bufEvent){
Json::Value root;
Json::Value data;
//获取MAC地址
data["mac"] = getMacAddress();
data["name"] = device_name;
root["protocol"] = API_DEVICE_INFO;
root["is_app"] = false;
root["data"] = data;
string json = root.toStyledString();
bufferevent_write(bufEvent, json.c_str(), json.length());
}
//读操作
void ReadEventCb(struct bufferevent *bufEvent, void *args){
Json::Reader reader;
Json::Value data;
//获取输入缓存
struct evbuffer * pInput = bufferevent_get_input(bufEvent);
//获取输入缓存数据的长度
int len = evbuffer_get_length(pInput);
//获取数据
char* body = new char[len+1];
memset(body,0,sizeof(char)*(len+1));
evbuffer_remove(pInput, body, len);
if(reader.parse(body, data)){
string func = data["protocol"].asString();
callFunc(bufEvent,data,func);
}
delete[] body;
return ;
}
//写操作
void WriteEventCb(struct bufferevent *bufEvent, void *args){
}
//关闭
void SignalEventCb(struct bufferevent * bufEvent, short sEvent, void * args){
//请求的连接过程已经完成
if(BEV_EVENT_CONNECTED == sEvent){
bufferevent_enable(bufEvent, EV_READ);
//设置读超时时间 10s
struct timeval tTimeout = {10, 0};
bufferevent_set_timeouts( bufEvent, &tTimeout, NULL);
string mac = getMacAddress();
if(mac.length() == 0){
printf("MAC地址获取错误请检查网卡配置\n");
event_base_loopexit(baseEvent, NULL);
exit(0);
}
//发送基本信息
sendDeviceInfo(bufEvent);
}
//写操作发生事件
if(BEV_EVENT_WRITING & sEvent){}
//操作时发生错误
if (sEvent & BEV_EVENT_ERROR){
perror("event");
event_base_loopexit(baseEvent, NULL);
}
//结束指示
if (sEvent & BEV_EVENT_EOF){
perror("event");
event_base_loopexit(baseEvent, NULL);
}
//读取发生事件或者超时处理
if(0 != (sEvent & (BEV_EVENT_TIMEOUT|BEV_EVENT_READING)) ){
//发送心跳包
//
//重新注册可读事件
bufferevent_enable(bufEvent, EV_READ);
}
return ;
}
//设置配置文件
void setConfig(const char* config_path){
Config config;
//检测配置文件是否存在
if(!config.FileExist(config_path)){
printf("config: not find config file\n");
exit(0);
}
//读取配置
config.ReadFile(config_path);
api_host = config.Read("SERVER_HOST", api_host);
api_port = config.Read("API_PORT", api_port);
network_card_name = config.Read("NETWORK_CARD", network_card_name);
device_name = config.Read("DEVICE_NAME", device_name);
}
//开始
void startRun(const char* ip,int port){
//创建事件驱动句柄
baseEvent = event_base_new();
//创建socket类型的bufferevent
struct bufferevent* bufferEvent = bufferevent_socket_new(baseEvent, -1, 0);
//构造服务器地址
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(api_host.c_str());
sin.sin_port = htons(api_port);
//连接服务器
if( bufferevent_socket_connect(bufferEvent, (struct sockaddr*)&sin, sizeof(sin)) < 0){
perror("socket");
return;
}
//设置回调函数, 及回调函数的参数
bufferevent_setcb(bufferEvent, ReadEventCb, WriteEventCb, SignalEventCb,NULL);
//开始事件循环
event_base_dispatch(baseEvent);
//事件循环结束 资源清理
bufferevent_free(bufferEvent);
event_base_free(baseEvent);
}
//初始化API列表
void initApiList() {
client_api_list[API_DEVICE_BASE_INFO] = &handlerGetDeviceBaseInfo;
client_api_list[API_DEVICE_KEY_DOWN] = &handlerKeyDown;
}
int main(){
//加载API列表
initApiList();
//加载配置文件
setConfig(CONFIG_PATH);
//启动sockt
startRun(api_host.c_str(),api_port);
return 0;
}
<|endoftext|> |
<commit_before>/*===================================[ Algorithmen und Datenstrukturen]================================================================*
*
*
* @Version: 1.0.0
* @Author: Achim Grolimund ([email protected])
* @Date: 01.1.2017
*
* @Description:
*
* Beispiel:
*
* Anmerkung:
*
*
*==============================================[ EOF RDM ]=============================================================================*/
#define DEBUG
#include <bits/stdc++.h>
#include "C:/Users/achim/Documents/Programming/C++/HF-ICT-AAD/myFunks/myFunks/myfunks.h"
#include "C:/Users/achim/Documents/Programming/C++/HF-ICT-AAD/myFunks/myFunks/debug.h"
using namespace std;
int kgv(int,int);
int ggtRek(int,int);
int main()
{
cout<<kgv(12,18)<<endl; //36
return 0;
}
int kgv(int zahl1, int zahl2)
{
return (zahl1*zahl2)/ggtRek(zahl1, zahl2);
}
//<-- GGT Berechnen Rekursiv -->
int ggtRek(int a, int b){
if(b==0) return a;
return ggtRek(b,a%b);
}
<commit_msg>update<commit_after>/*===================================[ Algorithmen und Datenstrukturen]================================================================*
*
*
* @Version: 1.0.0
* @Author: Achim Grolimund ([email protected])
* @Date: 01.1.2017
*
* @Description:
*
* Beispiel:
*
* Anmerkung:
*
*
*==============================================[ EOF RDM ]=============================================================================*/
#define DEBUG
#include <bits/stdc++.h>
#include "C:/Users/achim/Documents/Programming/C++/HF-ICT-AAD/myFunks/myFunks/myfunks.h"
#include "C:/Users/achim/Documents/Programming/C++/HF-ICT-AAD/myFunks/myFunks/debug.h"
using namespace std;
int kgv(int,int);
int ggtRek(int,int);
int main()
{
auto start = myFunks::myTime::start();
std::this_thread::sleep_for (std::chrono::seconds(1));
cout<<kgv(12,18)<<endl; //36
myFunks::myTime::stop(start);
return 0;
}
int kgv(int zahl1, int zahl2)
{
return (zahl1*zahl2)/ggtRek(zahl1, zahl2);
}
//<-- GGT Berechnen Rekursiv -->
int ggtRek(int a, int b){
if(b==0) return a;
return ggtRek(b,a%b);
}
<|endoftext|> |
<commit_before>#include "distributions/joint_GMM.h"
#include "distributions/joint_gaussian.h"
#include "vector"
#include "bmp_image.h"
#include "dataset/distr_array.h"
#include "io/edda_vtk_reader.h"
#include "io/edda_vtk_writer.h"
#include "io/edda_reader.h"
#include "io/edda_writer.h"
#include "distributions/histogram.h"
#include "dataset/distr_array.h"
using namespace edda;
using namespace std;
using namespace edda::dist;
//using image to test joint Gaussian GMM
int main()
{
//load testing image from disk
BMPImage image("test_img.bmp");
//down-sampled block size
int blockSize = 20;
int nVar = 3;//number of variables, rgb is 3 variables
int nGmmComp = 2;//number of Gaussian compoenents
//output image means and resampled image
BMPImage optImage("test_img.bmp");//output image, randomly give a image file
//number of row and col after down-sampleing
int dsVs = image.height / blockSize;
int dsUs = image.width / blockSize;
//Joint GMM array
shared_ary<JointGMM> array(new JointGMM[dsVs*dsUs], dsVs*dsUs);
thrust::default_random_engine rng;//random engine for getJointSample()
Real* varR = (Real*)malloc(sizeof(Real)*blockSize*blockSize);
Real* varG = (Real*)malloc(sizeof(Real)*blockSize*blockSize);
Real* varB = (Real*)malloc(sizeof(Real)*blockSize*blockSize);
//loop: go through each block
for (int dsV = 0; dsV < dsVs; dsV++){
for (int dsU = 0; dsU < dsUs; dsU++){
printf("%d %d\n", dsV, dsU);
//prepare training vectors to OpenCV EM
int cnt = 0;
for (int v = dsV*blockSize; v<(dsV + 1)*blockSize; v++) {//row
for (int u = dsU*blockSize; u<(dsU + 1)*blockSize; u++) {//col
varR[cnt] = (Real)(image.bitmapImage[(v*image.width + u) * 3 + 0]);
varG[cnt] = (Real)(image.bitmapImage[(v*image.width + u) * 3 + 1]);
varB[cnt] = (Real)(image.bitmapImage[(v*image.width + u) * 3 + 2]);
cnt++;
}
}
//EM in Edda
std::vector<Real*> trainSamples;
trainSamples.push_back(varR);
trainSamples.push_back(varG);
trainSamples.push_back(varB);
array[dsV*dsUs + dsU] = eddaComputeJointGMM(trainSamples, blockSize*blockSize, nGmmComp);
//resample this block and write to image
for (int i = 0; i < blockSize; i++){
for (int j = 0; j < blockSize; j++){
std::vector<Real> sample = getJointSample(array[dsV*dsUs + dsU], rng);
int rawV = dsV*blockSize + i;//u and v in the original image resolution
int rawU = dsU*blockSize + j;
//trim value to 0-255, it possible to sample any value from gaussian
//and store back to image buffer
for (int k = 0; k < nVar; k++){
if (sample[k] < 0) sample[k] = 0;
if (sample[k] > 255)sample[k] = 255;
optImage.bitmapImage[(rawV*image.width + rawU) * 3 + k] = sample[k];
}
}
}
}
}
//shared_ptr<Dataset<std::vector<Real>> > dataset = make_Dataset<std::vector<Real>>(
// new RegularCartesianGrid(1, 1, dsVs*dsUs),
// array
// );
// safe to free data, after constructing the distribution
free(varR);
free(varG);
free(varB);
//write three images to disk
optImage.writeImage(std::string("jointGMMTestOutput.bmp").c_str());//this is the output file name
std::cout << "Press any key to finish" << std::endl;
getchar();
}<commit_msg>Minor fix for test_jointGMM.cpp<commit_after>#include "distributions/joint_GMM.h"
#include "distributions/joint_gaussian.h"
#include "vector"
#include "bmp_image.h"
#include "dataset/distr_array.h"
#include "io/edda_vtk_reader.h"
#include "io/edda_vtk_writer.h"
#include "io/edda_reader.h"
#include "io/edda_writer.h"
#include "distributions/histogram.h"
#include "dataset/distr_array.h"
using namespace edda;
using namespace std;
using namespace edda::dist;
//using image to test joint Gaussian GMM
int main()
{
//load testing image from disk
BMPImage image("test_img.bmp");
//down-sampled block size
int blockSize = 20;
int nVar = 3;//number of variables, rgb is 3 variables
int nGmmComp = 2;//number of Gaussian compoenents
//output image means and resampled image
BMPImage optImage("test_img.bmp");//output image, randomly give a image file
//number of row and col after down-sampleing
int dsVs = image.height / blockSize;
int dsUs = image.width / blockSize;
//Joint GMM array
shared_ary<JointGMM> array(new JointGMM[dsVs*dsUs], dsVs*dsUs);
thrust::default_random_engine rng;//random engine for getJointSample()
Real* varR = (Real*)malloc(sizeof(Real)*blockSize*blockSize);
Real* varG = (Real*)malloc(sizeof(Real)*blockSize*blockSize);
Real* varB = (Real*)malloc(sizeof(Real)*blockSize*blockSize);
//loop: go through each block
for (int dsV = 0; dsV < dsVs; dsV++){
for (int dsU = 0; dsU < dsUs; dsU++){
printf("%d %d\n", dsV, dsU);
//prepare training vectors to OpenCV EM
int cnt = 0;
for (int v = dsV*blockSize; v<(dsV + 1)*blockSize; v++) {//row
for (int u = dsU*blockSize; u<(dsU + 1)*blockSize; u++) {//col
varR[cnt] = (Real)(image.bitmapImage[(v*image.width + u) * 3 + 0]);
varG[cnt] = (Real)(image.bitmapImage[(v*image.width + u) * 3 + 1]);
varB[cnt] = (Real)(image.bitmapImage[(v*image.width + u) * 3 + 2]);
cnt++;
}
}
//EM in Edda
std::vector<Real*> trainSamples;
trainSamples.push_back(varR);
trainSamples.push_back(varG);
trainSamples.push_back(varB);
array[dsV*dsUs + dsU] = eddaComputeJointGMM(trainSamples, blockSize*blockSize, nGmmComp);
//resample this block and write to image
for (int i = 0; i < blockSize; i++){
for (int j = 0; j < blockSize; j++){
std::vector<Real> sample = getJointSample(array[dsV*dsUs + dsU], rng);
int rawV = dsV*blockSize + i;//u and v in the original image resolution
int rawU = dsU*blockSize + j;
//trim value to 0-255, it possible to sample any value from gaussian
//and store back to image buffer
for (int k = 0; k < nVar; k++){
if (sample[k] < 0) sample[k] = 0;
if (sample[k] > 255)sample[k] = 255;
optImage.bitmapImage[(rawV*image.width + rawU) * 3 + k] = sample[k];
}
}
}
}
}
//shared_ptr<Dataset<std::vector<Real>> > dataset = make_Dataset<std::vector<Real>>(
// new RegularCartesianGrid(1, 1, dsVs*dsUs),
// array
// );
// safe to free data, after constructing the distribution
free(varR);
free(varG);
free(varB);
//write three images to disk
optImage.writeImage(std::string("jointGMMTestOutputggg.bmp").c_str());//this is the output file name
std::cout << "Press any key to finish" << std::endl;
getchar();
}<|endoftext|> |
<commit_before>// $Id$
// Main authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007
/**************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
* See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for *
* full copyright notice. *
**************************************************************************/
#include <TInterpreter.h>
#include <TRint.h>
#include <TROOT.h>
#include <TSystem.h>
#include <TError.h>
#include <AliLog.h>
#include <TEveUtil.h>
#include <TEveManager.h>
#include <Getline.h>
int main(int argc, char **argv)
{
static const TEveException kEH("alieve::main");
if (gSystem->Getenv("ALICE_ROOT") == 0)
{
Error(kEH.Data(), "ALICE_ROOT is not defined, aborting.");
gSystem->Exit(1);
}
TString evedir(Form("%s/EVE", gSystem->Getenv("ALICE_ROOT")));
if (gSystem->AccessPathName(evedir) == kTRUE)
{
Error(kEH.Data(), "Directory $ALICE_ROOT/EVE does not exist.");
gSystem->Exit(1);
}
TString macPath(gROOT->GetMacroPath());
macPath += Form(":%s/macros", evedir.Data());
gInterpreter->AddIncludePath(evedir);
if (gSystem->Getenv("ALICE_ROOT") != 0)
{
macPath += Form(":%s/alice-macros", evedir.Data());
gInterpreter->AddIncludePath(Form("%s/EVE", gSystem->Getenv("ALICE_ROOT")));
gInterpreter->AddIncludePath(Form("%s/include", gSystem->Getenv("ALICE_ROOT")));
gInterpreter->AddIncludePath(gSystem->Getenv("ALICE_ROOT"));
}
gROOT->SetMacroPath(macPath);
// How to hadle AliLog properly?
AliLog* log = new AliLog;
TRint app("App", &argc, argv);
TEveManager::Create();
gEve->RegisterGeometryAlias("Default", Form("%s/alice-data/alice_fullgeo.root", evedir.Data()));
app.Run(); // Never returns.
delete log;
return 0;
}
<commit_msg>By default, propagate picked element to its projectable.<commit_after>// $Id$
// Main authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007
/**************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
* See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for *
* full copyright notice. *
**************************************************************************/
#include <TInterpreter.h>
#include <TRint.h>
#include <TROOT.h>
#include <TSystem.h>
#include <TError.h>
#include <AliLog.h>
#include <TEveUtil.h>
#include <TEveManager.h>
#include <TEveSelection.h>
#include <Getline.h>
int main(int argc, char **argv)
{
static const TEveException kEH("alieve::main");
if (gSystem->Getenv("ALICE_ROOT") == 0)
{
Error(kEH.Data(), "ALICE_ROOT is not defined, aborting.");
gSystem->Exit(1);
}
TString evedir(Form("%s/EVE", gSystem->Getenv("ALICE_ROOT")));
if (gSystem->AccessPathName(evedir) == kTRUE)
{
Error(kEH.Data(), "Directory $ALICE_ROOT/EVE does not exist.");
gSystem->Exit(1);
}
TString macPath(gROOT->GetMacroPath());
macPath += Form(":%s/macros", evedir.Data());
gInterpreter->AddIncludePath(evedir);
if (gSystem->Getenv("ALICE_ROOT") != 0)
{
macPath += Form(":%s/alice-macros", evedir.Data());
gInterpreter->AddIncludePath(Form("%s/EVE", gSystem->Getenv("ALICE_ROOT")));
gInterpreter->AddIncludePath(Form("%s/include", gSystem->Getenv("ALICE_ROOT")));
gInterpreter->AddIncludePath(gSystem->Getenv("ALICE_ROOT"));
}
gROOT->SetMacroPath(macPath);
// How to hadle AliLog properly?
AliLog* log = new AliLog;
TRint app("App", &argc, argv);
TEveManager::Create();
gEve->GetSelection()->SetPickToSelect(TEveSelection::kPS_Projectable);
gEve->GetHighlight()->SetPickToSelect(TEveSelection::kPS_Projectable);
gEve->RegisterGeometryAlias("Default", Form("%s/alice-data/alice_fullgeo.root", evedir.Data()));
app.Run(); // Never returns.
delete log;
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "BinaryTree.hpp"
using namespace std;
int main(int argc, char **argv)
{
Lista<int> pre, in, post;
pre.insertar(10,1);
pre.insertar(20,2);
pre.insertar(40,3);
pre.insertar(80,4);
pre.insertar(50,5);
pre.insertar(90,6);
pre.insertar(30,7);
pre.insertar(60,8);
pre.insertar(70,9);
pre.insertar(100,10);
pre.insertar(110,11);
pre.insertar(120,12);
in.insertar(80,1);
in.insertar(40,2);
in.insertar(20,3);
in.insertar(50,4);
in.insertar(90,5);
in.insertar(10,6);
in.insertar(60,7);
in.insertar(30,8);
in.insertar(100,9);
in.insertar(70,10);
in.insertar(110,11);
in.insertar(120,12);
post.insertar(80,1);
post.insertar(40,2);
post.insertar(90,3);
post.insertar(50,4);
post.insertar(20,5);
post.insertar(60,6);
post.insertar(100,7);
post.insertar(120,8);
post.insertar(110,9);
post.insertar(70,10);
post.insertar(30,11);
post.insertar(10,12);
BinaryTree<int> tree(pre, in, preorden);
BinaryTree<int> tree2(post, in, postorden);
return 0;
}
<commit_msg>Test case changed<commit_after>#include <iostream>
#include "BinaryTree.hpp"
using namespace std;
int main(int argc, char **argv)
{
Lista<int> pre, in, post;
pre.insertar(10,1);
pre.insertar(20,2);
pre.insertar(40,3);
pre.insertar(80,4);
pre.insertar(50,5);
pre.insertar(90,6);
pre.insertar(30,7);
pre.insertar(60,8);
pre.insertar(70,9);
pre.insertar(100,10);
pre.insertar(110,11);
pre.insertar(120,12);
in.insertar(80,1);
in.insertar(40,2);
in.insertar(20,3);
in.insertar(50,4);
in.insertar(90,5);
in.insertar(10,6);
in.insertar(60,7);
in.insertar(30,8);
in.insertar(100,9);
in.insertar(70,10);
in.insertar(110,11);
in.insertar(120,12);
post.insertar(80,1);
post.insertar(40,2);
post.insertar(90,3);
post.insertar(50,4);
post.insertar(20,5);
post.insertar(60,6);
post.insertar(100,7);
post.insertar(120,8);
post.insertar(110,9);
post.insertar(70,10);
post.insertar(30,11);
post.insertar(10,12);
BinaryTree<int> tree(pre, in, preorden);
BinaryTree<int> tree2 = tree.getRight();
tree2.print(preorden);
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Fix camera lurch on unfocused click and drag<commit_after><|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#ifndef INCLUDED_SIMPLEMAPI_HXX
#define INCLUDED_SIMPLEMAPI_HXX
#define WIN32_LEAN_AND_MEAN
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#include <mapi.h>
#ifndef __MINGW32__
#include <mapix.h>
#endif
#if defined _MSC_VER
#pragma warning(pop)
#endif
class CSimpleMapi
{
public:
/**
@throws std::runtime_error
if either the mapi32.dll could not be loaded at all
or necessary function exports are missing
*/
CSimpleMapi(); // throws std::runtime_error;
~CSimpleMapi();
ULONG MAPILogon(
ULONG ulUIParam,
LPTSTR lpszProfileName,
LPTSTR lpszPassword,
FLAGS flFlags,
ULONG ulReserved,
LPLHANDLE lplhSession );
ULONG MAPILogoff(
LHANDLE lhSession,
ULONG ulUIParam,
FLAGS flFlags,
ULONG ulReserved );
ULONG MAPISendMail(
LHANDLE lhSession,
ULONG ulUIParam,
lpMapiMessage lpMessage,
FLAGS flFlags,
ULONG ulReserved );
private:
HMODULE m_hMapiDll;
LPMAPILOGON m_lpfnMapiLogon;
LPMAPILOGOFF m_lpfnMapiLogoff;
LPMAPISENDMAIL m_lpfnMapiSendMail;
};
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fix shell build with Win8 SDK<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#ifndef INCLUDED_SIMPLEMAPI_HXX
#define INCLUDED_SIMPLEMAPI_HXX
#define WIN32_LEAN_AND_MEAN
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#include <mapi.h>
#ifndef __MINGW32__
#if NTDDI_VERSION < NTDDI_WIN8
#include <mapix.h>
#endif
#endif
#if defined _MSC_VER
#pragma warning(pop)
#endif
class CSimpleMapi
{
public:
/**
@throws std::runtime_error
if either the mapi32.dll could not be loaded at all
or necessary function exports are missing
*/
CSimpleMapi(); // throws std::runtime_error;
~CSimpleMapi();
ULONG MAPILogon(
ULONG ulUIParam,
LPTSTR lpszProfileName,
LPTSTR lpszPassword,
FLAGS flFlags,
ULONG ulReserved,
LPLHANDLE lplhSession );
ULONG MAPILogoff(
LHANDLE lhSession,
ULONG ulUIParam,
FLAGS flFlags,
ULONG ulReserved );
ULONG MAPISendMail(
LHANDLE lhSession,
ULONG ulUIParam,
lpMapiMessage lpMessage,
FLAGS flFlags,
ULONG ulReserved );
private:
HMODULE m_hMapiDll;
LPMAPILOGON m_lpfnMapiLogon;
LPMAPILOGOFF m_lpfnMapiLogoff;
LPMAPISENDMAIL m_lpfnMapiSendMail;
};
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#pragma once
#include "interrupted_exception.hpp"
namespace kumori
{
class sync : boost::noncopyable
{
public:
sync(boost::asio::io_service& service, const std::function<void()>& entry_point, std::size_t stack_size)
: entry_point_(entry_point)
, timer_(service)
, context_(&sync::callback)
{
}
~sync()
{
}
void resume()
{
std::lock_guard<std::mutex> lock(mutex_);
current_impl() = this;
context_ = std::get<0>(context_(this));
}
void suspend()
{
current_impl() = nullptr;
BOOST_ASSERT(!mutex_.try_lock());
BOOST_ASSERT(original_context_);
original_context_ = std::get<0>(original_context_(nullptr));
}
template <class Callback>
void suspend_for(const boost::posix_time::time_duration& timeout, Callback&& cancel)
{
timer_.expires_from_now(timeout);
timer_.async_wait(
[&](const boost::system::error_code&)
{
resume();
});
suspend();
timer_.cancel();
cancel();
suspend();
if (interrupted_)
BOOST_THROW_EXCEPTION(interrupted_exception());
}
void interrupt()
{
interrupted_ = true;
timer_.cancel();
}
static sync& current()
{
BOOST_ASSERT(current_impl());
return *current_impl();
}
private:
static boost::context::execution_context<sync*> callback(boost::context::execution_context<sync*> context, sync* s)
{
return s->run(std::move(context));
}
boost::context::execution_context<sync*> run(boost::context::execution_context<sync*> context)
{
original_context_ = std::move(context);
try
{
entry_point_();
}
catch (boost::context::detail::forced_unwind&)
{
throw;
}
catch (...)
{
}
return std::move(original_context_);
}
static sync*& current_impl()
{
thread_local sync* s = nullptr;
return s;
}
std::function<void()> entry_point_;
std::mutex mutex_;
boost::asio::deadline_timer timer_;
std::atomic<bool> interrupted_{ false };
boost::context::execution_context<sync*> context_;
boost::context::execution_context<sync*> original_context_;
};
}
<commit_msg>Fix stack_size problem<commit_after>#pragma once
#include "interrupted_exception.hpp"
namespace kumori
{
class sync : boost::noncopyable
{
public:
sync(boost::asio::io_service& service, const std::function<void()>& entry_point, std::size_t stack_size)
: entry_point_(entry_point)
, timer_(service)
, stack_(stack_size)
, context_(std::allocator_arg_t(), stack_, &sync::callback)
{
}
~sync()
{
}
void resume()
{
std::lock_guard<std::mutex> lock(mutex_);
current_impl() = this;
context_ = std::get<0>(context_(this));
}
void suspend()
{
current_impl() = nullptr;
BOOST_ASSERT(!mutex_.try_lock());
BOOST_ASSERT(original_context_);
original_context_ = std::get<0>(original_context_(nullptr));
}
template <class Callback>
void suspend_for(const boost::posix_time::time_duration& timeout, Callback&& cancel)
{
timer_.expires_from_now(timeout);
timer_.async_wait(
[&](const boost::system::error_code&)
{
resume();
});
suspend();
timer_.cancel();
cancel();
suspend();
if (interrupted_)
BOOST_THROW_EXCEPTION(interrupted_exception());
}
void interrupt()
{
interrupted_ = true;
timer_.cancel();
}
static sync& current()
{
BOOST_ASSERT(current_impl());
return *current_impl();
}
private:
static boost::context::execution_context<sync*> callback(boost::context::execution_context<sync*> context, sync* s)
{
return s->run(std::move(context));
}
boost::context::execution_context<sync*> run(boost::context::execution_context<sync*> context)
{
original_context_ = std::move(context);
try
{
entry_point_();
}
catch (boost::context::detail::forced_unwind&)
{
throw;
}
catch (...)
{
}
return std::move(original_context_);
}
static sync*& current_impl()
{
thread_local sync* s = nullptr;
return s;
}
std::function<void()> entry_point_;
std::mutex mutex_;
boost::asio::deadline_timer timer_;
std::atomic<bool> interrupted_{ false };
boost::context::protected_fixedsize_stack stack_;
boost::context::execution_context<sync*> context_;
boost::context::execution_context<sync*> original_context_;
};
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2008, Arvid Norberg
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 author 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 "libtorrent/session.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/file_pool.hpp"
#include "libtorrent/storage.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/create_torrent.hpp"
#include "libtorrent/thread.hpp"
#include <boost/tuple/tuple.hpp>
#include <fstream>
#include <iostream>
#include "test.hpp"
#include "setup_transfer.hpp"
using namespace libtorrent;
// proxy: 0=none, 1=socks4, 2=socks5, 3=socks5_pw 4=http 5=http_pw
void test_transfer(boost::intrusive_ptr<torrent_info> torrent_file
, int proxy, int port, char const* protocol, bool url_seed, bool chunked_encoding)
{
using namespace libtorrent;
session ses(fingerprint(" ", 0,0,0,0), 0);
session_settings settings;
settings.max_queued_disk_bytes = 256 * 1024;
ses.set_settings(settings);
ses.set_alert_mask(~alert::progress_notification);
ses.listen_on(std::make_pair(51000, 52000));
error_code ec;
remove_all("./tmp2_web_seed", ec);
char const* test_name[] = {"no", "SOCKS4", "SOCKS5", "SOCKS5 password", "HTTP", "HTTP password"};
fprintf(stderr, "\n\n ==== TESTING === proxy: %s ==== protocol: %s ==== seed: %s === transfer-encoding: %s\n\n\n"
, test_name[proxy], protocol, url_seed ? "URL seed" : "HTTP seed", chunked_encoding ? "chunked": "none");
if (proxy)
{
start_proxy(8002, proxy);
proxy_settings ps;
ps.hostname = "127.0.0.1";
ps.port = 8002;
ps.username = "testuser";
ps.password = "testpass";
ps.type = (proxy_settings::proxy_type)proxy;
ses.set_proxy(ps);
}
add_torrent_params p;
p.auto_managed = false;
p.paused = false;
p.ti = torrent_file;
p.save_path = "./tmp2_web_seed";
p.storage_mode = storage_mode_compact;
torrent_handle th = ses.add_torrent(p, ec);
std::vector<announce_entry> empty;
th.replace_trackers(empty);
const size_type total_size = torrent_file->total_size();
float rate_sum = 0.f;
float ses_rate_sum = 0.f;
cache_status cs;
for (int i = 0; i < 30; ++i)
{
torrent_status s = th.status();
session_status ss = ses.status();
rate_sum += s.download_payload_rate;
ses_rate_sum += ss.payload_download_rate;
cs = ses.get_cache_status();
if (cs.blocks_read < 1) cs.blocks_read = 1;
if (cs.blocks_written < 1) cs.blocks_written = 1;
std::cerr << (s.progress * 100.f) << " %"
<< " torrent rate: " << (s.download_rate / 1000.f) << " kB/s"
<< " session rate: " << (ss.download_rate / 1000.f) << " kB/s"
<< " session total: " << ss.total_payload_download
<< " torrent total: " << s.total_payload_download
<< " rate sum:" << ses_rate_sum
<< " cache: " << cs.cache_size
<< " rcache: " << cs.read_cache_size
<< " buffers: " << cs.total_used_buffers
<< std::endl;
print_alerts(ses, " >> ses");
if (s.is_seeding /* && ss.download_rate == 0.f*/)
{
TEST_EQUAL(s.total_payload_download - s.total_redundant_bytes, total_size);
// we need to sleep here a bit to let the session sync with the torrent stats
test_sleep(1000);
TEST_EQUAL(ses.status().total_payload_download - ses.status().total_redundant_bytes
, total_size);
break;
}
test_sleep(500);
}
TEST_EQUAL(cs.cache_size, 0);
TEST_EQUAL(cs.total_used_buffers, 0);
std::cerr << "total_size: " << total_size
<< " rate_sum: " << rate_sum
<< " session_rate_sum: " << ses_rate_sum
<< " session total download: " << ses.status().total_payload_download
<< " torrent total download: " << th.status().total_payload_download
<< " redundant: " << th.status().total_redundant_bytes
<< std::endl;
// the rates for each second should sum up to the total, with a 10% error margin
// TEST_CHECK(fabs(rate_sum - total_size) < total_size * .1f);
// TEST_CHECK(fabs(ses_rate_sum - total_size) < total_size * .1f);
TEST_CHECK(th.status().is_seeding);
if (proxy) stop_proxy(8002);
TEST_CHECK(exists(combine_path("./tmp2_web_seed", torrent_file->file_at(0).path)));
remove_all("./tmp2_web_seed", ec);
}
void save_file(char const* filename, char const* data, int size)
{
error_code ec;
file out(filename, file::write_only, ec);
TEST_CHECK(!ec);
if (ec)
{
fprintf(stderr, "ERROR opening file '%s': %s\n", filename, ec.message().c_str());
return;
}
file::iovec_t b = { (void*)data, size };
out.writev(0, &b, 1, ec);
TEST_CHECK(!ec);
if (ec)
{
fprintf(stderr, "ERROR writing file '%s': %s\n", filename, ec.message().c_str());
return;
}
}
sha1_hash file_hash(std::string const& name)
{
std::vector<char> buf;
load_file(name, buf);
if (buf.empty()) return sha1_hash(0);
hasher h(&buf[0], buf.size());
return h.final();
}
// test_url_seed determines whether to use url-seed or http-seed
int run_suite(char const* protocol, bool test_url_seed, bool chunked_encoding)
{
using namespace libtorrent;
error_code ec;
create_directories("./tmp1_web_seed/test_torrent_dir", ec);
file_storage fs;
std::srand(10);
int piece_size = 16;
if (test_url_seed)
{
int file_sizes[] =
{ 5, 16 - 5, 16, 17, 10, 30, 30, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
,1,1,1,1,1,1,13,65,34,75,2,3,4,5,23,9,43,4,43,6, 4};
char random_data[300000];
for (int i = 0; i != sizeof(file_sizes)/sizeof(file_sizes[0]); ++i)
{
std::generate(random_data, random_data + sizeof(random_data), &std::rand);
char filename[200];
snprintf(filename, sizeof(filename), "./tmp1_web_seed/test_torrent_dir/test%d", i);
save_file(filename, random_data, file_sizes[i]);
}
add_files(fs, "./tmp1_web_seed/test_torrent_dir");
}
else
{
piece_size = 64 * 1024;
char random_data[64 * 1024 * 25];
std::generate(random_data, random_data + sizeof(random_data), &std::rand);
save_file("./tmp1_web_seed/seed", random_data, sizeof(random_data));
fs.add_file("seed", sizeof(random_data));
}
int port = start_web_server(strcmp(protocol, "https") == 0, chunked_encoding);
libtorrent::create_torrent t(fs, piece_size, 0, libtorrent::create_torrent::calculate_file_hashes);
char tmp[512];
if (test_url_seed)
{
snprintf(tmp, sizeof(tmp), "%s://127.0.0.1:%d/tmp1_web_seed", protocol, port);
t.add_url_seed(tmp);
}
else
{
snprintf(tmp, sizeof(tmp), "http://127.0.0.1:%d/seed", port);
t.add_http_seed(tmp);
}
// calculate the hash for all pieces
set_piece_hashes(t, "./tmp1_web_seed", ec);
if (ec)
{
fprintf(stderr, "error creating hashes for test torrent: %s\n"
, ec.message().c_str());
TEST_CHECK(false);
return 0;
}
std::vector<char> buf;
bencode(std::back_inserter(buf), t.generate());
boost::intrusive_ptr<torrent_info> torrent_file(new torrent_info(&buf[0], buf.size(), ec));
// verify that the file hashes are correct
for (int i = 0; i < torrent_file->num_files(); ++i)
{
TEST_CHECK(torrent_file->file_at(i).filehash);
sha1_hash h1 = *torrent_file->file_at(i).filehash;
sha1_hash h2 = file_hash(combine_path("./tmp1_web_seed", torrent_file->file_at(i).path));
fprintf(stderr, "%s: %s == %s\n", torrent_file->file_at(i).path.c_str()
, to_hex(h1.to_string()).c_str(), to_hex(h2.to_string()).c_str());
TEST_EQUAL(h1, h2);
}
for (int i = 0; i < 6; ++i)
test_transfer(torrent_file, i, port, protocol, test_url_seed, chunked_encoding);
if (test_url_seed)
{
torrent_file->rename_file(0, "./tmp2_web_seed/test_torrent_dir/renamed_test1");
test_transfer(torrent_file, 0, port, protocol, test_url_seed, chunked_encoding);
}
stop_web_server();
remove_all("./tmp1_web_seed", ec);
return 0;
}
int test_main()
{
int ret = 0;
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
#ifdef TORRENT_USE_OPENSSL
run_suite("https", i, j);
#endif
run_suite("http", i, j);
}
}
return ret;
}
<commit_msg>don't allocate too much memory on the stack in web seed test<commit_after>/*
Copyright (c) 2008, Arvid Norberg
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 author 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 "libtorrent/session.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/file_pool.hpp"
#include "libtorrent/storage.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/create_torrent.hpp"
#include "libtorrent/thread.hpp"
#include <boost/tuple/tuple.hpp>
#include <fstream>
#include <iostream>
#include "test.hpp"
#include "setup_transfer.hpp"
using namespace libtorrent;
// proxy: 0=none, 1=socks4, 2=socks5, 3=socks5_pw 4=http 5=http_pw
void test_transfer(boost::intrusive_ptr<torrent_info> torrent_file
, int proxy, int port, char const* protocol, bool url_seed, bool chunked_encoding)
{
using namespace libtorrent;
session ses(fingerprint(" ", 0,0,0,0), 0);
session_settings settings;
settings.max_queued_disk_bytes = 256 * 1024;
ses.set_settings(settings);
ses.set_alert_mask(~alert::progress_notification);
ses.listen_on(std::make_pair(51000, 52000));
error_code ec;
remove_all("./tmp2_web_seed", ec);
char const* test_name[] = {"no", "SOCKS4", "SOCKS5", "SOCKS5 password", "HTTP", "HTTP password"};
fprintf(stderr, "\n\n ==== TESTING === proxy: %s ==== protocol: %s ==== seed: %s === transfer-encoding: %s\n\n\n"
, test_name[proxy], protocol, url_seed ? "URL seed" : "HTTP seed", chunked_encoding ? "chunked": "none");
if (proxy)
{
start_proxy(8002, proxy);
proxy_settings ps;
ps.hostname = "127.0.0.1";
ps.port = 8002;
ps.username = "testuser";
ps.password = "testpass";
ps.type = (proxy_settings::proxy_type)proxy;
ses.set_proxy(ps);
}
add_torrent_params p;
p.auto_managed = false;
p.paused = false;
p.ti = torrent_file;
p.save_path = "./tmp2_web_seed";
p.storage_mode = storage_mode_compact;
torrent_handle th = ses.add_torrent(p, ec);
std::vector<announce_entry> empty;
th.replace_trackers(empty);
const size_type total_size = torrent_file->total_size();
float rate_sum = 0.f;
float ses_rate_sum = 0.f;
cache_status cs;
for (int i = 0; i < 30; ++i)
{
torrent_status s = th.status();
session_status ss = ses.status();
rate_sum += s.download_payload_rate;
ses_rate_sum += ss.payload_download_rate;
cs = ses.get_cache_status();
if (cs.blocks_read < 1) cs.blocks_read = 1;
if (cs.blocks_written < 1) cs.blocks_written = 1;
std::cerr << (s.progress * 100.f) << " %"
<< " torrent rate: " << (s.download_rate / 1000.f) << " kB/s"
<< " session rate: " << (ss.download_rate / 1000.f) << " kB/s"
<< " session total: " << ss.total_payload_download
<< " torrent total: " << s.total_payload_download
<< " rate sum:" << ses_rate_sum
<< " cache: " << cs.cache_size
<< " rcache: " << cs.read_cache_size
<< " buffers: " << cs.total_used_buffers
<< std::endl;
print_alerts(ses, " >> ses");
if (s.is_seeding /* && ss.download_rate == 0.f*/)
{
TEST_EQUAL(s.total_payload_download - s.total_redundant_bytes, total_size);
// we need to sleep here a bit to let the session sync with the torrent stats
test_sleep(1000);
TEST_EQUAL(ses.status().total_payload_download - ses.status().total_redundant_bytes
, total_size);
break;
}
test_sleep(500);
}
TEST_EQUAL(cs.cache_size, 0);
TEST_EQUAL(cs.total_used_buffers, 0);
std::cerr << "total_size: " << total_size
<< " rate_sum: " << rate_sum
<< " session_rate_sum: " << ses_rate_sum
<< " session total download: " << ses.status().total_payload_download
<< " torrent total download: " << th.status().total_payload_download
<< " redundant: " << th.status().total_redundant_bytes
<< std::endl;
// the rates for each second should sum up to the total, with a 10% error margin
// TEST_CHECK(fabs(rate_sum - total_size) < total_size * .1f);
// TEST_CHECK(fabs(ses_rate_sum - total_size) < total_size * .1f);
TEST_CHECK(th.status().is_seeding);
if (proxy) stop_proxy(8002);
TEST_CHECK(exists(combine_path("./tmp2_web_seed", torrent_file->file_at(0).path)));
remove_all("./tmp2_web_seed", ec);
}
void save_file(char const* filename, char const* data, int size)
{
error_code ec;
file out(filename, file::write_only, ec);
TEST_CHECK(!ec);
if (ec)
{
fprintf(stderr, "ERROR opening file '%s': %s\n", filename, ec.message().c_str());
return;
}
file::iovec_t b = { (void*)data, size };
out.writev(0, &b, 1, ec);
TEST_CHECK(!ec);
if (ec)
{
fprintf(stderr, "ERROR writing file '%s': %s\n", filename, ec.message().c_str());
return;
}
}
sha1_hash file_hash(std::string const& name)
{
std::vector<char> buf;
load_file(name, buf);
if (buf.empty()) return sha1_hash(0);
hasher h(&buf[0], buf.size());
return h.final();
}
// test_url_seed determines whether to use url-seed or http-seed
int run_suite(char const* protocol, bool test_url_seed, bool chunked_encoding)
{
using namespace libtorrent;
error_code ec;
create_directories("./tmp1_web_seed/test_torrent_dir", ec);
file_storage fs;
std::srand(10);
int piece_size = 16;
if (test_url_seed)
{
int file_sizes[] =
{ 5, 16 - 5, 16, 17, 10, 30, 30, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
,1,1,1,1,1,1,13,65,34,75,2,3,4,5,23,9,43,4,43,6, 4};
char* random_data = (char*)malloc(300000);
for (int i = 0; i != sizeof(file_sizes)/sizeof(file_sizes[0]); ++i)
{
std::generate(random_data, random_data + 300000, &std::rand);
char filename[200];
snprintf(filename, sizeof(filename), "./tmp1_web_seed/test_torrent_dir/test%d", i);
save_file(filename, random_data, file_sizes[i]);
}
add_files(fs, "./tmp1_web_seed/test_torrent_dir");
free(random_data);
}
else
{
piece_size = 64 * 1024;
char* random_data = (char*)malloc(64 * 1024 * 25);
std::generate(random_data, random_data + 64 * 1024 * 25, &std::rand);
save_file("./tmp1_web_seed/seed", random_data, 64 * 1024 * 25);
fs.add_file("seed", 64 * 1024 * 25);
free(random_data);
}
int port = start_web_server(strcmp(protocol, "https") == 0, chunked_encoding);
libtorrent::create_torrent t(fs, piece_size, 0, libtorrent::create_torrent::calculate_file_hashes);
char tmp[512];
if (test_url_seed)
{
snprintf(tmp, sizeof(tmp), "%s://127.0.0.1:%d/tmp1_web_seed", protocol, port);
t.add_url_seed(tmp);
}
else
{
snprintf(tmp, sizeof(tmp), "http://127.0.0.1:%d/seed", port);
t.add_http_seed(tmp);
}
// calculate the hash for all pieces
set_piece_hashes(t, "./tmp1_web_seed", ec);
if (ec)
{
fprintf(stderr, "error creating hashes for test torrent: %s\n"
, ec.message().c_str());
TEST_CHECK(false);
return 0;
}
std::vector<char> buf;
bencode(std::back_inserter(buf), t.generate());
boost::intrusive_ptr<torrent_info> torrent_file(new torrent_info(&buf[0], buf.size(), ec));
// verify that the file hashes are correct
for (int i = 0; i < torrent_file->num_files(); ++i)
{
TEST_CHECK(torrent_file->file_at(i).filehash);
sha1_hash h1 = *torrent_file->file_at(i).filehash;
sha1_hash h2 = file_hash(combine_path("./tmp1_web_seed", torrent_file->file_at(i).path));
fprintf(stderr, "%s: %s == %s\n", torrent_file->file_at(i).path.c_str()
, to_hex(h1.to_string()).c_str(), to_hex(h2.to_string()).c_str());
TEST_EQUAL(h1, h2);
}
for (int i = 0; i < 6; ++i)
test_transfer(torrent_file, i, port, protocol, test_url_seed, chunked_encoding);
if (test_url_seed)
{
torrent_file->rename_file(0, "./tmp2_web_seed/test_torrent_dir/renamed_test1");
test_transfer(torrent_file, 0, port, protocol, test_url_seed, chunked_encoding);
}
stop_web_server();
remove_all("./tmp1_web_seed", ec);
return 0;
}
int test_main()
{
int ret = 0;
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
#ifdef TORRENT_USE_OPENSSL
run_suite("https", i, j);
#endif
run_suite("http", i, j);
}
}
return ret;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2008, Arvid Norberg
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 author 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 "libtorrent/session.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/file_pool.hpp"
#include "libtorrent/storage.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/create_torrent.hpp"
#include "libtorrent/thread.hpp"
#include <boost/tuple/tuple.hpp>
#include <fstream>
#include <iostream>
#include "test.hpp"
#include "setup_transfer.hpp"
using namespace libtorrent;
// proxy: 0=none, 1=socks4, 2=socks5, 3=socks5_pw 4=http 5=http_pw
void test_transfer(boost::intrusive_ptr<torrent_info> torrent_file
, int proxy, int port, char const* protocol, bool url_seed, bool chunked_encoding)
{
using namespace libtorrent;
session ses(fingerprint(" ", 0,0,0,0), 0);
session_settings settings;
settings.max_queued_disk_bytes = 256 * 1024;
ses.set_settings(settings);
ses.set_alert_mask(~alert::progress_notification);
ses.listen_on(std::make_pair(51000, 52000));
error_code ec;
remove_all("./tmp2_web_seed", ec);
char const* test_name[] = {"no", "SOCKS4", "SOCKS5", "SOCKS5 password", "HTTP", "HTTP password"};
fprintf(stderr, "\n\n ==== TESTING === proxy: %s ==== protocol: %s ==== seed: %s === transfer-encoding: %s\n\n\n"
, test_name[proxy], protocol, url_seed ? "URL seed" : "HTTP seed", chunked_encoding ? "chunked": "none");
if (proxy)
{
start_proxy(8002, proxy);
proxy_settings ps;
ps.hostname = "127.0.0.1";
ps.port = 8002;
ps.username = "testuser";
ps.password = "testpass";
ps.type = (proxy_settings::proxy_type)proxy;
ses.set_proxy(ps);
}
add_torrent_params p;
p.auto_managed = false;
p.paused = false;
p.ti = torrent_file;
p.save_path = "./tmp2_web_seed";
p.storage_mode = storage_mode_compact;
torrent_handle th = ses.add_torrent(p, ec);
std::vector<announce_entry> empty;
th.replace_trackers(empty);
const size_type total_size = torrent_file->total_size();
float rate_sum = 0.f;
float ses_rate_sum = 0.f;
cache_status cs;
for (int i = 0; i < 30; ++i)
{
torrent_status s = th.status();
session_status ss = ses.status();
rate_sum += s.download_payload_rate;
ses_rate_sum += ss.payload_download_rate;
cs = ses.get_cache_status();
if (cs.blocks_read < 1) cs.blocks_read = 1;
if (cs.blocks_written < 1) cs.blocks_written = 1;
std::cerr << (s.progress * 100.f) << " %"
<< " torrent rate: " << (s.download_rate / 1000.f) << " kB/s"
<< " session rate: " << (ss.download_rate / 1000.f) << " kB/s"
<< " session total: " << ss.total_payload_download
<< " torrent total: " << s.total_payload_download
<< " rate sum:" << ses_rate_sum
<< " cache: " << cs.cache_size
<< " rcache: " << cs.read_cache_size
<< " buffers: " << cs.total_used_buffers
<< std::endl;
print_alerts(ses, " >> ses");
if (s.is_seeding /* && ss.download_rate == 0.f*/)
{
TEST_EQUAL(s.total_payload_download - s.total_redundant_bytes, total_size);
// we need to sleep here a bit to let the session sync with the torrent stats
test_sleep(1000);
TEST_EQUAL(ses.status().total_payload_download - ses.status().total_redundant_bytes
, total_size);
break;
}
test_sleep(500);
}
TEST_EQUAL(cs.cache_size, 0);
TEST_EQUAL(cs.total_used_buffers, 0);
std::cerr << "total_size: " << total_size
<< " rate_sum: " << rate_sum
<< " session_rate_sum: " << ses_rate_sum
<< " session total download: " << ses.status().total_payload_download
<< " torrent total download: " << th.status().total_payload_download
<< " redundant: " << th.status().total_redundant_bytes
<< std::endl;
// the rates for each second should sum up to the total, with a 10% error margin
// TEST_CHECK(fabs(rate_sum - total_size) < total_size * .1f);
// TEST_CHECK(fabs(ses_rate_sum - total_size) < total_size * .1f);
TEST_CHECK(th.status().is_seeding);
if (proxy) stop_proxy(8002);
TEST_CHECK(exists(combine_path("./tmp2_web_seed", torrent_file->file_at(0).path)));
remove_all("./tmp2_web_seed", ec);
}
void save_file(char const* filename, char const* data, int size)
{
error_code ec;
file out(filename, file::write_only, ec);
TEST_CHECK(!ec);
if (ec)
{
fprintf(stderr, "ERROR opening file '%s': %s\n", filename, ec.message().c_str());
return;
}
file::iovec_t b = { (void*)data, size };
out.writev(0, &b, 1, ec);
TEST_CHECK(!ec);
if (ec)
{
fprintf(stderr, "ERROR writing file '%s': %s\n", filename, ec.message().c_str());
return;
}
}
sha1_hash file_hash(std::string const& name)
{
std::vector<char> buf;
load_file(name, buf);
if (buf.empty()) return sha1_hash(0);
hasher h(&buf[0], buf.size());
return h.final();
}
// test_url_seed determines whether to use url-seed or http-seed
int run_suite(char const* protocol, bool test_url_seed, bool chunked_encoding)
{
using namespace libtorrent;
error_code ec;
create_directories("./tmp1_web_seed/test_torrent_dir", ec);
file_storage fs;
std::srand(10);
int piece_size = 16;
if (test_url_seed)
{
int file_sizes[] =
{ 5, 16 - 5, 16, 17, 10, 30, 30, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
,1,1,1,1,1,1,13,65,34,75,2,3,4,5,23,9,43,4,43,6, 4};
char random_data[300000];
for (int i = 0; i != sizeof(file_sizes)/sizeof(file_sizes[0]); ++i)
{
std::generate(random_data, random_data + sizeof(random_data), &std::rand);
char filename[200];
snprintf(filename, sizeof(filename), "./tmp1_web_seed/test_torrent_dir/test%d", i);
save_file(filename, random_data, file_sizes[i]);
}
add_files(fs, "./tmp1_web_seed/test_torrent_dir");
}
else
{
piece_size = 64 * 1024;
char random_data[64 * 1024 * 25];
std::generate(random_data, random_data + sizeof(random_data), &std::rand);
save_file("./tmp1_web_seed/seed", random_data, sizeof(random_data));
fs.add_file("seed", sizeof(random_data));
}
int port = start_web_server(strcmp(protocol, "https") == 0, chunked_encoding);
libtorrent::create_torrent t(fs, piece_size, 0, libtorrent::create_torrent::calculate_file_hashes);
char tmp[512];
if (test_url_seed)
{
snprintf(tmp, sizeof(tmp), "%s://127.0.0.1:%d/tmp1_web_seed", protocol, port);
t.add_url_seed(tmp);
}
else
{
snprintf(tmp, sizeof(tmp), "http://127.0.0.1:%d/seed", port);
t.add_http_seed(tmp);
}
// calculate the hash for all pieces
set_piece_hashes(t, "./tmp1_web_seed", ec);
if (ec)
{
fprintf(stderr, "error creating hashes for test torrent: %s\n"
, ec.message().c_str());
TEST_CHECK(false);
return 0;
}
std::vector<char> buf;
bencode(std::back_inserter(buf), t.generate());
boost::intrusive_ptr<torrent_info> torrent_file(new torrent_info(&buf[0], buf.size(), ec));
// verify that the file hashes are correct
for (int i = 0; i < torrent_file->num_files(); ++i)
{
TEST_CHECK(torrent_file->file_at(i).filehash);
sha1_hash h1 = *torrent_file->file_at(i).filehash;
sha1_hash h2 = file_hash(combine_path("./tmp1_web_seed", torrent_file->file_at(i).path));
fprintf(stderr, "%s: %s == %s\n", torrent_file->file_at(i).path.c_str()
, to_hex(h1.to_string()).c_str(), to_hex(h2.to_string()).c_str());
TEST_EQUAL(h1, h2);
}
for (int i = 0; i < 6; ++i)
test_transfer(torrent_file, i, port, protocol, test_url_seed, chunked_encoding);
if (test_url_seed)
{
torrent_file->rename_file(0, "./tmp2_web_seed/test_torrent_dir/renamed_test1");
test_transfer(torrent_file, 0, port, protocol, test_url_seed, chunked_encoding);
}
stop_web_server();
remove_all("./tmp1_web_seed", ec);
return 0;
}
int test_main()
{
int ret = 0;
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
#ifdef TORRENT_USE_OPENSSL
run_suite("https", i, j);
#endif
run_suite("http", i, j);
}
}
return ret;
}
<commit_msg>don't allocate too much memory on the stack in web seed test<commit_after>/*
Copyright (c) 2008, Arvid Norberg
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 author 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 "libtorrent/session.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/file_pool.hpp"
#include "libtorrent/storage.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/create_torrent.hpp"
#include "libtorrent/thread.hpp"
#include <boost/tuple/tuple.hpp>
#include <fstream>
#include <iostream>
#include "test.hpp"
#include "setup_transfer.hpp"
using namespace libtorrent;
// proxy: 0=none, 1=socks4, 2=socks5, 3=socks5_pw 4=http 5=http_pw
void test_transfer(boost::intrusive_ptr<torrent_info> torrent_file
, int proxy, int port, char const* protocol, bool url_seed, bool chunked_encoding)
{
using namespace libtorrent;
session ses(fingerprint(" ", 0,0,0,0), 0);
session_settings settings;
settings.max_queued_disk_bytes = 256 * 1024;
ses.set_settings(settings);
ses.set_alert_mask(~alert::progress_notification);
ses.listen_on(std::make_pair(51000, 52000));
error_code ec;
remove_all("./tmp2_web_seed", ec);
char const* test_name[] = {"no", "SOCKS4", "SOCKS5", "SOCKS5 password", "HTTP", "HTTP password"};
fprintf(stderr, "\n\n ==== TESTING === proxy: %s ==== protocol: %s ==== seed: %s === transfer-encoding: %s\n\n\n"
, test_name[proxy], protocol, url_seed ? "URL seed" : "HTTP seed", chunked_encoding ? "chunked": "none");
if (proxy)
{
start_proxy(8002, proxy);
proxy_settings ps;
ps.hostname = "127.0.0.1";
ps.port = 8002;
ps.username = "testuser";
ps.password = "testpass";
ps.type = (proxy_settings::proxy_type)proxy;
ses.set_proxy(ps);
}
add_torrent_params p;
p.auto_managed = false;
p.paused = false;
p.ti = torrent_file;
p.save_path = "./tmp2_web_seed";
p.storage_mode = storage_mode_compact;
torrent_handle th = ses.add_torrent(p, ec);
std::vector<announce_entry> empty;
th.replace_trackers(empty);
const size_type total_size = torrent_file->total_size();
float rate_sum = 0.f;
float ses_rate_sum = 0.f;
cache_status cs;
for (int i = 0; i < 30; ++i)
{
torrent_status s = th.status();
session_status ss = ses.status();
rate_sum += s.download_payload_rate;
ses_rate_sum += ss.payload_download_rate;
cs = ses.get_cache_status();
if (cs.blocks_read < 1) cs.blocks_read = 1;
if (cs.blocks_written < 1) cs.blocks_written = 1;
std::cerr << (s.progress * 100.f) << " %"
<< " torrent rate: " << (s.download_rate / 1000.f) << " kB/s"
<< " session rate: " << (ss.download_rate / 1000.f) << " kB/s"
<< " session total: " << ss.total_payload_download
<< " torrent total: " << s.total_payload_download
<< " rate sum:" << ses_rate_sum
<< " cache: " << cs.cache_size
<< " rcache: " << cs.read_cache_size
<< " buffers: " << cs.total_used_buffers
<< std::endl;
print_alerts(ses, " >> ses");
if (s.is_seeding /* && ss.download_rate == 0.f*/)
{
TEST_EQUAL(s.total_payload_download - s.total_redundant_bytes, total_size);
// we need to sleep here a bit to let the session sync with the torrent stats
test_sleep(1000);
TEST_EQUAL(ses.status().total_payload_download - ses.status().total_redundant_bytes
, total_size);
break;
}
test_sleep(500);
}
TEST_EQUAL(cs.cache_size, 0);
TEST_EQUAL(cs.total_used_buffers, 0);
std::cerr << "total_size: " << total_size
<< " rate_sum: " << rate_sum
<< " session_rate_sum: " << ses_rate_sum
<< " session total download: " << ses.status().total_payload_download
<< " torrent total download: " << th.status().total_payload_download
<< " redundant: " << th.status().total_redundant_bytes
<< std::endl;
// the rates for each second should sum up to the total, with a 10% error margin
// TEST_CHECK(fabs(rate_sum - total_size) < total_size * .1f);
// TEST_CHECK(fabs(ses_rate_sum - total_size) < total_size * .1f);
TEST_CHECK(th.status().is_seeding);
if (proxy) stop_proxy(8002);
TEST_CHECK(exists(combine_path("./tmp2_web_seed", torrent_file->file_at(0).path)));
remove_all("./tmp2_web_seed", ec);
}
void save_file(char const* filename, char const* data, int size)
{
error_code ec;
file out(filename, file::write_only, ec);
TEST_CHECK(!ec);
if (ec)
{
fprintf(stderr, "ERROR opening file '%s': %s\n", filename, ec.message().c_str());
return;
}
file::iovec_t b = { (void*)data, size };
out.writev(0, &b, 1, ec);
TEST_CHECK(!ec);
if (ec)
{
fprintf(stderr, "ERROR writing file '%s': %s\n", filename, ec.message().c_str());
return;
}
}
sha1_hash file_hash(std::string const& name)
{
std::vector<char> buf;
load_file(name, buf);
if (buf.empty()) return sha1_hash(0);
hasher h(&buf[0], buf.size());
return h.final();
}
// test_url_seed determines whether to use url-seed or http-seed
int run_suite(char const* protocol, bool test_url_seed, bool chunked_encoding)
{
using namespace libtorrent;
error_code ec;
create_directories("./tmp1_web_seed/test_torrent_dir", ec);
file_storage fs;
std::srand(10);
int piece_size = 16;
if (test_url_seed)
{
int file_sizes[] =
{ 5, 16 - 5, 16, 17, 10, 30, 30, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
,1,1,1,1,1,1,13,65,34,75,2,3,4,5,23,9,43,4,43,6, 4};
char* random_data = (char*)malloc(300000);
for (int i = 0; i != sizeof(file_sizes)/sizeof(file_sizes[0]); ++i)
{
std::generate(random_data, random_data + 300000, &std::rand);
char filename[200];
snprintf(filename, sizeof(filename), "./tmp1_web_seed/test_torrent_dir/test%d", i);
save_file(filename, random_data, file_sizes[i]);
}
add_files(fs, "./tmp1_web_seed/test_torrent_dir");
free(random_data);
}
else
{
piece_size = 64 * 1024;
char* random_data = (char*)malloc(64 * 1024 * 25);
std::generate(random_data, random_data + 64 * 1024 * 25, &std::rand);
save_file("./tmp1_web_seed/seed", random_data, 64 * 1024 * 25);
fs.add_file("seed", 64 * 1024 * 25);
free(random_data);
}
int port = start_web_server(strcmp(protocol, "https") == 0, chunked_encoding);
libtorrent::create_torrent t(fs, piece_size, 0, libtorrent::create_torrent::calculate_file_hashes);
char tmp[512];
if (test_url_seed)
{
snprintf(tmp, sizeof(tmp), "%s://127.0.0.1:%d/tmp1_web_seed", protocol, port);
t.add_url_seed(tmp);
}
else
{
snprintf(tmp, sizeof(tmp), "http://127.0.0.1:%d/seed", port);
t.add_http_seed(tmp);
}
// calculate the hash for all pieces
set_piece_hashes(t, "./tmp1_web_seed", ec);
if (ec)
{
fprintf(stderr, "error creating hashes for test torrent: %s\n"
, ec.message().c_str());
TEST_CHECK(false);
return 0;
}
std::vector<char> buf;
bencode(std::back_inserter(buf), t.generate());
boost::intrusive_ptr<torrent_info> torrent_file(new torrent_info(&buf[0], buf.size(), ec));
// verify that the file hashes are correct
for (int i = 0; i < torrent_file->num_files(); ++i)
{
TEST_CHECK(torrent_file->file_at(i).filehash);
sha1_hash h1 = *torrent_file->file_at(i).filehash;
sha1_hash h2 = file_hash(combine_path("./tmp1_web_seed", torrent_file->file_at(i).path));
fprintf(stderr, "%s: %s == %s\n", torrent_file->file_at(i).path.c_str()
, to_hex(h1.to_string()).c_str(), to_hex(h2.to_string()).c_str());
TEST_EQUAL(h1, h2);
}
for (int i = 0; i < 6; ++i)
test_transfer(torrent_file, i, port, protocol, test_url_seed, chunked_encoding);
if (test_url_seed)
{
torrent_file->rename_file(0, "./tmp2_web_seed/test_torrent_dir/renamed_test1");
test_transfer(torrent_file, 0, port, protocol, test_url_seed, chunked_encoding);
}
stop_web_server();
remove_all("./tmp1_web_seed", ec);
return 0;
}
int test_main()
{
int ret = 0;
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
#ifdef TORRENT_USE_OPENSSL
run_suite("https", i, j);
#endif
run_suite("http", i, j);
}
}
return ret;
}
<|endoftext|> |
<commit_before>#include <davix.hpp>
#include <davixcontext.hpp>
#include <params/davixrequestparams.hpp>
#include <auth/davixauth.hpp>
#include <gtest/gtest.h>
using namespace std;
using namespace Davix;
// instanciate and play with gates
TEST(CredTest, basicLoad){
DavixError* tmp_err=NULL;
davix_set_log_level(DAVIX_LOG_DEBUG | DAVIX_LOG_WARNING | DAVIX_LOG_TRACE);
Context c;
X509Credential cred;
ASSERT_FALSE(cred.hasCert());
string cert_path(TEST_VALID_CERT);
string cert_pass(TEST_VALID_CERT_PASS);
cout << " cred: " << cert_path << "pass " << cert_pass << endl;
int ret = cred.loadFromFileP12(cert_path.c_str(), cert_pass.c_str(), &tmp_err);
if(tmp_err){
cout << "err :" << tmp_err->getErrMsg() << endl;
}
ASSERT_EQ(0, ret);
ASSERT_EQ(NULL, tmp_err);
ASSERT_TRUE(cred.hasCert());
X509Credential cred2(cred);
ASSERT_TRUE(cred2.hasCert());
ret = cred.loadFromFileP12("/random/stupid/path", "", &tmp_err);
ASSERT_EQ(-1, ret);
ASSERT_EQ(StatusCode::CredentialNotFound, tmp_err->getStatus());
DavixError::clearError(&tmp_err);
ASSERT_FALSE(cred.hasCert());
ASSERT_TRUE(cred2.hasCert());
ret = cred.loadFromFileP12(cert_path.c_str(), "", &tmp_err);
ASSERT_EQ(-1, ret);
ASSERT_EQ(StatusCode::LoginPasswordError, tmp_err->getStatus());
DavixError::clearError(&tmp_err);
}
TEST(testAWS, awsToken){
std::string p_key("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY");
std::string a_key("AKIAIOSFODNN7EXAMPLE");
std::string req("GET\n"
"\n"
"\n"
"Tue, 27 Mar 2007 19:36:42 +0000\n"
"/johnsmith/photos/puppy.jpg");
std::string token("AWS AKIAIOSFODNN7EXAMPLE:"
"bWq2s1WEIj+Ydj0vQ697zp+IXMU=");
std::string res = getAwsAuthorizationField(req, p_key, a_key);
ASSERT_STREQ(res.c_str(), token.c_str());
}
<commit_msg>Disable unit test which uses hardcoded paths<commit_after>#include <davix.hpp>
#include <davixcontext.hpp>
#include <params/davixrequestparams.hpp>
#include <auth/davixauth.hpp>
#include <gtest/gtest.h>
using namespace std;
using namespace Davix;
// instanciate and play with gates
// TEST(CredTest, basicLoad){
// DavixError* tmp_err=NULL;
// davix_set_log_level(DAVIX_LOG_DEBUG | DAVIX_LOG_WARNING | DAVIX_LOG_TRACE);
// Context c;
// X509Credential cred;
// ASSERT_FALSE(cred.hasCert());
// string cert_path(TEST_VALID_CERT);
// string cert_pass(TEST_VALID_CERT_PASS);
// cout << " cred: " << cert_path << "pass " << cert_pass << endl;
// int ret = cred.loadFromFileP12(cert_path.c_str(), cert_pass.c_str(), &tmp_err);
// if(tmp_err){
// cout << "err :" << tmp_err->getErrMsg() << endl;
// }
// ASSERT_EQ(0, ret);
// ASSERT_EQ(NULL, tmp_err);
// ASSERT_TRUE(cred.hasCert());
// X509Credential cred2(cred);
// ASSERT_TRUE(cred2.hasCert());
// ret = cred.loadFromFileP12("/random/stupid/path", "", &tmp_err);
// ASSERT_EQ(-1, ret);
// ASSERT_EQ(StatusCode::CredentialNotFound, tmp_err->getStatus());
// DavixError::clearError(&tmp_err);
// ASSERT_FALSE(cred.hasCert());
// ASSERT_TRUE(cred2.hasCert());
// ret = cred.loadFromFileP12(cert_path.c_str(), "", &tmp_err);
// ASSERT_EQ(-1, ret);
// ASSERT_EQ(StatusCode::LoginPasswordError, tmp_err->getStatus());
// DavixError::clearError(&tmp_err);
// }
TEST(testAWS, awsToken){
std::string p_key("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY");
std::string a_key("AKIAIOSFODNN7EXAMPLE");
std::string req("GET\n"
"\n"
"\n"
"Tue, 27 Mar 2007 19:36:42 +0000\n"
"/johnsmith/photos/puppy.jpg");
std::string token("AWS AKIAIOSFODNN7EXAMPLE:"
"bWq2s1WEIj+Ydj0vQ697zp+IXMU=");
std::string res = getAwsAuthorizationField(req, p_key, a_key);
ASSERT_STREQ(res.c_str(), token.c_str());
}
<|endoftext|> |
<commit_before>#include <cstring>
#include <iostream>
#include <atomic>
#include <vector>
#include <functional>
#include <type_traits>
#include <stdexcept>
#include <flatbuffers/flatbuffers.h>
#include <flatbuffers/idl.h>
#include <flatbuffers/util.h>
#include "libvedis.h"
#include "libenet.h"
#include "signal_handlers.h"
#include "flightctrlstate_generated.h"
#include "netmessages_generated.h"
#include "server_generated.h"
using msg_handler = std::function<void(keron::net::host &, const keron::net::event &, const keron::messages::NetMessage &)>;
using config_ptr = std::unique_ptr<const keron::server::Configuration>;
void msg_none(keron::net::host &, const keron::net::event &, const keron::messages::NetMessage &)
{
std::cout << "No message.\n";
}
void msg_chat(keron::net::host &host, const keron::net::event &event, const keron::messages::NetMessage &msg)
{
auto chat = reinterpret_cast<const keron::messages::Chat *>(msg.message());
std::cout << "Chat message: " << chat->message()->c_str() << std::endl;
keron::net::packet response(event.packet->data, event.packet->dataLength, event.packet->flags);
host.broadcast(event.channelID, response);
}
void msg_flightctrl(keron::net::host &host, const keron::net::event &event, const keron::messages::NetMessage &flight)
{
auto flightCtrl = reinterpret_cast<const keron::messages::FlightCtrl *>(flight.message());
std::cout << "Flight control state" << std::endl;
}
void load_configuration(flatbuffers::Parser &parser, const std::string &schema, const std::string &configfile)
{
std::string serverschema;
std::string configjson;
parser.builder_.Clear();
if (!flatbuffers::LoadFile(schema.c_str(), false, &serverschema))
throw std::runtime_error("Cannot load server schema.");
parser.Parse(serverschema.c_str());
if (!flatbuffers::LoadFile(configfile.c_str(), false, &configjson)) {
std::cerr << "No server configuration found. Creating a default one." << std::endl;
flatbuffers::FlatBufferBuilder fbb;
auto cfg = keron::server::CreateConfiguration(fbb, fbb.CreateString("*"), 18246, 8, fbb.CreateString("server.vdb"));
auto generator = flatbuffers::GeneratorOptions();
generator.strict_json = true;
FinishConfigurationBuffer(fbb, cfg);
flatbuffers::GenerateText(parser, fbb.GetBufferPointer(), generator, &configjson);
if (!flatbuffers::SaveFile(configfile.c_str(), configjson.c_str(), configjson.size(), false))
throw std::runtime_error("Unable to write default configuration!");
throw std::runtime_error(
"A default configuration has been written. "
"Check the content of `server.json`, and restart the server.");
}
parser.Parse(configjson.c_str());
}
std::vector<msg_handler> initialize_messages_handlers()
{
using namespace keron::messages;
std::vector<msg_handler> handlers(3);
handlers[NetID_NONE] = msg_none;
handlers[NetID_Chat] = msg_chat;
handlers[NetID_FlightCtrl] = msg_flightctrl;
return handlers;
}
ENetAddress initialize_server_address(const keron::server::Configuration &config)
{
const std::string host(config.address()->c_str());
uint16_t port{config.port()};
ENetAddress address;
if (host == "*")
address.host = ENET_HOST_ANY;
else
enet_address_set_host(&address, host.c_str());
address.port = port;
return address;
}
int main(void)
{
std::cout << "Registering signal handlers." << std::endl;
keron::server::register_signal_handlers();
std::cout << "Loading server configuration." << std::endl;
flatbuffers::Parser parser;
load_configuration(parser, "schemas/server.fbs", "server.json");
auto settings = keron::server::GetConfiguration(parser.builder_.GetBufferPointer());
std::cout << "Firing up storage." << std::endl;
keron::db::store datastore(settings->datastore()->c_str());
std::cout << "Preparing message handlers." << std::endl;
std::vector<msg_handler> handlers = initialize_messages_handlers();
std::cout << "Initializing network." << std::endl;
keron::net::library enet;
auto address = initialize_server_address(*settings);
keron::net::host host(address, settings->maxclients(), 2);
if (!host) {
std::cerr << "ERROR: creating host." << std::endl;
return -3;
}
keron::net::event event;
std::cout << "Listening on " << settings->address()->c_str() << ":" << settings->port()
<< " " << settings->maxclients() << " clients allowed." << std::endl;
while (host.service(event, 100) >= 0 && !keron::server::stop) {
switch (event.type) {
case ENET_EVENT_TYPE_RECEIVE:
{
keron::net::packet packet(event.packet);
keron::net::address address(event.peer->address);
std::cout
<< "Received packet from "
<< address.ip()
<< " on channel " << static_cast<int>(event.channelID)
<< " size " << packet.length() << std::endl;
flatbuffers::Verifier verifier(packet.data(), packet.length());
if (!keron::messages::VerifyNetMessageBuffer(verifier)) {
std::cout << "Incorrect buffer received." << std::endl;
break;
}
auto message = keron::messages::GetNetMessage(packet.data());
keron::messages::NetID id = message->message_type();
std::cout << "Message is: " << keron::messages::EnumNameNetID(id) << std::endl;
if (!(id < handlers.size())) {
std::cout << "No available handlers.";
break;
}
handlers.at(id)(host, event, *message);
}
break;
case ENET_EVENT_TYPE_CONNECT:
{
keron::net::address address(event.peer->address);
std::cout << "Connection from: " << address.ip() << std::endl;
}
break;
case ENET_EVENT_TYPE_DISCONNECT:
{
keron::net::address address(event.peer->address);
std::cout << "Disconnection from: " << address.ip() << std::endl;
}
break;
case ENET_EVENT_TYPE_NONE:
// reached timeout without incomings.
break;
default:
std::cout << "Unhandled event `" << event.type << "`\n";
}
}
std::cout << "Server is shutting down." << std::endl;
return 0;
}
// vim: shiftwidth=4 tabstop=4
<commit_msg>Updated default port to something fancier.<commit_after>#include <cstring>
#include <iostream>
#include <atomic>
#include <vector>
#include <functional>
#include <type_traits>
#include <stdexcept>
#include <flatbuffers/flatbuffers.h>
#include <flatbuffers/idl.h>
#include <flatbuffers/util.h>
#include "libvedis.h"
#include "libenet.h"
#include "signal_handlers.h"
#include "flightctrlstate_generated.h"
#include "netmessages_generated.h"
#include "server_generated.h"
using msg_handler = std::function<void(keron::net::host &, const keron::net::event &, const keron::messages::NetMessage &)>;
using config_ptr = std::unique_ptr<const keron::server::Configuration>;
void msg_none(keron::net::host &, const keron::net::event &, const keron::messages::NetMessage &)
{
std::cout << "No message.\n";
}
void msg_chat(keron::net::host &host, const keron::net::event &event, const keron::messages::NetMessage &msg)
{
auto chat = reinterpret_cast<const keron::messages::Chat *>(msg.message());
std::cout << "Chat message: " << chat->message()->c_str() << std::endl;
keron::net::packet response(event.packet->data, event.packet->dataLength, event.packet->flags);
host.broadcast(event.channelID, response);
}
void msg_flightctrl(keron::net::host &host, const keron::net::event &event, const keron::messages::NetMessage &flight)
{
auto flightCtrl = reinterpret_cast<const keron::messages::FlightCtrl *>(flight.message());
std::cout << "Flight control state" << std::endl;
}
void load_configuration(flatbuffers::Parser &parser, const std::string &schema, const std::string &configfile)
{
std::string serverschema;
std::string configjson;
parser.builder_.Clear();
if (!flatbuffers::LoadFile(schema.c_str(), false, &serverschema))
throw std::runtime_error("Cannot load server schema.");
parser.Parse(serverschema.c_str());
if (!flatbuffers::LoadFile(configfile.c_str(), false, &configjson)) {
std::cerr << "No server configuration found. Creating a default one." << std::endl;
flatbuffers::FlatBufferBuilder fbb;
auto cfg = keron::server::CreateConfiguration(fbb,
fbb.CreateString("*"),
('K' << 8) | ('S' << 4) | 'P', 8, fbb.CreateString("server.vdb"));
auto generator = flatbuffers::GeneratorOptions();
generator.strict_json = true;
FinishConfigurationBuffer(fbb, cfg);
flatbuffers::GenerateText(parser, fbb.GetBufferPointer(), generator, &configjson);
if (!flatbuffers::SaveFile(configfile.c_str(), configjson.c_str(), configjson.size(), false))
throw std::runtime_error("Unable to write default configuration!");
throw std::runtime_error(
"A default configuration has been written. "
"Check the content of `server.json`, and restart the server.");
}
parser.Parse(configjson.c_str());
}
std::vector<msg_handler> initialize_messages_handlers()
{
using namespace keron::messages;
std::vector<msg_handler> handlers(3);
handlers[NetID_NONE] = msg_none;
handlers[NetID_Chat] = msg_chat;
handlers[NetID_FlightCtrl] = msg_flightctrl;
return handlers;
}
ENetAddress initialize_server_address(const keron::server::Configuration &config)
{
const std::string host(config.address()->c_str());
uint16_t port{config.port()};
ENetAddress address;
if (host == "*")
address.host = ENET_HOST_ANY;
else
enet_address_set_host(&address, host.c_str());
address.port = port;
return address;
}
int main(void)
{
std::cout << "Registering signal handlers." << std::endl;
keron::server::register_signal_handlers();
std::cout << "Loading server configuration." << std::endl;
flatbuffers::Parser parser;
load_configuration(parser, "schemas/server.fbs", "server.json");
auto settings = keron::server::GetConfiguration(parser.builder_.GetBufferPointer());
std::cout << "Firing up storage." << std::endl;
keron::db::store datastore(settings->datastore()->c_str());
std::cout << "Preparing message handlers." << std::endl;
std::vector<msg_handler> handlers = initialize_messages_handlers();
std::cout << "Initializing network." << std::endl;
keron::net::library enet;
auto address = initialize_server_address(*settings);
keron::net::host host(address, settings->maxclients(), 2);
if (!host) {
std::cerr << "ERROR: creating host." << std::endl;
return -3;
}
keron::net::event event;
std::cout << "Listening on " << settings->address()->c_str() << ":" << settings->port()
<< " " << settings->maxclients() << " clients allowed." << std::endl;
while (host.service(event, 100) >= 0 && !keron::server::stop) {
switch (event.type) {
case ENET_EVENT_TYPE_RECEIVE:
{
keron::net::packet packet(event.packet);
keron::net::address address(event.peer->address);
std::cout
<< "Received packet from "
<< address.ip()
<< " on channel " << static_cast<int>(event.channelID)
<< " size " << packet.length() << std::endl;
flatbuffers::Verifier verifier(packet.data(), packet.length());
if (!keron::messages::VerifyNetMessageBuffer(verifier)) {
std::cout << "Incorrect buffer received." << std::endl;
break;
}
auto message = keron::messages::GetNetMessage(packet.data());
keron::messages::NetID id = message->message_type();
std::cout << "Message is: " << keron::messages::EnumNameNetID(id) << std::endl;
if (!(id < handlers.size())) {
std::cout << "No available handlers.";
break;
}
handlers.at(id)(host, event, *message);
}
break;
case ENET_EVENT_TYPE_CONNECT:
{
keron::net::address address(event.peer->address);
std::cout << "Connection from: " << address.ip() << std::endl;
}
break;
case ENET_EVENT_TYPE_DISCONNECT:
{
keron::net::address address(event.peer->address);
std::cout << "Disconnection from: " << address.ip() << std::endl;
}
break;
case ENET_EVENT_TYPE_NONE:
// reached timeout without incomings.
break;
default:
std::cout << "Unhandled event `" << event.type << "`\n";
}
}
std::cout << "Server is shutting down." << std::endl;
return 0;
}
// vim: shiftwidth=4 tabstop=4
<|endoftext|> |
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
/**
* small utility to use instead of "su" when we want to just
* switch to the vespa user without any more fuss
**/
int main(int argc, char** argv)
{
if (argc < 2) {
fprintf(stderr, "missing arguments, usage: vespa-run-as-vespa-user <cmd> [args ...]\n");
return 1;
}
const char *username = getenv("VESPA_USER");
if (username == nullptr) {
username = "vespa";
}
struct passwd *p = getpwnam(username);
if (p == nullptr) {
fprintf(stderr, "FATAL error: user '%s' missing in passwd file\n", username);
return 1;
}
gid_t g = p->pw_gid;
uid_t u = p->pw_uid;
gid_t grouplist[256];
int group_arr_sz = 256;
int ggl = getgrouplist(username, g, grouplist, &group_arr_sz);
gid_t oldg = getgid();
uid_t oldu = getuid();
if (g != oldg && setgid(g) != 0) {
perror("FATAL error: could not change group id");
return 1;
}
size_t listsize = 1;
if (ggl > 0) {
listsize = group_arr_sz;
} else {
grouplist[0] = g;
}
if ((g != oldg || u != oldu) && setgroups(listsize, grouplist) != 0) {
perror("FATAL error: could not setgroups");
return 1;
}
if (u != oldu && setuid(u) != 0) {
perror("FATAL error: could not change user id");
return 1;
}
execvp(argv[1], &argv[1]);
perror("FATAL error: execvp failed");
return 1;
}
<commit_msg>try to make it work on Mac OS X also<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
/**
* small utility to use instead of "su" when we want to just
* switch to the vespa user without any more fuss
**/
int main(int argc, char** argv)
{
if (argc < 2) {
fprintf(stderr, "missing arguments, usage: vespa-run-as-vespa-user <cmd> [args ...]\n");
return 1;
}
const char *username = getenv("VESPA_USER");
if (username == nullptr) {
username = "vespa";
}
struct passwd *p = getpwnam(username);
if (p == nullptr) {
fprintf(stderr, "FATAL error: user '%s' missing in passwd file\n", username);
return 1;
}
gid_t g = p->pw_gid;
uid_t u = p->pw_uid;
gid_t grouplist[256];
int group_arr_sz = 256;
#ifdef __APPLE__
int mac_gid = g;
int mac_groups[256];
int ggl = getgrouplist(username, mac_gid, mac_groups, &group_arr_sz);
for (int i = 0; i < group_arr_sz; ++i) {
grouplist[i] = (gid_t) mac_groups[i];
}
#else
int ggl = getgrouplist(username, g, grouplist, &group_arr_sz);
#endif
gid_t oldg = getgid();
uid_t oldu = getuid();
if (g != oldg && setgid(g) != 0) {
perror("FATAL error: could not change group id");
return 1;
}
size_t listsize = 1;
if (ggl >= 0) {
listsize = group_arr_sz;
} else {
grouplist[0] = g;
}
if ((g != oldg || u != oldu) && setgroups(listsize, grouplist) != 0) {
perror("FATAL error: could not setgroups");
return 1;
}
if (u != oldu && setuid(u) != 0) {
perror("FATAL error: could not change user id");
return 1;
}
execvp(argv[1], &argv[1]);
perror("FATAL error: execvp failed");
return 1;
}
<|endoftext|> |
<commit_before>/*
* =====================================================================================
*
* Filename: encore.cpp
*
* Description: Encore - A computational framework for analysis of GWAS and other
* biological data
*
* Includes epistasis interaction analysis (reGAIN), eigenvector
* centrality SNP ranking (SNPrank), and feature selection using the
* Evaporative Cooling machine learning tool. Encore also utilizes
* plink for its ubiquitous data formats and wide array of GWAS
* functionality.
*
* Created: 02/01/2012
*
* Author: Nick Davis, [email protected]
*
* =====================================================================================
*/
#include <fstream>
#include <iostream>
#include <string>
#include <boost/program_options.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include "ec/EvaporativeCooling.h"
#include "plink/plinklibhandler.h"
#include "plink/plink.h"
#include "plink/options.h"
#include "plink/helper.h"
#include "snprank.h"
#include "regain.h"
using namespace boost;
namespace po = boost::program_options;
/********************************
* required plink data structures
*******************************/
// plink object
Plink* PP;
int main(int argc, char* argv[]) {
// command line variables
// data files
string infile = "";
string outfile_pref = "encore";
string covarfile = "";
string phenofile = "";
string extrfile = "";
//snprank
double gamma = 0.85;
// reGAIN
double sif_thresh = 0.05;
double fdr = 0.5;
// EC
string ec_algo = "all";
string ec_sm = "gm";
po::options_description desc("Encore - a tool for analysis of GWAS and other "
"biological data.\nUsage: encore -i snpdata.ped [mode] -o output-prefix");
desc.add_options()
("input-file,i", po::value<string>(&infile),
"Input GWAS file (.bed or .ped) or GAIN/reGAIN matrix (tab- or comma-separated)"
)
("output-prefix,o", po::value<string>(&outfile_pref),
"Prefix to use for all output files"
)
("snprank,s",
"Perform SNPrank analysis *mode*"
)
("gamma,g", po::value<double>(&gamma)->default_value(0.85, "0.85"),
"Damping factor (default is 0.85)"
)
("regain,r",
"Calculate regression GAIN *mode*"
)
("compress-matrices",
"Write binary (compressed) reGAIN matrices"
)
("sif-threshold", po::value<double>(&sif_thresh)->default_value(0.05, "0.05"),
"Numerical cutoff for SIF file interaction scores"
)
("fdr-prune",
"FDR prune reGAIN interaction terms"
)
("fdr", po::value<double>(&fdr)->default_value(0.5, "0.5"),
"FDR value for BH method"
)
("ec,e",
"Perform Evaporative Cooling (EC) analysis *mode*"
)
("ec-algorithm", po::value<string>(&ec_algo),
"EC ML algorithm (all|rf|rj)"
)
("ec-snp-metric", po::value<string>(&ec_sm),
"EC SNP metric (gm|am)"
)
("extract", po::value<string>(&extrfile),
"Extract list of SNPs from specified file"
)
("covar", po::value<string>(&covarfile),
"Include covariate file in analysis"
)
("pheno", po::value<string>(&phenofile),
"Include alternate phenotype file in analysis"
)
("assoc",
"Run Case/control, QT association tests *mode*"
)
("linear",
"Run linear regression model *mode*"
)
("ld-prune,l",
"Linkage disequilibrium (LD) pruning *mode*"
)
("help,h", "display this help screen")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
/********************************
* Help
*******************************/
if (vm.count("help")) {
cout << desc << endl;
return 1;
}
/*********************************
* Validate only one mode passed
********************************/
int modes = 0;
for (po::variables_map::iterator iter = vm.begin(); iter != vm.end(); ++iter) {
if (iter->first == "snprank" || iter->first == "regain" ||
iter->first == "ec" || iter->first == "assoc" ||
iter->first == "linear" || iter->first == "ld-prune") {
modes++;
}
}
if (modes > 1) {
cerr << "Error: Only one mode may be specified" << endl << endl << desc << endl;
return 1;
}
/********************************
* Input file
*******************************/
// require input file
if (!vm.count("input-file")) {
cerr << "Error: Must specify input file" << endl << endl << desc << endl;
return 1;
}
// ensure SNP/reGAIN file exists
else if (!boost::filesystem::exists(infile)) {
cerr << "Error: Input file " << infile << " does not exist" << endl;
return 1;
}
// Plink input file
else if (infile.find(".bed") != string::npos ||
infile.find(".ped") != string::npos) {
// set file root
vector<string> fileparts;
split(fileparts, infile, is_any_of("."));
par::fileroot = "";
// handle files with multiple .s in the name
for (int i =0; i < fileparts.size() - 1; i++) {
par::fileroot += fileparts[i];
if (fileparts.size() > 2 && i < fileparts.size() - 2)
par::fileroot += ".";
}
// set Plink's output file prefix
par::output_file_name = outfile_pref;
// initialize requisite Plink data structures
initPlink();
// read SNP file in PLINK
// binary file
if (infile.find(".bed") != string::npos) readPlBinFile();
// plaintext file
else if (infile.find(".ped") != string::npos) readPlFile();
// additional PLINK setup
initPlStats();
}
/********************************
* Covar file
*******************************/
if (vm.count("covarfile")){
// validate that covar file is used with proper modes
if (!(vm.count("regain") || vm.count("linear"))) {
cerr << "Error: Covariate file may only be used with --regain or --linear"
<< endl << desc << endl;
return 1;
}
// ensure covariate file exists
else if (!boost::filesystem::exists(covarfile)) {
cerr << "Error: Covariate file " << covarfile << " does not exist" << endl;
return 1;
}
// read covariate file using PLINK
else {
par::covar_file = true;
if(!PP->readCovListFile()){
cerr << "Error: Problem reading the covariates" << endl;
return 1;
}
}
}
/********************************
* Pheno file
*******************************/
if (vm.count("phenofile")) {
// alternate phenotype validation
if (vm.count("snprank")) {
cerr << "Error: Alternate phenotype file cannot be used with "\
"--snprank" << endl << desc << endl;
return 1;
}
// ensure alternate phenotype file exists
else if (!boost::filesystem::exists(phenofile)) {
cerr << "Error: Alernate phenotype file " << phenofile << " does not exist" << endl;
return 1;
}
// read alternate phenotype file using PLINK
else {
par::pheno_file = true;
if(!PP->readPhenoFile())
cerr << "Error: Problem reading the alternate phenotype file" << endl;
}
}
/********************************
* Extract file
*******************************/
if (vm.count("extract")) {
// extract validation
if (vm.count("snprank") || vm.count("ec") || vm.count("ldprune")) {
cerr << "Error: Extract file cannot be used with "\
"--snprank, --ec, or --ldprune" << endl << desc << endl;
return 1;
}
// ensure extract file exists
else if (!boost::filesystem::exists(extrfile)) {
cerr << "Error: Extract file " << extrfile << " does not exist" << endl;
return 1;
}
// read extract file SNPs using PLINK
else {
par::extract_set = true;
par::extract_file = extrfile;
PP->extractExcludeSet(false);
}
}
/*********************************
* Validate mode sub-options
********************************/
if (vm.count("gamma") && !vm.count("snprank")) {
cerr << "Error: --gamma must be used with --snprank" << endl << endl <<
desc << endl;
return 1;
}
if (vm.count("sif-threshold") && !vm.count("regain")) {
cerr << "Error: --sif-threshold must be used with --regain" << endl << endl <<
desc << endl;
return 1;
}
if (vm.count("fdr-prune") && !vm.count("regain")) {
cerr << "Error: --fdr-prune must be used with --regain" << endl << endl <<
desc << endl;
return 1;
}
if (vm.count("fdr") && !vm.count("regain")) {
cerr << "Error: --fdr must be used with --regain" << endl << endl <<
desc << endl;
return 1;
}
if (vm.count("ec-algorithm") && !vm.count("ec")) {
cerr << "Error: ec-algorithm must be used with --ec" << endl << endl <<
desc << endl;
return 1;
}
if (vm.count("ec-snp-metric") && !vm.count("ec")) {
cerr << "Error: ec-snp-metric must be used with --ec" << endl << endl <<
desc << endl;
return 1;
}
/*********************************
* Check primary mode of operation
********************************/
// SNPrank
if (vm.count("snprank")) {
SNPrank* sr = new SNPrank(infile);
cout << "Writing SNPrank results to [ " << outfile_pref << ".snprank ]" << endl;
sr->snprank(sr->getHeader(), sr->getData(), gamma, outfile_pref + ".snprank");
delete sr;
}
// reGAIN
else if (vm.count("regain")) {
if (!vm.count("extract"))
cout << "Warning: It is recommended to use an --extract file of SNPs with "\
"--regain" << endl;
// SNP major mode or individual major mode?
if(par::fast_epistasis) {
if(!par::SNP_major)
PP->Ind2SNP();
} else {
if(par::SNP_major)
PP->SNP2Ind();
}
bool fdrprune = vm.count("fdr-prune");
Regain* r = new Regain(vm.count("compress-matrices"), sif_thresh, fdrprune);
r->run();
if (fdrprune){
r->writeRegain();
r->fdrPrune(fdr);
}
r->writeRegain(fdrprune);
r->writePvals();
delete r;
}
// Evaporative Cooling (EC)
else if (vm.count("ec")) {
// EC options map
map<string,string> opts;
// required options for EC
opts.insert(pair<string,string>("ec-num-target", "0"));
opts.insert(pair<string,string>("snp-data", infile));
opts.insert(pair<string,string>("out-files-prefix", outfile_pref));
// defaults for ID matching
string numericfile = "";
vector<string> ind_ids;
vector<string> numeric_ids;
vector<string> pheno_ids;
bool datasetLoaded = false;
// validate algorithm
if (ec_algo != "all" && ec_algo != "rj" && ec_algo != "rf")
cerr << "Error: EC algorithm must be one of: (all|rj|rf)" << endl;
else opts.insert(pair<string,string>("ec-algorithm-steps", ec_algo));
// validate metric
if (ec_sm != "gm" && ec_sm != "am")
cerr << "Error: EC SNP metric must be one of: (gm|am)" << endl;
else opts.insert(pair<string,string>("snp-metric", ec_sm));
// find IDs for loading from the dataset
if(!GetMatchingIds(numericfile, phenofile,
numeric_ids, pheno_ids, ind_ids))
cerr << "Error: could not get matching IDs from numeric " <<
"and/or phenotype files" << endl;
// initialize dataset by extension
Dataset* ds = 0;
ds = ChooseSnpsDatasetByExtension(infile);
bool loaded = ds->LoadDataset(infile, "", phenofile, ind_ids);
if (!loaded)
cerr << "Error: Failure to load dataset for analysis" << endl;
// file data stats
ds->PrintStats();
// create ec object and run
EvaporativeCooling* ec = new EvaporativeCooling(ds, opts, SNP_ONLY_ANALYSIS);
if(!ec->ComputeECScores())
cerr << "Error: Failed to calculate EC scores" << endl;
// write results to file
cout << "Writing EC results to [ " << outfile_pref << ".ec ]" << endl;
ec->WriteAttributeScores(outfile_pref);
delete ds;
delete ec;
}
// Case/Control, QT association test OR linear model
else if (vm.count("assoc")) {
if (vm.count("linear"))
par::assoc_glm = true;
par::assoc_test = true;
PP->calcAssociationWithPermutation(*PP->pperm);
}
// LD-based pruning
else if (vm.count("ldprune")) {
par::prune_ld = true;
par::prune_ld_pairwise = true;
par::prune_ld_win = 50;
par::prune_ld_step = 5;
par::prune_ld_vif = 0.5;
PP->pruneLD();
}
else {
cerr << "Error: Invalid command mode, must be one of:" << endl
<< " --snprank, --regain, --ec, --assoc, --linear, --ldprune" << endl
<< endl << desc << endl;
// Plink exit
shutdown();
return 1;
}
// Plink exit
shutdown();
return 0;
}
<commit_msg>Fix covar and pheno checks, add additional Plink vars<commit_after>/*
* =====================================================================================
*
* Filename: encore.cpp
*
* Description: Encore - A computational framework for analysis of GWAS and other
* biological data
*
* Includes epistasis interaction analysis (reGAIN), eigenvector
* centrality SNP ranking (SNPrank), and feature selection using the
* Evaporative Cooling machine learning tool. Encore also utilizes
* plink for its ubiquitous data formats and wide array of GWAS
* functionality.
*
* Created: 02/01/2012
*
* Author: Nick Davis, [email protected]
*
* =====================================================================================
*/
#include <fstream>
#include <iostream>
#include <string>
#include <boost/program_options.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include "ec/EvaporativeCooling.h"
#include "plink/plinklibhandler.h"
#include "plink/plink.h"
#include "plink/options.h"
#include "plink/helper.h"
#include "snprank.h"
#include "regain.h"
using namespace boost;
namespace po = boost::program_options;
/********************************
* required plink data structures
*******************************/
// plink object
Plink* PP;
int main(int argc, char* argv[]) {
// command line variables
// data files
string infile = "";
string outfile_pref = "encore";
string covarfile = "";
string phenofile = "";
string extrfile = "";
//snprank
double gamma = 0.85;
// reGAIN
double sif_thresh = 0.05;
double fdr = 0.5;
// EC
string ec_algo = "all";
string ec_sm = "gm";
po::options_description desc("Encore - a tool for analysis of GWAS and other "
"biological data.\nUsage: encore -i snpdata.ped [mode] -o output-prefix");
desc.add_options()
("input-file,i", po::value<string>(&infile),
"Input GWAS file (.bed or .ped) or GAIN/reGAIN matrix (tab- or comma-separated)"
)
("output-prefix,o", po::value<string>(&outfile_pref),
"Prefix to use for all output files"
)
("snprank,s",
"Perform SNPrank analysis *mode*"
)
("gamma,g", po::value<double>(&gamma)->default_value(0.85, "0.85"),
"Damping factor (default is 0.85)"
)
("regain,r",
"Calculate regression GAIN *mode*"
)
("compress-matrices",
"Write binary (compressed) reGAIN matrices"
)
("sif-threshold", po::value<double>(&sif_thresh)->default_value(0.05, "0.05"),
"Numerical cutoff for SIF file interaction scores"
)
("fdr-prune",
"FDR prune reGAIN interaction terms"
)
("fdr", po::value<double>(&fdr)->default_value(0.5, "0.5"),
"FDR value for BH method"
)
("ec,e",
"Perform Evaporative Cooling (EC) analysis *mode*"
)
("ec-algorithm", po::value<string>(&ec_algo),
"EC ML algorithm (all|rf|rj)"
)
("ec-snp-metric", po::value<string>(&ec_sm),
"EC SNP metric (gm|am)"
)
("extract", po::value<string>(&extrfile),
"Extract list of SNPs from specified file"
)
("covar", po::value<string>(&covarfile),
"Include covariate file in analysis"
)
("pheno", po::value<string>(&phenofile),
"Include alternate phenotype file in analysis"
)
("assoc",
"Run Case/control, QT association tests *mode*"
)
("linear",
"Run linear regression model *mode*"
)
("ld-prune,l",
"Linkage disequilibrium (LD) pruning *mode*"
)
("help,h", "display this help screen")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
/********************************
* Help
*******************************/
if (vm.count("help")) {
cout << desc << endl;
return 1;
}
/*********************************
* Validate only one mode passed
********************************/
int modes = 0;
for (po::variables_map::iterator iter = vm.begin(); iter != vm.end(); ++iter) {
if (iter->first == "snprank" || iter->first == "regain" ||
iter->first == "ec" || iter->first == "assoc" ||
iter->first == "linear" || iter->first == "ld-prune") {
modes++;
}
}
if (modes > 1) {
cerr << "Error: Only one mode may be specified" << endl << endl << desc << endl;
return 1;
}
/********************************
* Input file
*******************************/
// require input file
if (!vm.count("input-file")) {
cerr << "Error: Must specify input file" << endl << endl << desc << endl;
return 1;
}
// ensure SNP/reGAIN file exists
else if (!boost::filesystem::exists(infile)) {
cerr << "Error: Input file " << infile << " does not exist" << endl;
return 1;
}
// Plink input file
else if (infile.find(".bed") != string::npos ||
infile.find(".ped") != string::npos) {
// set file root
vector<string> fileparts;
split(fileparts, infile, is_any_of("."));
par::fileroot = "";
// handle files with multiple .s in the name
for (int i =0; i < fileparts.size() - 1; i++) {
par::fileroot += fileparts[i];
if (fileparts.size() > 2 && i < fileparts.size() - 2)
par::fileroot += ".";
}
// set Plink's output file prefix
par::output_file_name = outfile_pref;
// initialize requisite Plink data structures
initPlink();
// read SNP file in PLINK
// binary file
if (infile.find(".bed") != string::npos) readPlBinFile();
// plaintext file
else if (infile.find(".ped") != string::npos) readPlFile();
// additional PLINK setup
initPlStats();
}
/********************************
* Covar file
*******************************/
if (vm.count("covar")){
// validate that covar file is used with proper modes
if (!(vm.count("regain") || vm.count("linear"))) {
cerr << "Error: Covariate file may only be used with --regain or --linear"
<< endl << desc << endl;
return 1;
}
// ensure covariate file exists
else if (!boost::filesystem::exists(covarfile)) {
cerr << "Error: Covariate file " << covarfile << " does not exist" << endl;
return 1;
}
// read covariate file using PLINK
else {
par::covar_file = true;
par::clist = true;
par::clist_filename = covarfile;
if(!PP->readCovListFile()){
cerr << "Error: Problem reading the covariates" << endl;
return 1;
}
}
}
/********************************
* Pheno file
*******************************/
if (vm.count("pheno")) {
// alternate phenotype validation
if (vm.count("snprank")) {
cerr << "Error: Alternate phenotype file cannot be used with "\
"--snprank" << endl << desc << endl;
return 1;
}
// ensure alternate phenotype file exists
else if (!boost::filesystem::exists(phenofile)) {
cerr << "Error: Alernate phenotype file " << phenofile << " does not exist" << endl;
return 1;
}
// read alternate phenotype file using PLINK
else {
par::pheno_file = true;
par::pheno_filename = phenofile;
if(!PP->readPhenoFile())
cerr << "Error: Problem reading the alternate phenotype file" << endl;
}
}
/********************************
* Extract file
*******************************/
if (vm.count("extract")) {
// extract validation
if (vm.count("snprank") || vm.count("ec") || vm.count("ldprune")) {
cerr << "Error: Extract file cannot be used with "\
"--snprank, --ec, or --ldprune" << endl << desc << endl;
return 1;
}
// ensure extract file exists
else if (!boost::filesystem::exists(extrfile)) {
cerr << "Error: Extract file " << extrfile << " does not exist" << endl;
return 1;
}
// read extract file SNPs using PLINK
else {
par::extract_set = true;
par::extract_file = extrfile;
PP->extractExcludeSet(false);
}
}
/*********************************
* Validate mode sub-options
********************************/
if (vm.count("gamma") && !vm.count("snprank")) {
cerr << "Error: --gamma must be used with --snprank" << endl << endl <<
desc << endl;
return 1;
}
if (vm.count("sif-threshold") && !vm.count("regain")) {
cerr << "Error: --sif-threshold must be used with --regain" << endl << endl <<
desc << endl;
return 1;
}
if (vm.count("fdr-prune") && !vm.count("regain")) {
cerr << "Error: --fdr-prune must be used with --regain" << endl << endl <<
desc << endl;
return 1;
}
if (vm.count("fdr") && !vm.count("regain")) {
cerr << "Error: --fdr must be used with --regain" << endl << endl <<
desc << endl;
return 1;
}
if (vm.count("ec-algorithm") && !vm.count("ec")) {
cerr << "Error: ec-algorithm must be used with --ec" << endl << endl <<
desc << endl;
return 1;
}
if (vm.count("ec-snp-metric") && !vm.count("ec")) {
cerr << "Error: ec-snp-metric must be used with --ec" << endl << endl <<
desc << endl;
return 1;
}
/*********************************
* Check primary mode of operation
********************************/
// SNPrank
if (vm.count("snprank")) {
SNPrank* sr = new SNPrank(infile);
cout << "Writing SNPrank results to [ " << outfile_pref << ".snprank ]" << endl;
sr->snprank(sr->getHeader(), sr->getData(), gamma, outfile_pref + ".snprank");
delete sr;
}
// reGAIN
else if (vm.count("regain")) {
if (!vm.count("extract"))
cout << "Warning: It is recommended to use an --extract file of SNPs with "\
"--regain" << endl;
// SNP major mode or individual major mode?
if(par::fast_epistasis) {
if(!par::SNP_major)
PP->Ind2SNP();
} else {
if(par::SNP_major)
PP->SNP2Ind();
}
bool fdrprune = vm.count("fdr-prune");
Regain* r = new Regain(vm.count("compress-matrices"), sif_thresh, fdrprune);
r->run();
if (fdrprune){
r->writeRegain();
r->fdrPrune(fdr);
}
r->writeRegain(fdrprune);
r->writePvals();
delete r;
}
// Evaporative Cooling (EC)
else if (vm.count("ec")) {
// EC options map
map<string,string> opts;
// required options for EC
opts.insert(pair<string,string>("ec-num-target", "0"));
opts.insert(pair<string,string>("snp-data", infile));
opts.insert(pair<string,string>("out-files-prefix", outfile_pref));
// defaults for ID matching
string numericfile = "";
vector<string> ind_ids;
vector<string> numeric_ids;
vector<string> pheno_ids;
bool datasetLoaded = false;
// validate algorithm
if (ec_algo != "all" && ec_algo != "rj" && ec_algo != "rf")
cerr << "Error: EC algorithm must be one of: (all|rj|rf)" << endl;
else opts.insert(pair<string,string>("ec-algorithm-steps", ec_algo));
// validate metric
if (ec_sm != "gm" && ec_sm != "am")
cerr << "Error: EC SNP metric must be one of: (gm|am)" << endl;
else opts.insert(pair<string,string>("snp-metric", ec_sm));
// find IDs for loading from the dataset
if(!GetMatchingIds(numericfile, phenofile,
numeric_ids, pheno_ids, ind_ids))
cerr << "Error: could not get matching IDs from numeric " <<
"and/or phenotype files" << endl;
// initialize dataset by extension
Dataset* ds = 0;
ds = ChooseSnpsDatasetByExtension(infile);
bool loaded = ds->LoadDataset(infile, "", phenofile, ind_ids);
if (!loaded)
cerr << "Error: Failure to load dataset for analysis" << endl;
// file data stats
ds->PrintStats();
// create ec object and run
EvaporativeCooling* ec = new EvaporativeCooling(ds, opts, SNP_ONLY_ANALYSIS);
if(!ec->ComputeECScores())
cerr << "Error: Failed to calculate EC scores" << endl;
// write results to file
cout << "Writing EC results to [ " << outfile_pref << ".ec ]" << endl;
ec->WriteAttributeScores(outfile_pref);
delete ds;
delete ec;
}
// Case/Control, QT association test OR linear model
else if (vm.count("assoc")) {
if (vm.count("linear"))
par::assoc_glm = true;
par::assoc_test = true;
PP->calcAssociationWithPermutation(*PP->pperm);
}
// LD-based pruning
else if (vm.count("ldprune")) {
par::prune_ld = true;
par::prune_ld_pairwise = true;
par::prune_ld_win = 50;
par::prune_ld_step = 5;
par::prune_ld_vif = 0.5;
PP->pruneLD();
}
else {
cerr << "Error: Invalid command mode, must be one of:" << endl
<< " --snprank, --regain, --ec, --assoc, --linear, --ldprune" << endl
<< endl << desc << endl;
// Plink exit
shutdown();
return 1;
}
// Plink exit
shutdown();
return 0;
}
<|endoftext|> |
<commit_before>#include <rusql/rusql.hpp>
#include "test.hpp"
#include "database_test.hpp"
int main(int argc, char *argv[]) {
auto db = get_database(argc, argv);
test_init(20);
db->execute("CREATE TABLE rusqltest (`value` VARCHAR(10) NOT NULL)");
test_start_try(6);
try {
db->execute("INSERT INTO rusqltest VALUES (?), (?), (?)", "a", "b", "c");
auto res = db->query("SELECT * FROM rusqltest");
test(res.get_string(1) == "a", "a was inserted");
res.next();
test(res, "two results");
test(res.get_string(1) == "b", "b was inserted");
res.next();
test(res, "three results");
test(res.get_string(1) == "c", "c was inserted");
res.next();
test(!res, "not more than three results");
} catch(std::exception &e) {
diag(e);
}
test_finish_try();
db->execute("DELETE FROM rusqltest");
try {
db->execute("INSERT INTO rusqltest VALUES (?)", "a", "b");
fail("Too many placeholders fails");
} catch(std::exception &) {
pass("Too many placeholders fails");
}
try {
db->execute("INSERT INTO rusqltest VALUES (?), (?)", "a");
fail("Too few placeholders fails");
} catch(std::exception &) {
pass("Too few placeholders fails");
}
db->execute("DELETE FROM rusqltest");
try {
db->execute("INSERT INTO rusqltest VALUES (?)", 5);
auto res = db->query("SELECT * FROM rusqltest");
diag("Actually stored string: '" + res.get_string(1) + "'");
fail("Disallowed to enter numerics in string field");
} catch(std::exception &) {
pass("Disallowed to enter numerics in string field");
}
db->execute("DELETE FROM rusqltest");
db->execute("INSERT INTO rusqltest VALUES (?)", "6");
try {
auto res = db->query("SELECT * FROM rusqltest");
auto r = res.get_uint64(1);
diag("Actually retrieved numeric: " + to_string(r));
fail("Disallowed to retrieve numerics from string field");
} catch(std::exception &) {
pass("Disallowed to retrieve numerics from string field");
}
db->execute("DROP TABLE rusqltest");
db->execute("CREATE TABLE rusqltest (`value` INT(2) NOT NULL)");
test_start_try(2);
try {
db->execute("INSERT INTO rusqltest VALUES (?)", 3);
auto res = db->query("SELECT * FROM rusqltest");
test(res.get_uint64(1) == 3, "3 was inserted");
res.next();
test(!res, "not more than one result");
} catch(std::exception &e) {
diag(e);
}
test_finish_try();
try {
auto res = db->query("SELECT * FROM rusqltest");
auto r = res.get_string(1);
diag("Actually retrieved string: '" + r + "'");
fail("Disallowed to retrieve strings from numeric field");
} catch(std::exception&) {
pass("Disallowed to retrieve strings from numeric fields");
}
db->execute("DELETE FROM rusqltest");
try {
db->execute("INSERT INTO rusqltest VALUES (?)", "4");
auto res = db->query("SELECT * FROM rusqltest");
auto r = res.get_uint64(1);
diag("Actually retrieved numeric: " + to_string(r));
fail("Disallowed to enter strings in numeric field");
} catch(std::exception&) {
pass("Disallowed to enter strings in numeric field");
}
db->execute("DROP TABLE rusqltest");
db->execute("CREATE TABLE rusqltest(`value` INT(2) NULL)");
test_start_try(3);
try {
db->execute("INSERT INTO rusqltest VALUES (?)", 2);
pass("Insert values into NULL field");
auto res = db->query("SELECT * FROM rusqltest");
bool r = res.is_null(1);
pass("Could ask if value is null");
test(!r, "Value inserted from 2 was not null");
} catch(std::exception &e) {
diag(e);
}
test_finish_try();
db->execute("DELETE FROM rusqltest");
test_start_try(3);
try {
db->execute("INSERT INTO rusqltest VALUES (?)", boost::none);
pass("Insert boost::none");
auto res = db->query("SELECT * FROM rusqltest");
bool r = res.is_null(1);
pass("Could ask if value is null");
test(r, "Value inserted from none was null");
} catch(std::exception &e) {
diag(e);
}
test_finish_try();
db->execute("DROP TABLE rusqltest");
return 0;
}
<commit_msg>Allow storing and retrieving numerics from string columns and strings from numeric columns.<commit_after>#include <rusql/rusql.hpp>
#include "test.hpp"
#include "database_test.hpp"
int main(int argc, char *argv[]) {
auto db = get_database(argc, argv);
test_init(24);
db->execute("CREATE TABLE rusqltest (`value` VARCHAR(10) NOT NULL)");
test_start_try(6);
try {
db->execute("INSERT INTO rusqltest VALUES (?), (?), (?)", "a", "b", "c");
auto res = db->query("SELECT * FROM rusqltest");
test(res.get_string(1) == "a", "a was inserted");
res.next();
test(res, "two results");
test(res.get_string(1) == "b", "b was inserted");
res.next();
test(res, "three results");
test(res.get_string(1) == "c", "c was inserted");
res.next();
test(!res, "not more than three results");
} catch(std::exception &e) {
diag(e);
}
test_finish_try();
db->execute("DELETE FROM rusqltest");
try {
db->execute("INSERT INTO rusqltest VALUES (?)", "a", "b");
fail("Too many placeholders fails");
} catch(std::exception &) {
pass("Too many placeholders fails");
}
try {
db->execute("INSERT INTO rusqltest VALUES (?), (?)", "a");
fail("Too few placeholders fails");
} catch(std::exception &) {
pass("Too few placeholders fails");
}
db->execute("DELETE FROM rusqltest");
test_start_try(2);
try {
db->execute("INSERT INTO rusqltest VALUES (?)", 5);
pass("Could insert numeric into string field");
auto res = db->query("SELECT * FROM rusqltest");
test(res.get_string(1) == "5", "Numeric was stored into string field correctly");
} catch(std::exception &e) {
diag(e);
}
test_finish_try();
db->execute("DELETE FROM rusqltest");
db->execute("INSERT INTO rusqltest VALUES (?)", "6");
test_start_try(2);
try {
auto res = db->query("SELECT * FROM rusqltest");
auto r = res.get_uint64(1);
pass("Could retrieve numeric from string field");
test(r == 6, "Numeric was retrieved from string field correctly");
} catch(std::exception &e) {
diag(e);
}
test_finish_try();
db->execute("DROP TABLE rusqltest");
db->execute("CREATE TABLE rusqltest (`value` INT(2) NOT NULL)");
test_start_try(2);
try {
db->execute("INSERT INTO rusqltest VALUES (?)", 3);
auto res = db->query("SELECT * FROM rusqltest");
test(res.get_uint64(1) == 3, "3 was inserted");
res.next();
test(!res, "not more than one result");
} catch(std::exception &e) {
diag(e);
}
test_finish_try();
test_start_try(2);
try {
auto res = db->query("SELECT * FROM rusqltest");
auto r = res.get_string(1);
pass("Could retrieve string from numeric field");
test(r == "3", "Retrieved string is correct");
} catch(std::exception &e) {
diag(e);
}
test_finish_try();
db->execute("DELETE FROM rusqltest");
test_start_try(2);
try {
db->execute("INSERT INTO rusqltest VALUES (?)", "4");
pass("Could insert string into numeric field");
auto res = db->query("SELECT * FROM rusqltest");
auto r = res.get_uint64(1);
test(r == 4, "Inserted string into numeric field is correct");
} catch(std::exception &e) {
diag(e);
}
test_finish_try();
db->execute("DROP TABLE rusqltest");
db->execute("CREATE TABLE rusqltest(`value` INT(2) NULL)");
test_start_try(3);
try {
db->execute("INSERT INTO rusqltest VALUES (?)", 2);
pass("Insert values into NULL field");
auto res = db->query("SELECT * FROM rusqltest");
bool r = res.is_null(1);
pass("Could ask if value is null");
test(!r, "Value inserted from 2 was not null");
} catch(std::exception &e) {
diag(e);
}
test_finish_try();
db->execute("DELETE FROM rusqltest");
test_start_try(3);
try {
db->execute("INSERT INTO rusqltest VALUES (?)", boost::none);
pass("Insert boost::none");
auto res = db->query("SELECT * FROM rusqltest");
bool r = res.is_null(1);
pass("Could ask if value is null");
test(r, "Value inserted from none was null");
} catch(std::exception &e) {
diag(e);
}
test_finish_try();
db->execute("DROP TABLE rusqltest");
return 0;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <cstdint>
#include <iostream>
#include <string>
#include <caf/config_option_adder.hpp>
#include <broker/bro.hh>
#include <broker/broker.hh>
#include <vast/defaults.hpp>
#include <vast/error.hpp>
#include <vast/event.hpp>
#include <vast/expression.hpp>
#include <vast/uuid.hpp>
#include <vast/concept/parseable/parse.hpp>
#include <vast/concept/parseable/vast/expression.hpp>
#include <vast/concept/parseable/vast/uuid.hpp>
#include <vast/system/writer_command_base.hpp>
#include <vast/system/sink.hpp>
#include <vast/detail/add_message_types.hpp>
#include <vast/detail/assert.hpp>
#include <vast/detail/overload.hpp>
namespace {
constexpr char control_topic[] = "/vast/control";
constexpr char data_topic[] = "/vast/data";
constexpr char default_address[] = "localhost";
constexpr uint16_t default_port = 43000;
// Our custom configuration with extra command line options for this tool.
class config : public broker::configuration {
public:
config() {
// As a stand-alone application, we reuse the global option group from CAF
// to avoid unnecessary prefixing.
opt_group{custom_options_, "global"}
.add<uint16_t>("port,p", "the port to listen at or connect to");
}
};
// Constructs a result event for Bro.
broker::bro::Event make_bro_event(std::string id, broker::data x) {
broker::vector args(2);
args[0] = std::move(id);
args[1] = std::move(x);
return {"VAST::result", std::move(args)};
}
// A VAST writer that publishes the event it gets to a Bro endpoint.
class bro_writer {
public:
bro_writer() = default;
bro_writer(broker::endpoint& endpoint, std::string query_id)
: endpoint_{&endpoint},
query_id_{std::move(query_id)} {
// nop
}
caf::expected<void> write(const vast::event& x) {
// TODO: publish to Broker endpoint.
std::cout << x.type().name() << std::endl;
return caf::no_error;
}
caf::expected<void> flush() {
return caf::no_error;
}
auto name() const {
return "bro-writer";
}
private:
broker::endpoint* endpoint_;
std::string query_id_;
};
// A custom command that allows us to re-use VAST command dispatching logic in
// order to issue a query that writes into a sink with a custom format.
class bro_command : public vast::system::writer_command_base {
public:
bro_command(broker::endpoint& endpoint)
: writer_command_base{nullptr, "bro"},
endpoint_{endpoint} {
// nop
}
// Sets the query ID to the UUID provided by Bro.
void query_id(std::string id) {
query_id_ = std::move(id);
}
protected:
caf::expected<caf::actor> make_sink(caf::scoped_actor& self,
const caf::config_value_map& options,
argument_iterator begin,
argument_iterator end) override {
VAST_UNUSED(options, begin, end);
bro_writer writer{endpoint_, query_id_};
return self->spawn(vast::system::sink<bro_writer>, std::move(writer),
vast::defaults::command::max_events);
}
private:
broker::endpoint& endpoint_;
std::string query_id_;
};
// Parses Broker data as Bro event.
caf::expected<std::pair<std::string, std::string>>
parse_query_event(const broker::data& x) {
std::pair<std::string, std::string> result;
auto event = broker::bro::Event(x);
if (event.name() != "VAST::query")
return make_error(vast::ec::parse_error, "invalid event name", event.name());
if (event.args().size() != 2)
return make_error(vast::ec::parse_error, "invalid number of arguments");
auto query_id = caf::get_if<std::string>(&event.args()[0]);
if (!query_id)
return make_error(vast::ec::parse_error, "invalid type of 1st argument");
result.first = *query_id;
if (!vast::parsers::uuid(*query_id))
return make_error(vast::ec::parse_error, "invalid query UUID", *query_id);
auto expression = caf::get_if<std::string>(&event.args()[1]);
if (!expression)
return make_error(vast::ec::parse_error, "invalid type of 2nd argument");
if (!vast::parsers::expr(*expression))
return make_error(vast::ec::parse_error, "invalid query expression",
*expression);
result.second = *expression;
return result;
}
} // namespace <anonymous>
int main(int argc, char** argv) {
// Parse the command line.
config cfg;
vast::detail::add_message_types(cfg);
cfg.parse(argc, argv);
std::string address = caf::get_or(cfg, "address", default_address);
uint16_t port = caf::get_or(cfg, "port", default_port);
// Create a Broker endpoint.
auto endpoint = broker::endpoint{std::move(cfg)};
endpoint.listen(address, port);
// Subscribe to the control channel.
auto subscriber = endpoint.make_subscriber({control_topic});
// Connect to VAST via a custom command.
bro_command cmd{endpoint};
auto& sys = endpoint.system();
caf::scoped_actor self{sys};
caf::config_value_map opts;
auto node = cmd.connect_to_node(self, opts);
if (!node) {
std::cerr << "failed to connect to VAST: " << sys.render(node.error())
<< std::endl;
return 1;
}
std::cerr << "connected to VAST successfully" << std::endl;
// Block until Bro peers with us.
auto receive_statuses = true;
auto status_subscriber = endpoint.make_status_subscriber(receive_statuses);
auto peered = false;
while (!peered) {
auto msg = status_subscriber.get();
caf::visit(vast::detail::overload(
[&](broker::none) {
// timeout
},
[&](broker::error error) {
std::cerr << sys.render(error) << std::endl;
},
[&](broker::status status) {
if (status == broker::sc::peer_added)
peered = true;
else
std::cerr << to_string(status) << std::endl;
}
), msg);
};
std::cerr << "peered with Bro successfully" << std::endl;
// Process queries from Bro.
auto done = false;
while (!done) {
std::cerr << "waiting for commands" << std::endl;
auto [topic, data] = subscriber.get();
// Parse the Bro query event.
auto result = parse_query_event(data);
if (!result) {
std::cerr << sys.render(result.error()) << std::endl;
return 1;
}
auto& [query_id, expression] = *result;
// Relay the query expression to VAST.
cmd.query_id(query_id);
auto args = std::vector<std::string>{expression};
auto rc = cmd.run(sys, args.begin(), args.end());
if (rc != 0) {
std::cerr << "failed to dispatch query to VAST" << std::endl;
return rc;
}
// A none value signals that the query has completed.
endpoint.publish(data_topic, make_bro_event(query_id, broker::nil));
}
}
<commit_msg>Add VAST error categories to Broker config<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <cstdint>
#include <iostream>
#include <string>
#include <caf/config_option_adder.hpp>
#include <broker/bro.hh>
#include <broker/broker.hh>
#include <vast/defaults.hpp>
#include <vast/error.hpp>
#include <vast/event.hpp>
#include <vast/expression.hpp>
#include <vast/uuid.hpp>
#include <vast/concept/parseable/parse.hpp>
#include <vast/concept/parseable/vast/expression.hpp>
#include <vast/concept/parseable/vast/uuid.hpp>
#include <vast/system/writer_command_base.hpp>
#include <vast/system/sink.hpp>
#include <vast/detail/add_error_categories.hpp>
#include <vast/detail/add_message_types.hpp>
#include <vast/detail/assert.hpp>
#include <vast/detail/overload.hpp>
namespace {
constexpr char control_topic[] = "/vast/control";
constexpr char data_topic[] = "/vast/data";
constexpr char default_address[] = "localhost";
constexpr uint16_t default_port = 43000;
// Our custom configuration with extra command line options for this tool.
class config : public broker::configuration {
public:
config() {
// As a stand-alone application, we reuse the global option group from CAF
// to avoid unnecessary prefixing.
opt_group{custom_options_, "global"}
.add<uint16_t>("port,p", "the port to listen at or connect to");
}
};
// Constructs a result event for Bro.
broker::bro::Event make_bro_event(std::string id, broker::data x) {
broker::vector args(2);
args[0] = std::move(id);
args[1] = std::move(x);
return {"VAST::result", std::move(args)};
}
// A VAST writer that publishes the event it gets to a Bro endpoint.
class bro_writer {
public:
bro_writer() = default;
bro_writer(broker::endpoint& endpoint, std::string query_id)
: endpoint_{&endpoint},
query_id_{std::move(query_id)} {
// nop
}
caf::expected<void> write(const vast::event& x) {
// TODO: publish to Broker endpoint.
std::cout << x.type().name() << std::endl;
return caf::no_error;
}
caf::expected<void> flush() {
return caf::no_error;
}
auto name() const {
return "bro-writer";
}
private:
broker::endpoint* endpoint_;
std::string query_id_;
};
// A custom command that allows us to re-use VAST command dispatching logic in
// order to issue a query that writes into a sink with a custom format.
class bro_command : public vast::system::writer_command_base {
public:
bro_command(broker::endpoint& endpoint)
: writer_command_base{nullptr, "bro"},
endpoint_{endpoint} {
// nop
}
// Sets the query ID to the UUID provided by Bro.
void query_id(std::string id) {
query_id_ = std::move(id);
}
protected:
caf::expected<caf::actor> make_sink(caf::scoped_actor& self,
const caf::config_value_map& options,
argument_iterator begin,
argument_iterator end) override {
VAST_UNUSED(options, begin, end);
bro_writer writer{endpoint_, query_id_};
return self->spawn(vast::system::sink<bro_writer>, std::move(writer),
vast::defaults::command::max_events);
}
private:
broker::endpoint& endpoint_;
std::string query_id_;
};
// Parses Broker data as Bro event.
caf::expected<std::pair<std::string, std::string>>
parse_query_event(const broker::data& x) {
std::pair<std::string, std::string> result;
auto event = broker::bro::Event(x);
if (event.name() != "VAST::query")
return make_error(vast::ec::parse_error, "invalid event name", event.name());
if (event.args().size() != 2)
return make_error(vast::ec::parse_error, "invalid number of arguments");
auto query_id = caf::get_if<std::string>(&event.args()[0]);
if (!query_id)
return make_error(vast::ec::parse_error, "invalid type of 1st argument");
result.first = *query_id;
if (!vast::parsers::uuid(*query_id))
return make_error(vast::ec::parse_error, "invalid query UUID", *query_id);
auto expression = caf::get_if<std::string>(&event.args()[1]);
if (!expression)
return make_error(vast::ec::parse_error, "invalid type of 2nd argument");
if (!vast::parsers::expr(*expression))
return make_error(vast::ec::parse_error, "invalid query expression",
*expression);
result.second = *expression;
return result;
}
} // namespace <anonymous>
int main(int argc, char** argv) {
// Parse the command line.
config cfg;
vast::detail::add_message_types(cfg);
vast::detail::add_error_categories(cfg);
cfg.parse(argc, argv);
std::string address = caf::get_or(cfg, "address", default_address);
uint16_t port = caf::get_or(cfg, "port", default_port);
// Create a Broker endpoint.
auto endpoint = broker::endpoint{std::move(cfg)};
endpoint.listen(address, port);
// Subscribe to the control channel.
auto subscriber = endpoint.make_subscriber({control_topic});
// Connect to VAST via a custom command.
bro_command cmd{endpoint};
auto& sys = endpoint.system();
caf::scoped_actor self{sys};
caf::config_value_map opts;
auto node = cmd.connect_to_node(self, opts);
if (!node) {
std::cerr << "failed to connect to VAST: " << sys.render(node.error())
<< std::endl;
return 1;
}
std::cerr << "connected to VAST successfully" << std::endl;
// Block until Bro peers with us.
auto receive_statuses = true;
auto status_subscriber = endpoint.make_status_subscriber(receive_statuses);
auto peered = false;
while (!peered) {
auto msg = status_subscriber.get();
caf::visit(vast::detail::overload(
[&](broker::none) {
// timeout
},
[&](broker::error error) {
std::cerr << sys.render(error) << std::endl;
},
[&](broker::status status) {
if (status == broker::sc::peer_added)
peered = true;
else
std::cerr << to_string(status) << std::endl;
}
), msg);
};
std::cerr << "peered with Bro successfully" << std::endl;
// Process queries from Bro.
auto done = false;
while (!done) {
std::cerr << "waiting for commands" << std::endl;
auto [topic, data] = subscriber.get();
// Parse the Bro query event.
auto result = parse_query_event(data);
if (!result) {
std::cerr << sys.render(result.error()) << std::endl;
return 1;
}
auto& [query_id, expression] = *result;
// Relay the query expression to VAST.
cmd.query_id(query_id);
auto args = std::vector<std::string>{expression};
auto rc = cmd.run(sys, args.begin(), args.end());
if (rc != 0) {
std::cerr << "failed to dispatch query to VAST" << std::endl;
return rc;
}
// A none value signals that the query has completed.
endpoint.publish(data_topic, make_bro_event(query_id, broker::nil));
}
}
<|endoftext|> |
<commit_before>//===- CoverageReport.cpp - Code coverage report -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class implements rendering of a code coverage report.
//
//===----------------------------------------------------------------------===//
#include "CoverageReport.h"
#include "RenderingSupport.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Format.h"
using namespace llvm;
namespace {
/// \brief Helper struct which prints trimmed and aligned columns.
struct Column {
enum TrimKind { NoTrim, WidthTrim, LeftTrim, RightTrim };
enum AlignmentKind { LeftAlignment, RightAlignment };
StringRef Str;
unsigned Width;
TrimKind Trim;
AlignmentKind Alignment;
Column(StringRef Str, unsigned Width)
: Str(Str), Width(Width), Trim(WidthTrim), Alignment(LeftAlignment) {}
Column &set(TrimKind Value) {
Trim = Value;
return *this;
}
Column &set(AlignmentKind Value) {
Alignment = Value;
return *this;
}
void render(raw_ostream &OS) const;
};
raw_ostream &operator<<(raw_ostream &OS, const Column &Value) {
Value.render(OS);
return OS;
}
}
void Column::render(raw_ostream &OS) const {
if (Str.size() <= Width) {
if (Alignment == RightAlignment) {
OS.indent(Width - Str.size());
OS << Str;
return;
}
OS << Str;
OS.indent(Width - Str.size());
return;
}
switch (Trim) {
case NoTrim:
OS << Str;
break;
case WidthTrim:
OS << Str.substr(0, Width);
break;
case LeftTrim:
OS << "..." << Str.substr(Str.size() - Width + 3);
break;
case RightTrim:
OS << Str.substr(0, Width - 3) << "...";
break;
}
}
static Column column(StringRef Str, unsigned Width) {
return Column(Str, Width);
}
template <typename T>
static Column column(StringRef Str, unsigned Width, const T &Value) {
return Column(Str, Width).set(Value);
}
static size_t FileReportColumns[] = {25, 10, 8, 8, 10, 10};
static size_t FunctionReportColumns[] = {25, 10, 8, 8, 10, 8, 8};
/// \brief Prints a horizontal divider which spans across the given columns.
template <typename T, size_t N>
static void renderDivider(T (&Columns)[N], raw_ostream &OS) {
unsigned Length = 0;
for (unsigned I = 0; I < N; ++I)
Length += Columns[I];
for (unsigned I = 0; I < Length; ++I)
OS << '-';
}
/// \brief Return the color which correponds to the coverage
/// percentage of a certain metric.
template <typename T>
static raw_ostream::Colors determineCoveragePercentageColor(const T &Info) {
if (Info.isFullyCovered())
return raw_ostream::GREEN;
return Info.getPercentCovered() >= 80.0 ? raw_ostream::YELLOW
: raw_ostream::RED;
}
void CoverageReport::render(const FileCoverageSummary &File, raw_ostream &OS) {
OS << column(File.Name, FileReportColumns[0], Column::NoTrim)
<< format("%*u", FileReportColumns[1],
(unsigned)File.RegionCoverage.NumRegions);
Options.colored_ostream(OS, File.RegionCoverage.isFullyCovered()
? raw_ostream::GREEN
: raw_ostream::RED)
<< format("%*u", FileReportColumns[2], (unsigned)File.RegionCoverage.NotCovered);
Options.colored_ostream(OS,
determineCoveragePercentageColor(File.RegionCoverage))
<< format("%*.2f", FileReportColumns[3] - 1,
File.RegionCoverage.getPercentCovered()) << '%';
OS << format("%*u", FileReportColumns[4],
(unsigned)File.FunctionCoverage.NumFunctions);
Options.colored_ostream(
OS, determineCoveragePercentageColor(File.FunctionCoverage))
<< format("%*.2f", FileReportColumns[5] - 1,
File.FunctionCoverage.getPercentCovered()) << '%';
OS << "\n";
}
void CoverageReport::render(const FunctionCoverageSummary &Function,
raw_ostream &OS) {
OS << column(Function.Name, FunctionReportColumns[0], Column::RightTrim)
<< format("%*u", FunctionReportColumns[1],
(unsigned)Function.RegionCoverage.NumRegions);
Options.colored_ostream(OS, Function.RegionCoverage.isFullyCovered()
? raw_ostream::GREEN
: raw_ostream::RED)
<< format("%*u", FunctionReportColumns[2],
(unsigned)Function.RegionCoverage.NotCovered);
Options.colored_ostream(
OS, determineCoveragePercentageColor(Function.RegionCoverage))
<< format("%*.2f", FunctionReportColumns[3] - 1,
Function.RegionCoverage.getPercentCovered()) << '%';
OS << format("%*u", FunctionReportColumns[4],
(unsigned)Function.LineCoverage.NumLines);
Options.colored_ostream(OS, Function.LineCoverage.isFullyCovered()
? raw_ostream::GREEN
: raw_ostream::RED)
<< format("%*u", FunctionReportColumns[5],
(unsigned)Function.LineCoverage.NotCovered);
Options.colored_ostream(
OS, determineCoveragePercentageColor(Function.LineCoverage))
<< format("%*.2f", FunctionReportColumns[6] - 1,
Function.LineCoverage.getPercentCovered()) << '%';
OS << "\n";
}
void CoverageReport::renderFunctionReports(ArrayRef<std::string> Files,
raw_ostream &OS) {
bool isFirst = true;
for (StringRef Filename : Files) {
if (isFirst)
isFirst = false;
else
OS << "\n";
OS << "File '" << Filename << "':\n";
OS << column("Name", FunctionReportColumns[0])
<< column("Regions", FunctionReportColumns[1], Column::RightAlignment)
<< column("Miss", FunctionReportColumns[2], Column::RightAlignment)
<< column("Cover", FunctionReportColumns[3], Column::RightAlignment)
<< column("Lines", FunctionReportColumns[4], Column::RightAlignment)
<< column("Miss", FunctionReportColumns[5], Column::RightAlignment)
<< column("Cover", FunctionReportColumns[6], Column::RightAlignment);
OS << "\n";
renderDivider(FunctionReportColumns, OS);
OS << "\n";
FunctionCoverageSummary Totals("TOTAL");
for (const auto &F : Coverage->getCoveredFunctions(Filename)) {
FunctionCoverageSummary Function = FunctionCoverageSummary::get(F);
++Totals.ExecutionCount;
Totals.RegionCoverage += Function.RegionCoverage;
Totals.LineCoverage += Function.LineCoverage;
render(Function, OS);
}
if (Totals.ExecutionCount) {
renderDivider(FunctionReportColumns, OS);
OS << "\n";
render(Totals, OS);
}
}
}
void CoverageReport::renderFileReports(raw_ostream &OS) {
// Adjust column widths to accomodate long paths and names.
for (StringRef Filename : Coverage->getUniqueSourceFiles()) {
FileReportColumns[0] = std::max(FileReportColumns[0], Filename.size());
for (const auto &F : Coverage->getCoveredFunctions(Filename)) {
FunctionReportColumns[0] =
std::max(FunctionReportColumns[0], F.Name.size());
}
}
OS << column("Filename", FileReportColumns[0])
<< column("Regions", FileReportColumns[1], Column::RightAlignment)
<< column("Miss", FileReportColumns[2], Column::RightAlignment)
<< column("Cover", FileReportColumns[3], Column::RightAlignment)
<< column("Functions", FileReportColumns[4], Column::RightAlignment)
<< column("Executed", FileReportColumns[5], Column::RightAlignment)
<< "\n";
renderDivider(FileReportColumns, OS);
OS << "\n";
FileCoverageSummary Totals("TOTAL");
for (StringRef Filename : Coverage->getUniqueSourceFiles()) {
FileCoverageSummary Summary(Filename);
for (const auto &F : Coverage->getCoveredFunctions(Filename)) {
FunctionCoverageSummary Function = FunctionCoverageSummary::get(F);
Summary.addFunction(Function);
Totals.addFunction(Function);
}
render(Summary, OS);
}
renderDivider(FileReportColumns, OS);
OS << "\n";
render(Totals, OS);
}
<commit_msg>[llvm-cov] Adjust column widths for function and file reports<commit_after>//===- CoverageReport.cpp - Code coverage report -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class implements rendering of a code coverage report.
//
//===----------------------------------------------------------------------===//
#include "CoverageReport.h"
#include "RenderingSupport.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Format.h"
using namespace llvm;
namespace {
/// \brief Helper struct which prints trimmed and aligned columns.
struct Column {
enum TrimKind { NoTrim, WidthTrim, LeftTrim, RightTrim };
enum AlignmentKind { LeftAlignment, RightAlignment };
StringRef Str;
unsigned Width;
TrimKind Trim;
AlignmentKind Alignment;
Column(StringRef Str, unsigned Width)
: Str(Str), Width(Width), Trim(WidthTrim), Alignment(LeftAlignment) {}
Column &set(TrimKind Value) {
Trim = Value;
return *this;
}
Column &set(AlignmentKind Value) {
Alignment = Value;
return *this;
}
void render(raw_ostream &OS) const;
};
raw_ostream &operator<<(raw_ostream &OS, const Column &Value) {
Value.render(OS);
return OS;
}
}
void Column::render(raw_ostream &OS) const {
if (Str.size() <= Width) {
if (Alignment == RightAlignment) {
OS.indent(Width - Str.size());
OS << Str;
return;
}
OS << Str;
OS.indent(Width - Str.size());
return;
}
switch (Trim) {
case NoTrim:
OS << Str;
break;
case WidthTrim:
OS << Str.substr(0, Width);
break;
case LeftTrim:
OS << "..." << Str.substr(Str.size() - Width + 3);
break;
case RightTrim:
OS << Str.substr(0, Width - 3) << "...";
break;
}
}
static Column column(StringRef Str, unsigned Width) {
return Column(Str, Width);
}
template <typename T>
static Column column(StringRef Str, unsigned Width, const T &Value) {
return Column(Str, Width).set(Value);
}
static size_t FileReportColumns[] = {25, 10, 8, 8, 10, 10};
static size_t FunctionReportColumns[] = {25, 10, 8, 8, 10, 8, 8};
/// \brief Adjust column widths to fit long file paths and function names.
static void adjustColumnWidths(coverage::CoverageMapping *CM) {
for (StringRef Filename : CM->getUniqueSourceFiles()) {
FileReportColumns[0] = std::max(FileReportColumns[0], Filename.size());
for (const auto &F : CM->getCoveredFunctions(Filename)) {
FunctionReportColumns[0] =
std::max(FunctionReportColumns[0], F.Name.size());
}
}
}
/// \brief Prints a horizontal divider which spans across the given columns.
template <typename T, size_t N>
static void renderDivider(T (&Columns)[N], raw_ostream &OS) {
unsigned Length = 0;
for (unsigned I = 0; I < N; ++I)
Length += Columns[I];
for (unsigned I = 0; I < Length; ++I)
OS << '-';
}
/// \brief Return the color which correponds to the coverage
/// percentage of a certain metric.
template <typename T>
static raw_ostream::Colors determineCoveragePercentageColor(const T &Info) {
if (Info.isFullyCovered())
return raw_ostream::GREEN;
return Info.getPercentCovered() >= 80.0 ? raw_ostream::YELLOW
: raw_ostream::RED;
}
void CoverageReport::render(const FileCoverageSummary &File, raw_ostream &OS) {
OS << column(File.Name, FileReportColumns[0], Column::NoTrim)
<< format("%*u", FileReportColumns[1],
(unsigned)File.RegionCoverage.NumRegions);
Options.colored_ostream(OS, File.RegionCoverage.isFullyCovered()
? raw_ostream::GREEN
: raw_ostream::RED)
<< format("%*u", FileReportColumns[2], (unsigned)File.RegionCoverage.NotCovered);
Options.colored_ostream(OS,
determineCoveragePercentageColor(File.RegionCoverage))
<< format("%*.2f", FileReportColumns[3] - 1,
File.RegionCoverage.getPercentCovered()) << '%';
OS << format("%*u", FileReportColumns[4],
(unsigned)File.FunctionCoverage.NumFunctions);
Options.colored_ostream(
OS, determineCoveragePercentageColor(File.FunctionCoverage))
<< format("%*.2f", FileReportColumns[5] - 1,
File.FunctionCoverage.getPercentCovered()) << '%';
OS << "\n";
}
void CoverageReport::render(const FunctionCoverageSummary &Function,
raw_ostream &OS) {
OS << column(Function.Name, FunctionReportColumns[0], Column::RightTrim)
<< format("%*u", FunctionReportColumns[1],
(unsigned)Function.RegionCoverage.NumRegions);
Options.colored_ostream(OS, Function.RegionCoverage.isFullyCovered()
? raw_ostream::GREEN
: raw_ostream::RED)
<< format("%*u", FunctionReportColumns[2],
(unsigned)Function.RegionCoverage.NotCovered);
Options.colored_ostream(
OS, determineCoveragePercentageColor(Function.RegionCoverage))
<< format("%*.2f", FunctionReportColumns[3] - 1,
Function.RegionCoverage.getPercentCovered()) << '%';
OS << format("%*u", FunctionReportColumns[4],
(unsigned)Function.LineCoverage.NumLines);
Options.colored_ostream(OS, Function.LineCoverage.isFullyCovered()
? raw_ostream::GREEN
: raw_ostream::RED)
<< format("%*u", FunctionReportColumns[5],
(unsigned)Function.LineCoverage.NotCovered);
Options.colored_ostream(
OS, determineCoveragePercentageColor(Function.LineCoverage))
<< format("%*.2f", FunctionReportColumns[6] - 1,
Function.LineCoverage.getPercentCovered()) << '%';
OS << "\n";
}
void CoverageReport::renderFunctionReports(ArrayRef<std::string> Files,
raw_ostream &OS) {
adjustColumnWidths(Coverage.get());
bool isFirst = true;
for (StringRef Filename : Files) {
if (isFirst)
isFirst = false;
else
OS << "\n";
OS << "File '" << Filename << "':\n";
OS << column("Name", FunctionReportColumns[0])
<< column("Regions", FunctionReportColumns[1], Column::RightAlignment)
<< column("Miss", FunctionReportColumns[2], Column::RightAlignment)
<< column("Cover", FunctionReportColumns[3], Column::RightAlignment)
<< column("Lines", FunctionReportColumns[4], Column::RightAlignment)
<< column("Miss", FunctionReportColumns[5], Column::RightAlignment)
<< column("Cover", FunctionReportColumns[6], Column::RightAlignment);
OS << "\n";
renderDivider(FunctionReportColumns, OS);
OS << "\n";
FunctionCoverageSummary Totals("TOTAL");
for (const auto &F : Coverage->getCoveredFunctions(Filename)) {
FunctionCoverageSummary Function = FunctionCoverageSummary::get(F);
++Totals.ExecutionCount;
Totals.RegionCoverage += Function.RegionCoverage;
Totals.LineCoverage += Function.LineCoverage;
render(Function, OS);
}
if (Totals.ExecutionCount) {
renderDivider(FunctionReportColumns, OS);
OS << "\n";
render(Totals, OS);
}
}
}
void CoverageReport::renderFileReports(raw_ostream &OS) {
adjustColumnWidths(Coverage.get());
OS << column("Filename", FileReportColumns[0])
<< column("Regions", FileReportColumns[1], Column::RightAlignment)
<< column("Miss", FileReportColumns[2], Column::RightAlignment)
<< column("Cover", FileReportColumns[3], Column::RightAlignment)
<< column("Functions", FileReportColumns[4], Column::RightAlignment)
<< column("Executed", FileReportColumns[5], Column::RightAlignment)
<< "\n";
renderDivider(FileReportColumns, OS);
OS << "\n";
FileCoverageSummary Totals("TOTAL");
for (StringRef Filename : Coverage->getUniqueSourceFiles()) {
FileCoverageSummary Summary(Filename);
for (const auto &F : Coverage->getCoveredFunctions(Filename)) {
FunctionCoverageSummary Function = FunctionCoverageSummary::get(F);
Summary.addFunction(Function);
Totals.addFunction(Function);
}
render(Summary, OS);
}
renderDivider(FileReportColumns, OS);
OS << "\n";
render(Totals, OS);
}
<|endoftext|> |
<commit_before>/* tests/win32/msgwnd.cpp
*
* Copyright (C) 2007 Antonio Di Monaco
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#include "tests/catch.hpp"
#include "win32/msgwnd.hpp"
TEST_CASE("Message window", "[Win32]")
{
SECTION("send a message")
{
Windows::MsgWnd w(
GetModuleHandle(NULL),
[] (UINT uMsg, WPARAM wP, LPARAM lP)
{
REQUIRE(uMsg == (WM_USER + 1));
REQUIRE(wP == static_cast< WPARAM >(0x01234567));
REQUIRE(lP == static_cast< LPARAM >(0x89ABCDEF));
});
w.start();
REQUIRE(w.handle() != NULL);
SendMessage(w.handle(),WM_USER + 1,static_cast< WPARAM >(0x01234567),static_cast< LPARAM >(0x89ABCDEF));
}
}
extern "C" int wmain(int argc, wchar_t **argv, wchar_t **)
{
return run(argc,argv);
}
<commit_msg>Fixing msgwnd test<commit_after>/* tests/win32/msgwnd.cpp
*
* Copyright (C) 2007 Antonio Di Monaco
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#include "tests/catch.hpp"
#include "win32/msgwnd.hpp"
#include "win32/synch.hpp"
TEST_CASE("Message window", "[Win32]")
{
SECTION("send a message")
{
Windows::Synch::Semaphore s(0,1);
REQUIRE(s);
bool flag = false;
Windows::MsgWnd w(
GetModuleHandle(NULL),
[&s, &flag] (UINT uMsg, WPARAM wP, LPARAM lP)
{
if ((uMsg == (WM_USER + 1)) &&
(wP == static_cast< WPARAM >(0x01234567)) &&
(lP == static_cast< LPARAM >(0x89ABCDEF)))
flag = true;
s.release();
});
w.start();
REQUIRE(w.handle() != NULL);
PostMessage(
w.handle(),
WM_USER + 1,
static_cast< WPARAM >(0x01234567),
static_cast< LPARAM >(0x89ABCDEF));
s.acquire();
REQUIRE(flag);
}
}
extern "C" int wmain(int argc, wchar_t **argv, wchar_t **)
{
return run(argc,argv);
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* thrill/mem/manager.hpp
*
* Part of Project Thrill.
*
* Copyright (C) 2015 Timo Bingmann <[email protected]>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef THRILL_MEM_MANAGER_HEADER
#define THRILL_MEM_MANAGER_HEADER
#include <algorithm>
#include <atomic>
#include <cassert>
namespace thrill {
namespace mem {
/*!
* Object shared by allocators and other classes to track memory
* allocations. These is one global mem::Manager per compute host. To track
* memory consumption of subcomponents of Thrill, one can create local child
* mem::Managers which report allocation automatically to their superiors.
*/
class Manager
{
static const bool debug = true;
public:
explicit Manager(Manager* super, const char* name)
: super_(super), name_(name)
{ }
~Manager();
//! return the superior Manager
Manager * super() { return super_; }
//! return total allocation (local value)
size_t total() const { return total_; }
//! add memory consumption.
Manager & add(size_t amount) {
size_t current = (total_ += amount);
peak_ = std::max(peak_.load(), current);
++alloc_count_;
if (super_) super_->add(amount);
return *this;
}
//! subtract memory consumption.
Manager & subtract(size_t amount) {
assert(total_ >= amount);
total_ -= amount;
if (super_) super_->subtract(amount);
return *this;
}
protected:
//! reference to superior memory counter
Manager* super_;
//! description for output
const char* name_;
//! total allocation
std::atomic<size_t> total_ { 0 };
//! peak allocation
std::atomic<size_t> peak_ { 0 };
//! number of allocation
std::atomic<size_t> alloc_count_ { 0 };
};
} // namespace mem
} // namespace thrill
#endif // !THRILL_MEM_MANAGER_HEADER
/******************************************************************************/
<commit_msg>debug = false<commit_after>/*******************************************************************************
* thrill/mem/manager.hpp
*
* Part of Project Thrill.
*
* Copyright (C) 2015 Timo Bingmann <[email protected]>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef THRILL_MEM_MANAGER_HEADER
#define THRILL_MEM_MANAGER_HEADER
#include <algorithm>
#include <atomic>
#include <cassert>
namespace thrill {
namespace mem {
/*!
* Object shared by allocators and other classes to track memory
* allocations. These is one global mem::Manager per compute host. To track
* memory consumption of subcomponents of Thrill, one can create local child
* mem::Managers which report allocation automatically to their superiors.
*/
class Manager
{
static const bool debug = false;
public:
explicit Manager(Manager* super, const char* name)
: super_(super), name_(name)
{ }
~Manager();
//! return the superior Manager
Manager * super() { return super_; }
//! return total allocation (local value)
size_t total() const { return total_; }
//! add memory consumption.
Manager & add(size_t amount) {
size_t current = (total_ += amount);
peak_ = std::max(peak_.load(), current);
++alloc_count_;
if (super_) super_->add(amount);
return *this;
}
//! subtract memory consumption.
Manager & subtract(size_t amount) {
assert(total_ >= amount);
total_ -= amount;
if (super_) super_->subtract(amount);
return *this;
}
protected:
//! reference to superior memory counter
Manager* super_;
//! description for output
const char* name_;
//! total allocation
std::atomic<size_t> total_ { 0 };
//! peak allocation
std::atomic<size_t> peak_ { 0 };
//! number of allocation
std::atomic<size_t> alloc_count_ { 0 };
};
} // namespace mem
} // namespace thrill
#endif // !THRILL_MEM_MANAGER_HEADER
/******************************************************************************/
<|endoftext|> |
<commit_before>/**
@file ConnectionSTREAMEntry.cpp
@author Lime Microsystems
@brief Implementation of STREAM board connection.
*/
#include "ConnectionSTREAM.h"
#include <iostream>
using namespace lime;
#ifdef __unix__
void ConnectionSTREAMEntry::handle_libusb_events()
{
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 250000;
while(mProcessUSBEvents.load() == true)
{
int r = libusb_handle_events_timeout_completed(ctx, &tv, NULL);
if(r != 0) printf("error libusb_handle_events %s\n", libusb_strerror(libusb_error(r)));
}
}
#endif // __UNIX__
//! make a static-initialized entry in the registry
void __loadConnectionSTREAMEntry(void) //TODO fixme replace with LoadLibrary/dlopen
{
static ConnectionSTREAMEntry STREAMEntry;
}
int USBTransferContext::idCounter = 0;
ConnectionSTREAMEntry::ConnectionSTREAMEntry(void):
ConnectionRegistryEntry("STREAM")
{
#ifdef __unix__
int r = libusb_init(&ctx); //initialize the library for the session we just declared
if(r < 0)
printf("Init Error %i\n", r); //there was an error
libusb_set_debug(ctx, 3); //set verbosity level to 3, as suggested in the documentation
mProcessUSBEvents.store(true);
mUSBProcessingThread = std::thread(&ConnectionSTREAMEntry::handle_libusb_events, this);
#endif
}
ConnectionSTREAMEntry::ConnectionSTREAMEntry(const std::string entryName):
ConnectionRegistryEntry(entryName)
{
#ifdef __unix__
int r = libusb_init(&ctx); //initialize the library for the session we just declared
if(r < 0)
printf("Init Error %i\n", r); //there was an error
libusb_set_debug(ctx, 3); //set verbosity level to 3, as suggested in the documentation
mProcessUSBEvents.store(true);
mUSBProcessingThread = std::thread(&ConnectionSTREAMEntry::handle_libusb_events, this);
#endif
}
ConnectionSTREAMEntry::~ConnectionSTREAMEntry(void)
{
#ifdef __unix__
mProcessUSBEvents.store(false);
mUSBProcessingThread.join();
libusb_exit(ctx);
#endif
}
#ifndef __unix__
/** @return name of usb device as string.
@param index device index in list
*/
std::string ConnectionSTREAMEntry::DeviceName(unsigned int index)
{
std::string name;
char tempName[USB_STRING_MAXLEN];
CCyUSBDevice device;
if (index >= device.DeviceCount())
return "";
for (int i = 0; i < USB_STRING_MAXLEN; ++i)
tempName[i] = device.DeviceName[i];
if (device.bSuperSpeed == true)
name = "USB 3.0";
else if (device.bHighSpeed == true)
name = "USB 2.0";
else
name = "USB";
name += " (";
name += tempName;
name += ")";
return name;
}
#endif
std::vector<ConnectionHandle> ConnectionSTREAMEntry::enumerate(const ConnectionHandle &hint)
{
std::vector<ConnectionHandle> handles;
#ifndef __unix__
CCyUSBDevice device;
if (device.DeviceCount())
{
for (int i = 0; i<device.DeviceCount(); ++i)
{
if (hint.index >= 0 && hint.index != i)
continue;
if (device.IsOpen())
device.Close();
device.Open(i);
ConnectionHandle handle;
handle.media = "USB";
handle.name = DeviceName(i);
handle.index = i;
std::wstring ws(device.SerialNumber);
handle.serial = std::string(ws.begin(),ws.end());
if (hint.serial.empty() or hint.serial == handle.serial)
{
handles.push_back(handle); //filter on serial
}
device.Close();
}
}
#else
libusb_device **devs; //pointer to pointer of device, used to retrieve a list of devices
int usbDeviceCount = libusb_get_device_list(ctx, &devs);
if(usbDeviceCount > 0)
{
for(int i=0; i<usbDeviceCount; ++i)
{
libusb_device_descriptor desc;
int r = libusb_get_device_descriptor(devs[i], &desc);
if(r<0)
printf("failed to get device description\n");
int pid = desc.idProduct;
int vid = desc.idVendor;
if(vid == 1204 && pid == 34323)
{
ConnectionHandle handle;
handle.media = "USB";
handle.name = "DigiGreen";
handle.addr = std::to_string(int(pid))+":"+std::to_string(int(vid));
handles.push_back(handle);
}
else if((vid == 1204 && pid == 241) || (vid == 1204 && pid == 243) || (vid == 7504 && pid == 24840))
{
libusb_device_handle *tempDev_handle(nullptr);
if(libusb_open(devs[i], &tempDev_handle) != 0 || tempDev_handle == nullptr)
continue;
if(libusb_kernel_driver_active(tempDev_handle, 0) == 1) //find out if kernel driver is attached
{
if(libusb_detach_kernel_driver(tempDev_handle, 0) == 0) //detach it
printf("Kernel Driver Detached!\n");
}
if(libusb_claim_interface(tempDev_handle, 0) < 0) //claim interface 0 (the first) of device
{
printf("Cannot Claim Interface\n");
}
std::string fullName;
//check operating speed
int speed = libusb_get_device_speed(devs[i]);
if(speed == LIBUSB_SPEED_HIGH)
fullName = "USB 2.0";
else if(speed == LIBUSB_SPEED_SUPER)
fullName = "USB 3.0";
else
fullName = "USB";
fullName += " (";
//read device name
char data[255];
r = libusb_get_string_descriptor_ascii(tempDev_handle, LIBUSB_CLASS_COMM, (unsigned char*)data, sizeof(data));
if(r > 0) fullName += std::string(data, size_t(r));
fullName += ")";
ConnectionHandle handle;
handle.media = "USB";
handle.name = fullName;
r = std::sprintf(data, "%.4x:%.4x", int(vid), int(pid));
if (r > 0) handle.addr = std::string(data, size_t(r));
if (desc.iSerialNumber > 0)
{
r = libusb_get_string_descriptor_ascii(tempDev_handle,desc.iSerialNumber,(unsigned char*)data, sizeof(data));
if(r<0)
printf("failed to get serial number\n");
else
handle.serial = std::string(data, size_t(r));
}
libusb_close(tempDev_handle);
//add handle conditionally, filter by serial number
if (hint.serial.empty() or hint.serial == handle.serial)
{
handles.push_back(handle);
}
}
}
}
else
{
libusb_free_device_list(devs, 1);
}
#endif
return handles;
}
IConnection *ConnectionSTREAMEntry::make(const ConnectionHandle &handle)
{
return new ConnectionSTREAM(ctx, handle.addr, handle.serial, handle.index);
}
<commit_msg>limesdr - enumerate set media and device name<commit_after>/**
@file ConnectionSTREAMEntry.cpp
@author Lime Microsystems
@brief Implementation of STREAM board connection.
*/
#include "ConnectionSTREAM.h"
#include <iostream>
using namespace lime;
#ifdef __unix__
void ConnectionSTREAMEntry::handle_libusb_events()
{
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 250000;
while(mProcessUSBEvents.load() == true)
{
int r = libusb_handle_events_timeout_completed(ctx, &tv, NULL);
if(r != 0) printf("error libusb_handle_events %s\n", libusb_strerror(libusb_error(r)));
}
}
#endif // __UNIX__
//! make a static-initialized entry in the registry
void __loadConnectionSTREAMEntry(void) //TODO fixme replace with LoadLibrary/dlopen
{
static ConnectionSTREAMEntry STREAMEntry;
}
int USBTransferContext::idCounter = 0;
ConnectionSTREAMEntry::ConnectionSTREAMEntry(void):
ConnectionRegistryEntry("STREAM")
{
#ifdef __unix__
int r = libusb_init(&ctx); //initialize the library for the session we just declared
if(r < 0)
printf("Init Error %i\n", r); //there was an error
libusb_set_debug(ctx, 3); //set verbosity level to 3, as suggested in the documentation
mProcessUSBEvents.store(true);
mUSBProcessingThread = std::thread(&ConnectionSTREAMEntry::handle_libusb_events, this);
#endif
}
ConnectionSTREAMEntry::ConnectionSTREAMEntry(const std::string entryName):
ConnectionRegistryEntry(entryName)
{
#ifdef __unix__
int r = libusb_init(&ctx); //initialize the library for the session we just declared
if(r < 0)
printf("Init Error %i\n", r); //there was an error
libusb_set_debug(ctx, 3); //set verbosity level to 3, as suggested in the documentation
mProcessUSBEvents.store(true);
mUSBProcessingThread = std::thread(&ConnectionSTREAMEntry::handle_libusb_events, this);
#endif
}
ConnectionSTREAMEntry::~ConnectionSTREAMEntry(void)
{
#ifdef __unix__
mProcessUSBEvents.store(false);
mUSBProcessingThread.join();
libusb_exit(ctx);
#endif
}
#ifndef __unix__
/** @return name of usb device as string.
@param index device index in list
*/
std::string ConnectionSTREAMEntry::DeviceName(unsigned int index)
{
std::string name;
char tempName[USB_STRING_MAXLEN];
CCyUSBDevice device;
if (index >= device.DeviceCount())
return "";
for (int i = 0; i < USB_STRING_MAXLEN; ++i)
tempName[i] = device.DeviceName[i];
if (device.bSuperSpeed == true)
name = "USB 3.0";
else if (device.bHighSpeed == true)
name = "USB 2.0";
else
name = "USB";
name += " (";
name += tempName;
name += ")";
return name;
}
#endif
std::vector<ConnectionHandle> ConnectionSTREAMEntry::enumerate(const ConnectionHandle &hint)
{
std::vector<ConnectionHandle> handles;
#ifndef __unix__
CCyUSBDevice device;
if (device.DeviceCount())
{
for (int i = 0; i<device.DeviceCount(); ++i)
{
if (hint.index >= 0 && hint.index != i)
continue;
if (device.IsOpen())
device.Close();
device.Open(i);
ConnectionHandle handle;
handle.media = "USB";
handle.name = DeviceName(i);
handle.index = i;
std::wstring ws(device.SerialNumber);
handle.serial = std::string(ws.begin(),ws.end());
if (hint.serial.empty() or hint.serial == handle.serial)
{
handles.push_back(handle); //filter on serial
}
device.Close();
}
}
#else
libusb_device **devs; //pointer to pointer of device, used to retrieve a list of devices
int usbDeviceCount = libusb_get_device_list(ctx, &devs);
if(usbDeviceCount > 0)
{
for(int i=0; i<usbDeviceCount; ++i)
{
libusb_device_descriptor desc;
int r = libusb_get_device_descriptor(devs[i], &desc);
if(r<0)
printf("failed to get device description\n");
int pid = desc.idProduct;
int vid = desc.idVendor;
if(vid == 1204 && pid == 34323)
{
ConnectionHandle handle;
handle.media = "USB";
handle.name = "DigiGreen";
handle.addr = std::to_string(int(pid))+":"+std::to_string(int(vid));
handles.push_back(handle);
}
else if((vid == 1204 && pid == 241) || (vid == 1204 && pid == 243) || (vid == 7504 && pid == 24840))
{
libusb_device_handle *tempDev_handle(nullptr);
if(libusb_open(devs[i], &tempDev_handle) != 0 || tempDev_handle == nullptr)
continue;
if(libusb_kernel_driver_active(tempDev_handle, 0) == 1) //find out if kernel driver is attached
{
if(libusb_detach_kernel_driver(tempDev_handle, 0) == 0) //detach it
printf("Kernel Driver Detached!\n");
}
if(libusb_claim_interface(tempDev_handle, 0) < 0) //claim interface 0 (the first) of device
{
printf("Cannot Claim Interface\n");
}
ConnectionHandle handle;
//check operating speed
int speed = libusb_get_device_speed(devs[i]);
if(speed == LIBUSB_SPEED_HIGH)
handle.media = "USB 2.0";
else if(speed == LIBUSB_SPEED_SUPER)
handle.media = "USB 3.0";
else
handle.media = "USB";
//read device name
char data[255];
r = libusb_get_string_descriptor_ascii(tempDev_handle, LIBUSB_CLASS_COMM, (unsigned char*)data, sizeof(data));
if(r > 0) handle.name = std::string(data, size_t(r));
r = std::sprintf(data, "%.4x:%.4x", int(vid), int(pid));
if (r > 0) handle.addr = std::string(data, size_t(r));
if (desc.iSerialNumber > 0)
{
r = libusb_get_string_descriptor_ascii(tempDev_handle,desc.iSerialNumber,(unsigned char*)data, sizeof(data));
if(r<0)
printf("failed to get serial number\n");
else
handle.serial = std::string(data, size_t(r));
}
libusb_close(tempDev_handle);
//add handle conditionally, filter by serial number
if (hint.serial.empty() or hint.serial == handle.serial)
{
handles.push_back(handle);
}
}
}
}
else
{
libusb_free_device_list(devs, 1);
}
#endif
return handles;
}
IConnection *ConnectionSTREAMEntry::make(const ConnectionHandle &handle)
{
return new ConnectionSTREAM(ctx, handle.addr, handle.serial, handle.index);
}
<|endoftext|> |
<commit_before>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetVerticalSync(true);
renderEngine = NULL;
ofxMultiGLFWWindow *glfw = (ofxMultiGLFWWindow*)ofGetWindowPtr();
//Look for number of monitors
//
int numberOfMonitors;
GLFWmonitor** monitors = glfwGetMonitors(&numberOfMonitors);
cout<<"Num windows: "<<numberOfMonitors<<endl;
// Setup the render views
//
if(numberOfMonitors == 3){
//Set the main window to full HD
ofSetWindowShape(1920, 1080);
//Find the positions of the monitors
//
vector<ofRectangle> monitorSizes;
for (int iC=0; iC < numberOfMonitors; iC++){
int xM; int yM;
glfwGetMonitorPos(monitors[iC], &xM, &yM);
const GLFWvidmode * desktopMode = glfwGetVideoMode(monitors[iC]);
ofRectangle monitorRect(xM, yM, desktopMode->width, desktopMode->height);
monitorSizes.push_back(monitorRect);
}
//Run through the windows, and create the additional render views
for(int i=0;i<2;i++){
GLFWwindow * window = glfw->createWindow();
glfw->setWindow(window);
if(i==0){
ofSetWindowPosition(monitorSizes[0].width + 200, 100);
} else {
ofSetWindowPosition(monitorSizes[0].width + monitorSizes[1].width + 200, 100);
ofToggleFullscreen();
}
ofToggleFullscreen();
}
glfw->setWindow(glfw->windows.at(0));
glfw->showWindow(glfw->windows.at(0));
} else {
ofToggleFullscreen();
}
// Load STUFF
//
calibration.load();
renderAssets.load();
imageQueue.loadQueueFromFile();
// SETUP Node
//
nodeCommunication.imageQueue = &imageQueue;
nodeCommunication.setup();
// SETUP audio trigger
audioTrigger.setup();
// start the RENDER
//
loadAnimation();
}
void ofApp::loadAnimation(){
if (renderEngine != NULL){
renderEngine->stop();
delete renderEngine;
renderEngine = NULL;
}
renderEngine = new RenderRadar();
// Link renderEngine to ImageQueue
//
imageQueue.renderEngine = renderEngine;
// Loading Resources (this could be pointers)
//
renderEngine->assets = &renderAssets;
// Setup The RenderEngine
//
renderEngine->setup();
renderEngine->addUIClass(&imageQueue);
renderEngine->addUIClass(&nodeCommunication);
renderEngine->addUIClass(&audioTrigger);
renderEngine->setCalibration(&calibration);
// Ready to GO
//
renderEngine->play();
renderEngine->getTimeline()->setDurationInSeconds(5);
}
//--------------------------------------------------------------
void ofApp::update(){
nodeCommunication.update();
imageQueue.update();
}
//--------------------------------------------------------------
void ofApp::draw(){
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<commit_msg>fullscreen on secondary monitor if one<commit_after>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetVerticalSync(true);
renderEngine = NULL;
ofxMultiGLFWWindow *glfw = (ofxMultiGLFWWindow*)ofGetWindowPtr();
//Look for number of monitors
//
int numberOfMonitors;
GLFWmonitor** monitors = glfwGetMonitors(&numberOfMonitors);
cout<<"Num windows: "<<numberOfMonitors<<endl;
// Setup the render views
//
if(numberOfMonitors == 3){
//Set the main window to full HD
ofSetWindowShape(1920, 1080);
//Find the positions of the monitors
//
vector<ofRectangle> monitorSizes;
for (int iC=0; iC < numberOfMonitors; iC++){
int xM; int yM;
glfwGetMonitorPos(monitors[iC], &xM, &yM);
const GLFWvidmode * desktopMode = glfwGetVideoMode(monitors[iC]);
ofRectangle monitorRect(xM, yM, desktopMode->width, desktopMode->height);
monitorSizes.push_back(monitorRect);
}
//Run through the windows, and create the additional render views
for(int i=0;i<2;i++){
GLFWwindow * window = glfw->createWindow();
glfw->setWindow(window);
if(i==0){
ofSetWindowPosition(monitorSizes[0].width + 200, 100);
} else {
ofSetWindowPosition(monitorSizes[0].width + monitorSizes[1].width + 200, 100);
ofToggleFullscreen();
}
ofToggleFullscreen();
}
glfw->setWindow(glfw->windows.at(0));
glfw->showWindow(glfw->windows.at(0));
} else if(numberOfMonitors == 2){
//Find the positions of the monitors
//
vector<ofRectangle> monitorSizes;
for (int iC=0; iC < numberOfMonitors; iC++){
int xM; int yM;
glfwGetMonitorPos(monitors[iC], &xM, &yM);
const GLFWvidmode * desktopMode = glfwGetVideoMode(monitors[iC]);
ofRectangle monitorRect(xM, yM, desktopMode->width, desktopMode->height);
monitorSizes.push_back(monitorRect);
}
ofSetWindowPosition(monitorSizes[0].width + 200, 100);
ofSetFullscreen(true);
} else {
ofToggleFullscreen();
}
// Load STUFF
//
calibration.load();
renderAssets.load();
imageQueue.loadQueueFromFile();
// SETUP Node
//
nodeCommunication.imageQueue = &imageQueue;
nodeCommunication.setup();
// SETUP audio trigger
audioTrigger.setup();
// start the RENDER
//
loadAnimation();
}
void ofApp::loadAnimation(){
if (renderEngine != NULL){
renderEngine->stop();
delete renderEngine;
renderEngine = NULL;
}
renderEngine = new RenderRadar();
// Link renderEngine to ImageQueue
//
imageQueue.renderEngine = renderEngine;
// Loading Resources (this could be pointers)
//
renderEngine->assets = &renderAssets;
// Setup The RenderEngine
//
renderEngine->setup();
renderEngine->addUIClass(&imageQueue);
renderEngine->addUIClass(&nodeCommunication);
renderEngine->addUIClass(&audioTrigger);
renderEngine->setCalibration(&calibration);
// Ready to GO
//
renderEngine->play();
renderEngine->getTimeline()->setDurationInSeconds(5);
}
//--------------------------------------------------------------
void ofApp::update(){
nodeCommunication.update();
imageQueue.update();
}
//--------------------------------------------------------------
void ofApp::draw(){
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<|endoftext|> |
<commit_before>#include "tcpserver.h"
#include "util/net.h"
using namespace std;
using namespace happyntrain::network;
using namespace happyntrain::fd;
namespace happyntrain {
class TCPChannel;
TCPChannel::TCPChannel(EventLoop* eventloop, ConnectionSocketFD&& connectionSocket)
: state_(State::INVALID),
channel_(nullptr),
eventloop_(eventloop),
address_(0),
connectionSocket_(std::forward<ConnectionSocketFD>(connectionSocket)),
inBuffer_(),
predictInBufferSize_(1 << 7),
outBuffer_(),
dataListener_(nullptr)
{}
TCPChannel::~TCPChannel() {}
void TCPChannel::Send(std::string msg) {}
void TCPChannel::Close() {}
// Register channel to eventloop
// including selector, events, and event-callback
void TCPChannel::Register(Ref<TCPChannel> self) {
channel_ = eventloop_->RegisterChannel(connectionSocket_);
// TODO: should register kWriteEventFlag ?
channel_->SetReadEnable();
state_ = State::CONNECTED;
channel_->OnRead([self] { self->OnReadable(); });
}
void TCPChannel::OnReadable() {
if (state_ != State::CONNECTED) {
WARN("connection fd(%d) not in connected state", channel_->fd());
// TODO: handle exception
return;
}
const size_t maxBufferSize = 1 << 15;
while (state_ == State::CONNECTED) {
Ptr<char[]> buffer(new char[predictInBufferSize_]);
ssize_t actualReadSize = connectionSocket_.read(buffer.get(), predictInBufferSize_);
DEBUG("Channel id(%lu) fd(%d) read(%zu/%zd)",
channel_->id(), channel_->fd(), actualReadSize, predictInBufferSize_);
if (actualReadSize == -1) {
int err = connectionSocket_.err();
if (err == EAGAIN || err == EWOULDBLOCK) {
FinishNonBlockingRead();
break;
} else if (err == EINTR) // interrupted
continue;
else {
break;
}
} else if (actualReadSize == 0) {
break;
} else {
inBuffer_.append(buffer.get(), predictInBufferSize_);
if (actualReadSize == predictInBufferSize_ && predictInBufferSize_ < maxBufferSize) {
predictInBufferSize_ <<= 1;
}
}
}
}
void TCPChannel::FinishNonBlockingRead() {
DEBUG("Buffer(%s)", inBuffer_.str().c_str());
if (dataListener_) {
dataListener_(shared_from_this(), inBuffer_);
}
else {
inBuffer_.clear();
}
}
// -------------------
class TCPServer;
//--------------------
TCPServer::TCPServer()
: listenChannel_(nullptr),
eventloop_(nullptr),
address_("127.0.0.1", 12346) {}
TCPServer::TCPServer(EventLoop* eventloop)
: listenChannel_(nullptr),
eventloop_(eventloop),
address_("127.0.0.1", 12346) {}
void TCPServer::Listen(int port) {
address_ = IP4Address(port);
Listen();
}
void TCPServer::Listen() {
ServerSocketFD listenFD;
Bind(listenFD);
EXIT_IF(listenFD.listen(128) == false, "fd(%d) listen to port(%d) failed",
listenFD.fd(), address_.port);
INFO("fd(%d) is now listening on port(%d)", listenFD.fd(), address_.port);
listenChannel_ = eventloop_->RegisterChannel(listenFD);
listenChannel_->SetReadEnable().OnRead([this]() { OnAcceptable(); });
}
void TCPServer::Bind(ServerSocketFD& listenFD) {
// Fail the program if these fail
EXIT_IF(listenFD.invalid(), "create listen socket fd failed");
EXIT_IF(listenFD.setNonBlock() == false, "fd(%d) set NONBLOCK fail",
listenFD.fd());
// Still go on even if these fail
EXPECT(listenFD.setReusePort(), "fd(%d) set REUSEPORT fail", listenFD.fd());
EXPECT(listenFD.setCloseOnExec(), "fd(%d) set CLOSEONEXEC fail",
listenFD.fd());
EXIT_IF(listenFD.bind(address_.host, address_.port) == false,
"fd(%d) bind port(%d) failed", listenFD.fd(), address_.port);
}
void TCPServer::OnAcceptable() {
const int listenFD = listenChannel_->fd();
while (true) {
ConnectionSocketFD connectionSocket(listenFD);
if (connectionSocket.invalid()) {
if (connectionSocket.err() != EAGAIN && connectionSocket.err() != EINTR)
ERROR("accept connection failed on listen fd(%d)", listenFD);
break;
}
DEBUG("accept connection fd(%d) succeed on listen fd(%d)", connectionSocket.fd(), listenFD);
Ref<TCPChannel> connection = newInstance<TCPChannel>(eventloop_, std::move(connectionSocket));
connection->Register(connection);
// connected !
OnConnect();
}
}
void TCPServer::OnConnect() {
}
// end happytrain
}<commit_msg>Fix: apppend autual read size to buffer<commit_after>#include "tcpserver.h"
#include "util/net.h"
using namespace std;
using namespace happyntrain::network;
using namespace happyntrain::fd;
namespace happyntrain {
class TCPChannel;
TCPChannel::TCPChannel(EventLoop* eventloop, ConnectionSocketFD&& connectionSocket)
: state_(State::INVALID),
channel_(nullptr),
eventloop_(eventloop),
address_(0),
connectionSocket_(std::forward<ConnectionSocketFD>(connectionSocket)),
inBuffer_(),
predictInBufferSize_(1 << 7),
outBuffer_(),
dataListener_(nullptr)
{}
TCPChannel::~TCPChannel() {}
void TCPChannel::Send(std::string msg) {}
void TCPChannel::Close() {}
// Register channel to eventloop
// including selector, events, and event-callback
void TCPChannel::Register() {
channel_ = eventloop_->RegisterChannel(connectionSocket_);
// TODO: should register kWriteEventFlag ?
channel_->SetReadEnable();
state_ = State::CONNECTED;
auto self = shared_from_this();
channel_->OnRead([self] { self->OnReadable(); });
}
void TCPChannel::OnReadable() {
if (state_ != State::CONNECTED) {
WARN("connection fd(%d) not in connected state", channel_->fd());
// TODO: handle exception
return;
}
const size_t maxBufferSize = 1 << 15;
while (state_ == State::CONNECTED) {
Ptr<char[]> buffer(new char[predictInBufferSize_]);
ssize_t actualReadSize = connectionSocket_.read(buffer.get(), predictInBufferSize_);
DEBUG("Channel id(%lu) fd(%d) read(%zd/%zu)",
channel_->id(), channel_->fd(), actualReadSize, predictInBufferSize_);
if (actualReadSize == -1) {
int err = connectionSocket_.err();
if (err == EAGAIN || err == EWOULDBLOCK) {
FinishNonBlockingRead();
break;
} else if (err == EINTR) // interrupted
continue;
else {
break;
}
} else if (actualReadSize == 0) {
break;
} else {
inBuffer_.append(buffer.get(), actualReadSize);
if (actualReadSize == predictInBufferSize_ && predictInBufferSize_ < maxBufferSize) {
predictInBufferSize_ <<= 1;
}
}
}
}
void TCPChannel::FinishNonBlockingRead() {
DEBUG("Buffer(%s)", inBuffer_.str().c_str());
if (dataListener_) {
dataListener_(shared_from_this(), inBuffer_);
}
else {
inBuffer_.clear();
}
}
// -------------------
class TCPServer;
//--------------------
TCPServer::TCPServer()
: listenChannel_(nullptr),
eventloop_(nullptr),
address_("127.0.0.1", 12346) {}
TCPServer::TCPServer(EventLoop* eventloop)
: listenChannel_(nullptr),
eventloop_(eventloop),
address_("127.0.0.1", 12346) {}
void TCPServer::Listen(int port) {
address_ = IP4Address(port);
Listen();
}
void TCPServer::Listen() {
ServerSocketFD listenFD;
Bind(listenFD);
EXIT_IF(listenFD.listen(128) == false, "fd(%d) listen to port(%d) failed",
listenFD.fd(), address_.port);
INFO("Server Socket FD(%d) is now listening on port(%d)", listenFD.fd(), address_.port);
listenChannel_ = eventloop_->RegisterChannel(listenFD);
listenChannel_->SetReadEnable().OnRead([this] { this->OnAcceptable(); });
}
void TCPServer::Bind(ServerSocketFD& listenFD) {
// Fail the program if these fail
EXIT_IF(listenFD.invalid(), "Create Server Socket fd failed");
EXIT_IF(listenFD.setNonBlock() == false, "Server Socket fd(%d) set NONBLOCK fail",
listenFD.fd());
// Still go on even if these fail
EXPECT(listenFD.setReusePort(), "Server Socket fd(%d) set REUSEPORT fail", listenFD.fd());
EXPECT(listenFD.setCloseOnExec(), "Server Socket fd(%d) set CLOSEONEXEC fail",
listenFD.fd());
EXIT_IF(listenFD.bind(address_.host, address_.port) == false,
"Server Socket fd(%d) bind port(%d) failed", listenFD.fd(), address_.port);
}
void TCPServer::OnAcceptable() {
const int listenFD = listenChannel_->fd();
while (true) {
ConnectionSocketFD connectionSocket(listenFD);
if (connectionSocket.invalid()) {
if (connectionSocket.err() != EAGAIN && connectionSocket.err() != EINTR)
ERROR("Accept connection failed on Server Socket fd(%d)", listenFD);
break;
}
DEBUG("Accept connection fd(%d) succeed on Server Socket fd(%d)", connectionSocket.fd(), listenFD);
Ref<TCPChannel> connection = newInstance<TCPChannel>(eventloop_, std::move(connectionSocket));
connection->Register();
// connected !
OnConnect();
}
}
void TCPServer::OnConnect() {
}
// end happytrain
}<|endoftext|> |
<commit_before>#include <boost/test/unit_test.hpp>
#include "client/Client.hpp"
#include "client/SocketFactory.hpp"
#include "server/CoreServer.hpp"
#include "net/Cert.hpp"
#include "net/Net.hpp"
#include "net/TcpSocket.hpp"
#include "Response.hpp"
#include "../TestThread.hpp"
#include <thread>
using namespace http;
BOOST_AUTO_TEST_SUITE(TestCoreServer)
static const uint16_t BASE_PORT = 5100;
class Server : public http::CoreServer
{
protected:
virtual http::Response handle_request(http::Request &)override
{
http::Response resp;
resp.status_code(200);
resp.headers.add("Content-Type", "text/plain");
resp.body = "OK";
return resp;
}
virtual http::Response parser_error_page(const http::ParserError &)override
{
throw std::runtime_error("Unexpected parser_error_page");
}
};
void success_server_thread(Server *server)
{
server->run();
}
BOOST_AUTO_TEST_CASE(success)
{
TestThread server_thread;
Server server;
server.add_tcp_listener("127.0.0.1", BASE_PORT + 0);
server.add_tls_listener("127.0.0.1", BASE_PORT + 1, load_pfx_cert("localhost.pfx", "password"));
server.add_tls_listener("127.0.0.1", BASE_PORT + 2, load_pfx_cert("wrong-host.pfx", "password"));
server_thread = TestThread(std::bind(&Server::run, &server));
http::DefaultSocketFactory socket_factory;
{
// http://
http::Request req;
req.method = GET;
req.headers.add("Host", "localhost");
req.raw_url = "/index.html";
auto resp = http::Client("localhost", BASE_PORT + 0, false, &socket_factory).make_request(req);
BOOST_CHECK_EQUAL(200, resp.status.code);
BOOST_CHECK_EQUAL("OK", resp.body);
}
{
// https:// - TLS
http::Request req;
req.method = GET;
req.headers.add("Host", "localhost");
req.raw_url = "/index.html";
auto resp = http::Client("localhost", BASE_PORT + 1, true, &socket_factory).make_request(req);
BOOST_CHECK_EQUAL(200, resp.status.code);
BOOST_CHECK_EQUAL("OK", resp.body);
}
{
// Expected to fail since cant validate the certificate
http::Request req;
req.method = GET;
req.headers.add("Host", "localhost");
req.raw_url = "/index.html";
BOOST_CHECK_THROW(
http::Client("localhost", BASE_PORT + 2, true, &socket_factory).make_request(req),
CertificateVerificationError);
}
server.exit();
server_thread.join();
}
BOOST_AUTO_TEST_CASE(keep_alive)
{
TestThread server_thread;
Server server;
server.add_tcp_listener("127.0.0.1", BASE_PORT + 3);
server_thread = TestThread(std::bind(&Server::run, &server));
{
ClientConnection conn(std::make_unique<TcpSocket>("localhost", BASE_PORT + 3));
Request req;
req.method = GET;
req.headers.add("Host", "localhost");
req.headers.add("Connection", "close");
req.raw_url = "/index.html";
auto resp = conn.make_request(req);
BOOST_CHECK_EQUAL("close", resp.headers.get("Connection"));
BOOST_CHECK_THROW(conn.make_request(req), std::runtime_error);
}
{
ClientConnection conn(std::make_unique<TcpSocket>("localhost", BASE_PORT + 3));
Request req;
req.method = GET;
req.headers.add("Host", "localhost");
req.headers.add("Connection", "keep-alive");
req.raw_url = "/index.html";
auto resp = conn.make_request(req);
BOOST_CHECK_EQUAL("keep-alive", resp.headers.get("Connection"));
BOOST_CHECK_NO_THROW(conn.make_request(req));
}
server.exit();
server_thread.join();
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Remove std::make_unique as is C++14<commit_after>#include <boost/test/unit_test.hpp>
#include "client/Client.hpp"
#include "client/SocketFactory.hpp"
#include "server/CoreServer.hpp"
#include "net/Cert.hpp"
#include "net/Net.hpp"
#include "net/TcpSocket.hpp"
#include "Response.hpp"
#include "../TestThread.hpp"
#include <thread>
using namespace http;
BOOST_AUTO_TEST_SUITE(TestCoreServer)
static const uint16_t BASE_PORT = 5100;
class Server : public http::CoreServer
{
protected:
virtual http::Response handle_request(http::Request &)override
{
http::Response resp;
resp.status_code(200);
resp.headers.add("Content-Type", "text/plain");
resp.body = "OK";
return resp;
}
virtual http::Response parser_error_page(const http::ParserError &)override
{
throw std::runtime_error("Unexpected parser_error_page");
}
};
void success_server_thread(Server *server)
{
server->run();
}
BOOST_AUTO_TEST_CASE(success)
{
TestThread server_thread;
Server server;
server.add_tcp_listener("127.0.0.1", BASE_PORT + 0);
server.add_tls_listener("127.0.0.1", BASE_PORT + 1, load_pfx_cert("localhost.pfx", "password"));
server.add_tls_listener("127.0.0.1", BASE_PORT + 2, load_pfx_cert("wrong-host.pfx", "password"));
server_thread = TestThread(std::bind(&Server::run, &server));
http::DefaultSocketFactory socket_factory;
{
// http://
http::Request req;
req.method = GET;
req.headers.add("Host", "localhost");
req.raw_url = "/index.html";
auto resp = http::Client("localhost", BASE_PORT + 0, false, &socket_factory).make_request(req);
BOOST_CHECK_EQUAL(200, resp.status.code);
BOOST_CHECK_EQUAL("OK", resp.body);
}
{
// https:// - TLS
http::Request req;
req.method = GET;
req.headers.add("Host", "localhost");
req.raw_url = "/index.html";
auto resp = http::Client("localhost", BASE_PORT + 1, true, &socket_factory).make_request(req);
BOOST_CHECK_EQUAL(200, resp.status.code);
BOOST_CHECK_EQUAL("OK", resp.body);
}
{
// Expected to fail since cant validate the certificate
http::Request req;
req.method = GET;
req.headers.add("Host", "localhost");
req.raw_url = "/index.html";
BOOST_CHECK_THROW(
http::Client("localhost", BASE_PORT + 2, true, &socket_factory).make_request(req),
CertificateVerificationError);
}
server.exit();
server_thread.join();
}
BOOST_AUTO_TEST_CASE(keep_alive)
{
TestThread server_thread;
Server server;
server.add_tcp_listener("127.0.0.1", BASE_PORT + 3);
server_thread = TestThread(std::bind(&Server::run, &server));
{
ClientConnection conn(std::unique_ptr<Socket>(new TcpSocket("localhost", BASE_PORT + 3)));
Request req;
req.method = GET;
req.headers.add("Host", "localhost");
req.headers.add("Connection", "close");
req.raw_url = "/index.html";
auto resp = conn.make_request(req);
BOOST_CHECK_EQUAL("close", resp.headers.get("Connection"));
BOOST_CHECK_THROW(conn.make_request(req), std::runtime_error);
}
{
ClientConnection conn(std::unique_ptr<Socket>(new TcpSocket("localhost", BASE_PORT + 3)));
Request req;
req.method = GET;
req.headers.add("Host", "localhost");
req.headers.add("Connection", "keep-alive");
req.raw_url = "/index.html";
auto resp = conn.make_request(req);
BOOST_CHECK_EQUAL("keep-alive", resp.headers.get("Connection"));
BOOST_CHECK_NO_THROW(conn.make_request(req));
}
server.exit();
server_thread.join();
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include "himan_unit.h"
#include "util.h"
#define BOOST_TEST_MODULE util
using namespace std;
using namespace himan;
const double kEpsilon = 1e-3;
BOOST_AUTO_TEST_CASE(UV_TO_GEOGRAPHICAL)
{
// Transform grid coordinates to lat and lon in stereographic projection
himan::point stereoUV(8.484046, 3.804569);
double lon = 72.79;
himan::point latlon = util::UVToGeographical(lon, stereoUV);
BOOST_CHECK_CLOSE(latlon.X(), 6.144442, kEpsilon);
BOOST_CHECK_CLOSE(latlon.Y(), -6.978511, kEpsilon);
stereoUV.X(-0.2453410);
stereoUV.Y(0.5808838);
lon = 23.39;
latlon = util::UVToGeographical(lon, stereoUV);
BOOST_CHECK_CLOSE(latlon.X(), 5.4238806e-03, kEpsilon);
BOOST_CHECK_CLOSE(latlon.Y(), 0.6305464, kEpsilon);
}
BOOST_AUTO_TEST_CASE(FILTER2D)
{
// Filter a plane with given filter kernel
// Declare matrices
himan::matrix<double> A(11,8,1,kFloatMissing);
himan::matrix<double> B(3,3,1,kFloatMissing);
himan::matrix<double> C;
himan::matrix<double> D(11,8,1,kFloatMissing);
// Fill matrix A that will be smoothend with checker-board pattern
for(size_t i=0; i < A.Size(); ++i)
{
if(i % 2 == 0)
{
A.Set(i, 0);
}
else
{
A.Set(i, 36);
}
}
// Fill matrix D with solution of the smoothened matrix Filter2D(A,B)
for(size_t i=0; i < D.SizeX(); ++i)
{
for(size_t j=0; j < D.SizeY(); ++j)
{
if(i == 0 || i == A.SizeX()-1 || j == 0 || j == A.SizeY()-1)
{
D.Set(i,j,0,18);
}
else if ((i % 2 != 0 && j % 2 != 0) || (i % 2 == 0 && j % 2 == 0))
{
D.Set(i,j,0,16);
}
else
{
D.Set(i,j,0,20);
}
}
}
// Fill matrix B (filter kernel) with constant values 1/9 so that sum(B) == 1
double filter_coeff(1.0/9.0);
B.Fill(filter_coeff);
// Compute smoothened matrix
C = himan::util::Filter2D(A,B);
// Compare results
for(size_t i=0; i < C.Size(); ++i)
{
BOOST_CHECK_CLOSE(C.At(i),D.At(i),kEpsilon);
}
// computed filtered matrix
std::cout << "Matrix C computed with Filter2D:" << std::endl;
for (size_t i=0; i < C.SizeX();++i){
for (size_t j=0; j < C.SizeY();++j){
std::cout << C.At(i,j,0) << " ";
}
std::cout << std::endl;
}
std::cout << std::endl << "Matrix D as reference case for Filter2D computation:" << std::endl;
for (size_t i=0; i < D.SizeX();++i){
for (size_t j=0; j < D.SizeY();++j){
std::cout << D.At(i,j,0) << " ";
}
std::cout << std::endl;
}
}
BOOST_AUTO_TEST_CASE(CENTRAL_DIFFERENCE)
{
// Filter a plane with given filter kernel
// Declare matrices
himan::matrix<double> A(5,5,1,kFloatMissing);
himan::matrix<double> B;
himan::matrix<double> C;
// Matrices containing the correct solution
himan::matrix<double> D(5,5,1,kFloatMissing);
himan::matrix<double> E(5,5,1,kFloatMissing);
// Fill matrix A and solution matrices D and E
for(size_t i=0; i < A.Size(); ++i)
{
A.Set(i, double(i));
D.Set(i,1.0/double(1+i/5));
E.Set(i,5.0);
}
std::pair<himan::matrix<double>,himan::matrix<double>> grad_A;
// Declare vectors for grid spacing
std::vector<double> dx {1.0,2.0,3.0,4.0,5.0};
std::vector<double> dy(5,1.0);
grad_A = himan::util::CentralDifference(A,dx,dy);
B = std::get<0>(grad_A);
C = std::get<1>(grad_A);
assert(B==D && C==E);
}
BOOST_AUTO_TEST_CASE(MAKESQLINTERVAL)
{
forecast_time f1("2015-01-09 00:00:00", "2015-01-09 12:00:00");
BOOST_REQUIRE(util::MakeSQLInterval(f1) == "12:00:00");
f1.StepResolution(kMinuteResolution);
BOOST_REQUIRE(util::MakeSQLInterval(f1) == "12:00:00");
forecast_time f2("2015-01-09 00:00:00", "2015-01-09 00:15:00");
BOOST_REQUIRE(util::MakeSQLInterval(f2) == "00:00:00");
f2.StepResolution(kMinuteResolution);
BOOST_REQUIRE(util::MakeSQLInterval(f2) == "00:15:00");
forecast_time f3("2015-01-09 00:00:00", "2015-01-19 00:16:00");
BOOST_REQUIRE(util::MakeSQLInterval(f3) == "240:00:00");
forecast_time f4("2015-01-09 00:00:00", "2015-10-19 00:00:00");
BOOST_REQUIRE(util::MakeSQLInterval(f4) == "6792:00:00");
forecast_time f5("2015-01-09 00:00:00", "2015-01-09 00:00:00");
BOOST_REQUIRE(util::MakeSQLInterval(f5) == "00:00:00");
}
BOOST_AUTO_TEST_CASE(EXPAND)
{
setenv("BOOST_TEST", "xyz", 1);
string test = "$BOOST_TEST/asdf";
string expanded = util::Expand(test);
BOOST_REQUIRE(expanded == "xyz/asdf");
setenv("BOOST_TEST_2", "123", 1);
test = "$BOOST_TEST/asdf/$BOOST_TEST_2";
expanded = util::Expand(test);
BOOST_REQUIRE(expanded == "xyz/asdf/123");
}
<commit_msg>use BOOST_CHECK<commit_after>#include "himan_unit.h"
#include "util.h"
#define BOOST_TEST_MODULE util
using namespace std;
using namespace himan;
const double kEpsilon = 1e-3;
BOOST_AUTO_TEST_CASE(UV_TO_GEOGRAPHICAL)
{
// Transform grid coordinates to lat and lon in stereographic projection
himan::point stereoUV(8.484046, 3.804569);
double lon = 72.79;
himan::point latlon = util::UVToGeographical(lon, stereoUV);
BOOST_CHECK_CLOSE(latlon.X(), 6.144442, kEpsilon);
BOOST_CHECK_CLOSE(latlon.Y(), -6.978511, kEpsilon);
stereoUV.X(-0.2453410);
stereoUV.Y(0.5808838);
lon = 23.39;
latlon = util::UVToGeographical(lon, stereoUV);
BOOST_CHECK_CLOSE(latlon.X(), 5.4238806e-03, kEpsilon);
BOOST_CHECK_CLOSE(latlon.Y(), 0.6305464, kEpsilon);
}
BOOST_AUTO_TEST_CASE(FILTER2D)
{
// Filter a plane with given filter kernel
// Declare matrices
himan::matrix<double> A(11,8,1,kFloatMissing);
himan::matrix<double> B(3,3,1,kFloatMissing);
himan::matrix<double> C;
himan::matrix<double> D(11,8,1,kFloatMissing);
// Fill matrix A that will be smoothend with checker-board pattern
for(size_t i=0; i < A.Size(); ++i)
{
if(i % 2 == 0)
{
A.Set(i, 0);
}
else
{
A.Set(i, 36);
}
}
// Fill matrix D with solution of the smoothened matrix Filter2D(A,B)
for(size_t i=0; i < D.SizeX(); ++i)
{
for(size_t j=0; j < D.SizeY(); ++j)
{
if(i == 0 || i == A.SizeX()-1 || j == 0 || j == A.SizeY()-1)
{
D.Set(i,j,0,18);
}
else if ((i % 2 != 0 && j % 2 != 0) || (i % 2 == 0 && j % 2 == 0))
{
D.Set(i,j,0,16);
}
else
{
D.Set(i,j,0,20);
}
}
}
// Fill matrix B (filter kernel) with constant values 1/9 so that sum(B) == 1
double filter_coeff(1.0/9.0);
B.Fill(filter_coeff);
// Compute smoothened matrix
C = himan::util::Filter2D(A,B);
// Compare results
for(size_t i=0; i < C.Size(); ++i)
{
BOOST_CHECK_CLOSE(C.At(i),D.At(i),kEpsilon);
}
// computed filtered matrix
std::cout << "Matrix C computed with Filter2D:" << std::endl;
for (size_t i=0; i < C.SizeX();++i){
for (size_t j=0; j < C.SizeY();++j){
std::cout << C.At(i,j,0) << " ";
}
std::cout << std::endl;
}
std::cout << std::endl << "Matrix D as reference case for Filter2D computation:" << std::endl;
for (size_t i=0; i < D.SizeX();++i){
for (size_t j=0; j < D.SizeY();++j){
std::cout << D.At(i,j,0) << " ";
}
std::cout << std::endl;
}
}
BOOST_AUTO_TEST_CASE(CENTRAL_DIFFERENCE)
{
// Filter a plane with given filter kernel
// Declare matrices
himan::matrix<double> A(5,5,1,kFloatMissing);
himan::matrix<double> B;
himan::matrix<double> C;
// Matrices containing the correct solution
himan::matrix<double> D(5,5,1,kFloatMissing);
himan::matrix<double> E(5,5,1,kFloatMissing);
// Fill matrix A and solution matrices D and E
for(size_t i=0; i < A.Size(); ++i)
{
A.Set(i, double(i));
D.Set(i,1.0/double(1+i/5));
E.Set(i,5.0);
}
std::pair<himan::matrix<double>,himan::matrix<double>> grad_A;
// Declare vectors for grid spacing
std::vector<double> dx {1.0,2.0,3.0,4.0,5.0};
std::vector<double> dy(5,1.0);
grad_A = himan::util::CentralDifference(A,dx,dy);
B = std::get<0>(grad_A);
C = std::get<1>(grad_A);
BOOST_CHECK(B==D && C==E);
}
BOOST_AUTO_TEST_CASE(MAKESQLINTERVAL)
{
forecast_time f1("2015-01-09 00:00:00", "2015-01-09 12:00:00");
BOOST_REQUIRE(util::MakeSQLInterval(f1) == "12:00:00");
f1.StepResolution(kMinuteResolution);
BOOST_REQUIRE(util::MakeSQLInterval(f1) == "12:00:00");
forecast_time f2("2015-01-09 00:00:00", "2015-01-09 00:15:00");
BOOST_REQUIRE(util::MakeSQLInterval(f2) == "00:00:00");
f2.StepResolution(kMinuteResolution);
BOOST_REQUIRE(util::MakeSQLInterval(f2) == "00:15:00");
forecast_time f3("2015-01-09 00:00:00", "2015-01-19 00:16:00");
BOOST_REQUIRE(util::MakeSQLInterval(f3) == "240:00:00");
forecast_time f4("2015-01-09 00:00:00", "2015-10-19 00:00:00");
BOOST_REQUIRE(util::MakeSQLInterval(f4) == "6792:00:00");
forecast_time f5("2015-01-09 00:00:00", "2015-01-09 00:00:00");
BOOST_REQUIRE(util::MakeSQLInterval(f5) == "00:00:00");
}
BOOST_AUTO_TEST_CASE(EXPAND)
{
setenv("BOOST_TEST", "xyz", 1);
string test = "$BOOST_TEST/asdf";
string expanded = util::Expand(test);
BOOST_REQUIRE(expanded == "xyz/asdf");
setenv("BOOST_TEST_2", "123", 1);
test = "$BOOST_TEST/asdf/$BOOST_TEST_2";
expanded = util::Expand(test);
BOOST_REQUIRE(expanded == "xyz/asdf/123");
}
<|endoftext|> |
<commit_before>// Copyright 2014 Toggl Desktop developers.
// NB! Setters should not directly calculate
// anything besides setting the field asked.
// This is because same setters are used when
// loading from database, JSON etc. If time entry
// needs to be recalculated after some user
// action, the recalculation should be started
// from context, using specific functions, not
// setters.
#include "../src/time_entry.h"
#include <sstream>
#include <algorithm>
#include <json/json.h> // NOLINT
#include "./const.h"
#include "./formatter.h"
#include "./https_client.h"
#include "Poco/DateTime.h"
#include "Poco/LocalDateTime.h"
#include "Poco/Logger.h"
#include "Poco/NumberParser.h"
#include "Poco/Timestamp.h"
namespace toggl {
bool TimeEntry::ResolveError(const error err) {
if (durationTooLarge(err) && Stop() && Start()) {
Poco::UInt64 seconds =
(std::min)(Stop() - Start(),
Poco::UInt64(kMaxTimeEntryDurationSeconds));
SetDurationInSeconds(seconds);
return true;
}
if (stopTimeMustBeAfterStartTime(err) && Stop() && Start()) {
SetStop(Start() + DurationInSeconds());
return true;
}
if (userCannotAccessWorkspace(err)) {
SetWID(0);
SetPID(0);
SetTID(0);
return true;
}
if (userCannotAccessTheSelectedProject(err)) {
SetPID(0);
SetTID(0);
return true;
}
if (userCannotAccessSelectedTask(err)) {
SetTID(0);
return true;
}
if (billableIsAPremiumFeature(err)) {
SetBillable(false);
return true;
}
if (isMissingCreatedWith(err)) {
SetCreatedWith(HTTPSClientConfig::UserAgent());
return true;
}
return false;
}
bool TimeEntry::isMissingCreatedWith(const error err) const {
return std::string::npos != std::string(err).find(
"created_with needs to be provided an a valid string");
}
bool TimeEntry::userCannotAccessTheSelectedProject(
const error err) const {
return (std::string::npos != std::string(err).find(
"User cannot access the selected project"));
}
bool TimeEntry::userCannotAccessSelectedTask(
const error err) const {
return (std::string::npos != std::string(err).find(
"User cannot access selected task"));
}
bool TimeEntry::durationTooLarge(const error err) const {
return (std::string::npos != std::string(err).find(
"Max allowed duration per 1 time entry is 1000 hours"));
}
bool TimeEntry::stopTimeMustBeAfterStartTime(const error err) const {
return (std::string::npos != std::string(err).find(
"Stop time must be after start time"));
}
bool TimeEntry::billableIsAPremiumFeature(const error err) const {
return (std::string::npos != std::string(err).find(
"Billable is a premium feature"));
}
void TimeEntry::DiscardAt(const Poco::UInt64 at) {
poco_assert(at);
Poco::Int64 duration = at + DurationInSeconds();
if (duration < 0) {
duration = -1 * duration;
}
SetDurationInSeconds(duration);
poco_assert(DurationInSeconds() >= 0);
SetStop(at);
SetUIModified();
}
void TimeEntry::StopTracking() {
DiscardAt(time(0));
}
std::string TimeEntry::String() const {
std::stringstream ss;
ss << "ID=" << ID()
<< " local_id=" << LocalID()
<< " description=" << description_
<< " wid=" << wid_
<< " guid=" << GUID()
<< " pid=" << pid_
<< " tid=" << tid_
<< " start=" << start_
<< " stop=" << stop_
<< " duration=" << duration_in_seconds_
<< " billable=" << billable_
<< " duronly=" << duronly_
<< " tags=" << Tags()
<< " created_with=" << CreatedWith()
<< " ui_modified_at=" << UIModifiedAt()
<< " deleted_at=" << DeletedAt()
<< " updated_at=" << UpdatedAt();
return ss.str();
}
void TimeEntry::SetDurOnly(const bool value) {
if (duronly_ != value) {
duronly_ = value;
SetDirty();
}
}
void TimeEntry::SetStart(const Poco::UInt64 value) {
if (start_ != value) {
start_ = value;
SetDirty();
}
}
void TimeEntry::SetStop(const Poco::UInt64 value) {
if (stop_ != value) {
stop_ = value;
SetDirty();
}
}
void TimeEntry::SetDescription(const std::string value) {
if (description_ != value) {
description_ = value;
SetDirty();
}
}
void TimeEntry::SetStopString(const std::string value) {
SetStop(Formatter::Parse8601(value));
}
void TimeEntry::SetCreatedWith(const std::string value) {
if (created_with_ != value) {
created_with_ = value;
SetDirty();
}
}
void TimeEntry::SetBillable(const bool value) {
if (billable_ != value) {
billable_ = value;
SetDirty();
}
}
void TimeEntry::SetWID(const Poco::UInt64 value) {
if (wid_ != value) {
wid_ = value;
SetDirty();
}
}
void TimeEntry::SetStopUserInput(const std::string value) {
SetStopString(value);
if (Stop() < Start()) {
// Stop time cannot be before start time,
// it'll get an error from backend.
Poco::Timestamp ts =
Poco::Timestamp::fromEpochTime(Stop()) + 1*Poco::Timespan::DAYS;
SetStop(ts.epochTime());
}
poco_assert(Stop() >= Start());
if (!IsTracking()) {
SetDurationInSeconds(Stop() - Start());
}
if (Dirty()) {
SetUIModified();
}
}
void TimeEntry::SetTID(const Poco::UInt64 value) {
if (tid_ != value) {
tid_ = value;
SetDirty();
}
}
static const char kTagSeparator = '\t';
void TimeEntry::SetTags(const std::string tags) {
if (Tags() != tags) {
TagNames.clear();
if (!tags.empty()) {
std::stringstream ss(tags);
while (ss.good()) {
std::string tag;
getline(ss, tag, kTagSeparator);
TagNames.push_back(tag);
}
}
SetDirty();
}
}
void TimeEntry::SetPID(const Poco::UInt64 value) {
if (pid_ != value) {
pid_ = value;
SetDirty();
}
}
void TimeEntry::SetDurationInSeconds(const Poco::Int64 value) {
if (duration_in_seconds_ != value) {
duration_in_seconds_ = value;
SetDirty();
}
}
void TimeEntry::SetStartUserInput(const std::string value) {
Poco::Int64 start = Formatter::Parse8601(value);
if (IsTracking()) {
SetDurationInSeconds(-start);
} else {
SetStop(start + DurationInSeconds());
}
SetStart(start);
if (Dirty()) {
SetUIModified();
}
}
void TimeEntry::SetStartString(const std::string value) {
SetStart(Formatter::Parse8601(value));
}
void TimeEntry::SetDurationUserInput(const std::string value) {
int seconds = Formatter::ParseDurationString(value);
if (IsTracking()) {
time_t now = time(0);
time_t start = now - seconds;
SetStart(start);
SetDurationInSeconds(-start);
} else {
SetDurationInSeconds(seconds);
}
SetStop(Start() + seconds);
if (Dirty()) {
SetUIModified();
}
}
void TimeEntry::SetProjectGUID(const std::string value) {
if (project_guid_ != value) {
project_guid_ = value;
SetDirty();
}
}
const std::string TimeEntry::Tags() const {
std::stringstream ss;
for (std::vector<std::string>::const_iterator it =
TagNames.begin();
it != TagNames.end();
it++) {
if (it != TagNames.begin()) {
ss << kTagSeparator;
}
ss << *it;
}
return ss.str();
}
std::string TimeEntry::DateHeaderString() const {
return Formatter::FormatDateHeader(start_);
}
std::string TimeEntry::StopString() const {
return Formatter::Format8601(stop_);
}
std::string TimeEntry::StartString() const {
return Formatter::Format8601(start_);
}
bool TimeEntry::IsToday() const {
Poco::Timestamp ts = Poco::Timestamp::fromEpochTime(Start());
Poco::LocalDateTime datetime(ts);
Poco::LocalDateTime today;
return today.year() == datetime.year() &&
today.month() == datetime.month() &&
today.day() == datetime.day();
}
void TimeEntry::LoadFromJSON(Json::Value data) {
Json::Value modified = data["ui_modified_at"];
Poco::UInt64 ui_modified_at(0);
if (modified.isString()) {
ui_modified_at = Poco::NumberParser::parseUnsigned64(
modified.asString());
} else {
ui_modified_at = modified.asUInt64();
}
if (UIModifiedAt() > ui_modified_at) {
std::stringstream ss;
ss << "Will not overwrite time entry "
<< String()
<< " with server data because we have a newer ui_modified_at";
logger().debug(ss.str());
return;
}
if (data.isMember("guid")) {
SetGUID(data["guid"].asString());
}
if (data.isMember("tags")) {
loadTagsFromJSON(data["tags"]);
}
if (data.isMember("created_with")) {
SetCreatedWith(data["created_with"].asString());
}
if (data.isMember("id")) {
SetID(data["id"].asUInt64());
}
SetDescription(data["description"].asString());
if (data.isMember("wid")) {
SetWID(data["wid"].asUInt64());
} else {
SetWID(0);
}
if (data.isMember("pid")) {
SetPID(data["pid"].asUInt64());
} else {
SetPID(0);
}
if (data.isMember("tid")) {
SetTID(data["tid"].asUInt64());
} else {
SetTID(0);
}
SetStartString(data["start"].asString());
SetStopString(data["stop"].asString());
SetDurationInSeconds(data["duration"].asInt64());
SetBillable(data["billable"].asBool());
SetDurOnly(data["duronly"].asBool());
SetUpdatedAtString(data["at"].asString());
SetUIModifiedAt(0);
}
Json::Value TimeEntry::SaveToJSON() const {
Json::Value n;
if (ID()) {
n["id"] = Json::UInt64(ID());
}
n["description"] = Formatter::EscapeJSONString(Description());
// Workspace ID can't be 0 on server side. So don't
// send 0 if we have no default workspace ID, because
// NULL is not 0
if (WID()) {
n["wid"] = Json::UInt64(WID());
}
n["guid"] = GUID();
if (!PID() && !ProjectGUID().empty()) {
n["pid"] = ProjectGUID();
} else {
n["pid"] = Json::UInt64(PID());
}
n["tid"] = Json::UInt64(TID());
n["start"] = StartString();
if (Stop()) {
n["stop"] = StopString();
}
n["duration"] = Json::Int64(DurationInSeconds());
n["billable"] = Billable();
n["duronly"] = DurOnly();
n["ui_modified_at"] = Json::UInt64(UIModifiedAt());
n["created_with"] = Formatter::EscapeJSONString(CreatedWith());
Json::Value tag_nodes;
for (std::vector<std::string>::const_iterator it = TagNames.begin();
it != TagNames.end();
it++) {
std::string tag_name = Formatter::EscapeJSONString(*it);
tag_nodes.append(Json::Value(tag_name));
}
n["tags"] = tag_nodes;
return n;
}
Poco::UInt64 TimeEntry::AbsDuration(const Poco::Int64 value) {
Poco::Int64 duration = value;
// Duration is negative when time is tracking
if (duration < 0) {
duration += time(0);
}
// If after calculation time is still negative,
// either computer clock is wrong or user
// has set start time to the future. Render positive
// duration only:
if (duration < 0) {
duration *= -1;
}
return static_cast<Poco::UInt64>(duration);
}
void TimeEntry::loadTagsFromJSON(Json::Value list) {
TagNames.clear();
for (unsigned int i = 0; i < list.size(); i++) {
std::string tag = list[i].asString();
if (!tag.empty()) {
TagNames.push_back(tag);
}
}
}
} // namespace toggl
<commit_msg> Fixed typo in error message (lib)<commit_after>// Copyright 2014 Toggl Desktop developers.
// NB! Setters should not directly calculate
// anything besides setting the field asked.
// This is because same setters are used when
// loading from database, JSON etc. If time entry
// needs to be recalculated after some user
// action, the recalculation should be started
// from context, using specific functions, not
// setters.
#include "../src/time_entry.h"
#include <sstream>
#include <algorithm>
#include <json/json.h> // NOLINT
#include "./const.h"
#include "./formatter.h"
#include "./https_client.h"
#include "Poco/DateTime.h"
#include "Poco/LocalDateTime.h"
#include "Poco/Logger.h"
#include "Poco/NumberParser.h"
#include "Poco/Timestamp.h"
namespace toggl {
bool TimeEntry::ResolveError(const error err) {
if (durationTooLarge(err) && Stop() && Start()) {
Poco::UInt64 seconds =
(std::min)(Stop() - Start(),
Poco::UInt64(kMaxTimeEntryDurationSeconds));
SetDurationInSeconds(seconds);
return true;
}
if (stopTimeMustBeAfterStartTime(err) && Stop() && Start()) {
SetStop(Start() + DurationInSeconds());
return true;
}
if (userCannotAccessWorkspace(err)) {
SetWID(0);
SetPID(0);
SetTID(0);
return true;
}
if (userCannotAccessTheSelectedProject(err)) {
SetPID(0);
SetTID(0);
return true;
}
if (userCannotAccessSelectedTask(err)) {
SetTID(0);
return true;
}
if (billableIsAPremiumFeature(err)) {
SetBillable(false);
return true;
}
if (isMissingCreatedWith(err)) {
SetCreatedWith(HTTPSClientConfig::UserAgent());
return true;
}
return false;
}
bool TimeEntry::isMissingCreatedWith(const error err) const {
return std::string::npos != std::string(err).find(
"created_with needs to be provided a valid string");
}
bool TimeEntry::userCannotAccessTheSelectedProject(
const error err) const {
return (std::string::npos != std::string(err).find(
"User cannot access the selected project"));
}
bool TimeEntry::userCannotAccessSelectedTask(
const error err) const {
return (std::string::npos != std::string(err).find(
"User cannot access selected task"));
}
bool TimeEntry::durationTooLarge(const error err) const {
return (std::string::npos != std::string(err).find(
"Max allowed duration per 1 time entry is 1000 hours"));
}
bool TimeEntry::stopTimeMustBeAfterStartTime(const error err) const {
return (std::string::npos != std::string(err).find(
"Stop time must be after start time"));
}
bool TimeEntry::billableIsAPremiumFeature(const error err) const {
return (std::string::npos != std::string(err).find(
"Billable is a premium feature"));
}
void TimeEntry::DiscardAt(const Poco::UInt64 at) {
poco_assert(at);
Poco::Int64 duration = at + DurationInSeconds();
if (duration < 0) {
duration = -1 * duration;
}
SetDurationInSeconds(duration);
poco_assert(DurationInSeconds() >= 0);
SetStop(at);
SetUIModified();
}
void TimeEntry::StopTracking() {
DiscardAt(time(0));
}
std::string TimeEntry::String() const {
std::stringstream ss;
ss << "ID=" << ID()
<< " local_id=" << LocalID()
<< " description=" << description_
<< " wid=" << wid_
<< " guid=" << GUID()
<< " pid=" << pid_
<< " tid=" << tid_
<< " start=" << start_
<< " stop=" << stop_
<< " duration=" << duration_in_seconds_
<< " billable=" << billable_
<< " duronly=" << duronly_
<< " tags=" << Tags()
<< " created_with=" << CreatedWith()
<< " ui_modified_at=" << UIModifiedAt()
<< " deleted_at=" << DeletedAt()
<< " updated_at=" << UpdatedAt();
return ss.str();
}
void TimeEntry::SetDurOnly(const bool value) {
if (duronly_ != value) {
duronly_ = value;
SetDirty();
}
}
void TimeEntry::SetStart(const Poco::UInt64 value) {
if (start_ != value) {
start_ = value;
SetDirty();
}
}
void TimeEntry::SetStop(const Poco::UInt64 value) {
if (stop_ != value) {
stop_ = value;
SetDirty();
}
}
void TimeEntry::SetDescription(const std::string value) {
if (description_ != value) {
description_ = value;
SetDirty();
}
}
void TimeEntry::SetStopString(const std::string value) {
SetStop(Formatter::Parse8601(value));
}
void TimeEntry::SetCreatedWith(const std::string value) {
if (created_with_ != value) {
created_with_ = value;
SetDirty();
}
}
void TimeEntry::SetBillable(const bool value) {
if (billable_ != value) {
billable_ = value;
SetDirty();
}
}
void TimeEntry::SetWID(const Poco::UInt64 value) {
if (wid_ != value) {
wid_ = value;
SetDirty();
}
}
void TimeEntry::SetStopUserInput(const std::string value) {
SetStopString(value);
if (Stop() < Start()) {
// Stop time cannot be before start time,
// it'll get an error from backend.
Poco::Timestamp ts =
Poco::Timestamp::fromEpochTime(Stop()) + 1*Poco::Timespan::DAYS;
SetStop(ts.epochTime());
}
poco_assert(Stop() >= Start());
if (!IsTracking()) {
SetDurationInSeconds(Stop() - Start());
}
if (Dirty()) {
SetUIModified();
}
}
void TimeEntry::SetTID(const Poco::UInt64 value) {
if (tid_ != value) {
tid_ = value;
SetDirty();
}
}
static const char kTagSeparator = '\t';
void TimeEntry::SetTags(const std::string tags) {
if (Tags() != tags) {
TagNames.clear();
if (!tags.empty()) {
std::stringstream ss(tags);
while (ss.good()) {
std::string tag;
getline(ss, tag, kTagSeparator);
TagNames.push_back(tag);
}
}
SetDirty();
}
}
void TimeEntry::SetPID(const Poco::UInt64 value) {
if (pid_ != value) {
pid_ = value;
SetDirty();
}
}
void TimeEntry::SetDurationInSeconds(const Poco::Int64 value) {
if (duration_in_seconds_ != value) {
duration_in_seconds_ = value;
SetDirty();
}
}
void TimeEntry::SetStartUserInput(const std::string value) {
Poco::Int64 start = Formatter::Parse8601(value);
if (IsTracking()) {
SetDurationInSeconds(-start);
} else {
SetStop(start + DurationInSeconds());
}
SetStart(start);
if (Dirty()) {
SetUIModified();
}
}
void TimeEntry::SetStartString(const std::string value) {
SetStart(Formatter::Parse8601(value));
}
void TimeEntry::SetDurationUserInput(const std::string value) {
int seconds = Formatter::ParseDurationString(value);
if (IsTracking()) {
time_t now = time(0);
time_t start = now - seconds;
SetStart(start);
SetDurationInSeconds(-start);
} else {
SetDurationInSeconds(seconds);
}
SetStop(Start() + seconds);
if (Dirty()) {
SetUIModified();
}
}
void TimeEntry::SetProjectGUID(const std::string value) {
if (project_guid_ != value) {
project_guid_ = value;
SetDirty();
}
}
const std::string TimeEntry::Tags() const {
std::stringstream ss;
for (std::vector<std::string>::const_iterator it =
TagNames.begin();
it != TagNames.end();
it++) {
if (it != TagNames.begin()) {
ss << kTagSeparator;
}
ss << *it;
}
return ss.str();
}
std::string TimeEntry::DateHeaderString() const {
return Formatter::FormatDateHeader(start_);
}
std::string TimeEntry::StopString() const {
return Formatter::Format8601(stop_);
}
std::string TimeEntry::StartString() const {
return Formatter::Format8601(start_);
}
bool TimeEntry::IsToday() const {
Poco::Timestamp ts = Poco::Timestamp::fromEpochTime(Start());
Poco::LocalDateTime datetime(ts);
Poco::LocalDateTime today;
return today.year() == datetime.year() &&
today.month() == datetime.month() &&
today.day() == datetime.day();
}
void TimeEntry::LoadFromJSON(Json::Value data) {
Json::Value modified = data["ui_modified_at"];
Poco::UInt64 ui_modified_at(0);
if (modified.isString()) {
ui_modified_at = Poco::NumberParser::parseUnsigned64(
modified.asString());
} else {
ui_modified_at = modified.asUInt64();
}
if (UIModifiedAt() > ui_modified_at) {
std::stringstream ss;
ss << "Will not overwrite time entry "
<< String()
<< " with server data because we have a newer ui_modified_at";
logger().debug(ss.str());
return;
}
if (data.isMember("guid")) {
SetGUID(data["guid"].asString());
}
if (data.isMember("tags")) {
loadTagsFromJSON(data["tags"]);
}
if (data.isMember("created_with")) {
SetCreatedWith(data["created_with"].asString());
}
if (data.isMember("id")) {
SetID(data["id"].asUInt64());
}
SetDescription(data["description"].asString());
if (data.isMember("wid")) {
SetWID(data["wid"].asUInt64());
} else {
SetWID(0);
}
if (data.isMember("pid")) {
SetPID(data["pid"].asUInt64());
} else {
SetPID(0);
}
if (data.isMember("tid")) {
SetTID(data["tid"].asUInt64());
} else {
SetTID(0);
}
SetStartString(data["start"].asString());
SetStopString(data["stop"].asString());
SetDurationInSeconds(data["duration"].asInt64());
SetBillable(data["billable"].asBool());
SetDurOnly(data["duronly"].asBool());
SetUpdatedAtString(data["at"].asString());
SetUIModifiedAt(0);
}
Json::Value TimeEntry::SaveToJSON() const {
Json::Value n;
if (ID()) {
n["id"] = Json::UInt64(ID());
}
n["description"] = Formatter::EscapeJSONString(Description());
// Workspace ID can't be 0 on server side. So don't
// send 0 if we have no default workspace ID, because
// NULL is not 0
if (WID()) {
n["wid"] = Json::UInt64(WID());
}
n["guid"] = GUID();
if (!PID() && !ProjectGUID().empty()) {
n["pid"] = ProjectGUID();
} else {
n["pid"] = Json::UInt64(PID());
}
n["tid"] = Json::UInt64(TID());
n["start"] = StartString();
if (Stop()) {
n["stop"] = StopString();
}
n["duration"] = Json::Int64(DurationInSeconds());
n["billable"] = Billable();
n["duronly"] = DurOnly();
n["ui_modified_at"] = Json::UInt64(UIModifiedAt());
n["created_with"] = Formatter::EscapeJSONString(CreatedWith());
Json::Value tag_nodes;
for (std::vector<std::string>::const_iterator it = TagNames.begin();
it != TagNames.end();
it++) {
std::string tag_name = Formatter::EscapeJSONString(*it);
tag_nodes.append(Json::Value(tag_name));
}
n["tags"] = tag_nodes;
return n;
}
Poco::UInt64 TimeEntry::AbsDuration(const Poco::Int64 value) {
Poco::Int64 duration = value;
// Duration is negative when time is tracking
if (duration < 0) {
duration += time(0);
}
// If after calculation time is still negative,
// either computer clock is wrong or user
// has set start time to the future. Render positive
// duration only:
if (duration < 0) {
duration *= -1;
}
return static_cast<Poco::UInt64>(duration);
}
void TimeEntry::loadTagsFromJSON(Json::Value list) {
TagNames.clear();
for (unsigned int i = 0; i < list.size(); i++) {
std::string tag = list[i].asString();
if (!tag.empty()) {
TagNames.push_back(tag);
}
}
}
} // namespace toggl
<|endoftext|> |
<commit_before>//----------------------------------------------------------------------------
/// \file timestamp.cpp
//----------------------------------------------------------------------------
/// \brief Implementation of timestamp class.
//----------------------------------------------------------------------------
// Copyright (c) 2011 Serge Aleynikov <[email protected]>
// Created: 2011-09-10
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the utxx open-source project.
Copyright (C) 2011 Serge Aleynikov <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***** END LICENSE BLOCK *****
*/
#include <utxx/convert.hpp>
#include <utxx/timestamp.hpp>
#include <utxx/compiler_hints.hpp>
#include <utxx/string.hpp>
#include <utxx/time.hpp>
#include <utxx/error.hpp>
#include <stdio.h>
namespace utxx {
boost::mutex timestamp::s_mutex;
thread_local long timestamp::s_next_local_midnight_nseconds = 0;
thread_local long timestamp::s_next_utc_midnight_nseconds = 0;
thread_local time_t timestamp::s_utc_nsec_offset = 0;
thread_local char timestamp::s_local_timestamp[16];
thread_local char timestamp::s_utc_timestamp[16];
thread_local char timestamp::s_local_timezone[8];
#ifdef DEBUG_TIMESTAMP
volatile long timestamp::s_hrcalls;
volatile long timestamp::s_syscalls;
#endif
namespace {
static const char* s_values[] = {
"none", "date", "date-time",
"date-time-msec", "date-time-usec", "date-time-nsec",
"time", "time-msec", "time-usec", "time-nsec"
};
}
stamp_type parse_stamp_type(const std::string& a_line) {
stamp_type t = find_index<stamp_type>(s_values, a_line, (stamp_type)-1, true);
if (int(t) == -1)
throw badarg_error("parse_stamp_tpe: invalid timestamp type: ", a_line);
return t;
}
const char* to_string(stamp_type a_type) {
assert(size_t(a_type) < length(s_values));
return s_values[a_type];
}
char* timestamp::write_date(char* a_buf, time_t a_utc_seconds, bool a_utc,
size_t eos_pos, char a_sep, bool a_use_cached_date)
{
long nsec = a_utc_seconds*1000000000L;
// If not same day - update cached string value
if (unlikely(nsec >= s_next_utc_midnight_nseconds))
update_midnight_nseconds(now_utc());
auto today_utc_midnight = s_next_utc_midnight_nseconds - 86400000000000L;
if (a_sep || !a_use_cached_date || nsec < today_utc_midnight)
return internal_write_date(a_buf, a_utc_seconds, a_utc, eos_pos, a_sep);
else {
strncpy(a_buf, a_utc ? s_utc_timestamp : s_local_timestamp, 9);
if (eos_pos) { a_buf[eos_pos] = '\0'; return a_buf + eos_pos; }
return a_buf + 9;
}
}
void timestamp::update_midnight_nseconds(time_val a_now)
{
auto s = a_now.sec();
struct tm tm;
localtime_r(&s, &tm);
s_utc_nsec_offset = tm.tm_gmtoff * 1000000000L;
auto now_midnight_nsecs = a_now.nanoseconds() -
a_now.nanoseconds() % (86400L * 1000000000L);
auto local_midnight_nsecs = now_midnight_nsecs - s_utc_nsec_offset;
s_next_utc_midnight_nseconds = now_midnight_nsecs + 86400L * 1000000000L;
s_next_local_midnight_nseconds = a_now.nanoseconds() >= local_midnight_nsecs
? (s_next_utc_midnight_nseconds - s_utc_nsec_offset)
: local_midnight_nsecs;
strncpy(s_local_timezone, tm.tm_zone, sizeof(s_local_timezone)-1);
s_local_timezone[sizeof(s_local_timezone)-1] = '\0';
// the mutex is not needed here at all - s_timestamp lives in TLS storage
internal_write_date(s_local_timestamp, s, false, 9, '\0');
internal_write_date(s_utc_timestamp, s, true, 9, '\0');
}
size_t timestamp::format_size(stamp_type a_tp)
{
switch (a_tp) {
case NO_TIMESTAMP: return 0;
case TIME: return 8;
case TIME_WITH_MSEC: return 12;
case TIME_WITH_USEC: return 15;
case TIME_WITH_NSEC: return 18;
case DATE: return 8;
case DATE_TIME: return 17;
case DATE_TIME_WITH_MSEC: return 21;
case DATE_TIME_WITH_USEC: return 24;
case DATE_TIME_WITH_NSEC: return 27;
default: break;
}
assert(false); // should never get here
return 0;
}
int timestamp::format(stamp_type a_tp, time_val tv, char* a_buf, size_t a_sz,
bool a_utc, bool a_day_chk, bool a_use_cached_date)
{
BOOST_ASSERT((a_tp < DATE_TIME && a_sz > 17) || a_sz > 27);
if (unlikely(a_tp == NO_TIMESTAMP)) {
a_buf[0] = '\0';
return 0;
}
auto pair = tv.split();
// If small time is given, it's a relative value.
bool rel = pair.first < 86400L;
auto now = a_day_chk || rel ? update().split() : pair;
if (rel)
pair.first += now.first;
auto sec = a_utc ? pair.first
: (pair.first + s_utc_nsec_offset / 1000000000L);
char* p;
switch (a_tp) {
case TIME:
case TIME_WITH_MSEC:
case TIME_WITH_USEC:
case TIME_WITH_NSEC: {
p = time_val::write_time(sec, pair.second, a_buf, a_tp);
return p - a_buf;
}
case DATE:
p = write_date(a_buf, sec, a_utc, 8, '\0', a_use_cached_date);
return 8;
case DATE_TIME:
case DATE_TIME_WITH_MSEC:
case DATE_TIME_WITH_USEC:
case DATE_TIME_WITH_NSEC: {
p = write_date(a_buf, sec, a_utc, 0, '\0', a_use_cached_date);
p = time_val::write_time(sec, pair.second, p, stamp_type(a_tp+4));
return p - a_buf;
}
default:
strcpy(a_buf, "UNDEFINED");
return -1;
}
}
time_val timestamp::from_string(const char* a_datetime, size_t n, bool a_utc) {
if (unlikely(n < 8 ||
(n > 8 && (n < 17 || a_datetime[8] != '-' ||
a_datetime[11] != ':' || a_datetime[14] != ':'))))
throw badarg_error("Invalid time format: ", std::string(a_datetime, n));
const char* p = a_datetime;
auto parse = [&p](int digits) {
int i = 0; const char* end = p + digits;
for (; p != end; ++p) i = (10*i) + (*p - '0');
return i;
};
unsigned hour = 0, min = 0, sec = 0;
long nsec = 0;
int year = parse(4);
unsigned mon = parse(2);
unsigned day = parse(2);
if (n > 8) {
p++;
hour = parse(2); p++;
min = parse(2); p++;
sec = parse(2);
const char* dot = p++;
if (*dot == '.' && n > 17)
{
const char* end = p + std::min<size_t>(6, n - (p - a_datetime));
while (*p >= '0' && *p <= '9' && p != end)
nsec = 10*nsec + (*p++ - '0');
int len = p - dot - 1;
switch (len)
{
case 3: nsec *= 1000000; break;
case 6: nsec *= 1000; break;
case 9: break;
default: throw badarg_error("Invalid microsecond format: ",
std::string(a_datetime, end - a_datetime));
}
}
}
return (a_utc
? time_val::universal_time(year, mon, day, hour, min, sec, 0)
: time_val::local_time(year, mon, day, hour, min, sec, 0)) + nsecs(nsec);
}
} // namespace utxx
<commit_msg>Fix size check<commit_after>//----------------------------------------------------------------------------
/// \file timestamp.cpp
//----------------------------------------------------------------------------
/// \brief Implementation of timestamp class.
//----------------------------------------------------------------------------
// Copyright (c) 2011 Serge Aleynikov <[email protected]>
// Created: 2011-09-10
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the utxx open-source project.
Copyright (C) 2011 Serge Aleynikov <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***** END LICENSE BLOCK *****
*/
#include <utxx/convert.hpp>
#include <utxx/timestamp.hpp>
#include <utxx/compiler_hints.hpp>
#include <utxx/string.hpp>
#include <utxx/time.hpp>
#include <utxx/error.hpp>
#include <stdio.h>
namespace utxx {
boost::mutex timestamp::s_mutex;
thread_local long timestamp::s_next_local_midnight_nseconds = 0;
thread_local long timestamp::s_next_utc_midnight_nseconds = 0;
thread_local time_t timestamp::s_utc_nsec_offset = 0;
thread_local char timestamp::s_local_timestamp[16];
thread_local char timestamp::s_utc_timestamp[16];
thread_local char timestamp::s_local_timezone[8];
#ifdef DEBUG_TIMESTAMP
volatile long timestamp::s_hrcalls;
volatile long timestamp::s_syscalls;
#endif
namespace {
static const char* s_values[] = {
"none", "date", "date-time",
"date-time-msec", "date-time-usec", "date-time-nsec",
"time", "time-msec", "time-usec", "time-nsec"
};
}
stamp_type parse_stamp_type(const std::string& a_line) {
stamp_type t = find_index<stamp_type>(s_values, a_line, (stamp_type)-1, true);
if (int(t) == -1)
throw badarg_error("parse_stamp_tpe: invalid timestamp type: ", a_line);
return t;
}
const char* to_string(stamp_type a_type) {
assert(size_t(a_type) < length(s_values));
return s_values[a_type];
}
char* timestamp::write_date(char* a_buf, time_t a_utc_seconds, bool a_utc,
size_t eos_pos, char a_sep, bool a_use_cached_date)
{
long nsec = a_utc_seconds*1000000000L;
// If not same day - update cached string value
if (unlikely(nsec >= s_next_utc_midnight_nseconds))
update_midnight_nseconds(now_utc());
auto today_utc_midnight = s_next_utc_midnight_nseconds - 86400000000000L;
if (a_sep || !a_use_cached_date || nsec < today_utc_midnight)
return internal_write_date(a_buf, a_utc_seconds, a_utc, eos_pos, a_sep);
else {
strncpy(a_buf, a_utc ? s_utc_timestamp : s_local_timestamp, 9);
if (eos_pos) { a_buf[eos_pos] = '\0'; return a_buf + eos_pos; }
return a_buf + 9;
}
}
void timestamp::update_midnight_nseconds(time_val a_now)
{
auto s = a_now.sec();
struct tm tm;
localtime_r(&s, &tm);
s_utc_nsec_offset = tm.tm_gmtoff * 1000000000L;
auto now_midnight_nsecs = a_now.nanoseconds() -
a_now.nanoseconds() % (86400L * 1000000000L);
auto local_midnight_nsecs = now_midnight_nsecs - s_utc_nsec_offset;
s_next_utc_midnight_nseconds = now_midnight_nsecs + 86400L * 1000000000L;
s_next_local_midnight_nseconds = a_now.nanoseconds() >= local_midnight_nsecs
? (s_next_utc_midnight_nseconds - s_utc_nsec_offset)
: local_midnight_nsecs;
strncpy(s_local_timezone, tm.tm_zone, sizeof(s_local_timezone)-1);
s_local_timezone[sizeof(s_local_timezone)-1] = '\0';
// the mutex is not needed here at all - s_timestamp lives in TLS storage
internal_write_date(s_local_timestamp, s, false, 9, '\0');
internal_write_date(s_utc_timestamp, s, true, 9, '\0');
}
size_t timestamp::format_size(stamp_type a_tp)
{
switch (a_tp) {
case NO_TIMESTAMP: return 0;
case TIME: return 8;
case TIME_WITH_MSEC: return 12;
case TIME_WITH_USEC: return 15;
case TIME_WITH_NSEC: return 18;
case DATE: return 8;
case DATE_TIME: return 17;
case DATE_TIME_WITH_MSEC: return 21;
case DATE_TIME_WITH_USEC: return 24;
case DATE_TIME_WITH_NSEC: return 27;
default: break;
}
assert(false); // should never get here
return 0;
}
int timestamp::format(stamp_type a_tp, time_val tv, char* a_buf, size_t a_sz,
bool a_utc, bool a_day_chk, bool a_use_cached_date)
{
BOOST_ASSERT(a_sz >= format_size(a_tp));
if (unlikely(a_tp == NO_TIMESTAMP)) {
a_buf[0] = '\0';
return 0;
}
auto pair = tv.split();
// If small time is given, it's a relative value.
bool rel = pair.first < 86400L;
auto now = a_day_chk || rel ? update().split() : pair;
if (rel)
pair.first += now.first;
auto sec = a_utc ? pair.first
: (pair.first + s_utc_nsec_offset / 1000000000L);
char* p;
switch (a_tp) {
case TIME:
case TIME_WITH_MSEC:
case TIME_WITH_USEC:
case TIME_WITH_NSEC: {
p = time_val::write_time(sec, pair.second, a_buf, a_tp);
return p - a_buf;
}
case DATE:
p = write_date(a_buf, sec, a_utc, 8, '\0', a_use_cached_date);
return 8;
case DATE_TIME:
case DATE_TIME_WITH_MSEC:
case DATE_TIME_WITH_USEC:
case DATE_TIME_WITH_NSEC: {
p = write_date(a_buf, sec, a_utc, 0, '\0', a_use_cached_date);
p = time_val::write_time(sec, pair.second, p, stamp_type(a_tp+4));
return p - a_buf;
}
default:
strcpy(a_buf, "UNDEFINED");
return -1;
}
}
time_val timestamp::from_string(const char* a_datetime, size_t n, bool a_utc) {
if (unlikely(n < 8 ||
(n > 8 && (n < 17 || a_datetime[8] != '-' ||
a_datetime[11] != ':' || a_datetime[14] != ':'))))
throw badarg_error("Invalid time format: ", std::string(a_datetime, n));
const char* p = a_datetime;
auto parse = [&p](int digits) {
int i = 0; const char* end = p + digits;
for (; p != end; ++p) i = (10*i) + (*p - '0');
return i;
};
unsigned hour = 0, min = 0, sec = 0;
long nsec = 0;
int year = parse(4);
unsigned mon = parse(2);
unsigned day = parse(2);
if (n > 8) {
p++;
hour = parse(2); p++;
min = parse(2); p++;
sec = parse(2);
const char* dot = p++;
if (*dot == '.' && n > 17)
{
const char* end = p + std::min<size_t>(6, n - (p - a_datetime));
while (*p >= '0' && *p <= '9' && p != end)
nsec = 10*nsec + (*p++ - '0');
int len = p - dot - 1;
switch (len)
{
case 3: nsec *= 1000000; break;
case 6: nsec *= 1000; break;
case 9: break;
default: throw badarg_error("Invalid microsecond format: ",
std::string(a_datetime, end - a_datetime));
}
}
}
return (a_utc
? time_val::universal_time(year, mon, day, hour, min, sec, 0)
: time_val::local_time(year, mon, day, hour, min, sec, 0)) + nsecs(nsec);
}
} // namespace utxx
<|endoftext|> |
<commit_before>#line 2 "togo/hash.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file hash.hpp
@brief Hashing utilities.
@ingroup hash
*/
#pragma once
#include <togo/config.hpp>
#include <togo/debug_constraints.hpp>
#include <togo/types.hpp>
#include <am/hash/fnv.hpp>
namespace togo {
namespace hash {
/**
@addtogroup hash
@{
*/
// TODO: Build constexpr version of MurmurHash2 (both lengths) and
// use it instead of FNV-1a
namespace {
static constexpr am::hash::HashLength const
hash32_length = am::hash::HashLength::HL32,
hash64_length = am::hash::HashLength::HL64;
}
/** @cond INTERNAL */
TOGO_CONSTRAIN_SAME(hash32, am::detail::hash::fnv_hash_type<hash32_length>);
TOGO_CONSTRAIN_SAME(hash64, am::detail::hash::fnv_hash_type<hash64_length>);
/** @endcond */
/**
Calculate 32-bit hash.
*/
inline hash32
calc32(
char const* const data,
unsigned const size
) {
return
size != 0
? am::hash::fnv1a<hash32_length>(data, size)
: hash32{0}
;
}
/**
Calculate 64-bit hash.
*/
inline hash64
calc64(
char const* const data,
unsigned const size
) {
return
size != 0
? am::hash::fnv1a<hash64_length>(data, size)
: hash64{0}
;
}
/**
32-bit hash literal.
*/
inline constexpr hash32
operator"" _hash32(
char const* const data,
std::size_t const size
) {
return
size != 0
? am::hash::fnv1a_c<hash32_length>(data, size)
: hash32{0}
;
}
/**
64-bit hash literal.
*/
inline constexpr hash64
operator"" _hash64(
char const* const data,
std::size_t const size
) {
return
size != 0
? am::hash::fnv1a_c<hash64_length>(data, size)
: hash64{0}
;
}
/// 32-bit hash identity (hash of nothing).
static constexpr hash32 const
IDENTITY32{0}; // = ""_hash32;
/// 64-bit hash identity (hash of nothing).
static constexpr hash64 const
IDENTITY64{0}; // = ""_hash64;
/** @} */ // end of doc-group hash
} // namespace hash
} // namespace togo
<commit_msg>hash: added calc overloads for StringRef.<commit_after>#line 2 "togo/hash.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file hash.hpp
@brief Hashing utilities.
@ingroup hash
*/
#pragma once
#include <togo/config.hpp>
#include <togo/debug_constraints.hpp>
#include <togo/types.hpp>
#include <togo/string.hpp>
#include <am/hash/fnv.hpp>
namespace togo {
namespace hash {
/**
@addtogroup hash
@{
*/
// TODO: Build constexpr version of MurmurHash2 (both lengths) and
// use it instead of FNV-1a
namespace {
static constexpr am::hash::HashLength const
hash32_length = am::hash::HashLength::HL32,
hash64_length = am::hash::HashLength::HL64;
}
/** @cond INTERNAL */
TOGO_CONSTRAIN_SAME(hash32, am::detail::hash::fnv_hash_type<hash32_length>);
TOGO_CONSTRAIN_SAME(hash64, am::detail::hash::fnv_hash_type<hash64_length>);
/** @endcond */
/**
Calculate 32-bit hash.
*/
inline hash32
calc32(
char const* const data,
unsigned const size
) {
return
size != 0
? am::hash::fnv1a<hash32_length>(data, size)
: hash32{0}
;
}
/**
Calculate 32-bit hash from string reference.
*/
inline hash32 calc32(StringRef const& ref) {
return hash::calc32(ref.data, ref.size);
}
/**
Calculate 64-bit hash.
*/
inline hash64
calc64(
char const* const data,
unsigned const size
) {
return
size != 0
? am::hash::fnv1a<hash64_length>(data, size)
: hash64{0}
;
}
/**
Calculate 64-bit hash from string reference.
*/
inline hash64 calc64(StringRef const& ref) {
return hash::calc64(ref.data, ref.size);
}
/**
32-bit hash literal.
*/
inline constexpr hash32
operator"" _hash32(
char const* const data,
std::size_t const size
) {
return
size != 0
? am::hash::fnv1a_c<hash32_length>(data, size)
: hash32{0}
;
}
/**
64-bit hash literal.
*/
inline constexpr hash64
operator"" _hash64(
char const* const data,
std::size_t const size
) {
return
size != 0
? am::hash::fnv1a_c<hash64_length>(data, size)
: hash64{0}
;
}
/// 32-bit hash identity (hash of nothing).
static constexpr hash32 const
IDENTITY32{0}; // = ""_hash32;
/// 64-bit hash identity (hash of nothing).
static constexpr hash64 const
IDENTITY64{0}; // = ""_hash64;
/** @} */ // end of doc-group hash
} // namespace hash
} // namespace togo
<|endoftext|> |
<commit_before>#line 2 "togo/tags.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file tags.hpp
@brief Variation/placeholder tags.
@ingroup utility
*/
#pragma once
#include <togo/config.hpp>
namespace togo {
/**
@addtogroup utility
@{
*/
/** @name Variation/placeholder tags */ /// @{
/**
Null value tag.
*/
enum class null_tag {};
/**
NUL-terminated string tag.
*/
enum class cstr_tag {};
/// @}
/** @} */ // end of doc-group utility
} // namespace togo
<commit_msg>tags: added bool_tag.<commit_after>#line 2 "togo/tags.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file tags.hpp
@brief Variation/placeholder tags.
@ingroup utility
*/
#pragma once
#include <togo/config.hpp>
namespace togo {
/**
@addtogroup utility
@{
*/
/** @name Variation/placeholder tags */ /// @{
/**
Null value tag.
*/
enum class null_tag {};
/**
NUL-terminated string tag.
*/
enum class cstr_tag {};
/**
Bool string tag.
*/
enum class bool_tag {};
/// @}
/** @} */ // end of doc-group utility
} // namespace togo
<|endoftext|> |
<commit_before>#include "ros/ros.h"
#include <gtest/gtest.h>
#include "geometry_msgs/Wrench.h"
#include "vortex_msgs/ThrusterForces.h"
class AllocatorTest : public ::testing::Test
{
public:
AllocatorTest()
{
pub = nh.advertise<geometry_msgs::Wrench>("rov_forces", 10);
sub = nh.subscribe("thruster_forces", 10, &AllocatorTest::Callback, this);
message_received = false;
if (!nh.getParam("/propulsion/thrusters/num", num_thrusters))
ROS_FATAL("Failed to read parameter number of thrusters.");
thrust.resize(num_thrusters);
}
void SetUp()
{
while (!IsNodeReady())
ros::spinOnce();
}
void Publish(double surge, double sway, double heave, double roll, double pitch, double yaw)
{
geometry_msgs::Wrench msg;
msg.force.x = surge;
msg.force.y = sway;
msg.force.z = heave;
msg.torque.x = roll;
msg.torque.y = pitch;
msg.torque.z = yaw;
pub.publish(msg);
}
void WaitForMessage()
{
while (!message_received)
ros::spinOnce();
}
int num_thrusters;
std::vector<double> thrust;
static const double MAX_ERROR = 1e-6;
private:
ros::NodeHandle nh;
ros::Publisher pub;
ros::Subscriber sub;
bool message_received;
void Callback(const vortex_msgs::ThrusterForces& msg)
{
thrust = msg.thrust;
message_received = true;
}
bool IsNodeReady()
{
return (pub.getNumSubscribers() > 0) && (sub.getNumPublishers() > 0);
}
};
TEST_F(AllocatorTest, CheckResponsiveness)
{
Publish(0, 0, 0, 0, 0, 0);
WaitForMessage();
}
TEST_F(AllocatorTest, ZeroInput)
{
Publish(0, 0, 0, 0, 0, 0);
WaitForMessage();
for(std::vector<double>::iterator it = thrust.begin(); it != thrust.end(); ++it)
{
EXPECT_NEAR(*it, 0, MAX_ERROR);
}
}
TEST_F(AllocatorTest, Forward)
{
Publish(1, 0, 0, 0, 0, 0);
WaitForMessage();
EXPECT_TRUE(thrust[0] > 0);
EXPECT_TRUE(thrust[1] > 0);
EXPECT_TRUE(thrust[2] < 0);
EXPECT_TRUE(thrust[3] < 0);
EXPECT_TRUE(thrust[4] < 0);
EXPECT_TRUE(thrust[5] > 0);
}
TEST_F(AllocatorTest, Sideways)
{
Publish(0, 1, 0, 0, 0, 0);
WaitForMessage();
EXPECT_TRUE(thrust[0] > 0);
EXPECT_TRUE(thrust[1] < 0);
EXPECT_TRUE(thrust[2] < 0);
EXPECT_TRUE(thrust[3] > 0);
EXPECT_NEAR(thrust[4], 0, MAX_ERROR);
EXPECT_NEAR(thrust[5], 0, MAX_ERROR);
}
TEST_F(AllocatorTest, Downward)
{
Publish(0, 0, 1, 0, 0, 0);
WaitForMessage();
EXPECT_NEAR(thrust[0], 0, MAX_ERROR);
EXPECT_NEAR(thrust[1], 0, MAX_ERROR);
EXPECT_NEAR(thrust[2], 0, MAX_ERROR);
EXPECT_NEAR(thrust[3], 0, MAX_ERROR);
EXPECT_TRUE(thrust[4] > 0);
EXPECT_TRUE(thrust[5] > 0);
}
TEST_F(AllocatorTest, TiltUp)
{
Publish(0, 0, 0, 0, 1, 0);
WaitForMessage();
EXPECT_NEAR(thrust[0], 0, MAX_ERROR);
EXPECT_NEAR(thrust[1], 0, MAX_ERROR);
EXPECT_NEAR(thrust[2], 0, MAX_ERROR);
EXPECT_NEAR(thrust[3], 0, MAX_ERROR);
EXPECT_TRUE(thrust[4] < 0);
EXPECT_TRUE(thrust[5] > 0);
}
TEST_F(AllocatorTest, TurnRight)
{
Publish(0, 0, 0, 0, 0, 1);
WaitForMessage();
EXPECT_TRUE(thrust[0] > 0);
EXPECT_TRUE(thrust[1] < 0);
EXPECT_TRUE(thrust[2] > 0);
EXPECT_TRUE(thrust[3] < 0);
EXPECT_NEAR(thrust[4], 0, MAX_ERROR);
EXPECT_NEAR(thrust[5], 0, MAX_ERROR);
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "allocator_test");
int ret = RUN_ALL_TESTS();
ros::shutdown();
return ret;
}
<commit_msg>Hard code values, not only signs<commit_after>#include "ros/ros.h"
#include <gtest/gtest.h>
#include "geometry_msgs/Wrench.h"
#include "vortex_msgs/ThrusterForces.h"
class AllocatorTest : public ::testing::Test
{
public:
AllocatorTest()
{
pub = nh.advertise<geometry_msgs::Wrench>("rov_forces", 10);
sub = nh.subscribe("thruster_forces", 10, &AllocatorTest::Callback, this);
message_received = false;
if (!nh.getParam("/propulsion/thrusters/num", num_thrusters))
ROS_FATAL("Failed to read parameter number of thrusters.");
thrust.resize(num_thrusters);
}
void SetUp()
{
while (!IsNodeReady())
ros::spinOnce();
}
void Publish(double surge, double sway, double heave, double roll, double pitch, double yaw)
{
geometry_msgs::Wrench msg;
msg.force.x = surge;
msg.force.y = sway;
msg.force.z = heave;
msg.torque.x = roll;
msg.torque.y = pitch;
msg.torque.z = yaw;
pub.publish(msg);
}
// TODO: This should be vectorized somehow in number of arguments
void ExpectThrustNear(double f1, double f2, double f3, double f4, double f5, double f6)
{
double arr[] = {f1, f2, f3, f4, f5, f6};
std::vector<double> thrust_expected (arr, arr + sizeof(arr) / sizeof(arr[0]) );
for (int i = 0; i < thrust.size(); ++i)
EXPECT_NEAR(thrust[i], thrust_expected[i], MAX_ERROR);
}
void ExpectThrustNear(double* arr)
{
for (int i = 0; i < thrust.size(); ++i)
EXPECT_NEAR(thrust[i], arr[i], MAX_ERROR);
}
void WaitForMessage()
{
while (!message_received)
ros::spinOnce();
}
int num_thrusters;
std::vector<double> thrust;
static const double MAX_ERROR = 1e-4;
private:
ros::NodeHandle nh;
ros::Publisher pub;
ros::Subscriber sub;
bool message_received;
void Callback(const vortex_msgs::ThrusterForces& msg)
{
thrust = msg.thrust;
message_received = true;
}
bool IsNodeReady()
{
return (pub.getNumSubscribers() > 0) && (sub.getNumPublishers() > 0);
}
};
TEST_F(AllocatorTest, CheckResponsiveness)
{
Publish(0, 0, 0, 0, 0, 0);
WaitForMessage();
}
TEST_F(AllocatorTest, ZeroInput)
{
Publish(0, 0, 0, 0, 0, 0);
WaitForMessage();
double thrust_expected[] = {0,0,0,0,0,0};
ExpectThrustNear(thrust_expected);
}
TEST_F(AllocatorTest, Forward)
{
Publish(1, 0, 0, 0, 0, 0);
WaitForMessage();
double thrust_expected[] = {0.35356, 0.35356, -0.35356, -0.35356, -0.20639, 0.20639};
ExpectThrustNear(thrust_expected);
}
TEST_F(AllocatorTest, Sideways)
{
Publish(0, 1, 0, 0, 0, 0);
WaitForMessage();
double thrust_expected[] = {0.35356, -0.35356, -0.35356, 0.35356, 0.0, 0.0};
ExpectThrustNear(thrust_expected);
}
TEST_F(AllocatorTest, Downward)
{
Publish(0, 0, 1, 0, 0, 0);
WaitForMessage();
double thrust_expected[] = {0.0, 0.0, 0.0, 0.0, 0.5, 0.5};
ExpectThrustNear(thrust_expected);
}
TEST_F(AllocatorTest, TiltUp)
{
Publish(0, 0, 0, 0, 1, 0);
WaitForMessage();
double thrust_expected[] = {0.0, 0.0, 0.0, 0.0, -3.1250, 3.1250};
ExpectThrustNear(thrust_expected);
}
TEST_F(AllocatorTest, TurnRight)
{
Publish(0, 0, 0, 0, 0, 1);
WaitForMessage();
double thrust_expected[] = {1.1666, -1.1666, 1.1666, -1.1666, 0.0, 0.0};
ExpectThrustNear(thrust_expected);
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "allocator_test");
int ret = RUN_ALL_TESTS();
ros::shutdown();
return ret;
}
<|endoftext|> |
<commit_before>//===- PowerPCRegisterInfo.cpp - PowerPC Register Information ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the PowerPC implementation of the MRegisterInfo class.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "reginfo"
#include "PowerPC.h"
#include "PowerPCRegisterInfo.h"
#include "PowerPCInstrBuilder.h"
#include "llvm/Constants.h"
#include "llvm/Type.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetFrameInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "Support/CommandLine.h"
#include "Support/Debug.h"
#include "Support/STLExtras.h"
#include <iostream>
using namespace llvm;
PowerPCRegisterInfo::PowerPCRegisterInfo()
: PowerPCGenRegisterInfo(PPC32::ADJCALLSTACKDOWN,
PPC32::ADJCALLSTACKUP) {}
static unsigned getIdx(const TargetRegisterClass *RC) {
if (RC == PowerPC::GPRCRegisterClass) {
switch (RC->getSize()) {
default: assert(0 && "Invalid data size!");
case 1: return 0;
case 2: return 1;
case 4: return 2;
}
} else if (RC == PowerPC::FPRCRegisterClass) {
switch (RC->getSize()) {
default: assert(0 && "Invalid data size!");
case 4: return 3;
case 8: return 4;
}
}
std::cerr << "Invalid register class to getIdx()!\n";
abort();
}
int
PowerPCRegisterInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned SrcReg, int FrameIdx,
const TargetRegisterClass *RC) const {
static const unsigned Opcode[] = {
PPC32::STB, PPC32::STH, PPC32::STW, PPC32::STFS, PPC32::STFD
};
unsigned OC = Opcode[getIdx(RC)];
MBB.insert(MI, addFrameReference(BuildMI(OC, 3).addReg(SrcReg),FrameIdx));
return 1;
}
int PowerPCRegisterInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned DestReg, int FrameIdx,
const TargetRegisterClass *RC) const{
static const unsigned Opcode[] = {
PPC32::LBZ, PPC32::LHZ, PPC32::LWZ, PPC32::LFS, PPC32::LFD
};
unsigned OC = Opcode[getIdx(RC)];
MBB.insert(MI, addFrameReference(BuildMI(OC, 2, DestReg), FrameIdx));
return 1;
}
int PowerPCRegisterInfo::copyRegToReg(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned DestReg, unsigned SrcReg,
const TargetRegisterClass *RC) const {
MachineInstr *I;
if (RC == PowerPC::GPRCRegisterClass) {
I = BuildMI(PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
} else if (RC == PowerPC::FPRCRegisterClass) {
I = BuildMI(PPC32::FMR, 1, DestReg).addReg(SrcReg);
} else {
std::cerr << "Attempt to copy register that is not GPR or FPR";
abort();
}
MBB.insert(MI, I);
return 1;
}
//===----------------------------------------------------------------------===//
// Stack Frame Processing methods
//===----------------------------------------------------------------------===//
// hasFP - Return true if the specified function should have a dedicated frame
// pointer register. This is true if the function has variable sized allocas or
// if frame pointer elimination is disabled.
//
static bool hasFP(MachineFunction &MF) {
return NoFramePointerElim || MF.getFrameInfo()->hasVarSizedObjects();
}
void PowerPCRegisterInfo::
eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
MachineBasicBlock::iterator I) const {
if (hasFP(MF)) {
// If we have a frame pointer, convert as follows:
// adjcallstackdown instruction => 'sub r1, r1, <amt>' and
// adjcallstackup instruction => 'add r1, r1, <amt>'
MachineInstr *Old = I;
int Amount = Old->getOperand(0).getImmedValue();
if (Amount != 0) {
// We need to keep the stack aligned properly. To do this, we round the
// amount of space needed for the outgoing arguments up to the next
// alignment boundary.
unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
Amount = (Amount+Align-1)/Align*Align;
MachineInstr *New;
if (Old->getOpcode() == PPC32::ADJCALLSTACKDOWN) {
New = BuildMI(PPC32::ADDI, 2, PPC32::R1).addReg(PPC32::R1)
.addSImm(-Amount);
} else {
assert(Old->getOpcode() == PPC32::ADJCALLSTACKUP);
New = BuildMI(PPC32::ADDI, 2, PPC32::R1).addReg(PPC32::R1)
.addSImm(Amount);
}
// Replace the pseudo instruction with a new instruction...
MBB.insert(I, New);
}
}
MBB.erase(I);
}
void
PowerPCRegisterInfo::eliminateFrameIndex(MachineFunction &MF,
MachineBasicBlock::iterator II) const {
unsigned i = 0;
MachineInstr &MI = *II;
while (!MI.getOperand(i).isFrameIndex()) {
++i;
assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
}
int FrameIndex = MI.getOperand(i).getFrameIndex();
// Replace the FrameIndex with base register with GPR1.
MI.SetMachineOperandReg(i, PPC32::R1);
// Take into account whether it's an add or mem instruction
unsigned OffIdx = (i == 2) ? 1 : 2;
// Now add the frame object offset to the offset from r1.
int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex) +
MI.getOperand(OffIdx).getImmedValue()+4;
if (!hasFP(MF))
Offset += MF.getFrameInfo()->getStackSize();
MI.SetMachineOperandConst(OffIdx, MachineOperand::MO_SignExtendedImmed, Offset);
DEBUG(std::cerr << "offset = " << Offset << std::endl);
}
void
PowerPCRegisterInfo::processFunctionBeforeFrameFinalized(MachineFunction &MF)
const {
// Do Nothing
}
void PowerPCRegisterInfo::emitPrologue(MachineFunction &MF) const {
MachineBasicBlock &MBB = MF.front(); // Prolog goes in entry BB
MachineBasicBlock::iterator MBBI = MBB.begin();
MachineFrameInfo *MFI = MF.getFrameInfo();
MachineInstr *MI;
// Get the number of bytes to allocate from the FrameInfo
unsigned NumBytes = MFI->getStackSize();
// FIXME: the assembly printer inserts "calls" aka branch-and-link to get the
// PC address. We may not know about those calls at this time, so be
// conservative.
if (MFI->hasCalls() || true) {
// When we have no frame pointer, we reserve argument space for call sites
// in the function immediately on entry to the current function. This
// eliminates the need for add/sub brackets around call sites.
//
NumBytes += MFI->getMaxCallFrameSize() +
24 /* Predefined PowerPC link area */ +
32 /* Predefined PowerPC params area */ +
0 /* local variables - managed by llvm*/ +
0 * 4 /* volatile GPRs used - managed by llvm */ +
0 * 8 /* volatile FPRs used - managed by llvm */;
// Round the size to a multiple of the alignment (don't forget the 4 byte
// offset though).
unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
NumBytes = ((NumBytes+4)+Align-1)/Align*Align - 4;
// Store the incoming LR so it is preserved across calls
MI = BuildMI(PPC32::MFLR, 0, PPC32::R0);
MBB.insert(MBBI, MI);
MI = BuildMI(PPC32::STW, 3).addReg(PPC32::R0).addSImm(8).addReg(PPC32::R1);
MBB.insert(MBBI, MI);
}
// Update frame info to pretend that this is part of the stack...
MFI->setStackSize(NumBytes);
// adjust stack pointer: r1 -= numbytes
if (NumBytes <= 32768) {
MI = BuildMI(PPC32::STWU, 3).addReg(PPC32::R1).addSImm(-NumBytes)
.addReg(PPC32::R1);
MBB.insert(MBBI, MI);
} else {
int NegNumbytes = -NumBytes;
MI = BuildMI(PPC32::LIS, 1, PPC32::R0).addSImm(NegNumbytes >> 16);
MBB.insert(MBBI, MI);
MI = BuildMI(PPC32::ORI, 2, PPC32::R0).addReg(PPC32::R0)
.addImm(NegNumbytes & 0xFFFF);
MBB.insert(MBBI, MI);
MI = BuildMI(PPC32::STWUX, 3).addReg(PPC32::R1).addReg(PPC32::R1)
.addReg(PPC32::R0);
MBB.insert(MBBI, MI);
}
}
void PowerPCRegisterInfo::emitEpilogue(MachineFunction &MF,
MachineBasicBlock &MBB) const {
const MachineFrameInfo *MFI = MF.getFrameInfo();
MachineBasicBlock::iterator MBBI = prior(MBB.end());
MachineInstr *MI;
assert(MBBI->getOpcode() == PPC32::BLR &&
"Can only insert epilog into returning blocks");
// Get the number of bytes allocated from the FrameInfo...
unsigned NumBytes = MFI->getStackSize();
// If we have calls, restore the LR value before we branch to it
// FIXME: the assembly printer inserts "calls" aka branch-and-link to get the
// PC address. We may not know about those calls at this time, so be
// conservative.
if (MFI->hasCalls() || true) {
// Restore LR
MI = BuildMI(PPC32::LWZ, 2, PPC32::R0).addSImm(NumBytes+8).addReg(PPC32::R1);
MBB.insert(MBBI, MI);
MI = BuildMI(PPC32::MTLR, 1).addReg(PPC32::R0);
MBB.insert(MBBI, MI);
}
// Adjust stack pointer back
if (NumBytes <= 32767) {
MI = BuildMI(PPC32::ADDI, 2, PPC32::R1).addReg(PPC32::R1).addSImm(NumBytes);
MBB.insert(MBBI, MI);
} else {
MI = BuildMI(PPC32::LWZ, 2, PPC32::R1).addSImm(0).addReg(PPC32::R1);
MBB.insert(MBBI, MI);
}
}
#include "PowerPCGenRegisterInfo.inc"
const TargetRegisterClass*
PowerPCRegisterInfo::getRegClassForType(const Type* Ty) const {
switch (Ty->getTypeID()) {
case Type::LongTyID:
case Type::ULongTyID: assert(0 && "Long values can't fit in registers!");
default: assert(0 && "Invalid type to getClass!");
case Type::BoolTyID:
case Type::SByteTyID:
case Type::UByteTyID:
case Type::ShortTyID:
case Type::UShortTyID:
case Type::IntTyID:
case Type::UIntTyID:
case Type::PointerTyID: return &GPRCInstance;
case Type::FloatTyID:
case Type::DoubleTyID: return &FPRCInstance;
}
}
<commit_msg>Do not store the stack pointer if the stack size is 0. Also, convert C-style comments to C++ and make sure code wraps at 80 cols.<commit_after>//===- PowerPCRegisterInfo.cpp - PowerPC Register Information ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the PowerPC implementation of the MRegisterInfo class.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "reginfo"
#include "PowerPC.h"
#include "PowerPCRegisterInfo.h"
#include "PowerPCInstrBuilder.h"
#include "llvm/Constants.h"
#include "llvm/Type.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetFrameInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "Support/CommandLine.h"
#include "Support/Debug.h"
#include "Support/STLExtras.h"
#include <iostream>
using namespace llvm;
PowerPCRegisterInfo::PowerPCRegisterInfo()
: PowerPCGenRegisterInfo(PPC32::ADJCALLSTACKDOWN,
PPC32::ADJCALLSTACKUP) {}
static unsigned getIdx(const TargetRegisterClass *RC) {
if (RC == PowerPC::GPRCRegisterClass) {
switch (RC->getSize()) {
default: assert(0 && "Invalid data size!");
case 1: return 0;
case 2: return 1;
case 4: return 2;
}
} else if (RC == PowerPC::FPRCRegisterClass) {
switch (RC->getSize()) {
default: assert(0 && "Invalid data size!");
case 4: return 3;
case 8: return 4;
}
}
std::cerr << "Invalid register class to getIdx()!\n";
abort();
}
int
PowerPCRegisterInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned SrcReg, int FrameIdx,
const TargetRegisterClass *RC) const {
static const unsigned Opcode[] = {
PPC32::STB, PPC32::STH, PPC32::STW, PPC32::STFS, PPC32::STFD
};
unsigned OC = Opcode[getIdx(RC)];
MBB.insert(MI, addFrameReference(BuildMI(OC, 3).addReg(SrcReg),FrameIdx));
return 1;
}
int PowerPCRegisterInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned DestReg, int FrameIdx,
const TargetRegisterClass *RC) const{
static const unsigned Opcode[] = {
PPC32::LBZ, PPC32::LHZ, PPC32::LWZ, PPC32::LFS, PPC32::LFD
};
unsigned OC = Opcode[getIdx(RC)];
MBB.insert(MI, addFrameReference(BuildMI(OC, 2, DestReg), FrameIdx));
return 1;
}
int PowerPCRegisterInfo::copyRegToReg(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned DestReg, unsigned SrcReg,
const TargetRegisterClass *RC) const {
MachineInstr *I;
if (RC == PowerPC::GPRCRegisterClass) {
I = BuildMI(PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
} else if (RC == PowerPC::FPRCRegisterClass) {
I = BuildMI(PPC32::FMR, 1, DestReg).addReg(SrcReg);
} else {
std::cerr << "Attempt to copy register that is not GPR or FPR";
abort();
}
MBB.insert(MI, I);
return 1;
}
//===----------------------------------------------------------------------===//
// Stack Frame Processing methods
//===----------------------------------------------------------------------===//
// hasFP - Return true if the specified function should have a dedicated frame
// pointer register. This is true if the function has variable sized allocas or
// if frame pointer elimination is disabled.
//
static bool hasFP(MachineFunction &MF) {
return NoFramePointerElim || MF.getFrameInfo()->hasVarSizedObjects();
}
void PowerPCRegisterInfo::
eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
MachineBasicBlock::iterator I) const {
if (hasFP(MF)) {
// If we have a frame pointer, convert as follows:
// adjcallstackdown instruction => 'sub r1, r1, <amt>' and
// adjcallstackup instruction => 'add r1, r1, <amt>'
MachineInstr *Old = I;
int Amount = Old->getOperand(0).getImmedValue();
if (Amount != 0) {
// We need to keep the stack aligned properly. To do this, we round the
// amount of space needed for the outgoing arguments up to the next
// alignment boundary.
unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
Amount = (Amount+Align-1)/Align*Align;
MachineInstr *New;
if (Old->getOpcode() == PPC32::ADJCALLSTACKDOWN) {
New = BuildMI(PPC32::ADDI, 2, PPC32::R1).addReg(PPC32::R1)
.addSImm(-Amount);
} else {
assert(Old->getOpcode() == PPC32::ADJCALLSTACKUP);
New = BuildMI(PPC32::ADDI, 2, PPC32::R1).addReg(PPC32::R1)
.addSImm(Amount);
}
// Replace the pseudo instruction with a new instruction...
MBB.insert(I, New);
}
}
MBB.erase(I);
}
void
PowerPCRegisterInfo::eliminateFrameIndex(MachineFunction &MF,
MachineBasicBlock::iterator II) const {
unsigned i = 0;
MachineInstr &MI = *II;
while (!MI.getOperand(i).isFrameIndex()) {
++i;
assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
}
int FrameIndex = MI.getOperand(i).getFrameIndex();
// Replace the FrameIndex with base register with GPR1.
MI.SetMachineOperandReg(i, PPC32::R1);
// Take into account whether it's an add or mem instruction
unsigned OffIdx = (i == 2) ? 1 : 2;
// Now add the frame object offset to the offset from r1.
int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex) +
MI.getOperand(OffIdx).getImmedValue()+4;
if (!hasFP(MF))
Offset += MF.getFrameInfo()->getStackSize();
MI.SetMachineOperandConst(OffIdx,MachineOperand::MO_SignExtendedImmed,Offset);
DEBUG(std::cerr << "offset = " << Offset << std::endl);
}
void
PowerPCRegisterInfo::processFunctionBeforeFrameFinalized(MachineFunction &MF)
const {
// Do Nothing
}
void PowerPCRegisterInfo::emitPrologue(MachineFunction &MF) const {
MachineBasicBlock &MBB = MF.front(); // Prolog goes in entry BB
MachineBasicBlock::iterator MBBI = MBB.begin();
MachineFrameInfo *MFI = MF.getFrameInfo();
MachineInstr *MI;
// Get the number of bytes to allocate from the FrameInfo
unsigned NumBytes = MFI->getStackSize();
// FIXME: the assembly printer inserts "calls" aka branch-and-link to get the
// PC address. We may not know about those calls at this time, so be
// conservative.
if (MFI->hasCalls() || true) {
// When we have no frame pointer, we reserve argument space for call sites
// in the function immediately on entry to the current function. This
// eliminates the need for add/sub brackets around call sites.
//
NumBytes += MFI->getMaxCallFrameSize() +
24 + // Predefined PowerPC link area
32 + // Predefined PowerPC params area
0 + // local variables - managed by LLVM
0 * 4 + // volatile GPRs used - managed by LLVM
0 * 8; // volatile FPRs used - managed by LLVM
// Round the size to a multiple of the alignment (don't forget the 4 byte
// offset though).
unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
NumBytes = ((NumBytes+4)+Align-1)/Align*Align - 4;
// Store the incoming LR so it is preserved across calls
MI = BuildMI(PPC32::MFLR, 0, PPC32::R0);
MBB.insert(MBBI, MI);
MI = BuildMI(PPC32::STW, 3).addReg(PPC32::R0).addSImm(8).addReg(PPC32::R1);
MBB.insert(MBBI, MI);
}
// Update frame info to pretend that this is part of the stack...
MFI->setStackSize(NumBytes);
// Do we need to allocate space on the stack?
if (NumBytes == 0) return;
// adjust stack pointer: r1 -= numbytes
if (NumBytes <= 32768) {
MI = BuildMI(PPC32::STWU, 3).addReg(PPC32::R1).addSImm(-NumBytes)
.addReg(PPC32::R1);
MBB.insert(MBBI, MI);
} else {
int NegNumbytes = -NumBytes;
MI = BuildMI(PPC32::LIS, 1, PPC32::R0).addSImm(NegNumbytes >> 16);
MBB.insert(MBBI, MI);
MI = BuildMI(PPC32::ORI, 2, PPC32::R0).addReg(PPC32::R0)
.addImm(NegNumbytes & 0xFFFF);
MBB.insert(MBBI, MI);
MI = BuildMI(PPC32::STWUX, 3).addReg(PPC32::R1).addReg(PPC32::R1)
.addReg(PPC32::R0);
MBB.insert(MBBI, MI);
}
}
void PowerPCRegisterInfo::emitEpilogue(MachineFunction &MF,
MachineBasicBlock &MBB) const {
const MachineFrameInfo *MFI = MF.getFrameInfo();
MachineBasicBlock::iterator MBBI = prior(MBB.end());
MachineInstr *MI;
assert(MBBI->getOpcode() == PPC32::BLR &&
"Can only insert epilog into returning blocks");
// Get the number of bytes allocated from the FrameInfo...
unsigned NumBytes = MFI->getStackSize();
// If we have calls, restore the LR value before we branch to it
// FIXME: the assembly printer inserts "calls" aka branch-and-link to get the
// PC address. We may not know about those calls at this time, so be
// conservative.
if (MFI->hasCalls() || true) {
// Restore LR
MI = BuildMI(PPC32::LWZ, 2,PPC32::R0).addSImm(NumBytes+8).addReg(PPC32::R1);
MBB.insert(MBBI, MI);
MI = BuildMI(PPC32::MTLR, 1).addReg(PPC32::R0);
MBB.insert(MBBI, MI);
}
// Do we need to adjust the stack pointer back?
if (NumBytes == 0) return;
// Adjust stack pointer back
if (NumBytes <= 32767) {
MI = BuildMI(PPC32::ADDI, 2, PPC32::R1).addReg(PPC32::R1).addSImm(NumBytes);
MBB.insert(MBBI, MI);
} else {
MI = BuildMI(PPC32::LWZ, 2, PPC32::R1).addSImm(0).addReg(PPC32::R1);
MBB.insert(MBBI, MI);
}
}
#include "PowerPCGenRegisterInfo.inc"
const TargetRegisterClass*
PowerPCRegisterInfo::getRegClassForType(const Type* Ty) const {
switch (Ty->getTypeID()) {
case Type::LongTyID:
case Type::ULongTyID: assert(0 && "Long values can't fit in registers!");
default: assert(0 && "Invalid type to getClass!");
case Type::BoolTyID:
case Type::SByteTyID:
case Type::UByteTyID:
case Type::ShortTyID:
case Type::UShortTyID:
case Type::IntTyID:
case Type::UIntTyID:
case Type::PointerTyID: return &GPRCInstance;
case Type::FloatTyID:
case Type::DoubleTyID: return &FPRCInstance;
}
}
<|endoftext|> |
<commit_before>#ifndef SCAN_CLASSIFY_SWITCH_BIT_BLOCK_RECOMBINER_HPP_
#define SCAN_CLASSIFY_SWITCH_BIT_BLOCK_RECOMBINER_HPP_
#include "clotho/recombination/bit_block_recombiner_def.hpp"
#include "clotho/recombination/inspect_methods.hpp"
#include "clotho/utility/bit_masks.hpp"
namespace clotho {
namespace recombine {
namespace walker {
namespace tag {
/**
* Scan and Classify walks the set bits in a block and stores their
* index (explodes the block into list of bit indices). The list of
* indices is iterated and the elements at these offsets are classified.
*
* This results in:
* - a single bit walking loop per 32-bit block
* - a simple loop over offsets
* - switch over the bit indices
*
* Thought process:
* - Bit scanning could more streamline (less context switching)
* - Requires more memory (64 * 4 = 256 Bytes)
* - Simpler classification loop (indices will be ordered as a result of scan)
* - Switch logic allows mask bits sets to be defined inline rather than computed
*
* Concern:
* - Doubles the number of iterative steps
*/
struct scan_and_classify_switch {};
} // namespace tag
} // namespace walker
} // namespace recombine
} // namespace clotho
namespace clotho {
namespace recombine {
#define CHECK_0() if( m_cfier( *first ) ) { res |= (Block) OFFSET( 0 ); }
#define CHECK( x ) if( m_cfier( *(first + x) ) ) { res |= (Block) OFFSET( x ); }
template < class Classifier, class InspectMethodTag >
class bit_block_recombiner< Classifier, InspectMethodTag, clotho::recombine::walker::tag::scan_and_classify_switch > {
public:
typedef Classifier classifier_type;
bit_block_recombiner( const classifier_type & cfier ) : m_cfier( cfier ) {}
template < class Block, class ElementIterator >
Block operator()( const Block b0, const Block b1, const ElementIterator first ) {
// Only compute the hash of each set bit
// In effect, delay the offset lookup to be performed by the switching logic
// Goal is to eliminate a 'double-lookup' (lookup from hash table, lookup based upon hash)
// This assumes switch logic results in a 'jump table'
unsigned int count = clotho::utility::hash_set_bits( InspectMethodTag::select(b0, b1), indices );
Block res = (Block)0;
unsigned int * idx = indices;
while( count-- ) {
switch( *idx++ ) {
case 0:
CHECK_0() break;
case 1:
CHECK(1) break;
case 2:
CHECK(28) break;
case 3:
CHECK(2) break;
case 4:
CHECK(29) break;
case 5:
CHECK(14) break;
case 6:
CHECK(24) break;
case 7:
CHECK(3) break;
case 8:
CHECK(30) break;
case 9:
CHECK(22) break;
case 10:
CHECK(20) break;
case 11:
CHECK(15) break;
case 12:
CHECK(25) break;
case 13:
CHECK(17) break;
case 14:
CHECK(4) break;
case 15:
CHECK(8) break;
case 16:
CHECK(31) break;
case 17:
CHECK(27) break;
case 18:
CHECK(13) break;
case 19:
CHECK(23) break;
case 20:
CHECK(21) break;
case 21:
CHECK(19) break;
case 22:
CHECK(16) break;
case 23:
CHECK(7) break;
case 24:
CHECK(26) break;
case 25:
CHECK(12) break;
case 26:
CHECK(18) break;
case 27:
CHECK(6) break;
case 28:
CHECK(11) break;
case 29:
CHECK(5) break;
case 30:
CHECK(10) break;
case 31:
CHECK(9) break;
case 32:
CHECK(32) break; // 0
case 33:
CHECK(33) break; // 1
case 34:
CHECK(60) break; // 28
case 35:
CHECK(34) break; // 2
case 36:
CHECK(61) break; // 29
case 37:
CHECK(46) break; // 14
case 38:
CHECK(56) break; // 24
case 39:
CHECK(35) break; // 3
case 40:
CHECK(62) break; // 30
case 41:
CHECK(54) break; // 22
case 42:
CHECK(52) break; // 20
case 43:
CHECK(47) break; // 15
case 44:
CHECK(57) break; // 25
case 45:
CHECK(49) break; // 17
case 46:
CHECK(36) break; // 4
case 47:
CHECK(40) break; // 8
case 48:
CHECK(63) break; // 31
case 49:
CHECK(59) break; // 27
case 50:
CHECK(45) break; // 13
case 51:
CHECK(55) break; // 23
case 52:
CHECK(53) break; // 21
case 53:
CHECK(51) break; // 19
case 54:
CHECK(48) break; // 16
case 55:
CHECK(39) break; // 7
case 56:
CHECK(58) break; // 26
case 57:
CHECK(44) break; // 12
case 58:
CHECK(50) break; // 18
case 59:
CHECK(38) break; // 6
case 60:
CHECK(43) break; // 11
case 61:
CHECK(37) break; // 5
case 62:
CHECK(42) break; // 10
case 63:
CHECK(41) break; // 9
default:
break;
}
}
Block rec = ((b0 & res) | (b1 & ~res));
return rec;
}
protected:
classifier_type m_cfier;
unsigned int indices[ 64 ];
};
#undef CHECK_0
#undef CHECK
} // namespace recombine
} // namespace clotho
#endif // SCAN_CLASSIFY_SWITCH_BIT_BLOCK_RECOMBINER_HPP_
<commit_msg>Made walking methods; Debating whether should be completely separated<commit_after>#ifndef SCAN_CLASSIFY_SWITCH_BIT_BLOCK_RECOMBINER_HPP_
#define SCAN_CLASSIFY_SWITCH_BIT_BLOCK_RECOMBINER_HPP_
#include "clotho/recombination/bit_block_recombiner_def.hpp"
#include "clotho/recombination/inspect_methods.hpp"
#include "clotho/utility/bit_masks.hpp"
namespace clotho {
namespace recombine {
namespace walker {
namespace tag {
/**
* Scan and Classify walks the set bits in a block and stores their
* index (explodes the block into list of bit indices). The list of
* indices is iterated and the elements at these offsets are classified.
*
* This results in:
* - a single bit walking loop per 32-bit block
* - a simple loop over offsets
* - switch over the bit indices
*
* Thought process:
* - Bit scanning could more streamline (less context switching)
* - Requires more memory (64 * 4 = 256 Bytes)
* - Simpler classification loop (indices will be ordered as a result of scan)
* - Switch logic allows mask bits sets to be defined inline rather than computed
*
* Concern:
* - Doubles the number of iterative steps
*/
struct scan_and_classify_switch {};
} // namespace tag
} // namespace walker
} // namespace recombine
} // namespace clotho
namespace clotho {
namespace recombine {
#define CHECK_0() if( m_cfier( *first ) ) { res |= (Block) OFFSET( 0 ); }
#define CHECK( x ) if( m_cfier( *(first + x) ) ) { res |= (Block) OFFSET( x ); }
template < class Classifier, class InspectMethodTag >
class bit_block_recombiner< Classifier, InspectMethodTag, clotho::recombine::walker::tag::scan_and_classify_switch > {
public:
typedef Classifier classifier_type;
bit_block_recombiner( const classifier_type & cfier ) : m_cfier( cfier ) {}
template < class Block, class ElementIterator >
Block operator()( const Block b0, const Block b1, const ElementIterator first ) {
Block mask = walk( InspectMethodTag::select(b0, b1), first );
Block rec = ((b0 & mask) | (b1 & ~mask));
return rec;
}
protected:
classifier_type m_cfier;
unsigned int indices[ 64 ];
template < class ElementIterator >
unsigned int walk( unsigned int b, const ElementIterator first ) {
// Only compute the hash of each set bit
// In effect, delay the offset lookup to be performed by the switching logic
// Goal is to eliminate a 'double-lookup' (lookup from hash table, lookup based upon hash)
// This assumes switch logic results in a 'jump table'
//
typedef unsigned int Block;
unsigned int count = clotho::utility::hash_set_bits( b, indices );
Block res = (Block)0;
unsigned int * idx = indices;
while( count-- ) {
switch( *idx++ ) {
case 0:
CHECK_0() break;
case 1:
CHECK(1) break;
case 2:
CHECK(28) break;
case 3:
CHECK(2) break;
case 4:
CHECK(29) break;
case 5:
CHECK(14) break;
case 6:
CHECK(24) break;
case 7:
CHECK(3) break;
case 8:
CHECK(30) break;
case 9:
CHECK(22) break;
case 10:
CHECK(20) break;
case 11:
CHECK(15) break;
case 12:
CHECK(25) break;
case 13:
CHECK(17) break;
case 14:
CHECK(4) break;
case 15:
CHECK(8) break;
case 16:
CHECK(31) break;
case 17:
CHECK(27) break;
case 18:
CHECK(13) break;
case 19:
CHECK(23) break;
case 20:
CHECK(21) break;
case 21:
CHECK(19) break;
case 22:
CHECK(16) break;
case 23:
CHECK(7) break;
case 24:
CHECK(26) break;
case 25:
CHECK(12) break;
case 26:
CHECK(18) break;
case 27:
CHECK(6) break;
case 28:
CHECK(11) break;
case 29:
CHECK(5) break;
case 30:
CHECK(10) break;
case 31:
CHECK(9) break;
default:
break;
}
}
return res;
}
template < class ElementIterator >
unsigned long walk( unsigned long b, const ElementIterator first ) {
// Only compute the hash of each set bit
// In effect, delay the offset lookup to be performed by the switching logic
// Goal is to eliminate a 'double-lookup' (lookup from hash table, lookup based upon hash)
// This assumes switch logic results in a 'jump table'
//
unsigned int lo = (unsigned int)b;
unsigned long mask = (unsigned long)walk( lo, first );
lo = (unsigned int) ( b >> 32 );
if( lo ) {
ElementIterator tmp = (first + 32);
unsigned long hi_mask = (unsigned long)walk(lo, tmp );
mask |= (hi_mask << 32);
}
return mask;
}
template < class ElementIterator >
unsigned long unrolled_walk( unsigned long b, const ElementIterator first ) {
// Only compute the hash of each set bit
// In effect, delay the offset lookup to be performed by the switching logic
// Goal is to eliminate a 'double-lookup' (lookup from hash table, lookup based upon hash)
// This assumes switch logic results in a 'jump table'
//
typedef unsigned long Block;
unsigned int count = clotho::utility::hash_set_bits( b, indices );
Block res = (Block)0;
unsigned int * idx = indices;
while( count-- ) {
switch( *idx++ ) {
case 0:
CHECK_0() break;
case 1:
CHECK(1) break;
case 2:
CHECK(28) break;
case 3:
CHECK(2) break;
case 4:
CHECK(29) break;
case 5:
CHECK(14) break;
case 6:
CHECK(24) break;
case 7:
CHECK(3) break;
case 8:
CHECK(30) break;
case 9:
CHECK(22) break;
case 10:
CHECK(20) break;
case 11:
CHECK(15) break;
case 12:
CHECK(25) break;
case 13:
CHECK(17) break;
case 14:
CHECK(4) break;
case 15:
CHECK(8) break;
case 16:
CHECK(31) break;
case 17:
CHECK(27) break;
case 18:
CHECK(13) break;
case 19:
CHECK(23) break;
case 20:
CHECK(21) break;
case 21:
CHECK(19) break;
case 22:
CHECK(16) break;
case 23:
CHECK(7) break;
case 24:
CHECK(26) break;
case 25:
CHECK(12) break;
case 26:
CHECK(18) break;
case 27:
CHECK(6) break;
case 28:
CHECK(11) break;
case 29:
CHECK(5) break;
case 30:
CHECK(10) break;
case 31:
CHECK(9) break;
case 32:
CHECK(32) break; // 0
case 33:
CHECK(33) break; // 1
case 34:
CHECK(60) break; // 28
case 35:
CHECK(34) break; // 2
case 36:
CHECK(61) break; // 29
case 37:
CHECK(46) break; // 14
case 38:
CHECK(56) break; // 24
case 39:
CHECK(35) break; // 3
case 40:
CHECK(62) break; // 30
case 41:
CHECK(54) break; // 22
case 42:
CHECK(52) break; // 20
case 43:
CHECK(47) break; // 15
case 44:
CHECK(57) break; // 25
case 45:
CHECK(49) break; // 17
case 46:
CHECK(36) break; // 4
case 47:
CHECK(40) break; // 8
case 48:
CHECK(63) break; // 31
case 49:
CHECK(59) break; // 27
case 50:
CHECK(45) break; // 13
case 51:
CHECK(55) break; // 23
case 52:
CHECK(53) break; // 21
case 53:
CHECK(51) break; // 19
case 54:
CHECK(48) break; // 16
case 55:
CHECK(39) break; // 7
case 56:
CHECK(58) break; // 26
case 57:
CHECK(44) break; // 12
case 58:
CHECK(50) break; // 18
case 59:
CHECK(38) break; // 6
case 60:
CHECK(43) break; // 11
case 61:
CHECK(37) break; // 5
case 62:
CHECK(42) break; // 10
case 63:
CHECK(41) break; // 9
default:
break;
}
}
return res;
}
};
#undef CHECK_0
#undef CHECK
} // namespace recombine
} // namespace clotho
#endif // SCAN_CLASSIFY_SWITCH_BIT_BLOCK_RECOMBINER_HPP_
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, Lakshman Anumolu, Pradeep Garigipati
* All rights reserved.
*
* This file is part of MeshIO whose distribution is governed by
* the BSD 2-Clause License contained in the accompanying LICENSE.txt
* file.
*/
#include <gtest/gtest.h>
#include <meshio/stl.hpp>
#include "testHelpers.hpp"
using namespace std;
using namespace meshio;
TEST(STL, READ_BINARY)
{
/* Reference STLData object */
vector< STLData<float> > referenceObjs;
initializeReferenceSTLObj(referenceObjs);
/* Read stl file using library function */
vector< STLData<float> > objs;
stl::read<float>(objs, TEST_DIR "/cube_binary.stl");
EXPECT_TRUE((objs[0] == referenceObjs[0]) == true);
referenceObjs.clear();
objs.clear();
}
TEST(STL, READ_ASCII)
{
/* Reference STLData object */
vector< STLData<float> > referenceObjs;
initializeReferenceSTLObj(referenceObjs);
vector< STLData<float> > objs;
stl::read<float>(objs, TEST_DIR "/cube_ascii.stl");
EXPECT_TRUE((objs[0] == referenceObjs[0]) == true);
referenceObjs.clear();
objs.clear();
}
TEST(STL, WRITE_ASCII)
{
/* Reference STLData object */
vector< STLData<float> > referenceObjs;
initializeReferenceSTLObj(referenceObjs);
vector< STLData<float> > objs;
stl::read<float>(objs, TEST_DIR "/cube_ascii.stl");
stl::write(TEST_DIR "/cube_ascii2ascii.stl", meshio::STL_ASCII, objs);
referenceObjs.clear();
objs.clear();
}
TEST(STL, CROSS_CHECK)
{
vector< STLData<float> > binReadObjs;
stl::read<float>(binReadObjs, TEST_DIR "/cube_binary.stl");
vector< STLData<float> > asciiReadObjs;
stl::read<float>(asciiReadObjs, TEST_DIR "/cube_ascii.stl");
EXPECT_TRUE((binReadObjs[0] == asciiReadObjs[0]) == true);
}<commit_msg>Corrected unit test condition checks<commit_after>/*
* Copyright (c) 2015, Lakshman Anumolu, Pradeep Garigipati
* All rights reserved.
*
* This file is part of MeshIO whose distribution is governed by
* the BSD 2-Clause License contained in the accompanying LICENSE.txt
* file.
*/
#include <gtest/gtest.h>
#include <meshio/stl.hpp>
#include "testHelpers.hpp"
using namespace std;
using namespace meshio;
TEST(STL, READ_BINARY)
{
/* Reference STLData object */
vector< STLData<float> > referenceObjs;
initializeReferenceSTLObj(referenceObjs);
/* Read stl file using library function */
vector< STLData<float> > objs;
stl::read<float>(objs, TEST_DIR "/cube_binary.stl");
EXPECT_TRUE(objs[0] == referenceObjs[0]);
referenceObjs.clear();
objs.clear();
}
TEST(STL, READ_ASCII)
{
/* Reference STLData object */
vector< STLData<float> > referenceObjs;
initializeReferenceSTLObj(referenceObjs);
vector< STLData<float> > objs;
stl::read<float>(objs, TEST_DIR "/cube_ascii.stl");
EXPECT_TRUE(objs[0] == referenceObjs[0]);
referenceObjs.clear();
objs.clear();
}
TEST(STL, WRITE_ASCII)
{
/* Reference STLData object */
vector< STLData<float> > referenceObjs;
initializeReferenceSTLObj(referenceObjs);
vector< STLData<float> > objs;
stl::read<float>(objs, TEST_DIR "/cube_ascii.stl");
stl::write(TEST_DIR "/cube_ascii2ascii.stl", meshio::STL_ASCII, objs);
referenceObjs.clear();
objs.clear();
}
TEST(STL, CROSS_CHECK)
{
vector< STLData<float> > binReadObjs;
stl::read<float>(binReadObjs, TEST_DIR "/cube_binary.stl");
vector< STLData<float> > asciiReadObjs;
stl::read<float>(asciiReadObjs, TEST_DIR "/cube_ascii.stl");
EXPECT_TRUE(binReadObjs[0] == asciiReadObjs[0]);
}<|endoftext|> |
<commit_before>#include "calc.cpp"
#include <iostream>
int main(){
while (std::cin) {
std::cout << "Please type your term to calculate: ";
int result = calc(std::cin);
std::cout << "= " << result << '\n';
}
}
<commit_msg>simpler prompt<commit_after>#include "calc.cpp"
#include <iostream>
int main(){
while (std::cin) {
std::cout << "Please type your input term: ";
int result = calc(std::cin);
std::cout << "= " << result << '\n';
}
}
<|endoftext|> |
<commit_before>//===-- X86FloatingPoint.cpp - FP_REG_KILL inserter -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the pass which inserts FP_REG_KILL instructions.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "x86-codegen"
#include "X86.h"
#include "X86InstrInfo.h"
#include "X86Subtarget.h"
#include "llvm/Instructions.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/CFG.h"
#include "llvm/ADT/Statistic.h"
using namespace llvm;
STATISTIC(NumFPKill, "Number of FP_REG_KILL instructions added");
namespace {
struct FPRegKiller : public MachineFunctionPass {
static char ID;
FPRegKiller() : MachineFunctionPass(&ID) {}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addPreservedID(MachineLoopInfoID);
AU.addPreservedID(MachineDominatorsID);
MachineFunctionPass::getAnalysisUsage(AU);
}
virtual bool runOnMachineFunction(MachineFunction &MF);
virtual const char *getPassName() const {
return "X86 FP_REG_KILL inserter";
}
};
char FPRegKiller::ID = 0;
}
FunctionPass *llvm::createX87FPRegKillInserterPass() {
return new FPRegKiller();
}
/// ContainsFPStackCode - Return true if the specific MBB has floating point
/// stack code, and thus needs an FP_REG_KILL.
static bool ContainsFPStackCode(MachineBasicBlock *MBB, unsigned SSELevel,
MachineRegisterInfo &MRI) {
// Scan the block, looking for instructions that define fp stack vregs.
for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
I != E; ++I) {
if (I->getNumOperands() == 0 || !I->getOperand(0).isReg())
continue;
for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
if (!I->getOperand(op).isReg() || !I->getOperand(op).isDef() ||
!TargetRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()))
continue;
const TargetRegisterClass *RegClass =
MRI.getRegClass(I->getOperand(op).getReg());
switch (RegClass->getID())
case X86::RFP32RegClassID:
case X86::RFP64RegClassID:
case X86::RFP80RegClassID:
return true;
}
}
// Check PHI nodes in successor blocks. These PHI's will be lowered to have
// a copy of the input value in this block. In SSE mode, we only care about
// 80-bit values.
// Final check, check LLVM BB's that are successors to the LLVM BB
// corresponding to BB for FP PHI nodes.
const BasicBlock *LLVMBB = MBB->getBasicBlock();
for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
SI != E; ++SI) {
const PHINode *PN;
for (BasicBlock::const_iterator II = SI->begin();
(PN = dyn_cast<PHINode>(II)); ++II) {
if (PN->getType()->isX86_FP80Ty() ||
(SSELevel == 0 && PN->getType()->isFloatingPointTy()) ||
(SSELevel < 2 && PN->getType()->isDoubleTy())) {
return true;
}
}
}
return false;
}
bool FPRegKiller::runOnMachineFunction(MachineFunction &MF) {
// If we are emitting FP stack code, scan the basic block to determine if this
// block defines any FP values. If so, put an FP_REG_KILL instruction before
// the terminator of the block.
// Note that FP stack instructions are used in all modes for long double,
// so we always need to do this check.
// Also note that it's possible for an FP stack register to be live across
// an instruction that produces multiple basic blocks (SSE CMOV) so we
// must check all the generated basic blocks.
// Scan all of the machine instructions in these MBBs, checking for FP
// stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
// Fast-path: If nothing is using the x87 registers, we don't need to do
// any scanning.
MachineRegisterInfo &MRI = MF.getRegInfo();
if (MRI.getRegClassVirtRegs(X86::RFP80RegisterClass).empty() &&
MRI.getRegClassVirtRegs(X86::RFP64RegisterClass).empty() &&
MRI.getRegClassVirtRegs(X86::RFP32RegisterClass).empty())
return false;
const X86Subtarget &Subtarget = MF.getTarget().getSubtarget<X86Subtarget>();
unsigned SSELevel = 0;
if (Subtarget.hasSSE2())
SSELevel = 2;
else if (Subtarget.hasSSE1())
SSELevel = 1;
bool Changed = false;
MachineFunction::iterator MBBI = MF.begin();
MachineFunction::iterator EndMBB = MF.end();
for (; MBBI != EndMBB; ++MBBI) {
MachineBasicBlock *MBB = MBBI;
// If this block returns, ignore it. We don't want to insert an FP_REG_KILL
// before the return.
if (!MBB->empty()) {
MachineBasicBlock::iterator EndI = MBB->end();
--EndI;
if (EndI->getDesc().isReturn())
continue;
}
// If we find any FP stack code, emit the FP_REG_KILL instruction.
if (ContainsFPStackCode(MBB, SSELevel, MRI)) {
BuildMI(*MBB, MBBI->getFirstTerminator(), DebugLoc(),
MF.getTarget().getInstrInfo()->get(X86::FP_REG_KILL));
++NumFPKill;
Changed = true;
}
}
return Changed;
}
<commit_msg>Use less evil form of switch stmt.<commit_after>//===-- X86FloatingPoint.cpp - FP_REG_KILL inserter -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the pass which inserts FP_REG_KILL instructions.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "x86-codegen"
#include "X86.h"
#include "X86InstrInfo.h"
#include "X86Subtarget.h"
#include "llvm/Instructions.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/CFG.h"
#include "llvm/ADT/Statistic.h"
using namespace llvm;
STATISTIC(NumFPKill, "Number of FP_REG_KILL instructions added");
namespace {
struct FPRegKiller : public MachineFunctionPass {
static char ID;
FPRegKiller() : MachineFunctionPass(&ID) {}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addPreservedID(MachineLoopInfoID);
AU.addPreservedID(MachineDominatorsID);
MachineFunctionPass::getAnalysisUsage(AU);
}
virtual bool runOnMachineFunction(MachineFunction &MF);
virtual const char *getPassName() const {
return "X86 FP_REG_KILL inserter";
}
};
char FPRegKiller::ID = 0;
}
FunctionPass *llvm::createX87FPRegKillInserterPass() {
return new FPRegKiller();
}
/// ContainsFPStackCode - Return true if the specific MBB has floating point
/// stack code, and thus needs an FP_REG_KILL.
static bool ContainsFPStackCode(MachineBasicBlock *MBB, unsigned SSELevel,
MachineRegisterInfo &MRI) {
// Scan the block, looking for instructions that define fp stack vregs.
for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
I != E; ++I) {
if (I->getNumOperands() == 0 || !I->getOperand(0).isReg())
continue;
for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
if (!I->getOperand(op).isReg() || !I->getOperand(op).isDef() ||
!TargetRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()))
continue;
const TargetRegisterClass *RegClass =
MRI.getRegClass(I->getOperand(op).getReg());
switch (RegClass->getID()) {
default: break;
case X86::RFP32RegClassID:
case X86::RFP64RegClassID:
case X86::RFP80RegClassID:
return true;
}
}
}
// Check PHI nodes in successor blocks. These PHI's will be lowered to have
// a copy of the input value in this block. In SSE mode, we only care about
// 80-bit values.
// Final check, check LLVM BB's that are successors to the LLVM BB
// corresponding to BB for FP PHI nodes.
const BasicBlock *LLVMBB = MBB->getBasicBlock();
for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
SI != E; ++SI) {
const PHINode *PN;
for (BasicBlock::const_iterator II = SI->begin();
(PN = dyn_cast<PHINode>(II)); ++II) {
if (PN->getType()->isX86_FP80Ty() ||
(SSELevel == 0 && PN->getType()->isFloatingPointTy()) ||
(SSELevel < 2 && PN->getType()->isDoubleTy())) {
return true;
}
}
}
return false;
}
bool FPRegKiller::runOnMachineFunction(MachineFunction &MF) {
// If we are emitting FP stack code, scan the basic block to determine if this
// block defines any FP values. If so, put an FP_REG_KILL instruction before
// the terminator of the block.
// Note that FP stack instructions are used in all modes for long double,
// so we always need to do this check.
// Also note that it's possible for an FP stack register to be live across
// an instruction that produces multiple basic blocks (SSE CMOV) so we
// must check all the generated basic blocks.
// Scan all of the machine instructions in these MBBs, checking for FP
// stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
// Fast-path: If nothing is using the x87 registers, we don't need to do
// any scanning.
MachineRegisterInfo &MRI = MF.getRegInfo();
if (MRI.getRegClassVirtRegs(X86::RFP80RegisterClass).empty() &&
MRI.getRegClassVirtRegs(X86::RFP64RegisterClass).empty() &&
MRI.getRegClassVirtRegs(X86::RFP32RegisterClass).empty())
return false;
const X86Subtarget &Subtarget = MF.getTarget().getSubtarget<X86Subtarget>();
unsigned SSELevel = 0;
if (Subtarget.hasSSE2())
SSELevel = 2;
else if (Subtarget.hasSSE1())
SSELevel = 1;
bool Changed = false;
MachineFunction::iterator MBBI = MF.begin();
MachineFunction::iterator EndMBB = MF.end();
for (; MBBI != EndMBB; ++MBBI) {
MachineBasicBlock *MBB = MBBI;
// If this block returns, ignore it. We don't want to insert an FP_REG_KILL
// before the return.
if (!MBB->empty()) {
MachineBasicBlock::iterator EndI = MBB->end();
--EndI;
if (EndI->getDesc().isReturn())
continue;
}
// If we find any FP stack code, emit the FP_REG_KILL instruction.
if (ContainsFPStackCode(MBB, SSELevel, MRI)) {
BuildMI(*MBB, MBBI->getFirstTerminator(), DebugLoc(),
MF.getTarget().getInstrInfo()->get(X86::FP_REG_KILL));
++NumFPKill;
Changed = true;
}
}
return Changed;
}
<|endoftext|> |
<commit_before>/* -----------------------------------------------------------------------------
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
----------------------------------------------------------------------------- */
// Author: Kevin P. Barry [[email protected]] [[email protected]]
#include <condition_variable>
#include <functional>
#include <list>
#include <mutex>
#include <string>
#include <thread>
#include <queue>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "thread-capture.h"
#include "thread-crosser.h"
using testing::ElementsAre;
namespace capture_thread {
class LogText : public ThreadCapture<LogText> {
public:
LogText() : cross_and_capture_to_(this) {}
static void Log(std::string line) {
if (GetCurrent()) {
GetCurrent()->LogLine(std::move(line));
}
}
const std::list<std::string> GetLinesUnsafe() {
return lines_;
}
private:
void LogLine(std::string line) {
std::lock_guard<std::mutex> lock(data_lock_);
lines_.emplace_back(std::move(line));
}
std::mutex data_lock_;
std::list<std::string> lines_;
const AutoThreadCrosser<LogText> cross_and_capture_to_;
};
class LogValues : public ThreadCapture<LogValues> {
public:
LogValues() : cross_and_capture_to_(this) {}
static void Count(int count) {
if (GetCurrent()) {
GetCurrent()->LogCount(count);
}
}
const std::list<int> GetCountsUnsafe() {
return counts_;
}
private:
void LogCount(int count) {
std::lock_guard<std::mutex> lock(data_lock_);
counts_.emplace_back(count);
}
std::mutex data_lock_;
std::list<int> counts_;
const AutoThreadCrosser<LogValues> cross_and_capture_to_;
};
class BlockingCallbackQueue {
public:
void Push(std::function<void()> callback) {
std::lock_guard<std::mutex> lock(queue_lock_);
queue_.push(std::move(callback));
condition_.notify_all();
}
// NOTE: Calling before returning avoids a race condition if WaitUntilEmpty()
// is used to wait until all calls complete.
bool PopAndCall() {
std::unique_lock<std::mutex> lock(queue_lock_);
while (queue_.empty()) {
condition_.wait(lock);
}
const bool valid = queue_.front().operator bool();
if (valid) {
queue_.front()();
}
queue_.pop();
condition_.notify_all();
return valid;
}
void WaitUntilEmpty() {
std::unique_lock<std::mutex> lock(queue_lock_);
while (!queue_.empty()) {
condition_.wait(lock);
}
}
private:
std::mutex queue_lock_;
std::condition_variable condition_;
std::queue<std::function<void()>> queue_;
};
TEST(ThreadCaptureTest, NoLoggerInterferenceWithDifferentTypes) {
LogText::Log("not logged");
LogValues::Count(0);
{
LogText text_logger;
LogText::Log("logged 1");
{
LogValues count_logger;
LogValues::Count(1);
LogText::Log("logged 2");
EXPECT_THAT(count_logger.GetCountsUnsafe(), ElementsAre(1));
}
LogText::Log("logged 3");
EXPECT_THAT(text_logger.GetLinesUnsafe(),
ElementsAre("logged 1", "logged 2", "logged 3"));
}
}
TEST(ThreadCaptureTest, SameTypeOverrides) {
LogText text_logger1;
LogText::Log("logged 1");
{
LogText text_logger2;
LogText::Log("logged 2");
EXPECT_THAT(text_logger2.GetLinesUnsafe(), ElementsAre("logged 2"));
}
LogText::Log("logged 3");
EXPECT_THAT(text_logger1.GetLinesUnsafe(),
ElementsAre("logged 1", "logged 3"));
}
TEST(ThreadCaptureTest, ThreadsAreNotCrossed) {
LogText logger;
LogText::Log("logged 1");
std::thread worker([] {
LogText::Log("logged 2");
});
worker.join();
EXPECT_THAT(logger.GetLinesUnsafe(), ElementsAre("logged 1"));
}
TEST(ThreadCrosserTest, WrapCallIsFineWithoutLogger) {
bool called = false;
ThreadCrosser::WrapCall([&called] {
called = true;
LogText::Log("not logged");
})();
EXPECT_TRUE(called);
}
TEST(ThreadCrosserTest, WrapCallIsNotLazy) {
LogText logger1;
bool called = false;
const auto callback = ThreadCrosser::WrapCall([&called] {
called = true;
LogText::Log("logged 1");
});
LogText logger2;
callback();
EXPECT_TRUE(called);
EXPECT_THAT(logger1.GetLinesUnsafe(), ElementsAre("logged 1"));
EXPECT_THAT(logger2.GetLinesUnsafe(), ElementsAre());
}
TEST(ThreadCrosserTest, WrapCallFallsThroughWithoutLogger) {
bool called = false;
const auto callback = ThreadCrosser::WrapCall([&called] {
called = true;
LogText::Log("logged 1");
});
LogText logger;
callback();
EXPECT_TRUE(called);
EXPECT_THAT(logger.GetLinesUnsafe(), ElementsAre("logged 1"));
}
TEST(ThreadCrosserTest, WrapCallWithNullCallbackIsNull) {
EXPECT_FALSE(ThreadCrosser::WrapCall(nullptr));
LogText logger;
EXPECT_FALSE(ThreadCrosser::WrapCall(nullptr));
}
TEST(ThreadCrosserTest, SingleThreadCrossing) {
LogText logger;
LogText::Log("logged 1");
std::thread worker(ThreadCrosser::WrapCall([] {
LogText::Log("logged 2");
}));
worker.join();
EXPECT_THAT(logger.GetLinesUnsafe(), ElementsAre("logged 1", "logged 2"));
}
TEST(ThreadCrosserTest, MultipleThreadCrossingWithMultipleLoggers) {
LogText text_logger;
LogText::Log("logged 1");
LogValues count_logger;
LogValues::Count(1);
std::thread worker(ThreadCrosser::WrapCall([] {
std::thread worker(ThreadCrosser::WrapCall([] {
LogText::Log("logged 2");
LogValues::Count(2);
}));
worker.join();
}));
worker.join();
EXPECT_THAT(text_logger.GetLinesUnsafe(),
ElementsAre("logged 1", "logged 2"));
EXPECT_THAT(count_logger.GetCountsUnsafe(), ElementsAre(1, 2));
}
TEST(ThreadCrosserTest, MultipleThreadCrossingWithDifferentLoggerScopes) {
LogText text_logger;
std::thread worker(ThreadCrosser::WrapCall([] {
LogValues count_logger;
std::thread worker(ThreadCrosser::WrapCall([] {
LogText::Log("logged 1");
LogValues::Count(1);
}));
worker.join();
EXPECT_THAT(count_logger.GetCountsUnsafe(), ElementsAre(1));
}));
worker.join();
EXPECT_THAT(text_logger.GetLinesUnsafe(), ElementsAre("logged 1"));
}
TEST(ThreadCrosserTest, DifferentLoggersInSameThread) {
BlockingCallbackQueue queue;
std::thread worker([&queue] {
while (true) {
LogText logger;
if (!queue.PopAndCall()) {
break;
}
LogText::Log("logged in thread");
EXPECT_THAT(logger.GetLinesUnsafe(), ElementsAre("logged in thread"));
}
});
LogText logger1;
queue.Push(ThreadCrosser::WrapCall([] {
LogText::Log("logged 1");
}));
queue.WaitUntilEmpty();
EXPECT_THAT(logger1.GetLinesUnsafe(), ElementsAre("logged 1"));
{
// It's important for the test case that logger2 overrides logger1, i.e.,
// that they are both in scope at the same time.
LogText logger2;
queue.Push(ThreadCrosser::WrapCall([] {
LogText::Log("logged 2");
}));
queue.WaitUntilEmpty();
EXPECT_THAT(logger2.GetLinesUnsafe(), ElementsAre("logged 2"));
}
queue.Push(ThreadCrosser::WrapCall([] {
LogText::Log("logged 3");
}));
queue.WaitUntilEmpty();
EXPECT_THAT(logger1.GetLinesUnsafe(), ElementsAre("logged 1", "logged 3"));
queue.Push(nullptr); // (Causes the thread to exit.)
worker.join();
}
} // namespace capture_thread
int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Adds a ThreadCrosser unit test that changes stack order of loggers.<commit_after>/* -----------------------------------------------------------------------------
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
----------------------------------------------------------------------------- */
// Author: Kevin P. Barry [[email protected]] [[email protected]]
#include <condition_variable>
#include <functional>
#include <list>
#include <mutex>
#include <string>
#include <thread>
#include <queue>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "thread-capture.h"
#include "thread-crosser.h"
using testing::ElementsAre;
namespace capture_thread {
class LogText : public ThreadCapture<LogText> {
public:
LogText() : cross_and_capture_to_(this) {}
static void Log(std::string line) {
if (GetCurrent()) {
GetCurrent()->LogLine(std::move(line));
}
}
const std::list<std::string> GetLinesUnsafe() {
return lines_;
}
private:
void LogLine(std::string line) {
std::lock_guard<std::mutex> lock(data_lock_);
lines_.emplace_back(std::move(line));
}
std::mutex data_lock_;
std::list<std::string> lines_;
const AutoThreadCrosser<LogText> cross_and_capture_to_;
};
class LogValues : public ThreadCapture<LogValues> {
public:
LogValues() : cross_and_capture_to_(this) {}
static void Count(int count) {
if (GetCurrent()) {
GetCurrent()->LogCount(count);
}
}
const std::list<int> GetCountsUnsafe() {
return counts_;
}
private:
void LogCount(int count) {
std::lock_guard<std::mutex> lock(data_lock_);
counts_.emplace_back(count);
}
std::mutex data_lock_;
std::list<int> counts_;
const AutoThreadCrosser<LogValues> cross_and_capture_to_;
};
class BlockingCallbackQueue {
public:
void Push(std::function<void()> callback) {
std::lock_guard<std::mutex> lock(queue_lock_);
queue_.push(std::move(callback));
condition_.notify_all();
}
// NOTE: Calling before returning avoids a race condition if WaitUntilEmpty()
// is used to wait until all calls complete.
bool PopAndCall() {
std::unique_lock<std::mutex> lock(queue_lock_);
while (queue_.empty()) {
condition_.wait(lock);
}
const bool valid = queue_.front().operator bool();
if (valid) {
queue_.front()();
}
queue_.pop();
condition_.notify_all();
return valid;
}
void WaitUntilEmpty() {
std::unique_lock<std::mutex> lock(queue_lock_);
while (!queue_.empty()) {
condition_.wait(lock);
}
}
private:
std::mutex queue_lock_;
std::condition_variable condition_;
std::queue<std::function<void()>> queue_;
};
TEST(ThreadCaptureTest, NoLoggerInterferenceWithDifferentTypes) {
LogText::Log("not logged");
LogValues::Count(0);
{
LogText text_logger;
LogText::Log("logged 1");
{
LogValues count_logger;
LogValues::Count(1);
LogText::Log("logged 2");
EXPECT_THAT(count_logger.GetCountsUnsafe(), ElementsAre(1));
}
LogText::Log("logged 3");
EXPECT_THAT(text_logger.GetLinesUnsafe(),
ElementsAre("logged 1", "logged 2", "logged 3"));
}
}
TEST(ThreadCaptureTest, SameTypeOverrides) {
LogText text_logger1;
LogText::Log("logged 1");
{
LogText text_logger2;
LogText::Log("logged 2");
EXPECT_THAT(text_logger2.GetLinesUnsafe(), ElementsAre("logged 2"));
}
LogText::Log("logged 3");
EXPECT_THAT(text_logger1.GetLinesUnsafe(),
ElementsAre("logged 1", "logged 3"));
}
TEST(ThreadCaptureTest, ThreadsAreNotCrossed) {
LogText logger;
LogText::Log("logged 1");
std::thread worker([] {
LogText::Log("logged 2");
});
worker.join();
EXPECT_THAT(logger.GetLinesUnsafe(), ElementsAre("logged 1"));
}
TEST(ThreadCrosserTest, WrapCallIsFineWithoutLogger) {
bool called = false;
ThreadCrosser::WrapCall([&called] {
called = true;
LogText::Log("not logged");
})();
EXPECT_TRUE(called);
}
TEST(ThreadCrosserTest, WrapCallIsNotLazy) {
LogText logger1;
bool called = false;
const auto callback = ThreadCrosser::WrapCall([&called] {
called = true;
LogText::Log("logged 1");
});
LogText logger2;
callback();
EXPECT_TRUE(called);
EXPECT_THAT(logger1.GetLinesUnsafe(), ElementsAre("logged 1"));
EXPECT_THAT(logger2.GetLinesUnsafe(), ElementsAre());
}
TEST(ThreadCrosserTest, WrapCallFallsThroughWithoutLogger) {
bool called = false;
const auto callback = ThreadCrosser::WrapCall([&called] {
called = true;
LogText::Log("logged 1");
});
LogText logger;
callback();
EXPECT_TRUE(called);
EXPECT_THAT(logger.GetLinesUnsafe(), ElementsAre("logged 1"));
}
TEST(ThreadCrosserTest, WrapCallWithNullCallbackIsNull) {
EXPECT_FALSE(ThreadCrosser::WrapCall(nullptr));
LogText logger;
EXPECT_FALSE(ThreadCrosser::WrapCall(nullptr));
}
TEST(ThreadCrosserTest, SingleThreadCrossing) {
LogText logger;
LogText::Log("logged 1");
std::thread worker(ThreadCrosser::WrapCall([] {
LogText::Log("logged 2");
}));
worker.join();
EXPECT_THAT(logger.GetLinesUnsafe(), ElementsAre("logged 1", "logged 2"));
}
TEST(ThreadCrosserTest, MultipleThreadCrossingWithMultipleLoggers) {
LogText text_logger;
LogText::Log("logged 1");
LogValues count_logger;
LogValues::Count(1);
std::thread worker(ThreadCrosser::WrapCall([] {
std::thread worker(ThreadCrosser::WrapCall([] {
LogText::Log("logged 2");
LogValues::Count(2);
}));
worker.join();
}));
worker.join();
EXPECT_THAT(text_logger.GetLinesUnsafe(),
ElementsAre("logged 1", "logged 2"));
EXPECT_THAT(count_logger.GetCountsUnsafe(), ElementsAre(1, 2));
}
TEST(ThreadCrosserTest, MultipleThreadCrossingWithDifferentLoggerScopes) {
LogText text_logger;
std::thread worker(ThreadCrosser::WrapCall([] {
LogValues count_logger;
std::thread worker(ThreadCrosser::WrapCall([] {
LogText::Log("logged 1");
LogValues::Count(1);
}));
worker.join();
EXPECT_THAT(count_logger.GetCountsUnsafe(), ElementsAre(1));
}));
worker.join();
EXPECT_THAT(text_logger.GetLinesUnsafe(), ElementsAre("logged 1"));
}
TEST(ThreadCrosserTest, DifferentLoggersInSameThread) {
BlockingCallbackQueue queue;
std::thread worker([&queue] {
while (true) {
LogText logger;
if (!queue.PopAndCall()) {
break;
}
LogText::Log("logged in thread");
EXPECT_THAT(logger.GetLinesUnsafe(), ElementsAre("logged in thread"));
}
});
LogText logger1;
queue.Push(ThreadCrosser::WrapCall([] {
LogText::Log("logged 1");
}));
queue.WaitUntilEmpty();
EXPECT_THAT(logger1.GetLinesUnsafe(), ElementsAre("logged 1"));
{
// It's important for the test case that logger2 overrides logger1, i.e.,
// that they are both in scope at the same time.
LogText logger2;
queue.Push(ThreadCrosser::WrapCall([] {
LogText::Log("logged 2");
}));
queue.WaitUntilEmpty();
EXPECT_THAT(logger2.GetLinesUnsafe(), ElementsAre("logged 2"));
}
queue.Push(ThreadCrosser::WrapCall([] {
LogText::Log("logged 3");
}));
queue.WaitUntilEmpty();
EXPECT_THAT(logger1.GetLinesUnsafe(), ElementsAre("logged 1", "logged 3"));
queue.Push(nullptr); // (Causes the thread to exit.)
worker.join();
}
TEST(ThreadCrosserTest, ReverseOrderOfLoggersOnStack) {
LogText logger1;
const auto callback = ThreadCrosser::WrapCall([] {
LogText::Log("logged 1");
});
LogText logger2;
const auto worker_call = ThreadCrosser::WrapCall([callback] {
// In callback(), logger1 overrides logger2, whereas in the main thread
// logger2 overrides logger1.
callback();
LogText::Log("logged 2");
});
LogText logger3;
// Call using a thread.
std::thread worker(worker_call);
worker.join();
EXPECT_THAT(logger1.GetLinesUnsafe(), ElementsAre("logged 1"));
EXPECT_THAT(logger2.GetLinesUnsafe(), ElementsAre("logged 2"));
EXPECT_THAT(logger3.GetLinesUnsafe(), ElementsAre());
// Call in the main thread.
worker_call();
EXPECT_THAT(logger1.GetLinesUnsafe(), ElementsAre("logged 1", "logged 1"));
EXPECT_THAT(logger2.GetLinesUnsafe(), ElementsAre("logged 2", "logged 2"));
EXPECT_THAT(logger3.GetLinesUnsafe(), ElementsAre());
}
} // namespace capture_thread
int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>//===-- VPlanVerifier.cpp -------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file defines the class VPlanVerifier, which contains utility functions
/// to check the consistency and invariants of a VPlan.
///
//===----------------------------------------------------------------------===//
#include "VPlanVerifier.h"
#include "llvm/ADT/DepthFirstIterator.h"
#define DEBUG_TYPE "loop-vectorize"
using namespace llvm;
static cl::opt<bool> EnableHCFGVerifier("vplan-verify-hcfg", cl::init(false),
cl::Hidden,
cl::desc("Verify VPlan H-CFG."));
/// Utility function that checks whether \p VPBlockVec has duplicate
/// VPBlockBases.
static bool hasDuplicates(const SmallVectorImpl<VPBlockBase *> &VPBlockVec) {
SmallDenseSet<const VPBlockBase *, 8> VPBlockSet;
for (const auto *Block : VPBlockVec) {
if (VPBlockSet.count(Block))
return true;
VPBlockSet.insert(Block);
}
return false;
}
/// Helper function that verifies the CFG invariants of the VPBlockBases within
/// \p Region. Checks in this function are generic for VPBlockBases. They are
/// not specific for VPBasicBlocks or VPRegionBlocks.
static void verifyBlocksInRegion(const VPRegionBlock *Region) {
for (const VPBlockBase *VPB :
make_range(df_iterator<const VPBlockBase *>::begin(Region->getEntry()),
df_iterator<const VPBlockBase *>::end(Region->getExit()))) {
// Check block's parent.
assert(VPB->getParent() == Region && "VPBlockBase has wrong parent");
// Check block's successors.
const auto &Successors = VPB->getSuccessors();
// There must be only one instance of a successor in block's successor list.
// TODO: This won't work for switch statements.
assert(!hasDuplicates(Successors) &&
"Multiple instances of the same successor.");
(void)hasDuplicates;
for (const VPBlockBase *Succ : Successors) {
// There must be a bi-directional link between block and successor.
const auto &SuccPreds = Succ->getPredecessors();
assert(std::find(SuccPreds.begin(), SuccPreds.end(), VPB) !=
SuccPreds.end() &&
"Missing predecessor link.");
(void)SuccPreds;
}
// Check block's predecessors.
const auto &Predecessors = VPB->getPredecessors();
// There must be only one instance of a predecessor in block's predecessor
// list.
// TODO: This won't work for switch statements.
assert(!hasDuplicates(Predecessors) &&
"Multiple instances of the same predecessor.");
for (const VPBlockBase *Pred : Predecessors) {
// Block and predecessor must be inside the same region.
assert(Pred->getParent() == VPB->getParent() &&
"Predecessor is not in the same region.");
// There must be a bi-directional link between block and predecessor.
const auto &PredSuccs = Pred->getSuccessors();
assert(std::find(PredSuccs.begin(), PredSuccs.end(), VPB) !=
PredSuccs.end() &&
"Missing successor link.");
(void)PredSuccs;
}
}
}
/// Verify the CFG invariants of VPRegionBlock \p Region and its nested
/// VPBlockBases. Do not recurse inside nested VPRegionBlocks.
static void verifyRegion(const VPRegionBlock *Region) {
const VPBlockBase *Entry = Region->getEntry();
const VPBlockBase *Exit = Region->getExit();
// Entry and Exit shouldn't have any predecessor/successor, respectively.
assert(!Entry->getNumPredecessors() && "Region entry has predecessors.");
assert(!Exit->getNumSuccessors() && "Region exit has successors.");
(void)Entry;
(void)Exit;
verifyBlocksInRegion(Region);
}
/// Verify the CFG invariants of VPRegionBlock \p Region and its nested
/// VPBlockBases. Recurse inside nested VPRegionBlocks.
static void verifyRegionRec(const VPRegionBlock *Region) {
verifyRegion(Region);
// Recurse inside nested regions.
for (const VPBlockBase *VPB :
make_range(df_iterator<const VPBlockBase *>::begin(Region->getEntry()),
df_iterator<const VPBlockBase *>::end(Region->getExit()))) {
if (const auto *SubRegion = dyn_cast<VPRegionBlock>(VPB))
verifyRegionRec(SubRegion);
}
}
void VPlanVerifier::verifyHierarchicalCFG(
const VPRegionBlock *TopRegion) const {
if (!EnableHCFGVerifier)
return;
DEBUG(dbgs() << "Verifying VPlan H-CFG.\n");
assert(!TopRegion->getParent() && "VPlan Top Region should have no parent.");
verifyRegionRec(TopRegion);
}
<commit_msg>Fix warning from r332654 with LLVM_ATTRIBUTE_USED<commit_after>//===-- VPlanVerifier.cpp -------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file defines the class VPlanVerifier, which contains utility functions
/// to check the consistency and invariants of a VPlan.
///
//===----------------------------------------------------------------------===//
#include "VPlanVerifier.h"
#include "llvm/ADT/DepthFirstIterator.h"
#define DEBUG_TYPE "loop-vectorize"
using namespace llvm;
static cl::opt<bool> EnableHCFGVerifier("vplan-verify-hcfg", cl::init(false),
cl::Hidden,
cl::desc("Verify VPlan H-CFG."));
/// Utility function that checks whether \p VPBlockVec has duplicate
/// VPBlockBases.
LLVM_ATTRIBUTE_USED static bool
hasDuplicates(const SmallVectorImpl<VPBlockBase *> &VPBlockVec) {
SmallDenseSet<const VPBlockBase *, 8> VPBlockSet;
for (const auto *Block : VPBlockVec) {
if (VPBlockSet.count(Block))
return true;
VPBlockSet.insert(Block);
}
return false;
}
/// Helper function that verifies the CFG invariants of the VPBlockBases within
/// \p Region. Checks in this function are generic for VPBlockBases. They are
/// not specific for VPBasicBlocks or VPRegionBlocks.
static void verifyBlocksInRegion(const VPRegionBlock *Region) {
for (const VPBlockBase *VPB :
make_range(df_iterator<const VPBlockBase *>::begin(Region->getEntry()),
df_iterator<const VPBlockBase *>::end(Region->getExit()))) {
// Check block's parent.
assert(VPB->getParent() == Region && "VPBlockBase has wrong parent");
// Check block's successors.
const auto &Successors = VPB->getSuccessors();
// There must be only one instance of a successor in block's successor list.
// TODO: This won't work for switch statements.
assert(!hasDuplicates(Successors) &&
"Multiple instances of the same successor.");
for (const VPBlockBase *Succ : Successors) {
// There must be a bi-directional link between block and successor.
const auto &SuccPreds = Succ->getPredecessors();
assert(std::find(SuccPreds.begin(), SuccPreds.end(), VPB) !=
SuccPreds.end() &&
"Missing predecessor link.");
(void)SuccPreds;
}
// Check block's predecessors.
const auto &Predecessors = VPB->getPredecessors();
// There must be only one instance of a predecessor in block's predecessor
// list.
// TODO: This won't work for switch statements.
assert(!hasDuplicates(Predecessors) &&
"Multiple instances of the same predecessor.");
for (const VPBlockBase *Pred : Predecessors) {
// Block and predecessor must be inside the same region.
assert(Pred->getParent() == VPB->getParent() &&
"Predecessor is not in the same region.");
// There must be a bi-directional link between block and predecessor.
const auto &PredSuccs = Pred->getSuccessors();
assert(std::find(PredSuccs.begin(), PredSuccs.end(), VPB) !=
PredSuccs.end() &&
"Missing successor link.");
(void)PredSuccs;
}
}
}
/// Verify the CFG invariants of VPRegionBlock \p Region and its nested
/// VPBlockBases. Do not recurse inside nested VPRegionBlocks.
static void verifyRegion(const VPRegionBlock *Region) {
const VPBlockBase *Entry = Region->getEntry();
const VPBlockBase *Exit = Region->getExit();
// Entry and Exit shouldn't have any predecessor/successor, respectively.
assert(!Entry->getNumPredecessors() && "Region entry has predecessors.");
assert(!Exit->getNumSuccessors() && "Region exit has successors.");
(void)Entry;
(void)Exit;
verifyBlocksInRegion(Region);
}
/// Verify the CFG invariants of VPRegionBlock \p Region and its nested
/// VPBlockBases. Recurse inside nested VPRegionBlocks.
static void verifyRegionRec(const VPRegionBlock *Region) {
verifyRegion(Region);
// Recurse inside nested regions.
for (const VPBlockBase *VPB :
make_range(df_iterator<const VPBlockBase *>::begin(Region->getEntry()),
df_iterator<const VPBlockBase *>::end(Region->getExit()))) {
if (const auto *SubRegion = dyn_cast<VPRegionBlock>(VPB))
verifyRegionRec(SubRegion);
}
}
void VPlanVerifier::verifyHierarchicalCFG(
const VPRegionBlock *TopRegion) const {
if (!EnableHCFGVerifier)
return;
DEBUG(dbgs() << "Verifying VPlan H-CFG.\n");
assert(!TopRegion->getParent() && "VPlan Top Region should have no parent.");
verifyRegionRec(TopRegion);
}
<|endoftext|> |
<commit_before>#pragma once
#include <array>
#include <vector>
#include <ostream>
#ifdef DEBUG
# include <iostream>
#endif
#include "util.hpp"
#include "debug.hpp"
namespace utki{
// TODO: remove when C++'20 becomes very common.
/**
* @brief span template class.
* This class is a wrapper of continuous memory buffer, it encapsulates pointer to memory block and size of that memory block.
* It does not own the memory.
* This is a replacement of std::span when C++'20 is not available.
*/
template <class T> class span final{
public:
typedef T value_type;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef value_type* iterator;
typedef const value_type* const_iterator;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
private:
pointer buf = nullptr;
size_type bufSize = 0;
public:
span(const span&) = default;
span& operator=(const span&) = default;
/**
* @brief Create a span object.
* Creates a span object which wraps given memory buffer of specified size.
* Note, the memory will not be freed upon this Buffer object destruction,
* Buffer does not own the memory.
* @param bufPtr - pointer to the memory buffer.
* @param bufSize - size of the memory buffer.
*/
span(pointer bufPtr, size_type bufSize)noexcept :
buf(bufPtr),
bufSize(bufSize)
{}
span()noexcept{}
/**
* @brief Constructor for automatic conversion from nullptr.
* @param bufPtr - pointer to the memory buffer. Makes not much sense, because size is 0 anyway.
*/
span(nullptr_t)noexcept :
buf(nullptr),
bufSize(0)
{}
/**
* @brief get buffer size.
* @return number of elements in buffer.
*/
size_type size()const noexcept{
return this->bufSize;
}
bool empty()const noexcept{
return this->size() == 0;
}
/**
* @brief get size of buffer in bytes.
* @return size of array in bytes.
*/
size_type size_bytes()const noexcept{
return this->size() * sizeof(value_type);
}
//TODO: deprecated, remove.
size_type sizeInBytes()const noexcept{
return this->size_bytes();
}
/**
* @brief access specified element of the buffer.
* Const version of Buffer::operator[].
* @param i - element index.
* @return reference to i'th element of the buffer.
*/
const_reference operator[](size_type i)const noexcept{
ASSERT(i < this->size())
return this->buf[i];
}
/**
* @brief access specified element of the buffer.
* @param i - element index.
* @return reference to i'th element of the buffer.
*/
reference operator[](size_type i)noexcept{
ASSERT_INFO(i < this->size(), "operator[]: index out of bounds")
return this->buf[i];
}
/**
* @brief get pointer to first element of the buffer.
* @return pointer to first element of the buffer.
*/
iterator begin()noexcept{
return this->buf;
}
/**
* @brief get pointer to first element of the buffer.
* @return pointer to first element of the buffer.
*/
const_iterator begin()const noexcept{
return this->cbegin();
}
const_iterator cbegin()const noexcept{
return this->buf;
}
/**
* @brief get pointer to "after last" element of the buffer.
* @return pointer to "after last" element of the buffer.
*/
iterator end()noexcept{
return this->buf + this->bufSize;
}
/**
* @brief get const pointer to "after last" element of the buffer.
* @return const pointer to "after last" element of the buffer.
*/
const_iterator end()const noexcept{
return this->cend();
}
const_iterator cend()const noexcept{
return this->buf + this->bufSize;
}
const_reverse_iterator crbegin()const noexcept{
return const_reverse_iterator(this->end());
}
const_reverse_iterator crend()const noexcept{
return const_reverse_iterator(this->begin());
}
reverse_iterator rbegin()noexcept{
return reverse_iterator(this->end());
}
const_reverse_iterator rbegin()const noexcept{
return const_reverse_iterator(this->end());
}
reverse_iterator rend()noexcept{
return reverse_iterator(this->begin());
}
const_reverse_iterator rend()const noexcept{
return const_reverse_iterator(this->begin());
}
pointer data()noexcept{
return this->buf;
}
const_pointer data()const noexcept{
return this->buf;
}
/**
* @brief Checks if pointer points somewhere within the buffer.
* @param p - pointer to check.
* @return true - if pointer passed as argument points somewhere within the buffer.
* @return false otherwise.
*/
bool overlaps(const_pointer p)const noexcept{
return this->begin() <= p && p <= (this->end() - 1);
}
friend std::ostream& operator<<(std::ostream& s, const span<T>& buf){
for(auto& e : buf){
s << e;
}
return s;
}
};
template <class T> inline utki::span<T> make_span(nullptr_t){
return utki::span<T>(nullptr);
}
template <class T> inline utki::span<T> make_span(T* buf, size_t size){
return utki::span<T>(buf, size);
}
template <class T> inline const utki::span<T> make_span(const T* buf, size_t size){
return utki::span<T>(const_cast<T*>(buf), size);
}
template <class T, std::size_t array_size> inline utki::span<T> make_span(std::array<T, array_size>& a){
return make_span(a.size() == 0 ? nullptr : &*a.begin(), a.size());
}
template <class T, std::size_t array_size> inline const utki::span<T> make_span(const std::array<T, array_size>& a){
return make_span(a.size() == 0 ? nullptr : &*a.begin(), a.size());
}
template <class T> inline utki::span<T> make_span(std::vector<T>& v){
return make_span(v.size() == 0 ? nullptr : &*v.begin(), v.size());
}
template <class T> inline const utki::span<T> make_span(const std::vector<T>& v){
return make_span(v.size() == 0 ? nullptr : &*v.begin(), v.size());
}
inline std::string to_string(const utki::span<char>& buf){
return std::string(buf.data(), buf.size());
}
}
<commit_msg>build fix<commit_after>#pragma once
#include <array>
#include <vector>
#include <ostream>
#ifdef DEBUG
# include <iostream>
#endif
#include "util.hpp"
#include "debug.hpp"
namespace utki{
// TODO: remove when C++'20 becomes very common.
/**
* @brief span template class.
* This class is a wrapper of continuous memory buffer, it encapsulates pointer to memory block and size of that memory block.
* It does not own the memory.
* This is a replacement of std::span when C++'20 is not available.
*/
template <class T> class span final{
public:
typedef T value_type;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef value_type* iterator;
typedef const value_type* const_iterator;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
private:
pointer buf = nullptr;
size_type bufSize = 0;
public:
span(const span&) = default;
span& operator=(const span&) = default;
/**
* @brief Create a span object.
* Creates a span object which wraps given memory buffer of specified size.
* Note, the memory will not be freed upon this Buffer object destruction,
* Buffer does not own the memory.
* @param bufPtr - pointer to the memory buffer.
* @param bufSize - size of the memory buffer.
*/
span(pointer bufPtr, size_type bufSize)noexcept :
buf(bufPtr),
bufSize(bufSize)
{}
span()noexcept{}
/**
* @brief Constructor for automatic conversion from nullptr.
* @param bufPtr - pointer to the memory buffer. Makes not much sense, because size is 0 anyway.
*/
span(std::nullptr_t)noexcept :
buf(nullptr),
bufSize(0)
{}
/**
* @brief get buffer size.
* @return number of elements in buffer.
*/
size_type size()const noexcept{
return this->bufSize;
}
bool empty()const noexcept{
return this->size() == 0;
}
/**
* @brief get size of buffer in bytes.
* @return size of array in bytes.
*/
size_type size_bytes()const noexcept{
return this->size() * sizeof(value_type);
}
//TODO: deprecated, remove.
size_type sizeInBytes()const noexcept{
return this->size_bytes();
}
/**
* @brief access specified element of the buffer.
* Const version of Buffer::operator[].
* @param i - element index.
* @return reference to i'th element of the buffer.
*/
const_reference operator[](size_type i)const noexcept{
ASSERT(i < this->size())
return this->buf[i];
}
/**
* @brief access specified element of the buffer.
* @param i - element index.
* @return reference to i'th element of the buffer.
*/
reference operator[](size_type i)noexcept{
ASSERT_INFO(i < this->size(), "operator[]: index out of bounds")
return this->buf[i];
}
/**
* @brief get pointer to first element of the buffer.
* @return pointer to first element of the buffer.
*/
iterator begin()noexcept{
return this->buf;
}
/**
* @brief get pointer to first element of the buffer.
* @return pointer to first element of the buffer.
*/
const_iterator begin()const noexcept{
return this->cbegin();
}
const_iterator cbegin()const noexcept{
return this->buf;
}
/**
* @brief get pointer to "after last" element of the buffer.
* @return pointer to "after last" element of the buffer.
*/
iterator end()noexcept{
return this->buf + this->bufSize;
}
/**
* @brief get const pointer to "after last" element of the buffer.
* @return const pointer to "after last" element of the buffer.
*/
const_iterator end()const noexcept{
return this->cend();
}
const_iterator cend()const noexcept{
return this->buf + this->bufSize;
}
const_reverse_iterator crbegin()const noexcept{
return const_reverse_iterator(this->end());
}
const_reverse_iterator crend()const noexcept{
return const_reverse_iterator(this->begin());
}
reverse_iterator rbegin()noexcept{
return reverse_iterator(this->end());
}
const_reverse_iterator rbegin()const noexcept{
return const_reverse_iterator(this->end());
}
reverse_iterator rend()noexcept{
return reverse_iterator(this->begin());
}
const_reverse_iterator rend()const noexcept{
return const_reverse_iterator(this->begin());
}
pointer data()noexcept{
return this->buf;
}
const_pointer data()const noexcept{
return this->buf;
}
/**
* @brief Checks if pointer points somewhere within the buffer.
* @param p - pointer to check.
* @return true - if pointer passed as argument points somewhere within the buffer.
* @return false otherwise.
*/
bool overlaps(const_pointer p)const noexcept{
return this->begin() <= p && p <= (this->end() - 1);
}
friend std::ostream& operator<<(std::ostream& s, const span<T>& buf){
for(auto& e : buf){
s << e;
}
return s;
}
};
template <class T> inline utki::span<T> make_span(nullptr_t){
return utki::span<T>(nullptr);
}
template <class T> inline utki::span<T> make_span(T* buf, size_t size){
return utki::span<T>(buf, size);
}
template <class T> inline const utki::span<T> make_span(const T* buf, size_t size){
return utki::span<T>(const_cast<T*>(buf), size);
}
template <class T, std::size_t array_size> inline utki::span<T> make_span(std::array<T, array_size>& a){
return make_span(a.size() == 0 ? nullptr : &*a.begin(), a.size());
}
template <class T, std::size_t array_size> inline const utki::span<T> make_span(const std::array<T, array_size>& a){
return make_span(a.size() == 0 ? nullptr : &*a.begin(), a.size());
}
template <class T> inline utki::span<T> make_span(std::vector<T>& v){
return make_span(v.size() == 0 ? nullptr : &*v.begin(), v.size());
}
template <class T> inline const utki::span<T> make_span(const std::vector<T>& v){
return make_span(v.size() == 0 ? nullptr : &*v.begin(), v.size());
}
inline std::string to_string(const utki::span<char>& buf){
return std::string(buf.data(), buf.size());
}
}
<|endoftext|> |
<commit_before>// operations with variables
#include <iostream>
int main()
{
// declaring variables
int a, b;
int result;
// process
a = 5;
b = 2;
a = a + 1;
result = a - b;
// print the result
std::cout << result << std::endl;
// terminate the program
return 0;
}
<commit_msg>add few more manipulations on variables<commit_after>// operations with variables
#include <iostream>
#include <string>
int main()
{
// declaring variables
int a = 0; // c-like initialization
int b (0); // constructor initialization
int result {0}; // uniform initialization
int foo (0);
auto bar (foo); // compiler will determine bar's type
decltype(foo) baar;
decltype(foo) baar2 (5);
// simulate use
(void)bar;
(void)baar;
// actual use
std::cout << baar2 << std::endl;
// process
a = 5;
b = 2;
a = a + 1;
result = a - b;
// print the result
std::cout << result << std::endl;
// using strings
std::string oneString ("So this is what a string looks like");
std::cout << oneString << std::endl;
// terminate the program
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chainparams.h>
#include <fs.h>
#include <logging.h>
#include <wallet/db.h>
#include <string>
std::vector<fs::path> ListDatabases(const fs::path& wallet_dir)
{
const size_t offset = wallet_dir.string().size() + 1;
std::vector<fs::path> paths;
boost::system::error_code ec;
for (auto it = fs::recursive_directory_iterator(wallet_dir, ec); it != fs::recursive_directory_iterator(); it.increment(ec)) {
if (ec) {
LogPrintf("%s: %s %s\n", __func__, ec.message(), it->path().string());
continue;
}
try {
// Get wallet path relative to walletdir by removing walletdir from the wallet path.
// This can be replaced by boost::filesystem::lexically_relative once boost is bumped to 1.60.
const fs::path path = it->path().string().substr(offset);
if (it->status().type() == fs::directory_file &&
(IsBDBFile(BDBDataFile(it->path())) || IsSQLiteFile(SQLiteDataFile(it->path())))) {
// Found a directory which contains wallet.dat btree file, add it as a wallet.
paths.emplace_back(path);
} else if (it.level() == 0 && it->symlink_status().type() == fs::regular_file && IsBDBFile(it->path())) {
if (it->path().filename() == "wallet.dat") {
// Found top-level wallet.dat btree file, add top level directory ""
// as a wallet.
paths.emplace_back();
} else {
// Found top-level btree file not called wallet.dat. Current bitcoin
// software will never create these files but will allow them to be
// opened in a shared database environment for backwards compatibility.
// Add it to the list of available wallets.
paths.emplace_back(path);
}
}
} catch (const std::exception& e) {
LogPrintf("%s: Error scanning %s: %s\n", __func__, it->path().string(), e.what());
it.no_push();
}
}
return paths;
}
fs::path BDBDataFile(const fs::path& wallet_path)
{
if (fs::is_regular_file(wallet_path)) {
// Special case for backwards compatibility: if wallet path points to an
// existing file, treat it as the path to a BDB data file in a parent
// directory that also contains BDB log files.
return wallet_path;
} else {
// Normal case: Interpret wallet path as a directory path containing
// data and log files.
return wallet_path / "wallet.dat";
}
}
fs::path SQLiteDataFile(const fs::path& path)
{
return path / "wallet.dat";
}
bool IsBDBFile(const fs::path& path)
{
if (!fs::exists(path)) return false;
// A Berkeley DB Btree file has at least 4K.
// This check also prevents opening lock files.
boost::system::error_code ec;
auto size = fs::file_size(path, ec);
if (ec) LogPrintf("%s: %s %s\n", __func__, ec.message(), path.string());
if (size < 4096) return false;
fsbridge::ifstream file(path, std::ios::binary);
if (!file.is_open()) return false;
file.seekg(12, std::ios::beg); // Magic bytes start at offset 12
uint32_t data = 0;
file.read((char*) &data, sizeof(data)); // Read 4 bytes of file to compare against magic
// Berkeley DB Btree magic bytes, from:
// https://github.com/file/file/blob/5824af38469ec1ca9ac3ffd251e7afe9dc11e227/magic/Magdir/database#L74-L75
// - big endian systems - 00 05 31 62
// - little endian systems - 62 31 05 00
return data == 0x00053162 || data == 0x62310500;
}
bool IsSQLiteFile(const fs::path& path)
{
if (!fs::exists(path)) return false;
// A SQLite Database file is at least 512 bytes.
boost::system::error_code ec;
auto size = fs::file_size(path, ec);
if (ec) LogPrintf("%s: %s %s\n", __func__, ec.message(), path.string());
if (size < 512) return false;
fsbridge::ifstream file(path, std::ios::binary);
if (!file.is_open()) return false;
// Magic is at beginning and is 16 bytes long
char magic[16];
file.read(magic, 16);
// Application id is at offset 68 and 4 bytes long
file.seekg(68, std::ios::beg);
char app_id[4];
file.read(app_id, 4);
file.close();
// Check the magic, see https://sqlite.org/fileformat2.html
std::string magic_str(magic, 16);
if (magic_str != std::string("SQLite format 3", 16)) {
return false;
}
// Check the application id matches our network magic
return memcmp(Params().MessageStart(), app_id, 4) == 0;
}
<commit_msg>wallet: Do not iterate a directory if having an error while accessing it<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chainparams.h>
#include <fs.h>
#include <logging.h>
#include <wallet/db.h>
#include <string>
std::vector<fs::path> ListDatabases(const fs::path& wallet_dir)
{
const size_t offset = wallet_dir.string().size() + 1;
std::vector<fs::path> paths;
boost::system::error_code ec;
for (auto it = fs::recursive_directory_iterator(wallet_dir, ec); it != fs::recursive_directory_iterator(); it.increment(ec)) {
if (ec) {
if (fs::is_directory(*it)) {
it.no_push();
LogPrintf("%s: %s %s -- skipping.\n", __func__, ec.message(), it->path().string());
} else {
LogPrintf("%s: %s %s\n", __func__, ec.message(), it->path().string());
}
continue;
}
try {
// Get wallet path relative to walletdir by removing walletdir from the wallet path.
// This can be replaced by boost::filesystem::lexically_relative once boost is bumped to 1.60.
const fs::path path = it->path().string().substr(offset);
if (it->status().type() == fs::directory_file &&
(IsBDBFile(BDBDataFile(it->path())) || IsSQLiteFile(SQLiteDataFile(it->path())))) {
// Found a directory which contains wallet.dat btree file, add it as a wallet.
paths.emplace_back(path);
} else if (it.level() == 0 && it->symlink_status().type() == fs::regular_file && IsBDBFile(it->path())) {
if (it->path().filename() == "wallet.dat") {
// Found top-level wallet.dat btree file, add top level directory ""
// as a wallet.
paths.emplace_back();
} else {
// Found top-level btree file not called wallet.dat. Current bitcoin
// software will never create these files but will allow them to be
// opened in a shared database environment for backwards compatibility.
// Add it to the list of available wallets.
paths.emplace_back(path);
}
}
} catch (const std::exception& e) {
LogPrintf("%s: Error scanning %s: %s\n", __func__, it->path().string(), e.what());
it.no_push();
}
}
return paths;
}
fs::path BDBDataFile(const fs::path& wallet_path)
{
if (fs::is_regular_file(wallet_path)) {
// Special case for backwards compatibility: if wallet path points to an
// existing file, treat it as the path to a BDB data file in a parent
// directory that also contains BDB log files.
return wallet_path;
} else {
// Normal case: Interpret wallet path as a directory path containing
// data and log files.
return wallet_path / "wallet.dat";
}
}
fs::path SQLiteDataFile(const fs::path& path)
{
return path / "wallet.dat";
}
bool IsBDBFile(const fs::path& path)
{
if (!fs::exists(path)) return false;
// A Berkeley DB Btree file has at least 4K.
// This check also prevents opening lock files.
boost::system::error_code ec;
auto size = fs::file_size(path, ec);
if (ec) LogPrintf("%s: %s %s\n", __func__, ec.message(), path.string());
if (size < 4096) return false;
fsbridge::ifstream file(path, std::ios::binary);
if (!file.is_open()) return false;
file.seekg(12, std::ios::beg); // Magic bytes start at offset 12
uint32_t data = 0;
file.read((char*) &data, sizeof(data)); // Read 4 bytes of file to compare against magic
// Berkeley DB Btree magic bytes, from:
// https://github.com/file/file/blob/5824af38469ec1ca9ac3ffd251e7afe9dc11e227/magic/Magdir/database#L74-L75
// - big endian systems - 00 05 31 62
// - little endian systems - 62 31 05 00
return data == 0x00053162 || data == 0x62310500;
}
bool IsSQLiteFile(const fs::path& path)
{
if (!fs::exists(path)) return false;
// A SQLite Database file is at least 512 bytes.
boost::system::error_code ec;
auto size = fs::file_size(path, ec);
if (ec) LogPrintf("%s: %s %s\n", __func__, ec.message(), path.string());
if (size < 512) return false;
fsbridge::ifstream file(path, std::ios::binary);
if (!file.is_open()) return false;
// Magic is at beginning and is 16 bytes long
char magic[16];
file.read(magic, 16);
// Application id is at offset 68 and 4 bytes long
file.seekg(68, std::ios::beg);
char app_id[4];
file.read(app_id, 4);
file.close();
// Check the magic, see https://sqlite.org/fileformat2.html
std::string magic_str(magic, 16);
if (magic_str != std::string("SQLite format 3", 16)) {
return false;
}
// Check the application id matches our network magic
return memcmp(Params().MessageStart(), app_id, 4) == 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2017-present Facebook, Inc.
*
* 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 <folly/Benchmark.h>
#include <thrift/lib/cpp/transport/TBufferTransports.h>
#include <thrift/lib/cpp/protocol/TBinaryProtocol.h>
#include <thrift/lib/cpp/protocol/THeaderProtocol.h>
#include <thrift/test/gen-cpp/DebugProtoTest_types.h>
#include <gflags/gflags.h>
using namespace boost;
using namespace apache::thrift::transport;
using namespace apache::thrift::protocol;
using namespace thrift::test::debug;
/** An adaptor class that maps the Duplex THeaderProtocolFactory back to a
* TProtocolFactory
*/
class TSingleHeaderProtocolFactory : public TProtocolFactory {
public:
TSingleHeaderProtocolFactory() {}
~TSingleHeaderProtocolFactory() override {}
std::shared_ptr<TProtocol> getProtocol(
std::shared_ptr<TTransport> trans) override {
TProtocolPair protocols = factory_.getProtocol(trans);
return protocols.first;
}
private:
THeaderProtocolFactory factory_;
};
template <class Protocol_>
void WriteOneOfEach(TProtocolFactory& prot_factory, int iters) {
OneOfEach ooe;
ooe.im_true = true;
ooe.im_false = false;
ooe.a_bite = 0xd6;
ooe.integer16 = 27000;
ooe.integer32 = 1<<24;
ooe.integer64 = (uint64_t)6000 * 1000 * 1000;
ooe.double_precision = M_PI;
ooe.some_characters = "JSON THIS! \"\1";
ooe.zomg_unicode = "\xd7\n\a\t";
ooe.base64 = "\1\2\3\255";
ooe.string_string_map["one"] = "two";
ooe.string_string_hash_map["three"] = "four";
ooe.float_precision = (float)12.345;
ooe.rank_map[567419810] = (float)0.211184;
ooe.rank_map[507959914] = (float)0.080382;
std::shared_ptr<TMemoryBuffer> buf(new TMemoryBuffer());
std::shared_ptr<TProtocol> generic_prot(prot_factory.getProtocol(buf));
Protocol_* prot = dynamic_cast<Protocol_*>(generic_prot.get());
if (!prot) {
abort();
}
for (int i = 0; i < iters; ++i) {
buf->resetBuffer();
ooe.write(prot);
prot->getTransport()->flush();
}
}
template <class Protocol_>
void ReadOneOfEach(TProtocolFactory& prot_factory, int iters) {
OneOfEach ooe;
ooe.im_true = true;
ooe.im_false = false;
ooe.a_bite = 0xd6;
ooe.integer16 = 27000;
ooe.integer32 = 1<<24;
ooe.integer64 = (uint64_t)6000 * 1000 * 1000;
ooe.double_precision = M_PI;
ooe.some_characters = "JSON THIS! \"\1";
ooe.zomg_unicode = "\xd7\n\a\t";
ooe.base64 = "\1\2\3\255";
ooe.string_string_map["one"] = "two";
ooe.string_string_hash_map["three"] = "four";
ooe.float_precision = (float)12.345;
ooe.rank_map[567419810] = (float)0.211184;
ooe.rank_map[507959914] = (float)0.080382;
std::shared_ptr<TMemoryBuffer> rbuf(new TMemoryBuffer());
std::shared_ptr<TMemoryBuffer> wbuf(new TMemoryBuffer());
std::shared_ptr<TProtocol> generic_iprot(prot_factory.getProtocol(rbuf));
std::shared_ptr<TProtocol> generic_oprot(prot_factory.getProtocol(wbuf));
Protocol_* iprot = dynamic_cast<Protocol_*>(generic_iprot.get());
Protocol_* oprot = dynamic_cast<Protocol_*>(generic_oprot.get());
if (!iprot || !oprot) {
abort();
}
ooe.write(oprot);
oprot->getTransport()->flush();
uint8_t* data;
uint32_t datasize;
wbuf->getBuffer(&data, &datasize);
// Don't construct a new OneOfEach object each time around the loop.
// The vector insert operations in the constructor take up a significant
// fraction of the time.
OneOfEach ooe2;
for (int i = 0; i < iters; ++i) {
rbuf->resetBuffer(data, datasize);
ooe2.read(iprot);
}
}
BENCHMARK(BM_WriteFullyTemplatized, iters) {
// Test with TBinaryProtocolT<TBufferBase>,
// and OneOfEach.write< TBinaryProtocolT<TBufferBase> >
TBinaryProtocolFactoryT<TBufferBase> prot_factory;
WriteOneOfEach< TBinaryProtocolT<TBufferBase> >(prot_factory, iters);
}
BENCHMARK(BM_WriteTransportTemplatized, iters) {
// Test with TBinaryProtocolT<TBufferBase>,
// but OneOfEach.write<TProtocol>
TBinaryProtocolFactoryT<TBufferBase> prot_factory;
WriteOneOfEach<TProtocol>(prot_factory, iters);
}
BENCHMARK(BM_WriteProtocolTemplatized, iters) {
// Test with TBinaryProtocol and OneOfEach.write<TBinaryProtocol>
TBinaryProtocolFactory prot_factory;
WriteOneOfEach<TBinaryProtocol>(prot_factory, iters);
}
BENCHMARK(BM_WriteGeneric, iters) {
// Test with TBinaryProtocol and OneOfEach.write<TProtocol>
TBinaryProtocolFactory prot_factory;
WriteOneOfEach<TProtocol>(prot_factory, iters);
}
BENCHMARK(BM_WriteHeaderGeneric, iters) {
// Test with TBinaryProtocol and OneOfEach.write<TProtocol>
TSingleHeaderProtocolFactory prot_factory;
WriteOneOfEach<THeaderProtocol>(prot_factory, iters);
}
BENCHMARK(BM_ReadFullyTemplatized, iters) {
// Test with TBinaryProtocolT<TBufferBase>,
// and OneOfEach.write< TBinaryProtocolT<TBufferBase> >
TBinaryProtocolFactoryT<TBufferBase> prot_factory;
ReadOneOfEach< TBinaryProtocolT<TBufferBase> >(prot_factory, iters);
}
BENCHMARK(BM_ReadTransportTemplatized, iters) {
// Test with TBinaryProtocolT<TBufferBase>,
// but OneOfEach.write<TProtocol>
TBinaryProtocolFactoryT<TBufferBase> prot_factory;
ReadOneOfEach<TProtocol>(prot_factory, iters);
}
BENCHMARK(BM_ReadProtocolTemplatized, iters) {
// Test with TBinaryProtocol and OneOfEach.write<TBinaryProtocol>
TBinaryProtocolFactory prot_factory;
ReadOneOfEach<TBinaryProtocol>(prot_factory, iters);
}
BENCHMARK(BM_ReadGeneric, iters) {
// Test with TBinaryProtocolT<TTransport> and OneOfEach.write<TProtocol>
TBinaryProtocolFactory prot_factory;
ReadOneOfEach<TProtocol>(prot_factory, iters);
}
BENCHMARK(BM_ReadHeaderGeneric, iters) {
// Test with TBinaryProtocolT<TTransport> and OneOfEach.write<TProtocol>
TSingleHeaderProtocolFactory prot_factory;
ReadOneOfEach<THeaderProtocol>(prot_factory, iters);
}
int main(int argc, char** argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
// Run the benchmarks
folly::runBenchmarksOnFlag();
return 0;
}
<commit_msg>Cut dead/legacy thrift/test/FbBenchmark.cpp<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2008-2013 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrust/detail/config.h>
#include <thrust/detail/reference.h>
#include <thrust/detail/type_traits.h>
#include <thrust/iterator/iterator_traits.h>
#include <thrust/system/detail/generic/select_system.h>
#include <thrust/system/detail/generic/memory.h>
#include <thrust/system/detail/adl/get_value.h>
#include <thrust/system/detail/adl/assign_value.h>
#include <thrust/system/detail/adl/iter_swap.h>
namespace thrust
{
template<typename Element, typename Pointer, typename Derived>
template<typename OtherElement, typename OtherPointer, typename OtherDerived>
__host__ __device__
reference<Element,Pointer,Derived>
::reference(const reference<OtherElement,OtherPointer,OtherDerived> &other,
typename thrust::detail::enable_if_convertible<
typename reference<OtherElement,OtherPointer,OtherDerived>::pointer,
pointer
>::type *)
: m_ptr(other.m_ptr)
{}
template<typename Element, typename Pointer, typename Derived>
__host__ __device__
reference<Element,Pointer,Derived>
::reference(const pointer &ptr)
: m_ptr(ptr)
{}
template<typename Element, typename Pointer, typename Derived>
__host__ __device__
typename reference<Element,Pointer,Derived>::pointer
reference<Element,Pointer,Derived>
::operator&() const
{
return m_ptr;
} // end reference::operator&()
template<typename Element, typename Pointer, typename Derived>
__host__ __device__
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator=(const value_type &v)
{
assign_from(&v);
return static_cast<derived_type&>(*this);
} // end reference::operator=()
template<typename Element, typename Pointer, typename Derived>
__host__ __device__
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator=(const reference &other)
{
assign_from(&other);
return static_cast<derived_type&>(*this);
} // end reference::operator=()
template<typename Element, typename Pointer, typename Derived>
template<typename OtherElement, typename OtherPointer, typename OtherDerived>
__host__ __device__
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator=(const reference<OtherElement,OtherPointer,OtherDerived> &other)
{
assign_from(&other);
return static_cast<derived_type&>(*this);
} // end reference::operator=()
template<typename Element, typename Pointer, typename Derived>
template<typename System>
typename reference<Element,Pointer,Derived>::value_type
reference<Element,Pointer,Derived>
::convert_to_value_type(System *system) const
{
using thrust::system::detail::generic::select_system;
return strip_const_get_value(select_system(*system));
} // end convert_to_value_type()
template<typename Element, typename Pointer, typename Derived>
__host__ __device__
reference<Element,Pointer,Derived>
::operator typename reference<Element,Pointer,Derived>::value_type () const
{
typedef typename thrust::iterator_system<pointer>::type System;
// XXX avoid default-constructing a system
// XXX use null a reference for dispatching
// XXX this assumes that the eventual invocation of
// XXX get_value will not access system state
System *system = 0;
return convert_to_value_type(system);
} // end reference::operator value_type ()
template<typename Element, typename Pointer, typename Derived>
template<typename System>
__host__ __device__
typename reference<Element,Pointer,Derived>::value_type
reference<Element,Pointer,Derived>
::strip_const_get_value(const System &system) const
{
System &non_const_system = const_cast<System&>(system);
using thrust::system::detail::generic::get_value;
return get_value(thrust::detail::derived_cast(non_const_system), m_ptr);
} // end reference::strip_const_get_value()
template<typename Element, typename Pointer, typename Derived>
template<typename System1, typename System2, typename OtherPointer>
void reference<Element,Pointer,Derived>
::assign_from(System1 *system1, System2 *system2, OtherPointer src)
{
using thrust::system::detail::generic::select_system;
strip_const_assign_value(select_system(*system1, *system2), src);
} // end assign_from()
template<typename Element, typename Pointer, typename Derived>
template<typename OtherPointer>
__host__ __device__
void reference<Element,Pointer,Derived>
::assign_from(OtherPointer src)
{
typedef typename thrust::iterator_system<pointer>::type System1;
typedef typename thrust::iterator_system<OtherPointer>::type System2;
// XXX avoid default-constructing a system
// XXX use null references for dispatching
// XXX this assumes that the eventual invocation of
// XXX assign_value will not access system state
System1 *system1 = 0;
System2 *system2 = 0;
assign_from(system1, system2, src);
} // end assign_from()
template<typename Element, typename Pointer, typename Derived>
template<typename System, typename OtherPointer>
__host__ __device__
void reference<Element,Pointer,Derived>
::strip_const_assign_value(const System &system, OtherPointer src)
{
System &non_const_system = const_cast<System&>(system);
using thrust::system::detail::generic::assign_value;
assign_value(thrust::detail::derived_cast(non_const_system), m_ptr, src);
} // end strip_const_assign_value()
template<typename Element, typename Pointer, typename Derived>
template<typename System>
void reference<Element,Pointer,Derived>
::swap(System *system, derived_type &other)
{
using thrust::system::detail::generic::select_system;
using thrust::system::detail::generic::iter_swap;
iter_swap(select_system(*system, *system), m_ptr, other.m_ptr);
} // end reference::swap()
template<typename Element, typename Pointer, typename Derived>
__host__ __device__
void reference<Element,Pointer,Derived>
::swap(derived_type &other)
{
typedef typename thrust::iterator_system<pointer>::type System;
// XXX avoid default-constructing a system
// XXX use null references for dispatching
// XXX this assumes that the eventual invocation
// XXX of iter_swap will not access system state
System *system = 0;
swap(system, other);
} // end reference::swap()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator++(void)
{
value_type temp = *this;
++temp;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator++()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::value_type
reference<Element,Pointer,Derived>
::operator++(int)
{
value_type temp = *this;
value_type result = temp++;
*this = temp;
return result;
} // end reference::operator++()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator+=(const value_type &rhs)
{
value_type temp = *this;
temp += rhs;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator+=()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator--(void)
{
value_type temp = *this;
--temp;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator--()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::value_type
reference<Element,Pointer,Derived>
::operator--(int)
{
value_type temp = *this;
value_type result = temp--;
*this = temp;
return result;
} // end reference::operator--()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator-=(const value_type &rhs)
{
value_type temp = *this;
temp -= rhs;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator-=()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator*=(const value_type &rhs)
{
value_type temp = *this;
temp *= rhs;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator*=()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator/=(const value_type &rhs)
{
value_type temp = *this;
temp /= rhs;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator/=()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator%=(const value_type &rhs)
{
value_type temp = *this;
temp %= rhs;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator%=()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator<<=(const value_type &rhs)
{
value_type temp = *this;
temp <<= rhs;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator<<=()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator>>=(const value_type &rhs)
{
value_type temp = *this;
temp >>= rhs;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator>>=()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator&=(const value_type &rhs)
{
value_type temp = *this;
temp &= rhs;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator&=()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator|=(const value_type &rhs)
{
value_type temp = *this;
temp |= rhs;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator|=()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator^=(const value_type &rhs)
{
value_type temp = *this;
temp ^= rhs;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator^=()
template<typename Element, typename Pointer, typename Derived,
typename charT, typename traits>
std::basic_ostream<charT, traits> &
operator<<(std::basic_ostream<charT, traits> &os,
const reference<Element, Pointer, Derived> &y) {
typedef typename reference<Element, Pointer, Derived>::value_type value_type;
return os << static_cast<value_type>(y);
} // end operator<<()
} // end thrust
<commit_msg>Sync attributes of reference::assign_from definitions with their declarations.<commit_after>/*
* Copyright 2008-2013 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrust/detail/config.h>
#include <thrust/detail/reference.h>
#include <thrust/detail/type_traits.h>
#include <thrust/iterator/iterator_traits.h>
#include <thrust/system/detail/generic/select_system.h>
#include <thrust/system/detail/generic/memory.h>
#include <thrust/system/detail/adl/get_value.h>
#include <thrust/system/detail/adl/assign_value.h>
#include <thrust/system/detail/adl/iter_swap.h>
namespace thrust
{
template<typename Element, typename Pointer, typename Derived>
template<typename OtherElement, typename OtherPointer, typename OtherDerived>
__host__ __device__
reference<Element,Pointer,Derived>
::reference(const reference<OtherElement,OtherPointer,OtherDerived> &other,
typename thrust::detail::enable_if_convertible<
typename reference<OtherElement,OtherPointer,OtherDerived>::pointer,
pointer
>::type *)
: m_ptr(other.m_ptr)
{}
template<typename Element, typename Pointer, typename Derived>
__host__ __device__
reference<Element,Pointer,Derived>
::reference(const pointer &ptr)
: m_ptr(ptr)
{}
template<typename Element, typename Pointer, typename Derived>
__host__ __device__
typename reference<Element,Pointer,Derived>::pointer
reference<Element,Pointer,Derived>
::operator&() const
{
return m_ptr;
} // end reference::operator&()
template<typename Element, typename Pointer, typename Derived>
__host__ __device__
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator=(const value_type &v)
{
assign_from(&v);
return static_cast<derived_type&>(*this);
} // end reference::operator=()
template<typename Element, typename Pointer, typename Derived>
__host__ __device__
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator=(const reference &other)
{
assign_from(&other);
return static_cast<derived_type&>(*this);
} // end reference::operator=()
template<typename Element, typename Pointer, typename Derived>
template<typename OtherElement, typename OtherPointer, typename OtherDerived>
__host__ __device__
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator=(const reference<OtherElement,OtherPointer,OtherDerived> &other)
{
assign_from(&other);
return static_cast<derived_type&>(*this);
} // end reference::operator=()
template<typename Element, typename Pointer, typename Derived>
template<typename System>
__host__ __device__
typename reference<Element,Pointer,Derived>::value_type
reference<Element,Pointer,Derived>
::convert_to_value_type(System *system) const
{
using thrust::system::detail::generic::select_system;
return strip_const_get_value(select_system(*system));
} // end convert_to_value_type()
template<typename Element, typename Pointer, typename Derived>
__host__ __device__
reference<Element,Pointer,Derived>
::operator typename reference<Element,Pointer,Derived>::value_type () const
{
typedef typename thrust::iterator_system<pointer>::type System;
// XXX avoid default-constructing a system
// XXX use null a reference for dispatching
// XXX this assumes that the eventual invocation of
// XXX get_value will not access system state
System *system = 0;
return convert_to_value_type(system);
} // end reference::operator value_type ()
template<typename Element, typename Pointer, typename Derived>
template<typename System>
__host__ __device__
typename reference<Element,Pointer,Derived>::value_type
reference<Element,Pointer,Derived>
::strip_const_get_value(const System &system) const
{
System &non_const_system = const_cast<System&>(system);
using thrust::system::detail::generic::get_value;
return get_value(thrust::detail::derived_cast(non_const_system), m_ptr);
} // end reference::strip_const_get_value()
template<typename Element, typename Pointer, typename Derived>
template<typename System1, typename System2, typename OtherPointer>
__host__ __device__
void reference<Element,Pointer,Derived>
::assign_from(System1 *system1, System2 *system2, OtherPointer src)
{
using thrust::system::detail::generic::select_system;
strip_const_assign_value(select_system(*system1, *system2), src);
} // end assign_from()
template<typename Element, typename Pointer, typename Derived>
template<typename OtherPointer>
__host__ __device__
void reference<Element,Pointer,Derived>
::assign_from(OtherPointer src)
{
typedef typename thrust::iterator_system<pointer>::type System1;
typedef typename thrust::iterator_system<OtherPointer>::type System2;
// XXX avoid default-constructing a system
// XXX use null references for dispatching
// XXX this assumes that the eventual invocation of
// XXX assign_value will not access system state
System1 *system1 = 0;
System2 *system2 = 0;
assign_from(system1, system2, src);
} // end assign_from()
template<typename Element, typename Pointer, typename Derived>
template<typename System, typename OtherPointer>
__host__ __device__
void reference<Element,Pointer,Derived>
::strip_const_assign_value(const System &system, OtherPointer src)
{
System &non_const_system = const_cast<System&>(system);
using thrust::system::detail::generic::assign_value;
assign_value(thrust::detail::derived_cast(non_const_system), m_ptr, src);
} // end strip_const_assign_value()
template<typename Element, typename Pointer, typename Derived>
template<typename System>
void reference<Element,Pointer,Derived>
::swap(System *system, derived_type &other)
{
using thrust::system::detail::generic::select_system;
using thrust::system::detail::generic::iter_swap;
iter_swap(select_system(*system, *system), m_ptr, other.m_ptr);
} // end reference::swap()
template<typename Element, typename Pointer, typename Derived>
__host__ __device__
void reference<Element,Pointer,Derived>
::swap(derived_type &other)
{
typedef typename thrust::iterator_system<pointer>::type System;
// XXX avoid default-constructing a system
// XXX use null references for dispatching
// XXX this assumes that the eventual invocation
// XXX of iter_swap will not access system state
System *system = 0;
swap(system, other);
} // end reference::swap()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator++(void)
{
value_type temp = *this;
++temp;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator++()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::value_type
reference<Element,Pointer,Derived>
::operator++(int)
{
value_type temp = *this;
value_type result = temp++;
*this = temp;
return result;
} // end reference::operator++()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator+=(const value_type &rhs)
{
value_type temp = *this;
temp += rhs;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator+=()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator--(void)
{
value_type temp = *this;
--temp;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator--()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::value_type
reference<Element,Pointer,Derived>
::operator--(int)
{
value_type temp = *this;
value_type result = temp--;
*this = temp;
return result;
} // end reference::operator--()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator-=(const value_type &rhs)
{
value_type temp = *this;
temp -= rhs;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator-=()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator*=(const value_type &rhs)
{
value_type temp = *this;
temp *= rhs;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator*=()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator/=(const value_type &rhs)
{
value_type temp = *this;
temp /= rhs;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator/=()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator%=(const value_type &rhs)
{
value_type temp = *this;
temp %= rhs;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator%=()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator<<=(const value_type &rhs)
{
value_type temp = *this;
temp <<= rhs;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator<<=()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator>>=(const value_type &rhs)
{
value_type temp = *this;
temp >>= rhs;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator>>=()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator&=(const value_type &rhs)
{
value_type temp = *this;
temp &= rhs;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator&=()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator|=(const value_type &rhs)
{
value_type temp = *this;
temp |= rhs;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator|=()
template<typename Element, typename Pointer, typename Derived>
typename reference<Element,Pointer,Derived>::derived_type &
reference<Element,Pointer,Derived>
::operator^=(const value_type &rhs)
{
value_type temp = *this;
temp ^= rhs;
*this = temp;
return static_cast<derived_type&>(*this);
} // end reference::operator^=()
template<typename Element, typename Pointer, typename Derived,
typename charT, typename traits>
std::basic_ostream<charT, traits> &
operator<<(std::basic_ostream<charT, traits> &os,
const reference<Element, Pointer, Derived> &y) {
typedef typename reference<Element, Pointer, Derived>::value_type value_type;
return os << static_cast<value_type>(y);
} // end operator<<()
} // end thrust
<|endoftext|> |
<commit_before>/*
* CandidateHeap.cpp
*
* Created on: Mar 27, 2016
* Author: michel
*/
#include "CandidateHeap.hpp"
CandidateHeap::CandidateHeap(std::string dir, int* activeIJs, int kPrime, TreeBuilderExtMem *tb, long sizeExp) : ArrayHeapExtMem(dir,activeIJs,sizeExp){
initialize( kPrime, tb);
}
CandidateHeap::CandidateHeap(std::string dir, int* activeIJs, int kPrime, TreeBuilderExtMem *tb) : ArrayHeapExtMem(dir,activeIJs){
initialize( kPrime, tb);
}
CandidateHeap::~CandidateHeap(){
clear();
}
void CandidateHeap::initialize (int kPrime, TreeBuilderExtMem *tb) {
this->firstActiveNode = -1;
this->origSize = 0;
this->expired = false;
this->representedRowCount = 0;
this->tb = tb;
this->kPrime = kPrime;
rowCounts = new int[tb->nextInternalNode+1]();
rDeltas = new float[tb->nextInternalNode+1];
nextActiveNode = new int[tb->nextInternalNode+1];
prevActiveNode = new int[tb->nextInternalNode+1];
rPrimes = new float[tb->RSize];
for (int i=0; i< tb->RSize; i++ ) {
rPrimes[i] = tb->R[i];
}
}
void CandidateHeap::insert(int i, int j, float key){
ArrayHeapExtMem::insert(i, j, key);
rowCounts[i]++;
rowCounts[j]++;
}
void CandidateHeap::buildNodeList () {
origSize = ArrayHeapExtMem::size();
int prev=-1;
for (int i=0; i<tb->nextInternalNode+1; i++) {
if (rowCounts[i] > 0) {
representedRowCount++;
if (firstActiveNode==-1) {
firstActiveNode = i;
} else {
prevActiveNode[i] = prev;
nextActiveNode[prev] = i;
}
prev = i;
}
}
prevActiveNode[0] = -1;
nextActiveNode[prev] = -1;
}
void CandidateHeap::removeMin(){
HeapReturn x = ArrayHeapExtMem::getBinaryHeapWithMin();
int i,j;
if(x.which){
BinaryHeap_FourInts* H = (BinaryHeap_FourInts*)x.h;
i = H->heap->front().first;
j = H->heap->front().second;
}else{
BinaryHeap_TwoInts* H = (BinaryHeap_TwoInts*)x.h;
i = H->heap->front().first;
j = H->heap->front().second;
}
int prev, next;
if (--rowCounts[i] == 0) { // compact list
representedRowCount--;
prev = prevActiveNode[i];
next = nextActiveNode[i];
if (next != -1) prevActiveNode[next] = prev;
if (prev != -1) nextActiveNode[prev] = next;
}
if (--rowCounts[j] == 0) { // compact list
representedRowCount--;
prev = prevActiveNode[j];
next = nextActiveNode[j];
if (next != -1) prevActiveNode[next] = prev;
if (prev != -1) nextActiveNode[prev] = next;
}
ArrayHeapExtMem::removeMin();
}
void CandidateHeap::calcDeltaValues (int newK) {
//prevActiveNode[0] = -1;
//nextActiveNode[0] = -1;
int x=firstActiveNode;
float minRdelt1, minRdelt2;
minRdelt1 = FLT_MAX;
minRdelt2 = FLT_MAX;
k_over_kprime = (float)(newK-2)/(kPrime-2);
int rx, prev, next;
while (x != -1) {
rx = tb->redirect[x];
if (rx == -1) {
prev = prevActiveNode[x];
next = nextActiveNode[x];
if (next != -1) prevActiveNode[next] = prev;
if (prev != -1) nextActiveNode[prev] = next;
x = next;
} else {
rDeltas[x] = k_over_kprime * rPrimes[rx] - tb->R[rx];
if (rDeltas[x] < minRdelt1) {
minRdelt2 = minRdelt1;
minRdelt1 = rDeltas[x];
} else if (rDeltas[x] < minRdelt2) {
minRdelt2 = rDeltas[x];
}
x = nextActiveNode[x];
}
}
minDeltaSum = minRdelt1 + minRdelt2;
}
void CandidateHeap::clear(){
//TODO: fix
ArrayHeapExtMem::deleteAll();
if (rPrimes!=NULL){
delete[] rPrimes;
rPrimes = NULL;
}
if (rDeltas!=NULL){
delete[] rDeltas;
rDeltas = NULL;
}
if (rowCounts!=NULL){
delete[] rowCounts;
rowCounts = NULL;
}
if (nextActiveNode!=NULL){
delete[] nextActiveNode;
nextActiveNode = NULL;
}
if (prevActiveNode!=NULL){
delete[] prevActiveNode;
prevActiveNode = NULL;
}
if (this->tb!=NULL){
delete this->tb;
tb = NULL;
}
}
<commit_msg>fixed infinite recursion bug<commit_after>/*
* CandidateHeap.cpp
*
* Created on: Mar 27, 2016
* Author: michel
*/
#include "CandidateHeap.hpp"
CandidateHeap::CandidateHeap(std::string dir, int* activeIJs, int kPrime, TreeBuilderExtMem *tb, long sizeExp) : ArrayHeapExtMem(dir,activeIJs,sizeExp){
initialize( kPrime, tb);
}
CandidateHeap::CandidateHeap(std::string dir, int* activeIJs, int kPrime, TreeBuilderExtMem *tb) : ArrayHeapExtMem(dir,activeIJs){
initialize( kPrime, tb);
}
CandidateHeap::~CandidateHeap(){
clear();
}
void CandidateHeap::initialize (int kPrime, TreeBuilderExtMem *tb) {
this->firstActiveNode = -1;
this->origSize = 0;
this->expired = false;
this->representedRowCount = 0;
this->tb = tb;
this->kPrime = kPrime;
rowCounts = new int[tb->nextInternalNode+1]();
rDeltas = new float[tb->nextInternalNode+1];
nextActiveNode = new int[tb->nextInternalNode+1];
prevActiveNode = new int[tb->nextInternalNode+1];
rPrimes = new float[tb->RSize];
for (int i=0; i< tb->RSize; i++ ) {
rPrimes[i] = tb->R[i];
}
}
void CandidateHeap::insert(int i, int j, float key){
ArrayHeapExtMem::insert(i, j, key);
rowCounts[i]++;
rowCounts[j]++;
}
void CandidateHeap::buildNodeList () {
origSize = ArrayHeapExtMem::size();
int prev=-1;
for (int i=0; i<tb->nextInternalNode+1; i++) {
if (rowCounts[i] > 0) {
representedRowCount++;
if (firstActiveNode==-1) {
firstActiveNode = i;
} else {
prevActiveNode[i] = prev;
nextActiveNode[prev] = i;
}
prev = i;
}
}
prevActiveNode[0] = -1;
nextActiveNode[prev] = -1;
}
void CandidateHeap::removeMin(){
HeapReturn x = ArrayHeapExtMem::getBinaryHeapWithMin();
int i,j;
if(x.which){
BinaryHeap_FourInts* H = (BinaryHeap_FourInts*)x.h;
i = H->heap->front().first;
j = H->heap->front().second;
}else{
BinaryHeap_TwoInts* H = (BinaryHeap_TwoInts*)x.h;
i = H->heap->front().first;
j = H->heap->front().second;
}
int prev, next;
if (--rowCounts[i] == 0) { // compact list
representedRowCount--;
prev = prevActiveNode[i];
next = nextActiveNode[i];
if (next != -1) prevActiveNode[next] = prev;
if (prev != -1) nextActiveNode[prev] = next;
}
if (--rowCounts[j] == 0) { // compact list
representedRowCount--;
prev = prevActiveNode[j];
next = nextActiveNode[j];
if (next != -1) prevActiveNode[next] = prev;
if (prev != -1) nextActiveNode[prev] = next;
}
ArrayHeapExtMem::removeMin();
}
void CandidateHeap::calcDeltaValues (int newK) {
//prevActiveNode[0] = -1;
//nextActiveNode[0] = -1;
int x=firstActiveNode;
float minRdelt1, minRdelt2;
minRdelt1 = FLT_MAX;
minRdelt2 = FLT_MAX;
k_over_kprime = (float)(newK-2)/(kPrime-2);
int rx, prev, next;
while (x != -1) {
rx = tb->redirect[x];
if (rx == -1) {
prev = prevActiveNode[x];
next = nextActiveNode[x];
if (next != -1) prevActiveNode[next] = prev;
if (prev != -1) nextActiveNode[prev] = next;
x = next;
} else {
rDeltas[x] = k_over_kprime * rPrimes[rx] - tb->R[rx];
if (rDeltas[x] < minRdelt1) {
minRdelt2 = minRdelt1;
minRdelt1 = rDeltas[x];
} else if (rDeltas[x] < minRdelt2) {
minRdelt2 = rDeltas[x];
}
x = nextActiveNode[x];
}
}
minDeltaSum = minRdelt1 + minRdelt2;
}
void CandidateHeap::clear(){
//TODO: fix
ArrayHeapExtMem::deleteAll();
if (rPrimes!=NULL){
delete[] rPrimes;
rPrimes = NULL;
}
if (rDeltas!=NULL){
delete[] rDeltas;
rDeltas = NULL;
}
if (rowCounts!=NULL){
delete[] rowCounts;
rowCounts = NULL;
}
if (nextActiveNode!=NULL){
delete[] nextActiveNode;
nextActiveNode = NULL;
}
if (prevActiveNode!=NULL){
delete[] prevActiveNode;
prevActiveNode = NULL;
}
/*
if (this->tb!=NULL){
delete this->tb;
tb = NULL;
}*/
}
<|endoftext|> |
<commit_before>/////
#include "Precompiled.h"
#include "GetOptInc.h"
#include "resource.h"
#include <Shellapi.h>
#include <Shlobj.h>
#include <Shlwapi.h>
#include <commctrl.h>
#if defined(_WIN32_WINNT_WIN8) && defined(_WIN32_WINNT) && \
_WIN32_WINNT >= _WIN32_WINNT_WIN8
#include <Processthreadsapi.h>
#endif
#include <strsafe.h>
#ifndef ASSERT
#ifdef _DEBUG
#include <assert.h>
#define ASSERT(x) assert(x)
#define ASSERT_HERE assert(FALSE)
#else // _DEBUG
#define ASSERT(x)
#endif //_DEBUG
#endif // ASSERT
#ifndef _tsizeof
#define _tsizeof(s) (sizeof(s) / sizeof(s[0]))
#endif //_tsizeof
#include <comdef.h>
#include <taskschd.h>
#define UNC_MAX_PATH (32 * 1024 - 1)
int OutErrorMessage(const wchar_t *errorMsg, const wchar_t *errorTitle);
void PrintVersion() {
int nButtonPressed = 0;
TaskDialog(NULL, GetModuleHandle(nullptr), L"Clangbuilder launcher",
L"Version Info: ", LAUNCHER_APP_VERSION, TDCBF_OK_BUTTON,
TD_INFORMATION_ICON, &nButtonPressed);
}
HRESULT CALLBACK TaskDialogCallbackProc(__in HWND hwnd, __in UINT msg,
__in WPARAM wParam, __in LPARAM lParam,
__in LONG_PTR lpRefData) {
UNREFERENCED_PARAMETER(lpRefData);
UNREFERENCED_PARAMETER(wParam);
switch (msg) {
case TDN_CREATED:
::SetForegroundWindow(hwnd);
break;
case TDN_RADIO_BUTTON_CLICKED:
break;
case TDN_BUTTON_CLICKED:
break;
case TDN_HYPERLINK_CLICKED:
ShellExecute(hwnd, NULL, (LPCTSTR)lParam, NULL, NULL, SW_SHOWNORMAL);
break;
}
return S_OK;
}
const wchar_t usageInfo[] =
L"OVERVIEW: Clangbuilder launcher utility\n"
L"\nOPTIONS:\n"
L"Usage: launcher [options| V:A:F:BEICRSLNH ] <input>\n"
L" -V\t[--vs] Visual Studio version \n\tAllow: 110| 120| 140| 141| "
L"150\n\n"
L" -A\t[--arch] LLVM Arch \n\tAllow: x86| x64| ARM| ARM64\n\n"
L" -F\t[--flavor] Flavor \n\tAllow: Debug| Release| MinSizeRel| "
L"RelWithDebInfo\n\n"
L" -B\t[--bootstrap] Bootstrap llvm\n"
L" -E\t[--env] Startup Environment not run builder\n"
L" -I\t[--install] Create Install Package\n"
L" -C\t[--clear] Clear Environment\n"
L" -R\t[--released] Build Last Released Revision\n"
L" -S\t[--static] Use Static C Runtime Library\n"
L" -L\t[--lldb] Build LLDB\n"
L" -N\t[--nmake] nmake\n"
L" -H\t[--help] Print Help Message";
void Usage() {
MessageBoxW(nullptr, usageInfo, L"Clangbuilder launcher Usage", MB_OK);
}
enum ClangBuilderChannel : int {
kOpenEnvironment = 0, ///
kUseMSBuild = 1,
kNinjaBootstrap
};
int LauncherStartup(const wchar_t *args, int channel) {
wchar_t pwszPath[UNC_MAX_PATH];
GetModuleFileNameW(nullptr, pwszPath, UNC_MAX_PATH);
PathRemoveFileSpecW(pwszPath);
PathRemoveFileSpecW(pwszPath);
PathRemoveFileSpecW(pwszPath);
std::wstring psfile = pwszPath;
switch (channel) {
case kOpenEnvironment:
psfile += L"\\bin\\ClangBuilderEnvironment.ps1";
break;
case kUseMSBuild:
psfile += L"\\bin\\ClangBuilderManager.ps1";
break;
case kNinjaBootstrap:
psfile += L"\\bin\\ClangBuilderBootstrap.ps1";
break;
default:
psfile = L"Not support channel value: " + std::to_wstring(channel);
OutErrorMessage(psfile.c_str(), L"Not support clangbuilder channel !");
return -2;
}
if (!PathFileExistsW(psfile.c_str())) {
OutErrorMessage(psfile.c_str(), L"PathFileExists return false");
return -1;
}
if (SHGetFolderPathW(NULL, CSIDL_SYSTEM, NULL, 0, pwszPath) != S_OK) {
return -1;
}
auto length = wcslen(pwszPath);
StringCchCatW(pwszPath, UNC_MAX_PATH - length,
L"\\WindowsPowerShell\\v1.0\\powershell.exe ");
length = wcslen(pwszPath);
auto offsetPtr = pwszPath + length;
StringCchPrintfW(offsetPtr, UNC_MAX_PATH - length,
L" -NoLogo -NoExit -File \"%s\" %s", psfile.c_str(), args);
PROCESS_INFORMATION pi;
STARTUPINFO si;
ZeroMemory(&si, sizeof(si));
ZeroMemory(&pi, sizeof(pi));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_SHOW;
if (CreateProcessW(nullptr, pwszPath, NULL, NULL, FALSE,
CREATE_NEW_CONSOLE | NORMAL_PRIORITY_CLASS, NULL, NULL,
&si, &pi)) {
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return 0;
}
return GetLastError();
}
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPWSTR lpCmdLine, int nCmdShow) {
UNREFERENCED_PARAMETER(hInstance);
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
UNREFERENCED_PARAMETER(nCmdShow);
const wchar_t *vs = nullptr;
const wchar_t *target = nullptr;
const wchar_t *flavor = nullptr;
bool createInstallPkg = false;
bool clearEnv = false;
bool useNmake = false;
bool buildReleasedRevision = false;
bool useStaticCRT = false;
bool buildLLDB = false;
int channel = kUseMSBuild;
int Argc = 0;
auto Argv_ = CommandLineToArgvW(GetCommandLineW(), &Argc);
wchar_t *const *Argv = Argv_;
int ch;
const wchar_t *short_opts = L"V:A:F:BEICRSLNH"; // L"V:T:C:BIERSLNH";
const option option_long_opt[] = {
///
{L"vs", required_argument, NULL, 'V'},
{L"arch", required_argument, NULL, 'A'},
{L"flavor", required_argument, NULL, 'F'},
{L"bootstrap", no_argument, NULL, 'B'},
{L"env", no_argument, NULL, 'E'},
{L"install", no_argument, NULL, 'I'},
{L"clear", no_argument, NULL, 'C'},
{L"released", no_argument, NULL, 'R'},
{L"static", no_argument, NULL, 'S'},
{L"lldb", no_argument, NULL, 'L'},
{L"nmake", no_argument, NULL, 'N'},
{L"help", no_argument, NULL, 'H'},
{0, 0, 0, 0}
///
};
while ((ch = getopt_long(Argc, Argv, short_opts, option_long_opt, NULL)) !=
-1) {
switch (ch) {
case 'V':
vs = optarg;
break;
case 'A':
target = optarg;
break;
case 'F':
flavor = optarg;
break;
case 'B':
channel = kNinjaBootstrap;
break;
case 'E':
channel = kOpenEnvironment;
break;
case 'I':
createInstallPkg = true;
break;
case 'C':
clearEnv = true;
break;
case 'R':
buildReleasedRevision = true;
break;
case 'S':
useStaticCRT = true;
break;
case 'L':
buildLLDB = true;
break;
case 'N':
useNmake = true;
break;
case 'H':
Usage();
LocalFree(Argv_);
return 0;
default:
break;
}
}
if (vs == nullptr || target == nullptr || flavor == nullptr) {
Usage();
return 0;
}
WCHAR szBuffer[UNC_MAX_PATH] = {0};
StringCbPrintfW(szBuffer, UNC_MAX_PATH, L" -VisualStudio %s -Arch %s", vs,
target);
if (channel != kOpenEnvironment) {
StringCbCatW(szBuffer, UNC_MAX_PATH, L" -Flavor ");
StringCbCatW(szBuffer, UNC_MAX_PATH, flavor);
if (createInstallPkg) {
StringCbCatW(szBuffer, UNC_MAX_PATH, L" -Install");
}
if (buildReleasedRevision) {
StringCbCatW(szBuffer, UNC_MAX_PATH, L" -Released");
}
if (useStaticCRT) {
StringCbCatW(szBuffer, UNC_MAX_PATH, L" -Static");
}
if (useNmake && channel == kUseMSBuild) {
StringCbCatW(szBuffer, UNC_MAX_PATH, L" -NMake");
}
if (buildLLDB && channel == kUseMSBuild) {
StringCbCatW(szBuffer, UNC_MAX_PATH, L" -LLDB");
}
}
if (clearEnv) {
StringCbCatW(szBuffer, UNC_MAX_PATH, L" -Clear");
}
auto result = LauncherStartup(szBuffer, channel);
LocalFree(Argv_);
return result;
}
int OutErrorMessage(const wchar_t *errorMsg, const wchar_t *errorTitle) {
int nButton = 0;
int nRadioButton = 0;
TASKDIALOGCONFIG tdConfig;
memset(&tdConfig, 0, sizeof(tdConfig));
tdConfig.cbSize = sizeof(tdConfig);
tdConfig.hwndParent = nullptr;
tdConfig.hInstance = GetModuleHandle(nullptr);
tdConfig.dwFlags = TDF_ALLOW_DIALOG_CANCELLATION | TDF_EXPAND_FOOTER_AREA |
TDF_POSITION_RELATIVE_TO_WINDOW | TDF_SIZE_TO_CONTENT |
TDF_ENABLE_HYPERLINKS;
tdConfig.nDefaultRadioButton = nRadioButton;
tdConfig.pszWindowTitle = L"Clangbuilder launcher Error";
tdConfig.pszMainInstruction = errorTitle;
tdConfig.hMainIcon = static_cast<HICON>(
LoadIcon(GetModuleHandle(nullptr), MAKEINTRESOURCE(IDI_ICON_LAUNCHER)));
tdConfig.dwFlags |= TDF_USE_HICON_MAIN;
tdConfig.pszContent = errorMsg;
tdConfig.pszExpandedInformation =
_T("For more information about this tool, ")
_T("Visit: <a href=\"https://github.com/fstudio/clangbuilder\">Force ")
_T("Charlie</a>");
tdConfig.pszCollapsedControlText = _T("More information");
tdConfig.pszExpandedControlText = _T("Less information");
tdConfig.pfCallback = TaskDialogCallbackProc;
HRESULT hr = TaskDialogIndirect(&tdConfig, &nButton, &nRadioButton, NULL);
return hr;
}
<commit_msg>Update launcher.cpp<commit_after>/////
#include "Precompiled.h"
#include "GetOptInc.h"
#include "resource.h"
#include <Shellapi.h>
#include <Shlobj.h>
#include <Shlwapi.h>
#include <commctrl.h>
#if defined(_WIN32_WINNT_WIN8) && defined(_WIN32_WINNT) && \
_WIN32_WINNT >= _WIN32_WINNT_WIN8
#include <Processthreadsapi.h>
#endif
#include <strsafe.h>
#ifndef ASSERT
#ifdef _DEBUG
#include <assert.h>
#define ASSERT(x) assert(x)
#define ASSERT_HERE assert(FALSE)
#else // _DEBUG
#define ASSERT(x)
#endif //_DEBUG
#endif // ASSERT
#ifndef _tsizeof
#define _tsizeof(s) (sizeof(s) / sizeof(s[0]))
#endif //_tsizeof
#include <comdef.h>
#include <taskschd.h>
#define UNC_MAX_PATH (32 * 1024 - 1)
int OutErrorMessage(const wchar_t *errorMsg, const wchar_t *errorTitle);
void PrintVersion() {
int nButtonPressed = 0;
TaskDialog(NULL, GetModuleHandle(nullptr), L"Clangbuilder launcher",
L"Version Info: ", LAUNCHER_APP_VERSION, TDCBF_OK_BUTTON,
TD_INFORMATION_ICON, &nButtonPressed);
}
HRESULT CALLBACK TaskDialogCallbackProc(__in HWND hwnd, __in UINT msg,
__in WPARAM wParam, __in LPARAM lParam,
__in LONG_PTR lpRefData) {
UNREFERENCED_PARAMETER(lpRefData);
UNREFERENCED_PARAMETER(wParam);
switch (msg) {
case TDN_CREATED:
::SetForegroundWindow(hwnd);
break;
case TDN_RADIO_BUTTON_CLICKED:
break;
case TDN_BUTTON_CLICKED:
break;
case TDN_HYPERLINK_CLICKED:
ShellExecute(hwnd, NULL, (LPCTSTR)lParam, NULL, NULL, SW_SHOWNORMAL);
break;
}
return S_OK;
}
const wchar_t usageInfo[] =
L"OVERVIEW: Clangbuilder launcher utility\n"
L"\nOPTIONS:\n"
L"Usage: launcher [options| V:A:F:BEICRSLNH ] <input>\n"
L" -V\t[--vs] Visual Studio version \n\tAllow: 110| 120| 140| 141| "
L"150\n\n"
L" -A\t[--arch] LLVM Arch \n\tAllow: x86| x64| ARM| ARM64\n\n"
L" -F\t[--flavor] Flavor \n\tAllow: Debug| Release| MinSizeRel| "
L"RelWithDebInfo\n\n"
L" -B\t[--bootstrap] Bootstrap llvm\n"
L" -E\t[--env] Startup Environment not run builder\n"
L" -I\t[--install] Create Install Package\n"
L" -C\t[--clear] Clear Environment\n"
L" -R\t[--released] Build Last Released Revision\n"
L" -S\t[--static] Use Static C Runtime Library\n"
L" -L\t[--lldb] Build LLDB\n"
L" -N\t[--nmake] nmake\n"
L" -H\t[--help] Print Help Message";
void Usage() {
MessageBoxW(nullptr, usageInfo, L"Clangbuilder launcher Usage", MB_OK);
}
enum ClangBuilderChannel : int {
kOpenEnvironment = 0, ///
kBaseBuilder = 1,
kNinjaBootstrap
};
int LauncherStartup(const wchar_t *args, int channel) {
wchar_t pwszPath[UNC_MAX_PATH];
GetModuleFileNameW(nullptr, pwszPath, UNC_MAX_PATH);
PathRemoveFileSpecW(pwszPath);
PathRemoveFileSpecW(pwszPath);
PathRemoveFileSpecW(pwszPath);
std::wstring psfile = pwszPath;
switch (channel) {
case kOpenEnvironment:
psfile += L"\\bin\\ClangBuilderEnvironment.ps1";
break;
case kBaseBuilder:
psfile += L"\\bin\\ClangBuilderManager.ps1";
break;
case kNinjaBootstrap:
psfile += L"\\bin\\ClangBuilderBootstrap.ps1";
break;
default:
psfile = L"Not support channel value: " + std::to_wstring(channel);
OutErrorMessage(psfile.c_str(), L"Not support clangbuilder channel !");
return -2;
}
if (!PathFileExistsW(psfile.c_str())) {
OutErrorMessage(psfile.c_str(), L"PathFileExists return false");
return -1;
}
if (SHGetFolderPathW(NULL, CSIDL_SYSTEM, NULL, 0, pwszPath) != S_OK) {
return -1;
}
auto length = wcslen(pwszPath);
StringCchCatW(pwszPath, UNC_MAX_PATH - length,
L"\\WindowsPowerShell\\v1.0\\powershell.exe ");
length = wcslen(pwszPath);
auto offsetPtr = pwszPath + length;
StringCchPrintfW(offsetPtr, UNC_MAX_PATH - length,
L" -NoLogo -NoExit -File \"%s\" %s", psfile.c_str(), args);
PROCESS_INFORMATION pi;
STARTUPINFO si;
ZeroMemory(&si, sizeof(si));
ZeroMemory(&pi, sizeof(pi));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_SHOW;
if (CreateProcessW(nullptr, pwszPath, NULL, NULL, FALSE,
CREATE_NEW_CONSOLE | NORMAL_PRIORITY_CLASS, NULL, NULL,
&si, &pi)) {
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return 0;
}
return GetLastError();
}
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPWSTR lpCmdLine, int nCmdShow) {
UNREFERENCED_PARAMETER(hInstance);
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
UNREFERENCED_PARAMETER(nCmdShow);
const wchar_t *vs = nullptr;
const wchar_t *target = nullptr;
const wchar_t *flavor = nullptr;
bool createInstallPkg = false;
bool clearEnv = false;
bool useNmake = false;
bool buildReleasedRevision = false;
bool useStaticCRT = false;
bool buildLLDB = false;
int channel = kBaseBuilder;
int Argc = 0;
auto Argv_ = CommandLineToArgvW(GetCommandLineW(), &Argc);
wchar_t *const *Argv = Argv_;
int ch;
const wchar_t *short_opts = L"V:A:F:BEICRSLNH"; // L"V:T:C:BIERSLNH";
const option option_long_opt[] = {
///
{L"vs", required_argument, NULL, 'V'},
{L"arch", required_argument, NULL, 'A'},
{L"flavor", required_argument, NULL, 'F'},
{L"bootstrap", no_argument, NULL, 'B'},
{L"env", no_argument, NULL, 'E'},
{L"install", no_argument, NULL, 'I'},
{L"clear", no_argument, NULL, 'C'},
{L"released", no_argument, NULL, 'R'},
{L"static", no_argument, NULL, 'S'},
{L"lldb", no_argument, NULL, 'L'},
{L"nmake", no_argument, NULL, 'N'},
{L"help", no_argument, NULL, 'H'},
{0, 0, 0, 0}
///
};
while ((ch = getopt_long(Argc, Argv, short_opts, option_long_opt, NULL)) !=
-1) {
switch (ch) {
case 'V':
vs = optarg;
break;
case 'A':
target = optarg;
break;
case 'F':
flavor = optarg;
break;
case 'B':
channel = kNinjaBootstrap;
break;
case 'E':
channel = kOpenEnvironment;
break;
case 'I':
createInstallPkg = true;
break;
case 'C':
clearEnv = true;
break;
case 'R':
buildReleasedRevision = true;
break;
case 'S':
useStaticCRT = true;
break;
case 'L':
buildLLDB = true;
break;
case 'N':
useNmake = true;
break;
case 'H':
Usage();
LocalFree(Argv_);
return 0;
default:
break;
}
}
if (vs == nullptr || target == nullptr || flavor == nullptr) {
Usage();
return 0;
}
WCHAR szBuffer[UNC_MAX_PATH] = {0};
StringCbPrintfW(szBuffer, UNC_MAX_PATH, L" -VisualStudio %s -Arch %s", vs,
target);
if (channel != kOpenEnvironment) {
StringCbCatW(szBuffer, UNC_MAX_PATH, L" -Flavor ");
StringCbCatW(szBuffer, UNC_MAX_PATH, flavor);
if (createInstallPkg) {
StringCbCatW(szBuffer, UNC_MAX_PATH, L" -Install");
}
if (buildReleasedRevision) {
StringCbCatW(szBuffer, UNC_MAX_PATH, L" -Released");
}
if (useStaticCRT) {
StringCbCatW(szBuffer, UNC_MAX_PATH, L" -Static");
}
if (useNmake && channel == kBaseBuilder) {
StringCbCatW(szBuffer, UNC_MAX_PATH, L" -NMake");
}
if (buildLLDB && channel == kBaseBuilder) {
StringCbCatW(szBuffer, UNC_MAX_PATH, L" -LLDB");
}
}
if (clearEnv) {
StringCbCatW(szBuffer, UNC_MAX_PATH, L" -Clear");
}
auto result = LauncherStartup(szBuffer, channel);
LocalFree(Argv_);
return result;
}
int OutErrorMessage(const wchar_t *errorMsg, const wchar_t *errorTitle) {
int nButton = 0;
int nRadioButton = 0;
TASKDIALOGCONFIG tdConfig;
memset(&tdConfig, 0, sizeof(tdConfig));
tdConfig.cbSize = sizeof(tdConfig);
tdConfig.hwndParent = nullptr;
tdConfig.hInstance = GetModuleHandle(nullptr);
tdConfig.dwFlags = TDF_ALLOW_DIALOG_CANCELLATION | TDF_EXPAND_FOOTER_AREA |
TDF_POSITION_RELATIVE_TO_WINDOW | TDF_SIZE_TO_CONTENT |
TDF_ENABLE_HYPERLINKS;
tdConfig.nDefaultRadioButton = nRadioButton;
tdConfig.pszWindowTitle = L"Clangbuilder launcher Error";
tdConfig.pszMainInstruction = errorTitle;
tdConfig.hMainIcon = static_cast<HICON>(
LoadIcon(GetModuleHandle(nullptr), MAKEINTRESOURCE(IDI_ICON_LAUNCHER)));
tdConfig.dwFlags |= TDF_USE_HICON_MAIN;
tdConfig.pszContent = errorMsg;
tdConfig.pszExpandedInformation =
_T("For more information about this tool, ")
_T("Visit: <a href=\"https://github.com/fstudio/clangbuilder\">Force ")
_T("Charlie</a>");
tdConfig.pszCollapsedControlText = _T("More information");
tdConfig.pszExpandedControlText = _T("Less information");
tdConfig.pfCallback = TaskDialogCallbackProc;
HRESULT hr = TaskDialogIndirect(&tdConfig, &nButton, &nRadioButton, NULL);
return hr;
}
<|endoftext|> |
<commit_before>//===--- clang.cpp - C-Language Front-end ---------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This utility may be invoked in the following manner:
// clang-cc --help - Output help info.
// clang-cc [options] - Read from stdin.
// clang-cc [options] file - Read from "file".
// clang-cc [options] file1 file2 - Read these files.
//
//===----------------------------------------------------------------------===//
#include "Options.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/Frontend/VerifyDiagnosticsClient.h"
#include "llvm/LLVMContext.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Host.h"
#include "llvm/System/Path.h"
#include "llvm/System/Signals.h"
#include "llvm/Target/TargetSelect.h"
using namespace clang;
//===----------------------------------------------------------------------===//
// Main driver
//===----------------------------------------------------------------------===//
std::string GetBuiltinIncludePath(const char *Argv0) {
llvm::sys::Path P =
llvm::sys::Path::GetMainExecutable(Argv0,
(void*)(intptr_t) GetBuiltinIncludePath);
if (!P.isEmpty()) {
P.eraseComponent(); // Remove /clang from foo/bin/clang
P.eraseComponent(); // Remove /bin from foo/bin
// Get foo/lib/clang/<version>/include
P.appendComponent("lib");
P.appendComponent("clang");
P.appendComponent(CLANG_VERSION_STRING);
P.appendComponent("include");
}
return P.str();
}
static void LLVMErrorHandler(void *UserData, const std::string &Message) {
Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
Diags.Report(diag::err_fe_error_backend) << Message;
// We cannot recover from llvm errors.
exit(1);
}
/// ClangFrontendTimer - The front-end activities should charge time to it with
/// TimeRegion. The -ftime-report option controls whether this will do
/// anything.
llvm::Timer *ClangFrontendTimer = 0;
static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
using namespace clang::frontend;
switch (CI.getFrontendOpts().ProgramAction) {
default:
llvm::llvm_unreachable("Invalid program action!");
case ASTDump: return new ASTDumpAction();
case ASTPrint: return new ASTPrintAction();
case ASTPrintXML: return new ASTPrintXMLAction();
case ASTView: return new ASTViewAction();
case DumpRawTokens: return new DumpRawTokensAction();
case DumpRecordLayouts: return new DumpRecordAction();
case DumpTokens: return new DumpTokensAction();
case EmitAssembly: return new EmitAssemblyAction();
case EmitBC: return new EmitBCAction();
case EmitHTML: return new HTMLPrintAction();
case EmitLLVM: return new EmitLLVMAction();
case EmitLLVMOnly: return new EmitLLVMOnlyAction();
case FixIt: return new FixItAction();
case GeneratePCH: return new GeneratePCHAction();
case GeneratePTH: return new GeneratePTHAction();
case InheritanceView: return new InheritanceViewAction();
case ParseNoop: return new ParseOnlyAction();
case ParsePrintCallbacks: return new PrintParseAction();
case ParseSyntaxOnly: return new SyntaxOnlyAction();
case PluginAction: {
if (CI.getFrontendOpts().ActionName == "help") {
llvm::errs() << "clang-cc plugins:\n";
for (FrontendPluginRegistry::iterator it =
FrontendPluginRegistry::begin(),
ie = FrontendPluginRegistry::end();
it != ie; ++it)
llvm::errs() << " " << it->getName() << " - " << it->getDesc() << "\n";
exit(1);
}
for (FrontendPluginRegistry::iterator it =
FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
it != ie; ++it) {
if (it->getName() == CI.getFrontendOpts().ActionName)
return it->instantiate();
}
CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
<< CI.getFrontendOpts().ActionName;
return 0;
}
case PrintDeclContext: return new DeclContextPrintAction();
case PrintPreprocessedInput: return new PrintPreprocessedAction();
case RewriteBlocks: return new RewriteBlocksAction();
case RewriteMacros: return new RewriteMacrosAction();
case RewriteObjC: return new RewriteObjCAction();
case RewriteTest: return new RewriteTestAction();
case RunAnalysis: return new AnalysisAction();
case RunPreprocessorOnly: return new PreprocessOnlyAction();
}
}
static TargetInfo *
ConstructCompilerInvocation(CompilerInvocation &Opts, Diagnostic &Diags,
const char *Argv0, bool &IsAST) {
// Initialize target options.
InitializeTargetOptions(Opts.getTargetOpts());
// Get information about the target being compiled for.
llvm::OwningPtr<TargetInfo> Target(
TargetInfo::CreateTargetInfo(Diags, Opts.getTargetOpts()));
if (!Target)
return 0;
// Initialize frontend options.
InitializeFrontendOptions(Opts.getFrontendOpts());
// Determine the input language, we currently require all files to match.
FrontendOptions::InputKind IK = Opts.getFrontendOpts().Inputs[0].first;
for (unsigned i = 1, e = Opts.getFrontendOpts().Inputs.size(); i != e; ++i) {
if (Opts.getFrontendOpts().Inputs[i].first != IK) {
llvm::errs() << "error: cannot have multiple input files of distinct "
<< "language kinds without -x\n";
return 0;
}
}
// Initialize language options.
//
// FIXME: These aren't used during operations on ASTs. Split onto a separate
// code path to make this obvious.
IsAST = (IK == FrontendOptions::IK_AST);
if (!IsAST)
InitializeLangOptions(Opts.getLangOpts(), IK, *Target);
// Initialize the static analyzer options.
InitializeAnalyzerOptions(Opts.getAnalyzerOpts());
// Initialize the dependency output options (-M...).
InitializeDependencyOutputOptions(Opts.getDependencyOutputOpts());
// Initialize the header search options.
InitializeHeaderSearchOptions(Opts.getHeaderSearchOpts(),
GetBuiltinIncludePath(Argv0));
// Initialize the other preprocessor options.
InitializePreprocessorOptions(Opts.getPreprocessorOpts());
// Initialize the preprocessed output options.
InitializePreprocessorOutputOptions(Opts.getPreprocessorOutputOpts());
// Initialize backend options, which may also be used to key some language
// options.
InitializeCodeGenOptions(Opts.getCodeGenOpts(), Opts.getLangOpts(),
Opts.getFrontendOpts().ShowTimers);
return Target.take();
}
int main(int argc, char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal();
llvm::PrettyStackTraceProgram X(argc, argv);
CompilerInstance Clang(&llvm::getGlobalContext(), false);
// Initialize targets first, so that --version shows registered targets.
llvm::InitializeAllTargets();
llvm::InitializeAllAsmPrinters();
llvm::cl::ParseCommandLineOptions(argc, argv,
"LLVM 'Clang' Compiler: http://clang.llvm.org\n");
// Construct the diagnostic engine first, so that we can build a diagnostic
// client to use for any errors during option handling.
InitializeDiagnosticOptions(Clang.getDiagnosticOpts());
Clang.createDiagnostics(argc, argv);
if (!Clang.hasDiagnostics())
return 1;
// Set an error handler, so that any LLVM backend diagnostics go through our
// error handler.
llvm::llvm_install_error_handler(LLVMErrorHandler,
static_cast<void*>(&Clang.getDiagnostics()));
// Now that we have initialized the diagnostics engine, create the target and
// the compiler invocation object.
//
// FIXME: We should move .ast inputs to taking a separate path, they are
// really quite different.
bool IsAST;
Clang.setTarget(
ConstructCompilerInvocation(Clang.getInvocation(), Clang.getDiagnostics(),
argv[0], IsAST));
if (!Clang.hasTarget())
return 1;
// Validate/process some options
if (Clang.getHeaderSearchOpts().Verbose)
llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
<< " based upon " << PACKAGE_STRING
<< " hosted on " << llvm::sys::getHostTriple() << "\n";
if (Clang.getFrontendOpts().ShowTimers)
ClangFrontendTimer = new llvm::Timer("Clang front-end time");
// Enforce certain implications.
if (!Clang.getFrontendOpts().ViewClassInheritance.empty())
Clang.getFrontendOpts().ProgramAction = frontend::InheritanceView;
if (!Clang.getFrontendOpts().FixItLocations.empty())
Clang.getFrontendOpts().ProgramAction = frontend::FixIt;
for (unsigned i = 0, e = Clang.getFrontendOpts().Inputs.size(); i != e; ++i) {
const std::string &InFile = Clang.getFrontendOpts().Inputs[i].second;
// If we aren't using an AST file, setup the file and source managers and
// the preprocessor.
if (!IsAST) {
if (!i) {
// Create a file manager object to provide access to and cache the
// filesystem.
Clang.createFileManager();
// Create the source manager.
Clang.createSourceManager();
} else {
// Reset the ID tables if we are reusing the SourceManager.
Clang.getSourceManager().clearIDTables();
}
// Create the preprocessor.
Clang.createPreprocessor();
}
llvm::OwningPtr<FrontendAction> Act(CreateFrontendAction(Clang));
if (!Act)
break;
Act->setCurrentTimer(ClangFrontendTimer);
if (Act->BeginSourceFile(Clang, InFile, IsAST)) {
Act->Execute();
Act->EndSourceFile();
}
}
if (Clang.getDiagnosticOpts().ShowCarets)
if (unsigned NumDiagnostics = Clang.getDiagnostics().getNumDiagnostics())
fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
(NumDiagnostics == 1 ? "" : "s"));
if (Clang.getFrontendOpts().ShowStats) {
Clang.getFileManager().PrintStats();
fprintf(stderr, "\n");
}
delete ClangFrontendTimer;
// Return the appropriate status when verifying diagnostics.
//
// FIXME: If we could make getNumErrors() do the right thing, we wouldn't need
// this.
if (Clang.getDiagnosticOpts().VerifyDiagnostics)
return static_cast<VerifyDiagnosticsClient&>(
Clang.getDiagnosticClient()).HadErrors();
// Managed static deconstruction. Useful for making things like
// -time-passes usable.
llvm::llvm_shutdown();
return (Clang.getDiagnostics().getNumErrors() != 0);
}
<commit_msg>Fix -Asserts warning.<commit_after>//===--- clang.cpp - C-Language Front-end ---------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This utility may be invoked in the following manner:
// clang-cc --help - Output help info.
// clang-cc [options] - Read from stdin.
// clang-cc [options] file - Read from "file".
// clang-cc [options] file1 file2 - Read these files.
//
//===----------------------------------------------------------------------===//
#include "Options.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/Frontend/VerifyDiagnosticsClient.h"
#include "llvm/LLVMContext.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Host.h"
#include "llvm/System/Path.h"
#include "llvm/System/Signals.h"
#include "llvm/Target/TargetSelect.h"
using namespace clang;
//===----------------------------------------------------------------------===//
// Main driver
//===----------------------------------------------------------------------===//
std::string GetBuiltinIncludePath(const char *Argv0) {
llvm::sys::Path P =
llvm::sys::Path::GetMainExecutable(Argv0,
(void*)(intptr_t) GetBuiltinIncludePath);
if (!P.isEmpty()) {
P.eraseComponent(); // Remove /clang from foo/bin/clang
P.eraseComponent(); // Remove /bin from foo/bin
// Get foo/lib/clang/<version>/include
P.appendComponent("lib");
P.appendComponent("clang");
P.appendComponent(CLANG_VERSION_STRING);
P.appendComponent("include");
}
return P.str();
}
static void LLVMErrorHandler(void *UserData, const std::string &Message) {
Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
Diags.Report(diag::err_fe_error_backend) << Message;
// We cannot recover from llvm errors.
exit(1);
}
/// ClangFrontendTimer - The front-end activities should charge time to it with
/// TimeRegion. The -ftime-report option controls whether this will do
/// anything.
llvm::Timer *ClangFrontendTimer = 0;
static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
using namespace clang::frontend;
switch (CI.getFrontendOpts().ProgramAction) {
default:
llvm::llvm_unreachable("Invalid program action!");
case ASTDump: return new ASTDumpAction();
case ASTPrint: return new ASTPrintAction();
case ASTPrintXML: return new ASTPrintXMLAction();
case ASTView: return new ASTViewAction();
case DumpRawTokens: return new DumpRawTokensAction();
case DumpRecordLayouts: return new DumpRecordAction();
case DumpTokens: return new DumpTokensAction();
case EmitAssembly: return new EmitAssemblyAction();
case EmitBC: return new EmitBCAction();
case EmitHTML: return new HTMLPrintAction();
case EmitLLVM: return new EmitLLVMAction();
case EmitLLVMOnly: return new EmitLLVMOnlyAction();
case FixIt: return new FixItAction();
case GeneratePCH: return new GeneratePCHAction();
case GeneratePTH: return new GeneratePTHAction();
case InheritanceView: return new InheritanceViewAction();
case ParseNoop: return new ParseOnlyAction();
case ParsePrintCallbacks: return new PrintParseAction();
case ParseSyntaxOnly: return new SyntaxOnlyAction();
case PluginAction: {
if (CI.getFrontendOpts().ActionName == "help") {
llvm::errs() << "clang-cc plugins:\n";
for (FrontendPluginRegistry::iterator it =
FrontendPluginRegistry::begin(),
ie = FrontendPluginRegistry::end();
it != ie; ++it)
llvm::errs() << " " << it->getName() << " - " << it->getDesc() << "\n";
exit(1);
}
for (FrontendPluginRegistry::iterator it =
FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
it != ie; ++it) {
if (it->getName() == CI.getFrontendOpts().ActionName)
return it->instantiate();
}
CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
<< CI.getFrontendOpts().ActionName;
return 0;
}
case PrintDeclContext: return new DeclContextPrintAction();
case PrintPreprocessedInput: return new PrintPreprocessedAction();
case RewriteBlocks: return new RewriteBlocksAction();
case RewriteMacros: return new RewriteMacrosAction();
case RewriteObjC: return new RewriteObjCAction();
case RewriteTest: return new RewriteTestAction();
case RunAnalysis: return new AnalysisAction();
case RunPreprocessorOnly: return new PreprocessOnlyAction();
}
}
static TargetInfo *
ConstructCompilerInvocation(CompilerInvocation &Opts, Diagnostic &Diags,
const char *Argv0, bool &IsAST) {
// Initialize target options.
InitializeTargetOptions(Opts.getTargetOpts());
// Get information about the target being compiled for.
llvm::OwningPtr<TargetInfo> Target(
TargetInfo::CreateTargetInfo(Diags, Opts.getTargetOpts()));
if (!Target)
return 0;
// Initialize frontend options.
InitializeFrontendOptions(Opts.getFrontendOpts());
// Determine the input language, we currently require all files to match.
FrontendOptions::InputKind IK = Opts.getFrontendOpts().Inputs[0].first;
for (unsigned i = 1, e = Opts.getFrontendOpts().Inputs.size(); i != e; ++i) {
if (Opts.getFrontendOpts().Inputs[i].first != IK) {
llvm::errs() << "error: cannot have multiple input files of distinct "
<< "language kinds without -x\n";
return 0;
}
}
// Initialize language options.
//
// FIXME: These aren't used during operations on ASTs. Split onto a separate
// code path to make this obvious.
IsAST = (IK == FrontendOptions::IK_AST);
if (!IsAST)
InitializeLangOptions(Opts.getLangOpts(), IK, *Target);
// Initialize the static analyzer options.
InitializeAnalyzerOptions(Opts.getAnalyzerOpts());
// Initialize the dependency output options (-M...).
InitializeDependencyOutputOptions(Opts.getDependencyOutputOpts());
// Initialize the header search options.
InitializeHeaderSearchOptions(Opts.getHeaderSearchOpts(),
GetBuiltinIncludePath(Argv0));
// Initialize the other preprocessor options.
InitializePreprocessorOptions(Opts.getPreprocessorOpts());
// Initialize the preprocessed output options.
InitializePreprocessorOutputOptions(Opts.getPreprocessorOutputOpts());
// Initialize backend options, which may also be used to key some language
// options.
InitializeCodeGenOptions(Opts.getCodeGenOpts(), Opts.getLangOpts(),
Opts.getFrontendOpts().ShowTimers);
return Target.take();
}
int main(int argc, char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal();
llvm::PrettyStackTraceProgram X(argc, argv);
CompilerInstance Clang(&llvm::getGlobalContext(), false);
// Initialize targets first, so that --version shows registered targets.
llvm::InitializeAllTargets();
llvm::InitializeAllAsmPrinters();
llvm::cl::ParseCommandLineOptions(argc, argv,
"LLVM 'Clang' Compiler: http://clang.llvm.org\n");
// Construct the diagnostic engine first, so that we can build a diagnostic
// client to use for any errors during option handling.
InitializeDiagnosticOptions(Clang.getDiagnosticOpts());
Clang.createDiagnostics(argc, argv);
if (!Clang.hasDiagnostics())
return 1;
// Set an error handler, so that any LLVM backend diagnostics go through our
// error handler.
llvm::llvm_install_error_handler(LLVMErrorHandler,
static_cast<void*>(&Clang.getDiagnostics()));
// Now that we have initialized the diagnostics engine, create the target and
// the compiler invocation object.
//
// FIXME: We should move .ast inputs to taking a separate path, they are
// really quite different.
bool IsAST = false;
Clang.setTarget(
ConstructCompilerInvocation(Clang.getInvocation(), Clang.getDiagnostics(),
argv[0], IsAST));
if (!Clang.hasTarget())
return 1;
// Validate/process some options
if (Clang.getHeaderSearchOpts().Verbose)
llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
<< " based upon " << PACKAGE_STRING
<< " hosted on " << llvm::sys::getHostTriple() << "\n";
if (Clang.getFrontendOpts().ShowTimers)
ClangFrontendTimer = new llvm::Timer("Clang front-end time");
// Enforce certain implications.
if (!Clang.getFrontendOpts().ViewClassInheritance.empty())
Clang.getFrontendOpts().ProgramAction = frontend::InheritanceView;
if (!Clang.getFrontendOpts().FixItLocations.empty())
Clang.getFrontendOpts().ProgramAction = frontend::FixIt;
for (unsigned i = 0, e = Clang.getFrontendOpts().Inputs.size(); i != e; ++i) {
const std::string &InFile = Clang.getFrontendOpts().Inputs[i].second;
// If we aren't using an AST file, setup the file and source managers and
// the preprocessor.
if (!IsAST) {
if (!i) {
// Create a file manager object to provide access to and cache the
// filesystem.
Clang.createFileManager();
// Create the source manager.
Clang.createSourceManager();
} else {
// Reset the ID tables if we are reusing the SourceManager.
Clang.getSourceManager().clearIDTables();
}
// Create the preprocessor.
Clang.createPreprocessor();
}
llvm::OwningPtr<FrontendAction> Act(CreateFrontendAction(Clang));
if (!Act)
break;
Act->setCurrentTimer(ClangFrontendTimer);
if (Act->BeginSourceFile(Clang, InFile, IsAST)) {
Act->Execute();
Act->EndSourceFile();
}
}
if (Clang.getDiagnosticOpts().ShowCarets)
if (unsigned NumDiagnostics = Clang.getDiagnostics().getNumDiagnostics())
fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
(NumDiagnostics == 1 ? "" : "s"));
if (Clang.getFrontendOpts().ShowStats) {
Clang.getFileManager().PrintStats();
fprintf(stderr, "\n");
}
delete ClangFrontendTimer;
// Return the appropriate status when verifying diagnostics.
//
// FIXME: If we could make getNumErrors() do the right thing, we wouldn't need
// this.
if (Clang.getDiagnosticOpts().VerifyDiagnostics)
return static_cast<VerifyDiagnosticsClient&>(
Clang.getDiagnosticClient()).HadErrors();
// Managed static deconstruction. Useful for making things like
// -time-passes usable.
llvm::llvm_shutdown();
return (Clang.getDiagnostics().getNumErrors() != 0);
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.