示例#1
0
namespace boost { namespace hana {
    //! @ingroup group-datatypes
    //! A `Monad` for searching infinite sets in finite time.
    //!
    //! Taken from http://math.andrej.com/2008/11/21/a-haskell-monad-for-infinite-search-in-finite-time/.
    struct SearchableSet {
        struct hana {
            struct operators
                : boost::hana::operators::of<Comparable, Monad>
            { };
        };
    };

    template <typename Find, typename = operators::adl>
    struct _sset {
        Find find;
        struct hana { using datatype = SearchableSet; };
    };

    BOOST_HANA_CONSTEXPR_LAMBDA auto searchable_set = [](auto pred) {
        return _sset<decltype(pred)>{pred};
    };

    BOOST_HANA_CONSTEXPR_LAMBDA auto singleton = [](auto x) {
        return searchable_set([=](auto p) { return x; });
    };

    BOOST_HANA_CONSTEXPR_LAMBDA auto doubleton = [](auto x, auto y) {
        return searchable_set([=](auto p) {
            return if_(p(x), x, y);
        });
    };

    BOOST_HANA_CONSTEXPR_LAMBDA auto union_ = [](auto xs, auto ys) {
        return flatten(doubleton(xs, ys));
    };

    //////////////////////////////////////////////////////////////////////////
    // Comparable
    //////////////////////////////////////////////////////////////////////////
    template <>
    struct equal_impl<SearchableSet, SearchableSet> {
        template <typename Xs, typename Ys>
        static constexpr auto apply(Xs xs, Ys ys)
        { return and_(subset(xs, ys), subset(ys, xs)); }
    };


    //////////////////////////////////////////////////////////////////////////
    // Functor
    //////////////////////////////////////////////////////////////////////////
    template <>
    struct transform_impl<SearchableSet> {
        template <typename Set, typename F>
        static constexpr auto apply(Set set, F f) {
            return searchable_set([=](auto q) {
                return f(set.find([=](auto x) { return q(f(x)); }));
            });
        }
    };

    //////////////////////////////////////////////////////////////////////////
    // Applicative
    //////////////////////////////////////////////////////////////////////////
    template <>
    struct lift_impl<SearchableSet> {
        template <typename X>
        static constexpr auto apply(X x)
        { return singleton(x); }
    };

    template <>
    struct ap_impl<SearchableSet> {
        template <typename F, typename Set>
        static constexpr auto apply(F fset, Set set) {
            return flatten(transform(fset, [=](auto f) {
                return transform(set, f);
            }));
        }
    };

    //////////////////////////////////////////////////////////////////////////
    // Monad
    //////////////////////////////////////////////////////////////////////////
    template <>
    struct flatten_impl<SearchableSet> {
        template <typename Set>
        static constexpr auto apply(Set set) {
            return searchable_set([=](auto p) {
                return set.find([=](auto set) {
                    return any_of(set, p);
                }).find(p);
            });
        }
    };

    //////////////////////////////////////////////////////////////////////////
    // Searchable
    //////////////////////////////////////////////////////////////////////////
    template <>
    struct find_impl<SearchableSet> {
        template <typename Set, typename Pred>
        static constexpr auto apply(Set set, Pred p) {
            auto x = set.find(p);
            return if_(p(x), just(x), nothing);
        }
    };

