<commit_before>/***************************************************************
 *
 * Copyright (C) 1990-2011, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * 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 "condor_common.h"
#include "generic_query.h"
#include "condor_attributes.h"
#include "condor_classad.h"
#include "MyString.h"

static char *new_strdup (const char *);

GenericQuery::
GenericQuery ()
{
	// initialize category counts
	integerThreshold = 0;
	stringThreshold = 0;
	floatThreshold = 0;

	// initialize pointers
	integerConstraints = 0;
	floatConstraints = 0;
	stringConstraints = 0;

	floatKeywordList = NULL;
	integerKeywordList = NULL;
	stringKeywordList = NULL;
}

GenericQuery::
GenericQuery (const GenericQuery &gq)
{
	// initialize category counts
	integerThreshold = 0;
	stringThreshold = 0;
	floatThreshold = 0;

	// initialize pointers
	integerConstraints = 0;
	floatConstraints = 0;
	stringConstraints = 0;

	floatKeywordList = NULL;
	integerKeywordList = NULL;
	stringKeywordList = NULL;

	copyQueryObject(gq);
}

GenericQuery::
~GenericQuery ()
{
	clearQueryObject ();

	// release memory
	if (stringConstraints) delete [] stringConstraints;
	if (floatConstraints)  delete [] floatConstraints;
	if (integerConstraints)delete [] integerConstraints;
}

int GenericQuery::
setNumIntegerCats (const int numCats)
{
	integerThreshold = (numCats > 0) ? numCats : 0;
	if (integerThreshold)
	{
		integerConstraints = new SimpleList<int> [integerThreshold];
		if (!integerConstraints)
			return Q_MEMORY_ERROR;
		return Q_OK;
	}
	return Q_INVALID_CATEGORY;
}

int GenericQuery::
setNumStringCats (const int numCats)
{
	stringThreshold = (numCats > 0) ? numCats : 0;
	if (stringThreshold)
	{
		stringConstraints = new List<char> [stringThreshold];
		if (!stringConstraints)
			return Q_MEMORY_ERROR;
		return Q_OK;
	}
	return Q_INVALID_CATEGORY;
}

int GenericQuery::
setNumFloatCats (const int numCats)
{
	floatThreshold = (numCats > 0) ? numCats : 0;
	if (floatThreshold)
	{
		floatConstraints = new SimpleList<float> [floatThreshold];
		if (!floatConstraints)
			return Q_MEMORY_ERROR;
		return Q_OK;
	}
	return Q_INVALID_CATEGORY;
}

// add an integer constraint
int GenericQuery::
addInteger (const int cat, int value)
{
    if (cat >= 0 && cat < integerThreshold)
    {
        if (!integerConstraints [cat].Append (value))
            return Q_MEMORY_ERROR;
        return Q_OK;
    }

    return Q_INVALID_CATEGORY;
}

int GenericQuery::
addFloat (const int cat, float value)
{
    if (cat >= 0 && cat < floatThreshold)
    {
        if (!floatConstraints [cat].Append (value))
            return Q_MEMORY_ERROR;
        return Q_OK;
    }

    return Q_INVALID_CATEGORY;
}

int GenericQuery::
addString (const int cat, const char *value)
{
    char *x;

    if (cat >= 0 && cat < stringThreshold)
    {
        x = new_strdup (value);
        if (!x) return Q_MEMORY_ERROR;
        stringConstraints [cat].Append (x);
        return Q_OK;
    }

    return Q_INVALID_CATEGORY;
}

int GenericQuery::
addCustomOR (const char *value)
{
    char *x = new_strdup (value);
	if (!x) return Q_MEMORY_ERROR;
	customORConstraints.Append (x);
	return Q_OK;
}

int GenericQuery::
addCustomAND (const char *value)
{
    char *x = new_strdup (value);
	if (!x) return Q_MEMORY_ERROR;
	customANDConstraints.Append (x);
	return Q_OK;
}

// clear functions
int GenericQuery::
clearInteger (const int cat)
{
	if (cat >= 0 && cat < integerThreshold)
	{
		clearIntegerCategory (integerConstraints [cat]);
		return Q_OK;
	}
	else
		return Q_INVALID_CATEGORY;
}

int GenericQuery::
clearString (const int cat)
{
	if (cat >= 0 && cat < stringThreshold)
	{
		clearStringCategory (stringConstraints [cat]);
		return Q_OK;
	}
	else
		return Q_INVALID_CATEGORY;
}

int GenericQuery::
clearFloat (const int cat)
{
	if (cat >= 0 && cat < floatThreshold)
	{
		clearFloatCategory (floatConstraints [cat]);
		return Q_OK;
	}
	else
		return Q_INVALID_CATEGORY;
}

int GenericQuery::
clearCustomOR ()
{
	clearStringCategory (customORConstraints);
	return Q_OK;
}

int GenericQuery::
clearCustomAND ()
{
	clearStringCategory (customANDConstraints);
	return Q_OK;
}

// set keyword lists
void GenericQuery::
setIntegerKwList (char **value)
{
	integerKeywordList = value;
}

void GenericQuery::
setStringKwList (char **value)
{
	stringKeywordList = value;
}

void GenericQuery::
setFloatKwList (char **value)
{
	floatKeywordList = value;
}

// make query
int GenericQuery::
makeQuery (MyString &req)
{
	int		i, value;
	char	*item;
	float   fvalue;

	req = "";

	// construct query requirement expression
	bool firstCategory = true;

	// add string constraints
	for (i = 0; i < stringThreshold; i++)
	{
		stringConstraints [i].Rewind ();
		if (!stringConstraints [i].AtEnd ())
		{
			bool firstTime = true;
			req += firstCategory ? "(" : " && (";
			while ((item = stringConstraints [i].Next ()))
			{
				req.formatstr_cat ("%s(%s == \"%s\")",
						 firstTime ? " " : " || ",
						 stringKeywordList [i], item);
				firstTime = false;
				firstCategory = false;
			}
			req += " )";
		}
	}

	// add integer constraints
	for (i = 0; i < integerThreshold; i++)
	{
		integerConstraints [i].Rewind ();
		if (!integerConstraints [i].AtEnd ())
		{
			bool firstTime = true;
			req += firstCategory ? "(" : " && (";
			while (integerConstraints [i].Next (value))
			{
				req.formatstr_cat ("%s(%s == %d)",
						 firstTime ? " " : " || ",
						 integerKeywordList [i], value);
				firstTime = false;
				firstCategory = false;
			}
			req += " )";
		}
	}

	// add float constraints
	for (i = 0; i < floatThreshold; i++)
	{
		floatConstraints [i].Rewind ();
		if (!floatConstraints [i].AtEnd ())
		{
			bool firstTime = true;
			req += firstCategory ? "(" : " && (";
			while (floatConstraints [i].Next (fvalue))
			{
				req.formatstr_cat ("%s(%s == %f)",
						 firstTime ? " " : " || ",
						 floatKeywordList [i], fvalue);
				firstTime = false;
				firstCategory = false;
			}
			req += " )";
		}
	}

	// add custom AND constraints
	customANDConstraints.Rewind ();
	if (!customANDConstraints.AtEnd ())
	{
		bool firstTime = true;
		req += firstCategory ? "(" : " && (";
		while ((item = customANDConstraints.Next ()))
		{
			req.formatstr_cat ("%s(%s)", firstTime ? " " : " && ", item);
			firstTime = false;
			firstCategory = false;
		}
		req += " )";
	}

	// add custom OR constraints
	customORConstraints.Rewind ();
	if (!customORConstraints.AtEnd ())
	{
		bool firstTime = true;
		req += firstCategory ? "(" : " && (";
		while ((item = customORConstraints.Next ()))
		{
			req.formatstr_cat ("%s(%s)", firstTime ? " " : " || ", item);
			firstTime = false;
			firstCategory = false;
		}
		req += " )";
	}

	return Q_OK;
}

int GenericQuery::
makeQuery (ExprTree *&tree)
{
	MyString req;
	int status = makeQuery(req);
	if (status != Q_OK) return status;

	// If there are no constraints, then we match everything.
	if (req.empty()) req = "TRUE";

	// parse constraints and insert into query ad
	if (ParseClassAdRvalExpr (req.Value(), tree) > 0) return Q_PARSE_ERROR;

	return Q_OK;
}

// helper functions --- clear
void GenericQuery::
clearQueryObject (void)
{
	int i;
	for (i = 0; i < stringThreshold; i++)
		if (stringConstraints) clearStringCategory (stringConstraints[i]);

	for (i = 0; i < integerThreshold; i++)
		if (integerConstraints) clearIntegerCategory (integerConstraints[i]);

	for (i = 0; i < floatThreshold; i++)
		if (integerConstraints) clearFloatCategory (floatConstraints[i]);

	clearStringCategory (customANDConstraints);
	clearStringCategory (customORConstraints);
}

void GenericQuery::
clearStringCategory (List<char> &str_category)
{
    char *x;
    str_category.Rewind ();
    while ((x = str_category.Next ()))
    {
        delete [] x;
        str_category.DeleteCurrent ();
    }
}

void GenericQuery::
clearIntegerCategory (SimpleList<int> &int_category)
{
    int item;

    int_category.Rewind ();
    while (int_category.Next (item))
        int_category.DeleteCurrent ();
}

void GenericQuery::
clearFloatCategory (SimpleList<float> &float_category)
{
    float item;

    float_category.Rewind ();
    while (float_category.Next (item))
        float_category.DeleteCurrent ();
}

// helper functions --- copy
void GenericQuery::
copyQueryObject (const GenericQuery &from)
{
	int i;

	// copy string constraints
   	for (i = 0; i < from.stringThreshold; i++)
		copyStringCategory (stringConstraints[i], from.stringConstraints[i]);

	// copy integer constraints
	for (i = 0; i < from.integerThreshold; i++)
		copyIntegerCategory (integerConstraints[i],from.integerConstraints[i]);

	// copy custom constraints
	copyStringCategory (customANDConstraints, const_cast<List<char> &>(from.customANDConstraints));
	copyStringCategory (customORConstraints, const_cast<List<char> &>(from.customORConstraints));

	// copy misc fields
	stringThreshold = from.stringThreshold;
	integerThreshold = from.integerThreshold;
	floatThreshold = from.floatThreshold;

	integerKeywordList = from.integerKeywordList;
	stringKeywordList = from.stringKeywordList;
	floatKeywordList = from.floatKeywordList;

	floatConstraints = from.floatConstraints;
	integerConstraints = from.integerConstraints;
	stringConstraints = from.stringConstraints;
}

void GenericQuery::
copyStringCategory (List<char> &to, List<char> &from)
{
	char *item;

	clearStringCategory (to);
	from.Rewind ();
	while ((item = from.Next ()))
		to.Append (new_strdup (item));
}

void GenericQuery::
copyIntegerCategory (SimpleList<int> &to, SimpleList<int> &from)
{
	int item;

	clearIntegerCategory (to);
	while (from.Next (item))
		to.Append (item);
}

void GenericQuery::
copyFloatCategory (SimpleList<float> &to, SimpleList<float> &from)
{
	float item;

	clearFloatCategory (to);
	while (from.Next (item))
		to.Append (item);
}

// strdup() which uses new
static char *new_strdup (const char *str)
{
    char *x = new char [strlen (str) + 1];
    if (!x) return 0;
    strcpy (x, str);
    return x;
}
<commit_msg>More coverity appeasement #6992<commit_after>/***************************************************************
 *
 * Copyright (C) 1990-2011, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * 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 "condor_common.h"
#include "generic_query.h"
#include "condor_attributes.h"
#include "condor_classad.h"
#include "MyString.h"

static char *new_strdup (const char *);

GenericQuery::
GenericQuery ()
{
	// initialize category counts
	integerThreshold = 0;
	stringThreshold = 0;
	floatThreshold = 0;

	// initialize pointers
	integerConstraints = 0;
	floatConstraints = 0;
	stringConstraints = 0;

	floatKeywordList = NULL;
	integerKeywordList = NULL;
	stringKeywordList = NULL;
}

GenericQuery::
GenericQuery (const GenericQuery &gq)
{
	// initialize category counts
	integerThreshold = 0;
	stringThreshold = 0;
	floatThreshold = 0;

	// initialize pointers
	integerConstraints = 0;
	floatConstraints = 0;
	stringConstraints = 0;

	floatKeywordList = NULL;
	integerKeywordList = NULL;
	stringKeywordList = NULL;

	copyQueryObject(gq);
}

GenericQuery::
~GenericQuery ()
{
	clearQueryObject ();

	// release memory
	if (stringConstraints) delete [] stringConstraints;
	if (floatConstraints)  delete [] floatConstraints;
	if (integerConstraints)delete [] integerConstraints;
}

int GenericQuery::
setNumIntegerCats (const int numCats)
{
	integerThreshold = (numCats > 0) ? numCats : 0;
	if (integerThreshold)
	{
		integerConstraints = new SimpleList<int> [integerThreshold];
		if (!integerConstraints)
			return Q_MEMORY_ERROR;
		return Q_OK;
	}
	return Q_INVALID_CATEGORY;
}

int GenericQuery::
setNumStringCats (const int numCats)
{
	stringThreshold = (numCats > 0) ? numCats : 0;
	if (stringThreshold)
	{
		stringConstraints = new List<char> [stringThreshold];
		if (!stringConstraints)
			return Q_MEMORY_ERROR;
		return Q_OK;
	}
	return Q_INVALID_CATEGORY;
}

int GenericQuery::
setNumFloatCats (const int numCats)
{
	floatThreshold = (numCats > 0) ? numCats : 0;
	if (floatThreshold)
	{
		floatConstraints = new SimpleList<float> [floatThreshold];
		if (!floatConstraints)
			return Q_MEMORY_ERROR;
		return Q_OK;
	}
	return Q_INVALID_CATEGORY;
}

// add an integer constraint
int GenericQuery::
addInteger (const int cat, int value)
{
    if (cat >= 0 && cat < integerThreshold)
    {
        if (!integerConstraints [cat].Append (value))
            return Q_MEMORY_ERROR;
        return Q_OK;
    }

    return Q_INVALID_CATEGORY;
}

int GenericQuery::
addFloat (const int cat, float value)
{
    if (cat >= 0 && cat < floatThreshold)
    {
        if (!floatConstraints [cat].Append (value))
            return Q_MEMORY_ERROR;
        return Q_OK;
    }

    return Q_INVALID_CATEGORY;
}

int GenericQuery::
addString (const int cat, const char *value)
{
    char *x;

    if (cat >= 0 && cat < stringThreshold)
    {
        x = new_strdup (value);
        if (!x) return Q_MEMORY_ERROR;
        stringConstraints [cat].Append (x);
        return Q_OK;
    }

    return Q_INVALID_CATEGORY;
}

int GenericQuery::
addCustomOR (const char *value)
{
    char *x = new_strdup (value);
	if (!x) return Q_MEMORY_ERROR;
	customORConstraints.Append (x);
	return Q_OK;
}

int GenericQuery::
addCustomAND (const char *value)
{
    char *x = new_strdup (value);
	if (!x) return Q_MEMORY_ERROR;
	customANDConstraints.Append (x);
	return Q_OK;
}

// clear functions
int GenericQuery::
clearInteger (const int cat)
{
	if (cat >= 0 && cat < integerThreshold)
	{
		clearIntegerCategory (integerConstraints [cat]);
		return Q_OK;
	}
	else
		return Q_INVALID_CATEGORY;
}

int GenericQuery::
clearString (const int cat)
{
	if (cat >= 0 && cat < stringThreshold)
	{
		clearStringCategory (stringConstraints [cat]);
		return Q_OK;
	}
	else
		return Q_INVALID_CATEGORY;
}

int GenericQuery::
clearFloat (const int cat)
{
	if (cat >= 0 && cat < floatThreshold)
	{
		clearFloatCategory (floatConstraints [cat]);
		return Q_OK;
	}
	else
		return Q_INVALID_CATEGORY;
}

int GenericQuery::
clearCustomOR ()
{
	clearStringCategory (customORConstraints);
	return Q_OK;
}

int GenericQuery::
clearCustomAND ()
{
	clearStringCategory (customANDConstraints);
	return Q_OK;
}

// set keyword lists
void GenericQuery::
setIntegerKwList (char **value)
{
	integerKeywordList = value;
}

void GenericQuery::
setStringKwList (char **value)
{
	stringKeywordList = value;
}

void GenericQuery::
setFloatKwList (char **value)
{
	floatKeywordList = value;
}

// make query
int GenericQuery::
makeQuery (MyString &req)
{
	int		i, value;
	char	*item;
	float   fvalue;

	req = "";

	// construct query requirement expression
	bool firstCategory = true;

	// add string constraints
	for (i = 0; i < stringThreshold; i++)
	{
		stringConstraints [i].Rewind ();
		if (!stringConstraints [i].AtEnd ())
		{
			bool firstTime = true;
			req += firstCategory ? "(" : " && (";
			while ((item = stringConstraints [i].Next ()))
			{
				req.formatstr_cat ("%s(%s == \"%s\")",
						 firstTime ? " " : " || ",
						 stringKeywordList [i], item);
				firstTime = false;
				firstCategory = false;
			}
			req += " )";
		}
	}

	// add integer constraints
	for (i = 0; i < integerThreshold; i++)
	{
		integerConstraints [i].Rewind ();
		if (!integerConstraints [i].AtEnd ())
		{
			bool firstTime = true;
			req += firstCategory ? "(" : " && (";
			while (integerConstraints [i].Next (value))
			{
				req.formatstr_cat ("%s(%s == %d)",
						 firstTime ? " " : " || ",
						 integerKeywordList [i], value);
				firstTime = false;
				firstCategory = false;
			}
			req += " )";
		}
	}

	// add float constraints
	for (i = 0; i < floatThreshold; i++)
	{
		floatConstraints [i].Rewind ();
		if (!floatConstraints [i].AtEnd ())
		{
			bool firstTime = true;
			req += firstCategory ? "(" : " && (";
			while (floatConstraints [i].Next (fvalue))
			{
				req.formatstr_cat ("%s(%s == %f)",
						 firstTime ? " " : " || ",
						 floatKeywordList [i], fvalue);
				firstTime = false;
				firstCategory = false;
			}
			req += " )";
		}
	}

	// add custom AND constraints
	customANDConstraints.Rewind ();
	if (!customANDConstraints.AtEnd ())
	{
		bool firstTime = true;
		req += firstCategory ? "(" : " && (";
		while ((item = customANDConstraints.Next ()))
		{
			req.formatstr_cat ("%s(%s)", firstTime ? " " : " && ", item);
			firstTime = false;
			firstCategory = false;
		}
		req += " )";
	}

	// add custom OR constraints
	customORConstraints.Rewind ();
	if (!customORConstraints.AtEnd ())
	{
		bool firstTime = true;
		req += firstCategory ? "(" : " && (";
		while ((item = customORConstraints.Next ()))
		{
			req.formatstr_cat ("%s(%s)", firstTime ? " " : " || ", item);
			firstTime = false;
			firstCategory = false;
		}
		req += " )";
	}

	return Q_OK;
}

int GenericQuery::
makeQuery (ExprTree *&tree)
{
	MyString req;
	int status = makeQuery(req);
	if (status != Q_OK) return status;

	// If there are no constraints, then we match everything.
	if (req.empty()) req = "TRUE";

	// parse constraints and insert into query ad
	if (ParseClassAdRvalExpr (req.Value(), tree) > 0) return Q_PARSE_ERROR;

	return Q_OK;
}

// helper functions --- clear
void GenericQuery::
clearQueryObject (void)
{
	int i;
	for (i = 0; i < stringThreshold; i++)
		if (stringConstraints) clearStringCategory (stringConstraints[i]);

	for (i = 0; i < integerThreshold; i++)
		if (integerConstraints) clearIntegerCategory (integerConstraints[i]);

	for (i = 0; i < floatThreshold; i++)
		if (integerConstraints) clearFloatCategory (floatConstraints[i]);

	clearStringCategory (customANDConstraints);
	clearStringCategory (customORConstraints);
}

void GenericQuery::
clearStringCategory (List<char> &str_category)
{
    char *x;
    str_category.Rewind ();
    while ((x = str_category.Next ()))
    {
        delete [] x;
        str_category.DeleteCurrent ();
    }
}

void GenericQuery::
clearIntegerCategory (SimpleList<int> &int_category)
{
    int item;

    int_category.Rewind ();
    while (int_category.Next (item))
        int_category.DeleteCurrent ();
}

void GenericQuery::
clearFloatCategory (SimpleList<float> &float_category)
{
    float item;

    float_category.Rewind ();
    while (float_category.Next (item))
        float_category.DeleteCurrent ();
}

// helper functions --- copy
void GenericQuery::
copyQueryObject (const GenericQuery &from)
{
	int i;

	// copy string constraints
   	for (i = 0; i < from.stringThreshold; i++)
		if (stringConstraints) copyStringCategory (stringConstraints[i], from.stringConstraints[i]);

	// copy integer constraints
	for (i = 0; i < from.integerThreshold; i++)
		if (integerConstraints) copyIntegerCategory (integerConstraints[i],from.integerConstraints[i]);

	// copy custom constraints
	copyStringCategory (customANDConstraints, const_cast<List<char> &>(from.customANDConstraints));
	copyStringCategory (customORConstraints, const_cast<List<char> &>(from.customORConstraints));

	// copy misc fields
	stringThreshold = from.stringThreshold;
	integerThreshold = from.integerThreshold;
	floatThreshold = from.floatThreshold;

	integerKeywordList = from.integerKeywordList;
	stringKeywordList = from.stringKeywordList;
	floatKeywordList = from.floatKeywordList;

	floatConstraints = from.floatConstraints;
	integerConstraints = from.integerConstraints;
	stringConstraints = from.stringConstraints;
}

void GenericQuery::
copyStringCategory (List<char> &to, List<char> &from)
{
	char *item;

	clearStringCategory (to);
	from.Rewind ();
	while ((item = from.Next ()))
		to.Append (new_strdup (item));
}

void GenericQuery::
copyIntegerCategory (SimpleList<int> &to, SimpleList<int> &from)
{
	int item;

	clearIntegerCategory (to);
	while (from.Next (item))
		to.Append (item);
}

void GenericQuery::
copyFloatCategory (SimpleList<float> &to, SimpleList<float> &from)
{
	float item;

	clearFloatCategory (to);
	while (from.Next (item))
		to.Append (item);
}

// strdup() which uses new
static char *new_strdup (const char *str)
{
    char *x = new char [strlen (str) + 1];
    if (!x) return 0;
    strcpy (x, str);
    return x;
}
<|endoftext|>


<commit_before>/*
 * PoolingGenConn.cpp
 *
 *  Created on: Apr 25, 2011
 *      Author: peteschultz
 */

