<commit_before>/*
 * Copyright 2013 Matthew Harvey
 *
 * 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 "date.hpp"
#include "date_parser.hpp"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/optional.hpp>
#include <boost/test/unit_test.hpp>
#include <iostream>

using boost::gregorian::date;
using boost::optional;
using std::cout;
using std::endl;

namespace dcm
{
namespace test
{

// %d  is for day component
// %m  is for month component
// %y  is for year component (2 digit)
// %Y  is for year component (full)
// Additional modifiers might possibly appear between the
// '%' and the format specifier.
// Note the above are not the only format specifiers that can possibly appear
// in a strftime-like string; but they are the only ones relevant when doing
// "tolerant" parsing.

BOOST_AUTO_TEST_CASE(test_date_parser_intolerant_parse)
{
	DateParser const dp0("%d %m %y", "%d %m %y");
	optional<date> const md0a = dp0.parse("13 10 2013");
	BOOST_CHECK(!md0a);
	optional<date> const md0b = dp0.parse("13 09 13");
	BOOST_CHECK(md0b);
	if (md0b) BOOST_CHECK_EQUAL(*md0b, date(2013, 9, 13));
	optional<date> const md0c = dp0.parse("13 9 13");
	BOOST_CHECK(md0c);
	if (md0c) BOOST_CHECK_EQUAL(*md0c, date(2013, 9, 13));
	optional<date> const md0d = dp0.parse("08 31 13", false);
	BOOST_CHECK(!md0d);
	optional<date> const md0e = dp0.parse("13 09");
	BOOST_CHECK(!md0e);
	optional<date> const md0f = dp0.parse("12 6 99", false);
	BOOST_CHECK(md0f);
	if (md0f) BOOST_CHECK_EQUAL(*md0f, date(1999, 6, 12));
	optional<date> const md0g = dp0.parse("13/10/2013");
	BOOST_CHECK(!md0g);
	optional<date> const md0h = dp0.parse("21");
	BOOST_CHECK(!md0h);

	DateParser const dp1("%d/%m/%y", "%d/%m/%y");
	optional<date> const md1a = dp1.parse("13/10/13");
	BOOST_CHECK(md1a);
	if (md1a) BOOST_CHECK_EQUAL(*md1a, date(2013, 10, 13));
	optional<date> const md1b = dp1.parse("13 10 13");
	BOOST_CHECK(!md1b);

	DateParser const dp2("%Y .. %d !!! %m", "%Y .. %d !!! %m");
	optional<date> const md2a = dp2.parse("3019 .. 4 !!! 1");
	BOOST_CHECK(md2a);
	if (md2a) BOOST_CHECK_EQUAL(*md2a, date(3019, 1, 4));
	optional<date> const md2b = dp2.parse("2019..4 !!! 1");
	BOOST_CHECK(md2b);
	if (md2b) BOOST_CHECK_EQUAL(*md2b, date(2019, 1, 4));
	optional<date> const md2c = dp2.parse("2019 4 1");
	BOOST_CHECK (!md2c);

	// Spaces in the format string can be skipped in the
	// candidate string.
	DateParser const dp3("%Y %m %d", "%Y %m %d");
	optional<date> const md3a = dp3.parse("20190619");
	BOOST_CHECK(md3a);
	if (md3a) BOOST_CHECK_EQUAL(*md3a, date(2019, 6, 19));
	optional<date> const md3b = dp3.parse("2019/06/19");
	BOOST_CHECK(!md3b);

	// But spaces cannot be inserted in the candidate string
	// if the format string doesn't allow for them.
	DateParser const dp4("%Y%m%d", "%Y%m%d");
	optional<date> const md4a = dp4.parse("20130619");
	BOOST_CHECK(md4a);
	if (md4a) BOOST_CHECK_EQUAL(*md4a, date(2013, 6, 19));
	optional<date> const md4b = dp4.parse("2013 06 19");
	BOOST_CHECK(!md4b);
	optional<date> const md4c = dp4.parse("2013 619");
	BOOST_CHECK(!md4c);

	// "%Y" can accept either 2-digit or 4-digit year.
	DateParser const dp5("%Y . %m . %d", "%Y . %m . %d");
	optional<date> const md5a = dp5.parse("2010.01.05");
	BOOST_CHECK(md5a);
	if (md5a) BOOST_CHECK_EQUAL(*md5a, date(2010, 1, 5));
	optional<date> const md5b = dp5.parse("10.05.05");
	BOOST_CHECK(md5b);
	if (md5b) BOOST_CHECK_EQUAL(*md5b, date(2010, 5, 5));
	// But "%y" will only accept 2-digit year
	DateParser const dp5x("%y . %m . %d", "%y . %m . %d");
	optional<date> const md5xa = dp5x.parse("2010.01.05");
	BOOST_CHECK(!md5xa);
	optional<date> const md5xb = dp5x.parse("10.01.05");
	BOOST_CHECK(md5xb);
	if (md5xb) BOOST_CHECK_EQUAL(*md5xb, date(2010, 1, 5));

	// Primary is format is used if possible
	DateParser const dp6("%y-%d-%m", "%y-%m-%d");
	optional<date> const md6a = dp6.parse("10-5-3");
	BOOST_CHECK(md6a);
	if (md6a) BOOST_CHECK_EQUAL(*md6a, date(2010, 3, 5));
	// But if not possible, secondary format is used.
	optional<date> const md6b = dp6.parse("10-12-14");
	BOOST_CHECK(md6b);
	if (md6b) BOOST_CHECK_EQUAL(*md6b, date(2010, 12, 14));
}

BOOST_AUTO_TEST_CASE(test_date_parser_tolerant_parse)
{
	DateParser const dp0("%d %m %y", "%d, %m, %y");
	optional<date> const md0a = dp0.parse("13 10 2013", true);
	BOOST_CHECK(md0a);
	if (md0a) BOOST_CHECK_EQUAL(*md0a, date(2013, 10, 13));
	optional<date> const md0b = dp0.parse("13 09 13", true);
	BOOST_CHECK(md0b);
	if (md0b) BOOST_CHECK_EQUAL(*md0b, date(2013, 9, 13));
	optional<date> const md0c = dp0.parse("13 9 13", true);
	BOOST_CHECK(md0c);
	if (md0c) BOOST_CHECK_EQUAL(*md0c, date(2013, 9, 13));
	optional<date> const md0d = dp0.parse("08 31 13", true);
	BOOST_CHECK(!md0d);
	optional<date> const md0e = dp0.parse("13 09", true);
	BOOST_CHECK(md0e);
	if (md0e) BOOST_CHECK_EQUAL(*md0e, date(today().year(), 9, 13));
	optional<date> const md0f = dp0.parse("12 6 99", true);
	BOOST_CHECK(md0f);
	if (md0f) BOOST_CHECK_EQUAL(*md0f, date(1999, 6, 12));
	optional<date> const md0g = dp0.parse("13/10/2013", true);
	BOOST_CHECK(!md0g);
	optional<date> const md0h = dp0.parse("0000030 010 00002013", true);
	BOOST_CHECK(md0h);
	if (md0h) BOOST_CHECK_EQUAL(*md0h, date(2013, 10, 30));
	optional<date> const md0i = dp0.parse("21", true);
	BOOST_CHECK(md0i);
	if (md0i) BOOST_CHECK_EQUAL(md0i, date(today().year(), today().month(), 21));

	DateParser const dp1("%d/%m/%y", "%d/%m/%y");
	optional<date> const md1a = dp1.parse("13/10/13", true);
	BOOST_CHECK(md1a);
	if (md1a) BOOST_CHECK_EQUAL(*md1a, date(2013, 10, 13));
	optional<date> const md1b = dp1.parse("13 10 13", true);
	BOOST_CHECK(!md1b);

	DateParser const dp2("%Y .. %d !!! %m", "%Y .. %d !! %m");
	optional<date> const md2a = dp2.parse("3019 .. 4 !!! 1", true);
	BOOST_CHECK(md2a);
	if (md2a) BOOST_CHECK_EQUAL(*md2a, date(3019, 1, 4));
	optional<date> const md2b = dp2.parse("2019..4 !!! 1", true);
	BOOST_CHECK(md2b);
	if (md2b) BOOST_CHECK_EQUAL(*md2b, date(2019, 1, 4));
	optional<date> const md2c = dp2.parse("2019 4 1", true);
	BOOST_CHECK (!md2c);

	DateParser const dp3("%Y %m %d", "%Y %m %d");
	optional<date> const md3a = dp3.parse("20190619", true);
	BOOST_CHECK(md3a);
	if (md3a) BOOST_CHECK_EQUAL(*md3a, date(2019, 6, 19));
	optional<date> const md3b = dp3.parse("2019/06/19", true);
	BOOST_CHECK(!md3b);

	DateParser const dp4("%Y%m%d", "%Y%m%d");
	optional<date> const md4a = dp4.parse("20130619", true);
	BOOST_CHECK(md4a);
	if (md4a) BOOST_CHECK_EQUAL(*md4a, date(2013, 6, 19));
	optional<date> const md4b = dp4.parse("2013 06 19", true);
	BOOST_CHECK(!md4b);
	optional<date> const md4c = dp4.parse("2013 619", true);
	BOOST_CHECK(!md4c);

	DateParser const dp5("%m-%d-%y", "%m-%d-%y");
	optional<date> const md5a = dp5.parse("5-3-2013", true);
	BOOST_CHECK(md5a);
	if (md5a) BOOST_CHECK_EQUAL(*md5a, date(2013, 5, 3));
	optional<date> const md5b = dp5.parse("5-3", true);
	BOOST_CHECK(md5b);
	if (md5b) BOOST_CHECK_EQUAL(*md5b, date(today().year(), 5, 3));
	optional<date> const md5c = dp5.parse("3", true);
	BOOST_CHECK(md5c);
	if (md5c) BOOST_CHECK_EQUAL(*md5c, date(today().year(), today().month(), 3));
}

}  // namespace test
}  // namespace dcm
<commit_msg>Fix minor error in date_parser_tests.cpp.<commit_after>/*
 * Copyright 2013 Matthew Harvey
 *
 * 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 "date.hpp"
#include "date_parser.hpp"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/optional.hpp>
#include <boost/test/unit_test.hpp>
#include <iostream>

using boost::gregorian::date;
using boost::optional;
using std::cout;
using std::endl;

namespace dcm
{
namespace test
{

// %d  is for day component
// %m  is for month component
// %y  is for year component (2 digit)
// %Y  is for year component (full)
// Additional modifiers might possibly appear between the
// '%' and the format specifier.
// Note the above are not the only format specifiers that can possibly appear
// in a strftime-like string; but they are the only ones relevant when doing
// "tolerant" parsing.

BOOST_AUTO_TEST_CASE(test_date_parser_intolerant_parse)
{
	DateParser const dp0("%d %m %y", "%d %m %y");
	optional<date> const md0a = dp0.parse("13 10 2013");
	BOOST_CHECK(!md0a);
	optional<date> const md0b = dp0.parse("13 09 13");
	BOOST_CHECK(md0b);
	if (md0b) BOOST_CHECK_EQUAL(*md0b, date(2013, 9, 13));
	optional<date> const md0c = dp0.parse("13 9 13");
	BOOST_CHECK(md0c);
	if (md0c) BOOST_CHECK_EQUAL(*md0c, date(2013, 9, 13));
	optional<date> const md0d = dp0.parse("08 31 13", false);
	BOOST_CHECK(!md0d);
	optional<date> const md0e = dp0.parse("13 09");
	BOOST_CHECK(!md0e);
	optional<date> const md0f = dp0.parse("12 6 99", false);
	BOOST_CHECK(md0f);
	if (md0f) BOOST_CHECK_EQUAL(*md0f, date(1999, 6, 12));
	optional<date> const md0g = dp0.parse("13/10/2013");
	BOOST_CHECK(!md0g);
	optional<date> const md0h = dp0.parse("21");
	BOOST_CHECK(!md0h);

	DateParser const dp1("%d/%m/%y", "%d/%m/%y");
	optional<date> const md1a = dp1.parse("13/10/13");
	BOOST_CHECK(md1a);
	if (md1a) BOOST_CHECK_EQUAL(*md1a, date(2013, 10, 13));
	optional<date> const md1b = dp1.parse("13 10 13");
	BOOST_CHECK(!md1b);

	DateParser const dp2("%Y .. %d !!! %m", "%Y .. %d !!! %m");
	optional<date> const md2a = dp2.parse("3019 .. 4 !!! 1");
	BOOST_CHECK(md2a);
	if (md2a) BOOST_CHECK_EQUAL(*md2a, date(3019, 1, 4));
	optional<date> const md2b = dp2.parse("2019..4 !!! 1");
	BOOST_CHECK(md2b);
	if (md2b) BOOST_CHECK_EQUAL(*md2b, date(2019, 1, 4));
	optional<date> const md2c = dp2.parse("2019 4 1");
	BOOST_CHECK (!md2c);

	// Spaces in the format string can be skipped in the
	// candidate string.
	DateParser const dp3("%Y %m %d", "%Y %m %d");
	optional<date> const md3a = dp3.parse("20190619");
	BOOST_CHECK(md3a);
	if (md3a) BOOST_CHECK_EQUAL(*md3a, date(2019, 6, 19));
	optional<date> const md3b = dp3.parse("2019/06/19");
	BOOST_CHECK(!md3b);

	// But spaces cannot be inserted in the candidate string
	// if the format string doesn't allow for them.
	DateParser const dp4("%Y%m%d", "%Y%m%d");
	optional<date> const md4a = dp4.parse("20130619");
	BOOST_CHECK(md4a);
	if (md4a) BOOST_CHECK_EQUAL(*md4a, date(2013, 6, 19));
	optional<date> const md4b = dp4.parse("2013 06 19");
	BOOST_CHECK(!md4b);
	optional<date> const md4c = dp4.parse("2013 619");
	BOOST_CHECK(!md4c);

	// "%Y" can accept either 2-digit or 4-digit year.
	DateParser const dp5("%Y . %m . %d", "%Y . %m . %d");
	optional<date> const md5a = dp5.parse("2010.01.05");
	BOOST_CHECK(md5a);
	if (md5a) BOOST_CHECK_EQUAL(*md5a, date(2010, 1, 5));
	optional<date> const md5b = dp5.parse("10.05.05");
	BOOST_CHECK(md5b);
	if (md5b) BOOST_CHECK_EQUAL(*md5b, date(2010, 5, 5));
	// But "%y" will only accept 2-digit year
	DateParser const dp5x("%y . %m . %d", "%y . %m . %d");
	optional<date> const md5xa = dp5x.parse("2010.01.05");
	BOOST_CHECK(!md5xa);
	optional<date> const md5xb = dp5x.parse("10.01.05");
	BOOST_CHECK(md5xb);
	if (md5xb) BOOST_CHECK_EQUAL(*md5xb, date(2010, 1, 5));

	// Primary is format is used if possible
	DateParser const dp6("%y-%d-%m", "%y-%m-%d");
	optional<date> const md6a = dp6.parse("10-5-3");
	BOOST_CHECK(md6a);
	if (md6a) BOOST_CHECK_EQUAL(*md6a, date(2010, 3, 5));
	// But if not possible, secondary format is used.
	optional<date> const md6b = dp6.parse("10-12-14");
	BOOST_CHECK(md6b);
	if (md6b) BOOST_CHECK_EQUAL(*md6b, date(2010, 12, 14));
}

BOOST_AUTO_TEST_CASE(test_date_parser_tolerant_parse)
{
	DateParser const dp0("%d %m %y", "%d, %m, %y");
	optional<date> const md0a = dp0.parse("13 10 2013", true);
	BOOST_CHECK(md0a);
	if (md0a) BOOST_CHECK_EQUAL(*md0a, date(2013, 10, 13));
	optional<date> const md0b = dp0.parse("13 09 13", true);
	BOOST_CHECK(md0b);
	if (md0b) BOOST_CHECK_EQUAL(*md0b, date(2013, 9, 13));
	optional<date> const md0c = dp0.parse("13 9 13", true);
	BOOST_CHECK(md0c);
	if (md0c) BOOST_CHECK_EQUAL(*md0c, date(2013, 9, 13));
	optional<date> const md0d = dp0.parse("08 31 13", true);
	BOOST_CHECK(!md0d);
	optional<date> const md0e = dp0.parse("13 09", true);
	BOOST_CHECK(md0e);
	if (md0e) BOOST_CHECK_EQUAL(*md0e, date(today().year(), 9, 13));
	optional<date> const md0f = dp0.parse("12 6 99", true);
	BOOST_CHECK(md0f);
	if (md0f) BOOST_CHECK_EQUAL(*md0f, date(1999, 6, 12));
	optional<date> const md0g = dp0.parse("13/10/2013", true);
	BOOST_CHECK(!md0g);
	optional<date> const md0h = dp0.parse("0000030 010 00002013", true);
	BOOST_CHECK(md0h);
	if (md0h) BOOST_CHECK_EQUAL(*md0h, date(2013, 10, 30));
	optional<date> const md0i = dp0.parse("21", true);
	BOOST_CHECK(md0i);
	if (md0i) BOOST_CHECK_EQUAL(*md0i, date(today().year(), today().month(), 21));

	DateParser const dp1("%d/%m/%y", "%d/%m/%y");
	optional<date> const md1a = dp1.parse("13/10/13", true);
	BOOST_CHECK(md1a);
	if (md1a) BOOST_CHECK_EQUAL(*md1a, date(2013, 10, 13));
	optional<date> const md1b = dp1.parse("13 10 13", true);
	BOOST_CHECK(!md1b);

	DateParser const dp2("%Y .. %d !!! %m", "%Y .. %d !! %m");
	optional<date> const md2a = dp2.parse("3019 .. 4 !!! 1", true);
	BOOST_CHECK(md2a);
	if (md2a) BOOST_CHECK_EQUAL(*md2a, date(3019, 1, 4));
	optional<date> const md2b = dp2.parse("2019..4 !!! 1", true);
	BOOST_CHECK(md2b);
	if (md2b) BOOST_CHECK_EQUAL(*md2b, date(2019, 1, 4));
	optional<date> const md2c = dp2.parse("2019 4 1", true);
	BOOST_CHECK (!md2c);

	DateParser const dp3("%Y %m %d", "%Y %m %d");
	optional<date> const md3a = dp3.parse("20190619", true);
	BOOST_CHECK(md3a);
	if (md3a) BOOST_CHECK_EQUAL(*md3a, date(2019, 6, 19));
	optional<date> const md3b = dp3.parse("2019/06/19", true);
	BOOST_CHECK(!md3b);

	DateParser const dp4("%Y%m%d", "%Y%m%d");
	optional<date> const md4a = dp4.parse("20130619", true);
	BOOST_CHECK(md4a);
	if (md4a) BOOST_CHECK_EQUAL(*md4a, date(2013, 6, 19));
	optional<date> const md4b = dp4.parse("2013 06 19", true);
	BOOST_CHECK(!md4b);
	optional<date> const md4c = dp4.parse("2013 619", true);
	BOOST_CHECK(!md4c);

	DateParser const dp5("%m-%d-%y", "%m-%d-%y");
	optional<date> const md5a = dp5.parse("5-3-2013", true);
	BOOST_CHECK(md5a);
	if (md5a) BOOST_CHECK_EQUAL(*md5a, date(2013, 5, 3));
	optional<date> const md5b = dp5.parse("5-3", true);
	BOOST_CHECK(md5b);
	if (md5b) BOOST_CHECK_EQUAL(*md5b, date(today().year(), 5, 3));
	optional<date> const md5c = dp5.parse("3", true);
	BOOST_CHECK(md5c);
	if (md5c) BOOST_CHECK_EQUAL(*md5c, date(today().year(), today().month(), 3));
}

}  // namespace test
}  // namespace dcm
<|endoftext|>


<commit_before><commit_msg>Negotiate on by default on all platforms.<commit_after><|endoftext|>


<commit_before><commit_msg>Test to see if IPv6 can be disabled: Will roll back ASAP<commit_after><|endoftext|>


<commit_before>#include <ruby.h>
#include <set>

using namespace std;

static VALUE enumerable_each_uniq_i(VALUE i, VALUE* memo)
{
    set<VALUE>& seen = *reinterpret_cast< set<VALUE>* >(memo);
    if (seen.find(i) == seen.end())
    {
	seen.insert(i);
	return rb_yield(i);
    }
    else
	return Qnil;

}

/* :nodoc: */
static VALUE enumerable_each_uniq(VALUE self)
{
    set<VALUE> seen;
    rb_iterate(rb_each, self,
	    RUBY_METHOD_FUNC(enumerable_each_uniq_i), (VALUE)&seen);
    return self;
}

