ColorClasses::Color Color3DTree::Node::classify(int y, int u, int v, unsigned int maxdistance, unsigned int maxneighbours)
{
  return classify(Vector3<int>(y, u, v), maxdistance, maxneighbours);
}
示例#2
0
void MainWindow::doClassification()
{

    QSqlQuery query;

    QString seqQuery;

    seqQuery = "SELECT DISTINCT name from showMeList";

    qDebug() << seqQuery;

    if (!query.exec(seqQuery))
     {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setText("Cannot select from ShowMeList table!");
        msgBox.exec();
        return;
     }

     ui->tableWidget->setRowCount(query.size());

    int row = 0;

    while (query.next())
    {

        createCase(query.value(0).toString());    // create a 1 row vector of current on disk

        float conf = classify(query.value(0).toString());  // this does the classification

        if (conf == -1) return;

        QString sConf;
        sConf.setNum(conf,'g',1);

        ui->tableWidget->setItem(row, 0, new QTableWidgetItem(query.value(0).toString()));
        ui->tableWidget->item(row, 0)->setBackgroundColor(Qt::white);

        QTableWidgetItem *item = new QTableWidgetItem();
        item->setTextAlignment(Qt::AlignCenter);
        item->setText(sConf);
        ui->tableWidget->setItem(row, 1, item);

        bool context = false;
        if (conf > 0.5)
        {
            ui->tableWidget->item(row, 1)->setBackgroundColor(Qt::green);
            context = true;
        }
        else
        {
            ui->tableWidget->item(row, 1)->setBackgroundColor(Qt::red);
        }

        if (!updateContextSensor(query.value(0).toString(),context)) return;

        ui->tableWidget->resizeColumnsToContents();

        row++;


    }

}
示例#3
0
bool DecimalUtil::isInf(Decimal128 x)
{
    return classify(x) == FP_INFINITE;
}
示例#4
0
/*-----------------------------------------------------------------------------------*/
static int 
parse_input(struct ctk_term_state* st, unsigned char c)
{
  unsigned char cl = classify(c);
  int ret = -1;
  switch(st->inputstate) {
  case ANS_IDLE:
    switch(cl) {
    case ACC_C0:
      {
	switch(c) {
	case ASCII_ESC: st->inputstate = ANS_ESCSEQ; break;
	case ASCII_BS:  enqueue_key(CH_DEL); break;
	case ASCII_HT:  enqueue_key(CH_TAB); break;
	case ASCII_FF:  ctk_term_redraw(st); break;
	case ASCII_CR:  enqueue_key(CH_ENTER); break;
	}
      }
      break;
      
    case ACC_INTERM:
    case ACC_PARAM:
    case ACC_LOWCASE:
    case ACC_UPCASE:
    case ACC_G1:
      ret = 1;
      break;
    case ACC_C1:
      if (c == ASCII_CSI) {
	st->inputstate = ANS_CTRLSEQ;
	st->ctrlCnt = 0;
      }
      else if (c == ASCII_SS3) {
	st->inputstate = ANS_SS3;
	st->ctrlCnt = 0;
      }
      break;
    case ACC_DEL:
      enqueue_key(CH_DEL);
      break;
    case ACC_SPEC:
      break;
    }
    break;
    
  case ANS_ESCSEQ:
    {
      switch(cl) {
      case ACC_C0:
      case ACC_DEL:
	break;
      case ACC_INTERM:
	st->inputstate = ANS_ESCSEQ_1;
	break;
      case ACC_UPCASE:
	/* C1 control character */
	if (c == '[') {
	  st->inputstate = ANS_CTRLSEQ;
	  st->ctrlCnt = 0;
	}
	else if (c == 'O') {
	  st->inputstate = ANS_SS3;
	  st->ctrlCnt = 0;
	}
	else {
	  st->inputstate = ANS_IDLE;
	}
	break;
      case ACC_PARAM:
	/* Private 2-character sequence */
      case ACC_LOWCASE:
	/* Standard 2-character sequence */
      default:
	st->inputstate = ANS_IDLE;
	break;
      }
    }
    break;
    
  case ANS_ESCSEQ_1:
    {
      switch(cl) {
      case ACC_C0:
      case ACC_INTERM:
	break;
      case ACC_PARAM:
	/* Private function*/
      case ACC_LOWCASE:
      case ACC_UPCASE:
	/* Standard function */
      default:
	st->inputstate = ANS_IDLE;
	break;
      }
    }
    break;
  case ANS_SS3:
    {
      switch(cl) {
      case ACC_PARAM:
	if (st->ctrlCnt < CTK_TERM_CTRLBUFLEN) st->ctrlbuf[st->ctrlCnt++]=c;
	break;
      case ACC_UPCASE:
	/* VT100 PF seq */
	if (st->ctrlCnt < CTK_TERM_CTRLBUFLEN) st->ctrlbuf[st->ctrlCnt++]=c;
	st->inputstate = ANS_IDLE;
	st->ctrlbuf[st->ctrlCnt] = 0;
	lookup_seq((const char*)(st->ctrlbuf), ss3map);
	break;
      default:
	st->inputstate = ANS_IDLE;
	break;
      }
    }
    break;
  case ANS_CTRLSEQ:
    {
      switch(cl) {
      case ACC_C0:
	break;
      case ACC_INTERM:
      case ACC_PARAM:
	if (st->ctrlCnt < CTK_TERM_CTRLBUFLEN) st->ctrlbuf[st->ctrlCnt++]=c;
	break;
      case ACC_LOWCASE:
      case ACC_UPCASE:
	/* Standard control sequence */
	if (st->ctrlCnt < CTK_TERM_CTRLBUFLEN) st->ctrlbuf[st->ctrlCnt++]=c;
	/* Cygwin console sends ESC [ [ A for function keys */
	if (c != '[') {
	  st->ctrlbuf[st->ctrlCnt] = 0;
	  lookup_seq((const char*)(st->ctrlbuf), ctrlmap);
	  st->inputstate = ANS_IDLE;
	}
	break;
      default:
	st->inputstate = ANS_IDLE;
	break;
      }
    }
    break;
  }
  return ret;
}
示例#5
0
	/**
	 * 	The classification process
	 * 	
	 * 	@param	test	The test set to set before run the classification process (in LibSVM format)
	 * */
	void MultiClassSVM::classify(struct svm_problem *test) {
		test_problem = test;
		classify();
	}
