Пример #1
0
static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
                                                   const char *e) {
  size_t l, i;
  const char *news = lua_tolstring(ms->L, 3, &l);
  for (i = 0; i < l; i++) {
    if (news[i] != L_ESC)
      luaL_addchar(b, news[i]);
    else {
      i++;  /* skip ESC */
      if (news[i] == '\0')
        luaL_error(ms->L, "malformed replacement string (ends with " LUA_QL("%%") ")");
      if (!isdigit(uchar(news[i])))
        luaL_addchar(b, news[i]);
      else if (news[i] == '0')
          luaL_addlstring(b, s, e - s);
      else {
        push_onecapture(ms, news[i] - '1', s, e);
        luaL_addvalue(b);  /* add capture to accumulated result */
      }
    }
  }
}
Пример #2
0
void QLCInputSource::run()
{
    qDebug() << Q_FUNC_INFO << "Thread started for universe" << m_universe << "channel" << m_channel;

    uchar inputValueCopy = m_inputValue;
    double dValue = m_outputValue;
    uchar lastOutputValue = m_outputValue;
    bool movementOn = false;

    while (m_running == true)
    {
        msleep(50);

        QMutexLocker locker(&m_mutex);

        if (lastOutputValue != m_outputValue)
            dValue = m_outputValue;

        if (inputValueCopy != m_inputValue || movementOn == true)
        {
            movementOn = false;
            inputValueCopy = m_inputValue;
            double moveAmount = 127 - inputValueCopy;
            if (moveAmount != 0)
            {
                dValue -= (moveAmount / m_sensitivity);
                dValue = CLAMP(dValue, 0, 255);

                uchar newDmxValue = uchar(dValue);
                qDebug() << "double value:" << dValue << "uchar val:" << newDmxValue;
                if (newDmxValue != m_outputValue)
                    emit inputValueChanged(m_universe, m_channel, newDmxValue);

                movementOn = true;
            }
            lastOutputValue = m_outputValue;
        }
    }
}
Пример #3
0
void MonitorFixture::updateValues(const QByteArray& ua)
{
    QLabel* label;
    uchar value;
    Fixture* fxi;
    QString str;
    int i = 0;

    /* Check that this MonitorFixture represents a fixture */
    if (m_fixture == Fixture::invalidId())
        return;

    /* Check that this MonitorFixture's fixture really exists */
    fxi = m_doc->fixture(m_fixture);
    if (fxi == NULL)
        return;

    QListIterator <QLabel*> it(m_valueLabels);
    while (it.hasNext() == true)
    {
        label = it.next();
        Q_ASSERT(label != NULL);

        value = uchar(ua.at(fxi->universeAddress() + i));
        i++;

        /* Set the label's text to reflect the changed value */
        if (m_valueStyle == Monitor::DMXValues)
        {
            label->setText(str.sprintf("%.3d", value));
        }
        else
        {
            label->setText(str.sprintf("%.3d", int(ceil(SCALE(qreal(value),
                                                              qreal(0), qreal(UCHAR_MAX),
                                                              qreal(0), qreal(100))))));
        }
    }
}
Пример #4
0
cv::Mat CMyImageProc::GenColorTexton_kmeans(cv::Mat &img, int clusterCount )
{
	if(img.channels() != 3) {
		cout<<"Only color images are supported!"<<endl;
		return cv::Mat();
	}

	cv::Mat samples(img.rows*img.cols, 3, CV_32F);
	cv::Mat centers, labels;
	int p = 0;
	for(int i=0; i<img.rows; i++) {
		for(int j=0; j<img.cols; j++, p++) {
			cv::Vec3b &pf = img.at<cv::Vec3b>(i, j);
			// You can now access the pixel value with cv::Vec3b
			float b = (float)pf[0];
			float g = (float)pf[1];
			float r = (float)pf[2];

			samples.at<float>(p, 0) = r;
			samples.at<float>(p, 1) = g;
			samples.at<float>(p, 2) = b;
		}
	}

	int attempts = 5;
	cv::kmeans(samples, clusterCount, labels, TermCriteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS, 10, 1.0), attempts, KMEANS_PP_CENTERS, centers);

	cv:: Mat textonImg(img.rows, img.cols, CV_8UC1, Scalar(uchar(0)));
	for(int k=0, i=0; i<img.rows; i++) {
		for(int j=0; j<img.cols; j++, k++) {
			int l = labels.at<int>(k,0);
			double f_l = l / (double)clusterCount;
			textonImg.at<uchar>(i,j) = (uchar) (int (f_l*255.0+0.5));
		}
	}

	return textonImg;
}
Пример #5
0
//----------------------------------------------------------------------
// change value of virtual register "BANK" and switch to another bank
static void split(int reg, sel_t v)
{
    if ( reg == -1 )
    {
        flow = 0;
        if ( v != BADSEL )
        {
            sel_t pclath = getSR(cmd.ea, PCLATH) & 0x1F;
            ea_t ea = calc_code_mem(uchar(v) | (pclath<<8));
            ua_add_cref(0, ea, fl_JN);
        }
    }
    else
    {
        if ( v == BADSEL ) v = 0;     // assume bank0 if bank is unknown
        if ( reg == BANK )
        {
            if ( ptype != PIC16 ) v &= 3;
            else v &= 0xF;
        }
        splitSRarea1(get_item_end(cmd.ea), reg, v, SR_auto);
    }
}
Пример #6
0
QString andrq::getString(QDataStream &in, int key)
{
	qint32 len;
	in >> len;
	char *data = (char *)qMalloc(len);
	in.readRawData(data, len);
	int dh = 0, dl = 0;

	int temp = key;
	dl |= temp & 0x000000FF;
	temp >>= 20;
	dh |= temp & 0x000000FF;

/*	if (!ans)
		return false;*/

	int ah = 184; //10111000b;
	for (int i = 0; i < len; ++i)
	{
		int al = uchar(data[i]);
		al ^= ah;

		al=(al%32)*8+al/32;	//циклический сдвиг al на 3 бита влево

		al ^= dh;
		al -= dl;

		data[i] = char(al);
		ah=(ah%8)*32+ah/8;	//циклический сдвиг ah вправо на 3 бита
	}
	static QTextCodec *ansii_codec = QTextCodec::codecForName("cp1251");
	static QTextCodec *utf8_codec = QTextCodec::codecForName("utf-8");
	QTextCodec *codec = isValidUtf8(QByteArray::fromRawData(data, len)) ? utf8_codec : ansii_codec;
	QString result = codec->toUnicode(data, len);
	qFree(data);
	return result;
}
Пример #7
0
/*
    Returns a human readable representation of the first \a len
    characters in \a data.
*/
static QByteArray qt_prettyDebug(const char *data, int len, int maxLength)
{
    if (!data) return "(null)";
    QByteArray out;
    for (int i = 0; i < len; ++i) {
        char c = data[i];
        if (isprint(int(uchar(c)))) {
            out += c;
        } else switch (c) {
        case '\n': out += "\\n"; break;
        case '\r': out += "\\r"; break;
        case '\t': out += "\\t"; break;
        default:
            QString tmp;
            tmp.sprintf("\\%o", c);
            out += tmp.toLatin1().constData();
        }
    }

    if (len < maxLength)
        out += "...";

    return out;
}
Пример #8
0
// Implements \newcolumntype{C}[opt]{body}
// as \newcommand\cmd[opt]{body}
// Here \cmd is some internal name, stored in nct_tok[C]
void Parser::T_newcolumn_type()
{
  TokenList L = mac_arg();
  uint c = 0; 
  if(L.empty()) parse_error("Empty argument to \\newcolumntype");
  else if(L.size() != 1)
    parse_error("More than one token in argument to \\newcolumntype");
  else {
    if(L.front().is_a_char())
      c = L.front().char_val().get_value();
    if(!(c>0 && c<nb_newcolumn)) {
      parse_error("Argument to \\newcolumntype is not a 7bit character");
      c= 0;
    }
  }
  Buffer& B = hash_table.my_buffer();
  B.reset();
  B.push_back("newcolumtype@");
  B.push_back(uchar(c)); // special hack if c=0 !
  cur_tok = hash_table.locate(B);
  new_array_object.add_a_type(c,cur_tok);
  back_input();
  get_new_command(rd_always,false); // definition is local
}
Пример #9
0
// error-diffusion dither into the fltk colormap
static void monodither(uchar* to, const uchar* from, int w, int delta) {
  static int ri,dir;
  int r=ri;
  int d, td;
  if (dir) {
    dir = 0;
    from = from+(w-1)*delta;
    to = to+(w-1);
    d = -delta;
    td = -1;
  } else {
    dir = 1;
    d = delta;
    td = 1;
  }
  for (;; from += d, to += td) {
    r += *from; if (r < 0) r = 0; else if (r>255) r = 255;
    int rr = r*FL_NUM_GRAY/256;
    r -= rr*255/(FL_NUM_GRAY-1);
    *to = uchar(FL_GRAY_RAMP+rr);
    if (!--w) break;
  }
  ri = r;
}
Пример #10
0
TStr THtmlLxChDef::GetWin1250FromYuascii(const TChA& ChA){
  TChA DstChA;
  for (int ChN=0; ChN<ChA.Len(); ChN++){
    char Ch=ChA[ChN];
    switch (Ch){
      case '~': DstChA+=uchar(232); break;
      case '^': DstChA+=uchar(200); break;
      case '}': DstChA+='c'; break;
      case ']': DstChA+='C'; break;
      case '|': DstChA+='d'; break;
      case '\\': DstChA+='D'; break;
      case '{': DstChA+=uchar(154); break;
      case '[': DstChA+=uchar(138); break;
      case '`': DstChA+=uchar(158); break;
      case '@': DstChA+=uchar(142); break;
      default: DstChA+=Ch;
    }
  }
  return DstChA;
}
Пример #11
0
 // increment the flag value (mod 4):
 void inc_flag(uint i) {
    set_flag(uchar((flag() + i) % (1 << FLAG_BITS)));
 }
