示例#1
0
void PcbXML::drawPad(QDomNode node){
	QDomElement element = node.toElement();
	QDomElement pad = m_svg->createElement("rect");
	
	// TODO: mask and keepout layers
	int x1 = qMin(element.attribute("rX1").toInt(),element.attribute("rX2").toInt()) + m_markx;
	int x2 = qMax(element.attribute("rX1").toInt(),element.attribute("rX2").toInt()) + m_markx;
	int y1 = qMin(element.attribute("rY1").toInt(),element.attribute("rY2").toInt()) + m_marky;
	int y2 = qMax(element.attribute("rY1").toInt(),element.attribute("rY2").toInt()) + m_marky;
	int thickness = element.attribute("Thickness").toInt();
	QString id = "connector" + QString::number(m_padCount) + "pad";
	
	m_padCount++;
	
	int x = x1 - (thickness/2);
	int y = y1 - (thickness/2);
	int width = x2 - x1 + thickness;
	int height = y2 -y1 + thickness;
	
	pad.setAttribute("x", x);
	pad.setAttribute("y", y);
	pad.setAttribute("width", width);
	pad.setAttribute("height", height);
	pad.setAttribute("fill", "rgb(255, 191, 0)");
	pad.setAttribute("id", id);
	
	QDomNode temp = m_copper.appendChild(pad);
	minMax(x,y,0);
	minMax(x+width,y+height,0);
}
示例#2
0
TEST_F(MinMaxTests, ThreeEntriesTests)
{
	const int numValues = 3;

	float floatValues[numValues] = { 22, 7, 52};
	float minFloatVal = 7;
	float maxFloatVal = 52;
	float floatMin;
	float floatMax;

	double doubleValues[numValues] = { -47, -2, -7};
	double minDoubleVal = -47;
	double maxDoubleVal = -2;
	double doubleMin;
	double doubleMax;

	std::sort(floatValues, floatValues + numValues);
	do
	{
		minMax(floatValues[0], floatValues[1], floatValues[2], &floatMin, &floatMax);
		EXPECT_EQ(minFloatVal, floatMin);
		EXPECT_EQ(maxFloatVal, floatMax);
	}
	while (std::next_permutation(floatValues, floatValues + numValues));

	std::sort(doubleValues, doubleValues + numValues);
	do
	{
		minMax(doubleValues[0], doubleValues[1], doubleValues[2], &doubleMin, &doubleMax);
		EXPECT_EQ(minDoubleVal, doubleMin);
		EXPECT_EQ(maxDoubleVal, doubleMax);
	}
	while (std::next_permutation(doubleValues, doubleValues + numValues));
};
__int64 CHexViewView::getTopLineFromTrackPosition() {
  SCROLLINFO scrollInfo;
  GetScrollInfo(SB_VERT,&scrollInfo);

  if(!m_useScrollBarHelper) {
    return minMax(scrollInfo.nTrackPos, 0, (int)m_maxTopLine);
  } else {
    const DoubleInterval &range = m_scrollBarHelper.getToInterval();
    const double trackPos = scrollInfo.nTrackPos;
    const double line = m_scrollBarHelper.backwardTransform(minMax(trackPos, range.getFrom(), range.getTo()));
    return (__int64)line;
  }
}
void CHexViewView::showCaret() {
  if(!m_caretVisible) {
    CreateSolidCaret(2, CARETHEIGHT);
    ShowCaret();
    m_caretVisible = true;
  }
  m_caret.y = minMax(m_caret.y, 0, m_maxCaret.y);
  m_caret.x = minMax(m_caret.x, 0, m_maxCaret.x);

  bool redraw = false;
  if(m_lineCount && (m_lastLineSize < m_lineSize) && (m_topLine + m_caret.y == m_lineCount-1)) {
    if(m_lineOffset > m_maxLastLineOffset) {
      m_lineOffset = m_maxLastLineOffset;
      isNewSelection();
      redraw = true;
    } else {
      m_caret.x = minMax(m_caret.x, 0, m_lastLineSize - m_lineOffset);
      redraw = isNewSelection();
    }
  } else {
    redraw = isNewSelection();
  }
  m_lastCurrentAddr = getCurrentAddr();
  m_lastSelection   = getSelection();

  if(redraw) {
    repaint();
    return;
  }

  CPoint p(m_caret.x * m_byteSize.cx + m_contentRect.left + m_digitIndex*m_charSize.cx, m_caret.y * m_byteSize.cy + m_contentRect.top);
  SetCaretPos(p);
  m_keepSelection = false;
/*
  const String tmp = format(_T("%s bytes. Addr:%s. Lsize:%d[%d]. Lcount:%I64u, Psize(%d,%d), Scroll(%d,%I64u),max(%d,%I64u)[%d], Caret(%d,%d),max:(%d,%d), Anchor:%I64d, Mark:%s, %s")
                          ,format1000(m_docSize       ).cstr()
                          ,format1000(getCurrentAddr()).cstr()
                          ,m_lineSize, m_lastLineSize
                          ,m_lineCount
                          ,m_pageSize.cx, m_pageSize.cy
                          ,m_lineOffset , m_topLine      , m_maxLineOffset, m_maxTopLine, m_maxLastLineOffset
                          ,m_caret.x    , m_caret.y      , m_maxCaret.x   , m_maxCaret.y
                          ,m_anchor
                          ,getSelection().toString().cstr()
                          ,m_shift ? _T("shift") : EMPTYSTRING);

  theApp.GetMainWnd()->SetWindowText(tmp.cstr());
*/
}
void BitalinoPacketListener::ProcessMessage( const osc::ReceivedMessage& m )  {
    
    try{        
        if( std::strcmp( m.AddressPattern(), "/wek/inputs" ) == 0 ){
            
            osc::ReceivedMessage::const_iterator arg = m.ArgumentsBegin();
            float emg = (arg++)->AsFloat();
            float emgFilt = (arg++)->AsFloat();
            float eda = (arg++)->AsFloat();
            
            this->emgBuffer[this->curEmgBuffIdx++] = emgFilt;
            if (this->curEmgBuffIdx >= BUFFER_SIZE) {
                this->curEmgBuffIdx = 0;
            }
            
            this->emgStd = minMax(this->emgBuffer, BUFFER_SIZE);
            
            float ecg = (arg++)->AsFloat();
            this->accelMean =(arg++)->AsFloat();
            this->lux = (arg++)->AsFloat();
            
            //std::cout << "emg: " << emg << " emgfilt: " << emgFilt << "  eda: " << eda << "  ecg: " << ecg << "  accel: " << accel << "  lux: " << lux << '\n';
            
        }
    }catch( osc::Exception& e ){
        // any parsing errors such as unexpected argument types, or
        // missing arguments get thrown as exceptions.
        std::cout << "error while parsing message: "
        << m.AddressPattern() << ": " << e.what() << "\n";
    }
}
void CSliderCtrlWithTransformation::setPos(double pos) {
  ASSERTCREATED();
  const DoubleInterval &iv = m_tr->getFromInterval();
  pos = minMax(pos, iv.getFrom(), iv.getTo());
  const int p = (int)m_tr->forwardTransform(pos);
  SetPos(p);
}
bool LinePolygonsCrossings::calcScanlineCrossings(bool fail_on_unavoidable_obstacles)
{
    
    min_crossing_idx = NO_INDEX;
    max_crossing_idx = NO_INDEX;

    for(unsigned int poly_idx = 0; poly_idx < boundary.size(); poly_idx++)
    {
        PolyCrossings minMax(poly_idx); 
        PolygonRef poly = boundary[poly_idx];
        Point p0 = transformation_matrix.apply(poly[poly.size() - 1]);
        for(unsigned int point_idx = 0; point_idx < poly.size(); point_idx++)
        {
            Point p1 = transformation_matrix.apply(poly[point_idx]);
            if ((p0.Y >= transformed_startPoint.Y && p1.Y <= transformed_startPoint.Y) || (p1.Y >= transformed_startPoint.Y && p0.Y <= transformed_startPoint.Y))
            { // if line segment crosses the line through the transformed start and end point (aka scanline)
                if (p1.Y == p0.Y) //Line segment is parallel with the scanline. That means that both endpoints lie on the scanline, so they will have intersected with the adjacent line.
                {
                    p0 = p1;
                    continue;
                }
                int64_t x = p0.X + (p1.X - p0.X) * (transformed_startPoint.Y - p0.Y) / (p1.Y - p0.Y); // intersection point between line segment and the scanline
                
                if (x >= transformed_startPoint.X && x <= transformed_endPoint.X)
                {
                    if (!((p1.Y == transformed_startPoint.Y && p1.Y < p0.Y) || (p0.Y == transformed_startPoint.Y && p0.Y < p1.Y)))
                    { // perform edge case only for line segments on and below the scanline, not for line segments on and above.
                        // \/ will be no crossings and /\ two, but most importantly | will be one crossing.
                        minMax.n_crossings++;
                    }
                    if(x < minMax.min.x) //For the leftmost intersection, move x left to stay outside of the border.
                                         //Note: The actual distance from the intersection to the border is almost always less than dist_to_move_boundary_point_outside, since it only moves along the direction of the scanline.
                    {
                        minMax.min.x = x;
                        minMax.min.point_idx = point_idx;
                    }
                    if(x > minMax.max.x) //For the rightmost intersection, move x right to stay outside of the border.
                    {
                        minMax.max.x = x;
                        minMax.max.point_idx = point_idx;
                    }
                }
            }
            p0 = p1;
        }

        if (fail_on_unavoidable_obstacles && minMax.n_crossings % 2 == 1)
        { // if start area and end area are not the same
            return false;
        }
        else if (minMax.min.point_idx != NO_INDEX) // then always also max.point_idx != NO_INDEX
        { // if this polygon crossed the scanline
            if (min_crossing_idx == NO_INDEX || minMax.min.x < crossings[min_crossing_idx].min.x) { min_crossing_idx = crossings.size(); }
            if (max_crossing_idx == NO_INDEX || minMax.max.x > crossings[max_crossing_idx].max.x) { max_crossing_idx = crossings.size(); }
            crossings.push_back(minMax);
        }
    }
    return true;
}
CHexViewView &CHexViewView::setTopLine(__int64 value, bool invalidate) {
  m_topLine = minMax(value, 0i64, m_maxTopLine);
  resetDigitIndex();
  if(invalidate) {
    repaint();
  }
  return *this;
}
CHexViewView &CHexViewView::setLineOffset(int value, bool invalidate) {
  m_lineOffset = minMax(value, 0, m_maxLineOffset);
  resetDigitIndex();
  if(invalidate) {
    repaint();
  }
  return *this;
}
示例#10
0
int main(int argc, const char * argv[]) {
    short min, max;
    short a[] = {1, 4, 5, 78, -100, 45, 28, 34, 5};
    
    minMax(a, 9, &min, &max);
    printf("min:%d max:%d\n", min, max);
    
    return 0;
}
示例#11
0
void PcbXML::drawPin(QDomNode node){
	QDomElement element = node.toElement();
	QDomElement pin = m_svg->createElement("circle");
	int x;
	int y;
	
	if( element.hasAttribute("aX") ){
		x = element.attribute("aX").toInt();	
		y = element.attribute("aY").toInt();
	}
	else {
		x = element.attribute("rX").toInt() + m_markx;
		y = element.attribute("rY").toInt() + m_marky;
	}
	
	int drill = element.attribute("Drill").toInt()/2;
	int thickness = element.attribute("Thickness").toInt()/2 - drill;
	int radius = drill + thickness/2;
	QString id = QString("connector%1pin").arg(m_pinCount);
	
	// BUG: what's up with str -> hex conversion???
	bool verify;
	bool square=false;
	if(element.hasAttribute("NFlags")) {
		square = element.attribute("NFlags").toInt(&verify,16) & 0x0100;
	}
	else if(element.hasAttribute("SFlags")) {
		square = element.attribute("SFlags").toInt(&verify,16) & 0x0100;
	}
	//DebugDialog::debug(QString("NFlags: %1 Value:%2 Square:%3").arg(element.attribute("NFlags")).arg(element.attribute("NFlags").toInt(&verify,16)).arg(square));
	
	m_pinCount++;
	
	if(square){
		QDomElement sq = m_svg->createElement("rect");
		sq.setAttribute("x",x-radius);
		sq.setAttribute("y",y-radius);
		sq.setAttribute("fill", "none");
		sq.setAttribute("width",radius*2);
		sq.setAttribute("height",radius*2);
		sq.setAttribute("stroke", "rgb(255, 191, 0)");
		sq.setAttribute("stroke-width", thickness);
		QDomNode tempsq = m_copper.appendChild(sq);
	}
	
	pin.setAttribute("cx", x);
	pin.setAttribute("cy", y);
	pin.setAttribute("r", radius);
	pin.setAttribute("stroke", "rgb(255, 191, 0)");
	pin.setAttribute("stroke-width", thickness);
	pin.setAttribute("id", id);
	pin.setAttribute("fill", "none");
	
	QDomNode temp = m_copper.appendChild(pin);
	minMax(x,y,radius+(thickness/2));
}
示例#12
0
void main(void)
{
	min=0;
	max=0;
int a[] = {100, -100, 200, -200, 500, -500, 400, -400, 300, -300};
minMax(a, 10);
//for(;;) {} /* wait forever */

printf("min=%d\n", min);
printf("max=%d", max);
}
示例#13
0
void PcbXML::drawElementLine(QDomNode node){
	QDomElement element = node.toElement();
	QDomElement line = m_svg->createElement("line");
	
	int x1 = element.attribute("X1").toInt() + m_markx;	
	int y1 = element.attribute("Y1").toInt() + m_marky;
	int x2 = element.attribute("X2").toInt() + m_markx;	
	int y2 = element.attribute("Y2").toInt() + m_marky;
	int thickness = element.attribute("Thickness").toInt();
	
	line.setAttribute("x1", x1);
	line.setAttribute("y1", y1);
	line.setAttribute("x2", x2);
	line.setAttribute("y2", y2);
	line.setAttribute("stroke", "white");
	line.setAttribute("stroke-width", thickness);
	QDomNode temp = m_silkscreen.appendChild(line);
	minMax(x1,y1,thickness);
	minMax(x2,y2,thickness);
}
示例#14
0
BigReal &copy(BigReal &to, const BigReal &from, size_t length) {
  if(!from._isnormal()) {
    to.clearDigits();
    to.copyFields(from);
  } else {
    length = minMax(length, (size_t)1, from.getLength());
    to.m_low = (to.m_expo = from.m_expo) - length + 1;
    to.m_negative = from.m_negative;
    to.clearDigits();
    to.copyDigits(from, length);
    to.trimZeroes();
  }
  return to;
}
示例#15
0
void LinePolygonsCrossings::calcScanlineCrossings()
{
    
    min_crossing_idx = NO_INDEX;
    max_crossing_idx = NO_INDEX;
        
    for(unsigned int poly_idx = 0; poly_idx < boundary.size(); poly_idx++)
    {
        PolyCrossings minMax(poly_idx); 
        PolygonRef poly = boundary[poly_idx];
        Point p0 = transformation_matrix.apply(poly[poly.size() - 1]);
        for(unsigned int point_idx = 0; point_idx < poly.size(); point_idx++)
        {
            Point p1 = transformation_matrix.apply(poly[point_idx]);
            if((p0.Y >= transformed_startPoint.Y && p1.Y <= transformed_startPoint.Y) || (p1.Y >= transformed_startPoint.Y && p0.Y <= transformed_startPoint.Y))
            {
                if(p1.Y == p0.Y) //Line segment is parallel with the scanline. That means that both endpoints lie on the scanline, so they will have intersected with the adjacent line.
                {
                    p0 = p1;
                    continue;
                }
                int64_t x = p0.X + (p1.X - p0.X) * (transformed_startPoint.Y - p0.Y) / (p1.Y - p0.Y);
                
                if (x >= transformed_startPoint.X && x <= transformed_endPoint.X)
                {
                    if(x < minMax.min.x) //For the leftmost intersection, move x left to stay outside of the border.
                                         //Note: The actual distance from the intersection to the border is almost always less than dist_to_move_boundary_point_outside, since it only moves along the direction of the scanline.
                    {
                        minMax.min.x = x;
                        minMax.min.point_idx = point_idx;
                    }
                    if(x > minMax.max.x) //For the rightmost intersection, move x right to stay outside of the border.
                    {
                        minMax.max.x = x;
                        minMax.max.point_idx = point_idx;
                    }
                }
            }
            p0 = p1;
        }
        
        if (minMax.min.point_idx != NO_INDEX)
        { // then also max.point_idx != -1
            if (min_crossing_idx == NO_INDEX || minMax.min.x < crossings[min_crossing_idx].min.x) { min_crossing_idx = crossings.size(); }
            if (max_crossing_idx == NO_INDEX || minMax.max.x > crossings[max_crossing_idx].max.x) { max_crossing_idx = crossings.size(); }
            crossings.push_back(minMax);
        }
        
    }
}
示例#16
0
//Handles compureter move
void Game::aiMove() {
	bool movemade = false;
	while (!movemade) {
		int i = minMax();

		setCell(i, currentPlayer);
		//int index  = (rand() % 9);
		//if (gridRows[index] == GRID_TYPE_NONE) {
		//	gridRows[index] = currentPlayer;
		movemade = true;
		//}
	}
	currentPlayer = 2;
};
示例#17
0
int AI::launchAI(const int tab[19][19], const t_flag& team, const int& pionOne, const int& pionTwo) {
    int toRet;

    for (int y = 0; y != 19; y++) {
        for (int x = 0; x != 19; x++) {
            _mapRule[y][x] = tab[y][x];
        }
    }
    _nbPionOne = pionOne;
    _nbPionTwo = pionTwo;
    _initTeam = team;
    toRet = minMax(team);
    std::cout << MAGENTA << "[IA] Value ask : " << toRet << END << std::endl;
    return toRet;
}
示例#18
0
文件: maxMin.c 项目: prakhar4/codes
int main()
{
	int n,a[MAXSIZE],ans[2], i;
	
	printf("\nEnter the no of elements ");
	scanf("%d",&n);
	
	for(i=1;i<=n;i++)
		scanf("%d",&a[i]);
		
	minMax(n,a,ans);
	
	printf("\nMinimum is %d \nMaximum is %d\n",ans[0],ans[1]);
	return 0;
}
示例#19
0
void CZoomDlg::scrollHorizontal(int n) {
  CEdit *e = (CEdit*)GetDlgItem(IDC_EDIT2LINES);
  LOGFONT lf;
  m_font.GetLogFont(&lf);
  SCROLLINFO info;
  info.cbSize = sizeof(info);
  e->GetScrollInfo(SB_HORZ, &info);
  const int newPos = minMax(info.nPos + n, info.nMin, info.nMax);
  const int amount = newPos - info.nPos;
  if(amount != 0) {
    e->SetScrollPos(SB_HORZ, newPos);
    e->ScrollWindow(-amount,0);
    UpdateWindow();
  }
}
void DRunningEnemy::Moving(float updateTime)
{
	for(int i = 0; i < numOfEnemies; i++)
	{
		runners.at(i)->MoveX(-speed[i] * updateTime);
		minMax(runners[i], i);
		playerCollision = PlayerCollisionDetection(i);
		if(runners.at(i)->GetX() < player->GetX()-200)
		{
			runners.at(i)->SetX(player->GetX()+400);
		}
		else if(playerCollision == true)
		{
			runners.at(i)->SetX(player->GetX()+400);
		}
	}
}
示例#21
0
unsigned int Heuristic::bestMove(board* b, int color) {
	int iterativeMaxLevel = ARRAY_SIZE;		// max level for iterative deepening search
	this->b = b;
	this->color = color;
	unsigned long long upArray[ARRAY_SIZE];

	memset(upArray,0,sizeof(unsigned long long)*ARRAY_SIZE);

	int sum=0;
	timeoutMove = 0;

	//maxLevel = 4;
	iteration = 0;
	counter = 0;
	firstMove = false;
	for(int i=0; i<ARRAY_SIZE; ++i) {
		bestLeafPath[i] = 0;
	}

	b->calculatePossibleMoves(color);
	if (b->getPossibleMoves(color).size() == 1)
		return *(b->getPossibleMoves(color).begin());

	for (maxLevel=1; maxLevel <= iterativeMaxLevel; ++maxLevel) {
		memset(upArray,0,sizeof(unsigned long long)*ARRAY_SIZE);		// filling array with 0
		iteration = 0;
		minMax(0, MINUS_INFINITY, PLUS_INFINITY, upArray);
		for (int i=0; i<ARRAY_SIZE; ++i) {								// copy best move found in last minMax
			bestLeafPath[i] = upArray[i];
		}
		std::cout<<"-> Level " << maxLevel<< " at " << iteration<< " iterations" << std::endl;
		sum += iteration;
		firstMove = true;
	}
	std::cout<<std::endl<<"sum: "<<sum<<std::endl;
	if (timeoutMove > 0 ) {			// timeout occurred, get last best value
		return timeoutMove;
	}
	return actualMove;
}
示例#22
0
void LinePolygonsCrossings::calcScanlineCrossings()
{
    
    min_crossing_idx = NO_INDEX;
    max_crossing_idx = NO_INDEX;
        
    for(unsigned int poly_idx = 0; poly_idx < boundary.size(); poly_idx++)
    {
        PolyCrossings minMax(poly_idx); 
        PolygonRef poly = boundary[poly_idx];
        Point p0 = transformation_matrix.apply(poly.back());
        for(unsigned int point_idx = 0; point_idx < poly.size(); point_idx++)
        {
            Point p1 = transformation_matrix.apply(poly[point_idx]);
            if ((p0.Y > transformed_startPoint.Y && p1.Y < transformed_startPoint.Y) || (p1.Y > transformed_startPoint.Y && p0.Y < transformed_startPoint.Y))
            {
                int64_t x = p0.X + (p1.X - p0.X) * (transformed_startPoint.Y - p0.Y) / (p1.Y - p0.Y);
                
                if (x >= transformed_startPoint.X && x <= transformed_endPoint.X)
                {
                    if (x < minMax.min.x) { minMax.min.x = x; minMax.min.point_idx = point_idx; }
                    if (x > minMax.max.x) { minMax.max.x = x; minMax.max.point_idx = point_idx; }
                }
            }
            p0 = p1;
        }
        
        if (minMax.min.point_idx != NO_INDEX)
        { // then also max.point_idx != -1
            if (min_crossing_idx == NO_INDEX || minMax.min.x < crossings[min_crossing_idx].min.x) { min_crossing_idx = crossings.size(); }
            if (max_crossing_idx == NO_INDEX || minMax.max.x > crossings[max_crossing_idx].max.x) { max_crossing_idx = crossings.size(); }
            crossings.push_back(minMax);
        }
        
    }
}
示例#23
0
Point AIPlayer::move(const GameField &gameField, const Player &opponent)
{
	int row = -1;
	int column = -1;
	int fieldSize = gameField.getSize();
	Point point(-1, -1);

	if (gameField.getSize() > 3)
	{
		do
		{
			row = -1;
			column = -1;

			while (row < 0 || row > fieldSize - 1)
			{
				row = rand() % fieldSize;
			}

			while (column < 0 || row > fieldSize - 1)
			{
				column = rand() % fieldSize;
			}
		} while (gameField.getField(row, column) != GameField::M_EMPTY_CHAR);

		point = Point(row, column);
	}
	else
	{
		MinMax minMax(*this, opponent);
		minMax.minMax(gameField, *this, opponent, 0);
		point = minMax.getBestMove();
		mLastMove = point;
	}
	return point;
}
示例#24
0
/* Combines min and max into one function that always does max */
double minMax(State *currBoard, int depth)
{
    State nextBoard;
    double rval;
    int i;
    double maxv=-100000.0;

    if(depth <= 0) return evalBoard2(currBoard);

    FindLegalMoves(currBoard);
    for(i=0; i<currBoard->numLegalMoves; i++) 
    {
        /* Set up the next state by copying the current state and then updating the new */
        /* state to reflect the new board after performing the move */
        memcpy (&nextBoard, currBoard, sizeof(State));
        PerformMove(nextBoard.board,currBoard->movelist[i],MoveLength(currBoard->movelist[i]));
        nextBoard.player = 3-nextBoard.player;

        rval = -minMax(&nextBoard, depth-1);

        if (rval > maxv) maxv = rval;
    }    
    return maxv;
}
示例#25
0
TEST_F(MinMaxTests, AribtraryEntriesTests)
{
	const int numValues = 5;

	float floatValues[numValues] = { 18, 7, 52, 12, 12};
	float minFloatVal = 7;
	float maxFloatVal = 52;
	float floatMin;
	float floatMax;

	double doubleValues[numValues] = { -23, -47, -2, -17, -17};
	double minDoubleVal = -47;
	double maxDoubleVal = -2;
	double doubleMin;
	double doubleMax;

	ASSERT_THROW(minMax(floatValues, 0, &floatMin, &floatMax), SurgSim::Framework::AssertionFailure);
	ASSERT_THROW(minMax(floatValues, -1, &floatMin, &floatMax), SurgSim::Framework::AssertionFailure);

	std::sort(floatValues, floatValues + numValues);
	do
	{
		minMax(floatValues, numValues, &floatMin, &floatMax);
		EXPECT_EQ(minFloatVal, floatMin);
		EXPECT_EQ(maxFloatVal, floatMax);
	}
	while (std::next_permutation(floatValues, floatValues + numValues));

	ASSERT_THROW(minMax(doubleValues, 0, &doubleMin, &doubleMax), SurgSim::Framework::AssertionFailure);
	ASSERT_THROW(minMax(doubleValues, -1, &doubleMin, &doubleMax), SurgSim::Framework::AssertionFailure);

	std::sort(doubleValues, doubleValues + numValues);
	do
	{
		minMax(doubleValues, numValues, &doubleMin, &doubleMax);
		EXPECT_EQ(minDoubleVal, doubleMin);
		EXPECT_EQ(maxDoubleVal, doubleMax);
	}
	while (std::next_permutation(doubleValues, doubleValues + numValues));
};
示例#26
0
void QgsGrassVectorMapLayer::load()
{
  clear();

  if ( !mMap )
  {
    return;
  }

  // Attributes are not loaded for topo layers in which case field == 0
  if ( mField == 0 )
  {
    return;
  }

  QgsDebugMsg( QString( "cidxFieldIndex() = %1 cidxFieldNumCats() = %2" ).arg( cidxFieldIndex() ).arg( cidxFieldNumCats() ) );

  mFieldInfo = Vect_get_field( mMap->map(), mField ); // should work also with field = 0

  if ( !mFieldInfo )
  {
    QgsDebugMsg( "No field info -> no attribute table" );
  }
  else
  {
    QgsDebugMsg( "Field info found -> open database" );

    QFileInfo di( mMap->grassObject().mapsetPath() + "/vector/" + mMap->grassObject().name() + "/dbln" );
    mLastLoaded = di.lastModified();

    QString error;
    dbDriver *databaseDriver = openDriver( error );

    if ( !databaseDriver || !error.isEmpty() )
    {
      QgsDebugMsg( error );
    }
    else
    {
      QgsDebugMsg( "Database opened -> open select cursor" );
      QgsGrass::lock(); // not sure if lock is necessary
      dbString dbstr;
      db_init_string( &dbstr );
      db_set_string( &dbstr, ( char * )"select * from " );
      db_append_string( &dbstr, mFieldInfo->table );

      QgsDebugMsg( QString( "SQL: %1" ).arg( db_get_string( &dbstr ) ) );
      dbCursor databaseCursor;
      if ( db_open_select_cursor( databaseDriver, &dbstr, &databaseCursor, DB_SCROLL ) != DB_OK )
      {
        db_close_database_shutdown_driver( databaseDriver );
        QgsGrass::warning( "Cannot select attributes from table '" + QString( mFieldInfo->table ) + "'" );
      }
      else
      {
#ifdef QGISDEBUG
        int nRecords = db_get_num_rows( &databaseCursor );
        QgsDebugMsg( QString( "Number of records: %1" ).arg( nRecords ) );
#endif

        dbTable  *databaseTable = db_get_cursor_table( &databaseCursor );
        int nColumns = db_get_table_number_of_columns( databaseTable );

        // Read columns' description
        for ( int i = 0; i < nColumns; i++ )
        {
          QPair<double, double> minMax( DBL_MAX, -DBL_MAX );

          dbColumn *column = db_get_table_column( databaseTable, i );

          int ctype = db_sqltype_to_Ctype( db_get_column_sqltype( column ) );
          QVariant::Type qtype = QVariant::String; //default to string
          QgsDebugMsg( QString( "column = %1 ctype = %2" ).arg( db_get_column_name( column ) ).arg( ctype ) );

          QString ctypeStr;
          switch ( ctype )
          {
            case DB_C_TYPE_INT:
              ctypeStr = QStringLiteral( "integer" );
              qtype = QVariant::Int;
              break;
            case DB_C_TYPE_DOUBLE:
              ctypeStr = QStringLiteral( "double" );
              qtype = QVariant::Double;
              break;
            case DB_C_TYPE_STRING:
              ctypeStr = QStringLiteral( "string" );
              qtype = QVariant::String;
              break;
            case DB_C_TYPE_DATETIME:
              ctypeStr = QStringLiteral( "datetime" );
              qtype = QVariant::String;
              break;
          }
          mTableFields.append( QgsField( db_get_column_name( column ), qtype, ctypeStr,
                                         db_get_column_length( column ), db_get_column_precision( column ) ) );
          mMinMax << minMax;
          if ( G_strcasecmp( db_get_column_name( column ), mFieldInfo->key ) == 0 )
          {
            mKeyColumn = i;
          }
        }

        if ( mKeyColumn < 0 )
        {
          mTableFields.clear();
          QgsGrass::warning( QObject::tr( "Key column '%1' not found in the table '%2'" ).arg( mFieldInfo->key, mFieldInfo->table ) );
        }
        else
        {
          mHasTable = true;
          // Read attributes to the memory
          for ( ;; )
          {
            int more;

            if ( db_fetch( &databaseCursor, DB_NEXT, &more ) != DB_OK )
            {
              QgsDebugMsg( "Cannot fetch DB record" );
              break;
            }
            if ( !more )
            {
              break; // no more records
            }

            // Check cat value
            dbColumn *column = db_get_table_column( databaseTable, mKeyColumn );
            dbValue *value = db_get_column_value( column );

            if ( db_test_value_isnull( value ) )
            {
              continue;
            }
            int cat = db_get_value_int( value );
            if ( cat < 0 )
            {
              continue;
            }

            QList<QVariant> values;
            for ( int i = 0; i < nColumns; i++ )
            {
              column = db_get_table_column( databaseTable, i );
              int sqltype = db_get_column_sqltype( column );
              int ctype = db_sqltype_to_Ctype( sqltype );
              value = db_get_column_value( column );
              db_convert_value_to_string( value, sqltype, &dbstr );

              QgsDebugMsgLevel( QString( "column = %1 value = %2" ).arg( db_get_column_name( column ), db_get_string( &dbstr ) ), 3 );

              QVariant variant;
              if ( !db_test_value_isnull( value ) )
              {
                int iv;
                double dv;
                //layer.mAttributes[layer.nAttributes].values[i] = strdup( db_get_string( &dbstr ) );
                switch ( ctype )
                {
                  case DB_C_TYPE_INT:
                    iv = db_get_value_int( value );
                    variant = QVariant( iv );
                    mMinMax[i].first = std::min( mMinMax[i].first, ( double )iv );
                    mMinMax[i].second = std::min( mMinMax[i].second, ( double )iv );
                    break;
                  case DB_C_TYPE_DOUBLE:
                    dv = db_get_value_double( value );
                    variant = QVariant( dv );
                    mMinMax[i].first = std::min( mMinMax[i].first, dv );
                    mMinMax[i].second = std::min( mMinMax[i].second, dv );
                    break;
                  case DB_C_TYPE_STRING:
                    // Store as byte array so that codec may be used later
                    variant = QVariant( QByteArray( db_get_value_string( value ) ) );
                    break;
                  case DB_C_TYPE_DATETIME:
                    variant = QVariant( QByteArray( db_get_string( &dbstr ) ) );
                    break;
                  default:
                    variant = QVariant( QByteArray( db_get_string( &dbstr ) ) );
                }
              }
              QgsDebugMsgLevel( QString( "column = %1 variant = %2" ).arg( db_get_column_name( column ), variant.toString() ), 3 );
              values << variant;
            }
            mAttributes.insert( cat, values );
          }
        }
        mValid = true;
        db_close_cursor( &databaseCursor );
        db_close_database_shutdown_driver( databaseDriver );
        db_free_string( &dbstr );

        QgsDebugMsg( QString( "mTableFields.size = %1" ).arg( mTableFields.size() ) );
        QgsDebugMsg( QString( "number of attributes = %1" ).arg( mAttributes.size() ) );
      }
      QgsGrass::unlock();
    }
  }

  // Add cat if no attribute fields exist (otherwise qgis crashes)
  if ( mTableFields.size() == 0 )
  {
    mKeyColumn = 0;
    mTableFields.append( QgsField( QStringLiteral( "cat" ), QVariant::Int, QStringLiteral( "integer" ) ) );
    QPair<double, double> minMax( 0, 0 );

    if ( cidxFieldIndex() >= 0 )
    {
      int ncats, cat, type, id;

      ncats = Vect_cidx_get_num_cats_by_index( mMap->map(), cidxFieldIndex() );

      if ( ncats > 0 )
      {
        Vect_cidx_get_cat_by_index( mMap->map(), cidxFieldIndex(), 0, &cat, &type, &id );
        minMax.first = cat;

        Vect_cidx_get_cat_by_index( mMap->map(), cidxFieldIndex(), ncats - 1, &cat, &type, &id );
        minMax.second = cat;
      }
    }
    mMinMax << minMax;
  }
  mFields = mTableFields;
  mAttributeFields = mTableFields;

  QgsDebugMsg( QString( "layer loaded mTableFields.size() = %1 mAttributes.size() = %2" ).arg( mTableFields.size() ).arg( mAttributes.size() ) );
  mValid = true;
}
示例#27
0
int Heuristic::minMax(int level, int alpha, int beta, unsigned long long downArray[]) {
	int tmp = 0;    // temporary value which is compared to max value
	int winCheck=0;

	set<unsigned long long int> tempMoveSet;
	set<unsigned long long int>::iterator iter, iterEnd, iterTmp;


	if (!aiPlayer->working) {			// if timeout!
		return 0;		// value doesn't matter
	}


	winCheck = b->terminal();
	if (winCheck == color+2)     // computer wins
		return PLUS_INFINITY / level;
	if (winCheck == 1)     // draw
		return 0;
	if (winCheck != 0)              // opponent wins
		return MINUS_INFINITY;


	// Leaf
	if (level == maxLevel) {
		iteration++;
		return evaluation();
	}


	// MAX
	if (level % 2 == 0) {

		// getting possible moves
		b->calculatePossibleMoves(color);
		tempMoveSet = b->getPossibleMoves(color);


		if (firstMove) {
			if (level == maxLevel-2) {		// in next minMax call start exploring tree without first move path
				firstMove = false;
			}
			tempMoveSet.erase(bestLeafPath[level]);		// delete best move from the set

			// copied part from above
			b->movePiece(bestLeafPath[level], color);	// do the best move
			unsigned long long * upArray;		// array given to upper minMax call
			upArray = new unsigned long long [ARRAY_SIZE];
			memset(upArray,0,sizeof(unsigned long long)*ARRAY_SIZE);		// cleaning array with 0
			tmp = minMax(level+1, alpha, beta, upArray);
			b->undoMove();
			b->clean();
			b->calculatePossibleMoves(color);
			if (tmp > alpha) {
				alpha = tmp;
				downArray[level] = bestLeafPath[level];						// store best move so far (at current level)
				for(int i = level+1; i<maxLevel; ++i) {			// copy good moves from higher levels
					downArray[i] = upArray[i];
				}
				if (level == 0) {
					actualMoveMutex.acquire();
						actualMove = bestLeafPath[level];
					actualMoveMutex.release();
				}
			}
			delete[] upArray;
		}

		iter = tempMoveSet.begin();
		iterEnd = tempMoveSet.end();

		for (; iter != iterEnd; ++iter) {
			if (alpha >= beta)      // while (alpha < beta)
				break;
			b->movePiece(*iter, color);
			unsigned long long * upArray;		// array given to upper minMax call
			upArray = new unsigned long long [ARRAY_SIZE];
			memset(upArray,0,sizeof(unsigned long long)*ARRAY_SIZE);		// cleaning array with 0
			tmp = minMax(level+1, alpha, beta, upArray);
			b->undoMove();
			b->clean();
			b->calculatePossibleMoves(color);
			if (tmp > alpha) {
				alpha = tmp;
				downArray[level] = *iter;						// store best move so far (at current level)
				for(int i = level+1; i<maxLevel; ++i) {			// copy good moves from higher levels
					downArray[i] = upArray[i];
				}

				if (level == 0) {
					actualMoveMutex.acquire();
						actualMove = *iter;
					actualMoveMutex.release();
				}
			}
			delete[] upArray;
		}
		return alpha;
	}

	// MIN
	else {

		// getting possible moves
		b->calculatePossibleMoves(!color);
		tempMoveSet = b->getPossibleMoves(!color);


		if (firstMove) {
			if (level == maxLevel-2) {		// in next minMax call start exploring tree without first move path
				firstMove = false;
			}
			tempMoveSet.erase(bestLeafPath[level]);		// delete best move from the set

			// copied part from above
			b->movePiece(bestLeafPath[level], !color);	// do the best move
			unsigned long long * upArray;		// array given to upper minMax call
			upArray = new unsigned long long [ARRAY_SIZE];
			memset(upArray,0,sizeof(unsigned long long)*ARRAY_SIZE);		// cleaning array with 0
			tmp = minMax(level+1, alpha, beta, upArray);
			b->undoMove();
			b->clean();
			b->calculatePossibleMoves(!color);
			if (tmp < beta) {
				beta = tmp;
				downArray[level] = bestLeafPath[level];						// store best move so far (at current level)
				for(int i = level+1; i<maxLevel; ++i) {			// copy good moves from higher levels
					downArray[i] = upArray[i];
				}
			}
			delete[] upArray;
		}

		iter = tempMoveSet.begin();
		iterEnd = tempMoveSet.end();

		for (; iter != iterEnd; ++iter) {
			if (alpha >= beta)      // while (alpha < beta)
				break;
			b->movePiece(*iter, !color);
			unsigned long long * upArray;		// array given to upper minMax call
			upArray = new unsigned long long [ARRAY_SIZE];
			memset(upArray,0,sizeof(unsigned long long)*ARRAY_SIZE);		// cleaning array with 0
			tmp = minMax(level+1, alpha, beta, upArray);
			b->undoMove();
			b->clean();
			b->calculatePossibleMoves(!color);
			if (tmp < beta) {
				beta = tmp;
				downArray[level] = *iter;						// store best move so far (at current level)
				for(int i = level+1; i<maxLevel; ++i) {			// copy good moves from higher levels
					downArray[i] = upArray[i];
				}
			}
			delete[] upArray;
		}
		return beta;
	}

}
示例#28
0
CRect CHexViewView::updateSettings(CDC *dc) {
  CRect cr;
  GetClientRect(&cr);
  CFont *oldFont = NULL;

  if(dc == NULL) {
    dc = &m_workDC;
    oldFont = dc->SelectObject(&m_font);
  }

  m_readOnly    = GetDocument()->isReadOnly();
  m_radixFormat = m_settings->getRadixFormat();
  m_asciiFormat = m_settings->getAsciiFormat();
  m_byteSize    = dc->GetTextExtent(m_settings->getDataSampleText());
  m_charSize    = dc->GetTextExtent(_T("0"));
  m_docSize     = GetDocument()->getSize();

  m_addrFormat.update(m_docSize, *m_settings);

  const bool showAddr           = m_settings->getShowAddr();
  const bool showAscii          = m_settings->getShowAscii();

  if(showAddr) {
    const String sampleText     = m_addrFormat.getSampleText();

    m_addrTextSize              = getTextExtent(*dc,sampleText);
  } else {
    m_addrTextSize = CSize(0,0);
  }
  m_contentRect.left            = m_addrTextSize.cx;
  m_contentRect.right           = cr.right  - m_byteSize.cx;
  m_contentRect.top             = m_addrTextSize.cy;
  m_contentRect.bottom          = cr.bottom - m_byteSize.cy;

  m_pageSize          = CSize((m_contentRect.Width()-4) / m_byteSize.cx + 1, m_contentRect.Height()/m_byteSize.cy);

  if(m_settings->getFitLinesToWindow()) {
    m_lineSize        = m_contentRect.Width()/m_byteSize.cx + 1; // Use windowsize to determine the number of bytes on each line
  } else {
    m_lineSize        = m_settings->getLineSize();
  }

  m_lineSize          = max(m_lineSize, 1);   // just to prevent division by zero. see below
  m_maxLineOffset     = max(m_lineSize - m_pageSize.cx, 0);
  m_lineOffset        = min(m_lineOffset, m_maxLineOffset);
  m_lineCount         = (m_docSize - 1)/m_lineSize + 1;
  m_maxTopLine        = max(m_lineCount - m_pageSize.cy, 0);
  m_topLine           = min(m_topLine, m_maxTopLine);
  m_maxCaret          = CPoint(m_pageSize.cx, m_pageSize.cy - 1);
  m_maxCaret.x        = minMax(m_maxCaret.x, 0, (int)min(m_docSize, m_lineSize));
  if(m_maxCaret.y >= m_lineCount) {
    m_maxCaret.y = (int)m_lineCount - 1;
  }
  if (m_maxCaret.y < 0) {
    m_maxCaret.y = 0;
  }
  m_lastLineSize      = m_docSize % m_lineSize;

  if(m_lastLineSize == 0) {
    m_lastLineSize = m_lineSize;
  }
  m_maxLastLineOffset = min(m_lastLineSize - 1, m_maxLineOffset);

  if(m_readOnly || m_settings->getShowAscii()) {  // readonly or ascii => only 0 is valid
    m_minDigitIndex = m_maxDigitIndex = 0;
  } else if((m_settings->getDataRadix() != 16)) { // dec or oct => [0..2]
    m_minDigitIndex = 0;
    m_maxDigitIndex = 2;
  } else  if(m_settings->getHex3Pos()) {          // hex 3-pos  => [1..2]
    m_minDigitIndex = 1;
    m_maxDigitIndex = 2;
  } else {                                        // hex 2-pos  => [0..1]
    m_minDigitIndex = 0;
    m_maxDigitIndex = 1;
  }

  m_digitIndex = minMax(m_digitIndex, m_minDigitIndex, m_maxDigitIndex);

  if(dc == &m_workDC) {
    dc->SelectObject(oldFont);
  }
  return cr;
}
示例#29
0
void CMakeAviDlg::scrollLines(int count) {
  const int index = getSelectedIndex() + count;
  setSelectedIndex(m_nameList, minMax(index, 0, (int)m_nameArray.size()));
}
示例#30
0
CHexViewView &CHexViewView::setDigitIndex(char index) {
  m_digitIndex = minMax(index, m_minDigitIndex, m_maxDigitIndex);
  return *this;
}