#include "PoolingGenConn.hpp"

namespace PV {
PoolingGenConn::PoolingGenConn(const char * name, HyPerCol * hc,
        HyPerLayer * pre, HyPerLayer * post, HyPerLayer * pre2, HyPerLayer * post2,
        const char * filename, InitWeights *weightInit) {
        initialize_base();
        initialize(name, hc, pre, post, pre2, post2, filename, weightInit);
}  // end of PoolingGenConn::PoolingGenConn(const char *, HyPerCol *,
   //   HyPerLayer *, HyPerLayer *, HyPerLayer *, HyPerLayer *, int, const char *)

int PoolingGenConn::initialize_base() {
    pre2 = NULL;
    post2 = NULL;
    return PV_SUCCESS;
}

int PoolingGenConn::initialize(const char * name, HyPerCol * hc,
        HyPerLayer * pre, HyPerLayer * post, HyPerLayer * pre2, HyPerLayer * post2,
        const char * filename, InitWeights *weightInit) {
   int status;
   PVParams * params = hc->parameters();
   status = GenerativeConn::initialize(name, hc, pre, post, filename, weightInit);
   if( status == PV_SUCCESS && checkLayersCompatible(pre, pre2) && checkLayersCompatible(post, post2) ) {
      this->pre2 = pre2;
      this->post2 = post2;
   }
   else {
      status = PV_FAILURE;
   }
   if( status == PV_SUCCESS ) {
      slownessFlag = params->value(name, "slownessFlag", 0.0/*default is false*/);
   }
   if( slownessFlag ) {
      status = getSlownessLayer(&slownessPre, "slownessPre");
      status = getSlownessLayer(&slownessPost, "slownessPost")==PV_SUCCESS ? status : PV_FAILURE;
   }
   if( slownessFlag && status == PV_SUCCESS ) {
      status = checkLayersCompatible(pre, slownessPre) ? status : PV_FAILURE;
      status = checkLayersCompatible(post, slownessPost) ? status : PV_FAILURE;
   }
   if( status != PV_SUCCESS ) {
      abort();
   }
   return status;
}  // end of PoolingGenConn::initialize(const char *, HyPerCol *,
   //   HyPerLayer *, HyPerLayer *, HyPerLayer *, HyPerLayer *, int, const char *, InitWeights *)

bool PoolingGenConn::checkLayersCompatible(HyPerLayer * layer1, HyPerLayer * layer2) {
	int nx1 = layer1->getLayerLoc()->nx;
	int nx2 = layer2->getLayerLoc()->nx;
	int ny1 = layer1->getLayerLoc()->ny;
	int ny2 = layer2->getLayerLoc()->ny;
	int nf1 = layer1->getLayerLoc()->nf;
	int nf2 = layer2->getLayerLoc()->nf;
	int nb1 = layer1->getLayerLoc()->nb;
	int nb2 = layer2->getLayerLoc()->nb;
    bool result = nx1==nx2 && ny1==ny2 && nf1==nf2 && nb1==nb2;
    if( !result ) {
    	const char * name1 = layer1->getName();
    	const char * name2 = layer2->getName();
        fprintf(stderr, "Group \"%s\": Layers \"%s\" and \"%s\" do not have compatible sizes\n", name, name1, name2);
        int len1 = (int) strlen(name1);
        int len2 = (int) strlen(name2);
        int len = len1 >= len2 ? len1 : len2;
        fprintf(stderr, "Layer \"%*s\": nx=%d, ny=%d, nf=%d, nb=%d\n", len, name1, nx1, ny1, nf1, nb1);
        fprintf(stderr, "Layer \"%*s\": nx=%d, ny=%d, nf=%d, nb=%d\n", len, name2, nx2, ny2, nf2, nb2);
    }
    return result;
}  // end of PoolingGenConn::PoolingGenConn(HyPerLayer *, HyPerLayer *)

int PoolingGenConn::getSlownessLayer(HyPerLayer ** l, const char * paramname) {
   int status = PV_SUCCESS;
   assert(slownessFlag);
   const char * slownessLayerName = parent->parameters()->stringValue(name, paramname, false);
   if( slownessLayerName == NULL ) {
      status = PV_FAILURE;
      fprintf(stderr, "PoolingGenConn \"%s\": if slownessFlag is set, parameter \"%s\" must be set\n", name, paramname);
   }
   if( status == PV_SUCCESS ) {
      *l = parent->getLayerFromName(slownessLayerName);
      if( *l == NULL ) {
         status = PV_FAILURE;
         fprintf(stderr, "PoolingGenConn \"%s\": %s layer \"%s\" was not found\n", name, paramname, slownessLayerName);
      }
   }
   return status;
}

int PoolingGenConn::updateWeights(int axonID) {
    int nPre = preSynapticLayer()->getNumNeurons();
    int nx = preSynapticLayer()->getLayerLoc()->nx;
    int ny = preSynapticLayer()->getLayerLoc()->ny;
    int nf = preSynapticLayer()->getLayerLoc()->nf;
    int pad = preSynapticLayer()->getLayerLoc()->nb;
    for(int kPre=0; kPre<nPre;kPre++) {
        int kExt = kIndexExtended(kPre, nx, ny, nf, pad);

        size_t offset = getAPostOffset(kPre, axonID);
        pvdata_t preact = preSynapticLayer()->getCLayer()->activity->data[kExt];
        pvdata_t preact2 = getPre2()->getCLayer()->activity->data[kExt];
        PVPatch * weights = getWeights(kPre,axonID);
        int nyp = weights->ny;
        int nk = weights->nx * nfp;
        pvdata_t * postactRef = &(postSynapticLayer()->getCLayer()->activity->data[offset]);
        pvdata_t * postact2Ref = &(getPost2()->getCLayer()->activity->data[offset]);
        int sya = getPostNonextStrides()->sy;
        pvdata_t * wtpatch = get_wData(axonID, kExt); // weights->data;
        int syw = syp;
        for( int y=0; y<nyp; y++ ) {
            int lineoffsetw = weights->offset;
            int lineoffseta = 0;
            for( int k=0; k<nk; k++ ) {
                float w = wtpatch[lineoffsetw + k] + relaxation*(preact*postactRef[lineoffseta + k]+preact2*postact2Ref[lineoffseta + k]);
                wtpatch[lineoffsetw + k] = w;
            }
            lineoffsetw += syw;
            lineoffseta += sya;
        }
    }
    if( slownessFlag ) {
       for(int kPre=0; kPre<nPre;kPre++) {
           int kExt = kIndexExtended(kPre, nx, ny, nf, pad);

           size_t offset = getAPostOffset(kPre, axonID);
           pvdata_t preact = slownessPre->getCLayer()->activity->data[kExt];
           PVPatch * weights = getWeights(kPre,axonID);
           int nyp = weights->ny;
           int nk = weights->nx * nfp;
           pvdata_t * postactRef = &(slownessPost->getCLayer()->activity->data[offset]);
           int sya = getPostNonextStrides()->sy;
           pvdata_t * wtpatch = get_wData(axonID, kExt); // weights->data;
           int syw = syp;
           for( int y=0; y<nyp; y++ ) {
               int lineoffsetw = 0;
               int lineoffseta = 0;
               for( int k=0; k<nk; k++ ) {
                   float w = wtpatch[lineoffsetw + k] - relaxation*(preact*postactRef[lineoffseta + k]);
                   wtpatch[lineoffsetw + k] = w;
               }
               lineoffsetw += syw;
               lineoffseta += sya;
           }
       }
    }
    if( nonnegConstraintFlag ) {
       for(int kPatch=0; kPatch<getNumDataPatches();kPatch++) {
          // PVPatch * weights = this->getKernelPatch(axonID, kPatch);
          pvdata_t * wtpatch = get_wDataHead(axonID, kPatch); // weights->data;
           int nk = nxp * nfp;
           int syw = nxp*nfp;
           for( int y=0; y < nyp; y++ ) {
               int lineoffsetw = 0;
               for( int k=0; k<nk; k++ ) {
                   pvdata_t w = wtpatch[lineoffsetw + k];
                   if( w<0 ) {
                      wtpatch[lineoffsetw + k] = 0;
                   }
               }
               lineoffsetw += syw;
           }
       }
    }
    // normalizeWeights now called in KernelConn::updateState
    lastUpdateTime = parent->simulationTime();

    return PV_SUCCESS;
}

}  // end namespace PV
<commit_msg>Bugfix for PoolingGenConn<commit_after>/*
 * PoolingGenConn.cpp
 *
 *  Created on: Apr 25, 2011
 *      Author: peteschultz
 */