    template <>
    struct any_of_impl<SearchableSet> {
        template <typename Set, typename Pred>
        static constexpr auto apply(Set set, Pred p) {
            return p(set.find(p));
        }
    };
}} // end namespace boost::hana
示例#2
0
int main()
{
	TabSample t;
	TabFoo f; 

	// MEMBER FUNCTIONS
	// ----------------
	
	// Test in
	{
		using TI = decltype(t.alpha.in(1, 2, 3));
		using TF = decltype(f.omega.in(1.0, 2.0, 3.0));
		using TT = decltype(t.beta.in("a", "b", "c"));
		static_assert(sqlpp::is_named_expression_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_named_expression_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_named_expression_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TT>::value, "type requirement");
	}

	// Test in with value list
	{
		using TI = decltype(t.alpha.in(sqlpp::value_list(std::vector<int>({1, 2, 3}))));
		using TF = decltype(f.omega.in(sqlpp::value_list(std::vector<float>({1.0, 2.0, 3.0}))));
		using TT = decltype(t.beta.in(sqlpp::value_list(std::vector<std::string>({"a", "b", "c"}))));
		static_assert(sqlpp::is_named_expression_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_named_expression_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_named_expression_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TT>::value, "type requirement");
	}

	// Test not_in
	{
		using TI = decltype(t.alpha.not_in(1, 2, 3));
		using TF = decltype(f.omega.not_in(1.0, 2.0, 3.0));
		using TT = decltype(t.beta.not_in("a", "b", "c"));
		static_assert(sqlpp::is_named_expression_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_named_expression_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_named_expression_t<TT>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TT>::value, "type requirement");
	}

	// Test not in with value list
	{
		using TI = decltype(t.alpha.not_in(sqlpp::value_list(std::vector<int>({1, 2, 3}))));
		using TF = decltype(f.omega.not_in(sqlpp::value_list(std::vector<float>({1.0, 2.0, 3.0}))));
		using TT = decltype(t.beta.not_in(sqlpp::value_list(std::vector<std::string>({"a", "b", "c"}))));
		static_assert(sqlpp::is_named_expression_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_named_expression_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_named_expression_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TT>::value, "type requirement");
	}

	// Test like
	{
		using TT = decltype(t.beta.like("%c%"));
		static_assert(sqlpp::is_named_expression_t<TT>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TT>::value, "type requirement");
	}

	// Test is_null
	{
		using TI = decltype(t.alpha.is_null());
		using TF = decltype(f.omega.is_null());
		using TT = decltype(t.beta.is_null());
		static_assert(sqlpp::is_named_expression_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_named_expression_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_named_expression_t<TT>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TT>::value, "type requirement");
	}

	// Test is_not_null
	{
		using TI = decltype(t.alpha.is_not_null());
		using TF = decltype(f.omega.is_not_null());
		using TT = decltype(t.beta.is_not_null());
		static_assert(sqlpp::is_named_expression_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_named_expression_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_named_expression_t<TT>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TT>::value, "type requirement");
	}

	// SUB_SELECT_FUNCTIONS
	// --------------------
	
	// Test exists
	{
		using TI = decltype(exists(select(t.alpha).from(t)));
		using TT = decltype(exists(select(t.beta).from(t)));
		static_assert(sqlpp::is_named_expression_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_named_expression_t<TT>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TT>::value, "type requirement");
	}

	// Test any
	{
		using TI = decltype(any(select(t.alpha).from(t)));
		using TT = decltype(any(select(t.beta).from(t)));
		using TF = decltype(any(select(f.omega).from(t)));
		static_assert(not sqlpp::is_named_expression_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_multi_expression_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_numeric_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_integral_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_named_expression_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_multi_expression_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_numeric_t<TF>::value, "tFpe requirement");
		static_assert(sqlpp::is_floating_point_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_named_expression_t<TT>::value, "type requirement");
		static_assert(sqlpp::is_multi_expression_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_integral_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_floating_point_t<TT>::value, "type requirement");
		static_assert(sqlpp::is_text_t<TT>::value, "type requirement");
	}

	// Test some
	{
		using TI = decltype(some(select(t.alpha).from(t)));
		using TT = decltype(some(select(t.beta).from(t)));
		using TF = decltype(some(select(f.omega).from(t)));
		static_assert(not sqlpp::is_named_expression_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_multi_expression_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_numeric_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_integral_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_numeric_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_named_expression_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_multi_expression_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_floating_point_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_text_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_named_expression_t<TT>::value, "type requirement");
		static_assert(sqlpp::is_multi_expression_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_integral_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_floating_point_t<TT>::value, "type requirement");
		static_assert(sqlpp::is_text_t<TT>::value, "type requirement");
	}

	// NUMERIC FUNCTIONS
  // -----------------

	// Test avg
	{
		using TI = decltype(avg(t.alpha));
		using TF = decltype(avg(f.omega));
		static_assert(sqlpp::is_named_expression_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_numeric_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_integral_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_floating_point_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_named_expression_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_numeric_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_integral_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_floating_point_t<TF>::value, "type requirement");
	}

	// Test count
	{
		using TI = decltype(count(t.alpha));
		using TT = decltype(count(t.beta));
		using TF = decltype(count(f.omega));
		static_assert(sqlpp::is_named_expression_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_numeric_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_integral_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_floating_point_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_named_expression_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_numeric_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_integral_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_floating_point_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_named_expression_t<TT>::value, "type requirement");
		static_assert(sqlpp::is_numeric_t<TT>::value, "type requirement");
		static_assert(sqlpp::is_integral_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_floating_point_t<TT>::value, "type requirement");
	}

	// Test max
	{
		using TI = decltype(max(t.alpha));
		using TF = decltype(max(f.omega));
		using TT = decltype(max(t.beta));
		static_assert(sqlpp::is_named_expression_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_numeric_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_integral_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_floating_point_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_named_expression_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_numeric_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_integral_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_floating_point_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_named_expression_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TT>::value, "type requirement");
		static_assert(sqlpp::is_text_t<TT>::value, "type requirement");
	}

	// Test min
	{
		using TI = decltype(min(t.alpha));
		using TF = decltype(min(f.omega));
		using TT = decltype(min(t.beta));
		static_assert(sqlpp::is_named_expression_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_numeric_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_integral_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_floating_point_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_named_expression_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_numeric_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_integral_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_floating_point_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_named_expression_t<TT>::value, "type requirement");
		static_assert(not sqlpp::is_numeric_t<TT>::value, "type requirement");
		static_assert(sqlpp::is_text_t<TT>::value, "type requirement");
	}

	// Test sum
	{
		using TI = decltype(sum(t.alpha));
		using TF = decltype(sum(f.omega));
		static_assert(sqlpp::is_named_expression_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_numeric_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_integral_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_floating_point_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_named_expression_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_numeric_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_integral_t<TF>::value, "type requirement");
		static_assert(sqlpp::is_floating_point_t<TF>::value, "type requirement");
	}

	// MISC FUNCTIONS
  // --------------

	// test value
	{
		using TB = decltype(sqlpp::value(true));
		using TI = decltype(sqlpp::value(7));
		using TF = decltype(sqlpp::value(1.5));
		using TT = decltype(sqlpp::value("cheesecake"));
		static_assert(not sqlpp::is_named_expression_t<TB>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TB>::value, "type requirement");
		static_assert(not sqlpp::is_named_expression_t<TB>::value, "type requirement");
		static_assert(sqlpp::is_integral_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_named_expression_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_floating_point_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_named_expression_t<TT>::value, "type requirement");
		static_assert(sqlpp::is_text_t<TT>::value, "type requirement");
	}

	// test flatten
	{
		using TB = decltype(flatten(t.gamma, db));
		using TI = decltype(flatten(t.alpha, db));
		using TF = decltype(flatten(f.omega, db));
		using TT = decltype(flatten(t.beta, db));
		static_assert(not sqlpp::is_named_expression_t<TB>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TB>::value, "type requirement");
		static_assert(not sqlpp::is_named_expression_t<TB>::value, "type requirement");
		static_assert(sqlpp::is_integral_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_named_expression_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_floating_point_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_named_expression_t<TT>::value, "type requirement");
		static_assert(sqlpp::is_text_t<TT>::value, "type requirement");
	}

	// test verbatim
	{
		using TB = decltype(sqlpp::verbatim<sqlpp::boolean>("1"));
		using TI = decltype(sqlpp::verbatim<sqlpp::bigint>("42"));
		using TF = decltype(sqlpp::verbatim<sqlpp::floating_point>("1.5"));
		using TT = decltype(sqlpp::verbatim<sqlpp::text>("cheesecake"));
		static_assert(not sqlpp::is_named_expression_t<TB>::value, "type requirement");
		static_assert(sqlpp::is_boolean_t<TB>::value, "type requirement");
		static_assert(not sqlpp::is_named_expression_t<TB>::value, "type requirement");
		static_assert(sqlpp::is_integral_t<TI>::value, "type requirement");
		static_assert(not sqlpp::is_named_expression_t<TI>::value, "type requirement");
		static_assert(sqlpp::is_floating_point_t<TF>::value, "type requirement");
		static_assert(not sqlpp::is_named_expression_t<TT>::value, "type requirement");
		static_assert(sqlpp::is_text_t<TT>::value, "type requirement");
	}

	// test verbatim_table
	{
		using T = decltype(sqlpp::verbatim_table("cheesecake"));
		static_assert(not sqlpp::is_named_expression_t<T>::value, "type requirement");
		static_assert(not sqlpp::is_expression_t<T>::value, "type requirement");
		static_assert(sqlpp::is_table_t<T>::value, "type requirement");
	}

	// test verbatim_table alias
	{
		SQLPP_ALIAS_PROVIDER_GENERATOR(kaesekuchen);
		using T = decltype(sqlpp::verbatim_table("cheesecake").as(kaesekuchen));
		static_assert(not sqlpp::is_named_expression_t<T>::value, "type requirement");
		static_assert(not sqlpp::is_expression_t<T>::value, "type requirement");
		static_assert(sqlpp::is_table_t<T>::value, "type requirement");
		static_assert(sqlpp::is_alias_t<T>::value, "type requirement");
	}

	return 0;
}
示例#3
0
String FormData::flattenToString() const
{
    Vector<char> bytes;
    flatten(bytes);
    return Latin1Encoding().decode(bytes.data(), bytes.size());
}
 void flatten(TreeNode* root) 
 {
     TreeNode *end = nullptr;
     flatten(root, end);
 }
示例#5
0
void hgTrackDb(char *org, char *database, char *trackDbName, char *sqlFile, char *hgRoot,
               boolean strict)
/* hgTrackDb - Create trackDb table from text files. */
{
struct trackDb *td;
char tab[PATH_LEN];
safef(tab, sizeof(tab), "%s.tab", trackDbName);

struct trackDb *tdbList = buildTrackDb(org, database, hgRoot, strict);
tdbList = flatten(tdbList);
slSort(&tdbList, trackDbCmp);
verbose(1, "Loaded %d track descriptions total\n", slCount(tdbList));

/* Write to tab-separated file; hold off on html, since it must be encoded */
    {
    verbose(2, "Starting write of tabs to %s\n", tab);
    FILE *f = mustOpen(tab, "w");
    for (td = tdbList; td != NULL; td = td->next)
        {
        hVarSubstTrackDb(td, database);
        char *hold = td->html;
        td->html = "";
	subChar(td->type, '\t', ' ');	/* Tabs confuse things. */
	subChar(td->shortLabel, '\t', ' ');	/* Tabs confuse things. */
	subChar(td->longLabel, '\t', ' ');	/* Tabs confuse things. */
	trackDbTabOut(td, f);
        td->html = hold;
        }
    carefulClose(&f);
    verbose(2, "Wrote tab representation to %s\n", tab);
    }

/* Update database */
    {
    char *create, *end;
    char query[256];
    struct sqlConnection *conn = sqlConnect(database);

    /* Load in table definition. */
    readInGulp(sqlFile, &create, NULL);
    create = trimSpaces(create);
    create = substituteTrackName(create, trackDbName);
    end = create + strlen(create)-1;
    if (*end == ';') *end = 0;
    sqlRemakeTable(conn, trackDbName, create);

    /* Load in regular fields. */
    sqlSafef(query, sizeof(query), "load data local infile '%s' into table %s", tab, trackDbName);
    verbose(2, "sending mysql \"%s\"\n", query);
    sqlUpdate(conn, query);
    verbose(2, "done tab file load");

    /* Load in html and settings fields. */
    for (td = tdbList; td != NULL; td = td->next)
	{
        if (isEmpty(td->html))
	    {
	    if (strict && !trackDbLocalSetting(td, "parent") && !trackDbLocalSetting(td, "superTrack") &&
	        !sameString(td->track,"cytoBandIdeo"))
		{
		fprintf(stderr, "Warning: html missing for %s %s %s '%s'\n",org, database, td->track, td->shortLabel);
		}
	    }
	else
	    {
	    updateBigTextField(conn,  trackDbName, "tableName", td->track, "html", td->html);
	    }
	if (td->settingsHash != NULL)
	    {
	    char *settings = settingsFromHash(td->settingsHash);
	    updateBigTextField(conn, trackDbName, "tableName", td->track,
	        "settings", settings);
	    if (showSettings)
		{
		verbose(1, "%s: type='%s';", td->track, td->type);
		if (isNotEmpty(settings))
		    {
		    char *oneLine = replaceChars(settings, "\n", "; ");
		    eraseTrailingSpaces(oneLine);
		    verbose(1, " %s", oneLine);
		    freeMem(oneLine);
		    }
		verbose(1, "\n");
		}
	    freeMem(settings);
	    }
	}

    sqlDisconnect(&conn);
    verbose(1, "Loaded database %s\n", database);
    }
}
 void flatten(TreeNode *root) {
     flatten(root, NULL);
 }
