<commit_before>/* Test suite for the library.  First, it ``tests'' that all the constructs it
 * uses compile successfully.  Then, its output to stdout is compared to the
 * expected output automatically extracted from slash-slash comments below.
 *
 * NOTE: For now, the test suite expects a 32-bit system.  On others, some tests
 * may fail, and it may be ineffective at catching bugs.  TODO: Remedy this. */

#include "BigIntegerLibrary.hh"

#include <string>
#include <iostream>
using namespace std;

// Evaluate expr and print the result or "error" as appropriate.
#define TEST(expr) do {\
	cout << "Line " << __LINE__ << ": ";\
	try {\
		cout << (expr);\
	} catch (const char *err) {\
		cout << "error";\
	}\
	cout << endl;\
} while (0)

const BigUnsigned &check(const BigUnsigned &x) {
	unsigned int l = x.getLength();
	if (l != 0 && x.getBlock(l-1) == 0)
		cout << "check: Unzapped number!" << endl;
	if (l > x.getCapacity())
		cout << "check: Capacity inconsistent with length!" << endl;
	return x;
}

const BigInteger &check(const BigInteger &x) {
	if (x.getSign() == 0 && !x.getMagnitude().isZero())
		cout << "check: Sign should not be zero!" << endl;
	if (x.getSign() != 0 && x.getMagnitude().isZero())
		cout << "check: Sign should be zero!" << endl;
	check(x.getMagnitude());
	return x;
}

short pathologicalShort = ~((unsigned short)(~0) >> 1);
int pathologicalInt = ~((unsigned int)(~0) >> 1);
long pathologicalLong = ~((unsigned long)(~0) >> 1);

int main() {

try {

BigUnsigned z(0), one(1), ten(10);
TEST(z); //0
TEST(1); //1
TEST(10); //10

// TODO: Comprehensively test the general and special cases of each function.

// === Default constructors ===

TEST(check(BigUnsigned())); //0
TEST(check(BigInteger())); //0

// === Block-array constructors ===

BigUnsigned::Blk myBlocks[3];
myBlocks[0] = 3;
myBlocks[1] = 4;
myBlocks[2] = 0;
BigUnsigned bu(myBlocks, 3);
TEST(check(bu)); //17179869187
TEST(check(BigInteger(myBlocks, 3))); //17179869187
TEST(check(BigInteger(bu         ))); //17179869187

// For nonzero magnitude, reject zero and invalid signs.
TEST(check(BigInteger(myBlocks, 3, BigInteger::positive))); //17179869187
TEST(check(BigInteger(myBlocks, 3, BigInteger::negative))); //-17179869187
TEST(check(BigInteger(myBlocks, 3, BigInteger::zero    ))); //error
TEST(check(BigInteger(bu,          BigInteger::positive))); //17179869187
TEST(check(BigInteger(bu,          BigInteger::negative))); //-17179869187
TEST(check(BigInteger(bu,          BigInteger::zero    ))); //error

// For zero magnitude, force the sign to zero without error.
BigUnsigned::Blk myZeroBlocks[1];
myZeroBlocks[0] = 0;
TEST(check(BigInteger(myZeroBlocks, 1, BigInteger::positive))); //0
TEST(check(BigInteger(myZeroBlocks, 1, BigInteger::negative))); //0
TEST(check(BigInteger(myZeroBlocks, 1, BigInteger::zero    ))); //0

// === BigUnsigned conversion limits ===

TEST(BigUnsigned(0).toUnsignedLong()); //0
TEST(BigUnsigned(4294967295U).toUnsignedLong()); //4294967295
TEST(stringToBigUnsigned("4294967296").toUnsignedLong()); //error

TEST(BigUnsigned(0).toLong()); //0
TEST(BigUnsigned(2147483647).toLong()); //2147483647
TEST(BigUnsigned(2147483648U).toLong()); //error

// int is the same as long on a 32-bit system
TEST(BigUnsigned(0).toUnsignedInt()); //0
TEST(BigUnsigned(4294967295U).toUnsignedInt()); //4294967295
TEST(stringToBigUnsigned("4294967296").toUnsignedInt()); //error

TEST(BigUnsigned(0).toInt()); //0
TEST(BigUnsigned(2147483647).toInt()); //2147483647
TEST(BigUnsigned(2147483648U).toInt()); //error

TEST(BigUnsigned(0).toUnsignedShort()); //0
TEST(BigUnsigned(65535).toUnsignedShort()); //65535
TEST(BigUnsigned(65536).toUnsignedShort()); //error

TEST(BigUnsigned(0).toShort()); //0
TEST(BigUnsigned(32767).toShort()); //32767
TEST(BigUnsigned(32768).toShort()); //error

// === BigInteger conversion limits ===

TEST(BigInteger(-1).toUnsignedLong()); //error
TEST(BigInteger(0).toUnsignedLong()); //0
TEST(BigInteger(4294967295U).toUnsignedLong()); //4294967295
TEST(stringToBigInteger("4294967296").toUnsignedLong()); //error

TEST(stringToBigInteger("-2147483649").toLong()); //error
TEST(stringToBigInteger("-2147483648").toLong()); //-2147483648
TEST(BigInteger(-2147483647).toLong()); //-2147483647
TEST(BigInteger(0).toLong()); //0
TEST(BigInteger(2147483647).toLong()); //2147483647
TEST(BigInteger(2147483648U).toLong()); //error

// int is the same as long on a 32-bit system
TEST(BigInteger(-1).toUnsignedInt()); //error
TEST(BigInteger(0).toUnsignedInt()); //0
TEST(BigInteger(4294967295U).toUnsignedInt()); //4294967295
TEST(stringToBigInteger("4294967296").toUnsignedInt()); //error

TEST(stringToBigInteger("-2147483649").toInt()); //error
TEST(stringToBigInteger("-2147483648").toInt()); //-2147483648
TEST(BigInteger(-2147483647).toInt()); //-2147483647
TEST(BigInteger(0).toInt()); //0
TEST(BigInteger(2147483647).toInt()); //2147483647
TEST(BigInteger(2147483648U).toInt()); //error

TEST(BigInteger(-1).toUnsignedShort()); //error
TEST(BigInteger(0).toUnsignedShort()); //0
TEST(BigInteger(65535).toUnsignedShort()); //65535
TEST(BigInteger(65536).toUnsignedShort()); //error

TEST(BigInteger(-32769).toShort()); //error
TEST(BigInteger(-32768).toShort()); //-32768
TEST(BigInteger(-32767).toShort()); //-32767
TEST(BigInteger(0).toShort()); //0
TEST(BigInteger(32767).toShort()); //32767
TEST(BigInteger(32768).toShort()); //error

// === Negative BigUnsigneds ===

// ...during construction
TEST(BigUnsigned(short(-1))); //error
TEST(BigUnsigned(pathologicalShort)); //error
TEST(BigUnsigned(-1)); //error
TEST(BigUnsigned(pathologicalInt)); //error
TEST(BigUnsigned(long(-1))); //error
TEST(BigUnsigned(pathologicalLong)); //error

// ...during subtraction
TEST(BigUnsigned(5) - BigUnsigned(6)); //error
TEST(stringToBigUnsigned("314159265358979323") - stringToBigUnsigned("314159265358979324")); //error
TEST(check(BigUnsigned(5) - BigUnsigned(5))); //0
TEST(check(stringToBigUnsigned("314159265358979323") - stringToBigUnsigned("314159265358979323"))); //0
TEST(check(stringToBigUnsigned("4294967296") - BigUnsigned(1))); //4294967295

// === BigUnsigned addition ===

TEST(check(BigUnsigned(0) + 0)); //0
TEST(check(BigUnsigned(0) + 1)); //1
// Ordinary carry
TEST(check(stringToBigUnsigned("8589934591" /* 2^33 - 1*/)
		+ stringToBigUnsigned("4294967298" /* 2^32 + 2 */))); //12884901889
// Creation of a new block
TEST(check(BigUnsigned(0xFFFFFFFFU) + 1)); //4294967296

// === BigUnsigned subtraction ===

TEST(check(BigUnsigned(1) - 0)); //1
TEST(check(BigUnsigned(1) - 1)); //0
TEST(check(BigUnsigned(2) - 1)); //1
// Ordinary borrow
TEST(check(stringToBigUnsigned("12884901889")
		- stringToBigUnsigned("4294967298"))); //8589934591
// Borrow that removes a block
TEST(check(stringToBigUnsigned("4294967296") - 1)); //4294967295

// === BigUnsigned multiplication and division ===

BigUnsigned a = check(BigUnsigned(314159265) * 358979323);
TEST(a); //112776680263877595
TEST(a / 123); //916883579381118
TEST(a % 123); //81

TEST(BigUnsigned(5) / 0); //error

// === Block accessors ===

BigUnsigned b;
TEST(b); //0
TEST(b.getBlock(0)); //0
b.setBlock(1, 314);
// Did b grow properly?  And did we zero intermediate blocks?
TEST(check(b)); //1348619730944
TEST(b.getLength()); //2
TEST(b.getBlock(0)); //0
TEST(b.getBlock(1)); //314
// Did b shrink properly?
b.setBlock(1, 0);
TEST(check(b)); //0

BigUnsigned bb(314);
bb.setBlock(1, 159);
// Make sure we used allocateAndCopy, not allocate
TEST(bb.getBlock(0)); //314
TEST(bb.getBlock(1)); //159
// Blocks beyond the number should be zero regardless of whether they are
// within the capacity.
bb.add(1, 2);
TEST(bb.getBlock(0)); //3
TEST(bb.getBlock(1)); //0
TEST(bb.getBlock(2)); //0
TEST(bb.getBlock(314159)); //0

// === Bit accessors ===

TEST(BigUnsigned(0).bitLength()); //0
TEST(BigUnsigned(1).bitLength()); //1
TEST(BigUnsigned(4095).bitLength()); //12
TEST(BigUnsigned(4096).bitLength()); //13
// 5 billion is between 2^32 (about 4 billion) and 2^33 (about 8 billion).
TEST(stringToBigUnsigned("5000000000").bitLength()); //33

// 25 is binary 11001.
BigUnsigned bbb(25);
TEST(bbb.getBit(4)); //1
TEST(bbb.getBit(3)); //1
TEST(bbb.getBit(2)); //0
TEST(bbb.getBit(1)); //0
TEST(bbb.getBit(0)); //1
TEST(bbb.bitLength()); //5
// Effectively add 2^32.
bbb.setBit(32, true);
TEST(bbb); //4294967321
bbb.setBit(31, true);
bbb.setBit(32, false);
TEST(check(bbb)); //2147483673

// === Combining BigUnsigned, BigInteger, and primitive integers ===

BigUnsigned p1 = BigUnsigned(3) * 5;
TEST(p1); //15
/* In this case, we would like g++ to implicitly promote the BigUnsigned to a
 * BigInteger, but it seems to prefer converting the -5 to a BigUnsigned, which
 * causes an error.  If I take out constructors for BigUnsigned from signed
 * primitive integers, the BigUnsigned(3) becomes ambiguous, and if I take out
 * all the constructors but BigUnsigned(unsigned long), g++ uses that
 * constructor and gets a wrong (positive) answer.  Thus, I think we'll just
 * have to live with this cast. */
BigInteger p2 = BigInteger(BigUnsigned(3)) * -5;
TEST(p2); //-15

// === Test some previous bugs ===

{
	/* Test that BigInteger division sets the sign to zero.
	 * Bug reported by David Allen. */
	BigInteger num(3), denom(5), quotient;
	num.divideWithRemainder(denom, quotient);
	check(quotient);
	num = 5;
	num.divideWithRemainder(denom, quotient);
	check(num);
}

{
	/* Test that BigInteger subtraction sets the sign properly.
	 * Bug reported by Samuel Larkin. */
	BigInteger zero(0), three(3), ans;
	ans = zero - three;
	TEST(check(ans).getSign()); //-1
}

{
	/* Test that BigInteger multiplication shifts bits properly on systems
	 * where long is bigger than int.  (Obviously, this would only catch the
	 * bug when run on such a system.)
	 * Bug reported by Mohand Mezmaz. */
	BigInteger f=4; f*=3;
	TEST(check(f)); //12
}

{
	/* Test that bitwise XOR allocates the larger length.
	 * Bug reported by Sriram Sankararaman. */
	BigUnsigned a(0), b(3), ans;
	ans = a ^ b;
	TEST(ans); //3
}

{
	/* Test that an aliased multiplication works.
	 * Bug reported by Boris Dessy. */
	BigInteger num(5);
	num *= num;
	TEST(check(num)); //25
}

{
	/* Test that BigUnsignedInABase(std::string) constructor rejects digits
	 * too big for the specified base.
	 * Bug reported by Niakam Kazemi. */
	TEST(BigUnsignedInABase("f", 10)); //error
}

} catch (const char *err) {
	cout << "UNCAUGHT ERROR: " << err << endl;
}

return 0;
}
<commit_msg>testsuite.cc: Upgrade test case to 64bit enviroment<commit_after>/* Test suite for the library.  First, it ``tests'' that all the constructs it
 * uses compile successfully.  Then, its output to stdout is compared to the
 * expected output automatically extracted from slash-slash comments below.
 *
 * NOTE: For now, the test suite expects a 32-bit system.  On others, some tests
 * may fail, and it may be ineffective at catching bugs.  TODO: Remedy this. */