Пример #12
0
void edgeProcess(Mat img_sym, Mat *imgH, Mat *edges, Mat mask, Mat gradx, Mat grady, int scale)
{
	int H = mask.rows, W = mask.cols;
	int i = 0, j = 0, k = 0;

	int TH_v = 6;
	int head_y = -1, head_x = -1, tail_y = -1, tail_x = -1;
	int sig[direction_num];
	int len = 0, slope = 0;

	double gx, gy;

	bool flag_mask=false;

	Mat cnt = Mat::zeros(H*scale, W*scale, CV_64F);
	Mat img = Mat::zeros(H*scale, W*scale, CV_64F);
// ------------------------------------------------------------------------------------------------
// vertical rods ----------------------------------------------------------------------------------
	for (j = 0; j < W; j++)
	{
		for (i = 0; i < H; i++)
		{
			if ((mask.at<uchar>(i, j) == 0 && len == 0)) // the value in mask(i,j) is negative
			{
				continue;
			}

			if ((j == 0) || (j == W - 1)) // boundary situation
			{
				flag_mask = (mask.at<uchar>(i, j) > 0);
			}
			else // mask(i,j) - ( mask(i,j) & mask(i-1,j) & mask(i+1,j) )
			{
				flag_mask = (mask.at<uchar>(i, j) > 0) ^ ((mask.at<uchar>(i, j) > 0) && (mask.at<uchar>(i, j - 1) > 0) && (mask.at<uchar>(i, j + 1) > 0));
			}
			// ----------------------------------------------------------------------------------------------
			if (!flag_mask && len == 0) // rod of 3 pixels long is not horizonal	
			{
				continue;
			}

			if (len == 0 && i != H-1) // the start of rod
			{
				len = 1;
				head_y = i;
				head_x = j;
				tail_y = i;
				tail_x = j;
				for (k = 0; k < direction_num; k++) // initialize the sig which marks three different directions(situations) 
				{
					sig[k] = 0;
				}
				// obtain the graduation information
				gy = grady.at<double>(i, j);
				gx = gradx.at<double>(i, j);
				// three directions
				if (abs(gx) > 0)
				{
					if (abs(gy) < 1)
					{
						sig[1] = sig[1] + 1;
					}
					else
					{
						if (gy*gx > 0)
						{
							sig[0] = sig[0] + 1;
						}
						else
						{
							sig[2] = sig[2] + 1;
						}
					}
				}
			}
			else
			{
				// the flag_mask positive pixels is continue in y coordinate and the same in x coordinate
				if (flag_mask) // i!=0 prevent j:j -> j+1, i:H-1 -> 0
				{
					if (len == 0) // boundary situation:  i==H-1
					{
						for (k = 0; k < direction_num; k++) // initialize the sig which marks three different directions(situations) 
						{
							sig[k] = 0;
						}
						len = 1;
						head_y = i;
						head_x = j;
						tail_y = i;
						tail_x = j;
					}
					// obtain the graduation information
					gy = grady.at<double>(i, j);
					gx = gradx.at<double>(i, j);
					// three directions
					if (abs(gx) > 0)
					{
						if (abs(gy) < 1)
						{
							sig[1] = sig[1] + 1;
						}
						else
						{
							if (gy*gx > 0)
							{
								sig[0] = sig[0] + 1;
							}
							else
							{
								sig[2] = sig[2] + 1;
							}
						}
					}
					if (i != H - 1) // not boundary situation
					{
						len = len + 1;
						tail_y++;
						continue;
					}	
				}
				// deal with the whole rod
				if (len > TH_v)
				{
					slope = 10;
				}
				else
				{
					bool corner[4]; // 4 corner around the rod
					if (head_y == 0 || head_x == 0) // left-top 
					{
						corner[0] = false;
					}
					else
					{
						corner[0] = (mask.at<uchar>(head_y-1, head_x-1) > 0);
					}
					if (head_y == 0 || head_x == W-1) // right-top 
					{
						corner[1] = false;
					}
					else
					{
						corner[1] = (mask.at<uchar>(head_y - 1, head_x + 1) > 0);
					}
					if (tail_y == H-1 || tail_x == 0) // left-bottom
					{
						corner[2] = false;
					}
					else
					{
						corner[2] = (mask.at<uchar>(tail_y+ 1, tail_x - 1) > 0);
					}
					if (tail_y == H-1 || tail_x == W-1) // right-bottom
					{
						corner[3] = false;
					}
					else
					{
						corner[3] = (mask.at<uchar>(tail_y + 1, tail_x + 1) > 0);
					}
					if (corner[0] || corner[1] || corner[2] || corner[3]) // rod directin cases
					{
						int max_value_sig = 0, idx = 0;
						bool max_value_multi_flag = max_value_position_in_array(sig, &max_value_sig, &idx, direction_num);
						if (max_value_multi_flag)
						{
							slope = 0;
						}
						else
						{
							switch (idx)
							{
							case 0:
								slope = -len;
								break;
							case 1:
								slope = 10;
								break;
							case 2:
								slope = len;
								break;
							default:
								slope = 0;
							}
						}
					}
					else
					{
						slope = 0;
					}
				}

				// handle rod
				if (slope != 0)
				{
					(*edges)(Rect(head_x, head_y, tail_x - head_x+1, tail_y - head_y+1)) = 255;
					Mat block;
					block.create(tail_y - head_y + 1, tail_x - head_x + 3, CV_8U);
					img_sym(Rect(head_x , head_y +  1, tail_x - head_x + 3, tail_y - head_y + 1)).copyTo(block);
					int L = block.rows;
					Mat Hpatch = Mat::zeros(scale*L, scale, CV_8U);
					fililRod(&block, &Hpatch, L, scale, slope, TH_v);
					//img(Rect(head_x*scale, head_y*scale, (tail_x - head_x + 1)*scale, (tail_y - head_y + 1)*scale)) = img(Rect(head_x*scale, head_y*scale, (tail_x - head_x + 1)*scale, (tail_y - head_y + 1)*scale)) + Hpatch;
					for (int x = head_x*scale; x < head_x*scale + (tail_x - head_x + 1)*scale; x++)
					{
						for (int y = head_y*scale; y < head_y*scale + (tail_y - head_y + 1)*scale; y++)
						{
							uchar temp = Hpatch.at<uchar>(y - head_y*scale, x - head_x*scale);
							img.at<double>(y, x) = img.at<double>(y, x) + double(temp);
						}
					}
					cnt(Rect(head_x*scale, head_y*scale, (tail_x - head_x + 1)*scale, (tail_y - head_y + 1)*scale)) = cnt(Rect(head_x*scale, head_y*scale, (tail_x - head_x + 1)*scale, (tail_y - head_y + 1)*scale)) + 1;
					/*namedWindow("block", WINDOW_NORMAL);
					imshow("block", Hpatch); 
					waitKey(10);*/
				}

				// prepare for next rod
				len = 0;
			}
		}
	}
// ------------------------------------------------------------------------------------------------
// horizontal rods --------------------------------------------------------------------------------
	for (i = 0; i < H; i++)
	{
		for (j = 0; j < W; j++)
		{
			if ((mask.at<uchar>(i, j) == 0 && len == 0)) // the value in mask(i,j) is negative
			{
				continue;
			}

			if ((i == 0) || (i == H - 1)) // boundary situation
			{
				flag_mask = (mask.at<uchar>(i, j) > 0);
			}
			else // mask(i,j) - ( mask(i,j) & mask(i,j-1) & mask(i,j+1) )
			{
				flag_mask = (mask.at<uchar>(i, j) > 0) ^ ((mask.at<uchar>(i, j) > 0) && (mask.at<uchar>(i - 1, j) > 0) && (mask.at<uchar>(i + 1, j) > 0));
			}

			// ----------------------------------------------------------------------------------------------
			if (!flag_mask && len == 0) // rod of 3 pixels long is not horizonal	
			{
				continue;
			}

			if (len == 0 && j != W-1) // the start of rod
			{
				len = 1;
				head_y = i;
				head_x = j;
				tail_y = i;
				tail_x = j;
				for (k = 0; k < 3; k++) // initialize the sig which marks three different directions(situations) 
				{
					sig[k] = 0;
				}
				// obtain the graduation information
				gy = grady.at<double>(i, j);
				gx = gradx.at<double>(i, j);
				// three directions
				if (abs(gy) > 0)
				{
					if (abs(gx) > 1)
					{
						sig[1] = sig[1] + 1;
					}
					else
					{
						if (gy*gx > 0)
						{
							sig[0] = sig[0] + 1;
						}
						else
						{
							sig[2] = sig[2] + 1;
						}
					}
				}
			}
			else
			{
				// the flag_mask positive pixels is continue in y coordinate and the same in x coordinate
				if (flag_mask) // there are two situations: boundary or ordinary
				{
					if (len == 0) // boundary situation:  i==H-1
					{
						for (k = 0; k < direction_num; k++) // initialize the sig which marks three different directions(situations) 
						{
							sig[k] = 0;
						}
						len = 1;
						head_y = i;
						head_x = j;
						tail_y = i;
						tail_x = j;
					}
					// obtain the graduation information
					gy = grady.at<double>(i, j);
					gx = gradx.at<double>(i, j);
					// three directions
					if (abs(gy) > 0)
					{
						if (abs(gx) > 1)
						{
							sig[1] = sig[1] + 1;
						}
						else
						{
							if (gy*gx > 0)
							{
								sig[0] = sig[0] + 1;
							}
							else
							{
								sig[2] = sig[2] + 1;
							}
						}
					}
					if (j != W - 1) // not boundary situation
					{
						len = len + 1;
						tail_x++;
						continue;
					}
				}

				// deal with the whole rod
				if (len > TH_v)
				{
					slope = 10;
				}
				else
				{
					bool corner[4]; // 4 corner around the rod
					if (head_y == 0 || head_x == 0) // left-top 
					{
						corner[0] = false;
					}
					else
					{
						corner[0] = (mask.at<uchar>(head_y - 1, head_x - 1) > 0);
					}
					if (head_y == 0 || head_x == W-1) // right-top 
					{
						corner[1] = false;
					}
					else
					{
						corner[1] = (mask.at<uchar>(head_y - 1, head_x + 1) > 0);
					}
					if (tail_y == H-1 || tail_x == 0) // left-bottom
					{
						corner[2] = false;
					}
					else
					{
						corner[2] = (mask.at<uchar>(tail_y + 1, tail_x - 1) > 0);
					}
					if (tail_y == H-1 || tail_x == W-1) // right-bottom
					{
						corner[3] = false;
					}
					else
					{
						corner[3] = (mask.at<uchar>(tail_y + 1, tail_x + 1) > 0);
					}
					if (corner[0] || corner[1] || corner[2] || corner[3]) // rod directin cases
					{
						int max_value_sig = 0, idx = 0;
						bool max_value_multi_flag = max_value_position_in_array(sig, &max_value_sig, &idx, direction_num);
						if (max_value_multi_flag)
						{
							slope = 0;
						}
						else
						{
							switch (idx)
							{
							case 0:
								slope = -len;
								break;
							case 1:
								slope = 10;
								break;
							case 2:
								slope = len;
								break;
							default:
								slope = 0;
							}
						}
					}
					else
					{
						slope = 0;
					}
				}

				// handle rod
				if (slope != 0)
				{
					(*edges)(Rect(head_x, head_y, tail_x - head_x + 1, tail_y - head_y + 1)) = 255;
					Mat block;
					block.create(tail_y - head_y + 3, tail_x - head_x + 1, CV_8U);
					img_sym(Rect(head_x + 1, head_y, tail_x - head_x + 1, tail_y - head_y + 3)).copyTo(block);
					Mat block_transpose;
					transpose(block, block_transpose);
					int L = block_transpose.rows;
					Mat Hpatch = Mat::zeros(scale*L, scale, CV_8U);
					fililRod(&block_transpose, &Hpatch, L, scale, slope, TH_v);
					Mat Hpatch_transpose;
					transpose(Hpatch, Hpatch_transpose);
					for (int x = head_x*scale; x < head_x*scale + (tail_x - head_x + 1)*scale; x++)
					{
						for (int y = head_y*scale; y < head_y*scale + (tail_y - head_y + 1)*scale; y++)
						{
							uchar temp = Hpatch_transpose.at<uchar>(y - head_y*scale, x - head_x*scale);
							img.at<double>(y, x) = img.at<double>(y, x) + double(temp);
						}
					}
					//img(Rect(head_x*scale, head_y*scale, (tail_x - head_x + 1)*scale, (tail_y - head_y + 1)*scale)) = img(Rect(head_x*scale, head_y*scale, (tail_x - head_x + 1)*scale, (tail_y - head_y + 1)*scale)) + Hpatch_transpose;
					cnt(Rect(head_x*scale, head_y*scale, (tail_x - head_x + 1)*scale, (tail_y - head_y + 1)*scale)) = cnt(Rect(head_x*scale, head_y*scale, (tail_x - head_x + 1)*scale, (tail_y - head_y + 1)*scale)) + 1;
					/*namedWindow("block", WINDOW_NORMAL);
					imshow("block", Hpatch);
					waitKey(10);*/
				}

				// prepare for next rod
				len = 0;
			}
		}
	}

	for (i = 0; i < H*scale; i++)
	{
		for (j = 0; j < W*scale; j++)
		{
			if (cnt.at<double>(i, j) > 1)
			{
				double temp = img.at<double>(i, j);
				temp = temp / cnt.at<double>(i, j);
				uchar result = uchar(temp);
				(*imgH).at<uchar>(i, j) = result;
			}
			else
			{
				double temp = img.at<double>(i, j);
				uchar result = uchar(temp);
				(*imgH).at<uchar>(i, j) = result;
			}
		}
	}
}
Пример #13
0
void loadThread::run()
{
	if(type == loadThread::fft)
	{
		quint32 i,j,index;
		QColor color, oppositeColor;
		int colors[6];
		float theta = 1.0;
                float theta2 = 1.0;
                float rotatePhase = 1.0;
		int value = 0;
		qint64 dataSize = nx*ny;

		for(quint32 k=leftI;k<rightI;k++)
		{
			i = k % (nx-1); j = k/(nx-1);
			index = (j*(nx) + i)*2;
			if(mode == 4) value = int(((fastMagnitude(((float*)rawData)[index],((float*)rawData)[index+1])-imageMin)/(imageMax-imageMin))*255.0);
			else if(mode == 3) value = int(((fastMagnitude(((short*)rawData)[index],((short*)rawData)[index+1])-imageMin)/(imageMax-imageMin))*255.0);
			if(value>255) value = 255;
			if(value<0) value = 0;

			if(showPhase)
			{
				rotatePhase = powf(-1,i+j);
				if(mode == 4) theta = (atan2(((float*)rawData)[index+1]*rotatePhase,((float*)rawData)[index]*rotatePhase)+2.0*PI)/(2.0*PI);
				else if(mode == 3) theta = (atan2(((short*)rawData)[index+1]*rotatePhase,((short*)rawData)[index]*rotatePhase)+2.0*PI)/(2.0*PI);
				theta = fmod(theta,1.0);

				if(theta<0.0) theta = 0.0;
				if(theta>1.0) theta = 1.0;

				color.setHsvF(theta, 1.0, value/255.0);
				theta2 = 1.0 - theta;
				if(theta2 > 1.0) theta2 = 1.0;
				if(theta2 < 0.0) theta2 = 0.0;
				oppositeColor.setHsvF(theta2, 1.0, value/255.0);
				color = color.toRgb();
				oppositeColor = oppositeColor.toRgb();
				colors[0] = color.red();
				colors[1] = color.blue();
				colors[2] = color.green();
				colors[3] = oppositeColor.red();
				colors[4] = oppositeColor.blue();
				colors[5] = oppositeColor.green();
			}
			else
				for(int c=0;c<6;c++)
					colors[c] = value;

			if(format ==  QImage::Format_RGB32)
			{
				if(j!=0 && i!=0) ((unsigned int*)imageData)[((ny-j)*(2*(nx-1))+(2*(nx-1)-1-i)-(nx-1))] = qRgb(colors[3],colors[4],colors[5]);
				((unsigned int*)imageData)[((j)*(2*(nx-1))+i+(nx-1)-1)] = qRgb(colors[0],colors[1],colors[2]);

				if(j==0) ((unsigned int*)imageData)[i]=0;
				if(i==(nx-1)-1) ((unsigned int*)imageData)[((j)*(2*(nx-1))+(2*(nx-1)-1))]=0;
			}
			else if(format == QImage::Format_Indexed8)
			{
                                /* CHEN:
				imageData[((j)*(2*(nx-1))+i+(nx-1)-1)] = value;
				if(j!=0) imageData[((ny-j)*(2*(nx-1))+(2*(nx-1)-1-i)-(nx-1))] = value;
				else imageData[i]=0;
				if(i==(nx-1)-1) imageData[((j)*(2*(nx-1))+(2*(nx-1)-1))]=0;
                                */
				imageData[((j)*(2*(nx-1))+i+(nx-1)-1)] = value;
				if(j!=0) imageData[((ny-j)*(2*(nx-1))+(2*(nx-1)-1-i)-(nx-1))] = value;
				else imageData[i]=0;
				if(i==(nx-1)-1) imageData[((j)*(2*(nx-1))+(2*(nx-1)-1))]=0;
			} 
			else return;
		}   
	}
  else if(type == loadThread::real)
	{
		int width;
                int value = 0;
		if(format == QImage::Format_Indexed8) width = 1;
		else if(format == QImage::Format_RGB32) width = 4;
		else return;

		for(quint32 i=leftI;i<rightI;i++)
		{
			if (mode == 0)
			{
				value = int((((uchar*)rawData)[i/width]-imageMin)/(imageMax-imageMin)*255.0);
			}
			else if(mode == 1)
			{
				value = int((((unsigned short*)rawData)[i/width]-imageMin)/(imageMax-imageMin)*255.0);
			}
			else if(mode == 2)
			{
				value =int((((float*)rawData)[i/width]-imageMin)/(imageMax-imageMin)*255.0);
			}

			if(format == QImage::Format_RGB32)
			{
				if(value>255) value = 255; if(value<0) value = 0;
				((int*)imageData)[i/width] = qRgb(value,value,value);
			}
			else
			{
				imageData[i] = uchar(value);
			}
		}
	}
}
Пример #14
0
static const char *
match(struct match_state *ms, const char *s, const char *p)
{
	const char *ep, *res;
	char previous;

	if (ms->matchdepth-- == 0) {
		match_error(ms, "pattern too complex");
		return (NULL);
	}

	/* using goto's to optimize tail recursion */
 init:
	/* end of pattern? */
	if (p != ms->p_end) {
		switch (*p) {
		case '(':
			/* start capture */
			if (*(p + 1) == ')')
				/* position capture? */
				s = start_capture(ms, s, p + 2, CAP_POSITION);
			else
				s = start_capture(ms, s, p + 1, CAP_UNFINISHED);
			break;
		case ')':
			/* end capture */
			s = end_capture(ms, s, p + 1);
			break;
		case '$':
			/* is the '$' the last char in pattern? */
			if ((p + 1) != ms->p_end) {
				/* no; go to default */
				goto dflt;
			}
			 /* check end of string */
			s = (s == ms->src_end) ? s : NULL;
			break;
		case L_ESC:
			/* escaped sequences not in the format class[*+?-]? */
			switch (*(p + 1)) {
			case 'b':
				/* balanced string? */
				s = matchbalance(ms, s, p + 2);
				if (s != NULL) {
					p += 4;
					/* return match(ms, s, p + 4); */
					goto init;
				} /* else fail (s == NULL) */
				break;
			case 'f':
				/* frontier? */
				p += 2;
				if (*p != '[') {
					match_error(ms, "missing '['"
					    " after '%f' in pattern");
					break;
				}
				/* points to what is next */
				ep = classend(ms, p);
				if (ms->error != NULL)
					break;
				previous =
				    (s == ms->src_init) ? '\0' : *(s - 1);
				if (!matchbracketclass(uchar(previous),
				    p, ep - 1) &&
				    matchbracketclass(uchar(*s),
				    p, ep - 1)) {
					p = ep;
					/* return match(ms, s, ep); */
					goto init;
				}
				/* match failed */
				s = NULL;
				break;
			case '0' ... '9':
				/* capture results (%0-%9)? */
				s = match_capture(ms, s, uchar(*(p + 1)));
				if (s != NULL) {
					p += 2;
					/* return match(ms, s, p + 2) */
					goto init;
				}
				break;
			default:
				goto dflt;
			}
			break;
		default:

			/* pattern class plus optional suffix */
	dflt:
			/* points to optional suffix */
			ep = classend(ms, p);
			if (ms->error != NULL)
				break;

			/* does not match at least once? */
			if (!singlematch(ms, s, p, ep)) {
				if (ms->repetitioncounter-- == 0) {
					match_error(ms, "max repetition items");
					s = NULL; /* fail */
				/* accept empty? */
				} else if
				    (*ep == '*' || *ep == '?' || *ep == '-') {
					 p = ep + 1;
					/* return match(ms, s, ep + 1); */
					 goto init;
				} else {
					/* '+' or no suffix */
					s = NULL; /* fail */
				}
			} else {
				/* matched once */
				/* handle optional suffix */
				switch (*ep) {
				case '?':
					/* optional */
					if ((res =
					    match(ms, s + 1, ep + 1)) != NULL)
						s = res;
					else {
						/* 
						 * else return
						 *     match(ms, s, ep + 1);
						 */
						p = ep + 1;
						goto init;
					}
					break;
				case '+':
					/* 1 or more repetitions */
					s++; /* 1 match already done */
					/* FALLTHROUGH */
				case '*':
					/* 0 or more repetitions */
					s = max_expand(ms, s, p, ep);
					break;
				case '-':
					/* 0 or more repetitions (minimum) */
					s = min_expand(ms, s, p, ep);
					break;
				default:
					/* no suffix */
					s++;
					p = ep;
					/* return match(ms, s + 1, ep); */
					goto init;
				}
			}
			break;
		}
	}
	ms->matchdepth++;
	return s;
}
Пример #15
0
static POINTS2IMAGEPtr points_to_image(sensor_msgs::PointCloud2ConstPtr velodyneData,
				       cv::Mat cameraExtrinsicMat,
				       cv::Mat cameraMat, cv::Mat distCoeff,
				       cv::Size imageSize)
{
    POINTS2IMAGEPtr result(new POINTS2IMAGE);
    result->header=velodyneData->header;
    result->height=imageSize.height;
    result->width=imageSize.width;
    POINT2IMAGE tmpdata;
    tmpdata.intensity=0;
    tmpdata.distance=0;
    result->points.resize(result->height*result->width,tmpdata);

    cv::Mat invR=cameraExtrinsicMat(cv::Rect(0,0,3,3)).t();
    cv::Mat invT=-invR*(cameraExtrinsicMat(cv::Rect(3,0,1,3)));

    int n=velodyneData->height;
    int m=velodyneData->width;
    char * data=(char *)(velodyneData->data.data());
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            int id=i*m+j;
            float * dataptr=(float *)(data+id*velodyneData->point_step);

            cv::Mat point(1,3,CV_64F);
            point.at<double>(0)=double(dataptr[0]);
            point.at<double>(1)=double(dataptr[1]);
            point.at<double>(2)=double(dataptr[2]);
            point=point*invR.t()+invT.t();

            if(point.at<double>(2)<=0)
            {
                continue;
            }

            double tmpx=point.at<double>(0)/point.at<double>(2);
            double tmpy=point.at<double>(1)/point.at<double>(2);
            double r2=tmpx*tmpx+tmpy*tmpy;
            double tmpdist=1+distCoeff.at<double>(0)*r2+distCoeff.at<double>(1)*r2*r2+distCoeff.at<double>(4)*r2*r2*r2;

            cv::Point2d imagepoint;
            imagepoint.x=tmpx*tmpdist+2*distCoeff.at<double>(2)*tmpx*tmpy+distCoeff.at<double>(3)*(r2+2*tmpx*tmpx);
            imagepoint.y=tmpy*tmpdist+distCoeff.at<double>(2)*(r2+2*tmpy*tmpy)+2*distCoeff.at<double>(3)*tmpx*tmpy;
            imagepoint.x=cameraMat.at<double>(0,0)*imagepoint.x+cameraMat.at<double>(0,2);
            imagepoint.y=cameraMat.at<double>(1,1)*imagepoint.y+cameraMat.at<double>(1,2);
            if(imagepoint.x>=0&&imagepoint.x<result->width&&imagepoint.y>=0&&imagepoint.y<result->height)
            {
                int px=int(imagepoint.x+0.5);
                int py=int(imagepoint.y+0.5);
                int pid=py*result->width+px;
                if(result->points[pid].distance==0||(result->points[pid].distance/100.0)>point.at<double>(2))
                {
                    result->points[pid].distance=ushort(point.at<double>(2)*100+0.5);
                    result->points[pid].intensity=uchar(dataptr[4]);
                }
            }
        }
    }
    return result;
}
Пример #16
0
static const char *match (MatchState *ms, const char *s, const char *p) {
  init: /* using goto's to optimize tail recursion */
  switch (*p) {
    case '(': {  /* start capture */
      if (*(p+1) == ')')  /* position capture? */
        return start_capture(ms, s, p+2, CAP_POSITION);
      else
        return start_capture(ms, s, p+1, CAP_UNFINISHED);
    }
    case ')': {  /* end capture */
      return end_capture(ms, s, p+1);
    }
    case L_ESC: {
      switch (*(p+1)) {
        case 'b': {  /* balanced string? */
          s = matchbalance(ms, s, p+2);
          if (s == NULL) return NULL;
          p+=4; goto init;  /* else return match(ms, s, p+4); */
        }
        case 'f': {  /* frontier? */
          const char *ep; char previous;
          p += 2;
          if (*p != '[')
            luaL_error(ms->L, "missing " LUA_QL("[") " after "
                               LUA_QL("%%f") " in pattern");
          ep = classend(ms, p);  /* points to what is next */
          previous = (s == ms->src_init) ? '\0' : *(s-1);
          if (matchbracketclass(uchar(previous), p, ep-1) ||
             !matchbracketclass(uchar(*s), p, ep-1)) return NULL;
          p=ep; goto init;  /* else return match(ms, s, ep); */
        }
        default: {
          if (isdigit(uchar(*(p+1)))) {  /* capture results (%0-%9)? */
            s = match_capture(ms, s, uchar(*(p+1)));
            if (s == NULL) return NULL;
            p+=2; goto init;  /* else return match(ms, s, p+2) */
          }
          goto dflt;  /* case default */
        }
      }
    }
    case '\0': {  /* end of pattern */
      return s;  /* match succeeded */
    }
    case '$': {
      if (*(p+1) == '\0')  /* is the `$' the last char in pattern? */
        return (s == ms->src_end) ? s : NULL;  /* check end of string */
      else goto dflt;
    }
    default: dflt: {  /* it is a pattern item */
      const char *ep = classend(ms, p);  /* points to what is next */
      int m = s<ms->src_end && singlematch(uchar(*s), p, ep);
      switch (*ep) {
        case '?': {  /* optional */
          const char *res;
          if (m && ((res=match(ms, s+1, ep+1)) != NULL))
            return res;
          p=ep+1; goto init;  /* else return match(ms, s, ep+1); */
        }
        case '*': {  /* 0 or more repetitions */
          return max_expand(ms, s, p, ep);
        }
        case '+': {  /* 1 or more repetitions */
          return (m ? max_expand(ms, s+1, p, ep) : NULL);
        }
        case '-': {  /* 0 or more repetitions (minimum) */
          return min_expand(ms, s, p, ep);
        }
        default: {
          if (!m) return NULL;
          s++; p=ep; goto init;  /* else return match(ms, s+1, ep); */
        }
      }
    }
  }
}
Пример #17
0
TileMove SimplePlayer::getTileMove(int player, const Tile * tile, const MoveHistoryEntry & move, const TileMovesType & possible)
{
	static constexpr int dx[8] = {-1,  0, +1,  0, -1, +1, +1, -1};
	static constexpr int dy[8] = { 0, -1,  0, +1, -1, -1, +1, +1};
	static constexpr Tile::Side dir[4]    = {Tile::left,  Tile::up,    Tile::right, Tile::down};
	static constexpr Tile::Side oppDir[4] = {Tile::right, Tile::down,  Tile::left,  Tile::up  };
#if SIMPLE_PLAYER_USE_MEEPLE_PENALTY
	static constexpr int meeplePenalties[MEEPLE_COUNT+1] = {5, 4, 3, 2, 1, 1, 0, 0};
	int const meeplePenalty = meeplePenalties[meepleCount];
#else
	static constexpr int meeplePenalty = 0;
#endif

	int const myBonus = game->getPlayerCount();
	int const opponentBonus = myBonus - 1;
	int const meepleCount = game->getPlayerMeeples(player);
	bool const hasMeeples = (meepleCount > 0);

	meepleMoveSet = false;
	if (tile->getCloisterNode() != 0)
	{
		if (hasMeeples)
		{
#if SIMPLE_PLAYER_RULE_CLOISTER_1
			//TODO filter out rotations?
			VarLengthArrayWrapper<TileMove const *, TILE_ARRAY_LENGTH>::type goodMoves;
			int best = 0;
			for (TileMove const & tileMove : possible)
			{
				int surroundingTiles = 0;
				for (int i = 0; i < 8; ++i)
				{
					if (board->getTile(tileMove.x + dx[i], tileMove.y + dy[i]) != 0)
						++surroundingTiles;
				}
				if (surroundingTiles > best)
				{
					best = surroundingTiles;
					goodMoves.clear();
					goodMoves.push_back(&tileMove);
				}
				else if (surroundingTiles == best)
				{
					goodMoves.push_back(&tileMove);
				}
			}

			for (uchar i = 0, c = tile->getNodeCount(); i < c; ++i)
			{
				if (tile->getNode(i)->getTerrain() == Cloister)
				{
					meepleMove.nodeIndex = i;
					meepleMoveSet = true;
					break;
				}
			}

			return *goodMoves[r.nextInt(goodMoves.size())];
#endif
		}
		else
		{
#if SIMPLE_PLAYER_RULE_CLOISTER_2
			VarLengthArrayWrapper<TileMove const *, TILE_ARRAY_LENGTH>::type goodMoves;
			int best = -10;
			for (TileMove const & tileMove : possible)
			{
				int points = 0;
				for (int i = 0; i < 8; ++i)
				{
					Tile const * t = board->getTile(tileMove.x + dx[i], tileMove.y + dy[i]);
					if (t != 0)
					{
						Node const * n = t->getCloisterNode();
						if (n != 0 && n->getMaxMeeples() != 0)
						{
							if (n->getPlayerMeeples(player) != 0)
								points += myBonus;
							else
								points -= opponentBonus;
						}
					}
				}
				if (points > best)
				{
					best = points;
					goodMoves.clear();
					goodMoves.push_back(&tileMove);
				}
				else if (points == best)
				{
					goodMoves.push_back(&tileMove);
				}
			}

			return *goodMoves[r.nextInt(goodMoves.size())];
#endif
		}
	}
	else // No cloister tile
	{
#if  SIMPLE_PLAYER_RULE_ROAD_CITY
		VarLengthArrayWrapper<Move, TILE_ARRAY_LENGTH * NODE_ARRAY_LENGTH>::type goodMoves;
		int best = std::numeric_limits<int>::min();
		for (TileMove const & tileMove : possible)
		{
			int tilePoints = 0;
			VarLengthArrayWrapper<MeepleMove, TILE_ARRAY_LENGTH>::type meepleMoves(1);
			int bestNodePoints = 0; //std::numeric_limits<int>::min();
			for (int i = 0; i < 4; ++i)
			{
				Tile const * t = board->getTile(tileMove.x + dx[i], tileMove.y + dy[i]);
				if (t == 0)
					continue;
				int points = 0;

				Tile::Side const & oppDirection = oppDir[i];
				TerrainType const & type = t->getEdge(oppDirection);
				if (type == Field)	//TODO Fields
					continue;
				//else Cities and Roads

				Tile::Side const & direction = dir[i];
				Q_ASSERT(type == tile->getEdge(direction, tileMove.orientation));

				uchar nodeIndex;
				Node const * nn = tile->getFeatureNodeAndIndex(direction, nodeIndex, tileMove.orientation);
				Node const * on = t->getFeatureNode(oppDirection);
				Q_ASSERT(nn != 0);
				Q_ASSERT(on != 0);
				Q_ASSERT(nodeIndex != uchar(-1));
				Q_ASSERT(on->getTerrain() == nn->getTerrain());

				int const score = nn->getScore() + on->getScore();
				uchar const max = on->getMaxMeeples();
				if (max != 0) //isOccupied
				{
					for (uint p = 0; p < game->getPlayerCount(); ++p)
					{
						if (on->getPlayerMeeples(p) != max)
							continue;
						if (p == (uint)player)
							points += myBonus*score;
						else
							points -= opponentBonus * score;
					}
				}
				else if (hasMeeples)
				{
					int nodePoints = myBonus*score - meeplePenalty;
					switch (type)
					{
						case City:
							nodePoints *= 3;
							break;
						case Road:
							nodePoints *= 2;
							break;
						case Field:
						case Cloister:
						case None:
							Q_UNREACHABLE();
							break;
					}

					if (nodePoints > bestNodePoints)
					{
						bestNodePoints = nodePoints;
						meepleMoves.clear();
						meepleMoves.push_back(MeepleMove{nodeIndex});
					}
					else if (nodePoints == bestNodePoints)
					{
						meepleMoves.push_back(MeepleMove{nodeIndex});
					}
				}

				switch (type)
				{
					case City:
						points *= 3;
						break;
					case Road:
						points *= 2;
						break;
					case Field:
					case Cloister:
					case None:
						Q_UNREACHABLE();
						break;
				}
				tilePoints += points;
			}

			tilePoints += bestNodePoints;
			if (tilePoints > best)
			{
				best = tilePoints;
				goodMoves.clear();
				for (MeepleMove const & mm : meepleMoves)
					goodMoves.push_back(Move{tileMove, mm});
			}
			else if (tilePoints == best)
			{
				for (MeepleMove const & mm : meepleMoves)
					goodMoves.push_back(Move{tileMove, mm});
			}
		}

		Move const & m = goodMoves[r.nextInt(goodMoves.size())];
		meepleMove = m.meepleMove;
		meepleMoveSet = true;
		return m.tileMove;
#endif
	}
	return RandomPlayer::instance.getTileMove(player, tile, move, possible);
}
Пример #18
0
 //! \brief create an rgba unsigned int from a COLOR and alpha
 inline uint color_to_rgba(CCOLOR& col, double alpha=1) {
    return build_rgba(uchar(255*col[0]),
                      uchar(255*col[1]),
                      uchar(255*col[2]),
                      uchar(255*alpha ));
 }