/* Returns true if +self+ is a singleton class */
static VALUE kernel_is_singleton_p(VALUE self)
{
    if (BUILTIN_TYPE(self) == T_CLASS && FL_TEST(self, FL_SINGLETON))
	return Qtrue;
    else
	return Qfalse;
}

extern "C" void Init_value_set();
extern "C" void Init_swap();

extern "C" void Init_faster()
{
    rb_define_method(rb_mEnumerable, "each_uniq", RUBY_METHOD_FUNC(enumerable_each_uniq), 0);
    rb_define_method(rb_mKernel, "is_singleton?", RUBY_METHOD_FUNC(kernel_is_singleton_p), 0);

    Init_value_set();
    Init_swap();
}

<commit_msg>[doc] document Kernel.is_singleton?<commit_after>#include <ruby.h>
#include <set>

using namespace std;

static VALUE enumerable_each_uniq_i(VALUE i, VALUE* memo)
{
    set<VALUE>& seen = *reinterpret_cast< set<VALUE>* >(memo);
    if (seen.find(i) == seen.end())
    {
	seen.insert(i);
	return rb_yield(i);
    }
    else
	return Qnil;

}

/* :nodoc: */
static VALUE enumerable_each_uniq(VALUE self)
{
    set<VALUE> seen;
    rb_iterate(rb_each, self,
	    RUBY_METHOD_FUNC(enumerable_each_uniq_i), (VALUE)&seen);
    return self;
}

/* call-seq:
 *  Kernel.is_singleton?(object)
 *
 * Returns true if +self+ is a singleton class
 */
static VALUE kernel_is_singleton_p(VALUE self)
{
    if (BUILTIN_TYPE(self) == T_CLASS && FL_TEST(self, FL_SINGLETON))
	return Qtrue;
    else
	return Qfalse;
}

extern "C" void Init_value_set();
extern "C" void Init_swap();

extern "C" void Init_faster()
{
    rb_define_method(rb_mEnumerable, "each_uniq", RUBY_METHOD_FUNC(enumerable_each_uniq), 0);
    rb_define_method(rb_mKernel, "is_singleton?", RUBY_METHOD_FUNC(kernel_is_singleton_p), 0);

    Init_value_set();
    Init_swap();
}

<|endoftext|>


<commit_before>/***************************************************************************
*   Copyright © 2003 Unai Garro <ugarro@gmail.com>                        *
*   Copyright © 2003 Cyril Bosselut <bosselut@b1project.com>              *
*   Copyright © 2003 Jason Kivlighn <jkivlighn@gmail.com>                 *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
***************************************************************************/

#include "selectpropertydialog.h"

