Example #1
0
void InteractionProperty::initialize(XML::Block& X) { //<interaction> son
    ITYPE = X["ITYPE"].getInteger();
    VTYPE = X["VTYPE"].getInteger();
    NBODY = X["NBODY"].getInteger();
    EBASE = X["EBASE"].getDouble();
    STYPE.init( 1, NBODY);
    STYPE.set_all(STYPE::UNDEF);
    VertexDensity.init( NBODY, NXMAX, ARRAY::EOL);
    VertexDensity.set_all(0.0);
    AverageInterval.init( NBODY, NXMAX, ARRAY::EOL);
    AverageInterval.set_all(-1.0);

    for (int i=0; i<X.NumberOfBlocks(); i++) {
        XML::Block& B = X[i];
        if (B.getName() == "VertexDensity") {
            int*x = new int[NBODY]; //edit sakakura
            //    int x[NBODY];
            for (int ii=0; ii<NBODY; ii++) {
                x[ii] = B.getInteger(ii);
            }
            double d = B.getDouble(NBODY);
            // VertexDensity   val[n] = d    を格納(n:1-n)
            // AverageInterval val[n] = 1/d  を格納(n:1-n)
            VertexDensity(x) = d; //x[0],x[1]分が処理される return C* val[id]
            AverageInterval(x) = 1.0/d;
            delete []x;
        }
    }
    //  Numberofblocksは/Interaction の行数

}
Example #2
0
 static void copyFromUtf8(Array& arr, uint8_t const* data)
 {
     if (data) {
         size_t user_len = UTF8Len(data);
         arr.init(user_len * 2);
         UTF8toUTF16({data, strlen(char_ptr_cast(data))}, arr.get_data(), user_len * 2);
     }
     else {
         arr.init(0);
     }
 }