#include "BigIntegerLibrary.hh"

#include <string>
#include <iostream>
using namespace std;

// Evaluate expr and print the result or "error" as appropriate.
#define TEST(expr) do {\
	cout << "Line " << __LINE__ << ": ";\
	try {\
		cout << (expr);\
	} catch (const char *err) {\
		cout << "error";\
	}\
	cout << endl;\
} while (0)

const BigUnsigned &check(const BigUnsigned &x) {
	unsigned int l = x.getLength();
	if (l != 0 && x.getBlock(l-1) == 0)
		cout << "check: Unzapped number!" << endl;
	if (l > x.getCapacity())
		cout << "check: Capacity inconsistent with length!" << endl;
	return x;
}

const BigInteger &check(const BigInteger &x) {
	if (x.getSign() == 0 && !x.getMagnitude().isZero())
		cout << "check: Sign should not be zero!" << endl;
	if (x.getSign() != 0 && x.getMagnitude().isZero())
		cout << "check: Sign should be zero!" << endl;
	check(x.getMagnitude());
	return x;
}

short pathologicalShort = ~((unsigned short)(~0) >> 1);
int pathologicalInt = ~((unsigned int)(~0) >> 1);
long pathologicalLong = ~((unsigned long)(~0) >> 1);

int main() {

try {

BigUnsigned z(0), one(1), ten(10);
TEST(z); //0
TEST(1); //1
TEST(10); //10

// TODO: Comprehensively test the general and special cases of each function.

// === Default constructors ===

TEST(check(BigUnsigned())); //0
TEST(check(BigInteger())); //0

// === Block-array constructors ===

BigUnsigned::Blk myBlocks[3];
myBlocks[0] = 3;
myBlocks[1] = 4;
myBlocks[2] = 0;
BigUnsigned bu(myBlocks, 3);
TEST(check(bu)); //73786976294838206467
TEST(check(BigInteger(myBlocks, 3))); //73786976294838206467
TEST(check(BigInteger(bu         ))); //73786976294838206467

// For nonzero magnitude, reject zero and invalid signs.
TEST(check(BigInteger(myBlocks, 3, BigInteger::positive))); //73786976294838206467
TEST(check(BigInteger(myBlocks, 3, BigInteger::negative))); //-73786976294838206467
TEST(check(BigInteger(myBlocks, 3, BigInteger::zero    ))); //error
TEST(check(BigInteger(bu,          BigInteger::positive))); //73786976294838206467
TEST(check(BigInteger(bu,          BigInteger::negative))); //-73786976294838206467
TEST(check(BigInteger(bu,          BigInteger::zero    ))); //error

// For zero magnitude, force the sign to zero without error.
BigUnsigned::Blk myZeroBlocks[1];
myZeroBlocks[0] = 0;
TEST(check(BigInteger(myZeroBlocks, 1, BigInteger::positive))); //0
TEST(check(BigInteger(myZeroBlocks, 1, BigInteger::negative))); //0
TEST(check(BigInteger(myZeroBlocks, 1, BigInteger::zero    ))); //0

// === BigUnsigned conversion limits ===

TEST(BigUnsigned(0).toUnsignedLong()); //0
TEST(BigUnsigned(4294967295U).toUnsignedLong()); //4294967295
TEST(stringToBigUnsigned("18446744073709551616").toUnsignedLong()); //error

TEST(BigUnsigned(0).toLong()); //0
TEST(BigUnsigned(2147483647).toLong()); //2147483647
TEST(BigUnsigned(18446744073709551615U).toLong()); //error

// int is the same as long on a 32-bit system
TEST(BigUnsigned(0).toUnsignedInt()); //0
TEST(BigUnsigned(4294967295U).toUnsignedInt()); //4294967295
TEST(stringToBigUnsigned("4294967296").toUnsignedInt()); //error

TEST(BigUnsigned(0).toInt()); //0
TEST(BigUnsigned(2147483647).toInt()); //2147483647
TEST(BigUnsigned(2147483648U).toInt()); //error

TEST(BigUnsigned(0).toUnsignedShort()); //0
TEST(BigUnsigned(65535).toUnsignedShort()); //65535
TEST(BigUnsigned(65536).toUnsignedShort()); //error

TEST(BigUnsigned(0).toShort()); //0
TEST(BigUnsigned(32767).toShort()); //32767
TEST(BigUnsigned(32768).toShort()); //error

// === BigInteger conversion limits ===

TEST(BigInteger(-1).toUnsignedLong()); //error
TEST(BigInteger(0).toUnsignedLong()); //0
TEST(BigInteger(4294967295U).toUnsignedLong()); //4294967295
TEST(stringToBigInteger("18446744073709551616").toUnsignedLong()); //error

TEST(stringToBigInteger("-9223372036854775809").toLong()); //error
TEST(stringToBigInteger("-2147483648").toLong()); //-2147483648
TEST(BigInteger(-2147483647).toLong()); //-2147483647
TEST(BigInteger(0).toLong()); //0
TEST(BigInteger(9223372036854775807).toLong()); //9223372036854775807
TEST(BigInteger(9223372036854775808U).toLong()); //error

// int is the same as long on a 32-bit system
TEST(BigInteger(-1).toUnsignedInt()); //error
TEST(BigInteger(0).toUnsignedInt()); //0
TEST(BigInteger(4294967295U).toUnsignedInt()); //4294967295
TEST(stringToBigInteger("4294967296").toUnsignedInt()); //error

TEST(stringToBigInteger("-2147483649").toInt()); //error
TEST(stringToBigInteger("-2147483648").toInt()); //-2147483648
TEST(BigInteger(-2147483647).toInt()); //-2147483647
TEST(BigInteger(0).toInt()); //0
TEST(BigInteger(2147483647).toInt()); //2147483647
TEST(BigInteger(2147483648U).toInt()); //error

TEST(BigInteger(-1).toUnsignedShort()); //error
TEST(BigInteger(0).toUnsignedShort()); //0
TEST(BigInteger(65535).toUnsignedShort()); //65535
TEST(BigInteger(65536).toUnsignedShort()); //error

TEST(BigInteger(-32769).toShort()); //error
TEST(BigInteger(-32768).toShort()); //-32768
TEST(BigInteger(-32767).toShort()); //-32767
TEST(BigInteger(0).toShort()); //0
TEST(BigInteger(32767).toShort()); //32767
TEST(BigInteger(32768).toShort()); //error

// === Negative BigUnsigneds ===

// ...during construction
TEST(BigUnsigned(short(-1))); //error
TEST(BigUnsigned(pathologicalShort)); //error
TEST(BigUnsigned(-1)); //error
TEST(BigUnsigned(pathologicalInt)); //error
TEST(BigUnsigned(long(-1))); //error
TEST(BigUnsigned(pathologicalLong)); //error

// ...during subtraction
TEST(BigUnsigned(5) - BigUnsigned(6)); //error
TEST(stringToBigUnsigned("314159265358979323") - stringToBigUnsigned("314159265358979324")); //error
TEST(check(BigUnsigned(5) - BigUnsigned(5))); //0
TEST(check(stringToBigUnsigned("314159265358979323") - stringToBigUnsigned("314159265358979323"))); //0
TEST(check(stringToBigUnsigned("4294967296") - BigUnsigned(1))); //4294967295

// === BigUnsigned addition ===

TEST(check(BigUnsigned(0) + 0)); //0
TEST(check(BigUnsigned(0) + 1)); //1
// Ordinary carry
TEST(check(stringToBigUnsigned("8589934591" /* 2^33 - 1*/)
		+ stringToBigUnsigned("4294967298" /* 2^32 + 2 */))); //12884901889
// Creation of a new block
TEST(check(BigUnsigned(0xFFFFFFFFU) + 1)); //4294967296

// === BigUnsigned subtraction ===

TEST(check(BigUnsigned(1) - 0)); //1
TEST(check(BigUnsigned(1) - 1)); //0
TEST(check(BigUnsigned(2) - 1)); //1
// Ordinary borrow
TEST(check(stringToBigUnsigned("12884901889")
		- stringToBigUnsigned("4294967298"))); //8589934591
// Borrow that removes a block
TEST(check(stringToBigUnsigned("4294967296") - 1)); //4294967295

// === BigUnsigned multiplication and division ===

BigUnsigned a = check(BigUnsigned(314159265) * 358979323);
TEST(a); //112776680263877595
TEST(a / 123); //916883579381118
TEST(a % 123); //81

TEST(BigUnsigned(5) / 0); //error

// === Block accessors ===

BigUnsigned b;
TEST(b); //0
TEST(b.getBlock(0)); //0
b.setBlock(1, 314);
// Did b grow properly?  And did we zero intermediate blocks?
TEST(check(b)); //5792277639144799207424
TEST(b.getLength()); //2
TEST(b.getBlock(0)); //0
TEST(b.getBlock(1)); //314
// Did b shrink properly?
b.setBlock(1, 0);
TEST(check(b)); //0

BigUnsigned bb(314);
bb.setBlock(1, 159);
// Make sure we used allocateAndCopy, not allocate
TEST(bb.getBlock(0)); //314
TEST(bb.getBlock(1)); //159
// Blocks beyond the number should be zero regardless of whether they are
// within the capacity.
bb.add(1, 2);
TEST(bb.getBlock(0)); //3
TEST(bb.getBlock(1)); //0
TEST(bb.getBlock(2)); //0
TEST(bb.getBlock(314159)); //0

// === Bit accessors ===

TEST(BigUnsigned(0).bitLength()); //0
TEST(BigUnsigned(1).bitLength()); //1
TEST(BigUnsigned(4095).bitLength()); //12
TEST(BigUnsigned(4096).bitLength()); //13
// 5 billion is between 2^32 (about 4 billion) and 2^33 (about 8 billion).
TEST(stringToBigUnsigned("5000000000").bitLength()); //33

// 25 is binary 11001.
BigUnsigned bbb(25);
TEST(bbb.getBit(4)); //1
TEST(bbb.getBit(3)); //1
TEST(bbb.getBit(2)); //0
TEST(bbb.getBit(1)); //0
TEST(bbb.getBit(0)); //1
TEST(bbb.bitLength()); //5
// Effectively add 2^32.
bbb.setBit(32, true);
TEST(bbb); //4294967321
bbb.setBit(31, true);
bbb.setBit(32, false);
TEST(check(bbb)); //2147483673

// === Combining BigUnsigned, BigInteger, and primitive integers ===

BigUnsigned p1 = BigUnsigned(3) * 5;
TEST(p1); //15
/* In this case, we would like g++ to implicitly promote the BigUnsigned to a
 * BigInteger, but it seems to prefer converting the -5 to a BigUnsigned, which
 * causes an error.  If I take out constructors for BigUnsigned from signed
 * primitive integers, the BigUnsigned(3) becomes ambiguous, and if I take out
 * all the constructors but BigUnsigned(unsigned long), g++ uses that
 * constructor and gets a wrong (positive) answer.  Thus, I think we'll just
 * have to live with this cast. */
BigInteger p2 = BigInteger(BigUnsigned(3)) * -5;
TEST(p2); //-15

// === Test some previous bugs ===

{
	/* Test that BigInteger division sets the sign to zero.
	 * Bug reported by David Allen. */
	BigInteger num(3), denom(5), quotient;
	num.divideWithRemainder(denom, quotient);
	check(quotient);
	num = 5;
	num.divideWithRemainder(denom, quotient);
	check(num);
}

{
	/* Test that BigInteger subtraction sets the sign properly.
	 * Bug reported by Samuel Larkin. */
	BigInteger zero(0), three(3), ans;
	ans = zero - three;
	TEST(check(ans).getSign()); //-1
}

{
	/* Test that BigInteger multiplication shifts bits properly on systems
	 * where long is bigger than int.  (Obviously, this would only catch the
	 * bug when run on such a system.)
	 * Bug reported by Mohand Mezmaz. */
	BigInteger f=4; f*=3;
	TEST(check(f)); //12
}

{
	/* Test that bitwise XOR allocates the larger length.
	 * Bug reported by Sriram Sankararaman. */
	BigUnsigned a(0), b(3), ans;
	ans = a ^ b;
	TEST(ans); //3
}

{
	/* Test that an aliased multiplication works.
	 * Bug reported by Boris Dessy. */
	BigInteger num(5);
	num *= num;
	TEST(check(num)); //25
}

{
	/* Test that BigUnsignedInABase(std::string) constructor rejects digits
	 * too big for the specified base.
	 * Bug reported by Niakam Kazemi. */
	TEST(BigUnsignedInABase("f", 10)); //error
}

} catch (const char *err) {
	cout << "UNCAUGHT ERROR: " << err << endl;
}

return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/notification_provider.h"

#include "base/string_util.h"
#include "base/task.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "chrome/renderer/render_thread.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/WebKit/chromium/public/WebNotificationPermissionCallback.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURL.h"

using WebKit::WebDocument;
using WebKit::WebNotification;
using WebKit::WebNotificationPresenter;
using WebKit::WebNotificationPermissionCallback;
using WebKit::WebString;
using WebKit::WebURL;

NotificationProvider::NotificationProvider(RenderView* view)
    : view_(view) {
}

bool NotificationProvider::show(const WebNotification& notification) {
  int notification_id = manager_.RegisterNotification(notification);
  if (notification.isHTML())
    return ShowHTML(notification, notification_id);
  else
    return ShowText(notification, notification_id);
}

void NotificationProvider::cancel(const WebNotification& notification) {
  int id;
  bool id_found = manager_.GetId(notification, id);
  // Won't be found if the notification has already been closed by the user.
  if (id_found)
    Send(new ViewHostMsg_CancelDesktopNotification(view_->routing_id(), id));
}

void NotificationProvider::objectDestroyed(
    const WebNotification& notification) {
  int id;
  bool id_found = manager_.GetId(notification, id);
  // Won't be found if the notification has already been closed by the user.
  if (id_found)
    manager_.UnregisterNotification(id);
}

WebNotificationPresenter::Permission NotificationProvider::checkPermission(
    const WebURL& url, WebDocument* document) {
  int permission;
  Send(new ViewHostMsg_CheckNotificationPermission(
          view_->routing_id(),
          url,
          document ? UTF16ToASCII(document->applicationID()) : "",
          &permission));
  return static_cast<WebNotificationPresenter::Permission>(permission);
}

void NotificationProvider::requestPermission(
    const WebString& origin, WebNotificationPermissionCallback* callback) {
  // We only request permission in response to a user gesture.
  if (!view_->webview()->mainFrame()->isProcessingUserGesture())
    return;

  int id = manager_.RegisterPermissionRequest(callback);

  Send(new ViewHostMsg_RequestNotificationPermission(view_->routing_id(),
                                                     GURL(origin), id));
}

bool NotificationProvider::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(NotificationProvider, message)
    IPC_MESSAGE_HANDLER(ViewMsg_PostDisplayToNotificationObject, OnDisplay);
    IPC_MESSAGE_HANDLER(ViewMsg_PostErrorToNotificationObject, OnError);
    IPC_MESSAGE_HANDLER(ViewMsg_PostCloseToNotificationObject, OnClose);
    IPC_MESSAGE_HANDLER(ViewMsg_PermissionRequestDone,
                        OnPermissionRequestComplete);
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void NotificationProvider::OnNavigate() {
  manager_.Clear();
}

bool NotificationProvider::ShowHTML(const WebNotification& notification,
                                    int id) {
  // Disallow HTML notifications from non-HTTP schemes.
  GURL url = notification.url();
  if (!url.SchemeIs(chrome::kHttpScheme) &&
      !url.SchemeIs(chrome::kHttpsScheme) &&
      !url.SchemeIs(chrome::kExtensionScheme))
    return false;

  DCHECK(notification.isHTML());
  return Send(new ViewHostMsg_ShowDesktopNotification(view_->routing_id(),
              GURL(view_->webview()->mainFrame()->url()).GetOrigin(),
              notification.url(), id));
}

bool NotificationProvider::ShowText(const WebNotification& notification,
                                    int id) {
  DCHECK(!notification.isHTML());
  return Send(new ViewHostMsg_ShowDesktopNotificationText(view_->routing_id(),
              GURL(view_->webview()->mainFrame()->url()).GetOrigin(),
              GURL(notification.icon()),
              notification.title(), notification.body(), id));
}

void NotificationProvider::OnDisplay(int id) {
  WebNotification notification;
  bool found = manager_.GetNotification(id, &notification);
  // |found| may be false if the WebNotification went out of scope in
  // the page before it was actually displayed to the user.
  if (found)
    notification.dispatchDisplayEvent();
}

void NotificationProvider::OnError(int id, const WebString& message) {
  WebNotification notification;
  bool found = manager_.GetNotification(id, &notification);
  // |found| may be false if the WebNotification went out of scope in
  // the page before the error occurred.
  if (found)
    notification.dispatchErrorEvent(message);
}

void NotificationProvider::OnClose(int id, bool by_user) {
  WebNotification notification;
  bool found = manager_.GetNotification(id, &notification);
  // |found| may be false if the WebNotification went out of scope in
  // the page before the associated toast was closed by the user.
  if (found) {
    notification.dispatchCloseEvent(by_user);
    manager_.UnregisterNotification(id);
  }
}

void NotificationProvider::OnPermissionRequestComplete(int id) {
  WebNotificationPermissionCallback* callback = manager_.GetCallback(id);
  DCHECK(callback);
  callback->permissionRequestComplete();
  manager_.OnPermissionRequestComplete(id);
}

bool NotificationProvider::Send(IPC::Message* message) {
  return RenderThread::current()->Send(message);
}
<commit_msg>Use the full URL of the icon in the notification, not just the string passed in -- so that that string doesn't have to be absolute.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/notification_provider.h"

#include "base/string_util.h"
#include "base/task.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "chrome/renderer/render_thread.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/WebKit/chromium/public/WebNotificationPermissionCallback.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURL.h"

using WebKit::WebDocument;
using WebKit::WebNotification;
using WebKit::WebNotificationPresenter;
using WebKit::WebNotificationPermissionCallback;
using WebKit::WebString;
using WebKit::WebURL;

NotificationProvider::NotificationProvider(RenderView* view)
    : view_(view) {
}

bool NotificationProvider::show(const WebNotification& notification) {
  int notification_id = manager_.RegisterNotification(notification);
  if (notification.isHTML())
    return ShowHTML(notification, notification_id);
  else
    return ShowText(notification, notification_id);
}

void NotificationProvider::cancel(const WebNotification& notification) {
  int id;
  bool id_found = manager_.GetId(notification, id);
  // Won't be found if the notification has already been closed by the user.
  if (id_found)
    Send(new ViewHostMsg_CancelDesktopNotification(view_->routing_id(), id));
}

void NotificationProvider::objectDestroyed(
    const WebNotification& notification) {
  int id;
  bool id_found = manager_.GetId(notification, id);
  // Won't be found if the notification has already been closed by the user.
  if (id_found)
    manager_.UnregisterNotification(id);
}

WebNotificationPresenter::Permission NotificationProvider::checkPermission(
    const WebURL& url, WebDocument* document) {
  int permission;
  Send(new ViewHostMsg_CheckNotificationPermission(
          view_->routing_id(),
          url,
          document ? UTF16ToASCII(document->applicationID()) : "",
          &permission));
  return static_cast<WebNotificationPresenter::Permission>(permission);
}

void NotificationProvider::requestPermission(
    const WebString& origin, WebNotificationPermissionCallback* callback) {
  // We only request permission in response to a user gesture.
  if (!view_->webview()->mainFrame()->isProcessingUserGesture())
    return;

  int id = manager_.RegisterPermissionRequest(callback);

  Send(new ViewHostMsg_RequestNotificationPermission(view_->routing_id(),
                                                     GURL(origin), id));
}

bool NotificationProvider::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(NotificationProvider, message)
    IPC_MESSAGE_HANDLER(ViewMsg_PostDisplayToNotificationObject, OnDisplay);
    IPC_MESSAGE_HANDLER(ViewMsg_PostErrorToNotificationObject, OnError);
    IPC_MESSAGE_HANDLER(ViewMsg_PostCloseToNotificationObject, OnClose);
    IPC_MESSAGE_HANDLER(ViewMsg_PermissionRequestDone,
                        OnPermissionRequestComplete);
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void NotificationProvider::OnNavigate() {
  manager_.Clear();
}

bool NotificationProvider::ShowHTML(const WebNotification& notification,
                                    int id) {
  // Disallow HTML notifications from non-HTTP schemes.
  GURL url = notification.url();
  if (!url.SchemeIs(chrome::kHttpScheme) &&
      !url.SchemeIs(chrome::kHttpsScheme) &&
      !url.SchemeIs(chrome::kExtensionScheme))
    return false;

  DCHECK(notification.isHTML());
  return Send(new ViewHostMsg_ShowDesktopNotification(view_->routing_id(),
              GURL(view_->webview()->mainFrame()->url()).GetOrigin(),
              notification.url(), id));
}

bool NotificationProvider::ShowText(const WebNotification& notification,
                                    int id) {
  DCHECK(!notification.isHTML());
  return Send(new ViewHostMsg_ShowDesktopNotificationText(view_->routing_id(),
              GURL(view_->webview()->mainFrame()->url()).GetOrigin(),
              notification.iconURL(),
              notification.title(), notification.body(), id));
}

void NotificationProvider::OnDisplay(int id) {
  WebNotification notification;
  bool found = manager_.GetNotification(id, &notification);
  // |found| may be false if the WebNotification went out of scope in
  // the page before it was actually displayed to the user.
  if (found)
    notification.dispatchDisplayEvent();
}

void NotificationProvider::OnError(int id, const WebString& message) {
  WebNotification notification;
  bool found = manager_.GetNotification(id, &notification);
  // |found| may be false if the WebNotification went out of scope in
  // the page before the error occurred.
  if (found)
    notification.dispatchErrorEvent(message);
}

void NotificationProvider::OnClose(int id, bool by_user) {
  WebNotification notification;
  bool found = manager_.GetNotification(id, &notification);
  // |found| may be false if the WebNotification went out of scope in
  // the page before the associated toast was closed by the user.
  if (found) {
    notification.dispatchCloseEvent(by_user);
    manager_.UnregisterNotification(id);
  }
}

void NotificationProvider::OnPermissionRequestComplete(int id) {
  WebNotificationPermissionCallback* callback = manager_.GetCallback(id);
  DCHECK(callback);
  callback->permissionRequestComplete();
  manager_.OnPermissionRequestComplete(id);
}

bool NotificationProvider::Send(IPC::Message* message) {
  return RenderThread::current()->Send(message);
}
<|endoftext|>


<commit_before>#include "perf_precomp.hpp"
#include <opencv2/imgproc.hpp>

#include "opencv2/ts/ocl_perf.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;

typedef std::tr1::tuple<std::string, std::string, int> Cascade_Image_MinSize_t;
typedef perf::TestBaseWithParam<Cascade_Image_MinSize_t> Cascade_Image_MinSize;

OCL_PERF_TEST_P(Cascade_Image_MinSize, CascadeClassifier,
                 testing::Combine(
                    testing::Values( string("cv/cascadeandhog/cascades/haarcascade_frontalface_alt.xml"),
                                     string("cv/cascadeandhog/cascades/lbpcascade_frontalface.xml") ),
                    testing::Values( string("cv/shared/lena.png"),
                                     string("cv/cascadeandhog/images/bttf301.png"),
                                     string("cv/cascadeandhog/images/class57.png") ),
                    testing::Values(30, 64, 90) ) )
{
    const string cascasePath = get<0>(GetParam());
    const string imagePath   = get<1>(GetParam());
    int min_size = get<2>(GetParam());
    Size minSize(min_size, min_size);

    CascadeClassifier cc( getDataPath(cascasePath) );
    if (cc.empty())
        FAIL() << "Can't load cascade file: " << getDataPath(cascasePath);

    Mat img = imread(getDataPath(imagePath), IMREAD_GRAYSCALE);
    if (img.empty())
        FAIL() << "Can't load source image: " << getDataPath(imagePath);

    vector<Rect> faces;

    equalizeHist(img, img);
    declare.in(img).time(60);

    UMat uimg = img.getUMat(ACCESS_READ);

    while(next())
    {
        faces.clear();
        cvtest::ocl::perf::safeFinish();

        startTimer();
        cc.detectMultiScale(uimg, faces, 1.1, 3, 0, minSize);
        stopTimer();
    }

    sort(faces.begin(), faces.end(), comparators::RectLess());
    SANITY_CHECK(faces, min_size/5);
}
<commit_msg>fixing compilation if `WITH_OPENCL=OFF`<commit_after>#include "perf_precomp.hpp"
#include <opencv2/imgproc.hpp>

#include "opencv2/ts/ocl_perf.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;

typedef std::tr1::tuple<std::string, std::string, int> Cascade_Image_MinSize_t;
typedef perf::TestBaseWithParam<Cascade_Image_MinSize_t> Cascade_Image_MinSize;

#ifdef HAVE_OPENCL

OCL_PERF_TEST_P(Cascade_Image_MinSize, CascadeClassifier,
                 testing::Combine(
                    testing::Values( string("cv/cascadeandhog/cascades/haarcascade_frontalface_alt.xml"),
                                     string("cv/cascadeandhog/cascades/lbpcascade_frontalface.xml") ),
                    testing::Values( string("cv/shared/lena.png"),
                                     string("cv/cascadeandhog/images/bttf301.png"),
                                     string("cv/cascadeandhog/images/class57.png") ),
                    testing::Values(30, 64, 90) ) )
{
    const string cascasePath = get<0>(GetParam());
    const string imagePath   = get<1>(GetParam());
    int min_size = get<2>(GetParam());
    Size minSize(min_size, min_size);

    CascadeClassifier cc( getDataPath(cascasePath) );
    if (cc.empty())
        FAIL() << "Can't load cascade file: " << getDataPath(cascasePath);

    Mat img = imread(getDataPath(imagePath), IMREAD_GRAYSCALE);
    if (img.empty())
        FAIL() << "Can't load source image: " << getDataPath(imagePath);

    vector<Rect> faces;

    equalizeHist(img, img);
    declare.in(img).time(60);

    UMat uimg = img.getUMat(ACCESS_READ);

    while(next())
    {
        faces.clear();
        cvtest::ocl::perf::safeFinish();

        startTimer();
        cc.detectMultiScale(uimg, faces, 1.1, 3, 0, minSize);
        stopTimer();
    }

    sort(faces.begin(), faces.end(), comparators::RectLess());
    SANITY_CHECK(faces, min_size/5);
}

#endif //HAVE_OPENCL
<|endoftext|>


<commit_before>//===--- PostfixOperatorCheck.cpp - clang-tidy-----------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "PostfixOperatorCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"

using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace cert {

void PostfixOperatorCheck::registerMatchers(MatchFinder *Finder) {
  if (!getLangOpts().CPlusPlus)
    return;

  Finder->addMatcher(functionDecl(anyOf(hasOverloadedOperatorName("++"),
                                        hasOverloadedOperatorName("--")))
                         .bind("decl"),
                     this);
}

void PostfixOperatorCheck::check(const MatchFinder::MatchResult &Result) {
  const auto *FuncDecl = Result.Nodes.getNodeAs<FunctionDecl>("decl");

  bool HasThis = false;
  if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(FuncDecl))
    HasThis = MethodDecl->isInstance();

  // Check if the operator is a postfix one.
  if (FuncDecl->getNumParams() != (HasThis ? 1 : 2))
    return;

  SourceRange ReturnRange = FuncDecl->getReturnTypeSourceRange();
  SourceLocation Location = ReturnRange.getBegin();
  if (!Location.isValid())
    return;

  QualType ReturnType = FuncDecl->getReturnType();

  // Warn when the operators return a reference.
  if (const auto *RefType = ReturnType->getAs<ReferenceType>()) {
    auto Diag = diag(Location, "overloaded %0 returns a reference instead of a "
                               "constant object type")
                << FuncDecl;

    if (Location.isMacroID() || ReturnType->getAs<TypedefType>() ||
        RefType->getPointeeTypeAsWritten()->getAs<TypedefType>())
      return;

    QualType ReplaceType =
        ReturnType.getNonReferenceType().getLocalUnqualifiedType();
    // The getReturnTypeSourceRange omits the qualifiers. We do not want to
    // duplicate the const.
    if (!ReturnType->getPointeeType().isConstQualified())
      ReplaceType.addConst();

    Diag << FixItHint::CreateReplacement(
        ReturnRange,
        ReplaceType.getAsString(Result.Context->getPrintingPolicy()) + " ");

    return;
  }

  if (ReturnType.isConstQualified() || ReturnType->isBuiltinType() ||
      ReturnType->isPointerType())
    return;

  auto Diag =
      diag(Location, "overloaded %0 returns a non-constant object instead of a "
                     "constant object type")
      << FuncDecl;

  if (!Location.isMacroID() && !ReturnType->getAs<TypedefType>())
    Diag << FixItHint::CreateInsertion(Location, "const ");
}

} // namespace cert
} // namespace tidy
} // namespace clang
<commit_msg>[clang-tidy] Ignore matches in template instantiations (cert-dcl21-cpp)<commit_after>//===--- PostfixOperatorCheck.cpp - clang-tidy-----------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "PostfixOperatorCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"