#include <kconfig.h>
#include <kglobal.h>
#include <klocale.h>
#include <QPointer>

#include "datablocks/ingredientpropertylist.h"
#include "dialogs/createunitdialog.h"
#include "backends/recipedb.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <KVBox>

SelectPropertyDialog::SelectPropertyDialog( QWidget* parent, int ingID, RecipeDB *database, OptionFlag showEmpty )
		: KDialog( parent), m_showEmpty(showEmpty),
		ingredientID(ingID), db(database)
{
	setModal( true );
	setButtons(KDialog::Ok | KDialog::Cancel);
	setDefaultButton( KDialog::Ok);
	setCaption(i18nc( "@title:window", "Choose Property" ));

	// Initialize internal variables
	unitListBack = new UnitList;

	// Initialize Widgets
	KVBox *page = new KVBox( this );
	setMainWidget( page );
	box = new Q3GroupBox( page );
	box->setTitle( i18nc( "@title:group", "Choose Property" ) );
	box->setColumnLayout( 0, Qt::Vertical );
	box->layout() ->setSpacing( 6 );
	box->layout() ->setMargin( 11 );
	QVBoxLayout *boxLayout = new QVBoxLayout( box->layout() );
	boxLayout->setAlignment( Qt::AlignTop );

	propertyChooseView = new K3ListView( box );

	KConfigGroup config( KGlobal::config(),  "Advanced" );
	bool show_id = config.readEntry( "ShowID", false );
	propertyChooseView->addColumn( "Id" , show_id ? -1 : 0 );

	propertyChooseView->addColumn( i18nc( "@title:column", "Property" ) );
	propertyChooseView->setSorting(1);
	propertyChooseView->setAllColumnsShowFocus( true );
	boxLayout->addWidget( propertyChooseView );

	QHBoxLayout *layout2 = new QHBoxLayout;

	perUnitsLabel = new QLabel( box );
	perUnitsLabel->setGeometry( QRect( 5, 285, 100, 30 ) );
	perUnitsLabel->setText( i18nc( "@label:textbox", "Per units:" ) );
	layout2->addWidget( perUnitsLabel );

	perUnitsBox = new KComboBox( true, box );
	layout2->addWidget( perUnitsBox );
	boxLayout->addLayout( layout2 );

	resize( QSize( 400, 400 ).expandedTo( minimumSizeHint() ) );
	//TODO port kde4
	//clearWState( WState_Polished );

	IngredientPropertyList propertyList;
	db->loadProperties( &propertyList );
	UnitList unitList;
	db->loadPossibleUnits( ingredientID, &unitList );

	// Load data
	loadProperties( &propertyList );
	loadUnits( &unitList );
}

SelectPropertyDialog::~SelectPropertyDialog()
{
	delete unitListBack;
}

int SelectPropertyDialog::propertyID( void )
{

	Q3ListViewItem * it;
	if ( ( it = propertyChooseView->selectedItem() ) ) {
		return ( it->text( 0 ).toInt() );
	}
	else
		return ( -1 );
}

int SelectPropertyDialog::perUnitsID()
{

	int comboCount = perUnitsBox->count();
	for (int i = 0; i < comboCount; ++i) {
		if (perUnitsBox->currentText() == perUnitsBox->itemText(i))
			return unitListBack->at( i ).id();
	}

	//new unit, add it to the database
	QString unit = perUnitsBox->currentText();
	int id = db->findExistingUnitByName( unit );
	if ( -1 == id )
	{
		QPointer<CreateUnitDialog> getUnit = new CreateUnitDialog( this, unit, QString() );
		if ( getUnit->exec() == QDialog::Accepted ) {
			Unit new_unit = getUnit->newUnit();
			db->createNewUnit( new_unit );

			id = db->lastInsertID();
		}
		delete getUnit;
	}
	db->addUnitToIngredient( ingredientID, id ); // Add chosen unit to ingredient in database

	return id;
}

void SelectPropertyDialog::loadProperties( IngredientPropertyList *propertyList )
{
	for ( IngredientPropertyList::const_iterator prop_it = propertyList->constBegin(); prop_it != propertyList->constEnd(); ++prop_it ) {
		( void ) new Q3ListViewItem( propertyChooseView, QString::number( (*prop_it).id ), (*prop_it).name );
	}
}
void SelectPropertyDialog::loadUnits( UnitList *unitList )
{
	for ( UnitList::const_iterator unit_it = unitList->constBegin(); unit_it != unitList->constEnd(); ++unit_it ) {
		QString unitName = ( *unit_it ).name();
		if ( unitName.isEmpty() ) {
			if ( m_showEmpty == ShowEmptyUnit )
				unitName = ' '+i18nc("@item", "-No unit-");
			else
				continue;
		}

		// Insert in the combobox
		perUnitsBox->insertItem( perUnitsBox->count(), unitName );

		// Store with index for using later
		Unit newUnit( *unit_it );
		newUnit.setName(unitName);
		unitListBack->append( newUnit );
	}
}
<commit_msg>Don't crash in SelectPropertyDialog when the "Per units:" combo box starts being empty, you type something in the combo box and you accept the dialog.<commit_after>/***************************************************************************
*   Copyright © 2003 Unai Garro <ugarro@gmail.com>                        *
*   Copyright © 2003 Cyril Bosselut <bosselut@b1project.com>              *
*   Copyright © 2003 Jason Kivlighn <jkivlighn@gmail.com>                 *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
***************************************************************************/

#include "selectpropertydialog.h"

#include <kconfig.h>
#include <kglobal.h>
#include <klocale.h>
#include <QPointer>

#include "datablocks/ingredientpropertylist.h"
#include "dialogs/createunitdialog.h"
#include "backends/recipedb.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <KVBox>

SelectPropertyDialog::SelectPropertyDialog( QWidget* parent, int ingID, RecipeDB *database, OptionFlag showEmpty )
		: KDialog( parent), m_showEmpty(showEmpty),
		ingredientID(ingID), db(database)
{
	setModal( true );
	setButtons(KDialog::Ok | KDialog::Cancel);
	setDefaultButton( KDialog::Ok);
	setCaption(i18nc( "@title:window", "Choose Property" ));

	// Initialize internal variables
	unitListBack = new UnitList;

	// Initialize Widgets
	KVBox *page = new KVBox( this );
	setMainWidget( page );
	box = new Q3GroupBox( page );
	box->setTitle( i18nc( "@title:group", "Choose Property" ) );
	box->setColumnLayout( 0, Qt::Vertical );
	box->layout() ->setSpacing( 6 );
	box->layout() ->setMargin( 11 );
	QVBoxLayout *boxLayout = new QVBoxLayout( box->layout() );
	boxLayout->setAlignment( Qt::AlignTop );

	propertyChooseView = new K3ListView( box );

	KConfigGroup config( KGlobal::config(),  "Advanced" );
	bool show_id = config.readEntry( "ShowID", false );
	propertyChooseView->addColumn( "Id" , show_id ? -1 : 0 );

	propertyChooseView->addColumn( i18nc( "@title:column", "Property" ) );
	propertyChooseView->setSorting(1);
	propertyChooseView->setAllColumnsShowFocus( true );
	boxLayout->addWidget( propertyChooseView );

	QHBoxLayout *layout2 = new QHBoxLayout;

	perUnitsLabel = new QLabel( box );
	perUnitsLabel->setGeometry( QRect( 5, 285, 100, 30 ) );
	perUnitsLabel->setText( i18nc( "@label:textbox", "Per units:" ) );
	layout2->addWidget( perUnitsLabel );

	perUnitsBox = new KComboBox( true, box );
	perUnitsBox->setInsertPolicy( QComboBox::NoInsert );
	layout2->addWidget( perUnitsBox );
	boxLayout->addLayout( layout2 );

	resize( QSize( 400, 400 ).expandedTo( minimumSizeHint() ) );
	//TODO port kde4
	//clearWState( WState_Polished );

	IngredientPropertyList propertyList;
	db->loadProperties( &propertyList );
	UnitList unitList;
	db->loadPossibleUnits( ingredientID, &unitList );

	// Load data
	loadProperties( &propertyList );
	loadUnits( &unitList );
}

SelectPropertyDialog::~SelectPropertyDialog()
{
	delete unitListBack;
}

int SelectPropertyDialog::propertyID( void )
{

	Q3ListViewItem * it;
	if ( ( it = propertyChooseView->selectedItem() ) ) {
		return ( it->text( 0 ).toInt() );
	}
	else
		return ( -1 );
}

int SelectPropertyDialog::perUnitsID()
{

	int comboCount = perUnitsBox->count();
	for (int i = 0; i < comboCount; ++i) {
		if (perUnitsBox->currentText() == perUnitsBox->itemText(i))
			return unitListBack->at( i ).id();
	}

	//new unit, add it to the database
	QString unit = perUnitsBox->currentText();
	int id = db->findExistingUnitByName( unit );
	if ( -1 == id )
	{
		QPointer<CreateUnitDialog> getUnit = new CreateUnitDialog( this, unit, QString() );
		if ( getUnit->exec() == QDialog::Accepted ) {
			Unit new_unit = getUnit->newUnit();
			db->createNewUnit( new_unit );

			id = db->lastInsertID();
		}
		delete getUnit;
	}
	db->addUnitToIngredient( ingredientID, id ); // Add chosen unit to ingredient in database

	return id;
}

void SelectPropertyDialog::loadProperties( IngredientPropertyList *propertyList )
{
	for ( IngredientPropertyList::const_iterator prop_it = propertyList->constBegin(); prop_it != propertyList->constEnd(); ++prop_it ) {
		( void ) new Q3ListViewItem( propertyChooseView, QString::number( (*prop_it).id ), (*prop_it).name );
	}
}
void SelectPropertyDialog::loadUnits( UnitList *unitList )
{
	for ( UnitList::const_iterator unit_it = unitList->constBegin(); unit_it != unitList->constEnd(); ++unit_it ) {
		QString unitName = ( *unit_it ).name();
		if ( unitName.isEmpty() ) {
			if ( m_showEmpty == ShowEmptyUnit )
				unitName = ' '+i18nc("@item", "-No unit-");
			else
				continue;
		}

		// Insert in the combobox
		perUnitsBox->insertItem( perUnitsBox->count(), unitName );

		// Store with index for using later
		Unit newUnit( *unit_it );
		newUnit.setName(unitName);
		unitListBack->append( newUnit );
	}
}
<|endoftext|>


<commit_before>#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>
#include <string>
#include <vector>
#include <array>
#include <cmath>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <ApplicationServices/ApplicationServices.h>
#include <unistd.h>

#include <opencv2/objdetect.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>

using namespace cv;
//using namespace std;

 /** Function Headers */
 void detectAndDisplay( Mat frame );

 /** Global variables */
 std::string face_cascade_name = "haarcascade_frontalface_alt.xml";
 std::string eyes_cascade_name = "haarcascade_eye_tree_eyeglasses.xml";
 CascadeClassifier face_cascade;
 CascadeClassifier eyes_cascade;
 std::string window_name = "Capture - Face detection";
 RNG rng(12345);

 /** @function main */
 int main( int argc, const char** argv )
 {
   VideoCapture cap(0);
   if(!cap.isOpened())
   		return -1;
   cv::Mat frame;
   cv::Mat frame_gray;
   std::vector<cv::Rect> faces;

   //-- 1. Load the cascades
   if( !face_cascade.load( face_cascade_name ) ){ printf("--(!)Error loading\n"); return -1; };
   if( !eyes_cascade.load( eyes_cascade_name ) ){ printf("--(!)Error loading\n"); return -1; };

   //-- 2. Read the video stream
   cap.read(frame);
   frame = cvQueryFrame( capture );

   //-- 3. Apply the classifier to the frame
       if( !frame.empty() ){

       	// display the frame
        //{ detectAndDisplay( frame ); }
       	// greyscale and downsample
  		cv::cvtColor( frame, frame_gray, CV_BGR2GRAY );
  		cv::equalizeHist( frame_gray, frame_gray );

  		face_cascade.detectMultiScale( frame_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, cv::Size(30, 30) );
  		}
       else{
       		printf(" --(!) No captured frame -- Break!"); break;
       	}

       if(waitKey(30) == 27){
       		break;
       	}
   }
   return 0;
 }
}