示例#6
0
文件: point.cpp 项目: P140N/origin
int Point::classify(Edge e)
{
  return classify(e.org, e.dest);
}
示例#7
0
int test__divdc3(double a, double b, double c, double d)
{
    double _Complex r = __divdc3(a, b, c, d);
//     printf("test__divdc3(%f, %f, %f, %f) = %f + I%f\n",
//             a, b, c, d, creal(r), cimag(r));
	double _Complex dividend;
	double _Complex divisor;
	
	__real__ dividend = a;
	__imag__ dividend = b;
	__real__ divisor = c;
	__imag__ divisor = d;
	
    switch (classify(dividend))
    {
    case zero:
        switch (classify(divisor))
        {
        case zero:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero:
            if (classify(r) != zero)
                return 1;
            break;
        case inf:
            if (classify(r) != zero)
                return 1;
            break;
        case NaN:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero_nan:
            if (classify(r) != NaN)
                return 1;
            break;
        }
        break;
    case non_zero:
        switch (classify(divisor))
        {
        case zero:
            if (classify(r) != inf)
                return 1;
            break;
        case non_zero:
            if (classify(r) != non_zero)
                return 1;
            {
            double _Complex z = (a * c + b * d) / (c * c + d * d)
                             + (b * c - a * d) / (c * c + d * d) * _Complex_I;
            if (cabs((r-z)/r) > 1.e-6)
                return 1;
            }
            break;
        case inf:
            if (classify(r) != zero)
                return 1;
            break;
        case NaN:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero_nan:
            if (classify(r) != NaN)
                return 1;
            break;
        }
        break;
    case inf:
        switch (classify(divisor))
        {
        case zero:
            if (classify(r) != inf)
                return 1;
            break;
        case non_zero:
            if (classify(r) != inf)
                return 1;
            break;
        case inf:
            if (classify(r) != NaN)
                return 1;
            break;
        case NaN:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero_nan:
            if (classify(r) != NaN)
                return 1;
            break;
        }
        break;
    case NaN:
        switch (classify(divisor))
        {
        case zero:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero:
            if (classify(r) != NaN)
                return 1;
            break;
        case inf:
            if (classify(r) != NaN)
                return 1;
            break;
        case NaN:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero_nan:
            if (classify(r) != NaN)
                return 1;
            break;
        }
        break;
    case non_zero_nan:
        switch (classify(divisor))
        {
        case zero:
            if (classify(r) != inf)
                return 1;
            break;
        case non_zero:
            if (classify(r) != NaN)
                return 1;
            break;
        case inf:
            if (classify(r) != NaN)
                return 1;
            break;
        case NaN:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero_nan:
            if (classify(r) != NaN)
                return 1;
            break;
        }
        break;
    }
    
    return 0;
}
示例#8
0
void detect_object2(CascadeClassifier *cc, cv::Mat &img, float startScale, float endScale, int layers, float offsetFactor, std::vector<cv::Rect> &rects)
{
    cv::Mat gray, sImg;

    int winX = cc->WIDTH;
    int winY = cc->HEIGHT;

    int dx = offsetFactor * winX;
    int dy = offsetFactor * winY;

    float *data = new float [winX * winY];
    float scaleStep = (endScale - startScale) / layers;

    if(endScale > startScale) {
        startScale = endScale;
        scaleStep = -scaleStep;
    }

    if(img.channels() == 3)
        cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY);
    else
        gray = img.clone();

    for(int i = 0; i < layers; i++)
    {
        cv::resize(gray, sImg, cv::Size(startScale * gray.cols, startScale * gray.rows));

        int ws = sImg.cols - winX;
        int hs = sImg.rows - winY;

        for(int y = 0; y < hs; y += dy)
        {
            for(int x = 0; x < ws; x += dx)
            {
                cv::Rect rect = cv::Rect(x, y, winX, winY);
                cv::Mat patch(sImg, rect);

                float *pData = data;
                uchar *iData = patch.data;

                for(int m = 0; m < winY; m++)
                {
                    for(int n = 0; n < winX; n++)
                        pData[n] = iData[n] / 255.0;

                    pData += winX;
                    iData += patch.step;
                }

#ifdef USE_HAAR_FEATURE
                integral_image(data, winX, winY);
#endif

                if(classify(cc, data, winX, 0, 0) == 1)
                {
                    rect.x /= startScale;
                    rect.y /= startScale;

                    rect.width /= startScale;
                    rect.height /= startScale;

                    rects.push_back(rect);
                }
            }

        }

        startScale += scaleStep;
    }

    delete [] data;
}
void basicOCR::printCvSeq(CvSeq* seq, IplImage* imgSrc, IplImage* img_gray, CvMemStorage* storage)
{
	CvSeq* si = seq;
	CvRect rcFirst = findFirstChar(seq, 0);
	if (rcFirst.x == 0)
	{
		printf("No words found...\n");
		return;
	}
	else
		printf("\nOCR of text:\n");
	CvRect rcNewFirst = rcFirst;
	cvDrawRect(imgSrc, cvPoint(rcFirst.x, rcFirst.y), cvPoint(rcFirst.x + rcFirst.width, rcFirst.y + rcFirst.height), CV_RGB(0, 0, 0));
	int printX = rcFirst.x - 1;
	int printY = rcFirst.y - 1;

	int idx = 0;
	char szName[56] = {0};
	int tempCount=0;

	while (true)
	{
		CvRect rc = findPrintRect(seq, printX, printY, rcFirst);
		cvDrawRect(imgSrc, cvPoint(rc.x, rc.y), cvPoint(rc.x + rc.width, rc.y + rc.height), CV_RGB(0, 0, 0));
		// dealing with useless Part
		/*if (rc.width <= 1 && rc.height <= 1)
		{
		continue;
		}*/

		if (printX < rc.x)
		{
			if ((rc.x - printX) >= (rcFirst.width / 2))
				printf(" ");
			printX = rc.x;
			//cvDrawRect(imgSrc, cvPoint(rc.x, rc.y), cvPoint(rc.x + rc.width, rc.y + rc.height), CV_RGB(255, 0, 0));
			IplImage* imgNo = cvCreateImage(cvSize(rc.width, rc.height), IPL_DEPTH_8U, 3);
			cvSetImageROI(imgSrc, rc);
			cvCopyImage(imgSrc, imgNo);
			cvResetImageROI(imgSrc);
			sprintf(szName, "wnd_%d", idx++);
			// show splited picture or not
			cvNamedWindow(szName);
			cvShowImage(szName, imgNo);
			IplImage* imgDst = cvCreateImage(cvSize(rc.width, rc.height),IPL_DEPTH_8U,1);
			cvCvtColor(imgNo, imgDst, CV_RGB2GRAY);
			printf("%c", (char)classify(imgDst, 0));
			cvReleaseImage(&imgNo);
		}
		else if (printX == rc.x && printX < imgSrc->width)
		{
			printX += rc.width;
		}
		else
		{
			printf("\n");
			printY = rcNewFirst.y + rcNewFirst.height;
			rcNewFirst = findFirstChar(seq, printY);
			if (rcNewFirst.x == 0)
				break;
			cvDrawRect(imgSrc, cvPoint(rcNewFirst.x, rcNewFirst.y), cvPoint(rcNewFirst.x + rcNewFirst.width, rcNewFirst.y + rcNewFirst.height), CV_RGB(0, 0, 0));
			printX = rcNewFirst.x - 1;
			printY = rcNewFirst.y - 1;
		}
	}
	cvNamedWindow("src");
	cvShowImage("src", imgSrc);
	cvWaitKey(0);
	cvReleaseMemStorage(&storage);
	cvReleaseImage(&imgSrc);
	cvReleaseImage(&img_gray);
	cvDestroyAllWindows();

}
示例#10
0
StrongClassifier* adaboost_learning(CascadeClassifier *cc, std::list<float *> &positiveSet, int numPos,
        std::list<float *> &negativeSet, int numNeg, std::list<float *> &validateSet, std::vector<Feature *> &featureSet,
            float maxfpr, float maxfnr)
{
    StrongClassifier *sc = new StrongClassifier;

    int width = cc->WIDTH;
    int height = cc->HEIGHT;

    float *weights = NULL, *values = NULL;

    int sampleSize = numPos + numNeg;
    int fsize = featureSet.size();

    float cfpr = 1.0;

    init_weights(&weights, numPos, numNeg);

    values = new float[sampleSize];
    memset(values, 0, sizeof(float) * sampleSize);

    while(cfpr > maxfpr)
    {
        std::list<float *>::iterator iter;
        float minError = 1, error, beta;
        WeakClassifier *bestWC = NULL;

        for(int i = 0; i < fsize; i++)
        {
            Feature *feat = new Feature;
            WeakClassifier *wc = new WeakClassifier;

            init_feature(feat, featureSet[i]);
            init_weak_classifier(wc, 0, 0, feat);

            iter = positiveSet.begin();
            for(int j = 0; j < numPos; j++, iter++)
                values[j] = get_value(feat, *iter, width, 0, 0);

            iter = negativeSet.begin();
            for(int j = 0; j < numNeg; j++, iter++)
                values[j + numPos] = get_value(feat, *iter, width, 0, 0);

            error = train(wc, values, numPos, numNeg, weights);

            if(error < minError)
            {
                if(bestWC != NULL){
                    clear(bestWC);
                    bestWC = NULL;
                }

                bestWC = wc;

                minError = error;

                printf("Select best weak classifier, min error: %f\r", minError);
                fflush(stdout);
            }

            else
                delete wc;
        }

        assert(minError > 0);

        printf("best weak classifier error = %f                      \n", minError);

        beta = minError / (1 - minError);

        int tp = 0;
        iter = positiveSet.begin();

        for(int i = 0; i < numPos; i++, iter++){
            if(classify(bestWC, *iter, width, 0, 0) == 1){
                weights[i] *= beta;
                tp ++;
            }
        }

        int tn = 0;
        iter = negativeSet.begin();

        for(int i = numPos; i < sampleSize; i++, iter++){
            if(classify(bestWC, *iter, width, 0, 0) != 1){
                weights[i] *= beta;
                tn++;
            }
        }

        update_weights(weights, numPos, numNeg);

        printf("TP = %d, TN = %d, beta = %f, log(1/beta) = %f\n", tp, tn, beta, log(1/beta));

        add(sc, bestWC, log(1/beta));

        train(sc, positiveSet, width, maxfnr);

        cfpr = fpr(sc, validateSet, width);

        printf("fpr validate: %f\n", fpr(sc, validateSet, width));
        printf("fpr negative: %f\n", fpr(sc, negativeSet, width));

        printf("\n");
    }

    printf("\nWeak classifier size %ld\n", sc->wcs.size());


    delete [] values;
    delete [] weights;

    return sc;
}
示例#11
0
int main_train(int argc, char **argv)
{
    char *posSplFile = NULL;
    char *negSplFile = NULL;
    char *modelFile = NULL;

    int stage = 15;
    int width = 0, height = 0;
    int numPos = 0, numNeg = 0;
    const int numVal = 400;

    float tarfpr = 0.05;
    float maxfnr = 0.05;

    std::vector<std::string> negImgList;

    if((argc - 1) / 2 != 10)
    {
        print_train_usage(argv[0]);
        return 1;
    }

    for(int i = 1; i < argc; i++)
    {
        if(strcmp(argv[i], "--stage") == 0)
            stage = atoi(argv[++i]);

        else if(strcmp(argv[i], "-X") == 0)
            width = atoi(argv[++i]);

        else if(strcmp(argv[i], "-Y") == 0)
            height = atoi(argv[++i]);

        else if(strcmp(argv[i], "--false_alarm_rate") == 0)
            tarfpr = atof(argv[++i]);

        else if(strcmp(argv[i], "--missing_rate") == 0)
            maxfnr = atof(argv[++i]);

        else if(strcmp(argv[i], "--pos") == 0)
            posSplFile = argv[++i];

        else if(strcmp(argv[i], "--neg") == 0)
            negSplFile = argv[++i];

        else if(strcmp(argv[i], "-m") == 0)
            modelFile = argv[++i];

        else if(strcmp(argv[i], "--numPos"))
            numPos = atoi(argv[++i]);

        else if(strcmp(argv[i], "--numNeg"))
            numNeg = atoi(argv[++i]);

        else
        {
            printf("Can't recognize params %s\n", argv[i]);
            print_train_usage(argv[0]);
            return 1;
        }
    }

    if(posSplFile == NULL || negSplFile == NULL || width == 0 || height == 0 || numPos <= 0 || numNeg <= 0){
        print_train_usage(argv[0]);
        return 1;
    }

    std::list<float *> positiveSet, negativeSet, validateSet;
    int ret;
    std::vector<Feature*> featureSet;
    float *stepFPR;
    float npRatio = 1.0 * numNeg / numPos;

    CascadeClassifier *cc = new CascadeClassifier();
    StrongClassifier* sc;
    float maxfpr = 1.0;

    std::list<StrongClassifier *> scs;
    init_cascade_classifier(cc, scs, width, height);

    printf("GENERATE POSITIVE SAMPLES\n");
    ret = generate_positive_samples(posSplFile, positiveSet, width, height, numPos);
    if(ret != 0) return 2;

    printf("GENERATE NEGATIVE SAMPLES\n");
    read_image_list(negSplFile, negImgList);

    for(int i = 0; i < numNeg; i ++)
    {
        float *data = NULL;
        read_neg_sample_from_file(negImgList, width, height, &data);

#ifdef USE_HAAR_FEATURE
        integral_image(data, width, height);
#endif
        negativeSet.push_back(data);
    }


    printf("GENERATE VALIDATE SAMPLES\n");
    generate_validate_samples(negImgList, width, height, validateSet, numPos);

    printf("Positive sample size: %ld\n", positiveSet.size());
    printf("Negative sample size: %ld\n", negativeSet.size());
    printf("Validate sample size: %d\n", numVal);

    printf("GENERATE FEATURE TEMPLATE\n");
    generate_feature_set(featureSet, width, height);

    printf("SELECT FEATURE TEMPLATE\n");
    select_feature(featureSet, positiveSet, validateSet, width);

    init_steps_false_positive(&stepFPR, stage, tarfpr);

    clock_t startTime = clock();
    char outname[128];

    for(int i = 0; i < stage; i++)
    {
        printf("\n--------------cascade stage %d-----------------\n", i+1);

        int correctSize = 0;

        std::list<float*>::iterator iter, iterEnd;

        numNeg = numPos * npRatio;
        printf("READ NEGATIVE SAMPLES\n");
        ret = generate_negative_samples(negImgList, width, height, cc, negativeSet, numNeg);
        if(ret != numNeg) {
            printf("Can't generate enough negatvie samples %d:%d\n", ret, numNeg);
            break;
        }

        printf("READ VALIDATE SAMPLES\n");
        ret = generate_negative_samples(negImgList, width, height, cc, validateSet, numVal);
        if(ret != numVal) {
            printf("Can't generate enough validate samples %d:%d\n", ret, numVal);
            break;
        }

        maxfpr *= stepFPR[i];

        printf("Positive sample size: %d\n", numPos);
        printf("Negative sample size: %d\n", numNeg);
        printf("Target false positive rate: %f\n", maxfpr);
        printf("Target false negative rate: %f\n", maxfnr);

        sc = adaboost_learning(cc, positiveSet, numPos, negativeSet, numNeg, validateSet, featureSet, maxfpr, maxfnr);
        add(cc, sc);

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

        while(iter != iterEnd)
        {
            if(classify(cc, *iter, width, 0, 0) == 0)
            {
                std::list<float*>::iterator iterTmp = iter;
                iter++;
                delete[] (*iterTmp);
                positiveSet.erase(iterTmp);
                iter--;
            }

            iter++;
        }

        numPos = positiveSet.size();
        printf("cascade TP: %d\n", numPos);

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

        correctSize = negativeSet.size();

        while(iter != iterEnd)
        {
            if(classify(cc, *iter, width, 0, 0) == 0)
            {
                std::list<float*>::iterator iterTmp = iter;
                iter++;
                delete[] (*iterTmp);
                negativeSet.erase(iterTmp);
                iter--;
            }

            iter++;
        }

        printf("cascade TN: %ld\n", correctSize - negativeSet.size());

        iter = validateSet.begin();
        iterEnd = validateSet.end();
        while(iter != iterEnd)
        {
            if(classify(cc, *iter, width, 0, 0) == 0)
            {
                std::list<float*>::iterator iterTmp = iter;
                iter++;
                delete[] (*iterTmp);
                validateSet.erase(iterTmp);
                iter--;
            }

            iter++;
        }

        printf("----------------------------------------\n");

        sprintf(outname, "model/cascade_%d.dat", i+1);
        save(cc, outname);

#ifdef SHOW_FEATURE
        print_feature(cc);
#endif
    }

    save(cc, modelFile);

    clock_t trainTime = clock() - startTime;

    printf("Train time:");
    print_time(trainTime);
    printf("\n");
    clear(cc);

    clear_list(positiveSet);
    clear_list(negativeSet);
    clear_list(validateSet);

    clear_features(featureSet);

    return 0;
}
示例#12
0
char Character::get_classification(){			//get the classifications and return the character
	classify();
	return recognized_char;
}
示例#13
0
int test__mulsc3(float a, float b, float c, float d)
{
    float _Complex r = __mulsc3(a, b, c, d);
//     printf("test__mulsc3(%f, %f, %f, %f) = %f + I%f\n",
//             a, b, c, d, crealf(r), cimagf(r));
	float _Complex dividend;
	float _Complex divisor;
	
	__real__ dividend = a;
	__imag__ dividend = b;
	__real__ divisor = c;
	__imag__ divisor = d;
	
    switch (classify(dividend))
    {
    case zero:
        switch (classify(divisor))
        {
        case zero:
            if (classify(r) != zero)
                return 1;
            break;
        case non_zero:
            if (classify(r) != zero)
                return 1;
            break;
        case inf:
            if (classify(r) != NaN)
                return 1;
            break;
        case NaN:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero_nan:
            if (classify(r) != NaN)
                return 1;
            break;
        }
        break;
    case non_zero:
        switch (classify(divisor))
        {
        case zero:
            if (classify(r) != zero)
                return 1;
            break;
        case non_zero:
            if (classify(r) != non_zero)
                return 1;
            {
            float _Complex z = a * c - b * d + _Complex_I*(a * d + b * c);
            // relaxed tolerance to arbitrary (1.e-6) amount.
            if (cabsf((r-z)/r) > 1.e-6)
                return 1;
            }
            break;
        case inf:
            if (classify(r) != inf)
                return 1;
            break;
        case NaN:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero_nan:
            if (classify(r) != NaN)
                return 1;
            break;
        }
        break;
    case inf:
        switch (classify(divisor))
        {
        case zero:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero:
            if (classify(r) != inf)
                return 1;
            break;
        case inf:
            if (classify(r) != inf)
                return 1;
            break;
        case NaN:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero_nan:
            if (classify(r) != inf)
                return 1;
            break;
        }
        break;
    case NaN:
        switch (classify(divisor))
        {
        case zero:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero:
            if (classify(r) != NaN)
                return 1;
            break;
        case inf:
            if (classify(r) != NaN)
                return 1;
            break;
        case NaN:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero_nan:
            if (classify(r) != NaN)
                return 1;
            break;
        }
        break;
    case non_zero_nan:
        switch (classify(divisor))
        {
        case zero:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero:
            if (classify(r) != NaN)
                return 1;
            break;
        case inf:
            if (classify(r) != inf)
                return 1;
            break;
        case NaN:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero_nan:
            if (classify(r) != NaN)
                return 1;
            break;
        }
        break;
    }
    
    return 0;
}
示例#14
0
//============================================================================
// main
//============================================================================
int main() {
	//*******************************************************
	cout << "---------[Program start]----------" << endl;

	/*	if (argc < 3) {
	 fprintf(stderr, "Usage: mnist <k> <mnist path> [<nr train images> <nr test images>]\n");
	 return EXIT_FAILURE;
	 }
	 */
	int k = 5; // TODO atoi(argv[1]);

	#ifdef PRINT
	cout << "k = " << k << endl;
	#endif
	
	string base = "/tmp/images/"; // TODO string base(argv[2]);

	LabelIterator *trainLabels = openLabels(base + "train-labels-idx1-ubyte");
	ImageIterator *trainImages = openImages(base + "train-images-idx3-ubyte");
	LabelIterator *testLabels = openLabels(base + "t10k-labels-idx1-ubyte");
	ImageIterator *testImages = openImages(base + "t10k-images-idx3-ubyte");

	if (trainLabels == 0 || trainImages == 0 || testLabels == 0 || testImages
			== 0) {
		cout
				<< "One or more files couldn't be found! Make sure that following files are in the directory given as argument:\n"
				<< "\ttrain-labels-idx1-ubyte\n"
				<< "\ttrain-images-idx3-ubyte\n"
				<< "\tt10k-labels-idx1-ubyte\n" << "\tt10k-images-idx3-ubyte\n"
				<< endl;
		exit(-1);
	}

	/*
	trainLabels->count = 1000;
	trainImages->count = 1000;
	testLabels->count = 1000;
	testImages->count = 1000;
	*/
	
	unsigned char label;
	unsigned char *image;

	Points<unsigned char, unsigned char> training_points(trainImages->count, trainImages->rows
			* trainImages->columns);
	Points<unsigned char, unsigned char> test_points(testImages->count, testImages->rows
			* testImages->columns);

	#ifdef PRINT
	cout << trainImages->count << " " << trainImages->rows*trainImages->columns << endl;
	cout << "size: " << trainImages->rows*trainImages->columns << "\tcount: " << trainImages->count << endl;
	#endif

	int i = 0;
	Point<unsigned char, unsigned char> *trainPoint;
	while (hasNextLabel(trainLabels) && hasNextImage(trainImages)) {
		image = nextImage(trainImages);
		label = nextLabel(trainLabels);

		trainPoint = training_points.getPoint(i++);
		imageToPoint(trainPoint, label, image, (trainImages->columns
				*trainImages->rows));

		#ifdef PRINT
		if ((i % 1000) == 0)
			cout << i << " training images loaded." << endl;
		#endif

		delete trainPoint;
		free(image);
	}

	i = 0;
	Point<unsigned char, unsigned char> *testPoint;
	while (hasNextLabel(testLabels) && hasNextImage(testImages)) {
		image = nextImage(testImages);
		label = nextLabel(testLabels);

		testPoint = test_points.getPoint(i++);
		imageToPoint(testPoint, label, image, (testImages->columns
				* testImages->rows));

		#ifdef PRINT
		if ((i % 1000) == 0)
			cout << i << " test images loaded." << endl;
		#endif

		delete testPoint;
		free(image);
	}
	//********************************************************
	
	unsigned char *result = classify(k, test_points, training_points);
	
	if (result != 0) {
		int errors = 0;		
		for (int i = 0; i < test_points.getCount(); i++) {
			if (result[i] != test_points.getLabel(i)[0]) {
				errors++;
			}
		}
		
		float error_rate = (float) errors / (float) test_points.getCount();
		printf("PPE:\t %d out of %d inaccurate classifications\n", errors, test_points.getCount());
		printf("PPE:\t Error rate is %f\n", error_rate);
		
		free(result);
	}

	printf("PPE:\t Program finished\n");

	return (0);
}
示例#15
0
文件: rpc.c 项目: dancrossnyc/harvey
int
ctlwrite(char *a, int atzero)
{
	char *p;
	int i, nmatch, ret;
	Attr *attr, **l, **lpriv, **lprotos, *pa, *priv, *protos;
	Key *k;
	Proto *proto;

	if(a[0] == '#' || a[0] == '\0')
		return 0;

	/*
	 * it would be nice to emit a warning of some sort here.
	 * we ignore all but the first line of the write.  this helps
	 * both with things like "echo delkey >/mnt/factotum/ctl"
	 * and writes that (incorrectly) contain multiple key lines.
	 */
	if((p = strchr(a, '\n')) != nil){
		if(p[1] != '\0'){
			werrstr("multiline write not allowed");
			return -1;
		}
		*p = '\0';
	}

	if((p = strchr(a, ' ')) == nil)
		p = "";
	else
		*p++ = '\0';
	switch(classify(a, ctltab, nelem(ctltab))){
	default:
	case Vunknown:
		werrstr("unknown verb");
		return -1;
	case Vdebug:
		debug ^= 1;
		return 0;
	case Vdelkey:
		nmatch = 0;
		attr = _parseattr(p);
		for(pa=attr; pa; pa=pa->next){
			if(pa->type != AttrQuery && pa->name[0]=='!'){
				werrstr("only !private? patterns are allowed for private fields");
				_freeattr(attr);
				return -1;
			}
		}
		for(i=0; i<ring->nkey; ){
			if(matchattr(attr, ring->key[i]->attr, ring->key[i]->privattr)){
				nmatch++;
				closekey(ring->key[i]);
				ring->nkey--;
				memmove(&ring->key[i], &ring->key[i+1], (ring->nkey-i)*sizeof(ring->key[0]));
			}else
				i++;
		}
		_freeattr(attr);
		if(nmatch == 0){
			werrstr("found no keys to delete");
			return -1;
		}
		return 0;
	case Vaddkey:
		attr = _parseattr(p);
		/* separate out proto= attributes */
		lprotos = &protos;
		for(l=&attr; (*l); ){
			if(strcmp((*l)->name, "proto") == 0){
				*lprotos = *l;
				lprotos = &(*l)->next;
				*l = (*l)->next;
			}else
				l = &(*l)->next;
		}
		*lprotos = nil;
		if(protos == nil){
			werrstr("key without protos");
			_freeattr(attr);
			return -1;
		}

		/* separate out private attributes */
		lpriv = &priv;
		for(l=&attr; (*l); ){
			if((*l)->name[0] == '!'){
				*lpriv = *l;
				lpriv = &(*l)->next;
				*l = (*l)->next;
			}else
				l = &(*l)->next;
		}
		*lpriv = nil;

		/* add keys */
		ret = 0;
		for(pa=protos; pa; pa=pa->next){
			if((proto = findproto(pa->val)) == nil){
				werrstr("unknown proto %s", pa->val);
				ret = -1;
				continue;
			}
			if(proto->addkey == nil){
				werrstr("proto %s doesn't take keys", proto->name);
				ret = -1;
				continue;
			}
			k = emalloc(sizeof(Key));
			k->attr = _mkattr(AttrNameval, "proto", proto->name, _copyattr(attr));
			k->privattr = _copyattr(priv);
			k->ref = 1;
			k->proto = proto;
			if(proto->addkey(k, atzero) < 0){
				ret = -1;
				closekey(k);
				continue;
			}
			closekey(k);
		}
		_freeattr(attr);
		_freeattr(priv);
		_freeattr(protos);
		return ret;
	}
}
void pdp::EMClassification::work(LungDataset& input, LungDataset& output)
{
    std::cout << "performing the expectation maximization step!" << std::endl;
	typedef itk::Image<float, 3> ImageType;
	typedef itk::Image<unsigned char, 3> MaskType;

	mitk::Image::Pointer mitkImage = input.getImage("Lungs");
	mitkImage->DisconnectPipeline();
	ImageType::Pointer img;
	mitk::CastToItkImage(mitkImage, img);

	mitk::Image::Pointer mitkMask = input.getImage("Otsu");
	mitkMask->DisconnectPipeline();
	MaskType::Pointer mask;
	mitk::CastToItkImage(mitkMask, mask);

	typedef itk::Vector< double, 1 > MeasurementVectorType;
	typedef itk::Statistics::ListSample< MeasurementVectorType > SampleType;

	SampleType::Pointer sample = prepareSample(img, mask);

    emit stepProgress(0.33f);

	//numberOfClasses = 4;

	typedef itk::Array< double > ParametersType;
	ParametersType params( 2 );
	std::vector< ParametersType > initialParameters( numberOfClasses );
	params[0] = -920.0;
	params[1] = 2500.0;//std = 50
	initialParameters[0] = params;
	params[0] = -835.0;
	params[1] = 1600.0;//std = 40
	initialParameters[1] = params;
	params[0] = -720.0;
	params[1] = 900.0;//std = 30
	initialParameters[2] = params;
	params[0] = -570.0;
	params[1] = 900.0;//std = 30
	initialParameters[3] = params;

	itk::Array< double > initialProportions(numberOfClasses);
	initialProportions[0] = 0.8;
	initialProportions[1] = 0.1;
	initialProportions[2] = 0.05;
	initialProportions[3] = 0.05;

	expectationMaximization(initialParameters, initialProportions, sample);

    emit stepProgress(0.66f);

	MaskType::Pointer nonLungTissueMask = classify(img, mask);

	// Cast the ITK -> MITK image and add it to the datatree.
	mitk::Image::Pointer mitkOut = mitk::Image::New();
	mitk::CastToMitkImage(nonLungTissueMask, mitkOut);
	output.addImage(mitkOut, "nonLungTissueMask");
	output.getDataStore()->Remove(output.getDataStore()->GetNamedNode("Otsu"));

    emit stepProgress(1.00f);
}
示例#17
0
文件: variant.cpp 项目: atks/vt
/**
 * Constructor.
 */