using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace cert {

void PostfixOperatorCheck::registerMatchers(MatchFinder *Finder) {
  if (!getLangOpts().CPlusPlus)
    return;

  Finder->addMatcher(functionDecl(anyOf(hasOverloadedOperatorName("++"),
                                        hasOverloadedOperatorName("--")),
                                  unless(isInstantiated()))
                         .bind("decl"),
                     this);
}

void PostfixOperatorCheck::check(const MatchFinder::MatchResult &Result) {
  const auto *FuncDecl = Result.Nodes.getNodeAs<FunctionDecl>("decl");

  bool HasThis = false;
  if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(FuncDecl))
    HasThis = MethodDecl->isInstance();

  // Check if the operator is a postfix one.
  if (FuncDecl->getNumParams() != (HasThis ? 1 : 2))
    return;

  SourceRange ReturnRange = FuncDecl->getReturnTypeSourceRange();
  SourceLocation Location = ReturnRange.getBegin();
  if (!Location.isValid())
    return;

  QualType ReturnType = FuncDecl->getReturnType();

  // Warn when the operators return a reference.
  if (const auto *RefType = ReturnType->getAs<ReferenceType>()) {
    auto Diag = diag(Location, "overloaded %0 returns a reference instead of a "
                               "constant object type")
                << FuncDecl;

    if (Location.isMacroID() || ReturnType->getAs<TypedefType>() ||
        RefType->getPointeeTypeAsWritten()->getAs<TypedefType>())
      return;

    QualType ReplaceType =
        ReturnType.getNonReferenceType().getLocalUnqualifiedType();
    // The getReturnTypeSourceRange omits the qualifiers. We do not want to
    // duplicate the const.
    if (!ReturnType->getPointeeType().isConstQualified())
      ReplaceType.addConst();

    Diag << FixItHint::CreateReplacement(
        ReturnRange,
        ReplaceType.getAsString(Result.Context->getPrintingPolicy()) + " ");

    return;
  }

  if (ReturnType.isConstQualified() || ReturnType->isBuiltinType() ||
      ReturnType->isPointerType())
    return;

  auto Diag =
      diag(Location, "overloaded %0 returns a non-constant object instead of a "
                     "constant object type")
      << FuncDecl;

  if (!Location.isMacroID() && !ReturnType->getAs<TypedefType>())
    Diag << FixItHint::CreateInsertion(Location, "const ");
}

} // namespace cert
} // namespace tidy
} // namespace clang
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Helper program to analyze the time that Chrome's renderers spend in system
// calls. Start Chrome like this:
//
// SECCOMP_SANDBOX_DEBUGGING=1 chrome --enable-seccomp-sandbox 2>&1 | timestats
//
// The program prints CPU time (0-100%) spent within system calls. This gives
// a general idea of where it is worthwhile to spend effort optimizing Chrome.
//
// Caveats:
//  - there currently is no way to estimate what the overhead is for running
//    inside of the sandbox vs. running without a sandbox.
//  - we currently use a very simple heuristic to decide whether a system call
//    is blocking or not. Blocking system calls should not be included in the
//    computations. But it is quite possible for the numbers to be somewhat
//    wrong, because the heuristic failed.
//  - in order to collect this data, we have to turn on sandbox debugging.
//    There is a measurable performance penalty to doing so. Production numbers
//    are strictly better than the numbers reported by this tool.
#include <set>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include <vector>