<commit_msg>two eye cascade<commit_after>#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <array>
#include <cmath>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/objdetect.hpp>
#include <ApplicationServices/ApplicationServices.h>
#include <unistd.h>
using namespace cv;

CGEventRef move;
CascadeClassifier faceCascade, eyeCascade;
bool bSuccess;
Mat frame, eyeTpl;
cv::Rect eyeBb;

void detectAndDisplay(Mat frame)
{
  cv::Rect rect;
  std::vector<cv::Rect> faces, eyes;
  Mat frame_gray;

  cvtColor( frame, frame_gray, CV_BGR2GRAY );
  equalizeHist( frame_gray, frame_gray );

  //-- Detect faces
  faceCascade.detectMultiScale( frame_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, cv::Size(30, 30) );

  for(int i=0; i<faces.size(); i++)
  {
    Mat face = frame_gray(faces[i]);
    eyeCascade.detectMultiScale(face, eyes, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, cv::Size(20,20));
    for(int j=0; j<eyes.size(); j++)
    {
      //-- draw rectangles on all eyes
      rect = eyes[0] + cv::Point(faces[i].x, faces[i].y);
    }

  }
}

int main(int argc, char** argv)
{
  std::cout << "Program initiated by user" << std::endl;
  faceCascade.load("haarcascade_frontalface_default.xml");
  eyeCascade.load("haarcascade_eye.xml");
  VideoCapture cap(0);
  Mat frame;

  if (!cap.isOpened())
  {
    std::cout << "ERROR: Some shit broke fam..." << std::endl;
    return -1;
  }
  else
    std::cout << "Webcam initiated" << std::endl;
  namedWindow("Hack NJIT 2016", CV_WINDOW_AUTOSIZE);
  bSuccess = cap.read(frame);
  while(true)
  {
    //moveCursor(getEyePos());
    bSuccess = cap.read(frame);
    if (!bSuccess)
    {
      std::cout << "Frame dropped" << std::endl;
      break;
    }

    if(!frame.empty())
    {
      detectAndDisplay(frame);
    }
    else
    {
      printf(" --(!) No captured frame -- Break!"); break;
    }

    imshow("HackTCNJ2016", frame);
    if (waitKey(30) == 27)
    {
      std::cout << "Program terminated by user" << std::endl;
      break;
    }
  }
  return 0;
}

<|endoftext|>


<commit_before>//===--- TestTU.cpp - Scratch source files for testing --------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "TestTU.h"
#include "TestFS.h"
#include "index/FileIndex.h"
#include "index/MemIndex.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/Utils.h"

namespace clang {
namespace clangd {

ParsedAST TestTU::build() const {
  std::string FullFilename = testPath(Filename),
              FullHeaderName = testPath(HeaderFilename),
              ImportThunk = testPath("import_thunk.h");
  // We want to implicitly include HeaderFilename without messing up offsets.
  // -include achieves this, but sometimes we want #import (to simulate a header
  // guard without messing up offsets). In this case, use an intermediate file.
  std::string ThunkContents = "#import \"" + FullHeaderName + "\"\n";

  llvm::StringMap<std::string> Files(AdditionalFiles);
  Files[FullFilename] = Code;
  Files[FullHeaderName] = HeaderCode;
  Files[ImportThunk] = ThunkContents;

  std::vector<const char *> Cmd = {"clang"};
  // FIXME: this shouldn't need to be conditional, but it breaks a
  // GoToDefinition test for some reason (getMacroArgExpandedLocation fails).
  if (!HeaderCode.empty()) {
    Cmd.push_back("-include");
    Cmd.push_back(ImplicitHeaderGuard ? ImportThunk.c_str()
                                      : FullHeaderName.c_str());
  }
  Cmd.insert(Cmd.end(), ExtraArgs.begin(), ExtraArgs.end());
  // Put the file name at the end -- this allows the extra arg (-xc++) to
  // override the language setting.
  Cmd.push_back(FullFilename.c_str());
  ParseInputs Inputs;
  Inputs.CompileCommand.Filename = FullFilename;
  Inputs.CompileCommand.CommandLine = {Cmd.begin(), Cmd.end()};
  Inputs.CompileCommand.Directory = testRoot();
  Inputs.Contents = Code;
  Inputs.FS = buildTestFS(Files);
  Inputs.Opts = ParseOptions();
  Inputs.Opts.ClangTidyOpts.Checks = ClangTidyChecks;
  Inputs.Opts.ClangTidyOpts.WarningsAsErrors = ClangTidyWarningsAsErrors;
  Inputs.Index = ExternalIndex;
  if (Inputs.Index)
    Inputs.Opts.SuggestMissingIncludes = true;
  auto CI = buildCompilerInvocation(Inputs);
  assert(CI && "Failed to build compilation invocation.");
  auto Preamble =
      buildPreamble(FullFilename, *CI,
                    /*OldPreamble=*/nullptr,
                    /*OldCompileCommand=*/Inputs.CompileCommand, Inputs,
                    /*StoreInMemory=*/true, /*PreambleCallback=*/nullptr);
  auto AST = buildAST(FullFilename, std::move(CI), Inputs, Preamble);
  if (!AST.hasValue()) {
    ADD_FAILURE() << "Failed to build code:\n" << Code;
    llvm_unreachable("Failed to build TestTU!");
  }
  return std::move(*AST);
}

SymbolSlab TestTU::headerSymbols() const {
  auto AST = build();
  return std::get<0>(indexHeaderSymbols(AST.getASTContext(),
                                        AST.getPreprocessorPtr(),
                                        AST.getCanonicalIncludes()));
}

std::unique_ptr<SymbolIndex> TestTU::index() const {
  auto AST = build();
  auto Idx = llvm::make_unique<FileIndex>(/*UseDex=*/true);
  Idx->updatePreamble(Filename, AST.getASTContext(), AST.getPreprocessorPtr(),
                      AST.getCanonicalIncludes());
  Idx->updateMain(Filename, AST);
  return std::move(Idx);
}

const Symbol &findSymbol(const SymbolSlab &Slab, llvm::StringRef QName) {
  const Symbol *Result = nullptr;
  for (const Symbol &S : Slab) {
    if (QName != (S.Scope + S.Name).str())
      continue;
    if (Result) {
      ADD_FAILURE() << "Multiple symbols named " << QName << ":\n"
                    << *Result << "\n---\n"
                    << S;
      assert(false && "QName is not unique");
    }
    Result = &S;
  }
  if (!Result) {
    ADD_FAILURE() << "No symbol named " << QName << " in "
                  << ::testing::PrintToString(Slab);
    assert(false && "No symbol with QName");
  }
  return *Result;
}

const NamedDecl &findDecl(ParsedAST &AST, llvm::StringRef QName) {
  llvm::SmallVector<llvm::StringRef, 4> Components;
  QName.split(Components, "::");

  auto &Ctx = AST.getASTContext();
  auto LookupDecl = [&Ctx](const DeclContext &Scope,
                           llvm::StringRef Name) -> const NamedDecl & {
    auto LookupRes = Scope.lookup(DeclarationName(&Ctx.Idents.get(Name)));
    assert(!LookupRes.empty() && "Lookup failed");
    assert(LookupRes.size() == 1 && "Lookup returned multiple results");
    return *LookupRes.front();
  };

  const DeclContext *Scope = Ctx.getTranslationUnitDecl();
  for (auto NameIt = Components.begin(), End = Components.end() - 1;
       NameIt != End; ++NameIt) {
    Scope = &cast<DeclContext>(LookupDecl(*Scope, *NameIt));
  }
  return LookupDecl(*Scope, Components.back());
}

const NamedDecl &findDecl(ParsedAST &AST,
                          std::function<bool(const NamedDecl &)> Filter) {
  struct Visitor : RecursiveASTVisitor<Visitor> {
    decltype(Filter) F;
    llvm::SmallVector<const NamedDecl *, 1> Decls;
    bool VisitNamedDecl(const NamedDecl *ND) {
      if (F(*ND))
        Decls.push_back(ND);
      return true;
    }
  } Visitor;
  Visitor.F = Filter;
  Visitor.TraverseDecl(AST.getASTContext().getTranslationUnitDecl());
  if (Visitor.Decls.size() != 1) {
    ADD_FAILURE() << Visitor.Decls.size() << " symbols matched.";
    assert(Visitor.Decls.size() == 1);
  }
  return *Visitor.Decls.front();
}

const NamedDecl &findUnqualifiedDecl(ParsedAST &AST, llvm::StringRef Name) {
  return findDecl(AST, [Name](const NamedDecl &ND) {
    if (auto *ID = ND.getIdentifier())
      if (ID->getName() == Name)
        return true;
    return false;
  });
}

} // namespace clangd
} // namespace clang
<commit_msg>[clangd] Force the required interpretation of #import on windows tests.<commit_after>//===--- TestTU.cpp - Scratch source files for testing --------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "TestTU.h"
#include "TestFS.h"
#include "index/FileIndex.h"
#include "index/MemIndex.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/Utils.h"