#include "PoolingGenConn.hpp"

namespace PV {
PoolingGenConn::PoolingGenConn(const char * name, HyPerCol * hc,
        HyPerLayer * pre, HyPerLayer * post, HyPerLayer * pre2, HyPerLayer * post2,
        const char * filename, InitWeights *weightInit) {
        initialize_base();
        initialize(name, hc, pre, post, pre2, post2, filename, weightInit);
}  // end of PoolingGenConn::PoolingGenConn(const char *, HyPerCol *,
   //   HyPerLayer *, HyPerLayer *, HyPerLayer *, HyPerLayer *, int, const char *)

int PoolingGenConn::initialize_base() {
    pre2 = NULL;
    post2 = NULL;
    return PV_SUCCESS;
}

int PoolingGenConn::initialize(const char * name, HyPerCol * hc,
        HyPerLayer * pre, HyPerLayer * post, HyPerLayer * pre2, HyPerLayer * post2,
        const char * filename, InitWeights *weightInit) {
   int status;
   PVParams * params = hc->parameters();
   status = GenerativeConn::initialize(name, hc, pre, post, filename, weightInit);
   if( status == PV_SUCCESS && checkLayersCompatible(pre, pre2) && checkLayersCompatible(post, post2) ) {
      this->pre2 = pre2;
      this->post2 = post2;
   }
   else {
      status = PV_FAILURE;
   }
   if( status == PV_SUCCESS ) {
      slownessFlag = params->value(name, "slownessFlag", 0.0/*default is false*/);
   }
   if( slownessFlag ) {
      status = getSlownessLayer(&slownessPre, "slownessPre");
      status = getSlownessLayer(&slownessPost, "slownessPost")==PV_SUCCESS ? status : PV_FAILURE;
   }
   if( slownessFlag && status == PV_SUCCESS ) {
      status = checkLayersCompatible(pre, slownessPre) ? status : PV_FAILURE;
      status = checkLayersCompatible(post, slownessPost) ? status : PV_FAILURE;
   }
   if( status != PV_SUCCESS ) {
      abort();
   }
   return status;
}  // end of PoolingGenConn::initialize(const char *, HyPerCol *,
   //   HyPerLayer *, HyPerLayer *, HyPerLayer *, HyPerLayer *, int, const char *, InitWeights *)

bool PoolingGenConn::checkLayersCompatible(HyPerLayer * layer1, HyPerLayer * layer2) {
	int nx1 = layer1->getLayerLoc()->nx;
	int nx2 = layer2->getLayerLoc()->nx;
	int ny1 = layer1->getLayerLoc()->ny;
	int ny2 = layer2->getLayerLoc()->ny;
	int nf1 = layer1->getLayerLoc()->nf;
	int nf2 = layer2->getLayerLoc()->nf;
	int nb1 = layer1->getLayerLoc()->nb;
	int nb2 = layer2->getLayerLoc()->nb;
    bool result = nx1==nx2 && ny1==ny2 && nf1==nf2 && nb1==nb2;
    if( !result ) {
    	const char * name1 = layer1->getName();
    	const char * name2 = layer2->getName();
        fprintf(stderr, "Group \"%s\": Layers \"%s\" and \"%s\" do not have compatible sizes\n", name, name1, name2);
        int len1 = (int) strlen(name1);
        int len2 = (int) strlen(name2);
        int len = len1 >= len2 ? len1 : len2;
        fprintf(stderr, "Layer \"%*s\": nx=%d, ny=%d, nf=%d, nb=%d\n", len, name1, nx1, ny1, nf1, nb1);
        fprintf(stderr, "Layer \"%*s\": nx=%d, ny=%d, nf=%d, nb=%d\n", len, name2, nx2, ny2, nf2, nb2);
    }
    return result;
}  // end of PoolingGenConn::PoolingGenConn(HyPerLayer *, HyPerLayer *)

int PoolingGenConn::getSlownessLayer(HyPerLayer ** l, const char * paramname) {
   int status = PV_SUCCESS;
   assert(slownessFlag);
   const char * slownessLayerName = parent->parameters()->stringValue(name, paramname, false);
   if( slownessLayerName == NULL ) {
      status = PV_FAILURE;
      fprintf(stderr, "PoolingGenConn \"%s\": if slownessFlag is set, parameter \"%s\" must be set\n", name, paramname);
   }
   if( status == PV_SUCCESS ) {
      *l = parent->getLayerFromName(slownessLayerName);
      if( *l == NULL ) {
         status = PV_FAILURE;
         fprintf(stderr, "PoolingGenConn \"%s\": %s layer \"%s\" was not found\n", name, paramname, slownessLayerName);
      }
   }
   return status;
}

int PoolingGenConn::updateWeights(int axonID) {
    int nPre = preSynapticLayer()->getNumNeurons();
    int nx = preSynapticLayer()->getLayerLoc()->nx;
    int ny = preSynapticLayer()->getLayerLoc()->ny;
    int nf = preSynapticLayer()->getLayerLoc()->nf;
    int pad = preSynapticLayer()->getLayerLoc()->nb;
    for(int kPre=0; kPre<nPre;kPre++) {
        int kExt = kIndexExtended(kPre, nx, ny, nf, pad);

        size_t offset = getAPostOffset(kPre, axonID);
        pvdata_t preact = preSynapticLayer()->getCLayer()->activity->data[kExt];
        pvdata_t preact2 = getPre2()->getCLayer()->activity->data[kExt];
        PVPatch * weights = getWeights(kPre,axonID);
        int nyp = weights->ny;
        int nk = weights->nx * nfp;
        pvdata_t * postactRef = &(postSynapticLayer()->getCLayer()->activity->data[offset]);
        pvdata_t * postact2Ref = &(getPost2()->getCLayer()->activity->data[offset]);
        int sya = getPostNonextStrides()->sy;
        pvdata_t * wtpatch = get_wData(axonID, kExt); // weights->data;
        int syw = syp;
        int lineoffsetw = weights->offset;
        int lineoffseta = 0;
        for( int y=0; y<nyp; y++ ) {
            for( int k=0; k<nk; k++ ) {
                float w = wtpatch[lineoffsetw + k] + relaxation*(preact*postactRef[lineoffseta + k]+preact2*postact2Ref[lineoffseta + k]);
                wtpatch[lineoffsetw + k] = w;
            }
            lineoffsetw += syw;
            lineoffseta += sya;
        }
    }
    if( slownessFlag ) {
       for(int kPre=0; kPre<nPre;kPre++) {
           int kExt = kIndexExtended(kPre, nx, ny, nf, pad);

           size_t offset = getAPostOffset(kPre, axonID);
           pvdata_t preact = slownessPre->getCLayer()->activity->data[kExt];
           PVPatch * weights = getWeights(kPre,axonID);
           int nyp = weights->ny;
           int nk = weights->nx * nfp;
           pvdata_t * postactRef = &(slownessPost->getCLayer()->activity->data[offset]);
           int sya = getPostNonextStrides()->sy;
           pvdata_t * wtpatch = get_wData(axonID, kExt); // weights->data;
           int syw = syp;
           for( int y=0; y<nyp; y++ ) {
               int lineoffsetw = 0;
               int lineoffseta = 0;
               for( int k=0; k<nk; k++ ) {
                   float w = wtpatch[lineoffsetw + k] - relaxation*(preact*postactRef[lineoffseta + k]);
                   wtpatch[lineoffsetw + k] = w;
               }
               lineoffsetw += syw;
               lineoffseta += sya;
           }
       }
    }
    if( nonnegConstraintFlag ) {
       for(int kPatch=0; kPatch<getNumDataPatches();kPatch++) {
          // PVPatch * weights = this->getKernelPatch(axonID, kPatch);
          pvdata_t * wtpatch = get_wDataHead(axonID, kPatch); // weights->data;
           int nk = nxp * nfp;
           int syw = nxp*nfp;
           for( int y=0; y < nyp; y++ ) {
               int lineoffsetw = 0;
               for( int k=0; k<nk; k++ ) {
                   pvdata_t w = wtpatch[lineoffsetw + k];
                   if( w<0 ) {
                      wtpatch[lineoffsetw + k] = 0;
                   }
               }
               lineoffsetw += syw;
           }
       }
    }
    // normalizeWeights now called in KernelConn::updateState
    lastUpdateTime = parent->simulationTime();

    return PV_SUCCESS;
}

}  // end namespace PV
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qcontactmanager.h"
#include "qcontactmanager_p.h"
#include "qcontactmanagerengine.h"
#include "qcontactmanagerenginefactory.h"
#include "qcontactmanagerenginev2wrapper_p.h"

