示例#1
0
    vector<string> fullJustify(vector<string> &words, int L) 
	{
		vector<string> justificated;
		int n = words.size();
		if (words.empty())
			return justificated;
		for (int i = 0; i < n; ++ i)
		{
			int length = 0;
			vector<string> line;
			length += words[i].size();
			line.push_back(words[i]);
			while (true)
			{
				if (i == n-1 || length + 1 + words[i+1].size() > L) {
					break;
				}
				++ i;
				length += (words[i].size() + 1);
				line.push_back(words[i]);				
			}
			int leftSpace = L - length;
			int spaceNum = line.size() - 1;
			string lineStr = "";
			// For the last line of text, it should be left justified and no extra space is inserted between words.
			if (i == n-1)
			{
				lineStr += line[0];
				for (int j = 1; j < line.size(); ++ j)
				{
					lineStr += " ";
					lineStr += line[j];
				}
				if (lineStr.size() < L)
					lineStr += getSpace(L-lineStr.size());
				justificated.push_back(lineStr);
				break;
			}
			if (spaceNum == 0) {
				lineStr = line[0] + getSpace(leftSpace);
				justificated.push_back(lineStr);
			} else {
				int a = leftSpace / spaceNum;
				int b = leftSpace % spaceNum;
				lineStr += line[0];
				for (int j = 1; j < line.size(); ++ j)
				{
					int temp = a;
					if (b > 0) {
						b --;
						temp += 1;
					}
					lineStr += getSpace(temp + 1);
					lineStr += line[j];
				}
				justificated.push_back(lineStr);
			}
		}
		return justificated;
    }