namespace clang {
namespace clangd {

ParsedAST TestTU::build() const {
  std::string FullFilename = testPath(Filename),
              FullHeaderName = testPath(HeaderFilename),
              ImportThunk = testPath("import_thunk.h");
  // We want to implicitly include HeaderFilename without messing up offsets.
  // -include achieves this, but sometimes we want #import (to simulate a header
  // guard without messing up offsets). In this case, use an intermediate file.
  std::string ThunkContents = "#import \"" + FullHeaderName + "\"\n";

  llvm::StringMap<std::string> Files(AdditionalFiles);
  Files[FullFilename] = Code;
  Files[FullHeaderName] = HeaderCode;
  Files[ImportThunk] = ThunkContents;

  std::vector<const char *> Cmd = {"clang"};
  // FIXME: this shouldn't need to be conditional, but it breaks a
  // GoToDefinition test for some reason (getMacroArgExpandedLocation fails).
  if (!HeaderCode.empty()) {
    Cmd.push_back("-include");
    Cmd.push_back(ImplicitHeaderGuard ? ImportThunk.c_str()
                                      : FullHeaderName.c_str());
    // ms-compatibility changes the meaning of #import.
    // The default is OS-dependent (on on windows), ensure it's off.
    if (ImplicitHeaderGuard)
      Cmd.push_back("-fno-ms-compatibility");
  }
  Cmd.insert(Cmd.end(), ExtraArgs.begin(), ExtraArgs.end());
  // Put the file name at the end -- this allows the extra arg (-xc++) to
  // override the language setting.
  Cmd.push_back(FullFilename.c_str());
  ParseInputs Inputs;
  Inputs.CompileCommand.Filename = FullFilename;
  Inputs.CompileCommand.CommandLine = {Cmd.begin(), Cmd.end()};
  Inputs.CompileCommand.Directory = testRoot();
  Inputs.Contents = Code;
  Inputs.FS = buildTestFS(Files);
  Inputs.Opts = ParseOptions();
  Inputs.Opts.ClangTidyOpts.Checks = ClangTidyChecks;
  Inputs.Opts.ClangTidyOpts.WarningsAsErrors = ClangTidyWarningsAsErrors;
  Inputs.Index = ExternalIndex;
  if (Inputs.Index)
    Inputs.Opts.SuggestMissingIncludes = true;
  auto CI = buildCompilerInvocation(Inputs);
  assert(CI && "Failed to build compilation invocation.");
  auto Preamble =
      buildPreamble(FullFilename, *CI,
                    /*OldPreamble=*/nullptr,
                    /*OldCompileCommand=*/Inputs.CompileCommand, Inputs,
                    /*StoreInMemory=*/true, /*PreambleCallback=*/nullptr);
  auto AST = buildAST(FullFilename, std::move(CI), Inputs, Preamble);
  if (!AST.hasValue()) {
    ADD_FAILURE() << "Failed to build code:\n" << Code;
    llvm_unreachable("Failed to build TestTU!");
  }
  return std::move(*AST);
}

SymbolSlab TestTU::headerSymbols() const {
  auto AST = build();
  return std::get<0>(indexHeaderSymbols(AST.getASTContext(),
                                        AST.getPreprocessorPtr(),
                                        AST.getCanonicalIncludes()));
}

std::unique_ptr<SymbolIndex> TestTU::index() const {
  auto AST = build();
  auto Idx = llvm::make_unique<FileIndex>(/*UseDex=*/true);
  Idx->updatePreamble(Filename, AST.getASTContext(), AST.getPreprocessorPtr(),
                      AST.getCanonicalIncludes());
  Idx->updateMain(Filename, AST);
  return std::move(Idx);
}

const Symbol &findSymbol(const SymbolSlab &Slab, llvm::StringRef QName) {
  const Symbol *Result = nullptr;
  for (const Symbol &S : Slab) {
    if (QName != (S.Scope + S.Name).str())
      continue;
    if (Result) {
      ADD_FAILURE() << "Multiple symbols named " << QName << ":\n"
                    << *Result << "\n---\n"
                    << S;
      assert(false && "QName is not unique");
    }
    Result = &S;
  }
  if (!Result) {
    ADD_FAILURE() << "No symbol named " << QName << " in "
                  << ::testing::PrintToString(Slab);
    assert(false && "No symbol with QName");
  }
  return *Result;
}

const NamedDecl &findDecl(ParsedAST &AST, llvm::StringRef QName) {
  llvm::SmallVector<llvm::StringRef, 4> Components;
  QName.split(Components, "::");

  auto &Ctx = AST.getASTContext();
  auto LookupDecl = [&Ctx](const DeclContext &Scope,
                           llvm::StringRef Name) -> const NamedDecl & {
    auto LookupRes = Scope.lookup(DeclarationName(&Ctx.Idents.get(Name)));
    assert(!LookupRes.empty() && "Lookup failed");
    assert(LookupRes.size() == 1 && "Lookup returned multiple results");
    return *LookupRes.front();
  };

  const DeclContext *Scope = Ctx.getTranslationUnitDecl();
  for (auto NameIt = Components.begin(), End = Components.end() - 1;
       NameIt != End; ++NameIt) {
    Scope = &cast<DeclContext>(LookupDecl(*Scope, *NameIt));
  }
  return LookupDecl(*Scope, Components.back());
}

const NamedDecl &findDecl(ParsedAST &AST,
                          std::function<bool(const NamedDecl &)> Filter) {
  struct Visitor : RecursiveASTVisitor<Visitor> {
    decltype(Filter) F;
    llvm::SmallVector<const NamedDecl *, 1> Decls;
    bool VisitNamedDecl(const NamedDecl *ND) {
      if (F(*ND))
        Decls.push_back(ND);
      return true;
    }
  } Visitor;
  Visitor.F = Filter;
  Visitor.TraverseDecl(AST.getASTContext().getTranslationUnitDecl());
  if (Visitor.Decls.size() != 1) {
    ADD_FAILURE() << Visitor.Decls.size() << " symbols matched.";
    assert(Visitor.Decls.size() == 1);
  }
  return *Visitor.Decls.front();
}

const NamedDecl &findUnqualifiedDecl(ParsedAST &AST, llvm::StringRef Name) {
  return findDecl(AST, [Name](const NamedDecl &ND) {
    if (auto *ID = ND.getIdentifier())
      if (ID->getName() == Name)
        return true;
    return false;
  });
}

} // namespace clangd
} // namespace clang
<|endoftext|>


<commit_before>/*
 * Test Driver for Botan
 */

#include <vector>
#include <string>

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <limits>
#include <memory>

#include <botan/botan.h>
#include <botan/libstate.h>
#include <botan/mp_types.h>

using namespace Botan;

#include "getopt.h"
#include "bench.h"
#include "validate.h"
#include "common.h"

const std::string VALIDATION_FILE = "checks/validate.dat";
const std::string BIGINT_VALIDATION_FILE = "checks/mp_valid.dat";
const std::string PK_VALIDATION_FILE = "checks/pk_valid.dat";
const std::string EXPECTED_FAIL_FILE = "checks/fail.dat";

int run_test_suite(RandomNumberGenerator& rng);

namespace {

template<typename T>
bool test(const char* type, int digits, bool is_signed)
   {
   if(std::numeric_limits<T>::is_specialized == false)
      {
      std::cout << "WARNING: Could not check parameters of " << type
                << " in std::numeric_limits" << std::endl;

      // assume it's OK (full tests will catch it later)
      return true;
      }

   // continue checking after failures
   bool passed = true;

   if(std::numeric_limits<T>::is_integer == false)
      {
      std::cout << "WARN: std::numeric_limits<> says " << type
                << " is not an integer" << std::endl;
      passed = false;
      }

   if(std::numeric_limits<T>::is_signed != is_signed)
      {
      std::cout << "ERROR: numeric_limits<" << type << ">::is_signed == "
                << std::boolalpha << std::numeric_limits<T>::is_signed
                << std::endl;
      passed = false;
      }

   if(std::numeric_limits<T>::digits != digits && digits != 0)
      {
      std::cout << "ERROR: numeric_limits<" << type << ">::digits == "
                << std::numeric_limits<T>::digits
                << " expected " << digits << std::endl;
      passed = false;
      }

   return passed;
   }

void test_types()
   {
   bool passed = true;

   passed = passed && test<Botan::byte  >("byte",    8, false);
   passed = passed && test<Botan::u16bit>("u16bit", 16, false);
   passed = passed && test<Botan::u32bit>("u32bit", 32, false);
   passed = passed && test<Botan::u64bit>("u64bit", 64, false);
   passed = passed && test<Botan::s32bit>("s32bit", 31,  true);
   passed = passed && test<Botan::word>("word", 0, false);

   if(!passed)
      std::cout << "Typedefs in include/types.h may be incorrect!\n";
   }

}

int main(int argc, char* argv[])
   {
   try
      {
      OptionParser opts("help|html|test|validate|"
                        "benchmark|bench-type=|bench-algo=|seconds=");
      opts.parse(argv);

      test_types(); // do this always

      Botan::LibraryInitializer init("thread_safe=no");

      if(opts.is_set("help") || argc <= 1)
         {
         std::cerr << "Test driver for "
                   << Botan::version_string() << "\n"
                   << "Options:\n"
                   << "  --test || --validate: Run tests (do this at least once)\n"
                   << "  --benchmark: Benchmark everything\n"
                   << "  --bench-type={block,mode,stream,hash,mac,rng,pk}:\n"
                   << "       Benchmark only algorithms of a particular type\n"
                   << "  --html: Produce HTML output for benchmarks\n"
                   << "  --seconds=n: Benchmark for n seconds\n"
                   << "  --init=<str>: Pass <str> to the library\n"
                   << "  --help: Print this message\n";
         return 1;
         }

      Botan::AutoSeeded_RNG rng;

      if(opts.is_set("validate") || opts.is_set("test"))
         {
         run_test_suite(rng);
         }
      if(opts.is_set("bench-algo") ||
         opts.is_set("benchmark") ||
         opts.is_set("bench-type"))
         {
         double seconds = 5;

         if(opts.is_set("seconds"))
            {
            seconds = std::atof(opts.value("seconds").c_str());
            if(seconds < 0.1 || seconds > (5 * 60))
               {
               std::cout << "Invalid argument to --seconds\n";
               return 2;
               }
            }

         const bool html = opts.is_set("html");

         if(opts.is_set("benchmark"))
            {
            benchmark("All", rng, html, seconds);
            }
         else if(opts.is_set("bench-algo"))
            {
            std::vector<std::string> algs =
               Botan::split_on(opts.value("bench-algo"), ',');

            for(u32bit j = 0; j != algs.size(); j++)
               {
               const std::string alg = algs[j];
               u32bit found = bench_algo(alg, rng, seconds);
               if(!found) // maybe it's a PK algorithm
                  bench_pk(rng, alg, html, seconds);
               }
            }
         else if(opts.is_set("bench-type"))
            {
            const std::string type = opts.value("bench-type");

            if(type == "all")
               benchmark("All", rng, html, seconds);
            else if(type == "block")
               benchmark("Block Cipher", rng, html, seconds);
            else if(type == "stream")
               benchmark("Stream Cipher", rng, html, seconds);
            else if(type == "hash")
               benchmark("Hash", rng, html, seconds);
            else if(type == "mode")
               benchmark("Cipher Mode", rng, html, seconds);
            else if(type == "mac")
               benchmark("MAC", rng, html, seconds);
            else if(type == "rng")
               benchmark("RNG", rng, html, seconds);
            else if(type == "pk")
               bench_pk(rng, "All", html, seconds);
            else
               std::cerr << "Unknown --bench-type " << type << "\n";
            }
         }
      }
   catch(std::exception& e)
      {
      std::cerr << "Exception: " << e.what() << std::endl;
      }
   catch(...)
      {
      std::cerr << "Unknown (...) exception caught" << std::endl;
      }

   return 0;
   }

int run_test_suite(RandomNumberGenerator& rng)
   {
   std::cout << "Beginning tests..." << std::endl;

   u32bit errors = 0;
   try
      {
      errors += do_validation_tests(VALIDATION_FILE, rng);
      errors += do_validation_tests(EXPECTED_FAIL_FILE, rng, false);
      errors += do_bigint_tests(BIGINT_VALIDATION_FILE, rng);
      errors += do_pk_validation_tests(PK_VALIDATION_FILE, rng);
      //errors += do_cvc_tests(rng);
      }
   catch(Botan::Exception& e)
      {
      std::cout << "Exception caught: " << e.what() << std::endl;
      return 1;
      }
   catch(std::exception& e)
      {
      std::cout << "Standard library exception caught: "
                << e.what() << std::endl;
      return 1;
      }
   catch(...)
      {
      std::cout << "Unknown exception caught." << std::endl;
      return 1;
      }

   if(errors)
      {
      std::cout << errors << " test"  << ((errors == 1) ? "" : "s")
                << " failed." << std::endl;
      return 1;
      }

   std::cout << "All tests passed!" << std::endl;
   return 0;
   }
<commit_msg>Move AutoSeeded_RNG decl before check for --help flag, so startup time is easy to measure<commit_after>/*
 * Test Driver for Botan
 */

#include <vector>
#include <string>

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <limits>
#include <memory>

#include <botan/botan.h>
#include <botan/libstate.h>
#include <botan/mp_types.h>

using namespace Botan;

#include "getopt.h"
#include "bench.h"
#include "validate.h"
#include "common.h"

const std::string VALIDATION_FILE = "checks/validate.dat";
const std::string BIGINT_VALIDATION_FILE = "checks/mp_valid.dat";
const std::string PK_VALIDATION_FILE = "checks/pk_valid.dat";
const std::string EXPECTED_FAIL_FILE = "checks/fail.dat";

int run_test_suite(RandomNumberGenerator& rng);