Variant::Variant(bcf_hdr_t* h, bcf1_t* v)
{
    this->h = h;
    this->v = v;

    type = classify(h, v);

    chrom = bcf_get_chrom(h, v);
    rid = bcf_get_rid(v);
    pos1 = bcf_get_pos1(v);

    no_overlapping_snps = 0;
    no_overlapping_indels = 0;
    no_overlapping_vntrs = 0;

    is_new_multiallelic =  false;

    //attempts to update relevant information on variants
    if (type==VT_SNP)
    {
        beg1 = bcf_get_pos1(v);
        end1 = bcf_get_pos1(v);
    }
    else if (type==VT_INDEL)
    {
        beg1 = bcf_get_pos1(v);
        end1 = bcf_get_info_int(h, v, "END", 0);

        //annotate ends
        if (!end1) end1 = bcf_get_end1(v);
    }
    //complex variants
    else if (type & (VT_SNP|VT_MNP|VT_INDEL|VT_CLUMPED))
    {
        beg1 = bcf_get_pos1(v);
        end1 = bcf_get_info_int(h, v, "END", 0);
        if (!end1) end1 = bcf_get_end1(v);
    }
    else if (type==VT_VNTR)
    {
        beg1 = bcf_get_pos1(v);
        end1 = bcf_get_info_int(h, v, "END", 0);
        if (!end1) end1 = bcf_get_end1(v);

        update_vntr_from_info_fields(h, v);

        vs.push_back(v);
        vntr_vs.push_back(v);
    }
    else if (type==VT_SV)
    {
        beg1 = bcf_get_pos1(v);
        end1 = bcf_get_info_int(h, v, "END", 0);
        if (!end1) end1 = bcf_get_end1(v);
    }
    else
    {
        std::cerr << "unexpected type in variant construction\n";
        print();
        exit(1);
    }
}
示例#18
0
文件: bidi.c 项目: Moteesh/reactos
/*************************************************************
 *    BIDI_Reorder
 *
 *     Returns TRUE if reordering was required and done.
 */