#define WINDOW     500  /* ms */
#define PEAK   (2*1000) /* ms */

class Datum {
  friend class Data;
 public:
  Datum(const char* name, double ms)
    : name_(name),
      ms_(ms) {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    timestamp_ = tv.tv_sec*1000.0 + tv.tv_usec/1000.0;
  }
  virtual ~Datum() { }

  double operator-(const Datum& b) {
    return timestamp_ - b.timestamp_;
  }

 protected:
  const char* name_;
  double      ms_;
  double      timestamp_;
};

class Data {
 public:
  Data() { }
  virtual ~Data() { }

  void addData(const char* name, double ms) {
    average_.push_back(Datum(name, ms));
    peak_.push_back(Datum(name, ms));

    // Prune entries outside of the window
    std::vector<Datum>::iterator iter;
    for (iter = average_.begin(); *average_.rbegin() - *iter > WINDOW; ++iter){
    }
    average_.erase(average_.begin(), iter);

    for (iter = peak_.begin(); *peak_.rbegin() - *iter > PEAK; ++iter){
    }
    peak_.erase(peak_.begin(), iter);

    // Add the total usage of all system calls inside of the window
    double total = 0;
    for (iter = average_.begin(); iter != average_.end(); ++iter) {
      total += iter->ms_;
    }

    // Compute the peak CPU usage during the last window
    double peak = 0;
    double max = 0;
    std::vector<Datum>::iterator tail = peak_.begin();
    for (iter = tail; iter != peak_.end(); ++iter) {
      while (*iter - *tail > WINDOW) {
        peak -= tail->ms_;
        ++tail;
      }
      peak += iter->ms_;
      if (peak > max) {
        max = peak;
      }
    }

    // Print the average CPU usage in the last window
    char buf[80];
    total *= 100.0/WINDOW;
    max   *= 100.0/WINDOW;
    sprintf(buf, "%6.2f%% (peak=%6.2f%%) ", total, max);

    // Animate the actual usage, displaying both average and peak values
    int len   = strlen(buf);
    int space = sizeof(buf) - len - 1;
    int mark  = (total * space + 50)/100;
    int bar   = (max   * space + 50)/100;
    for (int i = 0; i < mark; ++i) {
      buf[len++] = '*';
    }
    if (mark == bar) {
      if (bar) {
        len--;
      }
    } else {
      for (int i = 0; i < bar - mark - 1; ++i) {
        buf[len++] = ' ';
      }
    }
    buf[len++] = '|';
    while (len < static_cast<int>(sizeof(buf))) {
      buf[len++] = ' ';
    }
    strcpy(buf + len, "\r");
    fwrite(buf, len + 1, 1, stdout);
    fflush(stdout);
  }