#include "qcontact_p.h"

#include "qcontactaction.h"
#include "qcontactactiondescriptor.h"
#ifdef QT_SIMULATOR
#include "qcontactsimulatorbackend_p.h"
#endif

#include <QSharedData>
#include <QtPlugin>
#include <QPluginLoader>

#include <QDebug>
#include <QDir>
#include <QFile>

#include <QApplication>

#if defined(Q_OS_SYMBIAN)
# include <f32file.h>
#endif

#include "qcontactmemorybackend_p.h"
#include "qcontactinvalidbackend_p.h"
#include "qmobilitypluginsearch.h"

QTM_BEGIN_NAMESPACE

/* Shared QContactManager stuff here, default engine stuff below */
QHash<QString, QContactManagerEngineFactory*> QContactManagerData::m_engines;
QSet<QContactManager*> QContactManagerData::m_aliveEngines;
QList<QContactActionManagerPlugin*> QContactManagerData::m_actionManagers;

bool QContactManagerData::m_discoveredStatic;
QStringList QContactManagerData::m_pluginPaths;

static void qContactsCleanEngines()
{
    // This is complicated by needing to remove any engines before we unload factories
    foreach(QContactManager* manager, QContactManagerData::m_aliveEngines) {
        // We don't delete the managers here, we just kill their engines
        // and replace it with an invalid engine (for safety :/)
        QContactManagerData* d = QContactManagerData::managerData(manager);
        delete d->m_engine;
        d->m_engine = new QContactInvalidEngine();
    }

    QList<QContactManagerEngineFactory*> factories = QContactManagerData::m_engines.values();

    for (int i=0; i < factories.count(); i++) {
        delete factories.at(i);
    }
    QContactManagerData::m_engines.clear();
    QContactManagerData::m_actionManagers.clear();
    QContactManagerData::m_aliveEngines.clear();
}

static int parameterValue(const QMap<QString, QString>& parameters, const char* key, int defaultValue)
{
    if (parameters.contains(QString::fromAscii(key))) {
        bool ok;
        int version = parameters.value(QString::fromAscii(key)).toInt(&ok);

        if (ok)
            return version;
    }
    return defaultValue;
}