namespace {

template<typename T>
bool test(const char* type, int digits, bool is_signed)
   {
   if(std::numeric_limits<T>::is_specialized == false)
      {
      std::cout << "WARNING: Could not check parameters of " << type
                << " in std::numeric_limits" << std::endl;

      // assume it's OK (full tests will catch it later)
      return true;
      }

   // continue checking after failures
   bool passed = true;

   if(std::numeric_limits<T>::is_integer == false)
      {
      std::cout << "WARN: std::numeric_limits<> says " << type
                << " is not an integer" << std::endl;
      passed = false;
      }

   if(std::numeric_limits<T>::is_signed != is_signed)
      {
      std::cout << "ERROR: numeric_limits<" << type << ">::is_signed == "
                << std::boolalpha << std::numeric_limits<T>::is_signed
                << std::endl;
      passed = false;
      }

   if(std::numeric_limits<T>::digits != digits && digits != 0)
      {
      std::cout << "ERROR: numeric_limits<" << type << ">::digits == "
                << std::numeric_limits<T>::digits
                << " expected " << digits << std::endl;
      passed = false;
      }

   return passed;
   }

void test_types()
   {
   bool passed = true;

   passed = passed && test<Botan::byte  >("byte",    8, false);
   passed = passed && test<Botan::u16bit>("u16bit", 16, false);
   passed = passed && test<Botan::u32bit>("u32bit", 32, false);
   passed = passed && test<Botan::u64bit>("u64bit", 64, false);
   passed = passed && test<Botan::s32bit>("s32bit", 31,  true);
   passed = passed && test<Botan::word>("word", 0, false);

   if(!passed)
      std::cout << "Typedefs in include/types.h may be incorrect!\n";
   }

}

int main(int argc, char* argv[])
   {
   try
      {
      OptionParser opts("help|html|test|validate|"
                        "benchmark|bench-type=|bench-algo=|seconds=");
      opts.parse(argv);

      test_types(); // do this always

      Botan::LibraryInitializer init("thread_safe=no");

      Botan::AutoSeeded_RNG rng;

      if(opts.is_set("help") || argc <= 1)
         {
         std::cerr << "Test driver for "
                   << Botan::version_string() << "\n"
                   << "Options:\n"
                   << "  --test || --validate: Run tests (do this at least once)\n"
                   << "  --benchmark: Benchmark everything\n"
                   << "  --bench-type={block,mode,stream,hash,mac,rng,pk}:\n"
                   << "       Benchmark only algorithms of a particular type\n"
                   << "  --html: Produce HTML output for benchmarks\n"
                   << "  --seconds=n: Benchmark for n seconds\n"
                   << "  --init=<str>: Pass <str> to the library\n"
                   << "  --help: Print this message\n";
         return 1;
         }

      if(opts.is_set("validate") || opts.is_set("test"))
         {
         run_test_suite(rng);
         }
      if(opts.is_set("bench-algo") ||
         opts.is_set("benchmark") ||
         opts.is_set("bench-type"))
         {
         double seconds = 5;

         if(opts.is_set("seconds"))
            {
            seconds = std::atof(opts.value("seconds").c_str());
            if(seconds < 0.1 || seconds > (5 * 60))
               {
               std::cout << "Invalid argument to --seconds\n";
               return 2;
               }
            }

         const bool html = opts.is_set("html");

         if(opts.is_set("benchmark"))
            {
            benchmark("All", rng, html, seconds);
            }
         else if(opts.is_set("bench-algo"))
            {
            std::vector<std::string> algs =
               Botan::split_on(opts.value("bench-algo"), ',');

            for(u32bit j = 0; j != algs.size(); j++)
               {
               const std::string alg = algs[j];
               u32bit found = bench_algo(alg, rng, seconds);
               if(!found) // maybe it's a PK algorithm
                  bench_pk(rng, alg, html, seconds);
               }
            }
         else if(opts.is_set("bench-type"))
            {
            const std::string type = opts.value("bench-type");

            if(type == "all")
               benchmark("All", rng, html, seconds);
            else if(type == "block")
               benchmark("Block Cipher", rng, html, seconds);
            else if(type == "stream")
               benchmark("Stream Cipher", rng, html, seconds);
            else if(type == "hash")
               benchmark("Hash", rng, html, seconds);
            else if(type == "mode")
               benchmark("Cipher Mode", rng, html, seconds);
            else if(type == "mac")
               benchmark("MAC", rng, html, seconds);
            else if(type == "rng")
               benchmark("RNG", rng, html, seconds);
            else if(type == "pk")
               bench_pk(rng, "All", html, seconds);
            else
               std::cerr << "Unknown --bench-type " << type << "\n";
            }
         }
      }
   catch(std::exception& e)
      {
      std::cerr << "Exception: " << e.what() << std::endl;
      }
   catch(...)
      {
      std::cerr << "Unknown (...) exception caught" << std::endl;
      }

   return 0;
   }

int run_test_suite(RandomNumberGenerator& rng)
   {
   std::cout << "Beginning tests..." << std::endl;

   u32bit errors = 0;
   try
      {
      errors += do_validation_tests(VALIDATION_FILE, rng);
      errors += do_validation_tests(EXPECTED_FAIL_FILE, rng, false);
      errors += do_bigint_tests(BIGINT_VALIDATION_FILE, rng);
      errors += do_pk_validation_tests(PK_VALIDATION_FILE, rng);
      //errors += do_cvc_tests(rng);
      }
   catch(Botan::Exception& e)
      {
      std::cout << "Exception caught: " << e.what() << std::endl;
      return 1;
      }
   catch(std::exception& e)
      {
      std::cout << "Standard library exception caught: "
                << e.what() << std::endl;
      return 1;
      }
   catch(...)
      {
      std::cout << "Unknown exception caught." << std::endl;
      return 1;
      }

   if(errors)
      {
      std::cout << errors << " test"  << ((errors == 1) ? "" : "s")
                << " failed." << std::endl;
      return 1;
      }

   std::cout << "All tests passed!" << std::endl;
   return 0;
   }
<|endoftext|>


<commit_before>/**************************************************************************/
/**
**       TODDLER: Slimmed-down version of CHILD without Vegetation,
**                Stream Meandering, or mesh densification.
**
**                            C H I L D
**
**       CHANNEL-HILLSLOPE INTEGRATED LANDSCAPE DEVELOPMENT MODEL
**
**                      VERSION 2.1.2, JUNE 2000
**
**  Designed and created by Gregory E. Tucker, Stephen T. Lancaster,
**      Nicole M. Gasparini, and Rafael L. Bras, Department of Civil
**      and Environmental Engineering, Massachusetts Institute of
**      Technology, Cambridge, MA, USA.
**
**  @file toddlermain.cpp
**  @brief This file contains the main() routine that handles
**         top-level initialization and implements the main
**         time-loop.
**
**  NOTE: This source code is copyrighted material. It is distributed
**        solely for noncommercial research and educational purposes
**        only. Use in whole or in part for commercial purposes without
**        a written license from the copyright holder(s) is expressly
**        prohibited. Copies of this source code or any of its components
**        may not be transferred to any other individuals or organizations
**        without written consent. Copyright (C) Massachusetts Institute
**        of Technology, 1997-2000. All rights reserved.
**
**  For information regarding this program, please contact Greg Tucker at:
**
**       School of Geography and the Environment
**       University of Oxford
**       Mansfield Road
**       Oxford OX1 3TB United Kingdom
**
**  $Id: toddlermain.cpp,v 1.10 2003-05-23 12:02:51 childcvs Exp $
*/
/**************************************************************************/

/* set traps for some floating point exceptions on Linux */
#include "trapfpe.h"
#include "Inclusions.h"
#include "tFloodplain/tFloodplain.h"
#include "tEolian/tEolian.h"

Predicates predicate;

