コード例 #1
0
ファイル: misc.c プロジェクト: 00001/plan9port
obj*
makenode(int type, int n)
{
	obj *p;

	p = (obj *) calloc(1, sizeof(obj) + (n-1)*sizeof(ofloat));
	if (p == NULL)
		ERROR "out of space in makenode" FATAL;
	p->o_type = type;
	p->o_count = n;
	p->o_nobj = nobj;
	p->o_mode = hvmode;
	p->o_x = curx;
	p->o_y = cury;
	p->o_nt1 = ntext1;
	p->o_nt2 = ntext;
	ntext1 = ntext;	/* ready for next caller */
	if (nobj >= nobjlist)
		objlist = (obj **) grow((char *) objlist, "objlist",
			nobjlist *= 2, sizeof(obj *));
	objlist[nobj++] = p;
	return(p);
}
コード例 #2
0
ファイル: threadpool.c プロジェクト: GGGO/asterisk
/*!
 * \brief Queued task called when tasks are pushed into the threadpool
 *
 * This function first calls into the threadpool's listener to let it know
 * that a task has been pushed. It then wakes up all idle threads and moves
 * them into the active thread container.
 * \param data A task_pushed_data
 * \return 0
 */
static int queued_task_pushed(void *data)
{
	struct task_pushed_data *tpd = data;
	struct ast_threadpool *pool = tpd->pool;
	int was_empty = tpd->was_empty;
	unsigned int existing_active;

	if (pool->listener && pool->listener->callbacks->task_pushed) {
		pool->listener->callbacks->task_pushed(pool, pool->listener, was_empty);
	}

	existing_active = ao2_container_count(pool->active_threads);

	/* The first pass transitions any existing idle threads to be active, and
	 * will also remove any worker threads that have recently entered the dead
	 * state.
	 */
	ao2_callback(pool->idle_threads, OBJ_UNLINK | OBJ_NOLOCK | OBJ_NODATA,
			activate_thread, pool);

	/* If no idle threads could be transitioned to active grow the pool as permitted. */
	if (ao2_container_count(pool->active_threads) == existing_active) {
		if (!pool->options.auto_increment) {
			ao2_ref(tpd, -1);
			return 0;
		}
		grow(pool, pool->options.auto_increment);
		/* An optional second pass transitions any newly added threads. */
		ao2_callback(pool->idle_threads, OBJ_UNLINK | OBJ_NOLOCK | OBJ_NODATA,
				activate_thread, pool);
	}

	threadpool_send_state_changed(pool);
	ao2_ref(tpd, -1);
	return 0;
}
コード例 #3
0
inline void ConservativeRoots::genericAddPointer(void* p, TinyBloomFilter filter, MarkHook& markHook)
{
    markHook.mark(p);
    
    MarkedBlock* candidate = MarkedBlock::blockFor(p);
    if (filter.ruleOut(reinterpret_cast<Bits>(candidate))) {
        ASSERT(!candidate || !m_blocks->set().contains(candidate));
        return;
    }

    if (!MarkedBlock::isAtomAligned(p))
        return;

    if (!m_blocks->set().contains(candidate))
        return;

    if (!candidate->isLiveCell(p))
        return;

    if (m_size == m_capacity)
        grow();

    m_roots[m_size++] = static_cast<JSCell*>(p);
}
コード例 #4
0
ファイル: packrat.c プロジェクト: ranok/hammer
HParseResult* grow(HParserCacheKey *k, HParseState *state, HRecursionHead *head) {
  // Store the head into the recursion_heads
  h_hashtable_put(state->recursion_heads, &k->input_pos, head);
  HParserCacheValue *old_cached = h_hashtable_get(state->cache, k);
  if (!old_cached || PC_LEFT == old_cached->value_type)
    h_platform_errx(1, "impossible match");
  HParseResult *old_res = old_cached->right;

  // rewind the input
  state->input_stream = k->input_pos;
  
  // reset the eval_set of the head of the recursion at each beginning of growth
  head->eval_set = h_slist_copy(head->involved_set);
  HParseResult *tmp_res = perform_lowlevel_parse(state, k->parser);

  if (tmp_res) {
    if (pos_lt(old_cached->input_stream, state->input_stream)) {
      h_hashtable_put(state->cache, k, cached_result(state, tmp_res));
      return grow(k, state, head);
    } else {
      // we're done with growing, we can remove data from the recursion head
      h_hashtable_del(state->recursion_heads, &k->input_pos);
      HParserCacheValue *cached = h_hashtable_get(state->cache, k);
      if (cached && PC_RIGHT == cached->value_type) {
        state->input_stream = cached->input_stream;
	return cached->right;
      } else {
	h_platform_errx(1, "impossible match");
      }
    }
  } else {
    h_hashtable_del(state->recursion_heads, &k->input_pos);
    state->input_stream = old_cached->input_stream;
    return old_res;
  }
}
コード例 #5
0
ファイル: vlrankmap.cpp プロジェクト: holtzermann17/Noosphere
// occupy a position in the rank map
// 
void vlrankmap::add ( float _key ) {

	int index = index_of(_key);
		
	float key = _keys[index];

	// if new spot, see if we should grow. 
	// 
	if ( key == -1 ) { 
		
		// first mark this spot with our key
		_keys[index] = _key;

		// increase filled count
		filled++;

		// check for table resize
		//
		if (((float)filled/(float)size) > 0.75) {
		
			grow();
		}
	} 
}
コード例 #6
0
ファイル: ut_stringbuf.cpp プロジェクト: Distrotech/abiword
/* translates the current string to MIME "quoted-printable" format
 */