void QContactManagerData::createEngine(const QString& managerName, const QMap<QString, QString>& parameters)
{
    m_engine = 0;

    QString builtManagerName = managerName.isEmpty() ? QContactManager::availableManagers().value(0) : managerName;
    if (builtManagerName == QLatin1String("memory")) {
        QContactManagerEngine* engine = QContactMemoryEngine::createMemoryEngine(parameters);
        m_engine = new QContactManagerEngineV2Wrapper(engine);
        m_signalSource = engine;
#ifdef QT_SIMULATOR
    } else if (builtManagerName == QLatin1String("simulator")) {
        QContactManagerEngine* engine = QContactSimulatorEngine::createSimulatorEngine(parameters);
        m_engine = new QContactManagerEngineV2Wrapper(engine);
        m_signalSource = engine;
#endif
    } else {
        int implementationVersion = parameterValue(parameters, QTCONTACTS_IMPLEMENTATION_VERSION_NAME, -1);

        bool found = false;
        bool loadedDynamic = false;

        /* First check static factories */
        loadStaticFactories();

        /* See if we got a fast hit */
        QList<QContactManagerEngineFactory*> factories = m_engines.values(builtManagerName);
        m_lastError = QContactManager::NoError;

        while(!found) {
            foreach (QContactManagerEngineFactory* f, factories) {
                QList<int> versions = f->supportedImplementationVersions();
                if (implementationVersion == -1 ||//no given implementation version required
                        versions.isEmpty() || //the manager engine factory does not report any version
                        versions.contains(implementationVersion)) {
                    QContactManagerEngine* engine = f->engine(parameters, &m_lastError);
                    // if it's a V2, use it
                    m_engine = qobject_cast<QContactManagerEngineV2*>(engine);
                    if (!m_engine && engine) {
                        // Nope, v1, so wrap it
                        m_engine = new QContactManagerEngineV2Wrapper(engine);
                        m_signalSource = engine;
                    } else {
                        m_signalSource = m_engine; // use the v2 engine directly
                    }
                    found = true;
                    break;
                }
            }

            // Break if found or if this is the second time through
            if (loadedDynamic || found)
                break;

            // otherwise load dynamic factories and reloop
            loadFactories();
            factories = m_engines.values(builtManagerName);
            loadedDynamic = true;
        }

        // XXX remove this
        // the engine factory could lie to us, so check the real implementation version
        if (m_engine && (implementationVersion != -1 && m_engine->managerVersion() != implementationVersion)) {
            m_lastError = QContactManager::VersionMismatchError;
            m_signalSource = m_engine = 0;
        }

        if (!m_engine) {
            if (m_lastError == QContactManager::NoError)
                m_lastError = QContactManager::DoesNotExistError;
            m_signalSource = m_engine = new QContactInvalidEngine();
        }
    }
}

void QContactManagerData::loadStaticFactories()
{
    if (!m_discoveredStatic) {
#if !defined QT_NO_DEBUG
        const bool showDebug = qgetenv("QT_DEBUG_PLUGINS").toInt() > 0;
#endif

        m_discoveredStatic = true;

        /* Clean stuff up at the end */
        qAddPostRoutine(qContactsCleanEngines);

        /* Loop over all the static plugins */
        QObjectList staticPlugins = QPluginLoader::staticInstances();
        for (int i=0; i < staticPlugins.count(); i++ ){
            QContactManagerEngineFactory *f = qobject_cast<QContactManagerEngineFactory*>(staticPlugins.at(i));
            if (f) {
                QString name = f->managerName();
#if !defined QT_NO_DEBUG
                if (showDebug)
                    qDebug() << "Static: found an engine plugin" << f << "with name" << name;
#endif
                if (name != QLatin1String("memory") && name != QLatin1String("invalid") && !name.isEmpty()) {
                    // we also need to ensure that we haven't already loaded this factory.
                    if (m_engines.keys().contains(name)) {
                        qWarning() << "Static contacts plugin" << name << "has the same name as a currently loaded plugin; ignored";
                    } else {
                        m_engines.insertMulti(name, f);
                    }
                } else {
                    qWarning() << "Static contacts plugin with reserved name" << name << "ignored";
                }
            }
        }
    }
}

/* Plugin loader */
void QContactManagerData::loadFactories()
{
#if !defined QT_NO_DEBUG
    const bool showDebug = qgetenv("QT_DEBUG_PLUGINS").toInt() > 0;
#endif

    // Always do this..
    loadStaticFactories();

    // But only load dynamic plugins when the paths change
    QStringList paths = QCoreApplication::libraryPaths();
#ifdef QTM_PLUGIN_PATH
    paths << QLatin1String(QTM_PLUGIN_PATH);
#endif

    if (paths != m_pluginPaths) {
        m_pluginPaths = paths;

        QStringList plugins = mobilityPlugins(QLatin1String("contacts"));

        /* Now discover the dynamic plugins */
        for (int i=0; i < plugins.count(); i++) {
            QPluginLoader qpl(plugins.at(i));

#if !defined QT_NO_DEBUG
            if (showDebug)
                qDebug() << "Loading plugin" << plugins.at(i);
#endif

            QContactManagerEngineFactory *f = qobject_cast<QContactManagerEngineFactory*>(qpl.instance());
            QContactActionManagerPlugin *m = qobject_cast<QContactActionManagerPlugin*>(qpl.instance());

            if (f) {
                QString name = f->managerName();
#if !defined QT_NO_DEBUG
                if (showDebug)
                    qDebug() << "Dynamic: found a contact engine plugin" << f << "with name" << name;
#endif
                if (name != QLatin1String("memory") && name != QLatin1String("invalid") && !name.isEmpty()) {
                    // we also need to ensure that we haven't already loaded this factory.
                    if (m_engines.keys().contains(name)) {
                        qWarning() << "Contacts plugin" << plugins.at(i) << "has the same name as currently loaded plugin" << name << "; ignored";
                    } else {
                        m_engines.insertMulti(name, f);
                    }
                } else {
                    qWarning() << "Contacts plugin" << plugins.at(i) << "with reserved name" << name << "ignored";
                }
            }

            if (m) {
                m_actionManagers.append(m);
            }

            /* Debugging */
#if !defined QT_NO_DEBUG
            if (showDebug && !f && !m) {
                qDebug() << "Unknown plugin:" << qpl.errorString();
                if (qpl.instance()) {
                    qDebug() << "[qobject:" << qpl.instance() << "]";
                }
            }
#endif
        }

        QStringList engineNames;
        foreach (QContactManagerEngineFactory* f, m_engines.values()) {
            QStringList versions;
            foreach (int v, f->supportedImplementationVersions()) {
                versions << QString::fromAscii("%1").arg(v);
            }
            engineNames << QString::fromAscii("%1[%2]").arg(f->managerName()).arg(versions.join(QString::fromAscii(",")));
        }
#if !defined QT_NO_DEBUG
        if (showDebug) {
            qDebug() << "Found engines:" << engineNames;
            qDebug() << "Found action engines:" << m_actionManagers;
        }
#endif
    }
}

// Observer stuff

void QContactManagerData::registerObserver(QContactManager* manager, QContactObserver* observer)
{
    if (!manager)
        return;

    QContactManagerData* d = QContactManagerData::get(manager);

    d->m_observerForContact.insert(observer->contactLocalId(), observer);

    // If this is the first observer, connect to the engine too
    if (d->m_observerForContact.size() == 1) {
        // This takes advantage of the manager connectNotify code
        QObject::connect(manager, SIGNAL(contactsChanged(QList<QContactLocalId>)),
                manager, SLOT(_q_contactsUpdated(QList<QContactLocalId>)));
        QObject::connect(manager, SIGNAL(contactsRemoved(QList<QContactLocalId>)),
                manager, SLOT(_q_contactsDeleted(QList<QContactLocalId>)));
    }
}

void QContactManagerData::unregisterObserver(QContactManager* manager, QContactObserver* observer)
{
    Q_ASSERT(manager);

    QContactManagerData* d = QContactManagerData::get(manager);

    QContactLocalId key = d->m_observerForContact.key(observer);
    if (key != 0) {
        d->m_observerForContact.remove(key, observer);

        // If there are now no more observers, disconnect from the engine
        if (d->m_observerForContact.size() == 0) {
            // This takes advantage of the manager disconnectNotify code
            QObject::disconnect(manager, SIGNAL(contactsChanged(QList<QContactLocalId>)),
                    manager, SLOT(_q_contactsUpdated(QList<QContactLocalId>)));
            QObject::disconnect(manager, SIGNAL(contactsRemoved(QList<QContactLocalId>)),
                    manager, SLOT(_q_contactsDeleted(QList<QContactLocalId>)));
        }
    }
}

void QContactManagerData::_q_contactsUpdated(const QList<QContactLocalId>& ids)
{
    foreach (QContactLocalId id, ids) {
        QList<QContactObserver*> observers = m_observerForContact.values(id);
        foreach (QContactObserver* observer, observers) {
            QMetaObject::invokeMethod(observer, "contactChanged");
        }
    }
}

void QContactManagerData::_q_contactsDeleted(const QList<QContactLocalId>& ids)
{
    foreach (QContactLocalId id, ids) {
        QList<QContactObserver*> observers = m_observerForContact.values(id);
        foreach (QContactObserver* observer, observers) {
            QMetaObject::invokeMethod(observer, "contactRemoved");
        }
    }
}

// trampolines for private classes
QContactManagerData* QContactManagerData::get(const QContactManager* manager)
{
    return manager->d;
}

QContactManagerEngineV2* QContactManagerData::engine(const QContactManager* manager)
{
    if (manager)
        return manager->d->m_engine;
    return 0;
}

QTM_END_NAMESPACE

<commit_msg>Fixing double delete segfault in qContactsCleanEngines<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qcontactmanager.h"
#include "qcontactmanager_p.h"
#include "qcontactmanagerengine.h"
#include "qcontactmanagerenginefactory.h"
#include "qcontactmanagerenginev2wrapper_p.h"

#include "qcontact_p.h"

#include "qcontactaction.h"
#include "qcontactactiondescriptor.h"
#ifdef QT_SIMULATOR
#include "qcontactsimulatorbackend_p.h"
#endif

#include <QSharedData>
#include <QtPlugin>
#include <QPluginLoader>
#include <QWeakPointer>

#include <QDebug>
#include <QDir>
#include <QFile>

#include <QApplication>

#if defined(Q_OS_SYMBIAN)
# include <f32file.h>
#endif

#include "qcontactmemorybackend_p.h"
#include "qcontactinvalidbackend_p.h"
#include "qmobilitypluginsearch.h"

QTM_BEGIN_NAMESPACE

/* Shared QContactManager stuff here, default engine stuff below */
QHash<QString, QContactManagerEngineFactory*> QContactManagerData::m_engines;
QSet<QContactManager*> QContactManagerData::m_aliveEngines;
QList<QContactActionManagerPlugin*> QContactManagerData::m_actionManagers;

bool QContactManagerData::m_discoveredStatic;
QStringList QContactManagerData::m_pluginPaths;