void ofxBoundaryBehavior::draw()
{
    ofNoFill();
    ofSetColor(255, 100);
    ofDrawBox(0,0,0, xMax-xMin, yMax-yMin, zMax-zMin);
    ofSetColor(255, 0, 0, 100);
    ofDrawBox(0,0,0, xMax-xMin - getSpace()*2.0, yMax-yMin - getSpace()*2.0, zMax-zMin - getSpace()*2.0);
}
示例#3
0
void Spacing::writeFile(ostream & os, bool para) const
{
	if (space == Default) return;

	string cmd = para ? "\\paragraph_spacing " : "\\spacing ";

	if (getSpace() == Spacing::Other) {
		os << cmd << spacing_string[getSpace()]
		   << ' ' << getValueAsString() << "\n";
	} else {
		os << cmd << spacing_string[getSpace()] << "\n";
	}
}
ExFastExtractTcb::~ExFastExtractTcb()
{
  // Release resources acquired
  //
  freeResources();

  delete qParent_.up;
  delete qParent_.down;
 
  if (workAtp_)
  {
    workAtp_->release();
    deallocateAtp(workAtp_, getSpace());
  }

  if (inSqlBuffer_ && getHeap())
  {
    getHeap()->deallocateMemory(inSqlBuffer_);
    inSqlBuffer_ = NULL;
    childOutputTD_ = NULL;
  }
  if (sourceFieldsConvIndex_)
    getHeap()->deallocateMemory(sourceFieldsConvIndex_);

} // ExFastExtractTcb::~ExFastExtractTcb()
bool SlottedPage::update(uint16_t slotId, uint16_t len, const char* data){

//if the length of new data is same as or smaller than old data, then update in place
//if the length is bigger than old data, but can be contained in this page, insert the new data to front
//otherwise, make an indirection to another page(done in SPSegment::update)
	Slot &slot = slots[slotId];
	if(len <= slot.length){
		memcpy(records + slot.offset, data, len);
		slot.length = len;
		header.freeSpace += (slot.length - len);
		return true;
	}else{
		if(getSpace() >= len){
			uint16_t offset = header.dataStart - len + 1;
			memcpy(records + offset, data, len);
			header.spaceLeft -= len;
			header.freeSpace += slot.length;
			header.freeSpace -= len;
			slot.offset = offset;
			slot.length = len;
			return true;
		}
	}
		
	return false;
}
示例#6
0
文件: svg_out.c 项目: grossman/mscgen
void SvgTextC(struct ADrawTag *ctx,
              unsigned int     x,
              unsigned int     y,
              const char      *string,
              const char      *url)
{
    SvgContext  *context = getSvgCtx(ctx);
    unsigned int hw = SvgTextWidth(ctx, string) / 2;

    svgRect(ctx, getSvgBgPen(ctx), x - (hw + 2), y - SvgTextHeight(ctx) + 1, x + hw, y - 1);

    y += getSpace(ctx, SvgHelvetica.descender);

    if(url)
    {
        fprintf(getSvgFile(ctx), "<a xlink:href=\"%s\">", url);
    }

    fprintf(getSvgFile(ctx),
            "<text x=\"%u\" y=\"%u\" textLength=\"%u\" font-family=\"Helvetica\" font-size=\"%u\" fill=\"%s\" text-anchor=\"middle\">",
            x, y, SvgTextWidth(ctx, string), context->fontPoints, context->penColName);
    writeEscaped(ctx, string);
    fprintf(getSvgFile(ctx), "</text>\n");

    if(url)
    {
        fprintf(getSvgFile(ctx), "</a>", url);
    }
}
示例#7
0
std::map<std::string, int> h5n(
  const string &file
)
{
  H5::H5File h5f(file + "/coord.h5", H5F_ACC_RDONLY);
  hsize_t n[2];
  std::map<std::string, int> map;

  h5f.openDataSet("T").getSpace().getSimpleExtentDims(n, NULL);
  map["t"] = n[0];

  {
    auto h5d = h5f.openDataSet("T");

    float dt;
    {
      auto attr = h5d.openAttribute("dt");
      attr.read(attr.getDataType(), &dt);
    }

    auto h5s = h5d.getSpace();
    const hsize_t two = 2, zero = 0;
    float tmp[2];
    h5s.selectHyperslab( H5S_SELECT_SET, &two, &zero);
    h5d.read(tmp, H5::PredType::NATIVE_FLOAT, H5::DataSpace(1, &two), h5s);
    map["outfreq"] = (tmp[1] - tmp[0]) / dt;
  }

  h5f.openDataSet("X").getSpace().getSimpleExtentDims(n, NULL); // X gives cell-border coordinates (+1)
  map["x"] = n[0]-1;
  map["z"] = n[1]-1;

  return map;
}
示例#8
0
MVector2 MGuiTextureFont::getCharacterPosition(const char * text, const MVector2 & position, const float size, const unsigned int charId)
{
	MVector2 pos;
	float xc = position.x;
	float yc = position.y;
	
	unsigned int i;
	unsigned int tSize = strlen(text);
	for(i=0; i<charId && i<tSize; i++)
	{
		if(text[i] == '\n')	// return
		{
			yc += size;
			xc = position.x;
		}
		else if(text[i] == '	') // tab
		{
			xc += size * getTabSpace();
		}
		else
		{		
			xc += size * getSpace(); // move to next character
		}
	}

	pos.x = xc;
	pos.y = yc;

	return pos;
}
示例#9
0
bool placeShip(int size, COORDINATE* where, char direction, PLAYER* whom)
{
	int dist;
	COORDINATE target;
	
	//Make sure all of the spaces are clear (water)
	copyCoord(where, &target);
	dist=0;
	while(dist<size)
	{
		if(getSpace(&target, whom->board) != BOARD_WATER)
		{
			return error("Could not place ship there\n");
		}
		moveCoord(&target, 1, direction);
		dist++;
	}

	//Clear for placement!
	whom->hits += size; //Keep track of remaining hits

	//Place ship bits
	for(dist=0, copyCoord(where, &target); dist<size; dist++, moveCoord(&target, 1, direction))
	{
		setShip(&target, whom);
	}
	return true; //Success!
}
void ExProbeCacheTcb::freeResources()
{
  if (pool_) 
    {
      delete pool_;
      pool_ = NULL;
    }

  if (qparent_.up)
    {
      delete qparent_.up;
      qparent_.up = NULL;
    }
  
  if (qparent_.down)
    {
      delete qparent_.down;
      qparent_.down = NULL;
    }

  if (probeBytes_)  
    {
      NADELETEBASIC(probeBytes_, getSpace());
      probeBytes_ = NULL;
    }

  if (pcm_)
    {
      delete pcm_;
      pcm_ = NULL;
    }
}
示例#11
0
int main(int argc, char *argv[])
{
    unsigned char* image;
    int c,nBytes;
    unsigned char *bits;
    int char_height, char_width;
    int baseline_position, overline_thickness, space_left, space_right;
    char *prefix;
    char *charSet = " !#%'()*+,-./0123456789:<=>?ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_"
                    "abcdefghijklmnopqrstuvwxyz¡£«­°¹²³µ¶·»¼¿ÅÐØÞßãëð";
    unsigned char *charXOff = (unsigned char*)malloc(strlen(charSet));
    unsigned char *charWidth = (unsigned char*)malloc(strlen(charSet));
    unsigned char *charItalicOffset = (unsigned char*)malloc(strlen(charSet));
    FILE *f;

    if (argc<4 || (image=readImage(argv[1],&iW,&iH))==0 || iW%32!=0 || iH%6!=0) {
        printf("Usage: %s image.pgm prefix out.dat > out.java\n",argv[0]);
        exit(1);
    }
    prefix = argv[2];

    char_width = iW/32;
    char_height = iH/6;
    getBaselinePosition(image,'E',char_height,char_width,&baseline_position);
    getOverline(image,'¿',char_height,char_width,&overline_thickness);
    getSpace(image,'H',char_height,char_width,&space_left,&space_right);

    nBytes = (char_height*char_width*2+7)/8;
    bits = (unsigned char*)malloc(nBytes);

    f = fopen(argv[3],"w");
    for (c=0; c<(int)strlen(charSet); c++) {
        scan(image,charSet[c],char_height,char_width,bits);
        getWidth(image,charSet[c],char_height,char_width,space_left,space_right,
                 &charXOff[c],&charWidth[c]);
        getItalicOffset(image,charSet[c],char_height,char_width,
                        charXOff[c],charWidth[c],&charItalicOffset[c]);
        fwrite(bits,1,nBytes,f);
    }
    for (c=0; c<(int)strlen(charSet); c++)
        fwrite(charXOff+c,1,1,f);
    for (c=0; c<(int)strlen(charSet); c++)
        fwrite(charWidth+c,1,1,f);
    for (c=0; c<(int)strlen(charSet); c++)
        fwrite(charItalicOffset+c,1,1,f);
    fclose(f);

    printf("    static final String %sCharBitsResource = \"/%s\";\n",prefix,
           argv[3]);
    printf("    static final int %sCharMaxWidth = %d;\n",prefix,char_width/2);
    printf("    static final int %sCharHeight = %d;\n",prefix,char_height);
    printf("    static final int %sBaselinePosition = %d;\n",prefix,baseline_position);
    printf("    static final int %sOverlineThickness = %d;\n",prefix,overline_thickness);
    printf("    static final String %sCharSet =\n        \"",prefix);
    for (c=0; c<(int)strlen(charSet); c++)
        printStringChar(charSet[c]);
    printf("\";\n\n");
    return 0;
}
void t_Str::resize(size_t chars)
{
	size_t len = getLength();
	char *ptr;

	if(len >= chars)
		len = chars - 1;

	++len;

	if(!isBig() && chars <= minsize)
		return;

	if(!isBig())
	{
		ptr = getSpace(chars);
		memmove(ptr, content.ministring.text, len); 
		ptr[--len] = 0;
		content.ministring.big = true;
		content.bigstring.text = ptr;
		content.bigstring.length = len;
		setSize(chars);
		return;
	}
	
	if(chars <= minsize && getSize() > slotlimit)
	{
		ptr = getText();
		memmove(content.ministring.text, ptr, len);
		content.ministring.text[--len] = 0;
		content.ministring.big = false;
		content.ministring.length = (unsigned)len;
		delete[] ptr;
		return;
	}

	ptr = getSpace(chars);
	memmove(ptr, getText(), len);
	ptr[--len] = 0;
	clear();
	setSize(chars);
	content.bigstring.length = len;
	content.bigstring.text = ptr;
	content.ministring.big = true;
}
示例#13
0
NABoolean
ComSqlTextHandle::isSpace(const char &aChar) const
{
  if (aChar EQU getSpace())
  {
    return TRUE;
  }
  return FALSE;
}
示例#14
0
bool Manifold::Point::isInManifold() {
	std::vector<Manifold::PortalPtr>* portals = getSpace()->getPortals();
	for(int i=0; i<portals->size(); ++i) {
		if((*portals)[i]->containsPoint(this)) {
			return false;
		}
	}
	return true;
}
示例#15
0
void MGuiTextureFont::draw(const char * text, const MVector2 & position, float size)
{
	MRenderingContext * render = MGui::getInstance()->getRenderingContext();

	MVector2 g_vertices[4];
	MVector2 g_texCoords[4];

	float xc=position.x, yc=position.y, u=0, v=0;

	render->disableNormalArray();
	render->disableColorArray();
	render->enableVertexArray();
	render->enableTexCoordArray();

	render->setVertexPointer(M_FLOAT, 2, g_vertices);
	render->setTexCoordPointer(M_FLOAT, 2, g_texCoords);

	render->bindTexture(m_texture);

	unsigned int i;
	unsigned int textLength = strlen(text);
	for(i=0; i<textLength; i++)
	{
		if(text[i] == '\n')	// return
		{
			yc += size;
			xc = position.x;
		}
		else if(text[i] == '	') // tab
		{
			xc += size * getTabSpace();
		}
		else
		{
			u=float((unsigned char)text[i]%16)/16.0f; //u position of character
			v=float((unsigned char)text[i]/16)/16.0f; //v position of character

			g_texCoords[0] = MVector2(u, v+0.0625f);
			g_vertices[0] = MVector2(xc, yc+size);						
			
			g_texCoords[1] = MVector2(u+0.0625f, v+0.0625f);	
			g_vertices[1] = MVector2(xc+size, yc+size);							
			
			g_texCoords[3] = MVector2(u+0.0625f, v+0.001f);	
			g_vertices[3] = MVector2(xc+size, yc);							
			
			g_texCoords[2] = MVector2(u, v+0.001f);				
			g_vertices[2] = MVector2(xc, yc);

			render->drawArray(M_PRIMITIVE_TRIANGLE_STRIP, 0, 4);

			xc += size * getSpace(); //move to next character
		}
	}
}
示例#16
0
//
// Constructor for sort_grby_tcb
//
ex_sort_grby_tcb::ex_sort_grby_tcb(const ex_sort_grby_tdb &  sort_grby_tdb, 
				   const ex_tcb &    child_tcb,   // child queue pair
				   ex_globals * glob
				    ) : 
    ex_tcb( sort_grby_tdb, 1, glob),
    pool_(NULL)
{
  Space * space = (glob ? glob->getSpace() : 0);
  CollHeap * heap = (glob ? glob->getDefaultHeap() : 0);
  
  childTcb_ = &child_tcb;

  // Allocate the buffer pool
#pragma nowarn(1506)   // warning elimination 
  pool_ = new(space) ExSimpleSQLBuffer(sort_grby_tdb.numBuffers_,
				       sort_grby_tdb.bufferSize_,
		                       recLen(),
				       space);
#pragma warn(1506)  // warning elimination 

  // get the child queue pair
  qchild_  = child_tcb.getParentQueue(); 

  // Allocate the queue to communicate with parent
  allocateParentQueues(qparent_);

  // Intialize processedInputs_ to the next request to process
  processedInputs_ = qparent_.down->getTailIndex();

  // allocate work atp
  workAtp_ = allocateAtp(sort_grby_tdb.criDescUp_,getSpace());

  // fixup aggr expression
  if (aggrExpr())
    (void) aggrExpr()->fixup(0, getExpressionMode(), this, space, heap,
			     glob->computeSpace());

  // fixup move expression
  if (moveExpr())
    (void) moveExpr()->fixup(0, getExpressionMode(), this, space, heap,
			     glob->computeSpace());

  // fixup grby expression
  if (grbyExpr())
    (void) grbyExpr()->fixup(0, getExpressionMode(), this, space, heap,
			     glob->computeSpace());

  // fixup having expression
  if (havingExpr())
    (void) havingExpr()->fixup(0, getExpressionMode(), this, space, heap,
			       glob->computeSpace());

}
示例#17
0
MVector2 MGuiTextureFont::getMaxSize(const char * text, const float size)
{
	MVector2 max;
	float xc=0, yc=0;
	
	max.set(0, 0);

	unsigned int i;
	unsigned int tSize = strlen(text);
	for(i=0; i<tSize; i++)
	{
		if(text[i] == '\n') // return
		{
			yc += size;
			xc = 0;

			if(yc > max.y) max.y = yc;
		}
		else if(text[i] == '	') // tab
		{
			xc += size * getTabSpace(); //move to next character

			if(xc > max.x) max.x = xc;
		}
		else
		{
			xc += size * getSpace(); //move to next character

			if(xc > max.x) max.x = xc;
		}
	}

	max.x += size * getSpace();
	max.y += size;

	return max;
}
示例#18
0
int Solver::score(std::vector<Move> a)
{
	int res = 0;
	for (int i = 1; i < (int) a.size(); i++)
		res+= getSpace(a, i) * 100;

	res+= floatingScore(a) * 1000;

	int unstableCounter = 0;
	std::vector<Block> c = std::vector<Block>();
	for (int i = 0; i < (int) a.size(); i++) {
		if (a[i].left != Move::NO_BLOCK)
			c.push_back(blocks[a[i].left]);
		if (a[i].right != Move::NO_BLOCK)
			c.push_back(blocks[a[i].right]);
		if (!checkStability(c)) {
			if (a[i].mode == Move::TWO_HANDS)
				unstableCounter++;
			unstableCounter++;
		}
	}
	res+= unstableCounter * 1000;

	for (int i = 0; i < (int) a.size(); i++) {
		if (a[i].mode == Move::TWO_HANDS) {
			res+= 5;
			if (blocks[a[i].left].isOn(blocks[a[i].right]) ||
					blocks[a[i].right].isOn(blocks[a[i].left]))
				res+= 1000;

			if (blocks[a[i].right].x < blocks[a[i].left].x) {
				res+= 1000;
			}
		}
	}

	int counter = 0;
	for (int i = 0; i < (int) a.size(); i++) {
		if (a[i].left != Move::NO_BLOCK)
			counter++;
		if (a[i].right != Move::NO_BLOCK)
			counter--;
	}
	counter = counter < 0 ? -counter : counter;
	res+= counter * 5;

	return -res;
}
示例#19
0
// returns 0 if NOT in check after the move
// return 1 if in check after the move
int simCheck(struct board * b, struct piece * p, struct pos * move, struct piece * k )
{
	struct piece * inactivePiece = NULL;
	struct pos * tempLoc;
	struct board * nBoard = copyBoard(b);

	struct pos * nMove = makeLoc(move->x, move->y);
	nMove->type = move->type;
	if(move->type ==4)
	{
		nMove->additionalM1 = move->additionalM1;
		nMove->additionalM2 = move->additionalM2;
		nMove->additionalP = getSpace(nBoard, move->x, move->y);
	}
 	int temp = getOrder(b, p);
	int temp1;
	if(move->taken != NULL)
	{
		temp1 = getOrder(b,move->taken);
		nMove->taken = nBoard->pieces[temp1];
	}
	else{
		nMove->taken = NULL;
	}

//	printAllMoves(nBoard);
	movePiece(nBoard,nBoard->pieces[temp],nMove);
	updateAllMovesSim(nBoard);
	free(nMove);

	if(move->type == 4)
	{
		if(incheckCheck(nBoard,move->additionalP,move->additionalP->loc) == 1)
		{
			deleteBoard(nBoard);
			return 1;
		}
		deleteBoard(nBoard);
		return 0;
	}
	if(incheckCheck(nBoard,k,k->loc) == 1)
	{
		deleteBoard(nBoard);
		return 1;
	}
	deleteBoard(nBoard);
	return 0;
}
示例#20
0
bool checkForHit(COORDINATE* where, PLAYER* whom)
{
	char actual = getSpace(where, whom->board);
	if(actual == BOARD_SHIP) {
		setSpace(where, whom->board, GRID_HIT);
		setSpace(where, whom->view, GRID_HIT);
		whom->hits --;
		return true;
	} else if(actual == BOARD_WATER) {
		setSpace(where, whom->board, GRID_SPLOOSH);
		setSpace(where, whom->view, GRID_SPLOOSH);
		return false;
	} else {
		setSpace(where, whom->board, GRID_BAD);
		setSpace(where, whom->view, GRID_BAD);
		return false;
	}
}
示例#21
0
文件: svg_out.c 项目: grossman/mscgen
unsigned int SvgTextWidth(struct ADrawTag *ctx,
                          const char *string)
{
    unsigned long width = 0;

    while(*string != '\0')
    {
        int           i = *string & 0xff;
        unsigned long w = SvgHelvetica.widths[i];

        /* Ignore undefined characters */
        width += w > 0 ? w : 0;

        string++;
    }

    return getSpace(ctx, width);
}
示例#22
0
void String::copy(const String &original)
{
    clear();

    if(original.getLength() < minsize) {
        content.ministring.length = (unsigned)original.getLength();
        memmove(content.ministring.text, original.getText(), original.getLength() + 1);
        content.ministring.big = false;
        return;
    }

//  ptr = original.getText();
    content.bigstring.length = original.getLength();
    content.bigstring.size = setSize(original.getLength() + 1);
    content.bigstring.text = getSpace(original.getLength() + 1);
    content.ministring.big = true;
    memmove(content.bigstring.text, original.getText(), original.getLength() + 1);
}
示例#23
0
/* returns 2 if the move caused a promotion
 * returns 1 if valid
 * returns -1 if invalid m1
 * returns -2 if invalid m2
 * returns -3 if not your turn
 */