 private:
  std::vector<Datum> average_;
  std::vector<Datum> peak_;
};
static Data data;

int main(int argc, char *argv[]) {
  char buf[80];
  bool expensive = false;
  while (fgets(buf, sizeof(buf), stdin)) {
    // Allow longer delays for expensive system calls
    if (strstr(buf, "This is an expensive system call")) {
      expensive = true;
      continue;
    }

    // Parse the string and extra the elapsed time
    const char elapsed[] = "Elapsed time: ";
    char* ms_string = strstr(buf, elapsed);
    char* endptr;
    double ms;
    char* colon = strchr(buf, ':');

    // If this string doesn't match, then it must be some other type of
    // message. Just ignore it.
    if (!ms_string ||
        ((ms = strtod(ms_string + sizeof(elapsed) - 1, &endptr)),
         endptr == ms_string) ||
        !colon) {
      continue;
    }

    // Filter out system calls that were probably just blocking
    // TODO(markus): automatically compute the cut-off for blocking calls
    if (!expensive && ms > 0.05) {
      continue;
    }
    expensive = false;

    // Extract the name of the system call
    *colon = '\000';

    // Add the data point and update the display
    data.addData(buf, ms);
  }
  puts("");
  return 0;
}
<commit_msg>Minor cosmetic clean up<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Helper program to analyze the time that Chrome's renderers spend in system
// calls. Start Chrome like this:
//
// SECCOMP_SANDBOX_DEBUGGING=1 chrome --enable-seccomp-sandbox 2>&1 | timestats
//
// The program prints CPU time (0-100%) spent within system calls. This gives
// a general idea of where it is worthwhile to spend effort optimizing Chrome.
//
// Caveats:
//  - there currently is no way to estimate what the overhead is for running
//    inside of the sandbox vs. running without a sandbox.
//  - we currently use a very simple heuristic to decide whether a system call
//    is blocking or not. Blocking system calls should not be included in the
//    computations. But it is quite possible for the numbers to be somewhat
//    wrong, because the heuristic failed.
//  - in order to collect this data, we have to turn on sandbox debugging.
//    There is a measurable performance penalty to doing so. Production numbers
//    are strictly better than the numbers reported by this tool.
#include <set>
#include <vector>

#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>

static const int kAvgWindowSizeMs  =    500;
static const int kPeakWindowSizeMs = 2*1000;

// Class containing information on a single system call. Most notably, it
// contains the time when the system call happened, and the time that it
// took to complete.
class Datum {
  friend class Data;
 public:
  Datum(const char* name, double ms)
    : name_(name),
      ms_(ms) {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    timestamp_ = tv.tv_sec*1000.0 + tv.tv_usec/1000.0;
  }
  virtual ~Datum() { }

  double operator-(const Datum& b) {
    return timestamp_ - b.timestamp_;
  }

 protected:
  const char* name_;
  double      ms_;
  double      timestamp_;
};

// Class containing data on the most recent system calls. It maintains
// sliding averages for total CPU time used, and it also maintains a peak
// CPU usage. The peak usage is usually updated slower than the average
// usage, as that makes it easier to inspect visually.
class Data {
 public:
  Data() { }
  virtual ~Data() { }

  void addData(const char* name, double ms) {
    average_.push_back(Datum(name, ms));
    peak_.push_back(Datum(name, ms));

    // Prune entries outside of the window
    std::vector<Datum>::iterator iter;
    for (iter = average_.begin();
         *average_.rbegin() - *iter > kAvgWindowSizeMs;
         ++iter) {
    }
    average_.erase(average_.begin(), iter);

    for (iter = peak_.begin();
         *peak_.rbegin() - *iter > kPeakWindowSizeMs;
         ++iter){
    }
    peak_.erase(peak_.begin(), iter);

    // Add the total usage of all system calls inside of the window
    double total = 0;
    for (iter = average_.begin(); iter != average_.end(); ++iter) {
      total += iter->ms_;
    }

    // Compute the peak CPU usage during the last window
    double peak = 0;
    double max = 0;
    std::vector<Datum>::iterator tail = peak_.begin();
    for (iter = tail; iter != peak_.end(); ++iter) {
      while (*iter - *tail > kAvgWindowSizeMs) {
        peak -= tail->ms_;
        ++tail;
      }
      peak += iter->ms_;
      if (peak > max) {
        max = peak;
      }
    }

    // Print the average CPU usage in the last window
    char buf[80];
    total *= 100.0/kAvgWindowSizeMs;
    max   *= 100.0/kAvgWindowSizeMs;
    sprintf(buf, "%6.2f%% (peak=%6.2f%%) ", total, max);

    // Animate the actual usage, displaying both average and peak values
    int len   = strlen(buf);
    int space = sizeof(buf) - len - 1;
    int mark  = (total * space + 50)/100;
    int bar   = (max   * space + 50)/100;
    for (int i = 0; i < mark; ++i) {
      buf[len++] = '*';
    }
    if (mark == bar) {
      if (bar) {
        len--;
      }
    } else {
      for (int i = 0; i < bar - mark - 1; ++i) {
        buf[len++] = ' ';
      }
    }
    buf[len++] = '|';
    while (len < static_cast<int>(sizeof(buf))) {
      buf[len++] = ' ';
    }
    strcpy(buf + len, "\r");
    fwrite(buf, len + 1, 1, stdout);
    fflush(stdout);
  }

 private:
  std::vector<Datum> average_;
  std::vector<Datum> peak_;
};
static Data data;

int main(int argc, char *argv[]) {
  char buf[80];
  bool expensive = false;
  while (fgets(buf, sizeof(buf), stdin)) {
    // Allow longer delays for expensive system calls
    if (strstr(buf, "This is an expensive system call")) {
      expensive = true;
      continue;
    }

    // Parse the string and extract the elapsed time
    const char elapsed[] = "Elapsed time: ";
    char* ms_string = strstr(buf, elapsed);
    char* endptr;
    double ms;
    char* colon = strchr(buf, ':');

    // If this string doesn't match, then it must be some other type of
    // message. Just ignore it.
    // It is quite likely that we will regularly encounter debug messages
    // that either should be parsed by a completely different tool, or
    // messages that were intended for humans to read.
    if (!ms_string ||
        ((ms = strtod(ms_string + sizeof(elapsed) - 1, &endptr)),
         endptr == ms_string) ||
        !colon) {
      continue;
    }

    // Filter out system calls that were probably just blocking
    // TODO(markus): automatically compute the cut-off for blocking calls
    if (!expensive && ms > 0.05) {
      continue;
    }
    expensive = false;

    // Extract the name of the system call
    *colon = '\000';

    // Add the data point and update the display
    data.addData(buf, ms);
  }
  puts("");
  return 0;
}
<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkProperties.h"

#include "mitkCommandLineParser.h"
#include "mitkIOUtil.h"

#include <itksys/SystemTools.hxx>

#include "mitkPreferenceListReaderOptionsFunctor.h"

