long double Interface::readInput(std::string search) {
  std::vector<long double> out;
  out = readData(search);
  
  return out[0];
}
Example #2
0
uint32_t RTCMemStore::getMillis() {
  readData();
  uint32_t x = rtcData->millisStartIteration;
  updateData();
  return x;
}
Example #3
0
void RTCMemStore::init() {
  dataExisted = readData();
  updateData();
}
Example #4
0
uint8_t RTCMemStore::getIterations() {
  readData();
  uint8_t x = rtcData->interations;
  updateData();
  return x;
}
Example #5
0
double RTCMemStore::getAverage() {
  readData();
  double x = rtcData->avg1.getAverage();
  updateData();
  return x;
}
Example #6
0
static afs_int32
ReadTapeBlock(struct butm_tapeInfo *info,
	      char *buffer, /* assumed to be 16384 bytes */
	      afs_int32 *blockType)
{
    afs_int32 code = 0;
    afs_int32 rsize, fmtype;
    struct tapeLabel *label;
    struct fileMark *fmark;
    struct blockMark *bmark;
    struct progress *p;

    *blockType = BLOCK_UNKNOWN;

    p = (struct progress *)info->tmRock;

    memset(buffer, 0, BUTM_BLOCKSIZE);
    label = (struct tapeLabel *)buffer;
    fmark = (struct fileMark *)buffer;
    bmark = (struct blockMark *)buffer;

    rsize = readData(p->fid, buffer, BUTM_BLOCKSIZE, &info->error);
    if (rsize > 0) {
	incPosition(info, p->fid, rsize);
	p->reading++;
    }

    if (rsize == 0) {		/* Read a HW EOF Marker? OK */
	*blockType = BLOCK_EOF;
	incSize(info, config.fileMarkSize);	/* Size of filemark */
	if (!isafile)
	    info->position++;	/* bump position */
	p->reading = 0;		/* No reads since EOF */
    }

    else if (rsize != BUTM_BLOCKSIZE) {	/* Didn't Read a full block */
	info->status |= BUTM_STATUS_READERROR;
	ERROR_EXIT((rsize < 0) ? BUTM_IO : BUTM_EOT);
    }

    else if (ntohl(bmark->magic) == BLOCK_MAGIC) {	/* Data block? */
	*blockType = BLOCK_DATA;
    }

    else if (ntohl(fmark->magic) == FILE_MAGIC) {	/* Read a filemark? */
	fmtype = ntohl(fmark->nBytes);

	if (fmtype == FILE_BEGIN) {	/* filemark begin */
	    *blockType = BLOCK_FMBEGIN;
	} else if (fmtype == FILE_FMEND) {	/* filemark end */
	    *blockType = BLOCK_FMEND;
	    code = SeekFile(info, 1);
	} else if (fmtype == FILE_EOD) {	/* EOD mark */
	    *blockType = BLOCK_EOD;
	    info->status |= BUTM_STATUS_EOD;
	    code = SeekFile(info, 1);
	}
    }

    else if (ntohl(label->magic) == TAPE_MAGIC) {	/* Read a tape label? */
	*blockType = BLOCK_LABEL;
	code = SeekFile(info, 1);
    }

    if (isafile)
	info->position++;

  error_exit:
    return (code);
}
Example #7
0
void RTCMemStore::setLastDweet(const char *s) {
  readData();
  strcpy(rtcData->lastDweetCreated, s);
  updateData();
}
Example #8
0
int show_mask1(PARAM *p)
{
  DATA d;
  char event[MAX_EVENT_LENGTH];
  char text[MAX_EVENT_LENGTH];
  char str1[MAX_EVENT_LENGTH];
  int  i,w,h,val,x,y,button,ret;
  float xval, yval;

  defineMask(p);
  //rlSetDebugPrintf(1);
  if((ret=slotInit(p,&d)) != 0) return ret;
  readData(&d); // from shared memory, database or something else
  showData(p,&d);
  pvClearMessageQueue(p);
  while(1)
  {
    pvPollEvent(p,event);
    switch(pvParseEvent(event, &i, text))
    {
      case NULL_EVENT:
        readData(&d); // from shared memory, database or something else
        showData(p,&d);
        if((ret=slotNullEvent(p,&d)) != 0) return ret;
        break;
      case BUTTON_EVENT:
        if(trace) printf("BUTTON_EVENT id=%d\n",i);
        if((ret=slotButtonEvent(p,i,&d)) != 0) return ret;
        break;
      case BUTTON_PRESSED_EVENT:
        if(trace) printf("BUTTON_PRESSED_EVENT id=%d\n",i);
        if((ret=slotButtonPressedEvent(p,i,&d)) != 0) return ret;
        break;
      case BUTTON_RELEASED_EVENT:
        if(trace) printf("BUTTON_RELEASED_EVENT id=%d\n",i);
        if((ret=slotButtonReleasedEvent(p,i,&d)) != 0) return ret;
        break;
      case TEXT_EVENT:
        if(trace) printf("TEXT_EVENT id=%d %s\n",i,text);
        if((ret=slotTextEvent(p,i,&d,text)) != 0) return ret;
        break;
      case SLIDER_EVENT:
        sscanf(text,"(%d)",&val);
        if(trace) printf("SLIDER_EVENT val=%d\n",val);
        if((ret=slotSliderEvent(p,i,&d,val)) != 0) return ret;
        break;
      case CHECKBOX_EVENT:
        if(trace) printf("CHECKBOX_EVENT id=%d %s\n",i,text);
        if((ret=slotCheckboxEvent(p,i,&d,text)) != 0) return ret;
        break;
      case RADIOBUTTON_EVENT:
        if(trace) printf("RADIOBUTTON_EVENT id=%d %s\n",i,text);
        if((ret=slotRadioButtonEvent(p,i,&d,text)) != 0) return ret;
        break;
      case GL_INITIALIZE_EVENT:
        if(trace) printf("you have to call initializeGL()\n");
        if((ret=slotGlInitializeEvent(p,i,&d)) != 0) return ret;
        break;
      case GL_PAINT_EVENT:
        if(trace) printf("you have to call paintGL()\n");
        if((ret=slotGlPaintEvent(p,i,&d)) != 0) return ret;
        break;
      case GL_RESIZE_EVENT:
        sscanf(text,"(%d,%d)",&w,&h);
        if(trace) printf("you have to call resizeGL(w,h)\n");
        if((ret=slotGlResizeEvent(p,i,&d,w,h)) != 0) return ret;
        break;
      case GL_IDLE_EVENT:
        if((ret=slotGlIdleEvent(p,i,&d)) != 0) return ret;
        break;
      case TAB_EVENT:
        sscanf(text,"(%d)",&val);
        if(trace) printf("TAB_EVENT(%d,page=%d)\n",i,val);
        if((ret=slotTabEvent(p,i,&d,val)) != 0) return ret;
        break;
      case TABLE_TEXT_EVENT:
        sscanf(text,"(%d,%d,",&x,&y);
        pvGetText(text,str1);
        if(trace) printf("TABLE_TEXT_EVENT(%d,%d,\"%s\")\n",x,y,str1);
        if((ret=slotTableTextEvent(p,i,&d,x,y,str1)) != 0) return ret;
        break;
      case TABLE_CLICKED_EVENT:
        sscanf(text,"(%d,%d,%d)",&x,&y,&button);
        if(trace) printf("TABLE_CLICKED_EVENT(%d,%d,button=%d)\n",x,y,button);
        if((ret=slotTableClickedEvent(p,i,&d,x,y,button)) != 0) return ret;
        break;
      case SELECTION_EVENT:
        sscanf(text,"(%d,",&val);
        pvGetText(text,str1);
        if(trace) printf("SELECTION_EVENT(column=%d,\"%s\")\n",val,str1);
        if((ret=slotSelectionEvent(p,i,&d,val,str1)) != 0) return ret;
        break;
      case CLIPBOARD_EVENT:
        sscanf(text,"(%d",&val);
        if(trace) printf("CLIPBOARD_EVENT(id=%d)\n",val);
        if(trace) printf("clipboard = \n%s\n",p->clipboard);
        if((ret=slotClipboardEvent(p,i,&d,val)) != 0) return ret;
        break;
      case RIGHT_MOUSE_EVENT:
        if(trace) printf("RIGHT_MOUSE_EVENT id=%d text=%s\n",i,text);
        if((ret=slotRightMouseEvent(p,i,&d,text)) != 0) return ret;
        break;
      case KEYBOARD_EVENT:
        sscanf(text,"(%d",&val);
        if(trace) printf("KEYBOARD_EVENT modifier=%d key=%d\n",i,val);
        if((ret=slotKeyboardEvent(p,i,&d,val,i)) != 0) return ret;
        break;
      case PLOT_MOUSE_MOVED_EVENT:
        sscanf(text,"(%f,%f)",&xval,&yval);
        if(trace) printf("PLOT_MOUSE_MOVE %f %f\n",xval,yval);
        if((ret=slotMouseMovedEvent(p,i,&d,xval,yval)) != 0) return ret;
        break;
      case PLOT_MOUSE_PRESSED_EVENT:
        sscanf(text,"(%f,%f)",&xval,&yval);
        if(trace) printf("PLOT_MOUSE_PRESSED %f %f\n",xval,yval);
        if((ret=slotMousePressedEvent(p,i,&d,xval,yval)) != 0) return ret;
        break;
      case PLOT_MOUSE_RELEASED_EVENT:
        sscanf(text,"(%f,%f)",&xval,&yval);
        if(trace) printf("PLOT_MOUSE_RELEASED %f %f\n",xval,yval);
        if((ret=slotMouseReleasedEvent(p,i,&d,xval,yval)) != 0) return ret;
        break;
      case MOUSE_OVER_EVENT:
        sscanf(text,"%d",&val);
        if(trace) printf("MOUSE_OVER_EVENT %d\n",val);
        if((ret=slotMouseOverEvent(p,i,&d,val)) != 0) return ret;
        break;
      case USER_EVENT:
        if(trace) printf("USER_EVENT id=%d %s\n",i,text);
        if((ret=slotUserEvent(p,i,&d,text)) != 0) return ret;
        break;
      default:
        if(trace) printf("UNKNOWN_EVENT id=%d %s\n",i,text);
        break;
    }
  }
}
Example #9
0
int IptcParser::decode(
    IptcData& iptcData,
    const byte*     pData,
    uint32_t  size
)
{
#ifdef DEBUG
    std::cerr << "IptcParser::decode, size = " << size << "\n";
#endif
    const byte* pRead = pData;
    iptcData.clear();

    uint16_t record = 0;
    uint16_t dataSet = 0;
    uint32_t sizeData = 0;
    byte extTest = 0;

    while (pRead + 3 < pData + size) {
        // First byte should be a marker. If it isn't, scan forward and skip
        // the chunk bytes present in some images. This deviates from the
        // standard, which advises to treat such cases as errors.
        if (*pRead++ != marker_) continue;
        record = *pRead++;
        dataSet = *pRead++;

        extTest = *pRead;
        if (extTest & 0x80) {
            // extended dataset
            uint16_t sizeOfSize = (getUShort(pRead, bigEndian) & 0x7FFF);
            if (sizeOfSize > 4) return 5;
            pRead += 2;
            sizeData = 0;
            for (; sizeOfSize > 0; --sizeOfSize) {
                sizeData |= *pRead++ << (8 *(sizeOfSize-1));
            }
        }
        else {
            // standard dataset
            sizeData = getUShort(pRead, bigEndian);
            pRead += 2;
        }
        if (pRead + sizeData <= pData + size) {
            int rc = 0;
            if ((rc = readData(iptcData, dataSet, record, pRead, sizeData)) != 0) {
#ifndef SUPPRESS_WARNINGS
                EXV_WARNING << "Failed to read IPTC dataset "
                            << IptcKey(dataSet, record)
                            << " (rc = " << rc << "); skipped.\n";
#endif
            }
        }
#ifndef SUPPRESS_WARNINGS
        else {
            EXV_WARNING << "IPTC dataset " << IptcKey(dataSet, record)
                        << " has invalid size " << sizeData << "; skipped.\n";
        }
#endif
        pRead += sizeData;
    }

    return 0;
} // IptcParser::decode
/// Process data received by UART 
///
void simpleBinary::processSerial()
{
    while (serial->available() > 0) 
    {
      int data = serial->read();

      serbuf[serbuflen++] = data;
    }

    if(serbuflen > 3)
    {
      receiveTime = millis();
       
      if(serbuf[0] == _uartAddress)    
      {
        int address;
        char crc;
        
        switch(serbuf[1])
        {
          //new data
          case (char)0xD0:  
            if(serbuf[2] == 0x01)
            {
               //force all output data as new through user function
               forceAllNewData();
            }
            if(serbuf[2] == 0x00 || serbuf[2] == 0x01)
            {
               crc = CRC8::evalCRC(serbuf,3);

               if(crc != serbuf[3])
                  sendWrongData(crc);
                else
                  checkNewData();
            }   
            else
              sendUnknownData();              

            serbuflen = 0;                       
            break;
          //read data  
          case (char)0xD1: 
            if(serbuflen < 5)
              break;
              
            address =  serbuf[2] | (serbuf[3] << 8);
            
            crc = CRC8::evalCRC(serbuf,4);

            if(crc != serbuf[4])
               sendWrongData(crc);
            else
               readData(address);            

            serbuflen = 0;           
            break;
          //write byte
          case (char)0xDA:
            if(serbuflen < 6)
              break;
            //address
            address = serbuf[2] | (serbuf[3] << 8);
            //crc check
            crc = CRC8::evalCRC(serbuf,5);
            if(serbuf[5] != crc)
              sendWrongData(crc);
            else         
            {
              //check address
              if(!checkAddress(address))
                sendInvalidAddress();               
              //write data into memory
              if(saveByte(address,serbuf+4))
                sendOK();
              else
                sendSavingError();
            }
            //clear buffer
            serbuflen = 0;                                                           
            break;
          //write word
          case (char)0xDB:
            if(serbuflen < 7)
              break;

            //address 
            address = serbuf[2] | (serbuf[3] << 8);
            //crc check
            crc = CRC8::evalCRC(serbuf,6);
            if(serbuf[6] != crc)
              sendWrongData(crc);
            else       
            {
              //check address
              if(!checkAddress(address))
                sendInvalidAddress();                 
              //write data into memory
              if(saveWord(address,serbuf+4))
                sendOK();
              else
                sendSavingError();              
            }
            //clear buffer
            serbuflen = 0;            
            break;
          //write dword
          case (char)0xDC:
          case (char)0xDD:
            if(serbuflen < 9)
              break;

            //address
            address = serbuf[2] | (serbuf[3] << 8);
            //crc check
            crc = CRC8::evalCRC(serbuf,8);
            if(serbuf[8] != crc)
              sendWrongData(crc);
            else
            {
              //check address
              if(!checkAddress(address))
                sendInvalidAddress();
              //write data into memory
              if(saveDword(address,serbuf+4))
                sendOK();
              else
                sendSavingError();  
            }
            //clear buffer
            serbuflen = 0;             
            break;
          //write array
          case (char)0xDE:
            if(serbuflen < 6)
              break;
            
            int datalen;
            datalen = (serbuf[4] | (serbuf[5] << 8));
            //correct packet length check
            if(serbuflen < 7 + datalen)
              break;

            //address
            address = serbuf[2] | (serbuf[3] << 8);
            //crc check
            crc = CRC8::evalCRC(serbuf,6+datalen);
            if(serbuf[7+datalen] != crc)
              sendWrongData(crc);
            else            
            {
              //check address
              if(!checkAddress(address))
                sendInvalidAddress();
              char *pData = serbuf + 6;
              //write data into memory              
              if(saveArray(address,pData, datalen))
                sendOK();
              else
                sendSavingError();              
            }
            //clear buffer
            serbuflen = 0;               
            break;                        
          default:
            serbuflen = 0;
            sendUnknownData();
            break;            
         }
      }
      else
      {
        serbuflen = 0;
        return;
      }
    }
}
Example #11
0
int SRF02::getDistance(){	 
	 sendCommand(_deviceId, _mode);
	 delay(READ_DURATION);
     setRegister(_deviceId, RESULT_REGISTER);   	  
	 return readData(_deviceId, 2);      
}
Example #12
0
//Beginning of main(void)
int main(void)
{
	
	


	
				//Initializes variables
				struct holeStruct holeData[MAX_HOLES];
	
				struct dimenssionStruct dimenssion;
	
				struct dimenssionStruct*dimenPtr=&dimenssion;
	
				char label1[50];
	
				char label2[50];
	
				float inputDepth=0;
	
				//Holds input indicating if user wants to run or quit the program	 
				int mainChoice=0;
	
				//This hold the value (as returned by scanf()) indicating number of assignments made
				int validDepth=0;
	
				int soilChoice=0;
	
	
	

				int readResult=0; 
	
				//result from readData function is stored in readResult var.
				readResult=readData(holeData,label1,label2);
	
				
				switch(readResult)
				{
	
					case 0:
					{
		
								
									//If readResult=0, below code is executed
										   
									calcDimen(holeData,dimenPtr);
	
									calcHoleCoord(holeData,dimenPtr);
	
									initGraphics(dimenPtr);
	
									showAllData(holeData,label1,label2,dimenPtr);

									setcolor(WHITE);
									outtextxy(2,2,"Enter a depth in the console to see the soil information at that depth here.");	  
				 
									/*This do..while loop calls the routines inside it 
									as long as user does not decide to quit the program*/
									do{
		
		
		
													mainChoice=displayMainMenu();
		
		
													if(mainChoice==1)
													{
				
																do
																{
																			printf("\nEnter a depth (in meters):");
							
																			fflush(stdin);
							
																			validDepth=scanf("%f",&inputDepth);
							
						
																}while(validDepth==0);
						
							
																inputDepth=fabs(inputDepth);
					
																soilChoice=displaySoilMenu();
					
																processPrint(holeData,inputDepth,label1,label2,dimenPtr,soilChoice,1);
					
						
													}
		
		
			
	
	
	
										}while(mainChoice!=2);
	
	
				
										break;
					}


	
					case 1:
					{
			
										printf("You have chosen to exit the program because data from the file could not be read.\n Press Enter to exit.");
		
										break;
			
					}
					
					default:
					{
							printf("\nUnexpected error occoured in main(void)\n");
							break;
					}
		
	
	
				}

				return readResult;

	
	
}
Example #13
0
/**
 * Main program
 *
 * @param argc number of arguments passed to the program
 * @param argv array of arguments passed to the program
 *
 * @return status
 */