示例#7
0
 static constexpr auto apply(F fset, Set set) {
     return flatten(transform(fset, partial(transform, set)));
 }
示例#8
0
文件: cssize.cpp 项目: xzyfer/libsass
  Block_Ptr Cssize::debubble(Block_Ptr children, Statement_Ptr parent)
  {
    Has_Block_Obj previous_parent = 0;
    std::vector<std::pair<bool, Block_Obj>> baz = slice_by_bubble(children);
    Block_Obj result = SASS_MEMORY_NEW(Block, children->pstate());

    for (size_t i = 0, L = baz.size(); i < L; ++i) {
      bool is_bubble = baz[i].first;
      Block_Obj slice = baz[i].second;

      if (!is_bubble) {
        if (!parent) {
          result->append(slice);
        }
        else if (previous_parent) {
          previous_parent->block()->concat(slice);
        }
        else {
          previous_parent = Cast<Has_Block>(SASS_MEMORY_COPY(parent));
          previous_parent->block(slice);
          previous_parent->tabs(parent->tabs());

          result->append(previous_parent);
        }
        continue;
      }

      for (size_t j = 0, K = slice->length(); j < K; ++j)
      {
        Statement_Ptr ss;
        Statement_Obj stm = slice->at(j);
        // this has to go now here (too bad)
        Bubble_Obj node = Cast<Bubble>(stm);
        Media_Block_Ptr m1 = NULL;
        Media_Block_Ptr m2 = NULL;
        if (parent) m1 = Cast<Media_Block>(parent);
        if (node) m2 = Cast<Media_Block>(node->node());
        if (!parent ||
            parent->statement_type() != Statement::MEDIA ||
            node->node()->statement_type() != Statement::MEDIA ||
            (m1 && m2 && *m1->media_queries() == *m2->media_queries())
          )
        {
          ss = node->node();
        }
        else
        {
          List_Obj mq = merge_media_queries(
            Cast<Media_Block>(node->node()),
            Cast<Media_Block>(parent)
          );
          if (!mq->length()) continue;
          if (Media_Block* b = Cast<Media_Block>(node->node())) {
            b->media_queries(mq);
          }
          ss = node->node();
        }

        if (!ss) continue;

        ss->tabs(ss->tabs() + node->tabs());
        ss->group_end(node->group_end());

        Block_Obj bb = SASS_MEMORY_NEW(Block,
                                    children->pstate(),
                                    children->length(),
                                    children->is_root());
        bb->append(ss->perform(this));

        Block_Obj wrapper_block = SASS_MEMORY_NEW(Block,
                                              children->pstate(),
                                              children->length(),
                                              children->is_root());

        Block_Ptr wrapper = flatten(bb);
        wrapper_block->append(wrapper);

        if (wrapper->length()) {
          previous_parent = NULL;
        }

        if (wrapper_block) {
          result->append(wrapper_block);
        }
      }
    }

    return flatten(result);
  }
示例#9
0
文件: Editline.c 项目: wrapl/wrapl
typedef struct editline_t {
	const Std$Type_t *Type;
	EditLine *Handle;
	History *HistoryHandle;
	HistEvent HistoryEvent[1];
	int Continuation;
	Std$Object_t *PromptFn;
} editline_t;

TYPE(T);

GLOBAL_FUNCTION(New, 1) {
	editline_t *Edit = new(editline_t);
	Edit->Type = T;
	Edit->Handle = el_init(Std$String$flatten(Args[0].Val), stdin, stdout, stderr);
	Edit->HistoryHandle = history_init();
	history(Edit->HistoryHandle, Edit->HistoryEvent, H_SETSIZE, 800);
	el_set(Edit->Handle, EL_CLIENTDATA, Edit);
	el_set(Edit->Handle, EL_EDITOR, "emacs");
	el_set(Edit->Handle, EL_HIST, history, Edit->HistoryHandle);
	/*el_set(Edit->Handle, EL_BIND, "-a", "a", "ed-prev-line", NULL);
	el_set(Edit->Handle, EL_BIND, "-a", "z", "ed-next-line", NULL);
	el_set(Edit->Handle, EL_BIND, NULL);*/
	Edit->Continuation = 0;
	Result->Val = Edit;
	return SUCCESS;
};

static char *call_prompt(EditLine *Handle) {
	editline_t *Edit;
示例#10
0
value flatten(value const& v) {
  return {flatten(v.data()), flatten(v.type())};
}
示例#11
0
文件: green.c 项目: Darnor/PartDiff
int	main(int argc, char *argv[]) {
    int	c;
    int	n = 100;
    int	slow = 1;
    while (EOF != (c = getopt(argc, argv, "dn:s:")))
        switch (c) {
        case 'd':
            debug = 0;
            break;
        case 'n':
            n = atoi(optarg);
            break;
        case 's':
            slow = atoi(optarg);
            break;
        }

    preamble(stdout);

#if 0
    /* from left to right */
    for (int k = 1; k < n; k++) {
        func_t	*r = rhs(n);
        flatten(r, k);
        func_t	*s = solution(r, 0);
        for (int repeat = 0; repeat < slow; repeat++) {
            showfunctiongraph(stdout, r, s);
        }
        func_free(r);
        func_free(s);
    }
#endif

#if 0
    /* hierarchically */
    int	k = 2;
    while (k < 1024) {
        func_t	*r = rhs(k - 1);
        func_t	*s = solution(r, 0);
        for (int repeat = 0; repeat < slow; repeat++) {
            showfunctiongraph(stdout, r, s);
        }
        func_free(r);
        func_free(s);
        k <<= 1;
    }
#endif

    /* random addition of points */
    int	exponent = log2(n);
    int	repeats = 1;
    n = 1 << (++exponent);	// next larger power of 2
    func_t	*r0 = rhs(n);
    int	*use = (int *)calloc(n, sizeof(int));
    for (int k = 1; k <= n; k++) {
        /* adapt the repeats */
        repeats = 32 * pow(2, -k/16.);
        if (repeats < slow) {
            repeats = slow;
        }

        /* add a new point to the graph */
        int	index;
        while (1) {
            index = random() % n;
            if (0 == use[index]) {
                use[index] = 1;
                r0->highlight = index;
                break;
            }
        }

        /* mask some of the points in a copy of r0 */
        func_t	*r = func_copy(r0);
        double	scale = (1. + r->n) / (1. + k);
        for (int i = 0; i < r->n; i++) {
            r->f[i] *= scale;
            r->f[i] *= use[i];
        }

        /* create the associated solution */
        func_t	*s = solution(r, k);
        scale = 1/scale;
        for (int i = 0; i < r->n; i++) {
            r->f[i] *= scale;
        }

        /* display as many copies as necessary */
        for (int repeat = 0;
                (repeat < (slow * repeats)) && (repeat < 25);
                repeat++) {
            printf("%% n = %d, figure = %4d, iteration = %4d, "
                   "repeats = %2d, index = %4d\n",
                   n, figcounter, k, repeats, index);
            showfunctiongraph(stdout, r, s);
        }
        func_free(r);
        func_free(s);
    }
    func_free(r0);

    postamble(stdout);

    exit(EXIT_SUCCESS);
}
示例#12
0
	return R;
};

Std$Rational_t *_new(mpq_t *V) {
	Std$Rational_t *R = new(Std$Rational_t);
	R->Type = T;
	mpq_init(R->Value);
	mpq_set(R->Value, V);
	return R;
};

METHOD("Rational.New", TYP, Std$String$T) {
	Std$Rational_t *R = new(Std$Rational_t);
	R->Type = T;
	mpq_init(R->Value);
	mpq_set_str(R->Value, Std$String$flatten(Args[0].Val), 10);
	mpq_canonicalize(R->Value);
	Result->Val = R;
	return SUCCESS;
};