int main(int argc, char* argv[])
{
  mitkCommandLineParser parser;

  parser.setTitle("File Converter");
  parser.setCategory("Basic Image Processing");
  parser.setDescription("");
  parser.setContributor("MBI");

  parser.setArgumentPrefix("--","-");
  // Add command line argument names
  parser.addArgument("help", "h",mitkCommandLineParser::Bool, "Help:", "Show this help text");
  parser.addArgument("input", "i", mitkCommandLineParser::InputFile, "Input file:", "Input File",us::Any(),false);
  parser.addArgument("output", "o", mitkCommandLineParser::OutputFile, "Output file:", "Output file", us::Any(), false);
  parser.addArgument("reader", "r", mitkCommandLineParser::String, "Reader Name", "Reader Name", us::Any());
  parser.addArgument("list-readers", "lr", mitkCommandLineParser::Bool, "Reader Name", "Reader Name", us::Any());

  std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);

  if (parsedArgs.size()==0)
      return EXIT_FAILURE;

  // Show a help message
  if ( parsedArgs.count("help") || parsedArgs.count("h"))
  {
    std::cout << parser.helpText();
    return EXIT_SUCCESS;
  }

  std::string inputFilename = us::any_cast<std::string>(parsedArgs["input"]);
  std::string outputFilename = us::any_cast<std::string>(parsedArgs["output"]);

  mitk::PreferenceListReaderOptionsFunctor::ListType preference = {};
  if (parsedArgs.count("reader"))
  {
    preference.push_back(us::any_cast<std::string>(parsedArgs["reader"]));
  }

  if (parsedArgs.count("list-readers"))
  {
    mitk::IOUtil::LoadInfo loadInfo(inputFilename);
    auto readers = loadInfo.m_ReaderSelector.Get();

    std::string errMsg;
    if (readers.empty())
    {
      if (!itksys::SystemTools::FileExists(loadInfo.m_Path.c_str()))
      {
        errMsg += "File '" + loadInfo.m_Path + "' does not exist\n";
      }
      else
      {
        errMsg += "No reader available for '" + loadInfo.m_Path + "'\n";
      }
      MITK_ERROR << errMsg;
      return 0;
    }

    for (auto reader : loadInfo.m_ReaderSelector.Get())
    {
      std::cout  << " : " << reader.GetDescription() << std::endl;
    }
  }

  mitk::PreferenceListReaderOptionsFunctor::ListType emptyList = {};
  mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor(preference, emptyList);

  std::string extension = itksys::SystemTools::GetFilenameExtension(outputFilename);
  std::string filename = itksys::SystemTools::GetFilenameWithoutExtension(outputFilename);
  std::string path = itksys::SystemTools::GetFilenamePath(outputFilename);

  auto nodes = mitk::IOUtil::Load(inputFilename, &functor);

  unsigned count = 0;
  for (auto node : nodes)
  {
    std::string writeName = path + "/" + filename + extension;
    if (count > 0)
    {
      writeName = path + "/" + filename + "_" + std::to_string(count) + extension;
    }
    mitk::IOUtil::Save(node, writeName);
    ++count;
  }

  return EXIT_SUCCESS;
}
<commit_msg>Extended FileConverter<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkProperties.h"

#include "mitkCommandLineParser.h"
#include "mitkIOUtil.h"

#include <itksys/SystemTools.hxx>

#include "mitkPreferenceListReaderOptionsFunctor.h"

int main(int argc, char* argv[])
{
  mitkCommandLineParser parser;

  parser.setTitle("File Converter");
  parser.setCategory("Basic Image Processing");
  parser.setDescription("");
  parser.setContributor("MBI");

  parser.setArgumentPrefix("--","-");
  // Add command line argument names
  parser.addArgument("help", "h",mitkCommandLineParser::Bool, "Help:", "Show this help text");
  parser.addArgument("input", "i", mitkCommandLineParser::InputFile, "Input file:", "Input File",us::Any(),false);
  parser.addArgument("output", "o", mitkCommandLineParser::OutputFile, "Output file:", "Output file", us::Any(), false);
  parser.addArgument("reader", "r", mitkCommandLineParser::String, "Reader Name", "Reader Name", us::Any());
  parser.addArgument("list-readers", "lr", mitkCommandLineParser::Bool, "Reader Name", "Reader Name", us::Any());

  std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);

  if (parsedArgs.size()==0)
      return EXIT_FAILURE;

  // Show a help message
  if ( parsedArgs.count("help") || parsedArgs.count("h"))
  {
    std::cout << parser.helpText();
    return EXIT_SUCCESS;
  }

  std::string inputFilename = us::any_cast<std::string>(parsedArgs["input"]);
  std::string outputFilename = us::any_cast<std::string>(parsedArgs["output"]);

  mitk::PreferenceListReaderOptionsFunctor::ListType preference = {};
  if (parsedArgs.count("reader"))
  {
    preference.push_back(us::any_cast<std::string>(parsedArgs["reader"]));
  }

  if (parsedArgs.count("list-readers"))
  {
    mitk::IOUtil::LoadInfo loadInfo(inputFilename);
    auto readers = loadInfo.m_ReaderSelector.Get();

    std::string errMsg;
    if (readers.empty())
    {
      if (!itksys::SystemTools::FileExists(loadInfo.m_Path.c_str()))
      {
        errMsg += "File '" + loadInfo.m_Path + "' does not exist\n";
      }
      else
      {
        errMsg += "No reader available for '" + loadInfo.m_Path + "'\n";
      }
      MITK_ERROR << errMsg;
      return 0;
    }

    std::cout << "Available Readers: "<<std::endl << "------------------------" << std::endl;
    for (auto reader : loadInfo.m_ReaderSelector.Get())
    {
      std::cout  << " : " << reader.GetDescription() << std::endl;
    }
    return 0;
  }

  mitk::PreferenceListReaderOptionsFunctor::ListType emptyList = {};
  mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor(preference, emptyList);

  std::string extension = itksys::SystemTools::GetFilenameExtension(outputFilename);
  std::string filename = itksys::SystemTools::GetFilenameWithoutExtension(outputFilename);
  std::string path = itksys::SystemTools::GetFilenamePath(outputFilename);

  auto nodes = mitk::IOUtil::Load(inputFilename, &functor);

  unsigned count = 0;
  for (auto node : nodes)
  {
    std::string writeName = path + "/" + filename + extension;
    if (count > 0)
    {
      writeName = path + "/" + filename + "_" + std::to_string(count) + extension;
    }
    mitk::IOUtil::Save(node, writeName);
    ++count;
  }

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#ifndef PLAYERINFOPANEWIDGET_HPP
#define PLAYERINFOPANEWIDGET_HPP

#include <QWidget>
#include "Logics/Entities/OwPlayer.hpp"

namespace Ui
{
class PlayerInfoPaneWidget;
}

class PlayerInfoPaneWidget : public QWidget
{
    Q_OBJECT

private:
    Ui::PlayerInfoPaneWidget *ui;
    OwPlayer player;
    bool isPlayerInfoDirty = false;

public:
    explicit PlayerInfoPaneWidget(QWidget *parent, OwPlayer player);
    ~PlayerInfoPaneWidget(void);

protected:
    virtual bool eventFilter(QObject * object, QEvent * event) override;

private:
    void updateStatsSiteButtons(void);
    void updateToolButtons(void);

    void saveCurrentPlayerInfo(void);

signals:
    void playerInfoChanged(const OwPlayer & player);

private slots:
    void on_toolButton_savePlayerInfo_clicked(void);
    void on_toolButton_updatePlayerInfo_clicked(void);
    void on_toolButton_deletePlayerInfo_clicked(void);
    void on_lineEdit_playerBattleTag_textEdited(const QString & newBattleTag);
    void on_comboBox_owRegion_currentIndexChanged(const QString & region);
    void on_plainTextEdit_playerNote_textChanged(void);
    void on_checkBox_isFavorite_toggled(bool checked);
    void on_radioButton_likesPlayer_toggled(bool checked);
    void on_radioButto_undecidedPlayer_toggled(bool checked);
    void on_radioButton_dislikesPlayer_toggled(bool checked);
    void on_toolButton_openUrlPlayOverwatch_clicked();
    void on_toolButton_openUrlMasterOverwatch_clicked();
    void on_toolButton_openUrlOverbuff_clicked();
};

#endif // PLAYERINFOPANEWIDGET_HPP
<commit_msg>reformat code<commit_after>#ifndef PLAYERINFOPANEWIDGET_HPP
#define PLAYERINFOPANEWIDGET_HPP

#include <QWidget>
#include "Logics/Entities/OwPlayer.hpp"

namespace Ui
{
class PlayerInfoPaneWidget;
}

class PlayerInfoPaneWidget : public QWidget
{
    Q_OBJECT

private:
    Ui::PlayerInfoPaneWidget *ui;
    OwPlayer player;
    bool isPlayerInfoDirty = false;

public:
    explicit PlayerInfoPaneWidget(QWidget *parent, OwPlayer player);
    ~PlayerInfoPaneWidget(void);

protected:
    virtual bool eventFilter(QObject * object, QEvent * event) override;

private:
    void updateStatsSiteButtons(void);
    void updateToolButtons(void);

    void saveCurrentPlayerInfo(void);

signals:
    void playerInfoChanged(const OwPlayer & player);

private slots:
    void on_toolButton_savePlayerInfo_clicked(void);
    void on_toolButton_updatePlayerInfo_clicked(void);
    void on_toolButton_deletePlayerInfo_clicked(void);
    void on_lineEdit_playerBattleTag_textEdited(const QString & newBattleTag);
    void on_comboBox_owRegion_currentIndexChanged(const QString & region);
    void on_plainTextEdit_playerNote_textChanged(void);
    void on_checkBox_isFavorite_toggled(bool checked);
    void on_radioButton_likesPlayer_toggled(bool checked);
    void on_radioButto_undecidedPlayer_toggled(bool checked);
    void on_radioButton_dislikesPlayer_toggled(bool checked);
    void on_toolButton_openUrlPlayOverwatch_clicked(void);
    void on_toolButton_openUrlMasterOverwatch_clicked(void);
    void on_toolButton_openUrlOverbuff_clicked(void);
};

#endif // PLAYERINFOPANEWIDGET_HPP
<|endoftext|>


<commit_before>/* $Id$ */

/* The Next Great Finite Element Library. */
/* Copyright (C) 2003  Benjamin S. Kirk */

/* 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 */

 //
Example 28 - Meshing with LibMesh's TetGen and Triangle Interfaces

 //
 // LibMesh provides interfaces to both Triangle and TetGen for generating
 // Delaunay triangulations and tetrahedralizations in two and three dimensions
 // (respectively).

// Local header files
#include "mesh.h"
#include "mesh_triangle_support.h"
#include "mesh_generation.h"
#include "elem.h"
#include "mesh_tetgen_support.h"
#include "node.h"
#include "face_tri3.h"

// Bring in everything from the libMesh namespace
using namespace libMesh;

// Major functions called by main
void triangulate_domain();
void tetrahedralize_domain();

// Convenient data structure for holding/passing Mesh parameters
// for the tetrahedralize function.
struct MeshParams
{
  Real domain_x;
  Real domain_y;
  Real domain_z;
  Real hole_radius;
  Real hole_xpos;
  Real hole_ypos;
  Real hole_zpos;
};

// Helper routines for tetrahedralize_domain()
void add_sphere_surface_points_to_mesh(MeshBase& mesh,
				       Real radius,
				       unsigned refinements,
				       Point sphere_center);

void add_boundary_tris(MeshBase& mesh, MeshParams& mesh_params);