BOOL BIDI_Reorder(
                HDC hDC,        /*[in] Display DC */
                LPCWSTR lpString,       /* [in] The string for which information is to be returned */
                INT uCount,     /* [in] Number of WCHARs in string. */
                DWORD dwFlags,  /* [in] GetCharacterPlacement compatible flags specifying how to process the string */
                DWORD dwWineGCP_Flags,       /* [in] Wine internal flags - Force paragraph direction */
                LPWSTR lpOutString, /* [out] Reordered string */
                INT uCountOut,  /* [in] Size of output buffer */
                UINT *lpOrder, /* [out] Logical -> Visual order map */
                WORD **lpGlyphs, /* [out] reordered, mirrored, shaped glyphs to display */
                INT *cGlyphs /* [out] number of glyphs generated */
    )
{
    WORD *chartype;
    BYTE *levels;
    INT i, done;
    unsigned glyph_i;
    BOOL is_complex;

    int maxItems;
    int nItems;
    SCRIPT_CONTROL Control;
    SCRIPT_STATE State;
    SCRIPT_ITEM *pItems;
    HRESULT res;
    SCRIPT_CACHE psc = NULL;
    WORD *run_glyphs = NULL;
    WORD *pwLogClust = NULL;
    SCRIPT_VISATTR *psva = NULL;
    DWORD cMaxGlyphs = 0;
    BOOL  doGlyphs = TRUE;

    TRACE("%s, %d, 0x%08x lpOutString=%p, lpOrder=%p\n",
          debugstr_wn(lpString, uCount), uCount, dwFlags,
          lpOutString, lpOrder);

    memset(&Control, 0, sizeof(Control));
    memset(&State, 0, sizeof(State));
    if (lpGlyphs)
        *lpGlyphs = NULL;

    if (!(dwFlags & GCP_REORDER))
    {
        FIXME("Asked to reorder without reorder flag set\n");
        return FALSE;
    }

    if (lpOutString && uCountOut < uCount)
    {
        FIXME("lpOutString too small\n");
        return FALSE;
    }

    chartype = HeapAlloc(GetProcessHeap(), 0, uCount * sizeof(WORD));
    if (!chartype)
    {
        WARN("Out of memory\n");
        return FALSE;
    }

    if (lpOutString)
        memcpy(lpOutString, lpString, uCount * sizeof(WCHAR));

    is_complex = FALSE;
    for (i = 0; i < uCount && !is_complex; i++)
    {
        if ((lpString[i] >= 0x900 && lpString[i] <= 0xfff) ||
            (lpString[i] >= 0x1cd0 && lpString[i] <= 0x1cff) ||
            (lpString[i] >= 0xa840 && lpString[i] <= 0xa8ff))
            is_complex = TRUE;
    }

    /* Verify reordering will be required */
    if ((WINE_GCPW_FORCE_RTL == (dwWineGCP_Flags&WINE_GCPW_DIR_MASK)) ||
        ((dwWineGCP_Flags&WINE_GCPW_DIR_MASK) == WINE_GCPW_LOOSE_RTL))
        State.uBidiLevel = 1;
    else if (!is_complex)
    {
        done = 1;
        classify(lpString, chartype, uCount);
        for (i = 0; i < uCount; i++)
            switch (chartype[i])
            {
                case R:
                case AL:
                case RLE:
                case RLO:
                    done = 0;
                    break;
            }
        if (done)
        {
            HeapFree(GetProcessHeap(), 0, chartype);
            if (lpOrder)
            {
                for (i = 0; i < uCount; i++)
                    lpOrder[i] = i;
            }
            return TRUE;
        }
    }

    levels = HeapAlloc(GetProcessHeap(), 0, uCount * sizeof(BYTE));
    if (!levels)
    {
        WARN("Out of memory\n");
        HeapFree(GetProcessHeap(), 0, chartype);
        return FALSE;
    }

    maxItems = 5;
    pItems = HeapAlloc(GetProcessHeap(),0, maxItems * sizeof(SCRIPT_ITEM));
    if (!pItems)
    {
        WARN("Out of memory\n");
        HeapFree(GetProcessHeap(), 0, chartype);
        HeapFree(GetProcessHeap(), 0, levels);
        return FALSE;
    }

    if (lpGlyphs)
    {
#ifdef __REACTOS__
        /* ReactOS r57677 and r57679 */
        cMaxGlyphs = 3 * uCount / 2 + 16;
#else
        cMaxGlyphs = 1.5 * uCount + 16;
#endif
        run_glyphs = HeapAlloc(GetProcessHeap(),0,sizeof(WORD) * cMaxGlyphs);
        if (!run_glyphs)
        {
            WARN("Out of memory\n");
            HeapFree(GetProcessHeap(), 0, chartype);
            HeapFree(GetProcessHeap(), 0, levels);
            HeapFree(GetProcessHeap(), 0, pItems);
            return FALSE;
        }
        pwLogClust = HeapAlloc(GetProcessHeap(),0,sizeof(WORD) * uCount);
        if (!pwLogClust)
        {
            WARN("Out of memory\n");
            HeapFree(GetProcessHeap(), 0, chartype);
            HeapFree(GetProcessHeap(), 0, levels);
            HeapFree(GetProcessHeap(), 0, pItems);
            HeapFree(GetProcessHeap(), 0, run_glyphs);
            return FALSE;
        }
        psva = HeapAlloc(GetProcessHeap(),0,sizeof(SCRIPT_VISATTR) * uCount);
        if (!psva)
        {
            WARN("Out of memory\n");
            HeapFree(GetProcessHeap(), 0, chartype);
            HeapFree(GetProcessHeap(), 0, levels);
            HeapFree(GetProcessHeap(), 0, pItems);
            HeapFree(GetProcessHeap(), 0, run_glyphs);
            HeapFree(GetProcessHeap(), 0, pwLogClust);
            return FALSE;
        }
    }

    done = 0;
    glyph_i = 0;
    while (done < uCount)
    {
        INT j;
        classify(lpString + done, chartype, uCount - done);
        /* limit text to first block */
        i = resolveParagraphs(chartype, uCount - done);
        for (j = 0; j < i; ++j)
            switch(chartype[j])
            {
                case B:
                case S:
                case WS:
                case ON: chartype[j] = N;
                default: continue;
            }

        if ((dwWineGCP_Flags&WINE_GCPW_DIR_MASK) == WINE_GCPW_LOOSE_RTL)
            State.uBidiLevel = 1;
        else if ((dwWineGCP_Flags&WINE_GCPW_DIR_MASK) == WINE_GCPW_LOOSE_LTR)
            State.uBidiLevel = 0;

        if (dwWineGCP_Flags & WINE_GCPW_LOOSE_MASK)
        {
            for (j = 0; j < i; ++j)
                if (chartype[j] == L)
                {
                    State.uBidiLevel = 0;
                    break;
                }
                else if (chartype[j] == R || chartype[j] == AL)
                {
                    State.uBidiLevel = 1;
                    break;
                }
        }

        res = ScriptItemize(lpString + done, i, maxItems, &Control, &State, pItems, &nItems);
        while (res == E_OUTOFMEMORY)
        {
            maxItems = maxItems * 2;
            pItems = HeapReAlloc(GetProcessHeap(), 0, pItems, sizeof(SCRIPT_ITEM) * maxItems);
            if (!pItems)
            {
                WARN("Out of memory\n");
                HeapFree(GetProcessHeap(), 0, chartype);
                HeapFree(GetProcessHeap(), 0, levels);
                HeapFree(GetProcessHeap(), 0, run_glyphs);
                HeapFree(GetProcessHeap(), 0, pwLogClust);
                HeapFree(GetProcessHeap(), 0, psva);
                return FALSE;
            }
            res = ScriptItemize(lpString + done, i, maxItems, &Control, &State, pItems, &nItems);
        }

        if (lpOutString || lpOrder)
            for (j = 0; j < nItems; j++)
            {
                int k;
                for (k = pItems[j].iCharPos; k < pItems[j+1].iCharPos; k++)
                    levels[k] = pItems[j].a.s.uBidiLevel;
            }

        if (lpOutString)
        {
            /* assign directional types again, but for WS, S this time */
            classify(lpString + done, chartype, i);

            BidiLines(State.uBidiLevel, lpOutString + done, lpString + done,
                        chartype, levels, i, 0);
        }

        if (lpOrder)
        {
            int k, lastgood;
            for (j = lastgood = 0; j < i; ++j)
                if (levels[j] != levels[lastgood])
                {
                    --j;
                    if (odd(levels[lastgood]))
                        for (k = j; k >= lastgood; --k)
                            lpOrder[done + k] = done + j - k;
                    else
                        for (k = lastgood; k <= j; ++k)
                            lpOrder[done + k] = done + k;
                    lastgood = ++j;
                }
            if (odd(levels[lastgood]))
                for (k = j - 1; k >= lastgood; --k)
                    lpOrder[done + k] = done + j - 1 - k;
            else
                for (k = lastgood; k < j; ++k)
                    lpOrder[done + k] = done + k;
        }

        if (lpGlyphs && doGlyphs)
        {
            BYTE *runOrder;
            int *visOrder;
            SCRIPT_ITEM *curItem;

            runOrder = HeapAlloc(GetProcessHeap(), 0, maxItems * sizeof(*runOrder));
            visOrder = HeapAlloc(GetProcessHeap(), 0, maxItems * sizeof(*visOrder));
            if (!runOrder || !visOrder)
            {
                WARN("Out of memory\n");
                HeapFree(GetProcessHeap(), 0, runOrder);
                HeapFree(GetProcessHeap(), 0, visOrder);
                HeapFree(GetProcessHeap(), 0, chartype);
                HeapFree(GetProcessHeap(), 0, levels);
                HeapFree(GetProcessHeap(), 0, pItems);
                HeapFree(GetProcessHeap(), 0, psva);
                HeapFree(GetProcessHeap(), 0, pwLogClust);
                return FALSE;
            }

            for (j = 0; j < nItems; j++)
                runOrder[j] = pItems[j].a.s.uBidiLevel;

            ScriptLayout(nItems, runOrder, visOrder, NULL);

            for (j = 0; j < nItems; j++)
            {
                int k;
                int cChars,cOutGlyphs;
                curItem = &pItems[visOrder[j]];

                cChars = pItems[visOrder[j]+1].iCharPos - curItem->iCharPos;

                res = ScriptShape(hDC, &psc, lpString + done + curItem->iCharPos, cChars, cMaxGlyphs, &curItem->a, run_glyphs, pwLogClust, psva, &cOutGlyphs);
                while (res == E_OUTOFMEMORY)
                {
                    cMaxGlyphs *= 2;
                    run_glyphs = HeapReAlloc(GetProcessHeap(), 0, run_glyphs, sizeof(WORD) * cMaxGlyphs);
                    if (!run_glyphs)
                    {
                        WARN("Out of memory\n");
                        HeapFree(GetProcessHeap(), 0, runOrder);
                        HeapFree(GetProcessHeap(), 0, visOrder);
                        HeapFree(GetProcessHeap(), 0, chartype);
                        HeapFree(GetProcessHeap(), 0, levels);
                        HeapFree(GetProcessHeap(), 0, pItems);
                        HeapFree(GetProcessHeap(), 0, psva);
                        HeapFree(GetProcessHeap(), 0, pwLogClust);
                        HeapFree(GetProcessHeap(), 0, *lpGlyphs);
                        ScriptFreeCache(&psc);
                        *lpGlyphs = NULL;
                        return FALSE;
                    }
                    res = ScriptShape(hDC, &psc, lpString + done + curItem->iCharPos, cChars, cMaxGlyphs, &curItem->a, run_glyphs, pwLogClust, psva, &cOutGlyphs);
                }
                if (res)
                {
                    if (res == USP_E_SCRIPT_NOT_IN_FONT)
                        TRACE("Unable to shape with currently selected font\n");
                    else
                        FIXME("Unable to shape string (%x)\n",res);
                    j = nItems;
                    doGlyphs = FALSE;
                    HeapFree(GetProcessHeap(), 0, *lpGlyphs);
                    *lpGlyphs = NULL;
                }
                else
                {
                    if (*lpGlyphs)
                        *lpGlyphs = HeapReAlloc(GetProcessHeap(), 0, *lpGlyphs, sizeof(WORD) * (glyph_i + cOutGlyphs));
                   else
                        *lpGlyphs = HeapAlloc(GetProcessHeap(), 0, sizeof(WORD) * (glyph_i + cOutGlyphs));
                    for (k = 0; k < cOutGlyphs; k++)
                        (*lpGlyphs)[glyph_i+k] = run_glyphs[k];
                    glyph_i += cOutGlyphs;
                }
            }
            HeapFree(GetProcessHeap(), 0, runOrder);
            HeapFree(GetProcessHeap(), 0, visOrder);
        }

        done += i;
    }
    if (cGlyphs)
        *cGlyphs = glyph_i;

    HeapFree(GetProcessHeap(), 0, chartype);
    HeapFree(GetProcessHeap(), 0, levels);
    HeapFree(GetProcessHeap(), 0, pItems);
    HeapFree(GetProcessHeap(), 0, run_glyphs);
    HeapFree(GetProcessHeap(), 0, pwLogClust);
    HeapFree(GetProcessHeap(), 0, psva);
    ScriptFreeCache(&psc);
    return TRUE;
}
示例#19
0
void test_edges()
{
    const double pi = std::atan2(+0., -0.);
    const unsigned N = sizeof(x) / sizeof(x[0]);
    for (unsigned i = 0; i < N; ++i)
    {
        double r = arg(x[i]);
        if (std::isnan(x[i].real()) || std::isnan(x[i].imag()))
            assert(std::isnan(r));
        else
        {
            switch (classify(x[i]))
            {
            case zero:
                if (std::signbit(x[i].real()))
                {
                    if (std::signbit(x[i].imag()))
                        is_about(r, -pi);
                    else
                        is_about(r, pi);
                }
                else
                {
                    assert(std::signbit(x[i].imag()) == std::signbit(r));
                }
                break;
            case non_zero:
                if (x[i].real() == 0)
                {
                    if (x[i].imag() < 0)
                        is_about(r, -pi/2);
                    else
                        is_about(r, pi/2);
                }
                else if (x[i].imag() == 0)
                {
                    if (x[i].real() < 0)
                    {
                        if (std::signbit(x[i].imag()))
                            is_about(r, -pi);
                        else
                            is_about(r, pi);
                    }
                    else
                    {
                        assert(r == 0);
                        assert(std::signbit(x[i].imag()) == std::signbit(r));
                    }
                }
                else if (x[i].imag() > 0)
                    assert(r > 0);
                else
                    assert(r < 0);
                break;
            case inf:
                if (std::isinf(x[i].real()) && std::isinf(x[i].imag()))
                {
                    if (x[i].real() < 0)
                    {
                        if (x[i].imag() > 0)
                            is_about(r, 0.75 * pi);
                        else
                            is_about(r, -0.75 * pi);
                    }
                    else
                    {
                        if (x[i].imag() > 0)
                            is_about(r, 0.25 * pi);
                        else
                            is_about(r, -0.25 * pi);
                    }
                }
                else if (std::isinf(x[i].real()))
                {
                    if (x[i].real() < 0)
                    {
                        if (std::signbit(x[i].imag()))
                            is_about(r, -pi);
                        else
                            is_about(r, pi);
                    }
                    else
                    {
                        assert(r == 0);
                        assert(std::signbit(r) == std::signbit(x[i].imag()));
                    }
                }
                else
                {
                    if (x[i].imag() < 0)
                        is_about(r, -pi/2);
                    else
                        is_about(r, pi/2);
                }
                break;
            }
        }
    }
}
示例#20
0
pair<bool, double> RvmClassifier::getConfidence(pair<int, double> levelAndDistance) const {
	if (classify(levelAndDistance))
		return make_pair(true, levelAndDistance.second);
	else
		return make_pair(false, -levelAndDistance.second);
}
示例#21
0
int point::classify(edge& e)
{
	return classify(e.org, e.dest);
}
bool RvmClassifier::classify(const Mat& featureVector) const {
	return classify(computeHyperplaneDistance(featureVector));
}
示例#23
0
int
PyParser_AddToken(register parser_state *ps, register int type, char *str,
	          int lineno, int *expected_ret)
{
	register int ilabel;
	int err;
	
	D(printf("Token %s/'%s' ... ", _PyParser_TokenNames[type], str));
	
	/* Find out which label this token is */
	ilabel = classify(ps, type, str);
	if (ilabel < 0)
		return E_SYNTAX;
	
	/* Loop until the token is shifted or an error occurred */
	for (;;) {
		/* Fetch the current dfa and state */
		register dfa *d = ps->p_stack.s_top->s_dfa;
		register state *s = &d->d_state[ps->p_stack.s_top->s_state];
		
		D(printf(" DFA '%s', state %d:",
			d->d_name, ps->p_stack.s_top->s_state));
		
		/* Check accelerator */
		if (s->s_lower <= ilabel && ilabel < s->s_upper) {
			register int x = s->s_accel[ilabel - s->s_lower];
			if (x != -1) {
				if (x & (1<<7)) {
					/* Push non-terminal */
					int nt = (x >> 8) + NT_OFFSET;
					int arrow = x & ((1<<7)-1);
					dfa *d1 = PyGrammar_FindDFA(
						ps->p_grammar, nt);
					if ((err = push(&ps->p_stack, nt, d1,
						arrow, lineno)) > 0) {
						D(printf(" MemError: push\n"));
						return err;
					}
					D(printf(" Push ...\n"));
					continue;
				}
				
				/* Shift the token */
				if ((err = shift(&ps->p_stack, type, str,
						x, lineno)) > 0) {
					D(printf(" MemError: shift.\n"));
					return err;
				}
				D(printf(" Shift.\n"));
				/* Pop while we are in an accept-only state */
				while (s = &d->d_state
						[ps->p_stack.s_top->s_state],
					s->s_accept && s->s_narcs == 1) {
					D(printf("  DFA '%s', state %d: "
						 "Direct pop.\n",
						 d->d_name,
						 ps->p_stack.s_top->s_state));
					if (d->d_name[0] == 'i' &&
					    strcmp(d->d_name,
						   "import_stmt") == 0)
						future_hack(ps);
					s_pop(&ps->p_stack);
					if (s_empty(&ps->p_stack)) {
						D(printf("  ACCEPT.\n"));
						return E_DONE;
					}
					d = ps->p_stack.s_top->s_dfa;
				}
				return E_OK;
			}
		}
		
		if (s->s_accept) {
			if (d->d_name[0] == 'i' &&
			    strcmp(d->d_name, "import_stmt") == 0)
				future_hack(ps);
			/* Pop this dfa and try again */
			s_pop(&ps->p_stack);
			D(printf(" Pop ...\n"));
			if (s_empty(&ps->p_stack)) {
				D(printf(" Error: bottom of stack.\n"));
				return E_SYNTAX;
			}
			continue;
		}
		
		/* Stuck, report syntax error */
		D(printf(" Error.\n"));
		if (expected_ret) {
			if (s->s_lower == s->s_upper - 1) {
				/* Only one possible expected token */
				*expected_ret = ps->p_grammar->
				    g_ll.ll_label[s->s_lower].lb_type;
			}
			else 
		        	*expected_ret = -1;
		}
		return E_SYNTAX;
	}
void classifyAndTest(const Dataset& data,
		unsigned int numFolds,
		ClassifierType ctype,
		int verbosity,
		std::ostream& resultsOut,
		std::string modelOutName,
		std::ostream& finalResults)
{
	std::vector<unsigned int> timesRight(numFolds, 0);
	std::vector<unsigned int> timesWrong(numFolds, 0);
	std::vector<unsigned int> timesUndecided(numFolds, 0);
	auto totalTimesRight = 0;
	auto totalTimesWrong = 0;
	auto totalTimesUndecided = 0;

	// Classify and test the data
	for (auto k = 1; k <= numFolds; ++k)
	{
		// Partition into testing and training sets
		auto indices = kFoldIndices(k, numFolds, data.size());
		auto partitions = data.partition(indices.first, indices.second);

		// Create a classifier for the dataset
		auto c = partitions.training.classifier(ctype);

		// If it's a decision tree, output it
		if (ctype == ClassifierType::DECISION_TREE)
		{
			// Although for leave-one-out testing we only print one
			// tree, since there's ~100 of them and they all look
			// nearly identical.
			if (numFolds <= 20 || k == 1)
			{
				std::stringstream name;
				name << modelOutName << "-" << k << ".dot";
				auto modelOut = std::ofstream{name.str()};
				assert(modelOut.is_open());
				dynamic_cast<DecisionTree*>(c.get())->print(modelOut);
				modelOut.close();
			}
		}

		// Test each point in the testing set
		for (auto i = 0; i < partitions.testing.size(); ++i)
		{
			// Classify
			auto type = c->classify(partitions.testing.getPoint(i));

			if (type == partitions.testing.getType(i))
			{
				resultsOut << "Decided true class " << static_cast<int>(type)
					<< " for " << partitions.testing.getPoint(i) << std::endl;
			}
			else if (type == NoType)
			{
				resultsOut << "Undecided (actual "
					<< static_cast<int>(partitions.testing.getType(i))
					<< ") for " << partitions.testing.getPoint(i) << std::endl;
			}
			else
			{
				resultsOut << "Decided wrong class " << static_cast<int>(type)
					<< " (actual "
					<< static_cast<int>(partitions.testing.getType(i))
					<< ") for " << partitions.testing.getPoint(i) << std::endl;
			}

			// Update counters
			if (type == partitions.testing.getType(i))
			{
				++timesRight[k-1];
			}
			else if (type == NoType)
			{
				++timesUndecided[k-1];
			}
			else
			{
				++timesWrong[k-1];
			}
		}

		// Report the accuracy on this fold (unless we're just doing 1 element)
		if (partitions.testing.size() > 1)
		{
			resultsOut << "Fold " << k << ": timesRight=" << timesRight[k-1]
					  << ", timesWrong=" << timesWrong[k-1]
					  << ", timesUndecided=" << timesUndecided[k-1]
		              << ", accuracy: " << timesRight[k-1]/
					     static_cast<double>(timesWrong[k-1]
										+timesRight[k-1]+timesUndecided[k-1])
				      << std::endl << std::endl;
		}

		// Update overall accuracy
		totalTimesRight += timesRight[k-1];
		totalTimesUndecided += timesUndecided[k-1];
		totalTimesWrong += timesWrong[k-1];
	}

	// Report overall accuracy
	auto accuracy = totalTimesRight / static_cast<double>(totalTimesRight
		    		  + totalTimesWrong + totalTimesUndecided);
	resultsOut << "Total: timesRight=" << totalTimesRight
			  << ", timesWrong=" << totalTimesWrong
			  << ", timesUndecided=" << totalTimesUndecided
			  << ", accuracy=" << accuracy
			  << std::endl << std::endl << std::endl;

	finalResults << "," << accuracy;
}
示例#25
0
int test__muldc3(double a, double b, double c, double d)
{
    double _Complex r = __muldc3(a, b, c, d);
//     printf("test__muldc3(%f, %f, %f, %f) = %f + I%f\n",
//             a, b, c, d, creal(r), cimag(r));
	double _Complex dividend;
	double _Complex divisor;
	
	__real__ dividend = a;
	__imag__ dividend = b;
	__real__ divisor = c;
	__imag__ divisor = d;
	
    switch (classify(dividend))
    {
    case zero:
        switch (classify(divisor))
        {
        case zero:
            if (classify(r) != zero)
                return 1;
            break;
        case non_zero:
            if (classify(r) != zero)
                return 1;
            break;
        case inf:
            if (classify(r) != NaN)
                return 1;
            break;
        case NaN:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero_nan:
            if (classify(r) != NaN)
                return 1;
            break;
        }
        break;
    case non_zero:
        switch (classify(divisor))
        {
        case zero:
            if (classify(r) != zero)
                return 1;
            break;
        case non_zero:
            if (classify(r) != non_zero)
                return 1;
            if (r != a * c - b * d + _Complex_I*(a * d + b * c))
                return 1;
            break;
        case inf:
            if (classify(r) != inf)
                return 1;
            break;
        case NaN:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero_nan:
            if (classify(r) != NaN)
                return 1;
            break;
        }
        break;
    case inf:
        switch (classify(divisor))
        {
        case zero:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero:
            if (classify(r) != inf)
                return 1;
            break;
        case inf:
            if (classify(r) != inf)
                return 1;
            break;
        case NaN:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero_nan:
            if (classify(r) != inf)
                return 1;
            break;
        }
        break;
    case NaN:
        switch (classify(divisor))
        {
        case zero:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero:
            if (classify(r) != NaN)
                return 1;
            break;
        case inf:
            if (classify(r) != NaN)
                return 1;
            break;
        case NaN:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero_nan:
            if (classify(r) != NaN)
                return 1;
            break;
        }
        break;
    case non_zero_nan:
        switch (classify(divisor))
        {
        case zero:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero:
            if (classify(r) != NaN)
                return 1;
            break;
        case inf:
            if (classify(r) != inf)
                return 1;
            break;
        case NaN:
            if (classify(r) != NaN)
                return 1;
            break;
        case non_zero_nan:
            if (classify(r) != NaN)
                return 1;
            break;
        }
        break;
    }
    
    return 0;
}
示例#26
0
QVariant FolderStatusModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    if (role == Qt::EditRole)
        return QVariant();

    switch(classify(index)) {
    case AddButton: {
        if (role == FolderStatusDelegate::AddButton) {
            return QVariant(true);
        } else if (role == Qt::ToolTipRole) {
            if (!_accountState->isConnected()) {
                return tr("You need to be connected to add a folder");
            } if (_folders.count() == 1) {
                auto remotePath = _folders.at(0)._folder->remotePath();
                if (remotePath.isEmpty() || remotePath == QLatin1String("/")) {
                    // Syncing the entire owncloud: disable the add folder button (#3438)
                    return tr("Adding folder is disabled because you are already syncing all your files. "
                            "If you want to sync multiple folders, please remove the currently "
                            "configured root folder.");
                }
            }
            return tr("Click this button to add a folder to synchronize.");
        }
        return QVariant();
    }
    case SubFolder:
    {
        const auto &x = static_cast<SubFolderInfo *>(index.internalPointer())->_subs[index.row()];
        switch (role) {
        case Qt::ToolTipRole:
        case Qt::DisplayRole:
            return tr("%1 (%2)").arg(x._name, Utility::octetsToString(x._size));
        case Qt::CheckStateRole:
            return x._checked;
        case Qt::DecorationRole:
            return QFileIconProvider().icon(QFileIconProvider::Folder);
        case Qt::ForegroundRole:
            if (x._isUndecided) {
                return QColor(Qt::red);
            }
            break;
        }
    }
        return QVariant();
    case FetchLabel:
    {
        const auto x = static_cast<SubFolderInfo *>(index.internalPointer());
        switch(role) {
            case Qt::DisplayRole:
                if (x->_hasError) {
                    return tr("Error while loading the list of folders from the server.");
                } else {
                    return tr("Fetching folder list from server...");
                }
                break;
            default: return QVariant();
        }
    }
    case RootFolder:
        break;
    }

    const SubFolderInfo & folderInfo = _folders.at(index.row());
    auto f = folderInfo._folder;
    if (!f)
        return QVariant();

    const SubFolderInfo::Progress & progress = folderInfo._progress;
    const bool accountConnected = _accountState->isConnected();

    switch (role) {
    case FolderStatusDelegate::FolderPathRole         : return  f->shortGuiPath();
    case FolderStatusDelegate::FolderSecondPathRole   : return  f->remotePath();
    case FolderStatusDelegate::HeaderRole             : return  f->aliasGui();
    case FolderStatusDelegate::FolderAliasRole        : return  f->alias();
    case FolderStatusDelegate::FolderSyncPaused       : return  f->syncPaused();
    case FolderStatusDelegate::FolderAccountConnected : return  accountConnected;
    case Qt::ToolTipRole:
        if ( accountConnected )
            return Theme::instance()->statusHeaderText(f->syncResult().status());
        else
            return tr("Signed out");
    case FolderStatusDelegate::FolderStatusIconRole:
        if ( accountConnected ) {
            auto theme = Theme::instance();
            auto status = f->syncResult().status();
            if( f->syncPaused() ) {
                return theme->folderDisabledIcon( );
            } else {
                if( status == SyncResult::SyncPrepare ) {
                    return theme->syncStateIcon(SyncResult::SyncRunning);
                } else if( status == SyncResult::Undefined ) {
                    return theme->syncStateIcon( SyncResult::SyncRunning);
                } else {
                    // keep the previous icon for the prepare phase.
                    if( status == SyncResult::Problem) {
                        return theme->syncStateIcon( SyncResult::Success);
                    } else {
                        return theme->syncStateIcon( status );
                    }
                }
            }
        } else {
            return Theme::instance()->folderOfflineIcon();
        }
    case FolderStatusDelegate::SyncProgressItemString:
        return progress._progressString;
    case FolderStatusDelegate::WarningCount:
        return progress._warningCount;
    case FolderStatusDelegate::SyncProgressOverallPercent:
        return progress._overallPercent;
    case FolderStatusDelegate::SyncProgressOverallString:
        return progress._overallSyncString;
    }
    return QVariant();
}
示例#27
0
bool DecimalUtil::isNan(Decimal128 x)
{
    return classify(x) == FP_NAN;
}
示例#28
0
文件: ref.cpp 项目: att/uwin
void reference::output(FILE *fp)
{
  fputs(".]-\n", fp);
  for (int i = 0; i < 256; i++)
    if (field_index[i] != NULL_FIELD_INDEX && i != annotation_field) {
      string &f = field[field_index[i]];
      if (!csdigit(i)) {
	int j = reverse_fields.search(i);
	if (j >= 0) {
	  int n;
	  int len = reverse_fields.length();
	  if (++j < len && csdigit(reverse_fields[j])) {
	    n = reverse_fields[j] - '0';
	    for (++j; j < len && csdigit(reverse_fields[j]); j++)
	      // should check for overflow
	      n = n*10 + reverse_fields[j] - '0';
	  }
	  else 
	    n = INT_MAX;
	  reverse_names(f, n);
	}
      }
      int is_multiple = join_fields(f) > 0;
      if (capitalize_fields.search(i) >= 0)
	capitalize_field(f);
      if (memchr(f.contents(), '\n', f.length()) == 0) {
	fprintf(fp, ".ds [%c ", i);
	if (f[0] == ' ' || f[0] == '\\' || f[0] == '"')
	  putc('"', fp);
	put_string(f, fp);
	putc('\n', fp);
      }
      else {
	fprintf(fp, ".de [%c\n", i);
	put_string(f, fp);
	fputs("..\n", fp);
      }
      if (i == 'P') {
	int multiple_pages = 0;
	const char *s = f.contents();
	const char *end = f.contents() + f.length();
	for (;;) {
	  const char *token_start = s;
	  if (!get_token(&s, end))
	    break;
	  const token_info *ti = lookup_token(token_start, s);
	  if (ti->is_hyphen() || ti->is_range_sep()) {
	    multiple_pages = 1;
	    break;
	  }
	}
	fprintf(fp, ".nr [P %d\n", multiple_pages);
      }
      else if (i == 'E')
	fprintf(fp, ".nr [E %d\n", is_multiple);
    }
  for (const char *p = "TAO"; *p; p++) {
    int fi = field_index[(unsigned char)*p];
    if (fi != NULL_FIELD_INDEX) {
      string &f = field[fi];
      fprintf(fp, ".nr [%c %d\n", *p,
	      is_terminated(f.contents(), f.contents() + f.length()));
    }
  }
  int t = classify();
  fprintf(fp, ".][ %d %s\n", t, reference_types[t]);
  if (annotation_macro.length() > 0 && annotation_field >= 0
      && field_index[annotation_field] != NULL_FIELD_INDEX) {
    putc('.', fp);
    put_string(annotation_macro, fp);
    putc('\n', fp);
    put_string(field[field_index[annotation_field]], fp);
  }
}
示例#29
0
bool DecimalUtil::isFinite(Decimal128 x)
{
    int cl = classify(x);
    return cl != FP_INFINITE && cl != FP_NAN;
}
示例#30
0
文件: r.c 项目: wpwrak/subosm
    const struct node *b, const struct node *c)
{
	static const uint32_t color[] = {
		[good]		= GOOD,
		[average]	= AVERAGE,
		[bad]		= BAD,
		[remote]	= REMOTE
	};
	uint32_t ca, cb, cc;
	double wab, wac, wbc;
	int mabx, maby, macx, macy, mbcx, mbcy;
	int mx, my;

	/* colors of corners */

	ca = color[classify(a->d)];
	cb = color[classify(b->d)];
	cc = color[classify(c->d)];

	/* find where on a side the border is */

	wab = split(a->d, b->d);
	wac = split(a->d, c->d);
	wbc = split(b->d, c->d);

	/* border points on sides */

	mabx = wab*a->x+(1-wab)*b->x;
	maby = wab*a->y+(1-wab)*b->y;
	macx = wac*a->x+(1-wac)*c->x;
	macy = wac*a->y+(1-wac)*c->y;