static void qContactsCleanEngines()
{
    // This is complicated by needing to remove any engines before we unload factories
    // guard pointers as one engine could be parent of another manager and cause doubledelete
    QList<QWeakPointer<QContactManager> > aliveManagers;
    foreach(QContactManager* manager, QContactManagerData::m_aliveEngines) {
        aliveManagers << QWeakPointer<QContactManager>(manager);
    }

    foreach(QWeakPointer<QContactManager> manager, aliveManagers) {
        if (not manager) {
            // deleting engine of one manager, could cause deleting next manager in list (aggregation case)
            continue;
        }
        // We don't delete the managers here, we just kill their engines
        // and replace it with an invalid engine (for safety :/)
        QContactManagerData* d = QContactManagerData::managerData(manager.data());

        delete d->m_engine;
        d->m_engine = new QContactInvalidEngine();
    }

    QList<QContactManagerEngineFactory*> factories = QContactManagerData::m_engines.values();

    for (int i=0; i < factories.count(); i++) {
        delete factories.at(i);
    }
    QContactManagerData::m_engines.clear();
    QContactManagerData::m_actionManagers.clear();
    QContactManagerData::m_aliveEngines.clear();
}

static int parameterValue(const QMap<QString, QString>& parameters, const char* key, int defaultValue)
{
    if (parameters.contains(QString::fromAscii(key))) {
        bool ok;
        int version = parameters.value(QString::fromAscii(key)).toInt(&ok);

        if (ok)
            return version;
    }
    return defaultValue;
}

void QContactManagerData::createEngine(const QString& managerName, const QMap<QString, QString>& parameters)
{
    m_engine = 0;

    QString builtManagerName = managerName.isEmpty() ? QContactManager::availableManagers().value(0) : managerName;
    if (builtManagerName == QLatin1String("memory")) {
        QContactManagerEngine* engine = QContactMemoryEngine::createMemoryEngine(parameters);
        m_engine = new QContactManagerEngineV2Wrapper(engine);
        m_signalSource = engine;
#ifdef QT_SIMULATOR
    } else if (builtManagerName == QLatin1String("simulator")) {
        QContactManagerEngine* engine = QContactSimulatorEngine::createSimulatorEngine(parameters);
        m_engine = new QContactManagerEngineV2Wrapper(engine);
        m_signalSource = engine;
#endif
    } else {
        int implementationVersion = parameterValue(parameters, QTCONTACTS_IMPLEMENTATION_VERSION_NAME, -1);

        bool found = false;
        bool loadedDynamic = false;

        /* First check static factories */
        loadStaticFactories();

        /* See if we got a fast hit */
        QList<QContactManagerEngineFactory*> factories = m_engines.values(builtManagerName);
        m_lastError = QContactManager::NoError;

        while(!found) {
            foreach (QContactManagerEngineFactory* f, factories) {
                QList<int> versions = f->supportedImplementationVersions();
                if (implementationVersion == -1 ||//no given implementation version required
                        versions.isEmpty() || //the manager engine factory does not report any version
                        versions.contains(implementationVersion)) {
                    QContactManagerEngine* engine = f->engine(parameters, &m_lastError);
                    // if it's a V2, use it
                    m_engine = qobject_cast<QContactManagerEngineV2*>(engine);
                    if (!m_engine && engine) {
                        // Nope, v1, so wrap it
                        m_engine = new QContactManagerEngineV2Wrapper(engine);
                        m_signalSource = engine;
                    } else {
                        m_signalSource = m_engine; // use the v2 engine directly
                    }
                    found = true;
                    break;
                }
            }

            // Break if found or if this is the second time through
            if (loadedDynamic || found)
                break;

            // otherwise load dynamic factories and reloop
            loadFactories();
            factories = m_engines.values(builtManagerName);
            loadedDynamic = true;
        }

        // XXX remove this
        // the engine factory could lie to us, so check the real implementation version
        if (m_engine && (implementationVersion != -1 && m_engine->managerVersion() != implementationVersion)) {
            m_lastError = QContactManager::VersionMismatchError;
            m_signalSource = m_engine = 0;
        }

        if (!m_engine) {
            if (m_lastError == QContactManager::NoError)
                m_lastError = QContactManager::DoesNotExistError;
            m_signalSource = m_engine = new QContactInvalidEngine();
        }
    }
}

void QContactManagerData::loadStaticFactories()
{
    if (!m_discoveredStatic) {
#if !defined QT_NO_DEBUG
        const bool showDebug = qgetenv("QT_DEBUG_PLUGINS").toInt() > 0;
#endif

        m_discoveredStatic = true;

        /* Clean stuff up at the end */
        qAddPostRoutine(qContactsCleanEngines);

        /* Loop over all the static plugins */
        QObjectList staticPlugins = QPluginLoader::staticInstances();
        for (int i=0; i < staticPlugins.count(); i++ ){
            QContactManagerEngineFactory *f = qobject_cast<QContactManagerEngineFactory*>(staticPlugins.at(i));
            if (f) {
                QString name = f->managerName();
#if !defined QT_NO_DEBUG
                if (showDebug)
                    qDebug() << "Static: found an engine plugin" << f << "with name" << name;
#endif
                if (name != QLatin1String("memory") && name != QLatin1String("invalid") && !name.isEmpty()) {
                    // we also need to ensure that we haven't already loaded this factory.
                    if (m_engines.keys().contains(name)) {
                        qWarning() << "Static contacts plugin" << name << "has the same name as a currently loaded plugin; ignored";
                    } else {
                        m_engines.insertMulti(name, f);
                    }
                } else {
                    qWarning() << "Static contacts plugin with reserved name" << name << "ignored";
                }
            }
        }
    }
}

/* Plugin loader */
void QContactManagerData::loadFactories()
{
#if !defined QT_NO_DEBUG
    const bool showDebug = qgetenv("QT_DEBUG_PLUGINS").toInt() > 0;
#endif

    // Always do this..
    loadStaticFactories();

    // But only load dynamic plugins when the paths change
    QStringList paths = QCoreApplication::libraryPaths();
#ifdef QTM_PLUGIN_PATH
    paths << QLatin1String(QTM_PLUGIN_PATH);
#endif

    if (paths != m_pluginPaths) {
        m_pluginPaths = paths;

        QStringList plugins = mobilityPlugins(QLatin1String("contacts"));

        /* Now discover the dynamic plugins */
        for (int i=0; i < plugins.count(); i++) {
            QPluginLoader qpl(plugins.at(i));

#if !defined QT_NO_DEBUG
            if (showDebug)
                qDebug() << "Loading plugin" << plugins.at(i);
#endif

            QContactManagerEngineFactory *f = qobject_cast<QContactManagerEngineFactory*>(qpl.instance());
            QContactActionManagerPlugin *m = qobject_cast<QContactActionManagerPlugin*>(qpl.instance());

            if (f) {
                QString name = f->managerName();
#if !defined QT_NO_DEBUG
                if (showDebug)
                    qDebug() << "Dynamic: found a contact engine plugin" << f << "with name" << name;
#endif
                if (name != QLatin1String("memory") && name != QLatin1String("invalid") && !name.isEmpty()) {
                    // we also need to ensure that we haven't already loaded this factory.
                    if (m_engines.keys().contains(name)) {
                        qWarning() << "Contacts plugin" << plugins.at(i) << "has the same name as currently loaded plugin" << name << "; ignored";
                    } else {
                        m_engines.insertMulti(name, f);
                    }
                } else {
                    qWarning() << "Contacts plugin" << plugins.at(i) << "with reserved name" << name << "ignored";
                }
            }

            if (m) {
                m_actionManagers.append(m);
            }

            /* Debugging */
#if !defined QT_NO_DEBUG
            if (showDebug && !f && !m) {
                qDebug() << "Unknown plugin:" << qpl.errorString();
                if (qpl.instance()) {
                    qDebug() << "[qobject:" << qpl.instance() << "]";
                }
            }
#endif
        }

        QStringList engineNames;
        foreach (QContactManagerEngineFactory* f, m_engines.values()) {
            QStringList versions;
            foreach (int v, f->supportedImplementationVersions()) {
                versions << QString::fromAscii("%1").arg(v);
            }
            engineNames << QString::fromAscii("%1[%2]").arg(f->managerName()).arg(versions.join(QString::fromAscii(",")));
        }
#if !defined QT_NO_DEBUG
        if (showDebug) {
            qDebug() << "Found engines:" << engineNames;
            qDebug() << "Found action engines:" << m_actionManagers;
        }
#endif
    }
}

// Observer stuff

void QContactManagerData::registerObserver(QContactManager* manager, QContactObserver* observer)
{
    if (!manager)
        return;

    QContactManagerData* d = QContactManagerData::get(manager);

    d->m_observerForContact.insert(observer->contactLocalId(), observer);

    // If this is the first observer, connect to the engine too
    if (d->m_observerForContact.size() == 1) {
        // This takes advantage of the manager connectNotify code
        QObject::connect(manager, SIGNAL(contactsChanged(QList<QContactLocalId>)),
                manager, SLOT(_q_contactsUpdated(QList<QContactLocalId>)));
        QObject::connect(manager, SIGNAL(contactsRemoved(QList<QContactLocalId>)),
                manager, SLOT(_q_contactsDeleted(QList<QContactLocalId>)));
    }
}

void QContactManagerData::unregisterObserver(QContactManager* manager, QContactObserver* observer)
{
    Q_ASSERT(manager);

    QContactManagerData* d = QContactManagerData::get(manager);

    QContactLocalId key = d->m_observerForContact.key(observer);
    if (key != 0) {
        d->m_observerForContact.remove(key, observer);

        // If there are now no more observers, disconnect from the engine
        if (d->m_observerForContact.size() == 0) {
            // This takes advantage of the manager disconnectNotify code
            QObject::disconnect(manager, SIGNAL(contactsChanged(QList<QContactLocalId>)),
                    manager, SLOT(_q_contactsUpdated(QList<QContactLocalId>)));
            QObject::disconnect(manager, SIGNAL(contactsRemoved(QList<QContactLocalId>)),
                    manager, SLOT(_q_contactsDeleted(QList<QContactLocalId>)));
        }
    }
}

void QContactManagerData::_q_contactsUpdated(const QList<QContactLocalId>& ids)
{
    foreach (QContactLocalId id, ids) {
        QList<QContactObserver*> observers = m_observerForContact.values(id);
        foreach (QContactObserver* observer, observers) {
            QMetaObject::invokeMethod(observer, "contactChanged");
        }
    }
}

void QContactManagerData::_q_contactsDeleted(const QList<QContactLocalId>& ids)
{
    foreach (QContactLocalId id, ids) {
        QList<QContactObserver*> observers = m_observerForContact.values(id);
        foreach (QContactObserver* observer, observers) {
            QMetaObject::invokeMethod(observer, "contactRemoved");
        }
    }
}