// Begin the main program.
int main (int argc, char** argv)
{
  // Initialize libMesh and any dependent libaries, like in example 2.
  LibMeshInit init (argc, argv);

  libmesh_example_assert(2 <= LIBMESH_DIM, "2D support");

  // Triangle is supposed to support non-double precision, but it hits
  // segfaults or infinite loops when we try it on this example
  libmesh_example_assert(LIBMESH_DEFAULT_DOUBLE_PRECISION, "default (double) precision");

  std::cout << "Triangulating an L-shaped domain with holes" << std::endl;

  // 1.) 2D triangulation of L-shaped domain with three holes of different shape
  triangulate_domain();

  libmesh_example_assert(3 <= LIBMESH_DIM, "3D support");

  //std::cout << "Tetrahedralizing a prism domain with a spherical hole" << std::endl;

  // 2.) 3D tetrahedralization of rectangular domain with spherical hole
  // Disabling this for now - I get an infinite loop in tetgen.C  (in
  // two different places with two different tetgen versions...) - RHS
  // tetrahedralize_domain();

  return 0;
}

void triangulate_domain()
{
  // Use typedefs for slightly less typing.
  typedef TriangleInterface::Hole Hole;
  typedef TriangleInterface::PolygonHole PolygonHole;
  typedef TriangleInterface::ArbitraryHole ArbitraryHole;

  // Libmesh mesh that will eventually be created.
  Mesh mesh(2);

  // The points which make up the L-shape:
  mesh.add_point(Point( 0. ,  0.));
  mesh.add_point(Point( 0. , -1.));
  mesh.add_point(Point(-1. , -1.));
  mesh.add_point(Point(-1. ,  1.));
  mesh.add_point(Point( 1. ,  1.));
  mesh.add_point(Point( 1. ,  0.));

  // Declare the TriangleInterface object.  This is where
  // we can set parameters of the triangulation and where the
  // actual triangulate function lives.
  TriangleInterface t(mesh);

  // Customize the variables for the triangulation
  t.desired_area()       = .01;

  // A Planar Straight Line Graph (PSLG) is essentially a list
  // of segments which have to exist in the final triangulation.
  // For an L-shaped domain, Triangle will compute the convex
  // hull of boundary points if we do not specify the PSLG.
  // The PSLG algorithm is also required for triangulating domains
  // containing holes
  t.triangulation_type() = TriangleInterface::PSLG;

  // Define holes...

  // hole_1 is a circle (discretized by 50 points)
  PolygonHole hole_1(Point(-0.5,  0.5), // center
		     0.25,              // radius
		     50);               // n. points

  // hole_2 is itself a triangle
  PolygonHole hole_2(Point(0.5, 0.5),   // center
		     0.1,               // radius
		     3);                // n. points

  // hole_3 is an ellipse of 100 points which we define here
  Point ellipse_center(-0.5,  -0.5);
  const unsigned int n_ellipse_points=100;
  std::vector<Point> ellipse_points(n_ellipse_points);
  const Real
    dtheta = 2*libMesh::pi / static_cast<Real>(n_ellipse_points),
    a = .1,
    b = .2;

  for (unsigned int i=0; i<n_ellipse_points; ++i)
    ellipse_points[i]= Point(ellipse_center(0)+a*cos(i*dtheta),
			     ellipse_center(1)+b*sin(i*dtheta));

  ArbitraryHole hole_3(ellipse_center, ellipse_points);

  // Create the vector of Hole*'s ...
  std::vector<Hole*> holes;
  holes.push_back(&hole_1);
  holes.push_back(&hole_2);
  holes.push_back(&hole_3);

  // ... and attach it to the triangulator object
  t.attach_hole_list(&holes);

  // Triangulate!
  t.triangulate();

  // Write the result to file
  mesh.write("delaunay_l_shaped_hole.e");
}

void tetrahedralize_domain()
{
  // The algorithm is broken up into N steps: we must generate a convex hull
  // of TRI3 surfaces defining the boundary before we can tetrahedralize its
  // interior.

  // 1.) build_sphere() generates the points on the surface of a sphere
  // 2.) Use Tetgen to generate the convex hull of the sphere's surface
  // 3.) Generate elements comprising the outer boundary of the domain.
  // 4.) Tetrahedralize the interior of the domain

  // The mesh we will eventually generate
  Mesh mesh(3);

  // Object to hold all the mesh parameters
  MeshParams mp;

  mp.domain_x = 1.;
  mp.domain_y = 1.;
  mp.domain_z = 1.;
  mp.hole_radius = .25;
  mp.hole_xpos = .5;
  mp.hole_ypos = .5;
  mp.hole_zpos = .5;

  // A Point object used to mark the interior of the spherical hole
  Point hole_center(mp.hole_xpos,
		    mp.hole_ypos,
		    mp.hole_zpos);

  // 1.) Use build_sphere() to generate surface points on the sphere
  add_sphere_surface_points_to_mesh(mesh,
				    mp.hole_radius,
				    /*refinements=*/3,
				    hole_center);

  // 2.) Use Tetgen to generate the convex hull of the sphere's surface
  TetGenMeshInterface t(mesh);
  t.pointset_convexhull();

  // 3.) Generate elements comprising the outer boundary of the domain.
  add_boundary_tris(mesh, mp);

  // Also update neighbor information so that TetGen can verify there is
  // a convex hull.
  mesh.find_neighbors();

  // 4.) Tetrahedralize the interior of the domain with a hole cut out.
  Node hole_node(hole_center);
  std::vector<Node*> hole(1);
  hole[0] = &hole_node;

  // 0 means "use TetGen default value"
  Real quality_constraint = 0.;

  // The volume constraint determines the max-allowed tetrahedral
  // volume in the Mesh.  TetGen will split cells which are larger than
  // this size
  Real volume_constraint = .001;

  t.triangulate_conformingDelaunayMesh_carvehole(hole,
						 quality_constraint,
						 volume_constraint);

  // Find neighbors, etc in preparation for writing out the Mesh
  mesh.prepare_for_use();

  // Finally, write out the result
  mesh.write("sphere_hole.e");
}

void add_sphere_surface_points_to_mesh(MeshBase& mesh,
				       Real radius,
				       unsigned refinements,
				       Point sphere_center)
{
  // n_refinements=3 leads to 386 nodes on the sphere
  // n_refinements=4 leads to 1538 nodes on the sphere

  // Note: to use build_sphere, you currently must disable the Laplace mesh smoothing
  // in that function, it currently dies with a weird error if we try to do it...
  Mesh sphere_mesh(3);
  MeshTools::Generation::build_sphere(sphere_mesh, radius, refinements, HEX8);
  //sphere_mesh.write("sphere_mesh.e");

  std::set<unsigned> boundary_node_ids;

  // Loop over elements, find sides on boundary, add node IDs to boundary node set
  {
    MeshBase::element_iterator it = sphere_mesh.elements_begin();
    const MeshBase::element_iterator end = sphere_mesh.elements_end();
    for ( ; it != end; ++it)
      {
	Elem* elem = *it;

	for (unsigned s=0; s<elem->n_sides(); ++s)
	  if (elem->neighbor(s) == NULL)
	    {
	      // Add the elements of this side to the set
	      AutoPtr<Elem> side = elem->side(s);

	      for (unsigned n=0; n<side->n_nodes(); ++n)
		boundary_node_ids.insert( side->node(n) );
	    }
      }

  }

  // For all the boundary_node_ids, add them to the real Mesh
  {
    MeshBase::node_iterator it = sphere_mesh.nodes_begin();
    const MeshBase::node_iterator end = sphere_mesh.nodes_end();
    for ( ; it != end; ++it)
      {
	Node* node = *it;

	if ( boundary_node_ids.find(node->id()) != boundary_node_ids.end() )
	  {
	    mesh.add_point (*node + sphere_center);
	  }
      }
  }
}

void add_boundary_tris(MeshBase& mesh, MeshParams& mesh_params)
{
  // This function uses build_cube and tetgen to generate a convex hull of
  // the *outer* boundary, then adds those new points and elements to the
  // input mesh, thereby creating an outer boundary for the domain.
  Mesh outer_mesh(3);

  MeshTools::Generation::build_cube(outer_mesh,
				    1,1,1, // 1 element in each direction => 1 total element
				    0., mesh_params.domain_x,
				    0., mesh_params.domain_y,
				    0., mesh_params.domain_z,
				    HEX8);

  // The pointset_convexhull() algorithm will ignore the single Hex8
  // that's sitting in the Mesh, and just construct the triangulation
  // of the convex hull.
  TetGenMeshInterface t(outer_mesh);
  t.pointset_convexhull();

  // Now add all nodes from the boundary of the outer_mesh to the input mesh.
  // There should only be 8!  Store the IDs they are assigned by the input mesh.
  std::vector<unsigned> new_node_ids;
  new_node_ids.reserve(8);
  {
    MeshBase::node_iterator       node_it  = outer_mesh.nodes_begin();
    const MeshBase::node_iterator node_end = outer_mesh.nodes_end();
    for (; node_it != node_end; ++node_it)
      {
	// Grab a pointer to the node
	Node* old_node = *node_it;

	// Check that old_node is sequentially numbered?
	if (old_node->id() != new_node_ids.size())
	  {
	    libMesh::err << "Error, node IDs from build cube are not sequential!" << std::endl;
	    libmesh_error();
	  }

	// Add it to the input mesh, and catch the returned pointer
	Node* new_node = mesh.add_point (*old_node);

	// Store that ID so we can get a pointer to it later.
	new_node_ids.push_back(new_node->id());
      }
  }

  // Check to be sure that we didn't add too many/few nodes
  if (new_node_ids.size() != 8)
    libMesh::err << "Too many nodes found in outer_mesh!" << std::endl;

  // For each TRI3 element in the outer_mesh, add it to the input Mesh
  // with proper node assignments
  {
    MeshBase::element_iterator       el     = outer_mesh.elements_begin();
    const MeshBase::element_iterator end_el = outer_mesh.elements_end();

    for (; el != end_el; ++el)
      {
	Elem* old_elem = *el;

	if (old_elem->type() == TRI3)
	  {
	    Elem* new_elem = mesh.add_elem(new Tri3);

	    // Assign nodes in new elements.  Since this is an example,
	    // we'll do it in several steps.
	    for (unsigned i=0; i<old_elem->n_nodes(); ++i)
	      {
		// Node ID in the temporary mesh
		unsigned old_node_id = old_elem->node(i);

		// Mapping to node ID in input mesh
		unsigned new_node_id = new_node_ids[old_node_id];

		// Node pointer assigned from input mesh
		new_elem->set_node(i) = mesh.node_ptr(new_node_id);
	      }
	  }
      }
  }
}
<commit_msg>ex29 ought to work on non-double-precision libMesh now; let's try it.<commit_after>/* $Id$ */

/* The Next Great Finite Element Library. */
/* Copyright (C) 2003  Benjamin S. Kirk */

/* 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 */

 //
Example 28 - Meshing with LibMesh's TetGen and Triangle Interfaces

 //
 // LibMesh provides interfaces to both Triangle and TetGen for generating
 // Delaunay triangulations and tetrahedralizations in two and three dimensions
 // (respectively).

// Local header files
#include "mesh.h"
#include "mesh_triangle_support.h"
#include "mesh_generation.h"
#include "elem.h"
#include "mesh_tetgen_support.h"
#include "node.h"
#include "face_tri3.h"

