Exemple #1
0
int main (int argc, char **argv)
{
	struct sembuf buf = {0, 0, 0}; //declaration buf structure
	
	int semid = createSem(PATH, PROJECTID, SEMVALUE, IPC_CREAT | WRITEREADATT); //create semaphore

	switch(fork())
	{
		case -1: //if fork error
			perror(FORKERROR);
			exit(1);
			break;
		case 0: 
			printData(semid); //print process id and sem data
			buf.sem_op = CLOSE; // close semaphore
			if(semop(semid, &buf, 1) == -1) // send cmd
			{
				perror(SEMOPERROR);
				exit(EXIT_FAILURE);
			}
			criticalSection(); // do sth
			printData(semid); //print process id and sem data
			buf.sem_op = OPEN; // open semaphore
			if(semop(semid, &buf, 1) == -1) // send cmd
			{
				perror(SEMOPERROR);
				exit(EXIT_FAILURE);
			}
			break;
		default:
			printData(semid); //print process id and sem data
			buf.sem_op = CLOSE; // close semaphore
			if(semop(semid, &buf, 1) == -1) // send cmd
			{
				perror(SEMOPERROR);
				exit(EXIT_FAILURE);
			}
			criticalSection();  // do sth
			printData(semid); //print process id and sem data
			buf.sem_op = OPEN; // open semaphore
			if(semop(semid, &buf, 1) == -1) // send cmd
			{
				perror(SEMOPERROR);
				exit(EXIT_FAILURE);
			}
			printf(PARENTEND); //end of parent
			printData(semid); //print process id and sem data
			if(wait(NULL) == -1) // wait for children
			{
				perror(WAITERROR);
				exit(EXIT_FAILURE);
			}
			printf(SEMDELETE, semid); 
			deleteSem(semid); // delete sem
			
			break;
	}
	
	return 0;
}
/* Print the computed matrix at the given time step all processes
 * should send their local data to process rank 0 which is responsible
 * for printing */