int main (int argc, char** argv)
{
    char optstring[] = "n:t:o:va";
    unsigned int i;
    unsigned char previousBit;
    struct timeval* start;
    int option;
    unsigned int duration = 80;
    unsigned long int samples = 50000;
    unsigned char verbose = 0;
    unsigned char all = 0;
    FILE* output=0;
    BYTE_BUFFER buffer;

    /* reading options */
    opterr=0; /* Pas de message d'erreur automatique */
    while ((option = getopt(argc, argv, optstring)) != -1) {
        switch (option) {
            case 't':
                sscanf(optarg, "%d", &duration);
                break;
            case 'n':
                sscanf(optarg, "%lu", &samples);
                break;
            case 'a':
                all = 1;
                break;
            case 'v':
                verbose = 1;
                break;
            case 'o':
                output = fopen(optarg, "w");
                if (output==0) {
                    fprintf(stderr, "Could not open file %s\n", optarg);
                }
                break;
            default:
                usage(argv);
                return 0;
                break;
        }
    }

    /* Configure the GPIO */
    initIO();

    /* Read the data */
    fprintf(stderr, "Reading data\n");
    buffer = readData(samples, duration);

    /* Analyzing the data */
    fprintf(stderr, "Analyzing\n");
    analyse(buffer, output ? output : stdout, all);

    if (verbose) {
        fprintf(output ? output : stdout, "\n\nRawData\n");
        previousBit=0;
        for(i=0; i<buffer.size; i++) {
           if ((previousBit == 0) && (buffer.data[i] == 1))
               fprintf(output ? output : stdout, "\n");
           fprintf(output ? output : stdout, "%c", buffer.data[i]+'0');
           previousBit = buffer.data[i];
       }
    }

    destroyByteBuffer(buffer);
    return 0 ;
}
Example #14
0
int main(int argc, char** argv){
  int i,j, *NNs;
  double **x,**q, bbtime, brutetime,*dToNNs,divTemp;
  treenode *root;
  struct timeval tvB,tvE;

  printf("**** bbtree **** \n");
  processArgs(argc,argv);
  x = calloc(n,sizeof(double*));
  q = calloc(m,sizeof(double*));
  
  for(i=0;i<n;i++)
    x[i]=calloc(d,sizeof(double));
  for(i=0;i<m;i++)
    q[i]=calloc(d,sizeof(double));
  dToNNs = calloc(k,sizeof(double));
  NNs = calloc(k,sizeof(int));

  readData(x,n,d,datafile);
  readData(q,m,d,queryfile);

  bregdiv div;
  switch(divChoice){
  case USEL2:
    div = l2squared();
    printf("divergence = l_2^2\n");
    break;
  case USEKL:
    div = kl();
    printf("divergence = KL\n");
    break;
  case USEKLD:
    div = dkl();
    printf("divergence = conjugate to KL\n");
    printf("WARNING: this has not been tested thoroughly\n");
    break;
  case USEIS:
    div = is();
    printf("divergence = Itakura-Saito\n");
    printf("WARNING: this has not been tested thoroughly\n");
    break;
  }

  printf("building.....\n");
  gettimeofday(&tvB,NULL);
  root = buildTree(x,n,d,div,bucketSize);
  gettimeofday(&tvE,NULL);
  printf("done... build time: %6.2f \n",timediff(tvB,tvE));
  
  gettimeofday(&tvB,NULL);
  multisearch(root,q,x,div,n,d,m,eps,k,INT_MAX);
  gettimeofday(&tvE,NULL);
  bbtime = timediff(tvB,tvE);
  printf("BBTREE time elapsed = %6.3f \n",bbtime);
  
  
  //Example of how to save & retrieve a bbtree:

  /*writeTree(root,d,"treefile.txt");
  deleteTree(root);
  root = readTree("treefile.txt");

  gettimeofday(&tvB,NULL);
  multisearch(root,q,x,div,n,d,m,eps,0,1);
  gettimeofday(&tvE,NULL);
  bbtime = timediff(tvB,tvE);
  printf("BBTREE time elapsed = %6.3f \n",bbtime);
  */

  
  //brute force
  double curmin;
  int curBest;
  
  gettimeofday(&tvB,NULL);
  for(i=0;i<m;i++){
    for(j=0;j<k;j++){
      dToNNs[j]=HUGE_VAL;
      NNs[j]=-1;
    }
    curmin=HUGE_VAL;
    curBest=-1;
    for(j=0;j<n;j++){
      divTemp = div.div(x[j],q[i],d);
      if(NNs[0]==-1 || divTemp < dToNNs[0]){
	insert(NNs,dToNNs,j,divTemp,k);  
      }
    }
    /*    printf("query %d nns are \n",i);
    for(j=0;j<k;j++)
      printf("%d ",NNs[j]);
      printf("\n"); */
  }
  gettimeofday(&tvE,NULL);
  brutetime = timediff(tvB,tvE);
  printf("BRUTE time elapsed = %6.3f \n",brutetime);
  
  if(isOutfile){
    writeDoubs(2,outfile,bbtime,brutetime);
  }

  for(i=0;i<n;i++)
    free(x[i]);
  for(i=0;i<m;i++)
    free(q[i]);
  free(x);
  free(q);
  free(NNs);
  free(dToNNs);
  deleteTree(root);

  return 0;
}
Example #15
0
uint8_t  readReg(uint8_t reg)
{
  writeCommand(reg);
  return readData();
}
Example #16
0
int main(){
	//set up moves
	Move moves[4] ={{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
	
	//set up hash table
	HashTable *hashTable;
	HashTable *queueTable;
	int tableSize = pow(SIZE, 9) - SIZE + 1;

	int nos[SIZE * SIZE];
	int g[SIZE * SIZE];
	char *nums = (char *)calloc(SIZE * SIZE, sizeof(char));
	//char nums[9] = {'7', '2', '4', '5', '6', '0', '8', '3', '1'};
	nums = readData();
	char *gl = (char *)calloc(SIZE * SIZE, sizeof(char));
	//char gl[9] =  {'2', '4', '1', '7', '8', '6', '5', '0', '3'};
	gl = readData();
	int i;
	//converts char* to int*
	for(i = 0; i < SIZE * SIZE; i++) nos[i] = (int)nums[i] - '0';
	for(i = 0; i < SIZE * SIZE; i++) g[i] = (int)gl[i] - '0';
	goal = (Board *)calloc(1, sizeof(Board));
	insertTiles(goal, g);
	setNumbers(goal);
	start = (Board *)calloc(1, sizeof(Board));
	insertTiles(start, nos);
	setNumbers(start);
	start->depth = 0;
	printf("\nSTART:\n");
	printBoard(start);
	printf("\nGOAL:\n");
	printBoard(goal);
	Queue *queue;
	Board *newBoard;
	int f;
	for (f = 0; f < 5; f++){
		success = 0;
		hashTable = (HashTable *)createHashTable(tableSize);
		queueTable = (HashTable *)createHashTable(tableSize);
		solution = (Board *)calloc(1, sizeof(Board));
		Board *board = (Board *)calloc(1, sizeof(Board));
		board = start;
		switch(f){
			case 0:
				board->f = getH(board);
				break;
			case 1:
				board->f = getHout(board);
				break;
			case 2:
				board->f = getHmanhattan(board);
				break;
			case 3:
				board->f = getHgreat2(board);
				break;
			case 4:
				board->f = getHgreat3(board);
				break;
			default:
				printf("error\n");
		}
		//set up queue
		queue = (Queue *)createQueue();
		int error;
		if((error = insert(queue, board)) == 1){
			printf("failed to insert starting board\n");
			exit(1);
		}
		Node *current;
		//Board *newBoard;
		int m;
		int fVal;
		int tries = 0;
		//iterate through queue until done
		while(!success){	
			current = queue->head;
			if((fVal = lookupBoard(hashTable, current->b)) == -1) {
				if((error = addBoard(hashTable, current->b)) == 1) {
					printf("failed to add board to hashtable\n");
					exit(1);
				}
				//moves
				for(m = 0; m < 4; m++){
					if(!success) {
						if((newBoard = makeBoardOnMove(current, moves[m], f)) != NULL){
							if(newBoard->value == goal->value){
								success = 1;
								solution = newBoard;
							}
							if((fVal = lookupBoard(queueTable, newBoard)) == -1){
								tries++;
								if((error = insert(queue, newBoard)) == 1) {
									printf("failed to insert new board\n");
									exit(1);
								}
								if((error = addBoard(queueTable, newBoard)) == 1) {
									printf("failed to add new Board to queuetable\n");
									exit(1);
								}
							} else if(newBoard->f < fVal) {
								tries++;
								if((error = replace(queue, newBoard)) == 1) {
									printf("failed to replace with new board\n");
									exit(1);
								} 
								error = addBoard(queueTable, newBoard);
							} else {
								free(newBoard);
							}
						}
					}
				}
			}
			pop(queue);
			if(queue->head == NULL)printf("Empty Queue\n");
		}
		//print out results
		printf("\nTRIES:  %d\n", tries);
		printf("COST:  %d\n", solution->depth);
		printf("EST. DIST. START TO GOAL:  %d\n", start->f);
		printf("\nSOLUTION:  ");
		printPath(solution);
		int ql = getQueueLength(queue);
		printf("QUEUE LEN:  %d\n\n", ql);
		freeQueue(queue);
		free(queue);
		free(hashTable);
		free(queueTable);
		hashTable = NULL;
		queueTable = NULL;
		queue = NULL;
	}
	return 1;
}
Example #17
0
/********************************f******************************************/
void graphicsMode(void) {
  writeCommand(RA8875_MWCR0);
  uint8_t temp = readData();
  temp &= ~RA8875_MWCR0_TXTMODE; // bit #7
  writeData(temp);
}
Example #18
0
uint16_t TFTLCD::readRegister(uint16_t addr) {
   writeCommand(addr);
   return readData();
}
Example #19
0
int main(int argc, char **argv)
{
	TSS_RESULT tResult;
	TSS_HTPM hTpm;
	TSS_HKEY hEk;
	TSS_FLAG fEkAttrs;
	int iRc = -1;

#ifdef TSS_LIB_IS_12
	struct option opts[] = {{"revocable", no_argument, NULL, 'r'},
	{"generate-secret", no_argument, NULL, 'g'},
	{"infile", required_argument, NULL, 'i'},
	{"outfile", required_argument, NULL, 'o'},
	};
	UINT32 revDataSz;
	BYTE revokeData[TPM_SHA1BASED_NONCE_LEN];
	BYTE *pRevData;
#endif

	initIntlSys();

#ifdef TSS_LIB_IS_12
	if (genericOptHandler(argc, argv, "rgi:o:", opts, sizeof(opts) / sizeof(struct option),
			      parse, help) != 0)
		goto out;

	//Check commands for command hierarchy
	if (isRevocable) {
		if (needGenerateSecret) {
			if (!outFileSet) {
				logError(_("Please specify an output file\n"));
				goto out;
			}
			if (inFileSet) {
				logError(_("The option -i, --infile is not valid with -g\n"));
				goto out;
			}
		} else if (!inFileSet) {
			logError(_("Please specify -i, --infile or -g, --generate-secret\n"));
			goto out;
		} else if (outFileSet) {
			logError(_("The option -o, --outfile is not valid with -i, --infile"));
			goto out;
		}
	}
	logDebug("Input file name: %s\n", in_filename);
	logDebug("Output file name: %s\n", out_filename);

	if (inFileSet) {
		pRevData = revokeData;
		revDataSz = sizeof(revokeData);
		if (readData(revDataSz, &pRevData))
			goto out;
	} else if (outFileSet) {
		FILE *outfile = fopen(out_filename, "w");
		if (!outfile) {
			iRc = -1;
			logError(_("Unable to open output file: %s\n"), out_filename);
			goto out;
		}
		fclose(outfile);

		//TPM should generate the revoke data
		revDataSz = 0;
		pRevData = NULL;
	}
#else
	if (genericOptHandler(argc, argv, NULL, NULL, 0, NULL, NULL) != 0){
		logError(_("See man pages for details.\n"));
		goto out;
	}
#endif

	if (contextCreate(&hContext) != TSS_SUCCESS)
		goto out;

	if (contextConnect(hContext) != TSS_SUCCESS)
		goto out_close;

	if (contextGetTpm(hContext, &hTpm) != TSS_SUCCESS)
		goto out_close;

	//Initialize EK attributes here
	fEkAttrs = TSS_KEY_SIZE_2048 | TSS_KEY_TYPE_LEGACY;
	if (contextCreateObject(hContext, TSS_OBJECT_TYPE_RSAKEY, fEkAttrs, &hEk) != TSS_SUCCESS)
		goto out_close;

#ifdef TSS_LIB_IS_12
	if (isRevocable){
		tResult = tpmCreateRevEk(hTpm, hEk, NULL, &revDataSz, &pRevData);
		if (tResult != TSS_SUCCESS)
			goto out_close;
		//Writes the generated secret into the output file
		if (outFileSet) {
			if (writeData(revDataSz, pRevData)) {
				logError(_("Creating revocable EK succeeded, but writing the EK "
					   "revoke authorization to disk failed.\nPrinting the "
					   "revoke authorization instead:\n"));
				logHex(revDataSz, pRevData);
				logError(_("You should record this data, as its the authorization "
					   "you'll need to revoke your EK!\n"));
				goto out_close;
			}
		}
	} else
#endif
		tResult = tpmCreateEk(hTpm, hEk, NULL);
	if (tResult != TSS_SUCCESS)
		goto out_close;

	iRc = 0;
	logSuccess(argv[0]);

      out_close:
	contextClose(hContext);

      out:
	return iRc;
}
/* Find Num of word given directory */
int countWords(char *fileDir)
{

	int boyutX,boyutY; /* max satir boyutulari */
	char **arr; /* grekli array*/

	int i=0,j=0; /* gerekli degiskenler. */
	int lineNum;
	int total=0;

	/*recursively find file inside file taking on internet */
    	struct stat stDirInf;
    	struct dirent * stAllFiles;
    	DIR * stDirIn;
    	pid_t  pid;
    	char szFullName[MAXPATHLEN]; /* dosyalar icin */
    	char szDirectory[MAXPATHLEN];
  	struct stat stFileInf;
    	/*directory asil directory e kopyalanir*/
    	strncpy( szDirectory,fileDir, MAXPATHLEN - 1 );

    	/* Error Handling */
    	if (lstat( szDirectory, &stDirInf) < 0)
    	{
        	perror (szDirectory);
        	return;
    	}

    	if (!S_ISDIR(stDirInf.st_mode))
        	return;
    	if ((stDirIn = opendir( szDirectory)) == NULL) /* klasor open */
    	{
        	perror( szDirectory );
        	return;
    	}

    /* klasorun icerigi okunur */
    while (( stAllFiles = readdir(stDirIn)) != NULL)
    {
	/*Dosya name yeni array a alinir*/
        sprintf(szFullName, "%s/%s", szDirectory, stAllFiles -> d_name );

        if (lstat(szFullName, &stFileInf) < 0)
           perror ( szFullName );

        /* klasor mu diye bakilir, klasor ise onunda icine girilir. */
        if (S_ISDIR(stFileInf.st_mode))
        {
            if ((strcmp(stAllFiles->d_name , "..")) && (strcmp(stAllFiles->d_name , ".")))
            {
                /* recursive olarak ic icedosyalara girilebilir. */
		 //total=*totalWords;
		/*directory icine girdigimiz icin file num ve directory num arttirilir */
		 ++totalDirectory;
		 ++totalFile;
                 countWords(szFullName);
		 
            }
        }
        else /* dosya ise */
        {
	    /*file num yine arttilir*/
	    ++totalFile;
	   
            pid = fork(); /* proses oluşturulur */

            /* Error Handiling */
            if(pid == -1)
            {
                perror("Error: Unexpected things fork \n");
                exit(1);
            }

            /* pid 0 ise child dir. */
            if (pid == 0) 
            {
                
		/*child process sayisi arttirilir*/
          	 *totalChildProcess=*totalChildProcess+1;
		

		boyutX= getLineNum(szFullName);
		boyutY = getBoyut(szFullName);
    		arr=Make2DintArray(boyutX+1,boyutY+1);
			/*dosya okunur */
    		readData(szFullName,arr,boyutX);
		/*total words sayisi bulunup toplama a eklenir*/
		total=countWordsInArray(arr,boyutX);
		*totalWords=*totalWords+total;

		//printf(" %s inside total words %d\n",szFullName,total);
		printf("pid:%ld , %s  inside total words %d\n",(long)getpid(),szFullName,total);
		
		/*aldigimiz yer geri verilir*/
 
		freeArray(arr,boyutX+1);	
                exit(1); /* exit ile prosesler oldurulur. */
            }
            else
            {
		//totalWords+=total;
                wait(NULL);/* parent child lari bekler. */
            }
        }

    }  /* end while */
    /* Dosyalar kapanir. */
    while ((closedir(stDirIn) == -1) && (errno == EINTR)) ;
 

    return total;
}
Example #21
0
void RTCMemStore::getLastDweet(char *buf) {
  readData();
  strcpy(buf, rtcData->lastDweetCreated);
  updateData();
}
Example #22
0
/** TIA Reader
  * @ingroup TIA
*/
int ImageBase::readTIA(int select_img,bool isStack)
{
    TIAhead * header = new TIAhead;

    xmippFREAD(&header->endianess, sizeof(short int), 1, fimg, swap );

    // Set Endianess
    if (header->endianess == 18761)
        swap = 0;
    else
        swap = 1;
    if (IsBigEndian())
        swap = !swap;

    xmippFREAD(&header->SeriesID, sizeof(short int), 1, fimg, swap );
    xmippFREAD(&header->SeriesVersion, sizeof(short int), 1, fimg, swap);
    xmippFREAD(&header->DATA_TYPE_ID, sizeof(int), 1, fimg, swap);
    xmippFREAD(&header->TagTypeID, sizeof(int), 1, fimg, swap );
    xmippFREAD(&header->TotalNumberElements, sizeof(int), 1, fimg, swap );
    xmippFREAD(&header->NUMBER_IMAGES, sizeof(int), 1, fimg, swap );
    xmippFREAD(&header->OFFSET_ARRAY_OFFSET, sizeof(int), 1, fimg, swap );
    xmippFREAD(&header->numberdimensions, sizeof(int), 1, fimg, swap );

    // Check data type
    if (header->DATA_TYPE_ID != 16674)
        REPORT_ERROR(ERR_TYPE_INCORRECT, "ERROR: readTIA only processes images in real space");

    fseek(fimg, header->OFFSET_ARRAY_OFFSET, SEEK_SET);
    header->pDATA_OFFSET = (int *) askMemory(header->NUMBER_IMAGES * sizeof(int));
    xmippFREAD(header->pDATA_OFFSET, sizeof(int), header->NUMBER_IMAGES, fimg, swap);

    TIAdataHead* dataHeaders = new TIAdataHead [header->NUMBER_IMAGES];

    // Read all the image headers
    for (int i = 0; i < header->NUMBER_IMAGES; i++)
    {
        fseek(fimg, header->pDATA_OFFSET[i], SEEK_SET);
        xmippFREAD(&(dataHeaders[i].CalibrationOffsetX), sizeof(double), 1, fimg, swap);
        xmippFREAD(&dataHeaders[i].PIXEL_WIDTH, sizeof(double), 1, fimg, swap);
        xmippFREAD(&dataHeaders[i].CalibrationElementX, sizeof(int), 1, fimg, swap);
        xmippFREAD(&dataHeaders[i].CalibrationOffsetY, sizeof(double), 1, fimg, swap);
        xmippFREAD(&dataHeaders[i].PIXEL_HEIGHT, sizeof(double), 1, fimg, swap);
        xmippFREAD(&dataHeaders[i].CalibrationElementY, sizeof(int), 1, fimg, swap);
        xmippFREAD(&dataHeaders[i].DATA_TYPE, sizeof(short int), 1, fimg, swap);
        xmippFREAD(&dataHeaders[i].IMAGE_WIDTH, sizeof(int), 1, fimg, swap);
        xmippFREAD(&dataHeaders[i].IMAGE_HEIGHT, sizeof(int), 1, fimg, swap);
    }

    int _xDim,_yDim;
    size_t _nDim;

    size_t   imgStart = IMG_INDEX(select_img);
    size_t   imgEnd = (select_img != ALL_IMAGES) ? imgStart + 1 : header->NUMBER_IMAGES;

    if (select_img >  header->NUMBER_IMAGES)
        REPORT_ERROR(ERR_INDEX_OUTOFBOUNDS, formatString("readTIA: Image number %lu exceeds stack size %lu", select_img, header->NUMBER_IMAGES));
    else if (select_img == ALL_IMAGES)
    {
        for (int i = 1; i < header->NUMBER_IMAGES; i++)    // Check images dimensions. Need to be the same
        {
            if (dataHeaders[0].IMAGE_HEIGHT != dataHeaders[i].IMAGE_HEIGHT || \
                dataHeaders[0].IMAGE_WIDTH != dataHeaders[i].IMAGE_WIDTH  || \
                dataHeaders[0].DATA_TYPE != dataHeaders[i].DATA_TYPE)
                REPORT_ERROR(ERR_IMG_NOREAD, "readTIA: images in TIA file with different dimensions and data types are not supported");
        }
        _xDim = dataHeaders[0].IMAGE_WIDTH;
        _yDim = dataHeaders[0].IMAGE_HEIGHT;
        _nDim = (size_t) header->NUMBER_IMAGES;
    }
    else
    {
        _xDim = dataHeaders[imgStart].IMAGE_WIDTH;
        _yDim = dataHeaders[imgStart].IMAGE_HEIGHT;
        _nDim = 1;
    }

    // Map the parameters
    setDimensions(_xDim, _yDim, 1, _nDim);

    DataType datatype;
    //    dataHeaders[0].isSigned = false;
    int tiaDT;
    tiaDT = dataHeaders[imgStart].DATA_TYPE;
    offset = header->pDATA_OFFSET[imgStart] + TIAdataSIZE;

    switch ( tiaDT )
    {
    case 1:
        datatype = DT_UChar;
        break;
    case 2:
        datatype = DT_UShort;
        //        datatype = DT_Short;
        break;
    case 3:
        datatype = DT_UInt;
        break;
    case 4:
        datatype = DT_SChar;
        break;
    case 5:
        datatype = DT_Short;
        //        dataHeaders[0].isSigned = true;
        break;
    case 6:
        datatype = DT_Int;
        break;
    case 7:
        datatype = DT_Float;
        break;
    case 8:
        datatype = DT_Double;
        break;
    case 9:
        datatype = DT_CFloat;
        break;
    case 10:
        datatype = DT_CDouble;
        break;
    default:
        datatype = DT_Unknown;
        break;
    }

    MDMainHeader.setValue(MDL_SAMPLINGRATE_X,(double)dataHeaders[0].PIXEL_WIDTH);
    MDMainHeader.setValue(MDL_SAMPLINGRATE_Y,(double)dataHeaders[0].PIXEL_HEIGHT);
    MDMainHeader.setValue(MDL_DATATYPE,(int)datatype);

    if (dataMode == HEADER || (dataMode == _HEADER_ALL && _nDim > 1)) // Stop reading if not necessary
    {
        delete header;
        return 0;
    }

    MD.clear();
    MD.resize(imgEnd - imgStart,MDL::emptyHeader);
    double aux;
    for ( size_t i = 0; i < imgEnd - imgStart; ++i )
    {
        if (dataMode == _HEADER_ALL || dataMode == _DATA_ALL)
        {
            if(MDMainHeader.getValue(MDL_SAMPLINGRATE_X,aux))
            {
                MD[i].setValue(MDL_SHIFT_X, dataHeaders[i].CalibrationOffsetX/aux);
                aux = ROUND(dataHeaders[i].CalibrationElementX - \
                            dataHeaders[i].CalibrationOffsetX/aux - _xDim/2);
                MD[i].setValue(MDL_ORIGIN_X, aux);
            }
            if(MDMainHeader.getValue(MDL_SAMPLINGRATE_Y,aux))
            {
                MD[i].setValue(MDL_SHIFT_Y, dataHeaders[i].CalibrationOffsetY/aux);
                aux = ROUND(dataHeaders[i].CalibrationElementY - \
                            dataHeaders[i].CalibrationOffsetY/aux -_yDim/2);
                MD[i].setValue(MDL_ORIGIN_Y, aux);
            }
        }
    }

    delete header;

    if( dataMode < DATA )
        return 0;

    size_t pad = TIAdataSIZE;
    readData(fimg, select_img, datatype, pad);

    return(0);
}
Example #23
0
void RTCMemStore::setIterations(uint8_t i) {
  readData();
  rtcData->interations = i;
  updateData();
}
Example #24
0
qint64 AudioRingBuffer::readSamples(int16_t* destination, qint64 maxSamples) {
    return readData((char*) destination, maxSamples * sizeof(int16_t));
}
Example #25
0
void RTCMemStore::addAverageValue(double val, int weight) {
  readData();
  for (int i=0; i < weight; i++) rtcData->avg1.addValue(val);
  updateData();
}
Example #26
0
int main() {
    srand((unsigned)time(NULL));
    const float alpha = 0.15;
    const int I = 5;
    const int J = 4;
    const int K = 3;

    int rnd;
    int goal;
    string line;
    float input[I];
    float t[K] = {0.0, 0.0, 0.0};
    float maxval[4];
    float minval[4];
    char *inp;
    int *number;
    number = (int *)calloc(2, sizeof(int));
    char **nums;
    nums = (char **)calloc(2, sizeof(char *));

    inp = readData();
    int i = 0;
    nums[i] = strtok(inp, " ");
    while (i < 2) {
        //printf("token[%d]: %s\n", i, nums[i]);
        i++;
        nums[i] = strtok(NULL, " ");
    }
    // converts raw data to a string of characters negating the spaces.
    for(int n = 0; n < 2; n++) number[n] = atoi(nums[n]);
    //printf("*\n");
    //for(int n = 0; n < 2; n++) printf("token[%d]: %d\n", n, number[n]);
    int items = number[0];
    int elems = number[1];

    float data[items][elems];
    float rawdata[items][elems];
    if(SUBMIT) {
        //read in data set
        for(int l = 0; l < items; l++) {
            inp = readData();
            i = 0;
            nums[i] = strtok(inp, " ");
            while (i < elems) {
                //printf("%s  ", nums[i]);
                i++;
                nums[i] = strtok(NULL, " ");
            }
            printf("\n");
            for(int n = 0; n < elems; n++) rawdata[l][n] = atof(nums[n]);
        }

        /*cout << "rawdata: ";
        for(int r = 0; r < items; r++){
        	for(int c = 0; c < elems - 1; c++){
        		cout << rawdata[r][c] << " ";
        	}
        	cout << endl;
        }*/
    } else {
        ifstream in("irisClean.dat");
        for(int i = 0; i < items; i++) {
            in >> rawdata[i][0] >> rawdata[i][1] >> rawdata[i][2] >> rawdata[i][3] >> rawdata[i][4];
            //cout << "reading" << i << ": " << rawdata[i][0] << " " << rawdata[i][1] << " " << rawdata[i][2] << " " << rawdata[i][3] << " | " << rawdata[i][4] << endl;
        }
        in.close();
    }

//normalizeData
    for(int c = 0; c < elems - 1; c++) {
        maxval[c] = -10000.0;
        minval[c] = 10000.0;
        for(int r = 0; r < items; r++) {
            if(rawdata[r][c] > maxval[c]) maxval[c] = rawdata[r][c];
            if(rawdata[r][c] < minval[c]) minval[c] = rawdata[r][c];
        }
        //cout << minval[c] << " : " << maxval[c] << endl;
    }
    for(int c = 0; c < elems -1; c++) {
        //cout << "data ";
        for(int r = 0; r < items; r++) {
            data[r][c] = (rawdata[r][c] - minval[c]) / (maxval[c] - minval[c]);
            //cout << data[r][c] << " ";
        }
        //cout << endl;
    }
    for(int r = 0; r < items; r++) data[r][4] = rawdata[r][4];

//set up weights
    Matrix *v = new Matrix(J, I);
    for(int j = 0; j < J; j++) v->m[0][j] = 0.0;
    Matrix *w = new Matrix(K, J);
    Matrix *tempMatrix;
    Matrix *tempMatrix2;
    if(SHOW_WEIGHT) {
        cout << "w" << endl;
        w->print();
        cout << "v" << endl;
        v->print();
    }
    for(int ev = 0; ev < ITERATIONS; ev++) {

        rnd = rand() % items;
        input[0] = BIAS;
        for(int i = 0; i < elems - 1; i++) {
            input[i + 1] = data[rnd][i];
        }
        goal = (int)data[rnd][elems - 1];
        for(int k = 0; k < K; k++) t[k] = 0.0;
        t[goal] = 1.0;
        Matrix *x = new Matrix(input, I);
        if(SHOW_PROG)cout << "x" << endl;
        if(SHOW_PROG)x->print();
        Matrix *g = new Matrix(x->dotProduct(v));
        if(SHOW_PROG)cout << "g" << endl;
        if(SHOW_PROG)g->print();
        Matrix *a = g->s();
        a->m[0][0] = BIAS;
        if(SHOW_PROG)cout << "a" << endl;
        if(SHOW_PROG)a->print();
        Matrix *h = new Matrix(a->dotProduct(w));
        if(SHOW_PROG)cout << "h" << endl;
        if(SHOW_PROG)h->print();
        Matrix *y = h->s();
        if(SHOW_PROG)cout << "y" << endl;
        if(SHOW_PROG)y->print();
        if(SHOW_PROG)cout << "t" << endl;
        if(SHOW_PROG)for(int k = 0; k < K; k++)cout << t[k] << endl;
        if(SHOW_PROG)cout << "\nBACK" << endl;
        //back
        //calculate deltaY
        Matrix *deltaY = new Matrix(y);
        for(int k = 0; k < K; k++) {
            deltaY->m[0][k] = (t[k] - y->m[0][k]) * y->m[0][k] * (1.0 - y->m[0][k]);
            //deltaY->m[0][k] = (t[k] - y->m[0][k]);
        }
        if(SHOW_PROG)cout << "y" << endl;
        if(SHOW_PROG)y->print();
        if(SHOW_PROG)cout << "deltaY" << endl;
        if(SHOW_PROG)deltaY->print();

        //calculate deltaA
        Matrix *deltaA = new Matrix(a);
        //delete tempMatrix;
        tempMatrix = new Matrix(a);
        tempMatrix = deltaY->dotProduct(w->flip());
        if(SHOW_PROG)cout << "tempMatrix - deltaA" << endl;
        if(SHOW_PROG)tempMatrix->print();
        for(int j = 0; j < J; j++) {
            deltaA->m[0][j] = (a->m[0][j] * (1 - a->m[0][j])) * tempMatrix->m[0][j];
            //deltaA->m[0][j] = tempMatrix->m[0][j];
        }
        //deltaA->m[0][0] = 0.0;
        if(SHOW_PROG)cout << "deltaA" << endl;
        if(SHOW_PROG)deltaA->print();

        //adjust w
        delete tempMatrix2;
        tempMatrix2 = new Matrix(w);
        tempMatrix2 = deltaY->flip()->dotProduct(a->flip());
        delete tempMatrix;
        tempMatrix = new Matrix(w);
        tempMatrix = tempMatrix2->mult(alpha);
        if(SHOW_PROG)cout << "tempMatrix - w" << endl;
        if(SHOW_PROG)tempMatrix->print();
        delete tempMatrix2;
        tempMatrix2 = new Matrix(w);
        tempMatrix2 = w->add(tempMatrix);
        //w = w->add(tempMatrix);
        delete w;
        w = new Matrix(K, J);
        for(int r = 0 ; r < tempMatrix2->height; r++)
            for(int c = 0; c < tempMatrix2->width; c++)
                w->m[c][r] = tempMatrix2->m[c][r];
        //adjust v
        deltaA->m[0][0] = 0.0;
        delete tempMatrix2;
        tempMatrix2 = new Matrix(v);
        tempMatrix2 = deltaA->flip()->dotProduct(x->flip());
        delete tempMatrix;
        tempMatrix = new Matrix(v);
        tempMatrix = tempMatrix2->mult(alpha);
        if(SHOW_PROG)cout << "tempMatrix - v" << endl;
        if(SHOW_PROG)tempMatrix->print();
        delete tempMatrix2;
        tempMatrix2 = new Matrix(v);
        tempMatrix2 = v->add(tempMatrix);
        //v = v->add(tempMatrix);
        delete v;
        v = new Matrix(J, I);
        for(int r = 0 ; r < tempMatrix2->height; r++)
            for(int c = 0; c < tempMatrix2->width; c++)
                v->m[c][r] = tempMatrix2->m[c][r];
        delete x;
        delete g;
        delete a;
        delete h;
        delete y;
        delete deltaA;
        delete deltaY;
        delete tempMatrix;
    }
    //testing
    int max;
    int success = 0;
    if(SUBMIT) {
        inp = readData();

        // converts raw data to a string of characters negating the spaces.
        number[0] = atoi(inp);
        //printf("*\n");
        printf("token[0]: %d\n", number[0]);
        items = number[0];
        elems = elems - 1; //number[1];
        cout << items << " " << elems << endl;
    }
    float tdata[items][elems];
    float testdata[items][elems];
    if(SUBMIT) {
        //read in data set
        for(int l = 0; l < items; l++) {
            inp = readData();
            i = 0;
            nums[i] = strtok(inp, " ");
            while (i < elems) {
                //printf("%s  ",nums[i]);
                i++;
                nums[i] = strtok(NULL, " ");
            }
            //printf("\n");
            for(int n = 0; n < elems; n++) testdata[l][n] = atof(nums[n]);
        }
        for(int r = 0; r < items; r++) {
            cout << r << "testdata{ ";
            for(int c = 0; c < elems; c++) {
                cout << testdata[r][c] << " " ;
            }
            cout << "}" << endl;
        }
    } else {
        for(int r = 0; r < items; r++) {
            //cout << r << "testdata{ ";
            for(int c = 0; c < elems; c++) {
                testdata[r][c] = rawdata[r][c];
                //cout << testdata[r][c] << " " ;
            }
            //cout << "}" << endl;
        }
    }
    //normalizeTestData
    /*for(int c = 0; c < elems; c++){
    	cout << minval[c] << " : " << maxval[c] << endl;
    }*/
    for(int r = 0; r < items; r++) {
        for(int c = 0; c < elems; c++) {
            tdata[r][c] = (testdata[r][c] - minval[c]) / (maxval[c] - minval[c]);
        }
    }
    success = 0;
    int count = 0;
    for(int ds = 0; ds < items; ds++) {
        if(!SUBMIT)goal = rawdata[ds][elems - 1];
        input[0] = BIAS;
        for(int i = 0; i < elems; i++) {
            input[i + 1] = tdata[ds][i];
        }
        cout << "input " << ds << ": " << input[0] << " " << input[1] << " " << input[2] << " " << input[3] << " " << input[4] << endl;
        Matrix *x = new Matrix(input, I);
        if(SHOW_PROG)cout << "x" << endl;
        if(SHOW_PROG)x->print();
        Matrix *g = new Matrix(x->dotProduct(v));
        if(SHOW_PROG)cout << "g" << endl;
        if(SHOW_PROG)g->print();
        Matrix *a = g->s();
        a->m[0][0] = BIAS;
        if(SHOW_PROG)cout << "a" << endl;
        if(SHOW_PROG)a->print();
        Matrix *h = new Matrix(a->dotProduct(w));
        if(SHOW_PROG)cout << "h" << endl;
        if(SHOW_PROG)h->print();
        Matrix *y = h->s();
        if(SHOW_PROG)cout << "y" << endl;
        if(SHOW_PROG)y->print();
        if(SHOW_PROG)cout << "t" << endl;
        if(SHOW_PROG)for(int k = 0; k < K; k++)cout << t[k] << endl;
        if(SHOW_PROG)cout << "\nBACK" << endl;
        max = 0;
        float maxScore = 0;
        if(SHOW_TEST)cout << y->m[0][0] << " : "  << y->m[0][1] << " : " << y->m[0][2] << " || ";
        cout << "output: " << y->m[0][0] << " : "  << y->m[0][1] << " : " << y->m[0][2] << endl;
        for(int k = 0; k < K; k++) {
            if(y->m[0][k] > maxScore) {
                maxScore = y->m[0][k];
                max = k;
            }
        }
        delete x;
        delete g;
        delete a;
        delete y;
        if(!SUBMIT) {
            if(goal == max) success++;
        }
        if(SHOW_TEST)cout << "TEST(" << max << ")  GOAL:" << goal << endl;
        if(SUBMIT)cout << "TEST(" << count << "): " << max << endl;
        count++;
    }
    if(SHOW_TEST)cout << "success " << success << " out of " << count << " or " << 100 * (float)success / (float)count << "%" << endl;
    if(SHOW_WEIGHT) {
        cout << "\nw" << endl;
        w->print();
        cout << "v" << endl;
        v->print();
    }
}
Example #27
0
void RTCMemStore::addMillis(uint32_t ms) {
  readData();
  rtcData->millisStartIteration += ms;
  updateData();
}
Example #28
0
/**
 * Read a 512 byte block from an SD card device.
 *
 * \param[in] block Logical block to be read.
 * \param[out] dst Pointer to the location that will receive the data.

 * \return The value one, true, is returned for success and
 * the value zero, false, is returned for failure.
 */
uint8_t Sd2Card::readBlock(uint32_t block, uint8_t* dst) {
  return readData(block, 0, 512, dst);
}
Example #29
0
uint32_t RTCMemStore::getGenData(int idx) {
  readData();
  uint32_t x = rtcData->genData[idx];
  updateData();
  return x;
}
Example #30
0
// ---------------------------------- main() --------------------------------
int main(int argc, char *argv[]) {
	if (!parseArgs(argc, argv)) {
		if (errmsg[0] != '\0')
			printf("%s\n",errmsg);
		else
			printf("|status: ERROR: No command-line arguments, or error in arguments\n\nVersion: %s\n%s|\n",
			version,Usage);
		return 1;
	}
	
	if (!readData()) {
		if (errmsg[0] != '\0')
			printf("|status: ERROR: %s|\n", errmsg);
		else
			printf("|status: ERROR: Error reading mystore.dat\n\n%s|\n", Usage);
		return 1;
	}
	
	if (command == ADD && !add(argv[2],argv[3])) {
		if (errmsg[0] != '\0')
			printf("|status: ERROR: %s|\n", errmsg);
		else
			printf("|status: ERROR: Failure to add new item|\n");
		return 1;
	}
	
	if (command == STAT) {
		stat();
	}
	
	if (command == DISPLAY && !display(argv[2])) {
		if (errmsg[0] != '\0')
			printf("|status: ERROR: %s|\n", errmsg);
		else
			printf("|status: ERROR: Cannot display %s|\n",argv[2]);
		return 1;
	}
	
	if (command == DELETE && !delete(argv[2])) {
		if (errmsg[0] != '\0')
			printf("|status: ERROR: %s|\n", errmsg);
		else
			printf("|status: ERROR: Cannot delete %s|\n", argv[2]);
		return 1;
	}
	
	if (command == EDIT && !edit(argv[2])) {
		if (errmsg[0] != '\0')
			printf("|status: ERROR: %s|\n", errmsg);
		else
			printf("|status: ERROR: cannot edit %s|\n",argv[2]);
		return 1;
	}
	
	if (rewrite)
		if (!writeData()) {
			if (errmsg[0] != '\0')
				printf("|status: ERROR: %s|\n", errmsg);
			else
				printf("|status: ERROR: Could not write the data, file may be destroyed|\n");
			return 1;
		}
	
	
	return 0;
}