// trampolines for private classes
QContactManagerData* QContactManagerData::get(const QContactManager* manager)
{
    return manager->d;
}

QContactManagerEngineV2* QContactManagerData::engine(const QContactManager* manager)
{
    if (manager)
        return manager->d->m_engine;
    return 0;
}

QTM_END_NAMESPACE

<|endoftext|>


<commit_before>/*
 * ConnectedComponents.cpp
 *
 *  Created on: Dec 16, 2013
 *      Author: cls
 */

#include "ConnectedComponents.h"

#include <set>

namespace NetworKit {

ConnectedComponents::ConnectedComponents() {

}

ConnectedComponents::~ConnectedComponents() {

}

void ConnectedComponents::run(const Graph& G) {
	// calculate connected components by label propagation
	count z = G.numberOfNodes();
	this->component = std::vector<node>(z, none);

	G.parallelForNodes([&](node v){
		component[v] = v;
	});

	bool change = false;
	do {
		DEBUG("next iteration");
		change = false;
		G.parallelForNodes([&](node u) {
			G.forNeighborsOf(u, [&](node v) {
				if (component[v] < component[u]) {
					component[u] = component[v];
					change = true;
				}
			});
			// minimum neighboring label assigned
		});
	} while (change);
}

std::vector<index> ConnectedComponents::getComponentData() {
	return this->component;
}

std::map<index, count> ConnectedComponents::getComponentSizes() {
	std::map<index, count> componentSize;
	for (node u = 0; u < component.size(); ++u) {
		if (component[u] != none) {
			componentSize[component[u]] += 1;
		}
	}
	return componentSize;
}

std::vector<node> ConnectedComponents::getComponent(index label) {
	std::vector<node> nodesOfComponent;
	for (node u = 0; u < component.size(); ++u) {
		if (this->component[u] == label) {
			nodesOfComponent.push_back(u);
		}
	}
	return nodesOfComponent;
}

count ConnectedComponents::numberOfComponents() {
	count nc = 0;
	std::set<index> componentLabels;
	for (index i = 0; i < component.size(); ++i) {
		index c = component[i];
		if ((componentLabels.find(c) == componentLabels.end()) && (c != none)) { // label not encountered yet
			componentLabels.insert(c);
			nc++;
		}
	}
	return nc;
}

count ConnectedComponents::componentOfNode(node u) {
	assert (component[u] != none);
	return component[u];
}

}

<commit_msg>better load balancing for ConnectedComponents<commit_after>/*
 * ConnectedComponents.cpp
 *
 *  Created on: Dec 16, 2013
 *      Author: cls
 */

#include "ConnectedComponents.h"

#include <set>

namespace NetworKit {

ConnectedComponents::ConnectedComponents() {

}

ConnectedComponents::~ConnectedComponents() {

}

void ConnectedComponents::run(const Graph& G) {
	// calculate connected components by label propagation
	count z = G.numberOfNodes();
	this->component = std::vector<node>(z, none);

	G.parallelForNodes([&](node v){
		component[v] = v;
	});

	bool change = false;
	do {
		DEBUG("next iteration");
		change = false;
		G.balancedParallelForNodes([&](node u) {
			G.forNeighborsOf(u, [&](node v) {
				if (component[v] < component[u]) {
					component[u] = component[v];
					change = true;
				}
			});
			// minimum neighboring label assigned
		});
	} while (change);
}

std::vector<index> ConnectedComponents::getComponentData() {
	return this->component;
}

std::map<index, count> ConnectedComponents::getComponentSizes() {
	std::map<index, count> componentSize;
	for (node u = 0; u < component.size(); ++u) {
		if (component[u] != none) {
			componentSize[component[u]] += 1;
		}
	}
	return componentSize;
}

std::vector<node> ConnectedComponents::getComponent(index label) {
	std::vector<node> nodesOfComponent;
	for (node u = 0; u < component.size(); ++u) {
		if (this->component[u] == label) {
			nodesOfComponent.push_back(u);
		}
	}
	return nodesOfComponent;
}

count ConnectedComponents::numberOfComponents() {
	count nc = 0;
	std::set<index> componentLabels;
	for (index i = 0; i < component.size(); ++i) {
		index c = component[i];
		if ((componentLabels.find(c) == componentLabels.end()) && (c != none)) { // label not encountered yet
			componentLabels.insert(c);
			nc++;
		}
	}
	return nc;
}

count ConnectedComponents::componentOfNode(node u) {
	assert (component[u] != none);
	return component[u];
}

}

<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2009 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include "common.h"

/* interface header */
#include "bzfio.h"

/* system implementation headers */
#include <iostream>
#include <vector>
#include <string>
#include <stdarg.h>
#include <time.h>
#ifdef HAVE_UNISTD_H
#  include <unistd.h>
#endif
#ifdef __BEOS__
#  include <OS.h>
#endif
#if !defined(_WIN32)
#  include <sys/time.h>
#  include <sys/types.h>
#else /* !defined(_WIN32) */
#  include <mmsystem.h>
#endif

/** global used to control logging level across all applications */
int debugLevel = 0;

static bool doMicros = false;
static bool doTimestamp = false;

static int callProcDepth = 0;

//============================================================================//
//============================================================================//

struct LoggingProcPair {
  LoggingProcPair(LoggingProc p, void* d)
  : proc(p)
  , data(d)
  {}
  bool operator==(const LoggingProcPair& lpp) const {
    return (proc == lpp.proc) && (data == lpp.data);
  }
  LoggingProc proc;
  void*       data;
};
typedef std::vector<LoggingProcPair> LoggingProcVec;
static LoggingProcVec loggingProcs;

bool registerLoggingProc(LoggingProc proc, void* data)
{
  if (proc == NULL) {
    return false;
  }
  LoggingProcPair lpp(proc, data);
  for (size_t i = 0; i < loggingProcs.size(); i++) {
    if (lpp == loggingProcs[i]) {
      return false; // already registered
    }
  }
  loggingProcs.push_back(lpp);
  return true;
}

bool unregisterLoggingProc(LoggingProc proc, void* data)
{
  if (callProcDepth != 0) {
    logDebugMessage(0, "error: unregisterLoggingProc() used in a LoggingProc");
    return false;
  }
  LoggingProcPair lpp(proc, data);
  for (size_t i = 0; i < loggingProcs.size(); i++) {
    if (lpp == loggingProcs[i]) {
      loggingProcs.erase(loggingProcs.begin() + i);
      return true;
    }
  }
  return false;
}

static void callProcs(int level, const std::string& msg)
{
  callProcDepth++;
  for (size_t i = 0; i < loggingProcs.size(); i++) {
    const LoggingProcPair& lpp = loggingProcs[i];
    lpp.proc(level, msg, lpp.data);
  }
  callProcDepth--;
}

//============================================================================//
//============================================================================//

void setDebugTimestamp(bool enable, bool micros)
{
#ifdef _WIN32
  micros = false;
#endif
  doTimestamp = enable;
  doMicros = micros;
}

static const int tsBufferSize = 26;

static char *timestamp(char *buf, bool micros)
{
  struct tm *tm;
  if (micros) {
#if !defined(_WIN32)
    struct timeval tv;
    gettimeofday(&tv, NULL);
    tm = localtime((const time_t *)&tv.tv_sec);
    snprintf(buf, tsBufferSize, "%04d-%02d-%02d %02d:%02d:%02ld.%06ld: ",
             tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
             tm->tm_hour, tm->tm_min, (long)tm->tm_sec, (long)tv.tv_usec);
#endif
  } else {
    time_t tt;
    time(&tt);
    tm = localtime(&tt);
    snprintf(buf, tsBufferSize, "%04d-%02d-%02d %02d:%02d:%02d: ",
             tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
             tm->tm_hour, tm->tm_min, tm->tm_sec);
  }
  return buf;
}

//============================================================================//
//============================================================================//

static void realLogDebugMessage(int level, const char* text)
{
  if ((debugLevel >= level) || (level == 0)) {
#if defined(_MSC_VER)
    if (doTimestamp) {
      char tsbuf[tsBufferSize] = { 0 };
      W32_DEBUG_TRACE(timestamp(tsbuf, false));
    }
    W32_DEBUG_TRACE(text);
#else
    if (doTimestamp) {
      char tsbuf[tsBufferSize] = { 0 };
      std::cout << timestamp(tsbuf, doMicros);
    }
    std::cout << text;
    fflush(stdout);
#endif

    callProcs(level, text);
  }
}

void logDebugMessageArgs(int level, const char* fmt, va_list ap)
{
  char buffer[8192] = { 0 };

  if (!fmt) {
    return;
  }

  vsnprintf(buffer, sizeof(buffer), fmt, ap);

  realLogDebugMessage(level, buffer);
}

void logDebugMessage(int level, const char* fmt, ...)
{
  va_list ap;
  va_start(ap, fmt);
  logDebugMessageArgs(level, fmt, ap);
  va_end(ap);
}

void logDebugMessage(int level, const std::string &text)
{
  if (text.empty()) {
    return;
  }
  realLogDebugMessage(level, text.c_str());
}

//============================================================================//
//============================================================================//

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>bzfs: Fix timestamp buffer size so -ts micros output fits<commit_after>/* bzflag
 * Copyright (c) 1993 - 2009 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include "common.h"

/* interface header */
#include "bzfio.h"

/* system implementation headers */
#include <iostream>
#include <vector>
#include <string>
#include <stdarg.h>
#include <time.h>
#ifdef HAVE_UNISTD_H
#  include <unistd.h>
#endif
#ifdef __BEOS__
#  include <OS.h>
#endif
#if !defined(_WIN32)
#  include <sys/time.h>
#  include <sys/types.h>
#else /* !defined(_WIN32) */
#  include <mmsystem.h>
#endif

/** global used to control logging level across all applications */
int debugLevel = 0;

static bool doMicros = false;
static bool doTimestamp = false;

static int callProcDepth = 0;

//============================================================================//
//============================================================================//

struct LoggingProcPair {
  LoggingProcPair(LoggingProc p, void* d)
  : proc(p)
  , data(d)
  {}
  bool operator==(const LoggingProcPair& lpp) const {
    return (proc == lpp.proc) && (data == lpp.data);
  }
  LoggingProc proc;
  void*       data;
};
typedef std::vector<LoggingProcPair> LoggingProcVec;
static LoggingProcVec loggingProcs;

bool registerLoggingProc(LoggingProc proc, void* data)
{
  if (proc == NULL) {
    return false;
  }
  LoggingProcPair lpp(proc, data);
  for (size_t i = 0; i < loggingProcs.size(); i++) {
    if (lpp == loggingProcs[i]) {
      return false; // already registered
    }
  }
  loggingProcs.push_back(lpp);
  return true;
}