int tryMove(struct board* b,int x1,int y1,int x2,int y2, int player)
{
	if(player != b->currentPlayer)
	{
		return -3;
	}

	struct pos * m1 = makeLoc(x1,y1);
	struct pos * m2 = makeLoc(x2,y2);

	struct piece * mover = getSpace(b,x1,y1);
	if(mover == NULL)
	{
				return -1;
	}
	if(mover->player != b->currentPlayer)
		return -1;

	struct pos * m3 = validMoveForPiece(mover,m2);

	free(m1);
	free(m2);

	if(m3 != NULL)
	{
		movePiece(b, mover, m3);
		updateAllMoves(b);

		if(checkPromotion(b))
		{
			b->currentPlayer = (b->currentPlayer+1)%2;
			return 2;
		}
		return 1;
	}
	else
	{
		return -2;
	}
}
示例#24
0
void CStation::addAgent( CAgent& agent )
{
	// Increase the enter event count
	setEnterEventCount( getEnterEventCount() + 1 );

	//  If has necessity attribute
	if( getStationType().getHasNecessity() )
	{
		// Increase the necessity count for its entering agent
		setNecessity( agent, getNecessity( agent ) + 1 );
	}

	// Add the agent to list of currently visiting agents
	visitingAgents.push_back( &agent );

	// If the agent has a size attribute, set its size on this station to its normal size
	if( agent.getAgentType().getHasSize() )
	{
		agent.setSizeOnCurrentStation( agent.getAgentType().getSize() );
	}

	// If the station has a space attribute and the agent type has a size attribute, add size
	if( getStationType().getHasSpace() && agent.getAgentType().getHasSize() )
	{
		space = space + agent.getSizeOnCurrentStation();
	}

	// else if station type has a space attribute
	else if( getStationType().getHasSpace() )
	{
		// Store the agent's size on this station
		agent.setSizeOnCurrentStation( getStationType().getSpace() - getSpace() );

		// Set space to maximum
		space = getStationType().getSpace();
	}
}
示例#25
0
void printGrid(char grid[8][8])
{
	COORDINATE target;
	char symbol;
	for(int r=-1; r<8; r++)
	{
		for(int c=-1; c<8; c++)
		{
			if(r>=0 && c>=0)
			{
				setCoord(&target, c, r);
				symbol=getSpace(&target, grid);
				printf("%c", symbol);
			} 
			else //In row, column, or both
			{
				if(c<0 && r<0) printf("   ");
				if(c<0 && r>=0) printf("%2d ", MIN_ROW+r); //Show row numbers
				if(r<0 && c>=0) printf("%c", MIN_COL+c); //Show col letters
			}
		}
		printf("\n");
	}	
}
示例#26
0
文件: malloc.c 项目: Juncai/CS5600
void *malloc(size_t size)
{
	// add arena info for the current thread to the process info queue
	pthread_once(&once_control, &init);
	/* if (info->init == 0) { */
	if (info == NULL) {
		initArenaInfo();
	}

	void *sPtr = NULL;
	size_t realSize = size + sizeof(MallocHeader);
	if (size > MAX_SIZE) {	// for large space
		sPtr = mmap(NULL, realSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
		// handle MAP_FAILED
		if (sPtr == MAP_FAILED) return NULL;
		MallocHeader *hdr = (MallocHeader*) sPtr;
		hdr->size = realSize;
		ulEnqueue(-1, hdr);
		info->mmapSpace += realSize;
#if TEST > 0
		printf("%s:%d malloc(%zu): Allocated %zu bytes at %p\n",
			 __FILE__, __LINE__, size, realSize, sPtr);
#endif
	} else {	// handle small memory requests
		int binNo = sizeToBinNo(size);
		info->mallocCount[binNo]++;
		sPtr = getSpace(binNo);
		if (sPtr == NULL) return NULL;
		
#if TEST > 0
		printf("%s:%d malloc(%zu): Allocated %zu bytes at %p\n",
			 __FILE__, __LINE__, size, ((MallocHeader*)sPtr)->size, sPtr);
#endif
	}
	return sPtr + sizeof(MallocHeader);
}
void* CDVRPTRControllerV2::Entry()
{
	wxLogMessage(wxT("Starting DV-RPTR2 Modem Controller thread"));

	// Clock every 5ms-ish
	CTimer pollTimer(200U, 0U, 250U);

	pollTimer.start();

	while (!m_stopped) {
		// Poll the modem status every 250ms
		if (pollTimer.hasExpired()) {
			bool ret = getSpace();
			if (!ret) {
				ret = findModem();
				if (!ret) {
					wxLogMessage(wxT("Stopping DV-RPTR2 Modem Controller thread"));
					return NULL;
				}
			}

			pollTimer.reset();
		}

		unsigned int length;
		RESP_TYPE_V2 type = getResponse(m_buffer, length);

		switch (type) {
			case RT2_TIMEOUT:
				break;

			case RT2_ERROR: {
					bool ret = findModem();
					if (!ret) {
						wxLogMessage(wxT("Stopping DV-RPTR2 Modem Controller thread"));
						return NULL;
					}
				}
				break;

			case RT2_HEADER: {
					// CUtils::dump(wxT("RT2_HEADER"), m_buffer, length);
					m_mutex.Lock();

					unsigned int space = m_rxData.freeSpace();
					if (space < 57U) {
						wxLogMessage(wxT("Out of space in the DV-RPTR RX queue"));
					} else {
						unsigned char data[2U];
						data[0U] = DQT_HEADER;
						data[1U] = RADIO_HEADER_LENGTH_BYTES;
						m_rxData.addData(data, 2U);
						m_rxData.addData(m_buffer + 9U, RADIO_HEADER_LENGTH_BYTES - 2U);

						// Dummy checksum
						data[0U] = 0xFFU;
						data[1U] = 0xFFU;
						m_rxData.addData(data, 2U);

						data[0U] = DQT_DATA;
						data[1U] = DV_FRAME_LENGTH_BYTES;
						m_rxData.addData(data, 2U);
						m_rxData.addData(m_buffer + 51U, DV_FRAME_LENGTH_BYTES);

						m_rx = true;
					}

					m_mutex.Unlock();
				}
				break;

			case RT2_DATA: {
					// CUtils::dump(wxT("RT2_DATA"), m_buffer, length);
					m_mutex.Lock();

					unsigned int space = m_rxData.freeSpace();
					if (space < 16U) {
						wxLogMessage(wxT("Out of space in the DV-RPTR RX queue"));
					} else {
						unsigned char data[2U];
						data[0U] = DQT_DATA;
						data[1U] = DV_FRAME_LENGTH_BYTES;
						m_rxData.addData(data, 2U);
						m_rxData.addData(m_buffer + 51U, DV_FRAME_LENGTH_BYTES);

						m_rx = true;

						// End of transmission?
						if ((m_buffer[50U] & 0x40U) == 0x40) {
							data[0U] = DQT_EOT;
							data[1U] = 0U;
							m_rxData.addData(data, 2U);

							m_rx = false;
						}
					}

					m_mutex.Unlock();
				}
				break;

			case RT2_SPACE:
				m_space = m_buffer[9U];
				// CUtils::dump(wxT("RT2_SPACE"), m_buffer, length);
				break;

			// These should not be received in this loop, but don't complain if we do
			case RT2_QUERY:
			case RT2_CONFIG:
				break;

			default:
				wxLogMessage(wxT("Unknown DV-RPTR2 message, type"));
				CUtils::dump(wxT("Buffer dump"), m_buffer, length);
				break;
		}

		if (m_space > 0U) {
			if (!m_txData.isEmpty()) {
				m_mutex.Lock();

				unsigned char len = 0U;
				m_txData.getData(&len, 1U);

				unsigned char data[200U];
				m_txData.getData(data, len);

				m_mutex.Unlock();

				// CUtils::dump(wxT("Write"), data, len);

				int ret = m_serial.write(data, len);
				if (ret == -1) {
					bool ret = findModem();
					if (!ret) {
						wxLogMessage(wxT("Stopping DV-RPTR2 Modem Controller thread"));
						return NULL;
					}
				} else {
					m_space--;
				}
			}
		}

		Sleep(5UL);

		pollTimer.clock();
	}

	wxLogMessage(wxT("Stopping DV-RPTR2 Modem Controller thread"));

	m_serial.close();

	return NULL;
}
示例#28
0
int
main(int argc, char **argv) {
  // Try block to detect exceptions raised by any of the calls inside it
  try {
    // Turn off the auto-printing when failure occurs so that we can
    // handle the errors appropriately
    H5std_string FILE_NAME(argv[1]);
    Exception::dontPrint();

    // Open the file and the dataset in the file.
    H5File file(FILE_NAME, H5F_ACC_RDONLY);

    DataSet dataset;
    H5std_string dataset_name;
    auto objCount(H5Fget_obj_count(file.getId(), H5F_OBJ_ALL));
    for (size_t i = 0; i != objCount; ++i)
      if (H5G_DATASET == file.getObjTypeByIdx(i)) {
	dataset_name = file.getObjnameByIdx(i);
	dataset = file.openDataSet(dataset_name);
      }

    auto datatype(dataset.getDataType());
    auto dataspace(dataset.getSpace());

    hsize_t dims_in[2];
    auto ndims(dataspace.getSimpleExtentDims(dims_in, NULL));

    hsize_t dims_out[2] = { DIM0, DIM1 };	// dataset dimensions

    double *buf = new double[dims_in[0] * dims_in[1]];

    // Read data.
    dataset.read(buf, PredType::NATIVE_DOUBLE);//, memspace, dataspace);

    H5std_string outFileName("out.h5");

    // Create a new file using the default property lists. 
    H5File outfile(outFileName, H5F_ACC_TRUNC);

    // Create the data space for the dataset.
    DataSpace *output_dataspace = new DataSpace(ndims, dims_out);

    hsize_t chunk_dims[2] = { 20, 20 };	// chunk dimensions
    // Modify dataset creation property to enable chunking
    DSetCreatPropList *plist = new DSetCreatPropList;
    plist->setChunk(2, chunk_dims);

    // Set ZLIB (DEFLATE) Compression using level 9.
    plist->setDeflate(9);

    // Create the attributes.
    const size_t numAttrs = file.getNumAttrs();
    for (size_t i = 0; i != numAttrs; ++i) {
      auto attr(file.openAttribute(i));
      auto output_attr(outfile.createAttribute(attr.getName(), 
					       attr.getDataType(), 
					       attr.getSpace()));

      switch (attr.getTypeClass()) {
      case H5T_FLOAT: {
	double buf;
    	attr.read(attr.getDataType(), &buf);
    	output_attr.write(attr.getDataType(), &buf);
      }
	break;
      case H5T_STRING: {
	char *buf = new char[(unsigned long)attr.getStorageSize()];
    	attr.read(attr.getDataType(), buf);
    	output_attr.write(attr.getDataType(), buf);
	delete buf;
      }
	break;
      default:
	break;
      }
    }

    // Create the dataset.      
    DataSet *output_dataset = new DataSet(outfile.createDataSet(dataset_name, datatype, *output_dataspace, *plist));

    // Write data to dataset.
    output_dataset->write(buf, datatype);

    // Close objects and file.  Either approach will close the HDF5 item.
    delete output_dataspace;
    delete output_dataset;
    delete plist;
    file.close();
  }  // end of try block

  // catch failure caused by the H5File operations
  catch(FileIException &error) {
    error.printError();
    return -1;
  }

  // catch failure caused by the DataSet operations
  catch(DataSetIException &error) {
    error.printError();
    return -1;
  }

  // catch failure caused by the DataSpace operations
  catch(DataSpaceIException &error) {
    error.printError();
    return -1;
  }

  // catch failure caused by the Attribute operations
  catch (AttributeIException &error) {
    error.printError();
    return -1;
  }

  catch (std::exception &error) {
    std::cerr << error.what() << std::endl;
    return -1;
  }

  return 0;  // successfully terminated
}
示例#29
0
void MGuiTextureFont::drawSelection(const char * text, const MVector2 & position, float size, unsigned int startId, unsigned int endId)
{
	MRenderingContext * render = MGui::getInstance()->getRenderingContext();

	if(startId == endId)
		return;

	MVector2 g_vertices[4];

	render->disableNormalArray();
	render->disableColorArray();
	render->disableTexCoordArray();
	render->enableVertexArray();

	render->setVertexPointer(M_FLOAT, 2, g_vertices);

	unsigned int start;
	unsigned int end;

	if(endId > startId)
	{
		start = startId;
		end = endId;
	}
	else
	{
		start = endId;
		end = startId;
	}

	render->disableTexture();

	MVector2 startPosition = getCharacterPosition(text, position, size, start);
	float xc = startPosition.x;
	float yc = startPosition.y;

	float offset = (size - (size*getSpace()))*0.5f;

	// left quad
	g_vertices[0] = MVector2(xc+offset, yc);
	g_vertices[1] = MVector2(xc+offset, yc+size);

	unsigned int i;
	unsigned int textLength = strlen(text);
	for(i=start; i<end && i<textLength; i++)
	{
		if(text[i] == '\n')	// return
		{
			// right quad
			{
				g_vertices[3] = MVector2(xc+size*0.5f, yc+size);							
				g_vertices[2] = MVector2(xc+size*0.5f, yc);
				render->drawArray(M_PRIMITIVE_TRIANGLE_STRIP, 0, 4);
			}

			yc += size;
			xc = position.x;

			// left quad
			{
				g_vertices[0] = MVector2(xc+offset, yc);
				g_vertices[1] = MVector2(xc+offset, yc+size);
			}
		}
		else if(text[i] == '	') // tab
		{
			xc += size * getTabSpace();

			if(i+1 == end || i+1 == textLength)
			{
				// right quad
				g_vertices[3] = MVector2(xc+offset, yc+size);							
				g_vertices[2] = MVector2(xc+offset, yc);
				render->drawArray(M_PRIMITIVE_TRIANGLE_STRIP, 0, 4);
			}
		}
		else
		{
			xc += size * getSpace(); //move to next character

			if(i+1 == end || i+1 == textLength)
			{
				// right quad
				g_vertices[3] = MVector2(xc+offset, yc+size);							
				g_vertices[2] = MVector2(xc+offset, yc);
				render->drawArray(M_PRIMITIVE_TRIANGLE_STRIP, 0, 4);
			}
		}
	}
}
示例#30
0
unsigned int MGuiTextureFont::findPointedCharacter(const char * text, const MVector2 & position, const float size, const MVector2 & point)
{
	float xc=position.x, yc=position.y;
	float halfSpace = getSpace() * 0.50001f;
	float halfTabSpace = getTabSpace() - halfSpace;
																
	unsigned int tSize = strlen(text);

	// if out (up) of the first line
	if(point.y <= yc){
		return 0;
	}

	// if out (left) of the first line
	if(point.x <= xc)
	if(point.y <= (yc + size) && point.y >= yc){
		return 0;
	}

	unsigned int i;
	for(i=0; i<tSize; i++)
	{
		if(point.x < (xc + (size*0.5001f)) && point.x >= (xc + (size*0.5001f) - (size*getSpace())))
		if(point.y < (yc + size) && point.y >= yc){
			return i;
		}

		if(text[i] == '\n')	// return
		{
			// if out (right) of a line
			if(point.x >= (xc + (size * halfSpace)))
			if(point.y <= (yc + size) && point.y >= yc){
				return i;
			}

			yc += size;
			xc = position.x;

			// if out (left) of a line
			if(point.x <= xc)
			if(point.y <= (yc + size) && point.y >= yc){
				return i + 1;
			}
		}
		else if(text[i] == '	') // tab
		{
			if(point.x < (xc + (size * halfTabSpace)) && point.x >= (xc + (size*0.5001f) - (size*getSpace())))
			if(point.y < (yc + size) && point.y >= yc){
				return i;
			}

			if(point.x < (xc + (size * getTabSpace()) + (size*0.5001f) - (size*getSpace())) && point.x >= (xc + (size * halfTabSpace)))
			if(point.y < (yc + size) && point.y >= yc){
				if((i+1) < tSize)
					return i+1;
			}

			xc += size * getTabSpace();
		}
		else
		{	
			xc += size * getSpace(); // move to next character
		}
	}

	return (unsigned int)tSize;
}