void write_frame(int time) {
  // sends data row by row
  if (rank != 0) {
    for (int i=0; i<nyl; i++)
      MPI_Send(&u_curr[i+1][1], nxl, MPI_DOUBLE, 0, DATAPASS, comm);
  } else {
    printf("\n-------------------- time step:%d --------------------\n", time);
    for (int i=0; i < NPROCSY; i++) {
      int numRows = countRowForProc(i*NPROCSX);

      for (int j=0; j < numRows; j++) {
        for (int k=0; k < NPROCSX; k++) {
          int curr_rank = i*NPROCSX + k;

          if (curr_rank!=0) {
            int senderx = firstColForProc(curr_rank);
            int sendery = firstRowForProc(curr_rank);
            int senderNxl = countColForProc(curr_rank);

            MPI_Recv(recvbuf, senderNxl, MPI_DOUBLE, curr_rank, DATAPASS, comm, MPI_STATUS_IGNORE);
            printData(time, senderx, senderNxl, sendery+j, recvbuf);
          } else {
            printData(time, firstCol, nxl, firstRow+j, &u_curr[j+1][1]);
          }
        }
        printf("\n");
      }
    }
  } 
}
Exemple #3
0
int main() {
    srand((unsigned) time(NULL));

    buf = initBuf(BUFSIZE, BLKSIZE);

    initData();

    //输出R的内容
    //printData(R_START);
    //输出S的内容
    //printData(S_START);

    //找到R.A = 40
    int addr_find_R_A = findfirst(R_START, 40);
    printData(addr_find_R_A);

    //找到S.C = 60
    int addr_find_S_C = findfirst(S_START, 60);
    printData(addr_find_S_C);


    //R.A投影
    int projection_R_A = projection(R_START);
    printData(projection_R_A);
    printf("NUM = %d\n", BLKNUM);
    //R.A连接S.C
    int r_join_s = join(R_START, S_START);
    //printData(r_join_s);

    //printf("%d\n", BLKNUM);
    return 0;
}
Exemple #4
0
void 
PrintVisitor::visit(DerGtime& derGtime, ndnboost::any param)
{
  const string& indent = ndnboost::any_cast<const string&>(param);
  
  printData(derGtime.getHeader(), indent);
  printData(derGtime.getPayload(), indent + "   ");
}
Exemple #5
0
void 
PrintVisitor::visit(DerBitString& derBStr, ndnboost::any param)
{
  const string& indent = ndnboost::any_cast<const string&>(param);
      
  printData(derBStr.getHeader(), indent);
  const vector<uint8_t>& payload = derBStr.getPayload();
  cout << indent << "   " << " " << hex << setw(2) << setfill('0') << (int)(uint8_t)payload[0] << endl;
  printData(payload, indent + "   ", 1);
}
Exemple #6
0
void sort_test ( void (*q) (int data[], int left, int right), int dataSet[], int dataLen )
{
	if( q == quicksort )
		printf( "quicksort\n" );
	else if(q == mergesort)
		printf( "mergesort\n " );

	printf( "Original data:\t" );
	printData( dataSet, dataLen );

	q( dataSet, 0, dataLen-1 );

	printf( " Sorted data:\t" );
	printData( dataSet, dataLen );
}
Exemple #7
0
int main()
{
	char selection[1];
	int i, dataSize;
	while(1)
	{
		printf("\n1. Sort data by the float value & print high to low\n");
		printf("2. Sort data by the float value & print low to high\n");
		printf("3. Sort data by the int value & print high to low\n");
		printf("4. Sort data by the int value & print low to high\n");
		printf("5. Exit\n");
		scanf("%s", selection);
		i = atoi(selection);
		if (i==1)
		{
			dataSize = copyToArray();
			sortByFloat(dataSize, i);
			printData(dataSize);
		}
		else if (i==2)
		{
			copyToArray();
			sortByFloat(dataSize, i);
			printData(dataSize);
		}
		else if (i==3)
		{
			copyToArray();
			sortByInt(dataSize, i);
			printData(dataSize);
		}
		else if (i==4)
		{
			copyToArray();
			sortByInt(dataSize, i);
			printData(dataSize);
		}
		else if (i==5)
		{
			break;
		}
		else
		{
			printf("Invalid selection (1-5)");
		}
	};
	return 0;
}
Exemple #8
0
int main(void) {
  date today = {21,4,2016};
  int n = 0;
  char buffer[MAX_BUFFER_SIZE];
  int rtn;

  printf("How many teachers to introduce?\n");
  do {
    fgets(buffer, MAX_BUFFER_SIZE, stdin);
    rtn = sscanf(buffer, "%d",&n);
  } while(rtn != 1);

  teacher *t = (teacher *) malloc(n*sizeof(teacher));
  if(t == NULL) {
    printf("Not enough memory\n");
    exit(1);
  }
  for(int i=0; i < n; i++) {
    readTeacher(&t[i], today);
  }
  orderByAge(t, n);
  printData(t, n);

  free(t);
  return 0;
}
Exemple #9
0
int main() {
    std::unordered_map<std::string, std::vector<int>> data;
    std::vector<std::string> fileAsAnArray; // For testing
    // Read from file and build a mapping of words to sets of line numbers
    std::ifstream fileIn;
    fileIn.open("input.txt");
    std::string currWord;
    int i = 0;
    while (fileIn >> currWord) {
        data[currWord].push_back(i++);
        fileAsAnArray.push_back(currWord); // For testing
    }
    fileIn.close();
    printData(data);
    // For each word, test how close it is to every other word
    for (auto it1 = data.begin(); it1 != data.end(); ++it1) {
        for (auto it2 = data.begin(); it2 != data.end(); ++it2) {
            std::cout << "Distance between " << it1->first << " and " << it2->first << " is ";
            auto d1 = findDistanceBetween(it1->first, it2->first, data);
            auto d2 = testFindDistanceBetween(it1->first, it2->first,
                                              fileAsAnArray);
            if (d1 != d2) { assert(0); }
            std::cout << d1 << std::endl;
        }
    }
    return 0;
}
Exemple #10
0
int main()
{
  struct Employee emps[SIZE] = { { 98401, 10.60 },
                             { 526488, 9.75 },
                             { 765349, 10.50 },
                             { 34645, 12.25 },
                             { 127615, 8.35 } };

  for (int i = 0; i < SIZE; ++i){
    emps[i].hours = getHours(emps[i]);
    emps[i].overtime = getOvertimeHours(emps[i]);  /* Calculate total amount of overtime hours */
    emps[i].overtimePay = getOvertimePay(emps[i]);  /* Calculate total amount of overtime pay, if necessary */
    emps[i].gross = getGross(emps[i]); /* Calculate gross pay */
  }

  printData(emps);

  /* Calculate the total gross pay per employee 
  for (int i = 0; i < SIZE; i++)
  {
    hours[i] = getHours(clockNumber[i]);
    overtime[i] = getOvertimeHours(hours[i]);  /* Calculate total amount of overtime hours 
    overtimePay[i] = getOvertimePay(overtime[i], wage[i]);  /* Calculate total amount of overtime pay, if necessary 
    gross[i] = getGross(hours[i], overtimePay[i], wage[i]); /* Calculate gross pay 
  }

  printData(clockNumber, wage, hours, overtime, gross);
  */
  return(0);
}
void TestMoveWhenDestinationDirectoryDoesNotExist()
{
    std::cout << "PrintDataDirectoryUT TestMoveWhenDestinationDirectoryDoesNotExist" << std::endl;
    
    Copy("resources/slices/slice_1.png", testDataDir);
    Copy("resources/slices/slice_2.png", testDataDir);
   
    PrintDataDirectory printData(testDataDir);

    if (printData.Move("bogus"))
    {
        std::cout << "%TEST_FAILED% time=0 testname=TestMoveWhenDestinationDirectoryExists (PrintDataDirectoryUT) "
                << "message=Expected Move to return false, got true" << std::endl;
        mainReturnValue = EXIT_FAILURE;
        return;
    }

    // Verify that PrintData instance knows where its data resides after failure to move
    int expectedLayerCount = 2;
    int actualLayerCount = printData.GetLayerCount();
    if (expectedLayerCount != actualLayerCount)
    {
        std::cout << "%TEST_FAILED% time=0 testname=TestCreateFromNewDataWhenDownloadDirectoryContainsTarGzFile (PrintDataDirectoryUT) "
                << "message=Layer count incorrect after failing to move print data, expected "
                << expectedLayerCount << ", got " << actualLayerCount << std::endl;
        mainReturnValue = EXIT_FAILURE;
        return;
    }
}
Exemple #12
0
void printStack(stack* s){

  if(emptyStack(s) == 1){

    printf("\nThe stack is empty.\n");
    return;
  }
  stack* tempS = createStack();
  dnode* tempN = frontStack(s);
  data* d = createData(tempN->d->i1,tempN->d->i2,tempN->d->f1);
  while(emptyStack(s) != 1){

    tempN = frontStack(s);
    printData(tempN->d);
    d = createData(tempN->d->i1,tempN->d->i2,tempN->d->f1);
    pushStack(tempS,d);
    popStack(s);
  }
  while(emptyStack(tempS) != 1){

    tempN = frontStack(tempS);
    d = createData(tempN->d->i1,tempN->d->i2,tempN->d->f1);
    pushStack(s,d);
    popStack(tempS);
  }
  return;
}
Exemple #13
0
void ofxTouchBoard::printRawData(float x, float y){
	serial.lock();
		vector<ofxTB::Electrode> raw(serial.getData());
	serial.unlock();
	
	printData(raw, x, y);
}
void Transmitter::readPendingDatagrams()
{
  while (socket.hasPendingDatagrams()) {
	QByteArray datagram;
	QHostAddress sender;
	quint16 senderPort;

	qDebug() << "in" << __FUNCTION__;

	datagram.resize(socket.pendingDatagramSize());
	
	int rx = socket.readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
	if (rx == -1) {
	  qWarning() << "Failed to readDatagram:" << socket.errorString();
	} 

	payloadRecv += rx;
	totalRecv += rx + 28; // UDP + IPv4 headers

	qDebug() << "Sender:" << sender.toString() << ", port:" << senderPort;
	printData(&datagram);

	parseData(&datagram);
  }
}
void DataWarehouse::updateDate( uint16_t year, uint8_t month, uint8_t date )
{
    uint8_t j, k;
    uint8_t todayIndex;


    todayIndex = eeprom_read_byte( (const uint8_t *)STORE_ADDR_TODAYINDEX );

    eeprom_write_byte( (uint8_t *)STORE_ADDR_VALIDFLAG, ~DATA_VALID );
    writeDateInfo( todayIndex, year, month, date );   //record end date, display end date

    todayIndex = (todayIndex+1) % DATA_SAVE_DAYS;
    DBG_PRINTLN_VAR(todayIndex,DEC);

    eeprom_write_byte( (uint8_t *)STORE_ADDR_TODAYINDEX, todayIndex );
    writeDateInfo( todayIndex, year, month, date );   //record start date, only used internally

    for ( j = 0; j < DATA_TYPE_MAXNUM; j++ )
    {
        for ( k = 0; k < SAMPLE_TIMES_PERDAY; k++ )
        {
			writeData( INVALID_INT16, todayIndex, j, k );
        }
    }

    eeprom_write_byte( (uint8_t *)STORE_ADDR_VALIDFLAG, DATA_VALID );


#if _DEBUG
    printData(1);
#endif


}
Exemple #16
0
int intialize(char metaFile[], char dataFile[]) {
	S_table table;
	//Abre o arquivo de metadados
	FILE *F_meta = fopen(metaFile, "rb");
	//Verifica por erro na leitura do arquivo de metadados
	if(F_meta == NULL)
		return 1;
	//Pega a quantidade de campos contido no arquivo de metadados
	table.fieldCount = getFieldCount(F_meta);
	//Aloca N quantidade de campos, de acordo ao que foi lido do arquivo
	table.fields = (S_field *) malloc(sizeof(S_field) * table.fieldCount);
	//A função getFields lê do arquivo de metadados todos os dados dos campos e armazena-os na estrutura
	getFields(F_meta, table.fields,  table.fieldCount);
	//O arquivo de metadados é fechado
	fclose(F_meta);
	//Abre o arquivo de dados
	FILE *F_data = fopen(dataFile, "rb");
	//Verifica por erro na leitura do arquivo de dados
	if(F_data == NULL)
		return 2;
	//A função printData é chamada para imprimir os dados do arquivo de dados, de acordo com a estrutura informada em &table
	printData(&table, F_data);
	//Fecha o arquivo de dados
	fclose(F_data);
	return 0;
}
Exemple #17
0
Work * scs_init(Data * d, Cone * k, Info * info) {
	Work * w;
	timer initTimer;
	if (!d || !k || !info) {
		scs_printf("ERROR: Missing Data, Cone or Info input\n");
		return NULL;
	}
#ifdef EXTRAVERBOSE
	printData(d);
	printConeData(k);
#endif
#ifndef NOVALIDATE
	if (validate(d, k) < 0) {
		scs_printf("ERROR: Validation returned failure\n");
		return NULL;
	}
#endif
	tic(&initTimer);
	w = initWork(d, k);
	/* strtoc("init", &initTimer); */
	info->setupTime = tocq(&initTimer);
	if (d->VERBOSE) {
		scs_printf("Setup time: %1.2es\n", info->setupTime / 1e3);
	}
	return w;
}
Exemple #18
0
void ProbData::setValue(unsigned Row, unsigned Col, double Value)
{
	if (Col >= signed (ProbMat.size()))
	{
		std::cout << "\nError: Number of Columns is: " << static_cast<unsigned>(ProbMat.size()) << endl;
		std::cout << "Illegal Access in Column " << Col << endl;
		printData();
	}
	if (Row>= signed (ProbMat[Col].size()))
	{
		std::cout << "\nError: Number of Rows is: " << static_cast<unsigned>(ProbMat[Col].size()) << endl;
		std::cout << "Illegal Access in Row " << Row << endl;
		printData();
  }
	ProbMat[Col][Row] = Value;
}
void TestRemoveWhenUnderlyingDataExists()
{
    std::cout << "PrintDataDirectoryUT TestRemoveWhenUnderlyingDataExists" << std::endl;
   
    // To verify that the data is actually removed, the test checks for an empty parent directory
    // Create a child directory so a known parent directory exists
    std::string dataDir = testDataDir + "/dataDir";
    mkdir(dataDir.c_str(), 0755);
    
    Copy("resources/slices/slice_1.png", dataDir);
   
    PrintDataDirectory printData(dataDir);

    if (!printData.Remove())
    {
        std::cout << "%TEST_FAILED% time=0 testname=TestRemoveWhenUnderlyingDataExists (PrintDataDirectoryUT) "
                << "message=Expected Remove to return true, got false" << std::endl;
        mainReturnValue = EXIT_FAILURE;
        return;
    }

    // Verify that the directory no longer exists
    if (GetEntryCount(testDataDir, DT_DIR) != 0)
    {
        std::cout << "%TEST_FAILED% time=0 testname=TestRemoveWhenUnderlyingDataExists (PrintDataDirectoryUT) "
                << "message=Expected Remove to remove print data, directory still present" << std::endl;
        mainReturnValue = EXIT_FAILURE;
        return;
    }
}
Exemple #20
0
int CPAP_recv( int descriptor , uint8_t *cmd , int cmd_length )
{
    if ( cpap_global.uart_fd > 0 )
        descriptor = cpap_global.uart_fd;

    if ( descriptor <= 0 )
    {
        tryToOpenCPAP();
        return -1;
    }

    int recv_return;
    recv_return = rs232_recv( descriptor , (char *)cmd , cmd_length );

    if ( recv_return < 0 )
    {
        tryToOpenCPAP();

        if ( descriptor >= 0 )
            return CPAP_recv( descriptor , cmd , cmd_length );
        else
            return -1;
    }

    if ( recv_return > 0 && debug )
    {
        char message[32];
        sprintf( message , "FD(%d) >>>\n" , descriptor );
        printData( (char *)cmd , recv_return , message , 1 );
    }

    return recv_return;
}
Exemple #21
0
int CPAP_send( int descriptor , char *cmd , int cmd_length )
{
    if ( cpap_global.uart_fd > 0 )
        descriptor = cpap_global.uart_fd;

    if ( descriptor <= 0 )
    {
        tryToOpenCPAP();
        return -1;
    }

    if ( rs232_write( descriptor , cmd , cmd_length ) < 0 )
    {
        tryToOpenCPAP();

        if ( descriptor >= 0 )
            return CPAP_send( descriptor , cmd , cmd_length );
        else
            return -1;
    }

    if ( debug )
    {
        char message[32];
        sprintf( message , "FD(%d) <<<\n" , descriptor );
        printData( cmd , cmd_length ,  message , 1  );
    }

    return 0;
}
Exemple #22
0
void GaussianMatrix::setData( std::vector< std::vector< double > >  aData )
{
    std::cout << "setting data! " << std::endl;
    mData = aData;
    printData(); 
    if( mData.size() > 4 )
    {
        std::cout << "overdetermination!" << std::endl;
        overdetermined();
        printData();
        std::cout << "after overdetermination" << std::endl;
    }
    std::cout << "Making Gaussian: " << std::endl;
    makeGaussian();
    std::cout << "After Gaussian: " << std::endl;
    printData(); 
}
Exemple #23
0
/* Prints the given vector as independent dataset vector into the
   given file descriptor. */