int main( int argc, char **argv )
{
   int silent_mode,       // Option for silent mode (no time output to stdout)
       optDetachLim,      // Option for detachment-limited erosion only
       optFloodplainDep,  // Option for floodplain (overbank) deposition
       optLoessDep,       // Option for eolian deposition
       optVegetation,     // Option for dynamic vegetation cover
       optDiffuseDepo;    // Option for deposition / no deposition by diff'n
   tVegetation *vegetation(0);  // -> vegetation object
   tFloodplain *floodplain(0);  // -> floodplain object
   tEolian *loess(0);           // -> eolian deposition object

   /****************** INITIALIZATION *************************************\
   **  ALGORITHM
   **    Get command-line arguments (name of input file + any other opts)
   **    Set silent_mode flag
   **    Open main input file
   **    Create and initialize objects for...
   **      Mesh
   **      Output files
   **      Storm
   **      Stream network
   **      Erosion
   **      Uplift (or baselevel change)
   **      Run timer
   **    Write output for initial state
   **    Get options for erosion type, meandering, etc.
   \**********************************************************************/

   // Check command-line arguments
   if( argc<2 )
   {
      cerr << "Usage: " << argv[0] << " <input file>" << endl;
      ReportFatalError( "You need to give the name of an input file." );
   }

   // Check whether we're in silent mode
   silent_mode = ( argc>2 && argv[2][1]=='s' );

   // Say hello
   cout << "\nThis is TODDLER, version " << VERSION
	<< " (compiled " __DATE__ " " __TIME__ ")"
	<< endl << endl;

   // Open main input file
   tInputFile inputFile( argv[1] );

   // Create and initialize objects:
   cout << "Creating mesh...\n";
   tMesh<tLNode> mesh( inputFile );
   cout << "Creating output files...\n";
   tLOutput<tLNode> output( &mesh, inputFile );
   tStorm storm( inputFile );
   cout << "Creating stream network...\n";
   tStreamNet strmNet( mesh, storm, inputFile );
   tErosion erosion( &mesh, inputFile );
   tUplift uplift( inputFile );
   cout << "Writing data for time zero...\n";
   tRunTimer time( inputFile, !silent_mode );
   output.WriteOutput( 0 );
   cout << "Initialization done.\n";

   // Get various options
   optDetachLim = inputFile.ReadItem( optDetachLim, "OPTDETACHLIM" );
   optDiffuseDepo = inputFile.ReadItem( optDiffuseDepo, "OPTDIFFDEP" );
   optVegetation = inputFile.ReadItem( optVegetation, "OPTVEG" );
   optFloodplainDep = inputFile.ReadItem( optFloodplainDep, "OPTFLOODPLAIN" );
   optLoessDep = inputFile.ReadItem( optLoessDep, "OPTLOESSDEP" );

   // If applicable, create Vegetation object
   if( optVegetation )
       vegetation = new tVegetation( &mesh, inputFile );

   // If applicable, create floodplain object
   if( optFloodplainDep )
       floodplain = new tFloodplain( inputFile, &mesh );

   // If applicable, create eolian deposition object
   if( optLoessDep )
       loess = new tEolian( inputFile );

   // Option for time series output (IN PROGRESS)
   /*   switch( optTSOutput ){
   case 1:   // Volume output each N years.
     if( time.CheckTSOutputTime() )
       output.WriteVolOutput();
     break;
   case 2:   // Volume and vegetation cover output each N years.
     cout << "here" << endl;
     if( time.CheckTSOutputTime() ){
       cout << "there" << endl;
       output.WriteVolVegOutput();}
     break;
   case 3:   // All data at each storm.
     output.WriteTSOutput();
     break;
   case 0:   // No additional timeseries output.
     break;
   default:  // Invalid option.
     ReportFatalError( "The input file contains an invalid value for
OptTSOutput." );
   }   */

   // Temporary -- for canyon range stuff
   /*cout << "Densifying around fold strike ...\n";
   int optFoldDens = inputFile.ReadItem( optFoldDens, "OPTFOLDDENS" );
   if( optFoldDens )
     {
       double foldDensYmin = inputFile.ReadItem( foldDensYmin, "FOLDDENSYMIN" );
       double foldDensYmax = inputFile.ReadItem( foldDensYmax, "FOLDDENSYMAX" );
       double fault = inputFile.ReadItem( fault, "FAULTPOS" );
       for( int i=1; i<=optFoldDens; i++ )
	 {
	   tPtrList<tLNode> foldPoints;
	   tMeshListIter<tLNode> ni( mesh.getNodeList() );
	   tLNode *cn;
	   for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() )
	     {
	     if( cn->getY()>=foldDensYmin && cn->getY()<=foldDensYmax &&
		 cn->getX()>=7500 && cn->getX()<=92500 )
	       foldPoints.insertAtBack( cn );
	     if( cn->getY()<fault )
	       cn->setAlluvThickness( 100000 );
	     }
	   tPtrListIter<tLNode> fpi( foldPoints );
	   for( cn=fpi.FirstP(); !(fpi.AtEnd()); cn=fpi.NextP() )
	     mesh.AddNodesAround( cn, 0.0 );
	   foldPoints.Flush();
	 }
	 }*/

   /**************** MAIN LOOP ******************************************\
   **  ALGORITHM
   **    Generate storm
   **    Do storm...
   **      Update network (flow directions, drainage area, runoff)
   **      Water erosion/deposition (vertical)
   **      Meandering (if applicable)
   **      Floodplain deposition (if applicable)
   **    Do interstorm...
   **      Hillslope transport
   **      Vegetation (if applicable)
   **      Exposure history
   **      Mesh densification (if applicable)
   **      Eolian (loess) deposition (if applicable)
   **      Uplift (or baselevel change)
   **********************************************************************/
   while( !time.IsFinished() )
   {
      time.ReportTimeStatus();

      // Do storm...
      storm.GenerateStorm( time.getCurrentTime(),
                           strmNet.getInfilt(), strmNet.getSoilStore() );
      cout << storm.getRainrate() << " " << storm.getStormDuration() << " "
           << storm.interstormDur() << endl;

      strmNet.UpdateNet( time.getCurrentTime(), storm );

      if( optDetachLim )
          erosion.ErodeDetachLim( storm.getStormDuration(), &strmNet );
      else
          erosion.DetachErode( storm.getStormDuration(), &strmNet,
                               time.getCurrentTime() );

      if( optVegetation )
	  vegetation->UpdateVegetation( &mesh, storm.getStormDuration(),
					storm.interstormDur() );

      if( optFloodplainDep )
          floodplain->DepositOverbank( storm.getRainrate(),
                                       storm.getStormDuration(),
                                       time.getCurrentTime() );

      // Do interstorm...
      erosion.Diffuse( storm.getStormDuration() + storm.interstormDur(),
      optDiffuseDepo );

      erosion.UpdateExposureTime( storm.getStormDuration() +
                                      storm.interstormDur() );

      if( optLoessDep )
          loess->DepositLoess( &mesh,
                               storm.getStormDuration()+storm.interstormDur(),
                               time.getCurrentTime() );

      if( time.getCurrentTime() < uplift.getDuration() )
          uplift.DoUplift( &mesh,
                           storm.getStormDuration() + storm.interstormDur() );

      time.Advance( storm.getStormDuration() + storm.interstormDur() );

      if( time.CheckOutputTime() )
          output.WriteOutput( time.getCurrentTime() );

      if( output.OptTSOutput() ) output.WriteTSOutput();

      /* IN PROGRESS
      switch( optTSOutput ){
      case 1:   // Volume output each N years.
        if( time.CheckTSOutputTime() )
  output.WriteVolOutput();
break;
      case 2:   // Volume and vegetation cover output each N years.
if( time.CheckTSOutputTime() )
  output.WriteVolVegOutput();
break;
      case 3:   // All data at each storm.
output.WriteTSOutput();
break;
      case 0:   // No additional timeseries output.
break;
      default:  // Invalid option.
ReportFatalError( "The input file contains an invalid value for OptTSOutput."
*/

     /*tMeshListIter<tLNode> ni( mesh.getNodeList() );
      tLNode *cn;
      for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() )
	{
	  if( cn->getY()<25 && cn->getX()>250 && cn->getDrArea()>1000 )
	    cn->TellAll();
	}*/

   } // end of main loop

   delete tVegetation;
   delete tFloodplain;
   delete tEolian;

   return 0;
}

<commit_msg>(Arnaud) deallocate memory<commit_after>/**************************************************************************/
/**
**       TODDLER: Slimmed-down version of CHILD without Vegetation,
**                Stream Meandering, or mesh densification.
**
**                            C H I L D
**
**       CHANNEL-HILLSLOPE INTEGRATED LANDSCAPE DEVELOPMENT MODEL
**
**                      VERSION 2.1.2, JUNE 2000
**
**  Designed and created by Gregory E. Tucker, Stephen T. Lancaster,
**      Nicole M. Gasparini, and Rafael L. Bras, Department of Civil
**      and Environmental Engineering, Massachusetts Institute of
**      Technology, Cambridge, MA, USA.
**
**  @file toddlermain.cpp
**  @brief This file contains the main() routine that handles
**         top-level initialization and implements the main
**         time-loop.
**
**  NOTE: This source code is copyrighted material. It is distributed
**        solely for noncommercial research and educational purposes
**        only. Use in whole or in part for commercial purposes without
**        a written license from the copyright holder(s) is expressly
**        prohibited. Copies of this source code or any of its components
**        may not be transferred to any other individuals or organizations
**        without written consent. Copyright (C) Massachusetts Institute
**        of Technology, 1997-2000. All rights reserved.
**
**  For information regarding this program, please contact Greg Tucker at:
**
**       School of Geography and the Environment
**       University of Oxford
**       Mansfield Road
**       Oxford OX1 3TB United Kingdom
**
**  $Id: toddlermain.cpp,v 1.11 2003-05-23 12:04:29 childcvs Exp $
*/
/**************************************************************************/

/* set traps for some floating point exceptions on Linux */
#include "trapfpe.h"
#include "Inclusions.h"
#include "tFloodplain/tFloodplain.h"
#include "tEolian/tEolian.h"

Predicates predicate;

int main( int argc, char **argv )
{
   int silent_mode,       // Option for silent mode (no time output to stdout)
       optDetachLim,      // Option for detachment-limited erosion only
       optFloodplainDep,  // Option for floodplain (overbank) deposition
       optLoessDep,       // Option for eolian deposition
       optVegetation,     // Option for dynamic vegetation cover
       optDiffuseDepo;    // Option for deposition / no deposition by diff'n
   tVegetation *vegetation(0);  // -> vegetation object
   tFloodplain *floodplain(0);  // -> floodplain object
   tEolian *loess(0);           // -> eolian deposition object

   /****************** INITIALIZATION *************************************\
   **  ALGORITHM
   **    Get command-line arguments (name of input file + any other opts)
   **    Set silent_mode flag
   **    Open main input file
   **    Create and initialize objects for...
   **      Mesh
   **      Output files
   **      Storm
   **      Stream network
   **      Erosion
   **      Uplift (or baselevel change)
   **      Run timer
   **    Write output for initial state
   **    Get options for erosion type, meandering, etc.
   \**********************************************************************/

   // Check command-line arguments
   if( argc<2 )
   {
      cerr << "Usage: " << argv[0] << " <input file>" << endl;
      ReportFatalError( "You need to give the name of an input file." );
   }

   // Check whether we're in silent mode
   silent_mode = ( argc>2 && argv[2][1]=='s' );

   // Say hello
   cout << "\nThis is TODDLER, version " << VERSION
	<< " (compiled " __DATE__ " " __TIME__ ")"
	<< endl << endl;

   // Open main input file
   tInputFile inputFile( argv[1] );

   // Create and initialize objects:
   cout << "Creating mesh...\n";
   tMesh<tLNode> mesh( inputFile );
   cout << "Creating output files...\n";
   tLOutput<tLNode> output( &mesh, inputFile );
   tStorm storm( inputFile );
   cout << "Creating stream network...\n";
   tStreamNet strmNet( mesh, storm, inputFile );
   tErosion erosion( &mesh, inputFile );
   tUplift uplift( inputFile );
   cout << "Writing data for time zero...\n";
   tRunTimer time( inputFile, !silent_mode );
   output.WriteOutput( 0 );
   cout << "Initialization done.\n";

   // Get various options
   optDetachLim = inputFile.ReadItem( optDetachLim, "OPTDETACHLIM" );
   optDiffuseDepo = inputFile.ReadItem( optDiffuseDepo, "OPTDIFFDEP" );
   optVegetation = inputFile.ReadItem( optVegetation, "OPTVEG" );
   optFloodplainDep = inputFile.ReadItem( optFloodplainDep, "OPTFLOODPLAIN" );
   optLoessDep = inputFile.ReadItem( optLoessDep, "OPTLOESSDEP" );

   // If applicable, create Vegetation object
   if( optVegetation )
       vegetation = new tVegetation( &mesh, inputFile );

   // If applicable, create floodplain object
   if( optFloodplainDep )
       floodplain = new tFloodplain( inputFile, &mesh );

   // If applicable, create eolian deposition object
   if( optLoessDep )
       loess = new tEolian( inputFile );

   // Option for time series output (IN PROGRESS)
   /*   switch( optTSOutput ){
   case 1:   // Volume output each N years.
     if( time.CheckTSOutputTime() )
       output.WriteVolOutput();
     break;
   case 2:   // Volume and vegetation cover output each N years.
     cout << "here" << endl;
     if( time.CheckTSOutputTime() ){
       cout << "there" << endl;
       output.WriteVolVegOutput();}
     break;
   case 3:   // All data at each storm.
     output.WriteTSOutput();
     break;
   case 0:   // No additional timeseries output.
     break;
   default:  // Invalid option.
     ReportFatalError( "The input file contains an invalid value for
OptTSOutput." );
   }   */

   // Temporary -- for canyon range stuff
   /*cout << "Densifying around fold strike ...\n";
   int optFoldDens = inputFile.ReadItem( optFoldDens, "OPTFOLDDENS" );
   if( optFoldDens )
     {
       double foldDensYmin = inputFile.ReadItem( foldDensYmin, "FOLDDENSYMIN" );
       double foldDensYmax = inputFile.ReadItem( foldDensYmax, "FOLDDENSYMAX" );
       double fault = inputFile.ReadItem( fault, "FAULTPOS" );
       for( int i=1; i<=optFoldDens; i++ )
	 {
	   tPtrList<tLNode> foldPoints;
	   tMeshListIter<tLNode> ni( mesh.getNodeList() );
	   tLNode *cn;
	   for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() )
	     {
	     if( cn->getY()>=foldDensYmin && cn->getY()<=foldDensYmax &&
		 cn->getX()>=7500 && cn->getX()<=92500 )
	       foldPoints.insertAtBack( cn );
	     if( cn->getY()<fault )
	       cn->setAlluvThickness( 100000 );
	     }
	   tPtrListIter<tLNode> fpi( foldPoints );
	   for( cn=fpi.FirstP(); !(fpi.AtEnd()); cn=fpi.NextP() )
	     mesh.AddNodesAround( cn, 0.0 );
	   foldPoints.Flush();
	 }
	 }*/

   /**************** MAIN LOOP ******************************************\
   **  ALGORITHM
   **    Generate storm
   **    Do storm...
   **      Update network (flow directions, drainage area, runoff)
   **      Water erosion/deposition (vertical)
   **      Meandering (if applicable)
   **      Floodplain deposition (if applicable)
   **    Do interstorm...
   **      Hillslope transport
   **      Vegetation (if applicable)
   **      Exposure history
   **      Mesh densification (if applicable)
   **      Eolian (loess) deposition (if applicable)
   **      Uplift (or baselevel change)
   **********************************************************************/
   while( !time.IsFinished() )
   {
      time.ReportTimeStatus();

      // Do storm...
      storm.GenerateStorm( time.getCurrentTime(),
                           strmNet.getInfilt(), strmNet.getSoilStore() );
      cout << storm.getRainrate() << " " << storm.getStormDuration() << " "
           << storm.interstormDur() << endl;

      strmNet.UpdateNet( time.getCurrentTime(), storm );

      if( optDetachLim )
          erosion.ErodeDetachLim( storm.getStormDuration(), &strmNet );
      else
          erosion.DetachErode( storm.getStormDuration(), &strmNet,
                               time.getCurrentTime() );

      if( optVegetation )
	  vegetation->UpdateVegetation( &mesh, storm.getStormDuration(),
					storm.interstormDur() );

      if( optFloodplainDep )
          floodplain->DepositOverbank( storm.getRainrate(),
                                       storm.getStormDuration(),
                                       time.getCurrentTime() );

      // Do interstorm...
      erosion.Diffuse( storm.getStormDuration() + storm.interstormDur(),
      optDiffuseDepo );

      erosion.UpdateExposureTime( storm.getStormDuration() +
                                      storm.interstormDur() );

      if( optLoessDep )
          loess->DepositLoess( &mesh,
                               storm.getStormDuration()+storm.interstormDur(),
                               time.getCurrentTime() );

      if( time.getCurrentTime() < uplift.getDuration() )
          uplift.DoUplift( &mesh,
                           storm.getStormDuration() + storm.interstormDur() );

      time.Advance( storm.getStormDuration() + storm.interstormDur() );

      if( time.CheckOutputTime() )
          output.WriteOutput( time.getCurrentTime() );

      if( output.OptTSOutput() ) output.WriteTSOutput();

      /* IN PROGRESS
      switch( optTSOutput ){
      case 1:   // Volume output each N years.
        if( time.CheckTSOutputTime() )
  output.WriteVolOutput();
break;
      case 2:   // Volume and vegetation cover output each N years.
if( time.CheckTSOutputTime() )
  output.WriteVolVegOutput();
break;
      case 3:   // All data at each storm.
output.WriteTSOutput();
break;
      case 0:   // No additional timeseries output.
break;
      default:  // Invalid option.
ReportFatalError( "The input file contains an invalid value for OptTSOutput."
*/

     /*tMeshListIter<tLNode> ni( mesh.getNodeList() );
      tLNode *cn;
      for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() )
	{
	  if( cn->getY()<25 && cn->getX()>250 && cn->getDrArea()>1000 )
	    cn->TellAll();
	}*/

   } // end of main loop

   delete vegetation;
   delete floodplain;
   delete loess;

   return 0;
}