METHOD("Rational.New", TYP, Std$Integer$SmallT, TYP, Std$Integer$SmallT) {
	Std$Rational_t *R = new(Std$Rational_t);
	R->Type = T;
	mpq_init(R->Value);
	mpq_set_si(R->Value, ((Std$Integer_smallt *)Args[0].Val)->Value, ((Std$Integer_smallt *)Args[1].Val)->Value);
	mpq_canonicalize(R->Value);
	Result->Val = R;
	return SUCCESS;
};
示例#13
0
	GridColouring(int _n, int _m, int _c) : n(_n), m(_m), c(_c) {

		// Create vars

		createVars(x, n, m, 1, c, true);

		// Constraints

		// For each rectangle, corners cannot all be the same colour
		for (int r1 = 0; r1 < n; r1++) {
			for (int r2 = r1+1; r2 < n; r2++) {
				for (int c1 = 0; c1 < m; c1++) {
					for (int c2 = c1+1; c2 < m; c2++) {
						for (int z = 1; z <= c; z++) {
							vec<BoolView> a;
							a.push(BoolView(x[r1][c1]->getLit(z,0)));
							a.push(BoolView(x[r2][c1]->getLit(z,0)));
							a.push(BoolView(x[r1][c2]->getLit(z,0)));
							a.push(BoolView(x[r2][c2]->getLit(z,0)));
							bool_clause(a);
						}
					}
				}
			}
		}

		// Balance constraints
		if (BALANCE) {
			IntVar *llimit = getConstant(m/c);
			IntVar *ulimit = getConstant(m/c+1);
			for (int i = 0; i < n; i++) {
				for (int z = 1; z <= c; z++) {
					vec<BoolView> a;
					for (int j = 0; j < m; j++) {
						a.push(BoolView(x[i][j]->getLit(z,1)));
					}
					bool_linear(a, IRT_LE, ulimit);
					bool_linear(a, IRT_GE, llimit);
				}
			}
		}

		// Mathamatical global constraint
		if (USE_GLOBAL) addGlobalProp();

		// Test
		if (TEST) {
			assert(n == 16);
			assert(m == 16);
			assert(c == 4);
			for (int i = 0; i < 4; i++) {
				for (int j = 0; j < 16; j++) {
					x[i][j]->setVal((i+j/4)%4+1);
				}
			}
		}

		// Post some branchings

		vec<IntVar*> s;
		flatten(x, s);

		branch(s, VAR_INORDER, VAL_MIN);


	}
示例#14
0
 static constexpr auto apply(F fset, Set set) {
     return flatten(transform(fset, [=](auto f) {
         return transform(set, f);
     }));
 }
示例#15
0
文件: glom.c 项目: muennich/rc3
extern List *glom(Node *n) {
	List *v, *head, *tail;
	Node *words;
	if (n == NULL)
		return NULL;
	switch (n->type) {
	case nArgs:
	case nLappend:
		words = n->u[0].p;
		tail = NULL;
		while (words != NULL && (words->type == nArgs || words->type == nLappend)) {
			if (words->u[1].p != NULL && words->u[1].p->type != nWord)
				break;
			head = glom(words->u[1].p);
			if (head != NULL) {
				head->n = tail;
				tail = head;
			}
			words = words->u[0].p;
		}
		v = append(glom(words), tail); /* force left to right evaluation */
		return append(v, glom(n->u[1].p));
	case nBackq:
		return backq(n->u[0].p, n->u[1].p);
	case nConcat:
		head = glom(n->u[0].p); /* force left-to-right evaluation */
		return concat(head, glom(n->u[1].p));
	case nDup:
	case nRedir:
		qredir(n);
		return NULL;
	case nWord:
		return word(n->u[0].s, n->u[1].s);
	case nNmpipe:
		return mkcmdarg(n);
	default:
		/*
		   The next four operations depend on the left-child of glom
		   to be a variable name. Therefore the variable is looked up
		   here.
		*/
		if ((v = glom(n->u[0].p)) == NULL)
			rc_error("null variable name");
		if (v->n != NULL)
			rc_error("multi-word variable name");
		if (*v->w == '\0')
			rc_error("zero-length variable name");
		v = (*v->w == '*' && v->w[1] == '\0') ? varlookup(v->w)->n : varlookup(v->w);
		switch (n->type) {
		default:
			panic("unexpected node in glom");
			exit(1);
			/* NOTREACHED */
		case nCount:
			return count(v);
		case nFlat:
			return flatten(v);
		case nVar:
			return v;
		case nVarsub:
			return varsub(v, glom(n->u[1].p));
		}
	}
}
示例#16
0
		PolymorphicSharedPtr<NoncontiguousByteBlock> flatten(const T& in)
			{
			return flatten(SerializedObject::serialize(in, PolymorphicSharedPtr<VectorDataMemoryManager>()));
			}