Example #3
0
static void test_non_pod() {
    Array<Test> array;

    const size_t initial_capacity = 10, grow_capacity = 6, alignment = 4;
    UAllocTraits_t traits = {0};
    MBED_HOSTTEST_ASSERT(array.init(initial_capacity, grow_capacity, traits, alignment));

    // Just fill the first part of the array and verify
    unsigned idx;
    for (idx = 0; idx < initial_capacity; idx ++) {
        array.push_back(Test(idx, 'a'));
    }
    for (idx = 0; idx < initial_capacity; idx ++) {
        MBED_HOSTTEST_ASSERT(array[idx] == Test(idx, 'a'));
    }

    // Now override what we wrote with different data
    for (idx = 0; idx < initial_capacity; idx ++) {
        array[idx] = Test(idx, 'b');
    }
    for (idx = 0; idx < initial_capacity; idx ++) {
        const Test& t = array[idx];
        MBED_HOSTTEST_ASSERT(t == Test(idx, 'b'));
    }

    // Pop the last element from array (checks if destructor is called)
    array.pop_back();
   
    MBED_HOSTTEST_ASSERT(array.get_num_elements() == initial_capacity - 1);
    MBED_HOSTTEST_ASSERT(array.get_num_zones() == 1);
}
Example #4
0
void Algorithm::read() {

    //  if (DEBUG) printf("Algorithm::read> Start.\n");

    NSTYPE = X["General"]["NSTYPE"].getInteger(); //1 []operator
    NITYPE = X["General"]["NITYPE"].getInteger(); //1
    NVTYPE = X["General"]["NVTYPE"].getInteger(); //2
    NXMAX  = X["General"]["NXMAX" ].getInteger(); //2
    WDIAG  = X["General"]["WDIAG" ].getDouble(); // 0.25

    SPROP.init(1,NSTYPE); //1,SiteProperty
    IPROP.init(1,NITYPE); //1,InteractionProperty
    VPROP.init(1,NVTYPE); //2,VertexProperty

    for (int i=0; i<NITYPE; i++) { //1 IPROP(i) : return val[i]
        IPROP(i).NXMAX = NXMAX;
    }

    for (int i=0; i<NVTYPE; i++) { //2
        VPROP(i).NXMAX  = NXMAX;
    }

    for (int i=0; i<X.NumberOfBlocks(); i++) { //X.numberofblocks=6
        XML::Block& B = X[i];
        const string& name = B.getName();

        if ( name == "Site" ) {
            int id = B["STYPE"].getInteger(); //id=0
            SPROP(id).initialize(B); //463行目 この時点でSitePropertyClass set完了
            //SPROP(0) は、SiteProperty& val[0]を返す。
        }

        if ( name == "Interaction" ) {
            int id = B["ITYPE"].getInteger();//id=0
            IPROP(id).initialize(B);//son
        }

        if ( name == "Vertex" ) { //riyo
            int id = B["VTYPE"].getInteger(); //id=0,1
            // -- edit sakakura --
            VPROP(id).initialize(B,MXNIC1);//mayu
            //    VPROP(id).initialize(B);//mayu
            // -- edit sakakura --

        }
    }
}
static bool js_cocos2dx_CCControl_addTargetWithActionForControlEvents(JSContext *cx, uint32_t argc, jsval *vp)
{
    jsval *argv = JS_ARGV(cx, vp);
    JSObject *obj = JS_THIS_OBJECT(cx, vp);
    js_proxy_t *proxy = jsb_get_js_proxy(obj);
    cocos2d::extension::Control* cobj = (cocos2d::extension::Control *)(proxy ? proxy->ptr : NULL);
    JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object");
    
    bool ok = true;
    if (argc == 3)
    {
        JSObject* jsDelegate = JSVAL_TO_OBJECT(argv[0]);
        JSObject* jsFunc = JSVAL_TO_OBJECT(argv[1]);
        Control::EventType arg2;
        ok &= jsval_to_int32(cx, argv[2], (int32_t *)&arg2);
        JSB_PRECONDITION2(ok, cx, false, "Error processing control event");
        
        // Check whether the target already exists.
        auto range = JSB_ControlButtonTarget::_jsNativeTargetMap.equal_range(jsDelegate);
        for (auto it = range.first; it != range.second; ++it)
        {
            if (it->second->_jsFunc == jsFunc && arg2 == it->second->_type)
            {
                // Return true directly.
                JS_SET_RVAL(cx, vp, JSVAL_VOID);
                return true;
            }
        }
        
        // save the delegate
        JSB_ControlButtonTarget* nativeDelegate = new JSB_ControlButtonTarget();
        
        nativeDelegate->setJSTarget(jsDelegate);
        nativeDelegate->setJSAction(jsFunc);
        nativeDelegate->setEventType(arg2);

        Array* nativeDelegateArray = static_cast<Array*>(cobj->getUserObject());
        if (nullptr == nativeDelegateArray)
        {
            nativeDelegateArray = new Array();
            nativeDelegateArray->init();
            cobj->setUserObject(nativeDelegateArray);  // The reference of nativeDelegateArray is added to 2
            nativeDelegateArray->release(); // Release nativeDelegateArray to make the reference to 1
        }
        
        nativeDelegateArray->addObject(nativeDelegate); // The reference of nativeDelegate is added to 2
        nativeDelegate->release(); // Release nativeDelegate to make the reference to 1
        
        cobj->addTargetWithActionForControlEvents(nativeDelegate, cccontrol_selector(JSB_ControlButtonTarget::onEvent), arg2);
        
        JSB_ControlButtonTarget::_jsNativeTargetMap.insert(std::make_pair(jsDelegate, nativeDelegate));
        
        JS_SET_RVAL(cx, vp, JSVAL_VOID);
        
        return true;
    }
    JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 3);
    return false;
}
Example #6
0
//use the layout information in the umlgraph to find nodes in
//unconnected active parts of a CC that can be connected without
//crossings in the given embedding
void PlanRepInc::getExtAdjs(List<adjEntry> & /* extAdjs */)
{
	//in order not to change the current CC initialization,
	//we construct a copy of the active parts (one by one)
	//and use the layout information to compute a external
	//face for that part. An (original) adjEntry on this face
	//is then inserted into the extAdjs list.

	//derive the unconnected parts by a run through the current
	//copy
	//compute connected component of current CC

	NodeArray<int> component(*this);
	int numPartialCC = connectedComponents(*this, component);
	EdgeArray<edge> copyEdge;//copy edges in partial CC copy
	//now we compute a copy for every CC
	//initialize an array of lists of nodes contained in a CC
	Array<List<node> >  nodesInPartialCC;
	nodesInPartialCC.init(numPartialCC);

	for(node v : nodes)
		nodesInPartialCC[component[v]].pushBack(v);

	int i = 0;
	for (i = 0; i < numPartialCC; i++)
	{
		List<node> &theNodes = nodesInPartialCC[i];
		GraphCopy GC;
		GC.createEmpty(*this);
		GC.initByNodes(theNodes, copyEdge);
		//now we derive an outer face of GC by using the
		//layout information on it's original


		//TODO: Insert the bend points into the copy


		//CombinatorialEmbedding E(GC);

		//run through the faces and compute angles to
		//derive outer face
		//we dont care about the original structure of
		//the graph, i.e., if crossings are inserted aso
		//we only take the given partial CC and its layout
		//adjEntry extAdj = getExtAdj(GC, E);

		//for(node v : GC.nodes)
		//{
		//
		//}
	}//for


}//getextadj
Example #7
0
// ----------------------------------------------------------------------------
int main(int argc, char** argv) {
  DBG("[Lesson 2]: Iterators 4");

  int values[] = {5, 8, -9, 17, 4, 2, -3, 0, 11, 6};
  size_t size = sizeof(values) / sizeof(values[0]);

  Array array;
  array.init(values, size);
  array.print();

  DBG("[Lesson 2]: Iterators 4 [END]");
}
Example #8
0
void PivotMDS::getPivotDistanceMatrix(
	const GraphAttributes& GA,
	Array<Array<double> >& pivDistMatrix)
{
	const Graph& G = GA.constGraph();
	const int n = G.numberOfNodes();

	// lower the number of pivots if necessary
	int numberOfPivots = min(n, m_numberOfPivots);
	// number of pivots times n matrix used to store the graph distances
	pivDistMatrix.init(numberOfPivots);
	for (int i = 0; i < numberOfPivots; i++) {
		pivDistMatrix[i].init(n);
	}
	// edges costs array
	EdgeArray<double> edgeCosts;
	bool hasEdgeCosts = false;
	// already checked whether this attribute exists or not (see call method)
	if (m_hasEdgeCostsAttribute) {
		edgeCosts.init(G);
		for(edge e : G.edges)
		{
			edgeCosts[e] = GA.doubleWeight(e);
		}
		hasEdgeCosts = true;
	}
	// used for min-max strategy
	NodeArray<double> minDistances(G, std::numeric_limits<double>::infinity());
	NodeArray<double> shortestPathSingleSource(G);
	// the current pivot node
	node pivNode = G.firstNode();
	for (int i = 0; i < numberOfPivots; i++) {
		// get the shortest path from the currently processed pivot node to
		// all other nodes in the graph
		shortestPathSingleSource.fill(std::numeric_limits<double>::infinity());
		if (hasEdgeCosts) {
			dijkstra_SPSS(pivNode, G, shortestPathSingleSource, edgeCosts);
		} else {
			bfs_SPSS(pivNode, G, shortestPathSingleSource, m_edgeCosts);
		}
		copySPSS(pivDistMatrix[i], shortestPathSingleSource);
		// update the pivot and the minDistances array ... to ensure the
		// correctness set minDistance of the pivot node to zero
		minDistances[pivNode] = 0;
		for(node v : G.nodes)
		{
			minDistances[v] = min(minDistances[v], shortestPathSingleSource[v]);
			if (minDistances[v] > minDistances[pivNode]) {
				pivNode = v;
			}
		}
	}
}
Example #9
0
void VertexProperty::initialize( XML::Block& X,int mx) {//<vertex> //mayu
    VTYPE  = X["VTYPE"].getInteger();
    VCAT   = X["VCATEGORY"].getInteger();
    NBODY  = X["NBODY"].getInteger();
    NIC    = X["NumberOfInitialConfigurations"].getInteger();
    NLEG = 2 * NBODY;

    STYPE.init(1,NLEG);//array(int) STYPE //size 2,4
    STYPE.set_all(STYPE::UNDEF); //val[i]に(size()個分)-1をセット

    StateCode.init(NLEG,NXMAX,ARRAY::EOL); //array(int) StateCode -1をセット
    StateCode.set_all(STATE::UNDEF); //2^2,4^2

    SCNK.init(NBODY,NXMAX,ARRAY::EOL); //array(int) scnk
    SCNK.set_all(STATE::UNDEF); //-1 //size=2,4

    NST = StateCode.size(); //4,16
    _IC.init(3,NST,NLEG,NXMAX); //index用の数値用意[4,2,2],[16,4,2]
    _IC.set_all(0); //size 16,128

    // === edit sakakura ===
    //  if ( RUNTYPE == 1 ) {
    int id = X["VTYPE"].getInteger(); //id=0,1

    if (id == 0) {
        IC.init(1,NIC);
    } else {
        MIC = NIC;

        if (mx > NIC)MIC=mx;
        IC.init(1,MIC);
    }
    //   }
    // === edit sakakura ===

    int ic = 0;
    for (int i=0; i<X.NumberOfBlocks(); i++) { //2番目のtag
        XML::Block& B = X[i];
        if ( B.getName() == "InitialConfiguration" ) {
            IC[ic].setID(ic);
            IC[ic].NLEG = NLEG;
            IC[ic].initialize( B );
            ic++;
        }
    }

    // == edit sakakura ==
    if (id==1) {
        for ( int i=NIC; i<MIC; i++) {
            IC[i].setID(i);
            IC[i].NLEG = NLEG;//NLEG;
            IC[i].initialize(); //mai
        }
    }
    // == edit sakakura ==

}
Example #10
0
Array* Array::create()
{
    Array* pArray = new Array();

    if (pArray && pArray->init())
    {
        pArray->autorelease();
    }
    else
    {
        CC_SAFE_DELETE(pArray);
    }
    
    return pArray;
}
Example #11
0
Array* Array::create()
{
    Array* array = new Array();

    if (array && array->init())
    {
        array->autorelease();
    }
    else
    {
        CC_SAFE_DELETE(array);
    }

    return array;
}
Example #12
0
void VertexInitialConfiguration::initialize() {//<initialconfig>

    //printf("VertexInitialConfiguration::initialize> Start.\n");

    if (NLEG == 0) {
        printf("VertexInitialConfiguration::read> Error.\n");
        printf(" ...  NLEG has not been set.\n");
        exit(0);
    }

    State = new int [NLEG];

    NCH  = 4;  //X["NumberOfChannels"].getInteger();
    CH.init("VCH",1,NCH);

}
int BigqueryReader::get_bigquery_two_equal_cycle_col2(uint64_t prefix, ValueRule& rule, Bigquery& query, Array& result)
{
  int err = 0;
  char value[32];
  int64_t row_num = rule.get_row_num();
  int64_t start_val = 0;
  int64_t step = 0;
  int64_t size_cycle = 0;
  int64_t num_cycles = 0;
  int64_t equal_val = 0;

  // select sum(col1), count(col1), sum(col1) / count(col1), col2 from
  // bigquery_test group by col1 order by col1;
  rule.get_cycle_rule(0, start_val, step, size_cycle, num_cycles);
  rule.get_equal_rule(1, equal_val);
  assert(size_cycle * num_cycles == row_num);

  query.set_table_name(BIGQUERY_TABLE);
  query.add_select_column("sum(col1)");
  query.add_select_column("count(col1)");
  query.add_select_column("min(col1)");
  query.add_select_column("max(col1)");
  query.add_select_column("sum(col1) / count(col1)");
  query.add_groupby_column("col1");
  query.add_orderby_column("col1");
  query.add_filter("prefix", Bigquery::FILTER_EQ, prefix);
  query.add_filter("suffix", Bigquery::FILTER_LT, row_num);

  err = result.init(size_cycle, 5);
  if (0 == err)
  {
    for (int64_t i = 0; i < size_cycle; ++i)
    {
      sprintf(value, "%ld", (start_val + i * step) * num_cycles);
      result.set_value(i, 0, value, Array::INT_TYPE);
      sprintf(value, "%ld", num_cycles);
      result.set_value(i, 1, value, Array::INT_TYPE);
      sprintf(value, "%ld", start_val + i * step);
      result.set_value(i, 2, value, Array::INT_TYPE);
      sprintf(value, "%ld", start_val + i * step);
      result.set_value(i, 3, value, Array::INT_TYPE);
      sprintf(value, "%lf", (double) (start_val + i * step));
      result.set_value(i, 4, value, Array::FLOAT_TYPE);
    }
  }
  return err;
}
Example #14
0
void SiteProperty::initialize(XML::Block& X) { //<Site>

    STYPE = X["STYPE"].getInteger();
    NX    = X["NumberOfStates"].getInteger();
    VTYPE = X["VertexTypeOfSource"].getInteger();
    NIC   = NX;

    IC.init(1,NIC);

    for (int i=0; i<X.NumberOfBlocks(); i++) {
        XML::Block& B = X[i];
        if ( B.getName() == "InitialConfiguration" ) {
            int st = B["State"].getInteger();
            IC[st].initialize(B);
        }
    }
}
Example #15
0
void SiteInitialConfiguration::initialize(XML::Block& X) {

    //printf("SiteInitialConfiguration::initialize> Start.\n");

    State = X["State"].getInteger();
    NCH   = X["NumberOfChannels"].getInteger();
    CH.init("SCH",1,NCH);

    int ch = 0;
    for (int i=0; i<X.NumberOfBlocks(); i++) {
        XML::Block& B = X[i];
        if ( B.getName() == "Channel" ) CH[ch++].initialize(B);
    }

    if ( ch != NCH ) {
        printf("SiteInitialConfiguration::initialize> Error.\n");
        printf("  The actual number of channels (=%d)\n", ch);
        printf("  does not agree with NCH (=%d)\n", NCH);
    }

}
Example #16
0
void HelloWorld::updateGame(float dt)
{
	Array *projectilesToDelete = new Array();
    projectilesToDelete->init();
    
    Object* it = NULL;
    Object* jt = NULL;

	// for (it = _projectiles->begin(); it != _projectiles->end(); it++)
    CCARRAY_FOREACH(_projectiles, it)
	{
		auto projectile = dynamic_cast<Sprite*>(it);
		auto projectileRect = Rect(
			projectile->getPosition().x - (projectile->getContentSize().width/2),
			projectile->getPosition().y - (projectile->getContentSize().height/2),
			projectile->getContentSize().width,
			projectile->getContentSize().height);

		auto targetsToDelete = new Array();
        targetsToDelete->init();

		// for (jt = _targets->begin(); jt != _targets->end(); jt++)
        CCARRAY_FOREACH(_targets, jt)
		{
			auto target = dynamic_cast<Sprite*>(jt);
			auto targetRect = Rect(
				target->getPosition().x - (target->getContentSize().width/2),
				target->getPosition().y - (target->getContentSize().height/2),
				target->getContentSize().width,
				target->getContentSize().height);

			// if (Rect::RectIntersectsRect(projectileRect, targetRect))
            // rectの衝突判定
            if (projectileRect.intersectsRect(targetRect))
			{
				targetsToDelete->addObject(target);
			}
		}
// seq col + equal col
int BigqueryReader::get_bigquery_two_equal_seq_col1(uint64_t prefix, ValueRule& rule, Bigquery& query, Array& result)
{
  int err = 0;
  char value[32];
  int64_t row_num = rule.get_row_num();
  int64_t start_val = 0;
  int64_t step = 0;

  // select sum(col1), count(col1), sum(col1) / count(col1) from
  // bigquery_test group by col2;
  rule.get_seq_rule(0, start_val, step);
  query.set_table_name(BIGQUERY_TABLE);
  query.add_select_column("sum(col1)");
  query.add_select_column("count(col1)");
  query.add_select_column("min(col1)");
  query.add_select_column("max(col1)");
  query.add_select_column("sum(col1) / count(col1)");
  query.add_groupby_column("col2");
  query.add_filter("prefix", Bigquery::FILTER_EQ, prefix);
  query.add_filter("suffix", Bigquery::FILTER_LT, row_num);

  err = result.init(1, 5);
  if (0 == err)
  {
    sprintf(value, "%ld", start_val * row_num + row_num * (row_num - 1) * step / 2);
    result.set_value(0, 0, value, Array::INT_TYPE);
    sprintf(value, "%ld", row_num);
    result.set_value(0, 1, value, Array::INT_TYPE);
    sprintf(value, "%ld", start_val);
    result.set_value(0, 2, value, Array::INT_TYPE);
    sprintf(value, "%ld", start_val + (row_num - 1) * step);
    result.set_value(0, 3, value, Array::INT_TYPE);
    sprintf(value, "%lf", start_val + (double) ((row_num - 1) * step) / 2.0);
    result.set_value(0, 4, value, Array::FLOAT_TYPE);
  }

  return err;
}
int BigqueryReader::get_bigquery_one_equal_col2(uint64_t prefix, ValueRule& rule, Bigquery& query, Array& result)
{
  int err = 0;
  int64_t equal_val = 0;
  char value[32];
  int64_t row_num = rule.get_row_num();

  // select distinct col1 from bigquery_test;
  rule.get_equal_rule(0, equal_val);
  query.set_table_name(BIGQUERY_TABLE);
  query.add_select_column("col1");
  query.set_distinct(true);
  query.add_filter("prefix", Bigquery::FILTER_EQ, prefix);
  query.add_filter("suffix", Bigquery::FILTER_LT, row_num);

  err = result.init(1, 1);
  if (0 == err)
  {
    sprintf(value, "%ld", equal_val);
    result.set_value(0, 0, value, Array::INT_TYPE);
  }
  return err;
}
Example #19
0
void VertexInitialConfiguration::initialize(XML::Block& X) {//<initialconfig>

    //printf("VertexInitialConfiguration::initialize> Start.\n");

    if (NLEG == 0) {
        printf("VertexInitialConfiguration::read> Error.\n");
        printf(" ...  NLEG has not been set.\n");
        exit(0);
    }

    State = new int [NLEG];
    for (int i=0; i<NLEG; i++) {
        State[i] = X["State"].getInteger(i);
    }

    INC  = X["IncomingDirection"].getInteger();
    XINC = X["NewState"].getInteger();
    NCH  = X["NumberOfChannels"].getInteger();

    // -- edit sakakura --
    MCH  = 4;
    CH.init("VCH",1,MCH);
    //CH.init("VCH",1,NCH);//org
    // -- edit sakakura --

    int ch = 0;
    for (int i=0; i<X.NumberOfBlocks(); i++) {
        XML::Block& B = X[i];
        if (B.getName() == "Channel") CH[ch++].initialize(B);
    }

    if ( ch != NCH ) {
        printf("SiteInitialConfiguration::initialize> Error.\n");
        printf("  The actual number of channels (=%d)\n", ch);
        printf("  does not agree with NCH (=%d)\n", NCH);
    }
}
Example #20
0
static void test_pod() {
    Array<unsigned> array;

    const size_t initial_capacity = 20, grow_capacity = 12, alignment = 4;
    UAllocTraits_t traits = {0};
    MBED_HOSTTEST_ASSERT(array.init(initial_capacity, grow_capacity, traits, alignment));

    // Start filling the array
    for (unsigned i = 0; i < initial_capacity; i ++ ) {
        array.push_back(i);
    }
    MBED_HOSTTEST_ASSERT(array.get_num_elements() == initial_capacity);
    for (unsigned i = 0; i < initial_capacity; i ++) {
        MBED_HOSTTEST_ASSERT(array[i] == i);
    }
    MBED_HOSTTEST_ASSERT(array.get_num_zones() == 1);

    // Add another element, this should trigger the creation of another zone
    array.push_back(1000);
    MBED_HOSTTEST_ASSERT(array.get_num_zones() == 2);
    MBED_HOSTTEST_ASSERT(array.get_num_elements() == initial_capacity + 1);
    // Fill the second zone too
    for (unsigned i = 1; i < grow_capacity; i ++) {
        array.push_back(1000 + i);
    }
    MBED_HOSTTEST_ASSERT(array.get_num_elements() == initial_capacity + grow_capacity);
    for (unsigned i = 0; i < grow_capacity; i ++) {
        MBED_HOSTTEST_ASSERT(array.at(i + initial_capacity) == 1000 + i);
    }
    MBED_HOSTTEST_ASSERT(array.get_num_zones() == 2);
    unsigned save_for_later = array[initial_capacity + grow_capacity - 1];
    // Add yet another element, which should result in the creation of another zone
    array.push_back(10000);
    MBED_HOSTTEST_ASSERT(array[initial_capacity + grow_capacity] == 10000);
    MBED_HOSTTEST_ASSERT(array.get_num_zones() == 3);
    MBED_HOSTTEST_ASSERT(array.get_num_elements() == initial_capacity + grow_capacity + 1);

    // Remove the last element
    array.pop_back();
    MBED_HOSTTEST_ASSERT(array.get_num_elements() == initial_capacity + grow_capacity);
    MBED_HOSTTEST_ASSERT(array[array.get_num_elements() - 1] == save_for_later);
    MBED_HOSTTEST_ASSERT(array.get_num_zones() == 3); // the array doesn't (yet?) shrink

    // Simple bubble sort test illustrating moving around elements in the array
    const size_t total = initial_capacity + grow_capacity;
    for (unsigned i = 0; i < total; i ++) {
        array.at(i) = total - i - 1;
    }

    for (unsigned i = 0; i < total - 1; i ++) {
        for (unsigned j = i + 1; j < total; j ++) {
            if (array[i] > array[j]) {
                unsigned temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }
    }
    for (unsigned i = 0; i < total; i ++) {
        MBED_HOSTTEST_ASSERT(array[i] == i);
    }

    MBED_HOSTTEST_ASSERT(array.get_num_zones() == 3);
}
Example #21
0
//TODO: Regard some kind of aspect ration (input)
//(then also the rotation of a single component makes sense)
void ComponentSplitterLayout::reassembleDrawings(GraphAttributes& GA, const Array<List<node> > &nodesInCC)
{
	int numberOfComponents = nodesInCC.size();

	Array<IPoint> box;
	Array<IPoint> offset;
	Array<DPoint> oldOffset;
	Array<double> rotation;
	ConvexHull CH;

	// rotate components and create bounding rectangles

	//iterate through all components and compute convex hull
	for (int j = 0; j < numberOfComponents; j++)
	{
		//todo: should not use std::vector, but in order not
		//to have to change all interfaces, we do it anyway
		std::vector<DPoint> points;

		//collect node positions and at the same time center average
		// at origin
		double avg_x = 0.0;
		double avg_y = 0.0;
		for (node v : nodesInCC[j])
		{
			DPoint dp(GA.x(v), GA.y(v));
			avg_x += dp.m_x;
			avg_y += dp.m_y;
			points.push_back(dp);
		}
		avg_x /= nodesInCC[j].size();
		avg_y /= nodesInCC[j].size();

		//adapt positions to origin
		int count = 0;
		//assume same order of vertices and positions
		for (node v : nodesInCC[j])
		{
			//TODO: I am not sure if we need to update both
			GA.x(v) = GA.x(v) - avg_x;
			GA.y(v) = GA.y(v) - avg_y;
			points.at(count).m_x -= avg_x;
			points.at(count).m_y -= avg_y;

			count++;
		}

		// calculate convex hull
		DPolygon hull = CH.call(points);

		double best_area = numeric_limits<double>::max();
		DPoint best_normal;
		double best_width = 0.0;
		double best_height = 0.0;

		// find best rotation by using every face as rectangle border once.
		for (DPolygon::iterator j = hull.begin(); j != hull.end(); ++j) {
			DPolygon::iterator k = hull.cyclicSucc(j);

			double dist = 0.0;
			DPoint norm = CH.calcNormal(*k, *j);
			for (const DPoint &z : hull) {
				double d = CH.leftOfLine(norm, z, *k);
				if (d > dist) {
					dist = d;
				}
			}

			double left = 0.0;
			double right = 0.0;
			norm = CH.calcNormal(DPoint(0, 0), norm);
			for (const DPoint &z : hull) {
				double d = CH.leftOfLine(norm, z, *k);
				if (d > left) {
					left = d;
				}
				else if (d < right) {
					right = d;
				}
			}
			double width = left - right;

			dist = max(dist, 1.0);
			width = max(width, 1.0);

			double area = dist * width;

			if (area <= best_area) {
				best_height = dist;
				best_width = width;
				best_area = area;
				best_normal = CH.calcNormal(*k, *j);
			}
		}

		if (hull.size() <= 1) {
			best_height = 1.0;
			best_width = 1.0;
			best_area = 1.0;
			best_normal = DPoint(1.0, 1.0);
		}

		double angle = -atan2(best_normal.m_y, best_normal.m_x) + 1.5 * Math::pi;
		if (best_width < best_height) {
			angle += 0.5f * Math::pi;
			double temp = best_height;
			best_height = best_width;
			best_width = temp;
		}
		rotation.grow(1, angle);
		double left = hull.front().m_x;
		double top = hull.front().m_y;
		double bottom = hull.front().m_y;
		// apply rotation to hull and calc offset
		for (DPoint tempP : hull) {
			double ang = atan2(tempP.m_y, tempP.m_x);
			double len = sqrt(tempP.m_x*tempP.m_x + tempP.m_y*tempP.m_y);
			ang += angle;
			tempP.m_x = cos(ang) * len;
			tempP.m_y = sin(ang) * len;

			if (tempP.m_x < left) {
				left = tempP.m_x;
			}
			if (tempP.m_y < top) {
				top = tempP.m_y;
			}
			if (tempP.m_y > bottom) {
				bottom = tempP.m_y;
			}
		}
		oldOffset.grow(1, DPoint(left + 0.5 * static_cast<double>(m_border), -1.0 * best_height + 1.0 * bottom + 0.0 * top + 0.5 * (double)m_border));

		// save rect
		int w = static_cast<int>(best_width);
		int h = static_cast<int>(best_height);
		box.grow(1, IPoint(w + m_border, h + m_border));
	}// components

	offset.init(box.size());

	// call packer
	m_packer.get().call(box, offset, m_targetRatio);

	int index = 0;
	// Apply offset and rebuild Graph
	for (int j = 0; j < numberOfComponents; j++)
	{
		double angle = rotation[index];
		// apply rotation and offset to all nodes

		for (node v : nodesInCC[j])
		{
			double x = GA.x(v);
			double y = GA.y(v);
			double ang = atan2(y, x);
			double len = sqrt(x*x + y*y);
			ang += angle;
			x = cos(ang) * len;
			y = sin(ang) * len;

			x += static_cast<double>(offset[index].m_x);
			y += static_cast<double>(offset[index].m_y);

			x -= oldOffset[index].m_x;
			y -= oldOffset[index].m_y;

			GA.x(v) = x;
			GA.y(v) = y;

		}// while nodes in component

		index++;
	} // for components

	//now we center the whole graph again
	//TODO: why?
	//const Graph& G = GA.constGraph();
	//for(node v : G.nodes)
	//MLG.moveToZero();
}
Example #22
0
File: main.cpp Project: CCJY/coliru
template<class T> void setArr(T&& x)  { type = Arr; hArr.init(forward<T>(x)); }