<|endoftext|>


<commit_before>// Copyright 2022 DeepMind Technologies Limited
//
// 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 "open_spiel/games/checkers.h"

#include "open_spiel/spiel.h"
#include "open_spiel/tests/basic_tests.h"

namespace open_spiel {
namespace checkers {
namespace {

namespace testing = open_spiel::testing;

void BasicSerializationTest() {
  std::shared_ptr<const Game> game = LoadGame("checkers");
  std::unique_ptr<State> state = game->NewInitialState();
  std::unique_ptr<State> state2 = game->DeserializeState(state->Serialize());
  SPIEL_CHECK_EQ(state->ToString(), state2->ToString());
}

void BasicCheckersTests() {
  testing::LoadGameTest("checkers");
  testing::NoChanceOutcomesTest(*LoadGame("checkers"));
  testing::RandomSimTest(*LoadGame("checkers"), 100);
  testing::RandomSimTestWithUndo(*LoadGame("checkers"), 10);
}

// Board:
// 8........
// 7..*.....
// 6........
// 5....+.o.
// 4.....o..
// 3+.......
// 2...+....
// 1o.o.....
//  abcdefgh
// Player 0 should be able to do a double jump and crown a piece at b8
void MultipleJumpTest() {
  std::shared_ptr<const Game> game = LoadGame("checkers");
  std::unique_ptr<State> state = game->NewInitialState();
  CheckersState* cstate = static_cast<CheckersState*>(state.get());
  cstate->SetCustomBoard("0..........*.................+.o......o..+..........+....o.o.....");
  cstate->ApplyAction(cstate->LegalActions()[0]);
  // Confirm that player 0 is given only one action (f4 token is in the middle
  // of a multiple jump) and there's a capture opportunity for c1 piece as well
  // (which cannot be moved in this extra move)
  SPIEL_CHECK_EQ(cstate->LegalActions().size(), 1);
  cstate->ApplyAction(cstate->LegalActions()[0]);
  SPIEL_CHECK_EQ(cstate->BoardAt(0, 1), CellState::kWhiteKing);
  SPIEL_CHECK_EQ(cstate->BoardAt(1, 2), CellState::kEmpty);
  SPIEL_CHECK_EQ(cstate->BoardAt(3, 4), CellState::kEmpty);
}

// Board:
// 8...8....
// 7........
// 6........
// 5....+...
// 4........
// 3+.......
// 2........
// 1........
//  abcdefgh
// Player 0 should be able to move the crowned piece backwards
void CrownedPieceCanMoveBackwardsTest() {
  std::shared_ptr<const Game> game = LoadGame("checkers");
  std::unique_ptr<State> state = game->NewInitialState();
  CheckersState* cstate = static_cast<CheckersState*>(state.get());
  cstate->SetCustomBoard("0...8........................+...........+.......................");
  std::vector<Action> legal_actions = cstate->LegalActions();
  cstate->ApplyAction(legal_actions[0]);
  SPIEL_CHECK_EQ(cstate->BoardAt(1, 4), CellState::kWhiteKing);
}

// Board:
// 8........
// 7....+.+.
// 6........
// 5....+.o.
// 4.....o..
// 3+.......
// 2........
// 1o.o.....
//  abcdefgh
// Player 0 move should end after piece crowned
void MoveShouldEndAfterPieceCrownedTest() {
  std::shared_ptr<const Game> game = LoadGame("checkers");
  std::unique_ptr<State> state = game->NewInitialState();
  CheckersState* cstate = static_cast<CheckersState*>(state.get());
  cstate->SetCustomBoard("0............+.+.............+.o......o..+...............o.o.....");
  cstate->ApplyAction(cstate->LegalActions()[0]);
  cstate->ApplyAction(cstate->LegalActions()[0]);
  SPIEL_CHECK_EQ(cstate->CurrentPlayer(), 1);
}

}  // namespace
}  // namespace checkers
}  // namespace open_spiel

int main(int argc, char** argv) {
  open_spiel::checkers::BasicSerializationTest();
  open_spiel::checkers::BasicCheckersTests();
  open_spiel::checkers::MultipleJumpTest();
  open_spiel::checkers::CrownedPieceCanMoveBackwardsTest();
  open_spiel::checkers::MoveShouldEndAfterPieceCrownedTest();
}
<commit_msg>RandomSerializationTest added<commit_after>// Copyright 2022 DeepMind Technologies Limited
//
// 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 "open_spiel/games/checkers.h"

#include "open_spiel/spiel.h"
#include "open_spiel/tests/basic_tests.h"

namespace open_spiel {
namespace checkers {
namespace {

namespace testing = open_spiel::testing;

void BasicSerializationTest() {
  std::shared_ptr<const Game> game = LoadGame("checkers");
  std::unique_ptr<State> state = game->NewInitialState();
  std::unique_ptr<State> state2 = game->DeserializeState(state->Serialize());
  SPIEL_CHECK_EQ(state->ToString(), state2->ToString());
}

void RandomSerializationTest() {
  std::shared_ptr<const Game> game = LoadGame("checkers");
  std::unique_ptr<State> state = game->NewInitialState();
  for(int i = 0; i < 20; ++i) {
    state->ApplyAction(state->LegalActions()[0]);
  }
  std::unique_ptr<State> state2 = game->DeserializeState(state->Serialize());
  SPIEL_CHECK_EQ(state->ToString(), state2->ToString());
}

void BasicCheckersTests() {
  testing::LoadGameTest("checkers");
  testing::NoChanceOutcomesTest(*LoadGame("checkers"));
  testing::RandomSimTest(*LoadGame("checkers"), 100);
  testing::RandomSimTestWithUndo(*LoadGame("checkers"), 10);
}

// Board:
// 8........
// 7..*.....
// 6........
// 5....+.o.
// 4.....o..
// 3+.......
// 2...+....
// 1o.o.....
//  abcdefgh
// Player 0 should be able to do a double jump and crown a piece at b8
void MultipleJumpTest() {
  std::shared_ptr<const Game> game = LoadGame("checkers");
  std::unique_ptr<State> state = game->NewInitialState();
  CheckersState* cstate = static_cast<CheckersState*>(state.get());
  cstate->SetCustomBoard("0..........*.................+.o......o..+..........+....o.o.....");
  cstate->ApplyAction(cstate->LegalActions()[0]);
  // Confirm that player 0 is given only one action (f4 token is in the middle
  // of a multiple jump) and there's a capture opportunity for c1 piece as well
  // (which cannot be moved in this extra move)
  SPIEL_CHECK_EQ(cstate->LegalActions().size(), 1);
  cstate->ApplyAction(cstate->LegalActions()[0]);
  SPIEL_CHECK_EQ(cstate->BoardAt(0, 1), CellState::kWhiteKing);
  SPIEL_CHECK_EQ(cstate->BoardAt(1, 2), CellState::kEmpty);
  SPIEL_CHECK_EQ(cstate->BoardAt(3, 4), CellState::kEmpty);
}

// Board:
// 8...8....
// 7........
// 6........
// 5....+...
// 4........
// 3+.......
// 2........
// 1........
//  abcdefgh
// Player 0 should be able to move the crowned piece backwards
void CrownedPieceCanMoveBackwardsTest() {
  std::shared_ptr<const Game> game = LoadGame("checkers");
  std::unique_ptr<State> state = game->NewInitialState();
  CheckersState* cstate = static_cast<CheckersState*>(state.get());
  cstate->SetCustomBoard("0...8........................+...........+.......................");
  std::vector<Action> legal_actions = cstate->LegalActions();
  cstate->ApplyAction(legal_actions[0]);
  SPIEL_CHECK_EQ(cstate->BoardAt(1, 4), CellState::kWhiteKing);
}

// Board:
// 8........
// 7....+.+.
// 6........
// 5....+.o.
// 4.....o..
// 3+.......
// 2........
// 1o.o.....
//  abcdefgh
// Player 0 move should end after piece crowned
void MoveShouldEndAfterPieceCrownedTest() {
  std::shared_ptr<const Game> game = LoadGame("checkers");
  std::unique_ptr<State> state = game->NewInitialState();
  CheckersState* cstate = static_cast<CheckersState*>(state.get());
  cstate->SetCustomBoard("0............+.+.............+.o......o..+...............o.o.....");
  cstate->ApplyAction(cstate->LegalActions()[0]);
  cstate->ApplyAction(cstate->LegalActions()[0]);
  SPIEL_CHECK_EQ(cstate->CurrentPlayer(), 1);
}

}  // namespace
}  // namespace checkers
}  // namespace open_spiel

int main(int argc, char** argv) {
  open_spiel::checkers::BasicSerializationTest();
  open_spiel::checkers::RandomSerializationTest();
  open_spiel::checkers::BasicCheckersTests();
  open_spiel::checkers::MultipleJumpTest();
  open_spiel::checkers::CrownedPieceCanMoveBackwardsTest();
  open_spiel::checkers::MoveShouldEndAfterPieceCrownedTest();
}
<|endoftext|>