void dataset::printDependency (vector * v, FILE * f) {
  // print data header
  fprintf (f, "<indep %s %d>\n", v->getName (), v->getSize ());
  // print data itself
  printData (v, f);
  // print data footer
  fprintf (f, "</indep>\n");
}
Exemple #24
0
int main(void)
{
    sortData(data, LENGTH);

    printData(data, LENGTH);

    return 0;
}
Exemple #25
0
std::string LLNameValue::printNameValue() const
{
	std::string buffer;
	buffer = llformat("%s %s %s %s ", mName, mStringType, mStringClass, mStringSendto);
	buffer += printData();
//	llinfos << "Name Value Length: " << buffer.size() + 1 << llendl;
	return buffer;
}
Exemple #26
0
void Scope::print(void (*printData)(void *)) {
    printf("Scope: %-15s -----------------\n", name.c_str());
    for (std::map<std::string , void *>::iterator it=symbols.begin(); it!=symbols.end(); it++) {
        printf("%20s: ", (it->first).c_str());
        printData(it->second);
        printf("\n");
    }
    
}
Exemple #27
0
SHINY_INLINE char* printZone(char* output, const ShinyZone *a_zone, float a_topercent) {
	snprintf(output, OUTPUT_WIDTH_NAME + TRAILING, "%-*s",
		OUTPUT_WIDTH_NAME, a_zone->name);

	output += OUTPUT_WIDTH_NAME;

	output = printData(output, &a_zone->data, a_topercent);
	return output;
}
Exemple #28
0
void printList(List l)
{
	if (l == 0) {
		return;
	}
	printData(l->data);
	printf(" ");
	printList(l->nextPtr);
};
Exemple #29
0
 void printData(filepoint p){    // 打印数据
     Tnode<KeyType> tmpnode;
     filepoint pt;
     std::cout<<"this point:"<<p<<std::endl;
     if (p!=0) {
         tmpnode = readFromFile (p);
         tmpnode.printData ();
         std::cout<<std::endl;
         if (tmpnode.getLeaf ()==0){
             for (int i=0;i<tmpnode.getKeyNum ();++i){
                 pt = tmpnode.getChild (i);
                 if (pt != 0) printData (pt);
             }
             pt = tmpnode.getChild (tmpnode.getKeyNum ());
             if (pt != 0) printData (pt);
         }
     }
 }
Sedan::Sedan()
{
    numberDoor=4;
    numberWheel=4;
    Motor=1,0;
    Comodidad=" Muy buena ";
    Ligereza=" Ligero ";
    printData();
}