void UT_UTF8Stringbuf::escapeMIME ()
{
	static const char hex[16] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };
	static const char * s_eol = "=\r\n";

	if (m_strlen == 0) return;

	size_t bytes = 0;
	char * ptr = m_psz;
	while (*ptr)
		{
			char c = *ptr++;
			unsigned char u = static_cast<unsigned char>(c);

			if ((c == '\r') || (c == '\n') || (c == '=') || (u & 0x80)) bytes += 2;
		}
	if (bytes)
		{
			if (!grow (bytes)) return;

			char * pOld = m_pEnd;
			char * pNew = m_pEnd + bytes;

			while (pOld >= m_psz)
				{
					char c = *pOld--;
					unsigned char u = static_cast<unsigned char>(c);

					if ((u & 0x80) || (c == '\r') || (c == '\n') || (c == '='))
						{
							*pNew-- = hex[ u       & 0x0f];
							*pNew-- = hex[(u >> 4) & 0x0f];
							*pNew-- = '=';
						}
					else *pNew-- = c;
				}
コード例 #7
0
ファイル: bounds.cpp プロジェクト: pblottiere/PDAL
void Bounds::grow(const Bounds& other)
{
    grow(other.min());
    grow(other.max());
}
コード例 #8
0
ファイル: HandleHeap.cpp プロジェクト: 1833183060/wke
HandleHeap::HandleHeap(JSGlobalData* globalData)
    : m_globalData(globalData)
    , m_nextToFinalize(0)
{
    grow();
}
コード例 #9
0
ファイル: erl_process_dict.c プロジェクト: NaughtyCode/otp
static Eterm pd_hash_put(Process *p, Eterm id, Eterm value)
{ 
    unsigned int hval;
    Eterm *hp;
    Eterm tpl;
    Eterm old;
    Eterm tmp;
    int needed;
    int i = 0;
#ifdef DEBUG
    Eterm *hp_limit;
#endif

    if (p->dictionary == NULL) {
	/* Create it */
	array_put(&(p->dictionary), INITIAL_SIZE - 1, NIL);
	p->dictionary->homeSize = INITIAL_SIZE;
    }	
    hval = pd_hash_value(p->dictionary, id);
    old = ARRAY_GET(p->dictionary, hval);

    /*
     * Calculate the number of heap words needed and garbage
     * collect if necessary. (Might be a slight overestimation.)
     */
    needed = 3;			/* {Key,Value} tuple */
    if (is_boxed(old)) {
	/*
	 * We don't want to compare keys twice, so we'll always
	 * reserve the space for two CONS cells.
	 */
	needed += 2+2;
    } else if (is_list(old)) {
	i = 0;
	for (tmp = old; tmp != NIL && !EQ(tuple_val(TCAR(tmp))[1], id); tmp = TCDR(tmp)) {
	    ++i;
	}
	if (is_nil(tmp)) {
	    i = -1;
	    needed += 2;
	} else {
	    needed += 2*(i+1);
	}
    }
    if (HeapWordsLeft(p) < needed) {
	Eterm root[3];
	root[0] = id;
	root[1] = value;
	root[2] = old;
	BUMP_REDS(p, erts_garbage_collect(p, needed, root, 3));
	id = root[0];
	value = root[1];
	old = root[2];
    }
#ifdef DEBUG
    hp_limit = p->htop + needed;
#endif

    /*
     * Create the {Key,Value} tuple.
     */
    hp = HeapOnlyAlloc(p, 3);
    tpl = TUPLE2(hp, id, value);

    /*
     * Update the dictionary.
     */
    if (is_nil(old)) {
	array_put(&(p->dictionary), hval, tpl);
	++(p->dictionary->numElements);
    } else if (is_boxed(old)) {
	ASSERT(is_tuple(old));
	if (EQ(tuple_val(old)[1],id)) {
	    array_put(&(p->dictionary), hval, tpl);
	    return tuple_val(old)[2];
	} else {
	    hp = HeapOnlyAlloc(p, 4);
	    tmp = CONS(hp, old, NIL);
	    hp += 2;
	    ++(p->dictionary->numElements);
	    array_put(&(p->dictionary), hval, CONS(hp, tpl, tmp));
	    hp += 2;
	    ASSERT(hp <= hp_limit);
	}
    } else if (is_list(old)) {
	if (i == -1) {
	    /*
	     * New key. Simply prepend the tuple to the beginning of the list.
	     */
	    hp = HeapOnlyAlloc(p, 2);
	    array_put(&(p->dictionary), hval, CONS(hp, tpl, old));
	    hp += 2;
	    ASSERT(hp <= hp_limit);
	    ++(p->dictionary->numElements);
	} else {
	    /*
	     * i = Number of CDRs to skip to reach the changed element in the list.
	     *
	     * Replace old value in list. To avoid pointers from the old generation
	     * to the new, we must rebuild the list from the beginning up to and
	     * including the changed element.
	     */
	    Eterm nlist;
	    int j;

	    hp = HeapOnlyAlloc(p, (i+1)*2);
	    
	    /* Find the list element to change. */
	    for (j = 0, nlist = old; j < i; j++, nlist = TCDR(nlist)) {
		;
	    }
	    ASSERT(EQ(tuple_val(TCAR(nlist))[1], id));
	    nlist = TCDR(nlist); /* Unchanged part of list. */

	    /* Rebuild list before the updated element. */
	    for (tmp = old; i-- > 0; tmp = TCDR(tmp)) {
		nlist = CONS(hp, TCAR(tmp), nlist);
		hp += 2;
	    }
	    ASSERT(EQ(tuple_val(TCAR(tmp))[1], id));

	    /* Put the updated element first in the new list. */
	    nlist = CONS(hp, tpl, nlist);
	    hp += 2;
	    ASSERT(hp <= hp_limit);
	    array_put(&(p->dictionary), hval, nlist);
	    return tuple_val(TCAR(tmp))[2];
	}
    } else {
#ifdef DEBUG
	erts_fprintf(stderr,
		     "Process dictionary for process %T is broken, trying to "
		     "display term found in line %d:\n"
		     "%T\n", p->common.id, __LINE__, old);
#endif

	erl_exit(1, "Damaged process dictionary found during put/2.");
    }
    if (HASH_RANGE(p->dictionary) <= p->dictionary->numElements) {
	grow(p);
    }
    return am_undefined;
}
コード例 #10
0
ファイル: mgDWordArray.cpp プロジェクト: duaneking/SeaOfMemes
//--------------------------------------------------------------
// add an element
void mgDWordArray::add(
  DWORD elm)
{
  grow(m_elementCount+1);
  m_elements[m_elementCount++] = elm;
}
コード例 #11
0
void vec<T>::growTo(int size) {
    if (sz >= size) return;
    grow(size);
    for (int i = sz; i < size; i++) new (&data[i]) T();
    sz = size; }
コード例 #12
0
 // Stack interface:
 void     push  (void)              { if (sz == cap) grow(sz+1); new (&data[sz]) T()    ; sz++; }
コード例 #13
0
ファイル: array.hpp プロジェクト: SleepyAkubi/Propitious
	void resize(Array<T>& array, vol length)
	{
		if (length > array.capacity)
			grow(array, length);
		array.length = length;
	}
コード例 #14
0
ファイル: MemoryFrame.cpp プロジェクト: citic/botNeumann
int MemoryFrame::distributeVariablesIntoMemoryRows(int initialDelay)
{
	// The duration of this animation
	int duration = 0;

	// We iterate for all variables assigned to this frame, distributing them to its memory rows
	MemoryAllocations::iterator variableIterator = memoryAllocations.begin();
	int currentRow = 0;

	// Traverse all the variables
	while ( variableIterator != memoryAllocations.end() )
	{
		// For convenience
		MemoryAllocation* variable = *variableIterator;

		// We must allocate a variable, if all rows were filled
		if ( currentRow >= memoryRows.count() )
		{
			// We do not need to grow the frame for free memory
			if ( variable->isFreeFragment() )
			{
				// Skip to next variable
				++variableIterator;
				continue;
			}

			// All the memory rows are filled, but if the memory frame can grow, create more rows
			// ToDo: Only a piece of the variable may be needed to allocate, not the entire variable
			int requiredRows = (qMax(variable->size, 1ll) + (rowSize - 1)) / rowSize;
			qCCritical(logTemporary(), "Growing %d rows for %s of %lld bytes", requiredRows, qPrintable(variable->name), variable->size);

			// If it is unable to grow more, we have a segment overflow
			int growDuration = grow(requiredRows, initialDelay);
			if ( growDuration < 0 )
				return growDuration;

			// Add this duration to the proccess and the remaining animations
			duration += growDuration;
			initialDelay += growDuration;

			// Be sure there is a memory row to continue
			Q_ASSERT( currentRow < memoryRows.count() );
		}

		// Try to allocate this variable in the current row
		int entirelyAllocated = false;
		int rowAllocation = memoryRows[currentRow]->allocate(variable, entirelyAllocated, initialDelay);

		// Update the durations of animation
		duration += rowAllocation;
		initialDelay += rowAllocation;

		// If the variable was partially allocated or not allocated at all
		if ( entirelyAllocated <= 0 )
		{
			// Try to allocate the variable in the next row
			++currentRow;
			continue;
		}

		// The row accepted the variable, and it is completely allocated, move to the next variable
		++variableIterator;
	}

	// All variables were distributed in the available rows
	return duration;
}
コード例 #15
0
ファイル: bbtree.c プロジェクト: taysom/tau
void bb_insert (BbTree_s *tree, u64 key)
{
	BbNode_s **np = &tree->root;
	BbNode_s **pp;
	BbNode_s *head = NULL;
	BbNode_s *node = *np;
	int siblings;

	if (!node) {
		*np = bb_new(key);
		return;
	}
	if (node->siblings == 2) {
		grow(np);
		node = *np;
	}
	head = node;
	siblings = head->siblings;
	while (node->left) {
		pp = np;
		if (key < node->key) {
			np = &node->left;
			node = *np;
			head = node;
			siblings = head->siblings;
		} else {
			np = &node->right;
			node =*np;
// Need to know when going right goes down a level.
// 1. keep a count from head
// 2. Keep a count of right siblings
			if (siblings) {
				--siblings;
			} else {
				head = node;
				siblings = head->siblings;
			}
			aver(node);
		}
		if (node->siblings == 2) {
			np = split(head, pp, node);
			node = *np;
		}
		aver(node->siblings < 2);
	}
	if (!node->left) {
		if (key < node->key) {
			BbNode_s *child = bb_new(key);
			child->right = node;
			child->siblings = node->siblings + 1;
			node->siblings = 0;
			*np = child;
			return;
		}
		head = node;
		for (;;) {
			np = &node->right;
			node = *np;
			if (!node) {
				*np = bb_new(key);
				++head->siblings;
				return;
			}
			if (key < node->key) {
				BbNode_s *child = bb_new(key);
				child->right = node;
				child->siblings = node->siblings + 1;
				node->siblings = 0;
				*np = child;
				++head->siblings;
				return;
			}
		}
	}
#if 0
	for (;;) {
		BbNode_s *node = *np;
		if (!node) break;
		if (key < node->key) {
			np = &node->left;
		} else {
			np = &node->right;
		}
	}
	*np = bb_new(key);
#endif
}
コード例 #16
0
ファイル: parsemeta.c プロジェクト: hhirsch/netrek
static void version_s(struct sockaddr_in *address)
{
  char *p;
  time_t now = time(NULL);

  /* use return address on packet as host address for this server,
  since it isn't practical for the server to know it's own address; as
  is the case with multihomed machines */
  char *host = inet_ntoa(address->sin_addr);

  if (verbose) fprintf(stderr, "server at %s responded\n", host);

  p = strtok(NULL,","); /* server type */
  if (p == NULL) return;
  char type = p[0];

  /* ignore paradise servers */
  if (type == 'P') return;

  p = strtok(NULL,",");         /* comment */
  if (p == NULL) return;
  char *comment = strdup(p);
  if (strlen(comment) > LINE) comment[LINE] = '\0';

  p = strtok(NULL,",");         /* number of ports */
  if (p == NULL) return;
  // int ports = atoi(p);               /* not currently used */

  // TODO: accept more than one port reply

  p = strtok(NULL,",");         /* port */
  if (p == NULL) return;
  int port = atoi(p);

  p = strtok(NULL,",");         /* players */
  if (p == NULL) return;
  int players = atoi(p);

  p = strtok(NULL,",");         /* queue size */
  if (p == NULL) return;
  // int queue = atoi(p);               /* not currently used */

  /* find in current server list? */
  struct servers *sp = server_find(host, port);

  /* if it was not found, add it to the end of the list */
  if (sp == NULL) {
    grow(1);
    sp = serverlist + num_servers;
    num_servers++;
  }

  /* add or update the entry */
  strncpy(sp->address, host, LINE);
  sp->port = port;
  sp->age = 0;
  sp->when = now;
  sp->refresh = 1;
  sp->lifetime = 20;
  sp->players = players;
  if (type == 'u' && players == 0) {
    sp->status = statusNobody;
  } else {
    sp->status = statusOpen;
  }
  sp->typeflag = type;
  strncpy(sp->comment, comment, LINE);
  sp->pid = -1;
  sp->exitstatus = 0;
  sp->observer = 0;
  free(comment);
}
コード例 #17
0
 void     capacity (int size) { grow(size); }
コード例 #18
0
ファイル: heap.hpp プロジェクト: ybouret/yocto4
 virtual void reserve( size_t n ) { if( n > 0 ) grow(n);}
コード例 #19
0
 void     push  (const T& elem)     { if (sz == cap) grow(sz+1); new (&data[sz]) T(elem); sz++; }
コード例 #20
0
ファイル: heap.hpp プロジェクト: ybouret/yocto4
 //! insert the address
 inline void push( T *pObj )
 {
     if( size_ >= maxi_ )
         grow( next_increase(maxi_) );
     __push( pObj );
 }
コード例 #21
0
ファイル: testNewPoissonOp.cpp プロジェクト: rsnemmen/Chombo
int main(int argc, char* argv[])
{

#ifdef CH_MPI
  MPI_Init (&argc, &argv);
#endif

  // test parameters
  const int nGrids = 3;
  const int nCells0 = 32;
  // xLo has to be zero in order for DiriBc to work.
  const RealVect xLo = RealVect::Zero;
  const Real xHi = 1.0;
  const Box box0(IntVect::Zero, (nCells0-1)*IntVect::Unit);
  const int nGhosts = 1;
  const int resNT = 2; // norm Type
  const int errNT = 0;
  // A test is considered as a failure
  // if its convergence rate is smaller than below.
  const Real targetConvergeRate = 1.75;

  // solver parameters
  // To converge within 10 V-Cycles in 1D,
  //  nRelax=3 is the minimum number of relaxations.
  const int nRelax = 3; // m_pre=m_post
  // cycle Type, 1 : V-Cycle; -1 : FMG-Cycle
  const int cycleType[2] =
  {
    1, -1
  };
  const std::string cycleStr[2] =
  {
    "   V" , " FMG"
  };

  // test results holder
  const int nCycles[2] =
  {
    9, 5
  };
  const int maxCycles = 10; // > max(nCycles)
  //  Real resNorm[nGrids][nCycles+1], errNorm[nGrids][nCycles+1];
  Real resNorm[nGrids][maxCycles], errNorm[nGrids][maxCycles];
  Real convergeRate[nGrids-1][2];
  const Real log2r = 1.0/log(2.0);

  // status records the number of errors detected.
  int status = 0;
  for (int j=0; j<2; j++)
  {
    pout() << "\n**************************************************\n"
           << "\nTesting MultiGrid::oneCycle(correction, residual)\n"
           << " cycle type = " << cycleStr[j]
           << "; m_pre = m_post = " << nRelax << "\n";

    for (int iGrid=0; iGrid<nGrids; iGrid++)
    {
      int ref = 1;
      for (int i=0; i<iGrid; i++)
        ref*=2;
      const Real dx = xHi/nCells0/ref;
      const Box domain = refine(box0,ref);
      const Box ghostBox = grow(domain,nGhosts);

      pout() << "\n----------------------------------------------------\n";
      pout() << "nCells = " << nCells0*ref << " ; dx = " << dx << " \n";

      FArrayBox phi(ghostBox, 1);
      FArrayBox correction(ghostBox, 1);
      FArrayBox rhs(domain, 1);
      FArrayBox error(domain, 1);
      FArrayBox phiExact(domain, 1);
      FArrayBox residual(domain, 1);

      // set initial guess
      phi.setVal(0.0);
      // set RHS and the exact solution
      for (BoxIterator bit(domain); bit.ok(); ++bit)
        {
          const RealVect offset = bit()-domain.smallEnd();
          const RealVect x = xLo + dx*(0.5+offset);
          rhs(bit()) = rhsFunc( x );
          phiExact(bit()) = exactSolution( x );
        }

      // Initialize big objects
      NewPoissonOpFactory opFactory;
      opFactory.define(dx*RealVect(IntVect::Unit), constDiriBC);
      MultiGrid<FArrayBox> solver;
      BiCGStabSolver<FArrayBox> bottomSolver;
      bottomSolver.m_verbosity = 0;
      MGLevelOp<FArrayBox>* op = opFactory.MGnewOp(domain,0);
      solver.m_numMG = 1;
      solver.m_bottom = 1;
      solver.m_pre = nRelax;
      solver.m_post = nRelax;
      solver.m_cycle = cycleType[j];
      solver.define(opFactory, &bottomSolver, domain);

      // put the data into residual-correction form
      op->residual(residual, phi, rhs);
      resNorm[iGrid][0] = residual.norm(resNT);
      op->axby(error, phi, phiExact, 1, -1);
      errNorm[iGrid][0] = error.norm(errNT);
      solver.init(correction, residual);

      // Solve the problem using MultiGrid::oneCycle
      for (int i=0; i<nCycles[j]; i++)
        {
          correction.setVal(0.0);
          solver.oneCycle(correction, residual);
          op->incr(phi, correction, 1);
          op->residual(residual, phi, rhs);
          resNorm[iGrid][i+1] = residual.norm(resNT);
          op->axby(error, phi, phiExact, 1, -1);
          errNorm[iGrid][i+1] = error.norm(errNT);
        }
      delete op;

      // output a table of results
      pout()<< cycleStr[j] << "-Cycle N.O. |  residual " << resNT
            << "-norm  |  Error " << errNT << "-norm  \n";
      for (int i=0; i<nCycles[j]+1; i++)
        {
          pout() << "         " << i << "      |    " << resNorm[iGrid][i]
                 << "        |    " << errNorm[iGrid][i]  << "\n";
        }
    } // end grid loop

    pout() << "\nConvergence Rate based on the error in the last cycle:\n";
    for (int i=0; i<nGrids-1; i++)
    {
      Real ratio = errNorm[i][nCycles[j]]/errNorm[i+1][nCycles[j]];
      convergeRate[i][j] = log(ratio)*log2r;
      if (convergeRate[i][j] < targetConvergeRate)
      {
        status += 1;
      }
      pout() << "    " << convergeRate[i][j] << "\n";
    }
  }// end cycle type

  if (status==0)
  {
    pout() <<  "All tests passed!\n";
  }
  else
  {
    pout() <<  status << " tests failed!\n";
  }

#ifdef CH_MPI
  MPI_Finalize ();
#endif

  return status;
}
コード例 #22
0
ファイル: stack.cpp プロジェクト: emilio/gii-2
void stack<T, Allocator>::push(const T& val) noexcept {
	if ( size_ == capacity_ )
		grow();

	data[size_++] = val;
};
コード例 #23
0
ファイル: scat.c プロジェクト: npe9/harvey
void
flatten(void)
{
    int i, j, notflat;
    Record *or;
    int32_t key;

loop:
    copy();
    reset();
    notflat = 0;
    for(i=0,or=orec; i<norec; i++,or++) {
        switch(or->type) {
        default:
            fprint(2, "bad type %d in flatten\n", or->type);
            break;

        case NONGC:
            break;

        case Planet:
        case Abell:
        case NGC:
        case SAO:
            grow();
            memmove(cur, or, sizeof(Record));
            break;

        case NGCN:
            if(loadngc(or->index))
                notflat = 1;
            break;

        case NamedSAO:
            loadsao(or->index);
            notflat = 1;
            break;

        case NamedNGC:
            if(loadngc(or->index))
                notflat = 1;
            break;

        case NamedAbell:
            loadabell(or->index);
            notflat = 1;
            break;

        case PatchC:
            loadpatch(or->index);
            notflat = 1;
            break;

        case Patch:
            for(j=1; j<or->patch.nkey; j++) {
                key = or->patch.key[j];
                if((key&0x3F) == SAO)
                    loadsao((key>>8)&0xFFFFFF);
                else if((key&0x3F) == Abell)
                    loadabell((key>>8)&0xFFFFFF);
                else
                    loadngc((key>>16)&0xFFFF);
            }
            break;
        }
コード例 #24
0
ファイル: GodunovTrace.cpp プロジェクト: rsnemmen/Chombo
void TraceState(/// state at time t+dt/2 on edges in direction dir
                FArrayBox& a_stateHalf,
                /// cell-centered state at time t
                const FArrayBox& a_state,
                /// cell-centered velocity at time t
                const FArrayBox& a_cellVel,
                /// edge-centered advection velocity at time t+dt/2
                const FluxBox& a_advectionVel,
                /// cell-centered source
                const FArrayBox& a_source,
                /// Physical domain
                const ProblemDomain& a_dProblem,
                /// interior of grid patch
                const Box& a_gridBox,
                /// timeStep
                const Real a_dt,
                /// cell-spacing
                const Real a_dx,
                /// direction in which to perform tracing
                const int a_dir,
                /// which components to trace
                const Interval& a_srcComps,
                ///  where to put traced components in a_stateHalf,
                const Interval& a_destComps)

{

  int ncomp = a_srcComps.size();
  CH_assert (ncomp == a_destComps.size());
  int offset = a_destComps.begin() - a_srcComps.begin();
  Box edgeBox = a_gridBox;
  edgeBox.surroundingNodes(a_dir);

#ifdef SIMPLEUPWIND
  // simple cell-to-edge averaging may be causing us problems --
  // instead do simple upwinding

  for (int comp=a_srcComps.begin(); comp <= a_srcComps.end(); comp++)
  {
    int destcomp = comp+offset;
    FORT_UPWINDCELLTOEDGE(CHF_FRA1(a_stateHalf, destComp),
                          CHF_CONST_FRA1(a_state,comp),
                          CHF_CONST_FRA(a_advectionVel[a_dir]),
                          CHF_BOX(edgeBox),
                          CHF_CONST_INT(a_dir));
  }

#else


  // first compute slopes
  Box slopesBox = grow(a_gridBox,1);

  // these are debugging changes to sync with old code
#ifdef MATCH_OLDCODE
  FluxBox tempEdgeVel(slopesBox,1);
  tempEdgeVel.setVal(0.0);

  FArrayBox tempCellVel(slopesBox,SpaceDim);
  tempCellVel.setVal(0.0);


  CellToEdge(a_cellVel, tempEdgeVel);
  EdgeToCell(tempEdgeVel, tempCellVel);
  tempEdgeVel.clear(); // done with this, so reclaim memory
  EdgeToCell(a_advectionVel, tempCellVel);
#endif

  FArrayBox delS(slopesBox,1);
  FArrayBox sHat(slopesBox,1);
  FArrayBox sTilde(a_state.box(),1);

  for (int comp=a_srcComps.begin(); comp<=a_srcComps.end(); comp++)
  {
    int destComp = comp+offset;

#ifdef SET_BOGUS_VALUES
    delS.setVal(BOGUS_VALUE);
    sHat.setVal(BOGUS_VALUE);
    sTilde.setVal(BOGUS_VALUE);
#endif

    // compute van leer limited slopes in the normal direction
    // for now, always limit slopes, although might want to make
    // this a parameter
    int limitSlopes = 1;
    FORT_SLOPES(CHF_FRA1(delS,0),
                CHF_CONST_FRA1(a_state,comp),
                CHF_BOX(slopesBox),
                CHF_CONST_INT(a_dir),
                CHF_CONST_INT(limitSlopes));

    // this is a way to incorporate the minion correction --
    // stateTilde = state + (dt/2)*source
    sTilde.copy(a_source,comp,0,1);
    Real sourceFactor = a_dt/2.0;
    sTilde *= sourceFactor;
    sTilde.plus(a_state, comp,0,1);
    sHat.copy(sTilde,slopesBox);

    // now loop over directions, adding transverse components
    for (int localDir=0; localDir < SpaceDim; localDir++)
    {
      if (localDir != a_dir)
      {
        // add simple transverse components
        FORT_TRANSVERSE(CHF_FRA1(sHat,0),
                        CHF_CONST_FRA1(sTilde,0),
#ifdef MATCH_OLDCODE
                        CHF_CONST_FRA1(tempCellVel, localDir),
#else
                        CHF_CONST_FRA1(a_cellVel,localDir),
#endif
                        CHF_BOX(slopesBox),
                        CHF_CONST_REAL(a_dt),
                        CHF_CONST_REAL(a_dx),
                        CHF_CONST_INT(localDir));
                        //CHF_FRA1(temp,0));  // not used in function

      }
      else if (SpaceDim == 3)
      {
        // only add cross derivative transverse piece if we're in 3D
        // note that we need both components of velocity for this one
        FORT_TRANSVERSECROSS(CHF_FRA1(sHat,0),
                             CHF_CONST_FRA1(sTilde,0),
                             CHF_CONST_FRA(a_cellVel),
                             CHF_BOX(slopesBox),
                             CHF_CONST_REAL(a_dt),
                             CHF_CONST_REAL(a_dx),
                             CHF_CONST_INT(localDir));
      }
    } // end loop over directions

    // now compute left and right states and resolve the Reimann
    // problem to get single set of edge-centered values
    FORT_PREDICT(CHF_FRA1(a_stateHalf,destComp),
                 CHF_CONST_FRA1(sHat,0),
                 CHF_CONST_FRA1(delS,0),
                 CHF_CONST_FRA1(a_cellVel,a_dir),
                 CHF_CONST_FRA1(a_advectionVel[a_dir],0),
                 CHF_BOX(edgeBox),
                 CHF_CONST_REAL(a_dt),
                 CHF_CONST_REAL(a_dx),
                 CHF_CONST_INT(a_dir));
  } // end loop over components

#endif


}
コード例 #25
0
ファイル: vector.c プロジェクト: ulfalizer/practice
void vector_append(Vector *vector, void *val)
{
    if (vector->len == vector->buf_len)
        grow(vector);
    vector->buf[vector->len++] = val;
}
コード例 #26
0
ファイル: SlabService.cpp プロジェクト: dtgraves/EBAMRCNS
void
SlabService::fillGraph(BaseFab<int>&      a_regIrregCovered,
                       Vector<IrregNode>& a_nodes,
                       const Box&         a_validRegion,
                       const Box&         a_ghostRegion,
                       const ProblemDomain&         a_domain,
                       const RealVect&    a_origin,
                       const Real&        a_dx) const
{
  Box grownCovBox = grow(m_coveredRegion, 1);
  grownCovBox &= a_ghostRegion;
  IntVectSet ivsIrreg(grownCovBox);
  ivsIrreg -= m_coveredRegion;
  ivsIrreg &= a_domain;

  //set regirregcoverred flags
  CH_assert(a_regIrregCovered.box().contains(a_ghostRegion));

  //set every cell to regular
  a_regIrregCovered.setVal(1);
  for (BoxIterator bit(a_ghostRegion); bit.ok(); ++bit)
    {
      if (m_coveredRegion.contains(bit()))
        {
          //set covered cells to -1
          a_regIrregCovered(bit(), 0) = -1;
        }
      else if (ivsIrreg.contains(bit()))
        {
          //set irreg cells to 0
          a_regIrregCovered(bit(), 0) = 0;
        }
    }

  //now loop through irreg cells and make Nodes for them
  a_nodes.resize(0);
  for (IVSIterator ivsit(ivsIrreg); ivsit.ok(); ++ivsit)
    {
      const IntVect& iv = ivsit();
      if (a_validRegion.contains(iv))
        {
          IrregNode node;
          //first the obvious
          node.m_cell = iv;
          node.m_volFrac = 1.0;
          node.m_cellIndex = 0;
          node.m_volCentroid    = RealVect::Zero;
          //any time the next cell over is in the covered
          //region, there is no face.  If there is a cell
          //but it is outside the domain, the arc=-1 to signify
          //a boundary face.  Otherwise, the arc is -2 if it
          //is to a regular cell and 0 if it is to an irregular cell
          for (int idir = 0; idir < SpaceDim; idir++)
            {
              for (SideIterator sit; sit.ok(); ++sit)
                {
                  int arcIndex = node.index(idir, sit());
                  Vector<int>&      arcs     = node.m_arc[arcIndex];
                  Vector<Real>&     areaFracs= node.m_areaFrac[arcIndex];
                  Vector<RealVect>& faceCents= node.m_faceCentroid[arcIndex];
                  IntVect otherIV = iv + sign(sit())*BASISV(idir);
                  if (m_coveredRegion.contains(otherIV))
                    {
                      //do nothing, covered face. leave the vector empty
                    }
                  else
                    {
                      int otherCellIndex;
                      if (ivsIrreg.contains(otherIV))
                        {
                          //arc irregular cell inside the domain
                          otherCellIndex = 0;
                        }
                      else if (!a_domain.contains(otherIV))
                        {
                          //boundary face
                          otherCellIndex = -1;
                        }
                      else
                        {
                          //arc to regular cell
                          otherCellIndex = -2;
                        }
                      arcs.push_back(otherCellIndex);
                      Real     areaFrac = 1.0;
                      RealVect faceCent = RealVect::Zero;

                      areaFracs.push_back(areaFrac);
                      faceCents.push_back(faceCent);
                    } //end otherIV not covered
                }
            }
          //the boundary centroid and normal
          //depend on which side is covered

          for (int idir = 0; idir < SpaceDim; idir++)
            {
              for (SideIterator sit; sit.ok(); ++sit)
                {
                  int arcIndex = node.index(idir, sit());
                  Vector<int>& arcs = node.m_arc[arcIndex];
                  if (arcs.size() == 0)
                    {
                      int isign = sign(sit());
                      node.m_bndryCentroid[idir] = Real(isign)*0.5;
                    }
                }
            }
          a_nodes.push_back(node);
        }
    }
}
コード例 #27
0
ファイル: pqueue-heap.cpp プロジェクト: parthnaik/cs106b
void HeapPriorityQueue::enqueue(string value) {
    if (numAllocated == capacity) grow();
    pQueue[++numAllocated] = value;
    bubbleUp(numAllocated);
}
コード例 #28
0
//! Stores element in hash table.
dmz::Boolean
dmz::HashTableString::store (const String &Key, void *data) {

   Boolean result (False);

   if (data) {

      if ((_state.count + 1) > _state.size) { grow (); }

      if (_state.size >= (_state.count + 1)) {

         Int32 index = local_hash (Key) % _state.size;
         const Int32 StartIndex (index);
         Boolean done (False);

         Int32 foundIndex (-1);

         while (!done) {

            if (!_state.table[index].data && (foundIndex < 0)) { foundIndex = index; }

            if (!_state.table[index].dirty) { done = True; }
            else {

               if ((_state.table[index].key == Key) && _state.table[index].data) {

                  done = True;
                  foundIndex = -1;
               }
               else {

                  index++;
                  if (index >= _state.size) { index = 0; }
                  if (index == StartIndex) { done = True; }
               }
            }
         }

         if (foundIndex >= 0) {

            result = True;
            _state.count++;

            _state.table[foundIndex].prev = 0;
            _state.table[foundIndex].next = 0;
            _state.table[foundIndex].key = Key;
            _state.table[foundIndex].data = data;
            _state.table[foundIndex].dirty = True;

            if (_state.tail) {

               _state.table[foundIndex].prev = _state.tail;
               _state.tail->next = &(_state.table[foundIndex]);
               _state.tail = &(_state.table[foundIndex]);
            }
            else {

               _state.head = _state.tail = &(_state.table[foundIndex]);
            }
         }
      }
   }

   return result;
}
コード例 #29
0
ファイル: my_stack.cpp プロジェクト: Atsanda/tasks
    void MyStack::push(int val)
    {
        *(mem_p + size()) = val;

        grow();
    }
コード例 #30
0
ファイル: parsemeta.c プロジェクト: hhirsch/netrek
static void version_r(struct sockaddr_in *address) {
  char *p;
  int servers, i;
  time_t now = time(NULL);

  /* number of servers */
  p = strtok(NULL,"\n");
  if (p == NULL) return;
  servers = atoi(p);

  /* sanity check on number of servers */
  if (servers > 2048) return;
  if (servers < 0) return;

  if (verbose) fprintf(stderr,
                       "metaserver at %s responded with %d server%s\n",
                       inet_ntoa(address->sin_addr),
                       servers,
                       servers == 1 ? "" : "s" );

  if (servers == 0) return;

  /* for each server listed by this metaserver packet */
  for(i=0;i<servers;i++) {
    struct servers *sp = NULL;
    char *host, type;
    int port, status, age, players, queue, throwaway;

    throwaway = 0;

    host = strtok(NULL,",");            /* hostname */
    if (host == NULL) continue;

    p = strtok(NULL,",");               /* port */
    if (p == NULL) continue;
    port = atoi(p);

    p = strtok(NULL,",");               /* status */
    if (p == NULL) continue;
    status = atoi(p);

    /* ignore servers based on status */
    if (status > statusLevel)
      throwaway++;
    /* the sp->why_dead workaround */
    if (status == 6)
      if ((status - 3) <= statusLevel)
        throwaway--;

    p = strtok(NULL,",");               /* age (of data in seconds) */
    if (p == NULL) continue;
    age = atoi(p);

    p = strtok(NULL,",");               /* players */
    if (p == NULL) continue;
    players = atoi(p);

    p = strtok(NULL,",");               /* queue size */
    if (p == NULL) continue;
    queue = atoi(p);

    p = strtok(NULL,"\n");              /* server type */
    if (p == NULL) continue;
    type = p[0];

    /* ignore paradise servers */
    if (type == 'P') throwaway++;

    /* if it's to be thrown away, do not add this server, skip to next */
    if (throwaway) continue;

    /* find in current server list? */
    sp = server_find(host, port);

    /* if it was found, check age */
    if (sp != NULL) {
      if ((now-age) < (sp->when-sp->age)) {
        sp->age = now - (sp->when-sp->age);
        sp->when = now;
        sp->refresh = 1;
        sp->lifetime = 20;
        continue;
      } else {
        sp->age = age;
        sp->when = now;
        sp->lifetime = 20;
      }
    } else {
      /* not found, store it at the end of the list */
      grow(1);
      sp = serverlist + num_servers;
      num_servers++;
      strncpy(sp->address,host,LINE);
      sp->port = port;
      sp->age = age;
      sp->when = now;
      sp->lifetime = 4;
    }
    sp->refresh = 1;

    /* from meta.h of metaserver code */
#define SS_WORKING 0
#define SS_QUEUE 1
#define SS_OPEN 2
#define SS_EMPTY 3
#define SS_NOCONN 4
#define SS_INIT 5
    /* not a real metaserver number, but overcomes a limitation of dropping text */
    /* description of sp->why_dead */
#define SS_TOUT 6
    switch (status) {
    case SS_QUEUE:
      sp->status = statusWait;
      sp->players = queue;
      break;
    case SS_OPEN:
      sp->status = statusOpen;
      sp->players = players;
      break;
    case SS_EMPTY:
      sp->status = statusNobody;
      sp->players = 0;
      break;
    case SS_TOUT:
      sp->status = statusTout;
      sp->players = 0;
      break;
    case SS_NOCONN:                     /* no connection */
    case SS_WORKING:            /* metaserver should not return this */
    case SS_INIT:                       /* nor this */
    default:
      sp->status = statusNoConnect;
      sp->players = 0;
      break;
    }
    sp->typeflag = type;
    strcpy(sp->comment, "");
    sp->pid = -1;
    sp->exitstatus = 0;
    sp->observer = 0;
  }
}