示例#17
0
文件: flatten.cpp 项目: bvds/andes
bool flatten(expr * & e)	// flattens expr e wrt n_ops
{
  int k, q;
  expr * tempexp;
  EQCHK(e);

#if WITHDBG
  unsigned long thisdbg = ++dbgnum;	// recursive calls for debug
#endif
  DBG(cout << "flatten " << thisdbg << " called for " 
      << e->getInfix() << endl);

  if ((e->etype == unknown)  ||
      (e->etype == fake))
    throw(string("flatten called on unknown or fake expr"));
  if ( (e->etype == numval) || (e->etype == physvart))  return(false);
  bool answer = false;
  if (e->etype == function)			// top level is function
    {
      functexp * efunct = (functexp *) e;
      answer = flatten(efunct->arg);
      if (efunct->f->opty == sqrte) 
	{						// sqrt of product
	  if ( (efunct->arg->etype == n_op) &&
	       (((n_opexp *)efunct->arg)->op->opty == multe))
	    {
	      n_opexp * fargnop = (n_opexp *) efunct->arg;
	      if (fargnop->args->size() < 2) 
		{
		  // this can't happen if we guarantee all n_ops flatten
		  // returns always have at least two args:
		  unnop(efunct->arg);
		  DBGM(cout << "flatten " << thisdbg  << ":  returns " 
		      << e->getInfix()<< endl);
		  return(true); 
		}
	      DBG(cout << "flatten " << thisdbg << 
		   " called sqrt of product " << endl;
		   // e->dbgprint(0)
		   );
	      n_opexp * rootdone = new n_opexp(&mult); // holds part of prod
	      for (k = 0; k < fargnop->args->size(); k++) // extracted frm sqrt
		if (isnonneg((*fargnop->args)[k]))
		  {
		    tempexp = (expr *) new functexp(&sqrtff,
						    (*fargnop->args)[k]);
		    fargnop->MKS += ((*fargnop->args)[k])->MKS * -1.;//9/29/01
		    e->MKS += ((*fargnop->args)[k])->MKS * -0.5;//9/29/01
		    flatten(tempexp);
		    rootdone->addarg(tempexp);
		    for (q = k; q+1 < fargnop->args->size(); q++)
		      (*fargnop->args)[q] = (*fargnop->args)[q+1];
		    fargnop->args->pop_back();
		    k--;
		  }
	      if (fargnop->args->size() == 1) 
		{
		  unnop(efunct->arg);
		  eqnumsimp(e,true);
		  answer = true;
		}
	      else if (fargnop->args->size() == 0) 
		{
		  e->destroy(); e = rootdone; 
		  DBG(cout << "flatten " << thisdbg  << ":  returns " 
		      << e->getInfix()<< endl);
		  return(true); 
		}
	      if (rootdone->args->size() == 0)
		{
		  delete rootdone;
		  DBG({cout << "flatten " << thisdbg 
			 << " return false from sqrt of product" << endl; });
示例#18
0
/* initializes hdf5 struct and writes some of the initially known
   problem properties such as state variable names into hdf5 file*/
hdf5block_t* /*freshly allocated struct with ids and size parameters*/
h5block_init(char *output_file, /*will create this file for writing*/
	     ode_model_parameters *omp, /*contains MCMC problem description*/
	     size_t Samples, /* MCMC sample size*/
	     const char **x_name, /*ODE model State Variable names, array of strings*/
	     const char **p_name, /*ODE model parameter names, array of strings*/
	     const char **f_name)/*ODE model output function names, array of strings*/
{
  hsize_t *size=malloc(sizeof(hsize_t)*2);
  hsize_t *chunk_size=malloc(sizeof(hsize_t)*2);
  hid_t file_id = H5Fcreate(output_file, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
  assert(file_id>0);
  int D=get_number_of_MCMC_variables(omp);
  int N=get_number_of_state_variables(omp);
  int P=get_number_of_model_parameters(omp);
  int F=get_number_of_model_outputs(omp);
  
  char *x_names=flatten(x_name, (size_t) N, "; ");
  char *p_names=flatten(p_name, (size_t) P, "; ");
  char *f_names=flatten(f_name, (size_t) F, "; ");

  herr_t NameWriteError=0;
  NameWriteError&=H5LTmake_dataset_string(file_id,"StateVariableNames",x_names);
  NameWriteError&=H5LTmake_dataset_string(file_id,"ParameterNames",p_names);
  NameWriteError&=H5LTmake_dataset_string(file_id,"OutputFunctionNames",f_names);
  if (NameWriteError){
    fprintf(stderr,"[h5block_init] writing (x,p,f)-names into hdf5 file failed.");
  }/* else {
    printf("# [main] all names have been written to file «%s».\n",output_file);
    }*/
  free(x_names);
  free(p_names);
  free(f_names);
  
  hid_t para_property_id = H5Pcreate(H5P_DATASET_CREATE);
  hid_t post_property_id = H5Pcreate(H5P_DATASET_CREATE);
  
  /* here we set a «chunk size», which will coincide with the hyperslabs we select to write output*/
  // parameter sample chunk size:
  chunk_size[0]=CHUNK;
  chunk_size[1]=D;
  H5Pset_chunk(para_property_id, 2, chunk_size);
  hid_t para_chunk_id=H5Screate_simple(2, chunk_size, NULL); // a dataspace to write chunks/hyperslabs
  
  // posterior probability distribution chunk size:
  chunk_size[0]=CHUNK;
  chunk_size[1]=1;
  H5Pset_chunk(post_property_id, 2, chunk_size);
  hid_t post_chunk_id=H5Screate_simple(2, chunk_size, NULL);
  // hyperslab selection
  hsize_t *offset, *stride, *count, *block;
  offset=malloc(sizeof(hsize_t)*2);
  stride=malloc(sizeof(hsize_t)*2);
  count=malloc(sizeof(hsize_t)*2);
  block=malloc(sizeof(hsize_t)*2);  
  // hsize_t offset[2]={0,0}, stride[2]={1,1}, count[2]={1,1}, block[2];
  int i;
  for (i=0;i<2;i++) offset[i]=0;
  for (i=0;i<2;i++) stride[i]=1;
  for (i=0;i<2;i++)  count[i]=1;  
  block[0]=CHUNK;
  block[1]=D;

  // hdf5 file setup
  size[0]=Samples;
  size[1]=D;
  hid_t para_dataspace_id=H5Screate_simple(2, size, NULL);
  size[0]=Samples;
  size[1]=1;
  hid_t post_dataspace_id=H5Screate_simple(2, size, NULL);
    assert(post_dataspace_id>0 && para_dataspace_id>0);
  
  hid_t parameter_set_id = H5Dcreate2(file_id, "LogParameters", H5T_NATIVE_DOUBLE, para_dataspace_id, H5P_DEFAULT, para_property_id, H5P_DEFAULT);
  hid_t posterior_set_id = H5Dcreate2(file_id, "LogPosterior", H5T_NATIVE_DOUBLE, post_dataspace_id, H5P_DEFAULT, post_property_id, H5P_DEFAULT);
  assert(parameter_set_id>0 && posterior_set_id>0);
  //copy ids to struct
  hdf5block_t *h5block;
  h5block = malloc(sizeof(hdf5block_t));
  h5block->file_id = file_id;
  h5block->para_property_id = para_property_id;
  h5block->post_property_id = post_property_id;
  h5block->para_chunk_id = para_chunk_id;
  h5block->post_chunk_id = post_chunk_id;
  h5block->para_dataspace_id = para_dataspace_id;
  h5block->post_dataspace_id = post_dataspace_id;
  h5block->parameter_set_id = parameter_set_id;
  h5block->posterior_set_id = posterior_set_id;
  h5block->size = size;
  h5block->chunk_size = chunk_size;
  h5block->offset = offset;
  h5block->stride = stride;
  h5block->count = count;
  h5block->block = block;
  return h5block;
}
示例#19
0
 static constexpr auto apply(Xs xs, Ys ys) {
     return flatten(doubleton(xs, ys));
 }
示例#20
0
static int
not_new(Graph *g)
{	Graph	*q1; Node *tmp, *n1, *n2;
	Mapping	*map;

	tmp = flatten(g->Old);	/* duplicate, collapse, normalize */
	g->Other = g->Old;	/* non normalized full version */
	g->Old = tmp;

	g->oldstring = DoDump(g->Old);

	tmp = flatten(g->Next);
	g->nxtstring = DoDump(tmp);

	if (tl_verbose) dump_graph(g);

	Debug2("\tformula-old: [%s]\n", g->oldstring?g->oldstring->name:"true");
	Debug2("\tformula-nxt: [%s]\n", g->nxtstring?g->nxtstring->name:"true");
	for (q1 = Nodes_Set; q1; q1 = q1->nxt)
	{	Debug2("	compare old to: %s", q1->name->name);
		Debug2(" [%s]", q1->oldstring?q1->oldstring->name:"true");

		Debug2("	compare nxt to: %s", q1->name->name);
		Debug2(" [%s]", q1->nxtstring?q1->nxtstring->name:"true");

		if (q1->oldstring != g->oldstring
		||  q1->nxtstring != g->nxtstring)
		{	Debug(" => different\n");
			continue;
		}
		Debug(" => match\n");

		if (g->incoming)
			q1->incoming = catSlist(g->incoming, q1->incoming);

		/* check if there's anything in g->Other that needs
		   adding to q1->Other
		*/
		for (n2 = g->Other; n2; n2 = n2->nxt)
		{	for (n1 = q1->Other; n1; n1 = n1->nxt)
				if (isequal(n1, n2))
					break;
			if (!n1)
			{	Node *n3 = dupnode(n2);
				/* don't mess up n2->nxt */
				n3->nxt = q1->Other;
				q1->Other = n3;
		}	}

		map = (Mapping *) tl_emalloc(sizeof(Mapping));
	  	map->from = g->name->name;
	  	map->to   = q1;
	  	map->nxt = Mapped;
	  	Mapped = map;

		for (n1 = g->Other; n1; n1 = n2)
		{	n2 = n1->nxt;
			releasenode(1, n1);
		}
		for (n1 = g->Old; n1; n1 = n2)
		{	n2 = n1->nxt;
			releasenode(1, n1);
		}
		for (n1 = g->Next; n1; n1 = n2)
		{	n2 = n1->nxt;
			releasenode(1, n1);
		}
		return 1;
	}

	if (newstates) tl_verbose=1;
	Debug2("	New Node %s [", g->name->name);
	for (n1 = g->Old; n1; n1 = n1->nxt)
	{ Dump(n1); Debug(", "); }
	Debug2("] nr %d\n", Base);
	if (newstates) tl_verbose=0;

	Base++;
	g->nxt = Nodes_Set;
	Nodes_Set = g;

	return 0;
}
示例#21
0
int Interpret(int, char* [])
{
  MockDb db = {};
  MockDb::_serializer_context_t printer = {};

  const auto f = test::TabFoo{};
  const auto t = test::TabBar{};
  select(t.alpha.as(t.beta));

  serialize(insert_into(t).columns(t.beta, t.gamma), printer).str();
  {
    auto i = insert_into(t).columns(t.gamma, t.beta);
    i.values.add(t.gamma = true, t.beta = "cheesecake");
    serialize(i, printer).str();
    i.values.add(t.gamma = false, t.beta = sqlpp::tvin("coffee"));
    i.values.add(t.gamma = false, t.beta = sqlpp::tvin(std::string()));
    serialize(i, printer).str();
    i.values.add(t.gamma = sqlpp::default_value, t.beta = sqlpp::null);
    serialize(i, printer).str();
  }

  serialize(t.alpha = sqlpp::null, printer).str();
  serialize(t.alpha = sqlpp::default_value, printer).str();
  serialize(t.alpha, printer).str();
  serialize(-t.alpha, printer).str();
  serialize(+t.alpha, printer).str();
  serialize(-(t.alpha + 7), printer).str();
  serialize(t.alpha = 0, printer).str();
  serialize(t.alpha = sqlpp::tvin(0), printer).str();
  serialize(t.alpha == 0, printer).str();
  serialize(t.alpha == sqlpp::tvin(0), printer).str();
  serialize(t.alpha != 0, printer).str();
  serialize(t.gamma != sqlpp::tvin(false), printer).str();
  serialize(t.alpha == 7, printer).str();
  serialize(t.delta = sqlpp::tvin(0), printer).str();
  serialize(t.beta + "kaesekuchen", printer).str();

  serialize(sqlpp::select(), printer).str();
  serialize(sqlpp::select().flags(sqlpp::distinct), printer).str();
  serialize(select(t.alpha, t.beta).flags(sqlpp::distinct), printer).str();
  serialize(select(t.alpha, t.beta), printer).str();
  serialize(select(t.alpha, t.beta).from(t), printer).str();
  serialize(select(t.alpha, t.beta).from(t).where(t.alpha == 3), printer).str();
  serialize(select(t.alpha, t.beta).from(t).where(t.alpha == 3).group_by(t.gamma), printer).str();
  serialize(select(t.alpha, t.beta).from(t).where(t.alpha == 3).group_by(t.gamma).having(t.beta.like("%kuchen")),
            printer).str();
  serialize(select(t.alpha, t.beta)
                .from(t)
                .where(t.alpha == 3)
                .group_by(t.gamma)
                .having(t.beta.like("%kuchen"))
                .order_by(t.beta.asc()),
            printer).str();
  serialize(select(t.alpha, t.beta)
                .from(t)
                .where(t.alpha == 3)
                .group_by(t.gamma)
                .having(t.beta.like("%kuchen"))
                .order_by(t.beta.asc())
                .limit(17)
                .offset(3),
            printer).str();

  serialize(parameter(sqlpp::bigint(), t.alpha), printer).str();
  serialize(parameter(t.alpha), printer).str();
  serialize(t.alpha == parameter(t.alpha), printer).str();
  serialize(t.alpha == parameter(t.alpha) and (t.beta + "gimmick").like(parameter(t.beta)), printer).str();

  serialize(insert_into(t), printer).str();
  serialize(insert_into(f).default_values(), printer).str();
  serialize(insert_into(t).set(t.gamma = true), printer).str();
  // serialize(insert_into(t).set(t.gamma = sqlpp::tvin(false)), printer).str(); cannot test this since gamma cannot be
  // null and a static assert is thrown

  serialize(update(t), printer).str();
  serialize(update(t).set(t.gamma = true), printer).str();
  serialize(update(t).set(t.gamma = true).where(t.beta.in("kaesekuchen", "cheesecake")), printer).str();
  serialize(update(t).set(t.gamma = true).where(t.beta.in()), printer).str();

  serialize(remove_from(t), printer).str();
  serialize(remove_from(t).using_(t), printer).str();
  serialize(remove_from(t).where(t.alpha == sqlpp::tvin(0)), printer).str();
  serialize(remove_from(t).using_(t).where(t.alpha == sqlpp::tvin(0)), printer).str();

  // functions
  serialize(sqlpp::value(7), printer).str();
  serialize(sqlpp::verbatim<sqlpp::integral>("irgendwas integrales"), printer).str();
  serialize(sqlpp::value_list(std::vector<int>({1, 2, 3, 4, 5, 6, 8})), printer).str();
  serialize(exists(select(t.alpha).from(t)), printer).str();
  serialize(any(select(t.alpha).from(t)), printer).str();
  serialize(some(select(t.alpha).from(t)), printer).str();
  serialize(count(t.alpha), printer).str();
  serialize(min(t.alpha), printer).str();
  serialize(max(t.alpha), printer).str();
  serialize(avg(t.alpha), printer).str();
  serialize(sum(t.alpha), printer).str();
  serialize(sqlpp::verbatim_table("whatever"), printer).str();

  // alias
  serialize(t.as(t.alpha), printer).str();
  serialize(t.as(t.alpha).beta, printer).str();

  // select alias
  serialize(select(t.alpha).from(t).where(t.beta > "kaesekuchen").as(t.gamma), printer).str();

  serialize(t.alpha.is_null(), printer).str();

  // join
  serialize(t.inner_join(t.as(t.alpha)).on(t.beta == t.as(t.alpha).beta), printer).str();
  {
    auto inner = t.inner_join(t.as(t.alpha)).on(t.beta == t.as(t.alpha).beta);
    serialize(select(t.alpha).from(inner), printer).str();
  }

  // multi_column
  serialize(multi_column(t.alpha, (t.beta + "cake").as(t.gamma)).as(t.alpha), printer).str();
  serialize(multi_column(all_of(t)).as(t), printer).str();
  serialize(all_of(t).as(t), printer).str();

  // dynamic select
  {
    auto s = dynamic_select(db).dynamic_flags().dynamic_columns().from(t);
    s.selected_columns.add(t.beta);
    s.selected_columns.add(t.gamma);
    serialize(s, printer).str();
  }
  {
    auto s = dynamic_select(db).dynamic_flags().dynamic_columns().from(t);
    s.select_flags.add(sqlpp::distinct);
    s.selected_columns.add(t.beta);
    s.selected_columns.add(t.gamma);
    serialize(s, printer).str();
  }
  {
    // Behold, dynamically constructed queries might compile but be illegal SQL
    auto s = dynamic_select(db).dynamic_flags(sqlpp::distinct).dynamic_columns(t.alpha);
    s.select_flags.add(sqlpp::all);
    s.selected_columns.add(without_table_check(t.beta));
    s.selected_columns.add(without_table_check(t.gamma));
    serialize(s, printer).str();
  }

  // distinct aggregate
  serialize(count(sqlpp::distinct, t.alpha % 7), printer).str();
  serialize(avg(sqlpp::distinct, t.alpha - 7), printer).str();
  serialize(sum(sqlpp::distinct, t.alpha + 7), printer).str();

  serialize(select(all_of(t)).from(t).unconditionally(), printer).str();

  for (const auto& row : db(select(all_of(t)).from(t).unconditionally()))
  {
    serialize(row.alpha, printer);
    serialize(row.beta, printer);
    serialize(row.gamma, printer);
  }

  get_sql_name(t);
  get_sql_name(t.alpha);

  flatten(t.alpha == 7, db);

  auto x = boolean_expression(db, t.alpha == 7);
  x = sqlpp::boolean_expression<MockDb>(t.beta.like("%cheesecake"));
  x = x and boolean_expression(db, t.gamma);
  std::cerr << "----------------------------" << std::endl;
  printer.reset();
  std::cerr << serialize(x, printer).str() << std::endl;

  printer.reset();
  std::cerr << serialize(select(all_of(t)).from(t).where(t.alpha.in(select(f.epsilon).from(f).unconditionally())),
                         printer).str() << std::endl;

  printer.reset();
  std::cerr << serialize(select(all_of(t)).from(t).where(t.alpha.in()), printer).str() << std::endl;

  printer.reset();
  std::cerr << serialize(select(all_of(t)).from(t).where(t.alpha.not_in()), printer).str() << std::endl;

  auto schema = db.attach("lorem");
  auto s = schema_qualified_table(schema, t).as(sqlpp::alias::x);

  printer.reset();
  std::cerr << serialize(select(all_of(s)).from(s).unconditionally(), printer).str() << std::endl;

  printer.reset();
  std::cerr << serialize(sqlpp::case_when(true).then(t.alpha).else_(t.alpha + 1).as(t.beta), printer).str()
            << std::endl;

  return 0;
}
示例#22
0
static void
expand_g(Graph *g)
{	Node *now, *n1, *n2, *nx;
	int can_release;

	if (!g->New)
	{	Debug2("\nDone with %s", g->name->name);
		if (tl_verbose) dump_graph(g);
		if (not_new(g))
		{	if (tl_verbose) printf("\tIs Not New\n");
			return;
		}
		if (g->Next)
		{	Debug("	Has Next [");
			for (n1 = g->Next; n1; n1 = n1->nxt)
			{ Dump(n1); Debug(", "); }
			Debug("]\n");

			ng(ZS, getsym(g->name), g->Next, ZN, ZN);
		}
		return;
	}

	if (tl_verbose)
	{	Symbol *z;
		printf("\nExpand %s, from ", g->name->name);
		for (z = g->incoming; z; z = z->next)
			printf("%s, ", z->name);
		printf("\n\thandle:\t"); Explain(g->New->ntyp);
		dump_graph(g);
	}

	if (g->New->ntyp == AND)
	{	if (g->New->nxt)
		{	n2 = g->New->rgt;
			while (n2->nxt)
				n2 = n2->nxt;
			n2->nxt = g->New->nxt;
		}
		n1 = n2 = g->New->lft;
		while (n2->nxt)
			n2 = n2->nxt;
		n2->nxt = g->New->rgt;

		releasenode(0, g->New);

		g->New = n1;
		push_stack(g);
		return;
	}

	can_release = 0;	/* unless it need not go into Old */
	now = g->New;
	g->New = g->New->nxt;
	now->nxt = ZN;

	if (now->ntyp != TRUE)
	{	if (g->Old)
		{	for (n1 = g->Old; n1->nxt; n1 = n1->nxt)
				if (isequal(now, n1))
				{	can_release = 1;
					goto out;
				}
			n1->nxt = now;
		} else
			g->Old = now;
	}
out:
	switch (now->ntyp) {
	case FALSE:
		push_stack(g);
		break;
	case TRUE:
		releasenode(1, now);
		push_stack(g);
		break;
	case PREDICATE:
	case NOT:
		if (can_release) releasenode(1, now);
		push_stack(g);
		break;
	case V_OPER:
		Assert(now->rgt->nxt == ZN, now->ntyp);
		Assert(now->lft->nxt == ZN, now->ntyp);
		n1 = now->rgt;
		n1->nxt = g->New;

		if (can_release)
			nx = now;
		else
			nx = getnode(now); /* now also appears in Old */
		nx->nxt = g->Next;

		n2 = now->lft;
		n2->nxt = getnode(now->rgt);
		n2->nxt->nxt = g->New;
		g->New = flatten(n2);
		push_stack(g);
		ng(ZS, g->incoming, n1, g->Old, nx);
		break;

	case U_OPER:
		Assert(now->rgt->nxt == ZN, now->ntyp);
		Assert(now->lft->nxt == ZN, now->ntyp);
		n1 = now->lft;

		if (can_release)
			nx = now;
		else
			nx = getnode(now); /* now also appears in Old */
		nx->nxt = g->Next;

		n2 = now->rgt;
		n2->nxt = g->New;

		goto common;

#ifdef NXT
	case NEXT:
		nx = dupnode(now->lft);
		nx->nxt = g->Next;
		g->Next = nx;
		if (can_release) releasenode(0, now);
		push_stack(g);
		break;
#endif

	case OR:
		Assert(now->rgt->nxt == ZN, now->ntyp);
		Assert(now->lft->nxt == ZN, now->ntyp);
		n1 = now->lft;
		nx = g->Next;

		n2 = now->rgt;
		n2->nxt = g->New;
common:
		n1->nxt = g->New;

		ng(ZS, g->incoming, n1, g->Old, nx);
		g->New = flatten(n2);

		if (can_release) releasenode(1, now);

		push_stack(g);
		break;
	}
}
示例#23
0
std::vector<AbstractData*> AbstractPipeline::allOutputs() const
{
    return flatten(collect(m_stages, [](const AbstractStage * stage) { return stage->allOutputs(); }));
}
示例#24
0
 void do_update( ccube_p<real> const & g )
 {
     auto dEdW = convolve_sparse_flipped(*last_input, *g, filter_stride);
     filter_.update(*dEdW);
     flatten(filter_.W(), repeat_);
 }
示例#25
0
	node* tree_rebalance_simple(node* from, size_t nodeSize) {
		node temp(0);
		node* flatRoot = flatten(from, &temp);
		buildTree(nodeSize, flatRoot);
		return temp.left;
	}
示例#26
0
// Fragtree -> bin
std::string assemble(Node fragTree) {
    return serialize(flatten(dereference(fragTree)));
}
示例#27
0
String FormData::flattenToString() const
{
    Vector<char> bytes;
    flatten(bytes);
    return Latin1Encoding().decode(reinterpret_cast<const char*>(bytes.data()), bytes.size());
}
示例#28
0
// Fragtree -> tokens
std::vector<Node> prettyAssemble(Node fragTree) {
    return flatten(dereference(fragTree));
}
示例#29
0
vm_obj format_flatten(vm_obj const & fmt) {
    return to_obj(flatten(to_format(fmt)));
}
示例#30
0
void 
coarsen_klv (
/* Coarsen until nvtxs < vmax, compute and uncoarsen. */
    struct vtx_data **graph,	/* array of vtx data for graph */
    int nvtxs,		/* number of vertices in graph */
    int nedges,		/* number of edges in graph */
    int using_vwgts,		/* are vertices weights being used? */
    int using_ewgts,		/* are edge weights being used? */
    float *term_wgts[],		/* weights for terminal propogation */
    int igeom,                /* dimension for geometric information */
    float **coords,               /* coordinates for vertices */
    int vwgt_max,		/* largest vertex weight */
    int *assignment,		/* processor each vertex gets assigned to */
    double *goal,			/* desired set sizes */
    int architecture,		/* 0 => hypercube, d => d-dimensional mesh */
    int (*hops)[MAXSETS],	/* cost of edge between sets */
    int solver_flag,		/* which eigensolver to use */
    int ndims,		/* number of eigenvectors to calculate */
    int nsets,		/* number of sets being divided into */
    int vmax,			/* largest subgraph to stop coarsening */
    int mediantype,		/* flag for different assignment strategies */
    int mkconnected,		/* enforce connectivity before eigensolve? */
    double eigtol,		/* tolerence in eigen calculation */
    int nstep,		/* number of coarsenings between RQI steps */
    int step,			/* current step number */
    int **pbndy_list,		/* pointer to returned boundary list */
    double *weights,		/* weights of vertices in each set */
    int give_up		/* has coarsening bogged down? */
)
{
    extern FILE *Output_File;	/* output file or null */
    extern int DEBUG_TRACE;	/* trace the execution of the code */
    extern int DEBUG_COARSEN;	/* debug flag for coarsening */
    extern double COARSEN_RATIO_MIN;	/* vtx reduction demanded */
    extern int COARSEN_VWGTS;	/* use vertex weights while coarsening? */
    extern int COARSEN_EWGTS;	/* use edge weights while coarsening? */
    extern int LIMIT_KL_EWGTS;	/* limit edges weights in KL? */
    extern int COARSE_KLV;	/* apply klv as a smoother? */
    extern int COARSE_BPM;	/* apply bipartite matching/flow as a smoother? */
    extern double KL_IMBALANCE;	/* fractional imbalance allowed in KL */
    struct vtx_data **cgraph;	/* array of vtx data for coarsened graph */
    double    new_goal[MAXSETS];/* new goal if not using vertex weights */
    double   *real_goal;	/* chooses between goal and new_goal */
    double    total_weight;	/* total weight of vertices */
    double    goal_weight;	/* total weight of vertices in goal */
    float    *cterm_wgts[MAXSETS];	/* terminal weights for coarse graph */
    float    *new_term_wgts[MAXSETS];	/* modified for Bui's method */
    float   **real_term_wgts;	/* which of previous two to use */
    float     ewgt_max;		/* largest edge weight in graph */
    float    *twptr = NULL;	/* loops through term_wgts */
    float    *twptr_save = NULL;/* copy of twptr */
    float    *ctwptr;		/* loops through cterm_wgts */
    float   **ccoords;		/* coarse graph coordinates */
    int      *v2cv;		/* mapping from vtxs to coarse vtxs */
    int      *flag;		/* scatter array for coarse bndy vtxs */
    int      *bndy_list;	/* list of vertices on boundary */
    int      *cbndy_list;	/* list of vertices of coarse graph on boundary */
    int    *cassignment;	/* set assignments for coarsened vertices */
    int       flattened;	/* was this graph flattened? */
    int       list_length;	/* length of boundary vtx list */
    int       cnvtxs;		/* number of vertices in coarsened graph */
    int       cnedges;		/* number of edges in coarsened graph */
    int       cvwgt_max;	/* largest vertex weight in coarsened graph */
    int       nextstep;		/* next step in RQI test */
    int       max_dev;		/* largest allowed deviation from balance */
    int       i, j;		/* loop counters */
    int       find_bndy(), flatten();
    double    find_maxdeg();
    void      makevwsqrt(), make_connected(), print_connected(), eigensolve();
    void      make_unconnected(), assign(), klvspiff(), coarsen1(), free_graph();
    void      compress_ewgts(), restore_ewgts(), count_weights(), bpm_improve();
    void      simple_part();

    if (DEBUG_COARSEN > 0 || DEBUG_TRACE > 0) {
	printf("<Entering coarsen_kl, step=%d, nvtxs=%d, nedges=%d, vmax=%d>\n",
	       step, nvtxs, nedges, vmax);
    }

    /* Is problem small enough to solve? */
    if (nvtxs <= vmax || give_up) {
	real_goal = goal; 

        simple_part(graph, nvtxs, assignment, nsets, 1, real_goal);
        list_length = find_bndy(graph, nvtxs, assignment, 2, &bndy_list);

        count_weights(graph, nvtxs, assignment, nsets + 1, weights, 1);

        max_dev = (step == 0) ? vwgt_max : 5 * vwgt_max;
        total_weight = 0;
        for (i = 0; i < nsets; i++)
            total_weight += real_goal[i];

	if (max_dev > total_weight) max_dev = vwgt_max;
        goal_weight = total_weight * KL_IMBALANCE / nsets;
        if (goal_weight > max_dev)
            max_dev = goal_weight;

	if (COARSE_KLV) {
            klvspiff(graph, nvtxs, assignment, real_goal,
                 max_dev, &bndy_list, weights);
	}
	if (COARSE_BPM) {
	    bpm_improve(graph, assignment, real_goal, max_dev, &bndy_list,
			    weights, using_vwgts);
	}
	*pbndy_list = bndy_list;
	return;
    }

    /* Otherwise I have to coarsen. */
    flattened = FALSE;
    if (coords != NULL) {
        ccoords = smalloc(igeom * sizeof(float *));
    }
    else {
        ccoords = NULL;
    }
    if (FLATTEN && step == 0) {
	flattened = flatten(graph, nvtxs, nedges, &cgraph, &cnvtxs, &cnedges, &v2cv,
			    using_ewgts && COARSEN_EWGTS,
			    igeom, coords, ccoords);
    }
    if (!flattened) {
	coarsen1(graph, nvtxs, nedges, &cgraph, &cnvtxs, &cnedges, &v2cv,
		 igeom, coords, ccoords,
		 using_ewgts && COARSEN_EWGTS);
    }

    if (term_wgts[1] != NULL) {
	twptr = smalloc((cnvtxs + 1) * (nsets - 1) * sizeof(float));
	twptr_save = twptr;
	for (i = (cnvtxs + 1) * (nsets - 1); i; i--) {
	    *twptr++ = 0;
	}
	twptr = twptr_save;
	for (j = 1; j < nsets; j++) {
	    cterm_wgts[j] = twptr;
	    twptr += cnvtxs + 1;
	}
	for (j = 1; j < nsets; j++) {
	    ctwptr = cterm_wgts[j];
	    twptr = term_wgts[j];
	    for (i = 1; i < nvtxs; i++) {
		ctwptr[v2cv[i]] += twptr[i];
	    }
	}
    }

    else {
	cterm_wgts[1] = NULL;
    }

    /* If coarsening isn't working very well, give up and partition. */
    give_up = FALSE;
    if (nvtxs * COARSEN_RATIO_MIN < cnvtxs && cnvtxs > vmax && !flattened) {
	printf("WARNING: Coarsening not making enough progress, nvtxs = %d, cnvtxs = %d.\n",
	       nvtxs, cnvtxs);
	printf("         Recursive coarsening being stopped prematurely.\n");
	if (Output_File != NULL) {
	    fprintf(Output_File,
		    "WARNING: Coarsening not making enough progress, nvtxs = %d, cnvtxs = %d.\n",
		    nvtxs, cnvtxs);
	    fprintf(Output_File,
		    "         Recursive coarsening being stopped prematurely.\n");
	}
	give_up = TRUE;
    }

    /* Now recurse on coarse subgraph. */
    if (COARSEN_VWGTS) {
	cvwgt_max = 0;
	for (i = 1; i <= cnvtxs; i++) {
	    if (cgraph[i]->vwgt > cvwgt_max)
		cvwgt_max = cgraph[i]->vwgt;
	}
    }

    else
	cvwgt_max = 1;

    cassignment = smalloc((cnvtxs + 1) * sizeof(int));
    if (flattened)
	nextstep = step;
    else
	nextstep = step + 1;
    coarsen_klv(cgraph, cnvtxs, cnedges, COARSEN_VWGTS, COARSEN_EWGTS, cterm_wgts,
		igeom, ccoords, cvwgt_max, cassignment, goal, architecture, hops,
		solver_flag, ndims, nsets, vmax, mediantype, mkconnected,
		eigtol, nstep, nextstep, &cbndy_list, weights, give_up);

    /* Interpolate assignment back to fine graph. */
    for (i = 1; i <= nvtxs; i++) {
	assignment[i] = cassignment[v2cv[i]];
    }

    /* Construct boundary list from coarse boundary list. */
    flag = smalloc((cnvtxs + 1) * sizeof(int));
    for (i = 1; i <= cnvtxs; i++) {
	flag[i] = FALSE;
    }
    for (i = 0; cbndy_list[i]; i++) {
	flag[cbndy_list[i]] = TRUE;
    }

    list_length = 0;
    for (i = 1; i <= nvtxs; i++) {
	if (flag[v2cv[i]])
	    ++list_length;
    }

    bndy_list = smalloc((list_length + 1) * sizeof(int));

    list_length = 0;
    for (i = 1; i <= nvtxs; i++) {
	if (flag[v2cv[i]])
	    bndy_list[list_length++] = i;
    }
    bndy_list[list_length] = 0;

    sfree(flag);
    sfree(cbndy_list);


    /* Free the space that was allocated. */
    sfree(cassignment);
    if (twptr_save != NULL) {
	sfree(twptr_save);
	twptr_save = NULL;
    }
    free_graph(cgraph);
    sfree(v2cv);

    /* Smooth using KL or BPM every nstep steps. */
    if (!(step % nstep) && !flattened) {
	if (!COARSEN_VWGTS && step != 0) {	/* Construct new goal */
	    goal_weight = 0;
	    for (i = 0; i < nsets; i++)
		goal_weight += goal[i];
	    for (i = 0; i < nsets; i++)
		new_goal[i] = goal[i] * (nvtxs / goal_weight);
	    real_goal = new_goal;
	}
	else
	    real_goal = goal;

	if (LIMIT_KL_EWGTS) {
	    find_maxdeg(graph, nvtxs, using_ewgts, &ewgt_max);
	    compress_ewgts(graph, nvtxs, nedges, ewgt_max,
			   using_ewgts);
	}

	/* If not coarsening ewgts, then need care with term_wgts. */
	if (!using_ewgts && term_wgts[1] != NULL && step != 0) {
	    twptr = smalloc((nvtxs + 1) * (nsets - 1) * sizeof(float));
	    twptr_save = twptr;
	    for (j = 1; j < nsets; j++) {
		new_term_wgts[j] = twptr;
		twptr += nvtxs + 1;
	    }

	    for (j = 1; j < nsets; j++) {
		twptr = term_wgts[j];
		ctwptr = new_term_wgts[j];
		for (i = 1; i <= nvtxs; i++) {
		    if (twptr[i] > .5)
			ctwptr[i] = 1;
		    else if (twptr[i] < -.5)
			ctwptr[i] = -1;
		    else
			ctwptr[i] = 0;
		}
	    }
	    real_term_wgts = new_term_wgts;
	}
	else {
	    real_term_wgts = term_wgts;
	    new_term_wgts[1] = NULL;
	}

	max_dev = (step == 0) ? vwgt_max : 5 * vwgt_max;
	total_weight = 0;
	for (i = 0; i < nsets; i++) {
	    total_weight += real_goal[i];
	}
	if (max_dev > total_weight)
	    max_dev = vwgt_max;
	goal_weight = total_weight * KL_IMBALANCE / nsets;
	if (goal_weight > max_dev) {
	    max_dev = goal_weight;
	}

	if (!COARSEN_VWGTS) {
	    count_weights(graph, nvtxs, assignment, nsets + 1, weights,
			  (vwgt_max != 1));
	}

	if (COARSE_KLV) {
	    klvspiff(graph, nvtxs, assignment, real_goal,
		     max_dev, &bndy_list, weights);
	}
	if (COARSE_BPM) {
	    bpm_improve(graph, assignment, real_goal, max_dev, &bndy_list,
			weights, using_vwgts);
	}

	if (real_term_wgts != term_wgts && new_term_wgts[1] != NULL) {
	    sfree(real_term_wgts[1]);
	}

	if (LIMIT_KL_EWGTS)
	    restore_ewgts(graph, nvtxs);
    }

    *pbndy_list = bndy_list;

    if (twptr_save != NULL) {
	sfree(twptr_save);
	twptr_save = NULL;
    }

    /* Free the space that was allocated. */
    if (ccoords != NULL) {
        for (i = 0; i < igeom; i++)
            sfree(ccoords[i]);
        sfree(ccoords);
    }

    if (DEBUG_COARSEN > 0) {
	printf(" Leaving coarsen_klv, step=%d\n", step);
    }
}