// Bring in everything from the libMesh namespace
using namespace libMesh;

// Major functions called by main
void triangulate_domain();
void tetrahedralize_domain();

// Convenient data structure for holding/passing Mesh parameters
// for the tetrahedralize function.
struct MeshParams
{
  Real domain_x;
  Real domain_y;
  Real domain_z;
  Real hole_radius;
  Real hole_xpos;
  Real hole_ypos;
  Real hole_zpos;
};

// Helper routines for tetrahedralize_domain()
void add_sphere_surface_points_to_mesh(MeshBase& mesh,
				       Real radius,
				       unsigned refinements,
				       Point sphere_center);

void add_boundary_tris(MeshBase& mesh, MeshParams& mesh_params);

// Begin the main program.
int main (int argc, char** argv)
{
  // Initialize libMesh and any dependent libaries, like in example 2.
  LibMeshInit init (argc, argv);

  libmesh_example_assert(2 <= LIBMESH_DIM, "2D support");

  std::cout << "Triangulating an L-shaped domain with holes" << std::endl;

  // 1.) 2D triangulation of L-shaped domain with three holes of different shape
  triangulate_domain();

  libmesh_example_assert(3 <= LIBMESH_DIM, "3D support");

  //std::cout << "Tetrahedralizing a prism domain with a spherical hole" << std::endl;

  // 2.) 3D tetrahedralization of rectangular domain with spherical hole
  // Disabling this for now - I get an infinite loop in tetgen.C  (in
  // two different places with two different tetgen versions...) - RHS
  // tetrahedralize_domain();

  return 0;
}

void triangulate_domain()
{
  // Use typedefs for slightly less typing.
  typedef TriangleInterface::Hole Hole;
  typedef TriangleInterface::PolygonHole PolygonHole;
  typedef TriangleInterface::ArbitraryHole ArbitraryHole;

  // Libmesh mesh that will eventually be created.
  Mesh mesh(2);

  // The points which make up the L-shape:
  mesh.add_point(Point( 0. ,  0.));
  mesh.add_point(Point( 0. , -1.));
  mesh.add_point(Point(-1. , -1.));
  mesh.add_point(Point(-1. ,  1.));
  mesh.add_point(Point( 1. ,  1.));
  mesh.add_point(Point( 1. ,  0.));

  // Declare the TriangleInterface object.  This is where
  // we can set parameters of the triangulation and where the
  // actual triangulate function lives.
  TriangleInterface t(mesh);

  // Customize the variables for the triangulation
  t.desired_area()       = .01;

  // A Planar Straight Line Graph (PSLG) is essentially a list
  // of segments which have to exist in the final triangulation.
  // For an L-shaped domain, Triangle will compute the convex
  // hull of boundary points if we do not specify the PSLG.
  // The PSLG algorithm is also required for triangulating domains
  // containing holes
  t.triangulation_type() = TriangleInterface::PSLG;

  // Define holes...

  // hole_1 is a circle (discretized by 50 points)
  PolygonHole hole_1(Point(-0.5,  0.5), // center
		     0.25,              // radius
		     50);               // n. points

  // hole_2 is itself a triangle
  PolygonHole hole_2(Point(0.5, 0.5),   // center
		     0.1,               // radius
		     3);                // n. points

  // hole_3 is an ellipse of 100 points which we define here
  Point ellipse_center(-0.5,  -0.5);
  const unsigned int n_ellipse_points=100;
  std::vector<Point> ellipse_points(n_ellipse_points);
  const Real
    dtheta = 2*libMesh::pi / static_cast<Real>(n_ellipse_points),
    a = .1,
    b = .2;

  for (unsigned int i=0; i<n_ellipse_points; ++i)
    ellipse_points[i]= Point(ellipse_center(0)+a*cos(i*dtheta),
			     ellipse_center(1)+b*sin(i*dtheta));

  ArbitraryHole hole_3(ellipse_center, ellipse_points);

  // Create the vector of Hole*'s ...
  std::vector<Hole*> holes;
  holes.push_back(&hole_1);
  holes.push_back(&hole_2);
  holes.push_back(&hole_3);

  // ... and attach it to the triangulator object
  t.attach_hole_list(&holes);

  // Triangulate!
  t.triangulate();

  // Write the result to file
  mesh.write("delaunay_l_shaped_hole.e");
}

void tetrahedralize_domain()
{
  // The algorithm is broken up into N steps: we must generate a convex hull
  // of TRI3 surfaces defining the boundary before we can tetrahedralize its
  // interior.

  // 1.) build_sphere() generates the points on the surface of a sphere
  // 2.) Use Tetgen to generate the convex hull of the sphere's surface
  // 3.) Generate elements comprising the outer boundary of the domain.
  // 4.) Tetrahedralize the interior of the domain

  // The mesh we will eventually generate
  Mesh mesh(3);

  // Object to hold all the mesh parameters
  MeshParams mp;

  mp.domain_x = 1.;
  mp.domain_y = 1.;
  mp.domain_z = 1.;
  mp.hole_radius = .25;
  mp.hole_xpos = .5;
  mp.hole_ypos = .5;
  mp.hole_zpos = .5;

  // A Point object used to mark the interior of the spherical hole
  Point hole_center(mp.hole_xpos,
		    mp.hole_ypos,
		    mp.hole_zpos);

  // 1.) Use build_sphere() to generate surface points on the sphere
  add_sphere_surface_points_to_mesh(mesh,
				    mp.hole_radius,
				    /*refinements=*/3,
				    hole_center);

  // 2.) Use Tetgen to generate the convex hull of the sphere's surface
  TetGenMeshInterface t(mesh);
  t.pointset_convexhull();

  // 3.) Generate elements comprising the outer boundary of the domain.
  add_boundary_tris(mesh, mp);

  // Also update neighbor information so that TetGen can verify there is
  // a convex hull.
  mesh.find_neighbors();

  // 4.) Tetrahedralize the interior of the domain with a hole cut out.
  Node hole_node(hole_center);
  std::vector<Node*> hole(1);
  hole[0] = &hole_node;

  // 0 means "use TetGen default value"
  Real quality_constraint = 0.;

  // The volume constraint determines the max-allowed tetrahedral
  // volume in the Mesh.  TetGen will split cells which are larger than
  // this size
  Real volume_constraint = .001;

  t.triangulate_conformingDelaunayMesh_carvehole(hole,
						 quality_constraint,
						 volume_constraint);

  // Find neighbors, etc in preparation for writing out the Mesh
  mesh.prepare_for_use();

  // Finally, write out the result
  mesh.write("sphere_hole.e");
}

void add_sphere_surface_points_to_mesh(MeshBase& mesh,
				       Real radius,
				       unsigned refinements,
				       Point sphere_center)
{
  // n_refinements=3 leads to 386 nodes on the sphere
  // n_refinements=4 leads to 1538 nodes on the sphere

  // Note: to use build_sphere, you currently must disable the Laplace mesh smoothing
  // in that function, it currently dies with a weird error if we try to do it...
  Mesh sphere_mesh(3);
  MeshTools::Generation::build_sphere(sphere_mesh, radius, refinements, HEX8);
  //sphere_mesh.write("sphere_mesh.e");

  std::set<unsigned> boundary_node_ids;

  // Loop over elements, find sides on boundary, add node IDs to boundary node set
  {
    MeshBase::element_iterator it = sphere_mesh.elements_begin();
    const MeshBase::element_iterator end = sphere_mesh.elements_end();
    for ( ; it != end; ++it)
      {
	Elem* elem = *it;

	for (unsigned s=0; s<elem->n_sides(); ++s)
	  if (elem->neighbor(s) == NULL)
	    {
	      // Add the elements of this side to the set
	      AutoPtr<Elem> side = elem->side(s);

	      for (unsigned n=0; n<side->n_nodes(); ++n)
		boundary_node_ids.insert( side->node(n) );
	    }
      }

  }

  // For all the boundary_node_ids, add them to the real Mesh
  {
    MeshBase::node_iterator it = sphere_mesh.nodes_begin();
    const MeshBase::node_iterator end = sphere_mesh.nodes_end();
    for ( ; it != end; ++it)
      {
	Node* node = *it;

	if ( boundary_node_ids.find(node->id()) != boundary_node_ids.end() )
	  {
	    mesh.add_point (*node + sphere_center);
	  }
      }
  }
}

void add_boundary_tris(MeshBase& mesh, MeshParams& mesh_params)
{
  // This function uses build_cube and tetgen to generate a convex hull of
  // the *outer* boundary, then adds those new points and elements to the
  // input mesh, thereby creating an outer boundary for the domain.
  Mesh outer_mesh(3);

  MeshTools::Generation::build_cube(outer_mesh,
				    1,1,1, // 1 element in each direction => 1 total element
				    0., mesh_params.domain_x,
				    0., mesh_params.domain_y,
				    0., mesh_params.domain_z,
				    HEX8);

  // The pointset_convexhull() algorithm will ignore the single Hex8
  // that's sitting in the Mesh, and just construct the triangulation
  // of the convex hull.
  TetGenMeshInterface t(outer_mesh);
  t.pointset_convexhull();

  // Now add all nodes from the boundary of the outer_mesh to the input mesh.
  // There should only be 8!  Store the IDs they are assigned by the input mesh.
  std::vector<unsigned> new_node_ids;
  new_node_ids.reserve(8);
  {
    MeshBase::node_iterator       node_it  = outer_mesh.nodes_begin();
    const MeshBase::node_iterator node_end = outer_mesh.nodes_end();
    for (; node_it != node_end; ++node_it)
      {
	// Grab a pointer to the node
	Node* old_node = *node_it;

	// Check that old_node is sequentially numbered?
	if (old_node->id() != new_node_ids.size())
	  {
	    libMesh::err << "Error, node IDs from build cube are not sequential!" << std::endl;
	    libmesh_error();
	  }

	// Add it to the input mesh, and catch the returned pointer
	Node* new_node = mesh.add_point (*old_node);

	// Store that ID so we can get a pointer to it later.
	new_node_ids.push_back(new_node->id());
      }
  }

  // Check to be sure that we didn't add too many/few nodes
  if (new_node_ids.size() != 8)
    libMesh::err << "Too many nodes found in outer_mesh!" << std::endl;

  // For each TRI3 element in the outer_mesh, add it to the input Mesh
  // with proper node assignments
  {
    MeshBase::element_iterator       el     = outer_mesh.elements_begin();
    const MeshBase::element_iterator end_el = outer_mesh.elements_end();

    for (; el != end_el; ++el)
      {
	Elem* old_elem = *el;

	if (old_elem->type() == TRI3)
	  {
	    Elem* new_elem = mesh.add_elem(new Tri3);

	    // Assign nodes in new elements.  Since this is an example,
	    // we'll do it in several steps.
	    for (unsigned i=0; i<old_elem->n_nodes(); ++i)
	      {
		// Node ID in the temporary mesh
		unsigned old_node_id = old_elem->node(i);

		// Mapping to node ID in input mesh
		unsigned new_node_id = new_node_ids[old_node_id];

		// Node pointer assigned from input mesh
		new_elem->set_node(i) = mesh.node_ptr(new_node_id);
	      }
	  }
      }
  }
}
<|endoftext|>