Пример #19
0
/*!
    \internal
*/
qint64 QFSFileEnginePrivate::nativeRead(char *data, qint64 len)
{
    Q_Q(QFSFileEngine);

#ifdef Q_OS_SYMBIAN
    if (symbianFile.SubSessionHandle()) {
        if(len > KMaxTInt) {
            //this check is more likely to catch a corrupt length, since it isn't possible to allocate 2GB buffers (yet..)
            q->setError(QFile::ReadError, QLatin1String("Maximum 2GB in single read on this platform"));
            return -1;
        }
        TPtr8 ptr(reinterpret_cast<TUint8*>(data), static_cast<TInt>(len));
        TInt r = symbianFile.Read(symbianFilePos, ptr);
        if (r != KErrNone)
        {
            q->setError(QFile::ReadError, QSystemError(r, QSystemError::NativeError).toString());
            return -1;
        }
        symbianFilePos += ptr.Length();
        return qint64(ptr.Length());
    }
#endif
    if (fh && nativeIsSequential()) {
        size_t readBytes = 0;
        int oldFlags = fcntl(QT_FILENO(fh), F_GETFL);
        for (int i = 0; i < 2; ++i) {
            // Unix: Make the underlying file descriptor non-blocking
            if ((oldFlags & O_NONBLOCK) == 0)
                fcntl(QT_FILENO(fh), F_SETFL, oldFlags | O_NONBLOCK);

            // Cross platform stdlib read
            size_t read = 0;
            do {
                read = fread(data + readBytes, 1, size_t(len - readBytes), fh);
            } while (read == 0 && !feof(fh) && errno == EINTR);
            if (read > 0) {
                readBytes += read;
                break;
            } else {
                if (readBytes)
                    break;
                readBytes = read;
            }

            // Unix: Restore the blocking state of the underlying socket
            if ((oldFlags & O_NONBLOCK) == 0) {
                fcntl(QT_FILENO(fh), F_SETFL, oldFlags);
                if (readBytes == 0) {
                    int readByte = 0;
                    do {
                        readByte = fgetc(fh);
                    } while (readByte == -1 && errno == EINTR);
                    if (readByte != -1) {
                        *data = uchar(readByte);
                        readBytes += 1;
                    } else {
                        break;
                    }
                }
            }
        }
        // Unix: Restore the blocking state of the underlying socket
        if ((oldFlags & O_NONBLOCK) == 0) {
            fcntl(QT_FILENO(fh), F_SETFL, oldFlags);
        }
        if (readBytes == 0 && !feof(fh)) {
            // if we didn't read anything and we're not at EOF, it must be an error
            q->setError(QFile::ReadError, qt_error_string(int(errno)));
            return -1;
        }
        return readBytes;
    }

    return readFdFh(data, len);
}
Пример #20
0
void InputSelectionWidget::slotUpperSpinValueChanged(int value)
{
    m_inputSource->setRange(uchar(m_lowerSpin->value()), uchar(value));
}
Пример #21
0
static const char *match (MatchState *ms, const char *s, const char *p) {
  if (ms->matchdepth-- == 0)
    luaL_error(ms->L, "pattern too complex");
  init: /* using goto's to optimize tail recursion */
  if (p != ms->p_end) {  /* end of pattern? */
    switch (*p) {
      case '(': {  /* start capture */
        if (*(p + 1) == ')')  /* position capture? */
          s = start_capture(ms, s, p + 2, CAP_POSITION);
        else
          s = start_capture(ms, s, p + 1, CAP_UNFINISHED);
        break;
      }
      case ')': {  /* end capture */
        s = end_capture(ms, s, p + 1);
        break;
      }
      case '$': {
        if ((p + 1) != ms->p_end)  /* is the `$' the last char in pattern? */
          goto dflt;  /* no; go to default */
        s = (s == ms->src_end) ? s : NULL;  /* check end of string */
        break;
      }
      case L_ESC: {  /* escaped sequences not in the format class[*+?-]? */
        switch (*(p + 1)) {
          case 'b': {  /* balanced string? */
            s = matchbalance(ms, s, p + 2);
            if (s != NULL) {
              p += 4; goto init;  /* return match(ms, s, p + 4); */
            }  /* else fail (s == NULL) */
            break;
          }
          case 'f': {  /* frontier? */
            const char *ep; char previous;
            p += 2;
            if (*p != '[')
              luaL_error(ms->L, "missing " LUA_QL("[") " after "
                                 LUA_QL("%%f") " in pattern");
            ep = classend(ms, p);  /* points to what is next */
            previous = (s == ms->src_init) ? '\0' : *(s - 1);
            if (!matchbracketclass(uchar(previous), p, ep - 1) &&
               matchbracketclass(uchar(*s), p, ep - 1)) {
              p = ep; goto init;  /* return match(ms, s, ep); */
            }
            s = NULL;  /* match failed */
            break;
          }
          case '0': case '1': case '2': case '3':
          case '4': case '5': case '6': case '7':
          case '8': case '9': {  /* capture results (%0-%9)? */
            s = match_capture(ms, s, uchar(*(p + 1)));
            if (s != NULL) {
              p += 2; goto init;  /* return match(ms, s, p + 2) */
            }
            break;
          }
          default: goto dflt;
        }
        break;
      }
      default: dflt: {  /* pattern class plus optional suffix */
        const char *ep = classend(ms, p);  /* points to optional suffix */
        /* does not match at least once? */
        if (!singlematch(ms, s, p, ep)) {
          if (*ep == '*' || *ep == '?' || *ep == '-') {  /* accept empty? */
            p = ep + 1; goto init;  /* return match(ms, s, ep + 1); */
          }
          else  /* '+' or no suffix */
            s = NULL;  /* fail */
        }
        else {  /* matched once */
          switch (*ep) {  /* handle optional suffix */
            case '?': {  /* optional */
              const char *res;
              if ((res = match(ms, s + 1, ep + 1)) != NULL)
                s = res;
              else {
                p = ep + 1; goto init;  /* else return match(ms, s, ep + 1); */
              }
              break;
            }
            case '+':  /* 1 or more repetitions */
              s++;  /* 1 match already done */
              /* go through */
            case '*':  /* 0 or more repetitions */
              s = max_expand(ms, s, p, ep);
              break;
            case '-':  /* 0 or more repetitions (minimum) */
              s = min_expand(ms, s, p, ep);
              break;
            default:  /* no suffix */
              s++; p = ep; goto init;  /* return match(ms, s + 1, ep); */
          }
        }
        break;
      }
    }
  }
  ms->matchdepth++;
  return s;
}
Пример #22
0
void GLWidget::draw()
{
    QPainter p(this); // used for text overlay

    // save the GL state set for QPainter
    saveGLState();

    // render the 'bubbles.svg' file into our framebuffer object
    QPainter fbo_painter(fbo);
    svg_renderer->render(&fbo_painter);
    fbo_painter.end();

    // draw into the GL widget
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glFrustum(-1, 1, -1, 1, 10, 100);
    glTranslatef(0.0f, 0.0f, -15.0f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glViewport(0, 0, width(), height());
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glBindTexture(GL_TEXTURE_2D, fbo->texture());
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glEnable(GL_TEXTURE_2D);
    glEnable(GL_MULTISAMPLE);
    glEnable(GL_CULL_FACE);

    // draw background
    glPushMatrix();
    glScalef(1.7f, 1.7f, 1.7f);
    glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
    glCallList(tile_list);
    glPopMatrix();

    const int w = logo.width();
    const int h = logo.height();

    glRotatef(rot_x, 1.0f, 0.0f, 0.0f);
    glRotatef(rot_y, 0.0f, 1.0f, 0.0f);
    glRotatef(rot_z, 0.0f, 0.0f, 1.0f);
    glScalef(scale/w, scale/w, scale/w);

    glDepthFunc(GL_LESS);
    glEnable(GL_DEPTH_TEST);
    // draw the Qt icon
    glTranslatef(-w+1, -h+1, 0.0f);
    for (int y=h-1; y>=0; --y) {
        uint *p = (uint*) logo.scanLine(y);
        uint *end = p + w;
        int  x = 0;
        while (p < end) {
            glColor4ub(qRed(*p), qGreen(*p), qBlue(*p), uchar(qAlpha(*p)*.9));
            glTranslatef(0.0f, 0.0f, wave[y*w+x]);
            if (qAlpha(*p) > 128)
                glCallList(tile_list);
            glTranslatef(0.0f, 0.0f, -wave[y*w+x]);
            glTranslatef(2.0f, 0.0f, 0.0f);
            ++x;
            ++p;
        }
        glTranslatef(-w*2.0f, 2.0f, 0.0f);
    }

    // restore the GL state that QPainter expects
    restoreGLState();

    // draw the overlayed text using QPainter
    p.setPen(QColor(197, 197, 197, 157));
    p.setBrush(QColor(197, 197, 197, 127));
    p.drawRect(QRect(0, 0, width(), 50));
    p.setPen(Qt::black);
    p.setBrush(Qt::NoBrush);
    const QString str1(tr("A simple OpenGL framebuffer object example."));
    const QString str2(tr("Use the mouse wheel to zoom, press buttons and move mouse to rotate, double-click to flip."));
    QFontMetrics fm(p.font());
    p.drawText(width()/2 - fm.width(str1)/2, 20, str1);
    p.drawText(width()/2 - fm.width(str2)/2, 20 + fm.lineSpacing(), str2);
}
int main(int argc, char * argv[])
{
    system("bash dataprep.sh");

    #pragma omp parallel for
    for(int n=1; n<argc; n++)
    {
        Mat srcImg=imread(argv[n],CV_LOAD_IMAGE_GRAYSCALE);
        Mat img=imread(argv[n],CV_LOAD_IMAGE_COLOR);
        string str=argv[n];
        cout<<"\n\n processing the image: "<<str<<endl;
        if (!srcImg.data)
        {
            cout<<"failed to load the image!\n";
            // return 0;
            continue;
        }

        for(int i=0; i< srcImg.rows; i++)
        {
            for(int j=0; j<5; j++)
            {
                srcImg.at<uchar>(i,j)=uchar(0);
                srcImg.at<uchar>(i,srcImg.cols-j-1)=uchar(0);
            }
        }

        for(int i=0; i<srcImg.cols; i++)
        {
            for(int j=0; j<5; j++)
            {
                srcImg.at<uchar>(j,i)=uchar(0);
                srcImg.at<uchar>(srcImg.rows-j-1,i)=uchar(0);
            }
        }

        //detect lsd lines in an input image;
        int cols=srcImg.rows;
        int rows=srcImg.cols;
        double*  lsd_srcImg=new double[cols*rows];
        for (int i=0; i<cols; i++)
        {
            for (int j=0; j<rows; j++)
            {
                lsd_srcImg[i+j*cols]=static_cast<double>(srcImg.at<uchar>(i,j));
            }
        }
        double* lsd_dstImg;
        int n=0;
        lsd_dstImg=lsd(&n,lsd_srcImg,cols,rows);

        cout<<"finished the lsd detection!\n";
        vector<LSDline> lsdLine;
        for (int i=0; i<n; i++)
        {
            LSDline lsdLine_tmp;
            lsdLine_tmp.lineBegin.y=lsd_dstImg[i*7+0];
            lsdLine_tmp.lineBegin.x=lsd_dstImg[i*7+1];
            lsdLine_tmp.lineEnd.y=lsd_dstImg[i*7+2];
            lsdLine_tmp.lineEnd.x=lsd_dstImg[i*7+3];
            lsdLine_tmp.width=lsd_dstImg[i*7+4];
            lsdLine_tmp.p=lsd_dstImg[i*7+5];
            lsdLine_tmp.log_nfa=lsd_dstImg[i*7+6];
            lsdLine_tmp.tagBegin=1;
            lsdLine_tmp.tagEnd=1;
            cout<<lsdLine_tmp.lineBegin.x<<" "<<lsdLine_tmp.lineBegin.y<<" "<<lsdLine_tmp.lineEnd.x<<"  "<<lsdLine_tmp.lineEnd.y<<endl;
            float distThreshold=12;
            if(sqrt((lsdLine_tmp.lineBegin.x-lsdLine_tmp.lineEnd.x)*(lsdLine_tmp.lineBegin.x-lsdLine_tmp.lineEnd.x)+
                    (lsdLine_tmp.lineBegin.y-lsdLine_tmp.lineEnd.y)*(lsdLine_tmp.lineBegin.y-lsdLine_tmp.lineEnd.y))>distThreshold)
            {
                lsdLine.push_back(lsdLine_tmp);
            }
        }

        cout<<"the detected lsd lines' number is: "<<lsdLine.size()<<endl;
        //define the img1 to display the detected LSD lines and junctions;
        Mat img1(img.size(),CV_8UC3,Scalar::all(0));
        delete[] lsd_srcImg;


        displayLSDline(lsdLine,img1);
        //imwrite("img1.bmp",img1);

        vector<Ljunct> Jlist;
        vector<LsdJunction> lsdJunction;



        if(LSD2Junct(lsdLine,Jlist,lsdJunction,search_distance,img))
        {
            cout<<"transform successfully!\n";
        }
        else
        {
            cout<<"cannot form L-junctions from LSD lines!\n";
            //for processing, we also need to write the the detect result;
            char c='_';
            int name_end=str.find(c,0);
            string ori_name_tmp1=str.substr(7,name_end-7);
            // char* ch2=".bmp";
            // int location=str.find(ch2,0);
            // string ori_name_tmp1 = str.substr(7,location-7);
            string dst_tmp = "./DetectResultOri/"+ori_name_tmp1;
            string ori_name_tmp="./OrigImg/"+ori_name_tmp1;

            // Mat oriImg_tmp = imread(ori_name_tmp.c_str(),CV_LOAD_IMAGE_COLOR);
            // imwrite(dst_tmp,oriImg_tmp);
            string filestring_tmp="./dstFile/"+str.substr(srcImgDir.size(),str.size()-4)+".jpg.txt";
            ofstream file_out(filestring_tmp.c_str());
            if(!file_out.is_open())
            {
                cout<<"cannot open the txt file!\n";
            }
            string imageName=str.substr(srcImgDir.size(),str.size()-4)+".jpg";
            file_out<<imageName<<"\t"<<img.cols<<"\t"<<img.rows<<endl;

            continue;
        }
        //vector<string> code_string1;
        vector<Ljunct> Jlist_coding;
        vector<codeStringBoundingBox> code_string;
        code_string=encodingFromLsdJunction(lsdJunction, Jlist_coding,srcImg);
        classifyRoadMarking(code_string,srcImg);

        string str_tmp=str.substr(srcImgDir.size(),str.size());
        cout<<"!!!!!the Jlist_coding size is: "<<Jlist_coding.size()<<endl<<endl;
        
        displayLjunct(Jlist_coding,img1,str_tmp);

        DrawBoundingBox(code_string,img,str_tmp);

        //drawing the bounding box in original image;
        char c='_';
        int name_end=str.find(c,0);
      //  string ori_name=str.substr(7,name_end-7);
        
         char* ch=".bmp";
         int location=str.find(ch,0);
         cout<<"the find .bmp in "<<str<<" is in "<<location<<endl;
         string ori_name=str.substr(7,location-7);
        
         cout<<ori_name<<endl;
         string ori_img="./OrigImg/"+ori_name+".JPG";

         Mat oriImg=imread(ori_img.c_str(),CV_LOAD_IMAGE_COLOR);
         if(!oriImg.data)
         {
             cout<<"cannot load the original image!\n";
             //return 0;
             char ch;
             cin.get(ch);
             continue;
         }
         
        /*
        Point2f imgP1=Point2f(219,668);
        Point2f imgP2=Point2f(452,469);
        Point2f imgP3=Point2f(622,472);
        Point2f imgP4=Point2f(882,681);
        Point2f imgP5=Point2f(388,520);
        Point2f imgP6=Point2f(688,523);
        Point2f imgP7=Point2f(454,538);
        Point2f imgP8=Point2f(645,539);
        Point2f imgP9=Point2f(508,486);
        Point2f imgP10=Point2f(573,509);

        Point2f imgP[10]= {imgP1,imgP2,imgP3,imgP4,imgP5,imgP6,imgP7,imgP8,imgP9,imgP10};
        Point2f objP1=Point2f(250,900);
        Point2f objP2=Point2f(250,100);
        Point2f objP3=Point2f(800,100);
        Point2f objP4=Point2f(800,900);
        Point2f objP5=Point2f(250,550);
        Point2f objP6=Point2f(800,550);
        Point2f objP7=Point2f(400,625);
        Point2f objP8=Point2f(650,625);
        Point2f objP9=Point2f(450,300);
        Point2f objP10=Point2f(600,475);



        Point2f objP[10]= {objP1,objP2,objP3,objP4,objP5,objP6,objP7,objP8,objP9,objP10};
        */
        vector<Point2f> imgP;
        imgP.push_back(Point2f(300,450));
        imgP.push_back(Point2f(700,450));
        imgP.push_back(Point2f(465,450));
        imgP.push_back(Point2f(535,450));
        imgP.push_back(Point2f(260,820));
        imgP.push_back(Point2f(740,820));

        vector<Point2f> objP;
        objP.push_back(Point2f(0,0));
        objP.push_back(Point2f(1000,0));
        objP.push_back(Point2f(400,0));
        objP.push_back(Point2f(600,0));
        objP.push_back(Point2f(400,1000));
        objP.push_back(Point2f(600,1000));

        //Mat H=getPerspectiveTransform(objP,imgP);
        Mat H=findHomography(objP,imgP,CV_RANSAC);
        DrawBoundingBox_Ori(code_string,oriImg,ori_name,H,str_tmp);
    }
    return 0;
}
Пример #24
0
static inline Char Latin1Char(char ch)
{
    return ushort(uchar(ch));
}
Пример #25
0
bool MidiRecorder::writeTrack(MasterClockNanos midiTick) {

    // Writing track header, we'll fill length field later
    if (!writeFile(trackID, 4)) return false;
    quint64 trackLenPos = file.pos();
    quint32 trackLen = 0;
    if (!writeFile((char *)&trackLen, 4)) return false;

    // Writing actual MIDI events
    uint runningStatus = 0;
    quint32 eventTicks = 0; // Number of ticks from start of recording
    uchar eventData[16]; // Buffer for single short event / sysex header
    for (int i = 0; i < midiEventList.count(); i++) {
        // Compute timestamp
        const QMidiEvent &evt = midiEventList.at(i);
        uchar *data = eventData;
        quint32 deltaTicks = (evt.getTimestamp() - startNanos) / midiTick - eventTicks;
        eventTicks += deltaTicks;
        writeVarLenInt(data, deltaTicks);

        uchar *sysexData = evt.getSysexData();
        if (sysexData != NULL) {
            // Process Sysex
            quint32 sysexLen = evt.getSysexLen();
            if (sysexLen < 4 || sysexData[0] != 0xF0 || sysexData[sysexLen - 1] != 0xF7) {
                // Invalid sysex, skipping
                qDebug() << "MidiRecorder: wrong sysex skipped at:" << evt.getTimestamp() - startNanos << "nanos, length:" << sysexLen;
                eventTicks -= deltaTicks;
                continue;
            }
            *(data++) = sysexData[0];
            writeVarLenInt(data, sysexLen - 1);
            if (!writeFile((char *)eventData, data - eventData)) return false;
            if (!writeFile((char *)&sysexData[1], sysexLen - 1)) return false;
            runningStatus = 0;
        } else {
            // Process short message
            quint32 message = evt.getShortMessage();
            uint newStatus = message & 0xFF;
            if (0xF0 <= newStatus) {
                // No support for escaping System messages, ignore
                qDebug() << "MidiRecorder: unsupported System message skipped at:" << evt.getTimestamp() - startNanos << "nanos, code:" << newStatus;
                continue;
            }
            if (newStatus == runningStatus) {
                message >>= 8;
                if ((newStatus & 0xE0) == 0xC0) {
                    // It's a short message with one data byte
                    *(data++) = uchar(message);
                } else {
                    // It's a short message with two data bytes
                    qToLittleEndian<quint16>(message, data);
                    data += 2;
                }
            } else {
                if ((newStatus & 0xE0) == 0xC0) {
                    // It's a short message with one data byte
                    qToLittleEndian<quint16>(message, data);
                    data += 2;
                } else {
                    // It's a short message with two data bytes
                    qToLittleEndian<quint32>(message, data);
                    data += 3;
                }
                runningStatus = newStatus;
            }
            if (!writeFile((char *)eventData, data - eventData)) return false;
        }
Пример #26
0
static inline QString escapedString(const Char *begin, int length, bool isUnicode = true)
{
    QChar quote(QLatin1Char('"'));
    QString out = quote;

    bool lastWasHexEscape = false;
    const Char *end = begin + length;
    for (const Char *p = begin; p != end; ++p) {
        // check if we need to insert "" to break an hex escape sequence
        if (Q_UNLIKELY(lastWasHexEscape)) {
            if (fromHex(*p) != -1) {
                // yes, insert it
                out += QLatin1Char('"');
                out += QLatin1Char('"');
            }
            lastWasHexEscape = false;
        }

        if (sizeof(Char) == sizeof(QChar)) {
            // Surrogate characters are category Cs (Other_Surrogate), so isPrintable = false for them
            int runLength = 0;
            while (p + runLength != end &&
                   QChar::isPrint(p[runLength]) && p[runLength] != '\\' && p[runLength] != '"')
                ++runLength;
            if (runLength) {
                out += QString(reinterpret_cast<const QChar *>(p), runLength);
                p += runLength - 1;
                continue;
            }
        } else if (isPrintable(*p) && *p != '\\' && *p != '"') {
            QChar c = QLatin1Char(*p);
            out += c;
            continue;
        }

        // print as an escape sequence (maybe, see below for surrogate pairs)
        int buflen = 2;
        ushort buf[sizeof "\\U12345678" - 1];
        buf[0] = '\\';

        switch (*p) {
        case '"':
        case '\\':
            buf[1] = *p;
            break;
        case '\b':
            buf[1] = 'b';
            break;
        case '\f':
            buf[1] = 'f';
            break;
        case '\n':
            buf[1] = 'n';
            break;
        case '\r':
            buf[1] = 'r';
            break;
        case '\t':
            buf[1] = 't';
            break;
        default:
            if (!isUnicode) {
                // print as hex escape
                buf[1] = 'x';
                buf[2] = toHexUpper(uchar(*p) >> 4);
                buf[3] = toHexUpper(uchar(*p));
                buflen = 4;
                lastWasHexEscape = true;
                break;
            }
            if (QChar::isHighSurrogate(*p)) {
                if ((p + 1) != end && QChar::isLowSurrogate(p[1])) {
                    // properly-paired surrogates
                    uint ucs4 = QChar::surrogateToUcs4(*p, p[1]);
                    if (QChar::isPrint(ucs4)) {
                        buf[0] = *p;
                        buf[1] = p[1];
                        buflen = 2;
                    } else {
                        buf[1] = 'U';
                        buf[2] = '0'; // toHexUpper(ucs4 >> 32);
                        buf[3] = '0'; // toHexUpper(ucs4 >> 28);
                        buf[4] = toHexUpper(ucs4 >> 20);
                        buf[5] = toHexUpper(ucs4 >> 16);
                        buf[6] = toHexUpper(ucs4 >> 12);
                        buf[7] = toHexUpper(ucs4 >> 8);
                        buf[8] = toHexUpper(ucs4 >> 4);
                        buf[9] = toHexUpper(ucs4);
                        buflen = 10;
                    }
                    ++p;
                    break;
                }
                // improperly-paired surrogates, fall through
            }
            buf[1] = 'u';
            buf[2] = toHexUpper(ushort(*p) >> 12);
            buf[3] = toHexUpper(ushort(*p) >> 8);
            buf[4] = toHexUpper(*p >> 4);
            buf[5] = toHexUpper(*p);
            buflen = 6;
        }
Пример #27
0
QT_BEGIN_NAMESPACE

#ifndef QT_NO_CODEC_FOR_C_STRINGS
#  ifdef QT_NO_TEXTCODEC
#    define QT_NO_CODEC_FOR_C_STRINGS
#  endif
#endif

#define FLAG(x) (1 << (x))

/*!
    \class QLatin1Char
    \brief The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.

    \ingroup string-processing

    This class is only useful to avoid the codec for C strings business
    in the QChar(ch) constructor. You can avoid it by writing
    QChar(ch, 0).

    \sa QChar, QLatin1String, QString
*/

/*!
    \fn const char QLatin1Char::toLatin1() const

    Converts a Latin-1 character to an 8-bit ASCII representation of
    the character.
*/

/*!
    \fn const ushort QLatin1Char::unicode() const

    Converts a Latin-1 character to an 16-bit-encoded Unicode representation
    of the character.
*/

/*!
    \fn QLatin1Char::QLatin1Char(char c)

    Constructs a Latin-1 character for \a c. This constructor should be
    used when the encoding of the input character is known to be Latin-1.
*/

/*!
    \class QChar
    \brief The QChar class provides a 16-bit Unicode character.

    \ingroup string-processing
    \reentrant

    In Qt, Unicode characters are 16-bit entities without any markup
    or structure. This class represents such an entity. It is
    lightweight, so it can be used everywhere. Most compilers treat
    it like a \c{unsigned short}.

    QChar provides a full complement of testing/classification
    functions, converting to and from other formats, converting from
    composed to decomposed Unicode, and trying to compare and
    case-convert if you ask it to.

    The classification functions include functions like those in the
    standard C++ header \<cctype\> (formerly \<ctype.h\>), but
    operating on the full range of Unicode characters. They all
    return true if the character is a certain type of character;
    otherwise they return false. These classification functions are
    isNull() (returns true if the character is '\\0'), isPrint()
    (true if the character is any sort of printable character,
    including whitespace), isPunct() (any sort of punctation),
    isMark() (Unicode Mark), isLetter() (a letter), isNumber() (any
    sort of numeric character, not just 0-9), isLetterOrNumber(), and
    isDigit() (decimal digits). All of these are wrappers around
    category() which return the Unicode-defined category of each
    character.

    QChar also provides direction(), which indicates the "natural"
    writing direction of this character. The joining() function
    indicates how the character joins with its neighbors (needed
    mostly for Arabic) and finally hasMirrored(), which indicates
    whether the character needs to be mirrored when it is printed in
    its "unnatural" writing direction.

    Composed Unicode characters (like \aring) can be converted to
    decomposed Unicode ("a" followed by "ring above") by using
    decomposition().

    In Unicode, comparison is not necessarily possible and case
    conversion is very difficult at best. Unicode, covering the
    "entire" world, also includes most of the world's case and
    sorting problems. operator==() and friends will do comparison
    based purely on the numeric Unicode value (code point) of the
    characters, and toUpper() and toLower() will do case changes when
    the character has a well-defined uppercase/lowercase equivalent.
    For locale-dependent comparisons, use
    QString::localeAwareCompare().

    The conversion functions include unicode() (to a scalar),
    toLatin1() (to scalar, but converts all non-Latin-1 characters to
    0), row() (gives the Unicode row), cell() (gives the Unicode
    cell), digitValue() (gives the integer value of any of the
    numerous digit characters), and a host of constructors.

    QChar provides constructors and cast operators that make it easy
    to convert to and from traditional 8-bit \c{char}s. If you
    defined \c QT_NO_CAST_FROM_ASCII and \c QT_NO_CAST_TO_ASCII, as
    explained in the QString documentation, you will need to
    explicitly call fromAscii() or fromLatin1(), or use QLatin1Char,
    to construct a QChar from an 8-bit \c char, and you will need to
    call toAscii() or toLatin1() to get the 8-bit value back.

    \sa QString, Unicode, QLatin1Char
*/

/*!
    \enum QChar::UnicodeVersion

    Specifies which version of the \l{http://www.unicode.org/}{Unicode standard}
    introduced a certain character.

    \value Unicode_1_1  Version 1.1
    \value Unicode_2_0  Version 2.0
    \value Unicode_2_1_2  Version 2.1.2
    \value Unicode_3_0  Version 3.0
    \value Unicode_3_1  Version 3.1
    \value Unicode_3_2  Version 3.2
    \value Unicode_4_0  Version 4.0
    \value Unicode_4_1  Version 4.1
    \value Unicode_5_0  Version 5.0
    \value Unicode_Unassigned  The value is not assigned to any character
        in version 5.0 of Unicode.

    \sa unicodeVersion()
*/

/*!
    \enum QChar::Category

    This enum maps the Unicode character categories.

    The following characters are normative in Unicode:

    \value Mark_NonSpacing  Unicode class name Mn

    \value Mark_SpacingCombining  Unicode class name Mc

    \value Mark_Enclosing  Unicode class name Me

    \value Number_DecimalDigit  Unicode class name Nd

    \value Number_Letter  Unicode class name Nl

    \value Number_Other  Unicode class name No

    \value Separator_Space  Unicode class name Zs

    \value Separator_Line  Unicode class name Zl

    \value Separator_Paragraph  Unicode class name Zp

    \value Other_Control  Unicode class name Cc

    \value Other_Format  Unicode class name Cf

    \value Other_Surrogate  Unicode class name Cs

    \value Other_PrivateUse  Unicode class name Co

    \value Other_NotAssigned  Unicode class name Cn


    The following categories are informative in Unicode:

    \value Letter_Uppercase  Unicode class name Lu

    \value Letter_Lowercase  Unicode class name Ll

    \value Letter_Titlecase  Unicode class name Lt

    \value Letter_Modifier  Unicode class name Lm

    \value Letter_Other Unicode class name Lo

    \value Punctuation_Connector  Unicode class name Pc

    \value Punctuation_Dash  Unicode class name Pd

    \value Punctuation_Open  Unicode class name Ps

    \value Punctuation_Close  Unicode class name Pe

    \value Punctuation_InitialQuote  Unicode class name Pi

    \value Punctuation_FinalQuote  Unicode class name Pf

    \value Punctuation_Other  Unicode class name Po

    \value Symbol_Math  Unicode class name Sm

    \value Symbol_Currency  Unicode class name Sc

    \value Symbol_Modifier  Unicode class name Sk

    \value Symbol_Other  Unicode class name So

    \value NoCategory  Qt cannot find an appropriate category for the character.

    \omitvalue Punctuation_Dask

    \sa category()
*/

/*!
    \enum QChar::Direction

    This enum type defines the Unicode direction attributes. See the
    \l{http://www.unicode.org/}{Unicode Standard} for a description
    of the values.

    In order to conform to C/C++ naming conventions "Dir" is prepended
    to the codes used in the Unicode Standard.

    \value DirAL
    \value DirAN
    \value DirB
    \value DirBN
    \value DirCS
    \value DirEN
    \value DirES
    \value DirET
    \value DirL
    \value DirLRE
    \value DirLRO
    \value DirNSM
    \value DirON
    \value DirPDF
    \value DirR
    \value DirRLE
    \value DirRLO
    \value DirS
    \value DirWS

    \sa direction()
*/

/*!
    \enum QChar::Decomposition

    This enum type defines the Unicode decomposition attributes. See
    the \l{http://www.unicode.org/}{Unicode Standard} for a
    description of the values.

    \value NoDecomposition
    \value Canonical
    \value Circle
    \value Compat
    \value Final
    \value Font
    \value Fraction
    \value Initial
    \value Isolated
    \value Medial
    \value Narrow
    \value NoBreak
    \value Small
    \value Square
    \value Sub
    \value Super
    \value Vertical
    \value Wide

    \omitvalue Single

    \sa decomposition()
*/

/*!
    \enum QChar::Joining

    This enum type defines the Unicode joining attributes. See the
    \l{http://www.unicode.org/}{Unicode Standard} for a description
    of the values.

    \value Center
    \value Dual
    \value OtherJoining
    \value Right

    \sa joining()
*/

/*!
    \enum QChar::CombiningClass

    \internal

    This enum type defines names for some of the Unicode combining
    classes. See the \l{http://www.unicode.org/}{Unicode Standard}
    for a description of the values.

    \value Combining_Above
    \value Combining_AboveAttached
    \value Combining_AboveLeft
    \value Combining_AboveLeftAttached
    \value Combining_AboveRight
    \value Combining_AboveRightAttached
    \value Combining_Below
    \value Combining_BelowAttached
    \value Combining_BelowLeft
    \value Combining_BelowLeftAttached
    \value Combining_BelowRight
    \value Combining_BelowRightAttached
    \value Combining_DoubleAbove
    \value Combining_DoubleBelow
    \value Combining_IotaSubscript
    \value Combining_Left
    \value Combining_LeftAttached
    \value Combining_Right
    \value Combining_RightAttached
*/

/*!
    \enum QChar::SpecialCharacter

    \value Null A QChar with this value isNull().
    \value Nbsp Non-breaking space.
    \value ReplacementCharacter The character shown when a font has no glyph
           for a certain codepoint. A special question mark character is often
           used. Codecs use this codepoint when input data cannot be
           represented in Unicode.
    \value ObjectReplacementCharacter Used to represent an object such as an
           image when such objects cannot be presented.
    \value ByteOrderMark
    \value ByteOrderSwapped
    \value ParagraphSeparator
    \value LineSeparator

    \omitvalue null
    \omitvalue replacement
    \omitvalue byteOrderMark
    \omitvalue byteOrderSwapped
    \omitvalue nbsp
*/

/*!
    \fn void QChar::setCell(uchar cell)
    \internal
*/

/*!
    \fn void QChar::setRow(uchar row)
    \internal
*/

/*!
    \fn QChar::QChar()

    Constructs a null QChar ('\\0').

    \sa isNull()
*/

/*!
    \fn QChar::QChar(QLatin1Char ch)

    Constructs a QChar corresponding to ASCII/Latin-1 character \a ch.
*/

/*!
    \fn QChar::QChar(SpecialCharacter ch)

    Constructs a QChar for the predefined character value \a ch.
*/

/*!
    Constructs a QChar corresponding to ASCII/Latin-1 character \a
    ch.
*/
QChar::QChar(char ch)
{
#ifndef QT_NO_CODEC_FOR_C_STRINGS
    if (QTextCodec::codecForCStrings())
        // #####
        ucs =  QTextCodec::codecForCStrings()->toUnicode(&ch, 1).at(0).unicode();
    else
#endif
        ucs = uchar(ch);
}
Пример #28
0
bool ChaserRunner::write(MasterTimer* timer, UniverseArray* universes)
{
    // Nothing to do
    if (m_steps.size() == 0)
        return false;

    if (m_newCurrent != -1)
    {
        // Manually-set current step
        m_currentStep = m_newCurrent;
        m_newCurrent = -1;

        // No need to do roundcheck here, since manually-set steps are
        // always within m_steps limits.

        m_elapsed = 1;
        handleChannelSwitch(timer, universes);
        emit currentStepChanged(m_currentStep);
    }
    else if (m_elapsed == 0)
    {
        // First step
        m_elapsed = 1;
        handleChannelSwitch(timer, universes);
        emit currentStepChanged(m_currentStep);
    }
    else if ((isAutoStep() && m_elapsed >= Bus::instance()->value(m_holdBusId))
             || m_next == true || m_previous == true)
    {
        // Next step
        if (m_direction == Function::Forward)
        {
            // "Previous" for a forwards chaser is -1
            if (m_previous == true)
                m_currentStep--;
            else
                m_currentStep++;
        }
        else
        {
            // "Previous" for a backwards scene is +1
            if (m_previous == true)
                m_currentStep++;
            else
                m_currentStep--;
        }

        if (roundCheck() == false)
            return false;

        m_elapsed = 1;
        m_next = false;
        m_previous = false;

        handleChannelSwitch(timer, universes);
        emit currentStepChanged(m_currentStep);
    }
    else
    {
        // Current step. UINT_MAX is the maximum hold time.
        if (m_elapsed < UINT_MAX)
            m_elapsed++;
    }

    QMutableMapIterator <quint32,FadeChannel> it(m_channelMap);
    while (it.hasNext() == true)
    {
        Scene* scene = qobject_cast<Scene*> (m_steps.at(m_currentStep));
        if (scene == NULL)
            continue;

        quint32 fadeTime = Bus::instance()->value(scene->busID());

        FadeChannel& channel(it.next().value());
        if (channel.current() == channel.target() && channel.group() != QLCChannel::Intensity)
        {
            /* Write the final value to LTP channels only once */
        }
        else
        {
            uchar value = uchar(floor((qreal(channel.calculateCurrent(fadeTime, m_elapsed)) * m_intensity) + 0.5));
            universes->write(channel.address(), value, channel.group());
        }
    }

    return true;
}
Пример #29
0
bool cAdapter::align(char * read, size_t rLen, uchar * qual, size_t qLen, cElementSet &result, int bc, bool bBestAlign)
{
	bool bDetermined = false;
	ELEMENT elem;
	double dMaxPenalty = cMatrix::dPenaltyPerErr * len + 0.001;
	int iMaxIndel = ceil(cMatrix::dEpsilonIndel * len);
	int minK = bBestAlign ? ((cMatrix::iMinOverlap >= (int)(len - iMaxIndel + 1)) ? (int)(len - iMaxIndel + 1) : cMatrix::iMinOverlap) : 1;
	double dMu = (bc >= 0) ? cMatrix::dMu : MIN_PENALTY;

	deque<ELEMENT> queue;
	ELEMENT element;
	double score;
	uint64 legalBits = 0;
	int i, j, jj;
	element.idx.bc = bc + 1;
	if(trimMode & TRIM_HEAD){
		for(i=1; i<=int(len)-minK; i++){
			element.idx.pos = -i;
			element.score = cMatrix::dPenaltyPerErr * i;
			element.nIndel = 0;
			queue.push_back(element);
			legalBits = (legalBits << 1) | 1;
		}
	}
	else{
		for(i=1,score=cMatrix::dDelta; i<int(len); i++,score+=cMatrix::dDelta){
			if(i > iMaxIndel) break;
			element.idx.pos = -i;
			element.score = score;
			element.nIndel = i;
			queue.push_back(element);
			legalBits = (legalBits << 1) | 1;
		}
	}
	element.nIndel = 0;
	uint64 mbits, xbits, unbits, dnbits, d0bits;
	unbits = dnbits = 0L;
	double penal;
	for(j=0; j<int(rLen); j++){
		jj = j;
		mbits = matchBits[codeMap[uchar(read[jj])]];
		penal = ((qLen > 0) ? cMatrix::penalty[qual[jj]] : dMu);

		element.idx.pos = j;
		element.score = ((mbits & 0x01) == 0) ? penal : 0;
		queue.push_front(element);

		xbits = mbits | unbits;
		dnbits <<= 1;
		unbits <<= 1;
		d0bits = ((dnbits + (xbits & dnbits)) ^ dnbits) | xbits;
		legalBits = (legalBits << 1) | 1;

		UPDATE_COLUMN(queue, d0bits, legalBits, unbits, dnbits, penal, dMaxPenalty, iMaxIndel);

		dnbits &= d0bits;
		unbits &= d0bits;

		if(queue.size() == len){
			if(bBestAlign){
				if(trimMode == TRIM_HEAD){
					i = (queue.back().idx.pos < 0) ? (len + queue.back().idx.pos) : len;
					if( !bDetermined || (i * cMatrix::dMu - queue.back().score) > elem.score * (i+1) ){
						elem = queue.back();
						dMaxPenalty = elem.score;
						elem.score = (i * cMatrix::dMu - elem.score) / (i+1); // normalization
						elem.idx.pos = rLen - 1 - j;
					}
				}
				else{
					elem = queue.back();
					dMaxPenalty = elem.score + ((trimMode == TRIM_TAIL) ? EPSILON : 0);
					elem.score = (len * cMatrix::dMu - elem.score) / (len + 1); // normalization
				}
				bDetermined = true;
				if(dMaxPenalty == 0) break;
			}
			else{
				elem = queue.back();
				elem.score = len * cMatrix::dMu - elem.score; // normalization
				result.insert(elem);
			}
			queue.pop_back();
		}
	}
	if(dMaxPenalty > 0){ // not the case of "perfect match for single-end reads trimming"
		if(bBestAlign){
			if(trimMode & TRIM_TAIL){
				dMaxPenalty = (cMatrix::dPenaltyPerErr * queue.size() + 0.001);
				for(i=queue.size(); i>=minK; i--, dMaxPenalty-=cMatrix::dPenaltyPerErr){
					if(dMaxPenalty <= 0) break;
					if(queue.back().score < dMaxPenalty){
						if(!bDetermined || ((i * cMatrix::dMu - queue.back().score) > elem.score * (i+1)) ){
							elem = queue.back();
							dMaxPenalty = elem.score;
							elem.score = (i * cMatrix::dMu - elem.score) / (i+1); // normalization
							bDetermined = true;
						}
					}
					queue.pop_back();
				}
			}
			else{
				dMaxPenalty -= (len - queue.size()) * cMatrix::dDelta;
				iMaxIndel -= (len - queue.size());
				for(i=queue.size(); i>=minK; i--, dMaxPenalty-=cMatrix::dDelta, iMaxIndel--){
					if( (dMaxPenalty <= 0) || (iMaxIndel < 0) ) break;
					if( (queue.back().score < dMaxPenalty) && (queue.back().nIndel <= iMaxIndel) ){
						if(!bDetermined || ((i * cMatrix::dMu - queue.back().score) > elem.score * (i+1)) ){
							elem = queue.back();
							dMaxPenalty = elem.score;
							elem.score = (i * cMatrix::dMu - elem.score) / (i+1); // normalization
							elem.idx.pos = -(len - i);
							bDetermined = true;
						}
					}
					queue.pop_back();
				}
			}
		}
		else{
			dMaxPenalty = cMatrix::dPenaltyPerErr * queue.size() + 0.001;
			for(i=queue.size(); i>=minK; i--, dMaxPenalty-=cMatrix::dPenaltyPerErr){
				if(queue.back().score < dMaxPenalty){
					elem = queue.back();
					elem.score = i * cMatrix::dMu - elem.score; // normalization
					result.insert(elem);
				}
				queue.pop_back();
			}
		}
	}
	if(bDetermined){
		result.clear();
		result.insert(elem);
	}

	return bDetermined;
}
Пример #30
0
QMap <quint32,FadeChannel>
ChaserRunner::createFadeChannels(const UniverseArray* universes,
                                 QMap <quint32,FadeChannel>& zeroChannels) const
{
    QMap <quint32,FadeChannel> map;
    if (m_currentStep >= m_steps.size() || m_currentStep < 0)
        return map;

    Scene* scene = qobject_cast<Scene*> (m_steps.at(m_currentStep));
    Q_ASSERT(scene != NULL);

    // Put all current channels to a map of channels that will be faded to zero.
    // If the same channels are added to the new channel map, they are removed
    // from this zero map.
    zeroChannels = m_channelMap;

    QListIterator <SceneValue> it(scene->values());
    while (it.hasNext() == true)
    {
        SceneValue value(it.next());
        Fixture* fxi = m_doc->fixture(value.fxi);
        if (fxi == NULL || fxi->channel(value.channel) == NULL)
            continue;

        FadeChannel channel;
        channel.setAddress(fxi->universeAddress() + value.channel);
        channel.setGroup(fxi->channel(value.channel)->group());
        channel.setTarget(value.value);

        // Get starting value from universes. For HTP channels it's always 0.
        channel.setStart(uchar(universes->preGMValues()[channel.address()]));

        // Transfer last step's current value to current step's starting value.
        if (m_channelMap.contains(channel.address()) == true)
            channel.setStart(m_channelMap[channel.address()].current());
        channel.setCurrent(channel.start());

        // Append the channel to the channel map
        map[channel.address()] = channel;

        // Remove the channel from a map of to-be-zeroed channels since now it
        // has a new value to fade to.
        zeroChannels.remove(channel.address());
    }

    // All channels that were present in the previous step but are not present
    // in the current step will go through this zeroing process.
    QMutableMapIterator <quint32,FadeChannel> zit(zeroChannels);
    while (zit.hasNext() == true)
    {
        zit.next();
        FadeChannel& channel(zit.value());
        if (channel.current() == 0 || channel.group() != QLCChannel::Intensity)
        {
            // Remove all non-HTP channels and such HTP channels that are
            // already at zero. There's nothing to do for them.
            zit.remove();
        }
        else
        {
            // This HTP channel was present in the previous step, but is absent
            // in the current. It's nicer that we fade it back to zero, rather
            // than just let it drop straight to zero.
            channel.setStart(channel.current());
            channel.setTarget(0);
        }
    }

    return map;
}