bool unregisterLoggingProc(LoggingProc proc, void* data)
{
  if (callProcDepth != 0) {
    logDebugMessage(0, "error: unregisterLoggingProc() used in a LoggingProc");
    return false;
  }
  LoggingProcPair lpp(proc, data);
  for (size_t i = 0; i < loggingProcs.size(); i++) {
    if (lpp == loggingProcs[i]) {
      loggingProcs.erase(loggingProcs.begin() + i);
      return true;
    }
  }
  return false;
}

static void callProcs(int level, const std::string& msg)
{
  callProcDepth++;
  for (size_t i = 0; i < loggingProcs.size(); i++) {
    const LoggingProcPair& lpp = loggingProcs[i];
    lpp.proc(level, msg, lpp.data);
  }
  callProcDepth--;
}

//============================================================================//
//============================================================================//

void setDebugTimestamp(bool enable, bool micros)
{
#ifdef _WIN32
  micros = false;
#endif
  doTimestamp = enable;
  doMicros = micros;
}

static const int tsBufferSize = 29;

static char *timestamp(char *buf, bool micros)
{
  struct tm *tm;
  if (micros) {
#if !defined(_WIN32)
    struct timeval tv;
    gettimeofday(&tv, NULL);
    tm = localtime((const time_t *)&tv.tv_sec);
    snprintf(buf, tsBufferSize, "%04d-%02d-%02d %02d:%02d:%02ld.%06ld: ",
             tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
             tm->tm_hour, tm->tm_min, (long)tm->tm_sec, (long)tv.tv_usec);
#endif
  } else {
    time_t tt;
    time(&tt);
    tm = localtime(&tt);
    snprintf(buf, tsBufferSize, "%04d-%02d-%02d %02d:%02d:%02d: ",
             tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
             tm->tm_hour, tm->tm_min, tm->tm_sec);
  }
  return buf;
}

//============================================================================//
//============================================================================//

static void realLogDebugMessage(int level, const char* text)
{
  if ((debugLevel >= level) || (level == 0)) {
#if defined(_MSC_VER)
    if (doTimestamp) {
      char tsbuf[tsBufferSize] = { 0 };
      W32_DEBUG_TRACE(timestamp(tsbuf, false));
    }
    W32_DEBUG_TRACE(text);
#else
    if (doTimestamp) {
      char tsbuf[tsBufferSize] = { 0 };
      std::cout << timestamp(tsbuf, doMicros);
    }
    std::cout << text;
    fflush(stdout);
#endif

    callProcs(level, text);
  }
}

void logDebugMessageArgs(int level, const char* fmt, va_list ap)
{
  char buffer[8192] = { 0 };

  if (!fmt) {
    return;
  }

  vsnprintf(buffer, sizeof(buffer), fmt, ap);

  realLogDebugMessage(level, buffer);
}

void logDebugMessage(int level, const char* fmt, ...)
{
  va_list ap;
  va_start(ap, fmt);
  logDebugMessageArgs(level, fmt, ap);
  va_end(ap);
}

void logDebugMessage(int level, const std::string &text)
{
  if (text.empty()) {
    return;
  }
  realLogDebugMessage(level, text.c_str());
}

//============================================================================//
//============================================================================//

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>/*!
 * \author ddubois
 * \date 28-Apr-18.
 */

#ifndef NOVA_RENDERER_FRAMEBUFFER_MANAGER_H
#define NOVA_RENDERER_FRAMEBUFFER_MANAGER_H

#include <cstdint>
#include <glm/glm.hpp>
#include <vector>
#include <vulkan/vulkan.h>
#include "../../util/utils.hpp"

namespace nova::renderer {
    class vulkan_render_engine;

    NOVA_EXCEPTION(swapchain_creation_failed);
    NOVA_EXCEPTION(present_failed);

    /*!
     * \brief Deals with the swapchain, yo
     *
     * Methods to get he next swapchain image and whatnot are found here
     *
     * You can even get the framebuffer constructed from the current swapchain. Wow!
     */
    class swapchain_manager {
    public:
        swapchain_manager(uint32_t num_swapchain_images,
                          vulkan_render_engine& render_engine,
                          glm::ivec2 window_dimensions,
                          const std::vector<VkPresentModeKHR>& present_modes);

        void present_current_image(VkSemaphore wait_semaphores) const;

        /*!
         * \brief Acquires the next image in the swapchain, signalling the provided semaphore when the image is ready
         * to be rendered to
         *
         * \param image_acquire_semaphore The semaphore to signal when the image is ready to be rendered to
         */
        void acquire_next_swapchain_image(VkSemaphore image_acquire_semaphore);

        void set_current_layout(VkImageLayout new_layout);

        VkFramebuffer get_current_framebuffer();
        VkFence get_current_frame_fence();

        VkImage get_current_image();
        VkImageLayout get_current_layout();
        [[nodiscard]] VkExtent2D get_swapchain_extent() const;
        [[nodiscard]] VkFormat get_swapchain_format() const;

        // I've had a lot of bugs with RAII so here's an explicit cleanup method
        void deinit();

        [[nodiscard]] uint32_t get_current_index() const;
        [[nodiscard]] uint32_t get_num_images() const;

    private:
        vulkan_render_engine& render_engine;

        VkSwapchainKHR swapchain{};
        VkExtent2D swapchain_extent;
        VkPresentModeKHR present_mode;
        VkFormat swapchain_format;

        std::vector<VkFramebuffer> framebuffers;
        std::vector<VkImageView> swapchain_image_views;
        std::vector<VkImage> swapchain_images;
        std::vector<VkImageLayout> swapchain_image_layouts;
        std::vector<VkFence> fences;

        uint32_t num_swapchain_images;
        uint32_t cur_swapchain_index = 0;

        static VkSurfaceFormatKHR choose_surface_format(const std::vector<VkSurfaceFormatKHR>& formats);

        static VkPresentModeKHR choose_present_mode(const std::vector<VkPresentModeKHR>& modes);

        static VkExtent2D choose_surface_extent(const VkSurfaceCapabilitiesKHR& caps, const glm::ivec2& window_dimensions);

        void transition_swapchain_images_into_correct_layout(const std::vector<VkImage>& images) const;
    };
} // namespace nova::renderer

#endif // NOVA_RENDERER_FRAMEBUFFER_MANAGER_H<commit_msg>Real format<commit_after>/*!
 * \author ddubois
 * \date 28-Apr-18.
 */

#ifndef NOVA_RENDERER_FRAMEBUFFER_MANAGER_H
#define NOVA_RENDERER_FRAMEBUFFER_MANAGER_H

#include <cstdint>
#include <glm/glm.hpp>
#include <vector>
#include <vulkan/vulkan.h>
#include "../../util/utils.hpp"

namespace nova::renderer {
    class vulkan_render_engine;

    NOVA_EXCEPTION(swapchain_creation_failed);
    NOVA_EXCEPTION(present_failed);

    /*!
     * \brief Deals with the swapchain, yo
     *
     * Methods to get he next swapchain image and whatnot are found here
     *
     * You can even get the framebuffer constructed from the current swapchain. Wow!
     */
    class swapchain_manager {
    public:
        swapchain_manager(uint32_t num_swapchain_images,
                          vulkan_render_engine& render_engine,
                          glm::ivec2 window_dimensions,
                          const std::vector<VkPresentModeKHR>& present_modes);

        void present_current_image(VkSemaphore wait_semaphores) const;

        /*!
         * \brief Acquires the next image in the swapchain, signalling the provided semaphore when the image is ready
         * to be rendered to
         *
         * \param image_acquire_semaphore The semaphore to signal when the image is ready to be rendered to
         */
        void acquire_next_swapchain_image(VkSemaphore image_acquire_semaphore);

        void set_current_layout(VkImageLayout new_layout);

        VkFramebuffer get_current_framebuffer();
        VkFence get_current_frame_fence();

        VkImage get_current_image();
        VkImageLayout get_current_layout();
        [[nodiscard]] VkExtent2D get_swapchain_extent() const;
        [[nodiscard]] VkFormat get_swapchain_format() const;

        // I've had a lot of bugs with RAII so here's an explicit cleanup method
        void deinit();

        [[nodiscard]] uint32_t get_current_index() const;
        [[nodiscard]] uint32_t get_num_images() const;

    private:
        vulkan_render_engine& render_engine;

        VkSwapchainKHR swapchain{};
        VkExtent2D swapchain_extent;
        VkPresentModeKHR present_mode;
        VkFormat swapchain_format;

        std::vector<VkFramebuffer> framebuffers;
        std::vector<VkImageView> swapchain_image_views;
        std::vector<VkImage> swapchain_images;
        std::vector<VkImageLayout> swapchain_image_layouts;
        std::vector<VkFence> fences;

        uint32_t num_swapchain_images;
        uint32_t cur_swapchain_index = 0;

        static VkSurfaceFormatKHR choose_surface_format(const std::vector<VkSurfaceFormatKHR>& formats);

        static VkPresentModeKHR choose_present_mode(const std::vector<VkPresentModeKHR>& modes);

        static VkExtent2D choose_surface_extent(const VkSurfaceCapabilitiesKHR& caps, const glm::ivec2& window_dimensions);

        void transition_swapchain_images_into_correct_layout(const std::vector<VkImage>& images) const;
    };
} // namespace nova::renderer

#endif // NOVA_RENDERER_FRAMEBUFFER_MANAGER_H<|endoftext|>


<commit_before>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "ConstantIC.h"
#include "libmesh/point.h"

template<>
InputParameters validParams<ConstantIC>()
{
  InputParameters params = validParams<InitialCondition>();
  params.set<Real>("value") = 0.0;
  return params;
}

ConstantIC::ConstantIC(const std::string & name, InputParameters parameters) :
    InitialCondition(name, parameters),
    _value(getParam<Real>("value"))
{
}

Real
ConstantIC::value(const Point & /*p*/)
{
  return _value;
}

<commit_msg>Fixing ConstantIC's input parameters (refs #2300)<commit_after>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "ConstantIC.h"
#include "libmesh/point.h"

template<>
InputParameters validParams<ConstantIC>()
{
  InputParameters params = validParams<InitialCondition>();
  params.addRequiredParam<Real>("value", "The value to be set in IC");
  return params;
}

ConstantIC::ConstantIC(const std::string & name, InputParameters parameters) :
    InitialCondition(name, parameters),
    _value(getParam<Real>("value"))
{
}

Real
ConstantIC::value(const Point & /*p*/)
{
  return _value;
}

<|endoftext|>