Esempio n. 1
0
hkDemo::Result PatchesVersionVerify::stepDemo()
{
    hkReferencedObject::lockAll();
    if( m_done == false )
    {
        m_done = true;
        TeeStream teeStream;
        teeStream.add( hkcout.getStreamWriter() );
        hkOstream disk("PatchesVersionVerify.txt");
        teeStream.add( disk.getStreamWriter() );
        hkOstream demoOutput(&teeStream);

        demoOutput << "// *****    VERIFY PATCHES    *****\n";
        hkDataWorldDict world;
        const hkClassNameRegistry* reg = hkBuiltinTypeRegistry::getInstance().getClassNameRegistry();

        hkVersionPatchManager manager;
        registerInitialClassPatches(manager);
        registerPatches(manager);
        hkVersionCheckingUtils::verifyClassPatches(demoOutput, world, *reg, manager, g_variants[m_variantId].m_verbose ? hkVersionCheckingUtils::VERBOSE : hkVersionCheckingUtils::NONE);

        demoOutput << "\n// *****    DONE    *****\n";
    }
    hkReferencedObject::unlockAll();
    return DEMO_OK;
}
Esempio n. 2
0
	void on_paint_mesh(const k3d::mesh& Mesh, const k3d::gl::painter_render_state& RenderState, k3d::iproperty::changed_signal_t& ChangedSignal)
	{
		const k3d::color color = RenderState.node_selection ? k3d::color(1, 1, 1) : k3d::color(0.8, 0.8, 0.8);
		const k3d::color selected_color = RenderState.show_component_selection ? k3d::color(1, 0, 0) : color;

		for(k3d::mesh::primitives_t::const_iterator primitive = Mesh.primitives.begin(); primitive != Mesh.primitives.end(); ++primitive)
		{
			boost::scoped_ptr<k3d::disk::const_primitive> disk(k3d::disk::validate(Mesh, **primitive));
			if(!disk)
				continue;

			glPolygonOffset(1.0, 1.0);
			glEnable(GL_POLYGON_OFFSET_FILL);
			glEnable(GL_LIGHTING);

			glMatrixMode(GL_MODELVIEW);
			for(k3d::uint_t i = 0; i != disk->matrices.size(); ++i)
			{
				k3d::gl::material(GL_FRONT_AND_BACK, GL_DIFFUSE, disk->selections[i] ? selected_color : color);

				glPushMatrix();
				k3d::gl::push_matrix(disk->matrices[i]);
				draw_solid(RenderState, disk->heights[i], disk->radii[i], disk->sweep_angles[i]);
				glPopMatrix();
			}
		}
	}
Esempio n. 3
0
	void on_select_mesh(const k3d::mesh& Mesh, const k3d::gl::painter_render_state& RenderState, const k3d::gl::painter_selection_state& SelectionState, k3d::iproperty::changed_signal_t& ChangedSignal)
	{
		if(!SelectionState.select_component.count(k3d::selection::SURFACE))
			return;

		k3d::uint_t primitive_index = 0;
		for(k3d::mesh::primitives_t::const_iterator primitive = Mesh.primitives.begin(); primitive != Mesh.primitives.end(); ++primitive, ++primitive_index)
		{
			boost::scoped_ptr<k3d::disk::const_primitive> disk(k3d::disk::validate(Mesh, **primitive));
			if(!disk)
				continue;

			k3d::gl::push_selection_token(k3d::selection::PRIMITIVE, primitive_index);

			glDisable(GL_LIGHTING);

			glMatrixMode(GL_MODELVIEW);
			for(k3d::uint_t i = 0; i != disk->matrices.size(); ++i)
			{
				k3d::gl::push_selection_token(k3d::selection::SURFACE, i);

				glPushMatrix();
				k3d::gl::push_matrix(disk->matrices[i]);
				draw_solid(RenderState, disk->heights[i], disk->radii[i], disk->sweep_angles[i]);
				glPopMatrix();

				k3d::gl::pop_selection_token(); // SURFACE
			}

			k3d::gl::pop_selection_token(); // PRIMITIVE
		}
	}
Esempio n. 4
0
int main(){
    cpu();
    printf("----------------\n");
    disk();
    printf("----------------\n");
    memory();
    printf("----------------\n");
    net();
    printf("----------------\n");
}
Esempio n. 5
0
void Splitter::sendCueData()
{
    bool cdQuality = disk()->audioFile()->isCdQuality();
    OutFormat *format = OutFormat::currentFormat();

    bool fakeIndex = (format->createCue() and
                      format->preGapType() == OutFormat::PreGapAddToFirstTrack);

    QString s = QString("FILE \"%1\" WAVE").arg(disk()->audioFileName());
    mProcess->write(s.toLocal8Bit() + "\n");

    for (int t=0; t<disk()->count(); ++t)
    {
        Track *track = disk()->track(t);

        QString s = QString("TRACK %1 AUDIO").arg(t + 1);
        DEBUG_CUE << s;
        mProcess->write(s.toLocal8Bit() + "\n");

        if (fakeIndex && t == 0)
        {
            QString s = cdQuality ? "  INDEX 01 00:00:00" : "  INDEX 01 00:00.000";
            DEBUG_CUE << s;
            mProcess->write(s.toLocal8Bit() + "\n");
        }
        else
        {

            for (int i=0; i<100; ++i)
            {
                if (!track->cueIndex(i).isNull())
                {
                    QString s = QString("  INDEX %1 %2")
                            .arg(i, 2, 10, QChar('0'))
                            .arg(track->cueIndex(i).toString(cdQuality));
                DEBUG_CUE << s;
                mProcess->write(s.toLocal8Bit() + "\n");
                }
            }
        }
    }
}
void TautoPresetProps::getVolume(void)
{
    const char_t *flnm=deci->getSourceName();
    char_t dsk[MAX_PATH];
    _splitpath_s(flnm,dsk,MAX_PATH,NULL,0,NULL,0,NULL,0);
    DWORD serial,maximumComponentLength,volumeFlags;
    ffstring disk(dsk);
    disk += _l("\\");
    wasVolume=GetVolumeInformation(disk.c_str(),volumeName,256,&serial,&maximumComponentLength,&volumeFlags,NULL,0);
    if (wasVolume) {
        tsnprintf_s(volumeSerial, countof(volumeSerial), _TRUNCATE, _l("%X-%X"),(int)HIWORD(serial),(int)LOWORD(serial));
    }
}
Esempio n. 7
0
void putblobs(void)
{
struct blob *ablob,*ablob2,*temp;
int x,y,dy;
int i,size;
long x2,y2,vel;

	ablob=activeblobs;
	activeblobs=0;
	while(ablob)
	{
		dy=ablob->blobdy;
		if(ablob->blobsize!=SMALLSIZE && (dy>-THRESHOLD && dy<THRESHOLD && !(rand()&7) || (rand()&127)==63))
		{
			i=explodenum;
			while(i-- && freeblobs)
			{
				ablob2=freeblobs;
				freeblobs=freeblobs->blobnext;
				ablob2->blobx=ablob->blobx;
				ablob2->bloby=ablob->bloby;
				for(;;)
				{
					x2=(rand()&511)-256;
					y2=(rand()&511)-256;
					vel=x2*x2+y2*y2;
					if(vel>0x3000 && vel<0x10000L) break;
				}
				ablob2->blobdx=ablob->blobdx+x2;
				ablob2->blobdy=ablob->blobdy+y2;
				ablob2->bloblife=16+(rand()&31);
				ablob2->blobsize=SMALLSIZE;
				ablob2->blobnext=activeblobs;
				activeblobs=ablob2;
				ablob->bloblife=1;
			}			
		}
		x=ablob->blobx>>BLOBFRAC;
		y=ablob->bloby>>BLOBFRAC;
		size=ablob->blobsize;
		if(size==BIGSIZE && ablob->blobdy>0 && ablob->blobdy<200)
			size=sizes[ablob->bloblife&7];
		if(x>10 && x<XSIZE-10 && y>10 && y<YSIZE-10)
			disk(x,YSIZE-1-y,size);
		temp=ablob;
		ablob=ablob->blobnext;
		temp->blobnext=activeblobs;
		activeblobs=temp;
	}
}
Esempio n. 8
0
/************************************************
 Split audio file to temporary dir
 ************************************************/
void Splitter::doRun()
{
    QStringList args;
    args << "split";
    args << "-w";
    args << "-O" << "always";
    args << "-n" << "%04d";
    args << "-t" << mFilePrefix +"%n";
    args << "-d" << mWorkDir;
    args << disk()->audioFileName();
    //qDebug() << args;

    QString shntool = settings->value(Settings::Prog_Shntool).toString();
    mProcess = new QProcess();
    mProcess->setReadChannel(QProcess::StandardError);

    mProcess->start(shntool, args);
    mProcess->waitForStarted();

    sendCueData();
    mProcess->closeWriteChannel();

    parseOut();
    mProcess->waitForFinished(-1);

    QProcess *proc = mProcess;
    mProcess = 0;
    delete proc;

    if (OutFormat::currentFormat()->createCue())
    {
        CueCreator cue(disk());
        cue.setHasPregapFile(mPreGapExists);
        if (!cue.write())
            error(disk()->track(0), cue.errorString());
    }
}
Esempio n. 9
0
void net_habitue_device_SC101::handleResolvePacket(sockaddr_in *addr, mbuf_t m, size_t len, outstanding *out, void *ctx)
{
  clock_get_uptime(&_lastReply);
  
  if (mbuf_len(m) < out->len &&
      mbuf_pullup(&m, out->len) != 0)
  {
    KINFO("pullup failed");
    return;
  }
  
  KDEBUG("resolve succeeded!");
  
  psan_resolve_response_t *res = (psan_resolve_response_t *)mbuf_data(m);
  
  sockaddr_in part;
  bzero(&part, sizeof(part));
  part.sin_len = sizeof(part);
  part.sin_family = AF_INET;
  part.sin_port = htons(PSAN_PORT);
  part.sin_addr = res->ip4;
  
  OSData *partData = OSData::withBytes(&part, sizeof(part));
  if (partData)
  {
    setProperty(gSC101DevicePartitionAddressKey, partData);
    partData->release();
  }
  
  OSData *rootData = OSData::withBytes(addr, sizeof(*addr));
  if (rootData)
  {
    setProperty(gSC101DeviceRootAddressKey, rootData);
    rootData->release();
  }
  
  IODelete(out, outstanding, 1);
  
  mbuf_freem(m);

  if (!getProperty(gSC101DeviceSizeKey))
    disk();
}
Esempio n. 10
0
int File::saveToDisk(string name){
    cout<<name<<endl<<endl;
    ofstream disk("filesystem.disk",ios::out  | ios::app | ios::binary);
        int temp=2;
        disk.write((char*)&temp,sizeof(int));
        unsigned char t=(*this).getAccess();
        disk.write((char*)&t,sizeof(t));
        temp=(*this).getSize();
        disk.write((char*)&temp,sizeof(int));
        const char *tempName = name.c_str();
        int lengthName=strlen(tempName);
        disk.write((char*)&lengthName,sizeof(lengthName));
        disk.write(tempName,lengthName+1);
        //запись стандартной части окончена,пишем даты,хозяина и потоки
        Tcreated.saveToDisk(disk);
        Tmodified.saveToDisk(disk);
        disk.write((char*)&ownerUID,sizeof(int));
        strTbl->saveToDisk(disk);
        disk.close();
}
// Apply the half-kernel at 't' away from the center of the circle
static uint8_t eval_at(float t, float halfWidth, float* halfKernel, int kernelWH) {
    SkASSERT(!(kernelWH & 1));

    const float kernelOff = (kernelWH-1)/2.0f;

    float acc = 0;

    for (int y = 0; y < kernelWH/2; ++y) {
        if (kernelOff-y > halfWidth+0.5f) {
            // All disk() samples in this row will be 0.0f
            continue;
        }

        for (int x = 0; x < kernelWH; ++x) {
            float image = disk(t - kernelOff + x, -kernelOff + y, halfWidth);
            float kernel = halfKernel[y*kernelWH+x];
            acc += kernel * image;
        }
    }

    return SkUnitScalarClampToByte(acc);
}
Esempio n. 12
0
/**************************************************************************
  * find correct disk related to list item
**/
DiskEntry *KDFWidget::selectedDisk( TQListViewItem *item )
{
  if( item == 0 )
  {
    item = mList->selectedItem();
  }
  if( item == 0 )
  {
    return(0);
  }

  DiskEntry disk(item->text(deviceCol));
  disk.setMountPoint(item->text(mntCol));

  // I can't get find() to work. The Disks::compareItems(..) is
  // never called.
  //
  //int pos=mDiskList->find(disk);

  int pos = -1;
  for( u_int i=0; i<mDiskList.count(); i++ )
  {
    DiskEntry *item = mDiskList.at(i);
    int res = disk.deviceName().compare( item->deviceName() );
    if( res == 0 )
    {
      res = disk.mountPoint().compare( item->mountPoint() );
    }
    if( res == 0 )
    {
      pos = i;
      break;
    }
  }


  return mDiskList.at(pos);
  //  return(0);
}
Esempio n. 13
0
int main(int argc, char *argv[])
{
	if (argc < 5) {
        printf ("Not enough information\n");
        return EXIT_FAILURE;
	}
	
	char output[2][10] =
	{
	"test pass",
	"test fail"
	};

	radix *data;
	data = (radix *) malloc(sizeof(radix));
	
	data->a = atoi(argv[1]);
	data->b = atoi(argv[2]);
	data->c = atoi(argv[3]);
	int rezult = atoi(argv[4]);

	int diskr = disk(data);
	int i;
	
	if (diskr == rezult)
		i = 0;
	else 
		i = 1;
		
	 FILE *out;
    out = fopen("rez_d.txt", "a");
    fprintf(out, "a= %d  b= %d c= %d rezult= %d real = %d %s\n", data->a, data->b, data->c, rezult, diskr, output[i]);
    printf ("\n");
    free(data);
    fclose(out);

	return 0;
}
Esempio n. 14
0
int main(){

	if(config()) printf("system parameters config error!\n");

	/*
	delayMode=0;
	displayMode=1;	//determine information dispay mode
					//0 hide the content of the process loaded to system; 1 show all information 
	reportLevel=2; //0 report Warning and Error, 1 report Normal, Warning and Error, 2 report all
	updateSysfun=0;
	*/
	
	interpreter IM(101,30);
	editor e(103);
	assembler a(102);
	dispatcher os(105,10,30,40);
	storage  sys(106, sysPath[0]);
	storage  disk(107,sysPath[1]);


	//************************************************************************************************************
	//Dont modify this part!
	{	//initialize system
		FILE *fp;	//file pointer used to open code file for system function 
		int i;
		procptr pptr;
		pptr=new process[sysFunNumber];	//create process for system function
		process tp(0,100,10,40,0);	//process template, the code part is large but the data part is very small, with high priority
		
		for(i=0; i<sysFunNumber; i++){
			pptr[i].copy(tp);	//copy template process to each sysfun process
			pptr[i].ID=i;	//give each sysfun a new id(system function call number) 
			
		
			if(updateSysfun==1){	//reassemble sysfun
				sys.getFile(fp, sysFunTable[i],0); //open the function code file
				if(e.ASM(fp,a,sysFunTable[i])!=-1){
					Load(pptr,sysFunTable[i]);
					os.sysCall.put(i,&pptr[i]);	//load the system function to the sysCall list in scheduler
				}
				sys.releaseFile(fp);	//close file
			}
			else{
				Load(pptr,sysFunTable[i]);
				os.sysCall.put(i,&pptr[i]);	//load the system function to the sysCall list in scheduler
			}
	

		}
	}	//throuth this step, all the system function has been load into the system
	//************************************************************************************************************

	//************************************************************************************************************
	{	//load user code to system
		FILE *run;	//file ptr of list file
		FILE *pfr;	//pointer to the code file
		procptr pptr;	//used to create user process
		process tpf(0,100,40,50,1);	//process template, the data part is larger than sysfun, but priority is lower

		int id=50;	//least user proc ID
		char name[50]; //used to code file name
		disk.getFile(run,runList,0);
		fscanf(run,"%s",name);	//read code file name
		while(strcmp(name,"end") && strcmp(name, "END")){ //list file end with "end" or "END"
			disk.getFile(pfr,name,0);	//open code file
			pptr=new process;	//create user process
			pptr->copy(tpf);	//copy template process to each process
			pptr->ID=id++;	//give user process a new id
			printf("process ID:%d\n", pptr->ID);
	
			if(e.ASM(pfr,a,name) != -1){
				Load(pptr,name);
				os.loader(pptr);	//load process to scheduler
			}
			disk.releaseFile(pfr);	//close code file 
			fscanf(run,"%s",name); //read next code file name
		}
		disk.releaseFile(run);	//close list file
	}	//throuth this step, all the user process has been load into the system
	//*************************************************************************************************************

	
	os.swap2(IM);	//swap process to run and wait, when a user process finished, it will be put into finished queue 
	

	//*************************************************************************************************************
	{	//show the finished process data part
		procptr pptr;
		//pcbptr pblock;
		int r=0;
		//r=os.finished.deQueue(pptr); //get a process from finished queue
		r=os.finished.deQueue(pptr);
		
		
		printf("\ndisplay data?(y/n): ");
		char c;
		c=getche();
		putchar('\n');

		
		while(r!=-1){	//finished queue isnt empty
			printf("process ID:%d\n", pptr->ID);
			if(c=='y' || c=='Y'){
				int i;
				printf("memory ID:%d\n",pptr->MData.ID);
				for(i=0; i<pptr->MData.mSize; i++)
				printf("%-4d%d\n",i,pptr->MData.read(i)); //show M.mem[i]
			}
			printf("execute times:%d\n",pptr->exetime);
			r=os.finished.deQueue(pptr);	//get next process
		}
	}
	//*************************************************************************************************************

	//systemChecker.check(RES, sysLog);	//show system end state, normal state is show "queue::deQueue: queue is empty"

	printf("\nPress any key to exit.");
	getch();

	return 0;
}
Esempio n. 15
0
interact()

{

	int	i, intrpt();
	char	cmd[80], *rest, *index();

	for (;;) {
		if (firsttime++ == 0) {
			signal(SIGINT, intrpt, -1);
			 setret(env);
		}
		if (cmdinp(cmd) < 0)
			return (0);
		rest = index(cmd, ' ');
		if (rest)
			*rest++ = '\0';
		i = chkcmd(cmd);
#ifdef DEBUG
		printf("command: %s, ind: %d\n", cmd, i);
#endif

		switch (i) {
		default:
			errinp;
			break;
		case CMD_DIR:
		case CMD_LS:
			dispdir();
			break;

		case CMD_RENAME:
			rename(rest);
			break;

		case CMD_OCOPY:
			copyc(rest, 0);
			break;

		case CMD_ICOPY:
			pip(rest, 0);
			break;

		case CMD_DELETE:
		case CMD_ERASE:
			delete(rest);
			break;

		case CMD_EXIT:
		case CMD_LOGOUT:
			return(0);

		case CMD_TYPE:
			copy(rest, stdout, 0);
			break;

		case CMD_HELP:
			help();
			break;

		case CMD_OCCOPY:
			copyc(rest, 1);
			break;

		case CMD_ICCOPY:
			pip(rest,1);
			break;

		case CMD_DUMP:
			dump(rest);
			break;

		case CMD_UNIX:
			system(rest);
			break;

		case CMD_DISK:
			disk();
			break;

		}
	}
}
Esempio n. 16
0
/*
	MAIN()
	------
*/
int main(int argc, char *argv[])
{
    static char *seperators = " ";
    char *file, *token, *where_to, *filename;			// *start;
    char **term_list, **first, **last, **current;
    ANT_link_extract_term *link_index, *index_term;
    long terms_in_index, current_docid, param, file_number;
    long lowercase_only, first_param;
    long is_utf8_token, cmp, is_substring = FALSE;				// token_len
    char *command;
    ANT_directory_iterator_object file_object;

    char buffer[1024 * 1024];

    if (argc < 3)
        exit(printf("Usage:%s [-chinese] [-lowercase] <index> <file_to_link> ...\n", argv[0]));

    first_param = 1;
    lowercase_only = FALSE;
    chinese = FALSE;

    for (param = 1; param < argc; param++)
    {
        if (*argv[param] == '-')
        {
            command = argv[param] + 1;
            if (strcmp(command, "lowercase") == 0)
            {
                lowercase_only = TRUE;
                ++first_param;
            }
            else if (strcmp(command, "chinese") == 0)
            {
                chinese = TRUE;
                ++first_param;
            }
            else
                exit(printf("Unknown parameter:%s\n", argv[param]));
        }
    }

    link_index = read_index(argv[first_param], &terms_in_index);

    file_number = 1;
    for (param = first_param + 1; param < argc; param++)
    {
        ANT_directory_iterator_recursive disk(argv[param]);  // make the recursive pattern matching as for default files reading
        if (disk.first(&file_object) == NULL)
            file = filename = NULL;
        else
        {
            filename = file_object.filename;
            file = ANT_disk::read_entire_file(filename);
        }
        while (file != NULL)
        {
            current_docid = get_doc_id(file);
            if (current_docid > 0)
            {
//			printf("ID:%d\n", current_docid);
                string_clean(file, lowercase_only, TRUE);

                current = term_list = new char *[strlen(file)];		// this is the worst case by far
                if (chinese)
                    create_utf8_token_list(file, term_list);
                else
                {
                    for (token = strtok(file, seperators); token != NULL; token = strtok(NULL, seperators))
                        *current++ = token;
                    *current = NULL;
                }


                for (first = term_list; *first != NULL; first++)
                {
//				fprintf(stderr, "%s\n", *first);
                    where_to = buffer;
                    for (last = first; *last != NULL; last++)
                    {
                        if (where_to == buffer)
                        {
                            strcpy(buffer, *first);
                            where_to = buffer + strlen(buffer);
                            if (chinese)
                            {
                                if ((*first[0] & 0x80) && isutf8(*first))
                                    is_utf8_token = TRUE;
                                else
                                    is_utf8_token = FALSE;
                            }
                        }
                        else
                        {
                            if (!chinese)
                                *where_to++ = ' ';
                            strcpy(where_to, *last);
                            where_to += strlen(*last);
                        }

                        *where_to = '\0';

                        index_term = find_term_in_list(buffer, link_index, terms_in_index);

                        if (index_term == NULL)
                            break;		// we're after the last term in the list so can stop because we can't be a substring

                        if (chinese)
                        {
                            is_substring = FALSE;
                            cmp = utf8_token_compare(buffer, index_term->term, &is_substring);
                        }
                        else
                            cmp = string_compare(buffer, index_term->term);

                        if (cmp == 0)		// we're a term in the list
                        {
                            index_term->total_occurences++;
                            if (index_term->last_docid != current_docid)
                            {
                                index_term->last_docid = current_docid;
                                index_term->docs_containing_term++;
                            }
                        }
                        else
                        {
                            if (chinese)
                                cmp = is_substring == TRUE ? 0 : 1;
                            else
                                cmp = memcmp(buffer, index_term->term, strlen(buffer));
                            if  (cmp != 0)
                                break;		// we're a not a substring so we can't find a longer term
                        }
                    }
                }
                if (chinese)
                    free_utf8_token_list(term_list);
                delete [] term_list;
                delete [] file;

                if (file_number % 1000 == 0)
                    fprintf(stderr, "Files processed:%d\n", file_number);
                file_number++;
            }
            else
                fprintf(stderr, "Error reading file %s\n", filename);
            //filename = disk.get_next_filename();
            if (disk.next(&file_object) == NULL)
                file = filename = NULL;
            else
            {
                filename = file_object.filename;
                file = ANT_disk::read_entire_file(filename);
            }
        }
    }

    print_answer(link_index, terms_in_index);

    fprintf(stderr, "%s Completed\n", argv[0]);

    return 0;
}
Esempio n. 17
0
void mrbig(void)
{
	char *p;
	time_t t, lastrun;
	int sleeptime, i;
	char hostname[256];
	DWORD hostsize;

	/*
	 * install exception logging/stacktrace handler.
	 * We need to resolve the symbol at run time because windows 2000
	 * does not have it.
	 */
	do {
		HMODULE dll;
		PVOID (*ptr) (ULONG First,PVECTORED_EXCEPTION_HANDLER Handler) = NULL;
		dll = LoadLibraryEx("kernel32.dll", NULL, 0);
		if (dll == NULL)
			break;
		ptr = (typeof(ptr))GetProcAddress(dll, "AddVectoredExceptionHandler");
		if (ptr == NULL)
			break;
		ptr(1, VectoredExceptionHandler);
		mrlog("VectoredExceptionHandler handler has been installed");
	} while(0);

	if (debug) {
		mrlog("mrbig()");
	}
	for (i = 0; _environ[i]; i++) {
		startup_log("%s", _environ[i]);
	}
	for (;;) {
		if (debug) mrlog("main loop");
		read_cfg("mrbig", cfgfile);
		readcfg();
		t = time(NULL);
		strlcpy(now, ctime(&t), sizeof now);
		p = strchr(now, '\n');
		if (p) *p = '\0';
		hostsize = sizeof hostname;
		if (GetComputerName(hostname, &hostsize)) {
			for (i = 0; hostname[i]; i++)
				hostname[i] = tolower(hostname[i]);
			snprcat(now, sizeof now, " [%s]", hostname);
		}

		cpu();
		check_chunks("after cpu test");

		disk();
		check_chunks("after disk test");

		memory();
		check_chunks("after memory test");

		msgs();
		check_chunks("after msgs test");

		procs();
		check_chunks("after procs test");

		svcs();
		check_chunks("after svcs test");

		wmi();
		check_chunks("after wmi test");

		if (pickupdir[0]) ext_tests();

		lastrun = t;
		t = time(NULL);
		if (t < lastrun) {
			mrlog("mainloop: timewarp detected, sleep for %d",
				mrloop);
			sleeptime = mrloop;
		} else {
			sleeptime = mrloop-(t-lastrun);
		}
		if (sleeptime < SLEEP_MIN) sleeptime = SLEEP_MIN;
		if (debug) mrlog("started at %d, finished at %d, sleep for %d",
			(int)lastrun, (int)t, sleeptime);
		clear_cfg();
		if (debug) {
			dump_chunks();
			check_chunks("after main loop");
		}
		Sleep(sleeptime*1000);
	}
}
Esempio n. 18
0
main()
{
      
/******************************************************************************/
/*  BUILDING DISK POSITION DISTRIBUTION                                       */
/******************************************************************************/

    std::cout << "Building disk\n";         //  printing disk parameters
    std::cout << "  Mdisk = " << Md << "\n";
    std::cout << "  Ndisk = " << Ndisk << "\n";
    std::cout << "  Radial Scale Length h = " << h << "\n";
    std::cout << "  Vertical Scale Length z0 = " << z0 << "\n";
    std::cout << "  Radial Cutoff = " << diskcut << "\n";
    std::cout << "  Vertical Cutoff = " << thickcut << "\n";
    
    std::vector<Vector> disk(Ndisk, Vector(3)); //  array of disk positions
    
    min = 0.0, max = diskcut;               //  setting max and min radii
    topbound = findtopbound(surfacedist, min, max);   //  finding topbound
    
    for (int i = 0; i < Ndisk; i++)         //  for each particle in disk
    {
        r = rejectionsample(surfacedist, min, max, topbound); //  choose
                                            //  random radius
        disk[i][0] = r;                     //  assigning as such
        disk[i][1] = randomreal(0.0, 2.0*PI); //  randomize azimuthal angle
    }                                       
    
    min = -thickcut;                        //  setting min and max
    max = thickcut;                         //  heights
    topbound = findtopbound(diskthick, min, max);   //  finding topbound
    for (int i = 0; i < Ndisk; i++)         //  for each disk particle
    {
        disk[i][2] = rejectionsample(diskthick, min, max, topbound);    //
                                            //  choosing height randomly
        bodies[i].mass = Md / ((double)Ndisk);  //  assigning masses such that
                                            //  total mass is correct
        bodies[i].pos = cyltocart(disk[i]); //  transforming to cartesian coords
        bodies[i].id = i;                   //  assigning particle id
        bodies[i].DM = false;               //  these are not dark
    }
    

/******************************************************************************/
/*  BUILDING HALO POSITION DISTRIBUTION                                       */
/******************************************************************************/
    
    std::cout << "Building Halo\n";         //  printing parameters
    std::cout << "  Mhalo = " << Mh << "\n";
    std::cout << "  Nhalo = " << Nhalo << "\n";
    std::cout << "  Scale Length rc = " << rc << "\n";
    std::cout << "  Scale Length gamma = " << g << "\n";
    std::cout << "  Cutoff Radius = " << halocut << "\n";

    std::vector<Vector> halo(Nhalo, Vector(3)); //  array of halo positions
    
    min = 0.0, max = halocut;               //  max and min for distribution
    topbound = findtopbound(hernquisthalo, min, max);   //  finding topbound
    for (int i = 0; i < Nhalo; i++)         //  for each bulge particle
    {
        r = rejectionsample(hernquisthalo, min, max, topbound);  //  select r from
                                            //  distribution
        bodies[Ndisk + i].pos = randomsphere(r);    //  randomize position
                                            //  on sphere
        bodies[Ndisk + i].mass = Mh / ((double)Nhalo);  //  normalizing mass
        bodies[Ndisk + i].id = Ndisk + i;   //  setting appropriate ID
        bodies[Ndisk + i].DM = true;        //  these are dark
        halo[i] = carttosphere(bodies[Ndisk + i].pos);  //  saving copy in
                                            //  spherical coords for later
    }
    

/******************************************************************************/
/*  BUILDING BULGE POSITION DISTRIBUTION                                      */
/******************************************************************************/

    std::cout << "Building Bulge\n";
    std::cout << "  Mbulge = " << Mb << "\n";
    std::cout << "  Nbulge = " << Nbulge << "\n";
    std::cout << "  Scale Length a = " << a << "\n";
    std::cout << "  Cutoff Radius = " << bulgecut << "\n";
    
    std::vector<Vector> bulge(Nbulge, Vector(3));   //  array of bulge positions
    
    min = 0.0; max = bulgecut;              //  distribution max and min
    topbound = findtopbound(bulgedist, min, max);   //  finding topbound
    for (int i = 0; i < Nbulge; i++)        //  for each particle
    {
        r = rejectionsample(bulgedist, min, max, topbound);  //  select r from
                                            //  distribution
        bodies[Ndisk + Nhalo + i].pos = randomsphere(r);    //  randomize sphere
                                            //  position
        bodies[Ndisk + Nhalo + i].mass = Mb / (double)Nbulge;   //  setting mass
        bodies[Ndisk + Nhalo + i].id = Ndisk + Nhalo + i;   //  setting IDs
        bulge[i] = carttosphere(bodies[Ndisk + Nhalo + i].pos); //  saving copy
                                            //  in spherical coordinates
    }

    
/******************************************************************************/
/*  Approximating Cumulative Mass Distribution M(r)                           */
/******************************************************************************/
    
    dr = halocut / ((double) massbins);     //  setting separation between mass
                                            //  bins
    
    std::cout << "Approximating Cumulative Mass Distribution M(r)\n";
    std::cout << "  Number of bins = " << massbins << "\n";
    std::cout << "  dr = " << dr << "\n";
    
    std::vector <Vector> Massatr(massbins, Vector(2));  //  Array to hold
                                            //  radius and value of cumulative
                                            //  mass distribution
    
    for (int i = 0; i < massbins; i++)      //  for each mass bin
    {
        Massatr[i][1] = ((double)(i+1))*dr; //  setting radius
        Massatr[i][0] = 0.0;                //  clearing total mass
        
        for (int j = 0; j < Ndisk; j++)     //  for each disk mass
        {
            r = sqrt(disk[j][0]*disk[j][0] + disk[j][2]*disk[j][2]);    // radius
                                            //  in spherical coordinates
            if((r < (double)(i+1)*dr))      //  if radius less than bin radius
            {
                Massatr[i][0] += Md / (double)Ndisk;    //  add mass
            }
        }
        
        for (int j = 0; j < Nhalo; j++)     //  for each halo mass
        {
            r = halo[j][0];                 //  radius
            if((r < (double)(i+1)*dr))      // if radius less than bin radius
            {
                Massatr[i][0] += Mh / (double)Nhalo;    //  add mass
            }
        }
        
        for (int j = 0; j < Nbulge; j++)    // for each bulge mass
        {
            r = bulge[j][0];                //  radius
            if((r < (double)(i+1)*dr))      //  if radius less than bin radius
            {
                Massatr[i][0] += Mb / (double)Nbulge;   //  add mass
            }
        }
    }
    
    
/******************************************************************************/
/*  Setting Halo Velocities                                                   */
/******************************************************************************/
    
    std::cout << "Setting Halo Velocities\n";
    
    double v;                               //  variable to hold speed
    double vesc;                            //  variable to hold escape speed
    
    std::vector<Vector> halovels(Nhalo, Vector(3)); //  Vector to hold halo
                                            //  velocities
    
    for (int i = 0; i < Nhalo; i++)         //  for each halo mass
    {
        r = halo[i][0];                     //  radius
        
        startbin = floor(r/dr);             //  starting index is floor of r/dr
        
        vesc = sqrt(2.0*Massatr[startbin][0]/r);    //  escape velocity
        
        vr2 = 0.0;                          //  clearing radial dispersion
        for (int j = startbin; j < massbins; j++)   //  for each mass bin
        {
            vr2 += hernquisthalo(Massatr[j][1])*dr*Massatr[j][0];   //  add 
        }                                   //  contribution
        vr2 /= (hernquisthalo(r)/(r*r));    //  dividing by halo density at r
        
        
        min = 0.0;                          //  distribution min
        max = 0.95*vesc;                    //  distribution max is 0.95 of
                                            //  escape velocity
        topbound = vr2 / 2.71828;           //  topbound is vr^2 / e
        
        v = rejectionsample(halospeeddist, min, max, topbound); //  selecting
                                            //  absolute speed
        halovels[i] = randomsphere(v);      //  randomizing cartesian velocities
                                            //  on a sphere of radius v
        bodies[Ndisk + i].vel = halovels[i];//  assigning velocities as such
        
    }
    
    
/******************************************************************************/
/*  Setting Bulge Velocities                                                  */
/******************************************************************************/

    
    std::cout << "Setting Bulge Velocities\n";
    
    std::vector<Vector> bulgevels(Nbulge, Vector(3));   // Vector to hold bulge
                                             // velocities
    
    for (int i = 0; i < Nbulge; i++)        //  for each particle
    {
        r = bulge[i][0];                    //  radius
        
        startbin = floor(r / dr);           //  starting index
        
        vesc = sqrt(2.0*Massatr[startbin][0]/r);    //  escape velocity
        
        vr2 = 0.0;                          //  clearing radial dispersion
        
        for (int j = startbin; j < massbins; j++)   //  for each mass bin
        {
            vr2 += bulgedist(Massatr[j][1])*dr*Massatr[j][0];   // add
                                            //  contribution
        }
        vr2 /= bulgedist(r)/(r*r);          //  dividing by halo density at r
        
        
        min = 0.0;                          //  distribution min
        max = 0.95*vesc;                    //  max is 0.95 of escape velocity
        topbound = vr2 / 2.71828;           //  topbound is vr^2 /e
        
        v = rejectionsample(bulgedist, min, max, topbound); //  selecting absolute
                                            //  absolute speed
        bulgevels[i] = randomsphere(v);     //  randomizing constrained cartesian
                                            //  velocities
        bodies[Ndisk + Nhalo + i].vel = bulgevels[i];   //  assining data as such
    }

    
/******************************************************************************/
/*  Setting Disk Velocities                                                   */
/******************************************************************************/

    std::cout << "Setting Disk Velocities\n";
    std::cout << "  Q = " << Q << "\n";
    std::cout << "  Reference radius = " << rref << "\n";
    std::vector<Vector> diskvels(Ndisk, Vector(3)); //  Vector to hold disk
                                            //  velocities
    
    double vz2;                             //  vertical dispersion
    double vc;                              //  circular speed
    double ar;                              //  radial acceleration
    double k;                               //  epicyclic frequency
    double sigmaz2;                         //  azimuthal velocity dispersion
    double sigmaavg;                        //  average dispersion
    double Omega;                           //  angular frequency
    double A;                               //  radial dispersion constant
    int count;                              //  count variable for averaging
    Vector acc(3);                          //  vector to store acceleration
    double as = 0.25*h;
    
    
    maketree(bodies, Ntot, root);           //  making tree
    
    // NORMALIZING RADIAL DISPERSION
    std::cout << "  Normalizing Radial Distribution\n";
    dr = diskcut / 1000.0;                  //  width of annulus in which
                                            //  to average dispersion
    sigmaavg = 0.0;                         //  zeroing average
    for (int i = 0; i < Ndisk; i++)         //  for each disk particle
    {
        r = disk[i][0];                     //  radius
        if (fabs(r - rref) < dr)            //  if radius in annulus
        {                                   //  calculate epicylclic frequency
            k = epicyclicfrequency(bodies, Ntot, i, root, eps, theta, 0.05*dr);
            sigmaavg += 3.36*Sigma(r)/k;    //  calculate dispersion and add to
                                            //  average
            count += 1;                     //  up count
        }  
    }
    
    sigmaavg /= (double)count;              //  divide total by count
    sigmaavg *= Q;                          //  adjust by Q
    
    A = sigmaavg*sigmaavg / Sigma(rref);    //  setting norm constant
    
    
    //  ASSIGNING VELOCITIES
    std::cout << "  Setting particle velocities\n";
    for (int i = 0; i < Ndisk; i++)         //  for every particle
    {
        r = disk[i][0];                     //  radius
        vz2 = PI*z0*Sigma(sqrt(r*r + 2.0*as*as));    //  vertical dispersion
        diskvels[i][2] = gaussianrandom(sqrt(vz2)); //  randomizing vertical
                                            //  with this dispersion
        
        vr2 = A*Sigma(sqrt(r*r + 2.0*as*as));   //  assigning radial dispersion
        diskvels[i][0] = gaussianrandom(sqrt(vr2)); //  randomizing radial
                                            //  dispersion
        
        acc = treeforce(&bodies[i], root, eps, theta);  //  acceleration
        ar = (acc[0]*bodies[i].pos[0] + acc[1]*bodies[i].pos[1])/r; //
                                            //  radial acceleration
        Omega = sqrt(fabs(ar)/r);           //  angular frequency
        k = epicyclicfrequency(bodies, Ntot, i, root, eps, theta, dr);  //
                                            //  epicyclic frequency
        vc = Omega*r;                       //  circular speed
        v = sqrt(fabs(vc*vc + vr2*(1.0 - (k*k)/(4.0*Omega*Omega) - 2.0*r/h)));  //
                                            //  azimuthal streaming velocity
        sigmaz2 = vr2*k*k/(4.0*Omega*Omega);//  azimuthal dispersion
        v += gaussianrandom(sqrt(sigmaz2)); //  adding random azimuthal component
        diskvels[i][1] = v;                 //  assigning azimuthal velocity 
        
                                            //  transforming to cartesian coords
        bodies[i].vel[0] = diskvels[i][0]*cos(disk[i][1])
                            - diskvels[i][1]*sin(disk[i][1]);
        bodies[i].vel[1] = diskvels[i][0]*sin(disk[i][1])
                            + diskvels[i][1]*cos(disk[i][1]);
        bodies[i].vel[2] = diskvels[i][2];
    }
    
    
/******************************************************************************/
/*  Reporting Average Disk Speed                                              */
/******************************************************************************/
    
    v = 0.0;
    
    for (int i = 0; i < Ndisk; i++)
    {
        v += bodies[i].vel.norm();
    }
    
    v /= (double)Ndisk;
    
    std::cout << "Average Disk Particle Speed: " << v << "\n";
    std::cout << "Disk Size: " << diskcut << "\n";
    std::cout << "Disk Crossing Time: " << diskcut / v << "\n";
    
    
    writeinitfile(Ntot, Nhalo, bodies, "data/initfile.txt");
    
    
 
}
Esempio n. 19
0
int
main(int argc, char **argv)
{
	puts("Copyright (c) 2001-2010 pinc Software.");

	if (argc < 2 || !strcmp(argv[1], "--help")) {
		char *filename = strrchr(argv[0],'/');
		fprintf(stderr,"usage: %s [-srib] <device> [allocation_group start]\n"
				"\t-s\tdump superblock\n"
				"\t-r\tdump root node\n"
				"       the following options need the allocation_group/start "
					"parameters:\n"
				"\t-i\tdump inode\n"
				"\t-b\tdump b+tree\n"
				"\t-v\tvalidate b+tree\n"
				"\t-h\thexdump\n"
				"\t-o\tshow disk offsets\n",
				filename ? filename + 1 : argv[0]);
		return -1;
	}

	bool dumpRootNode = false;
	bool dumpInode = false;
	bool dumpSuperBlock = false;
	bool dumpBTree = false;
	bool validateBTree = false;
	bool dumpHex = false;
	bool showOffsets = false;

	while (*++argv) {
		char *arg = *argv;
		if (*arg == '-') {
			while (*++arg && isalpha(*arg)) {
				switch (*arg) {
					case 's':
						dumpSuperBlock = true;
						break;
					case 'r':
						dumpRootNode = true;
						break;
					case 'i':
						dumpInode = true;
						break;
					case 'b':
						dumpBTree = true;
						break;
					case 'v':
						validateBTree = true;
						break;
					case 'h':
						dumpHex = true;
						break;
					case 'o':
						showOffsets = true;
						break;
				}
			}
		} else
			break;
	}

	Disk disk(argv[0]);
	if (disk.InitCheck() < B_OK)
	{
		fprintf(stderr, "Could not open device or file: %s\n", strerror(disk.InitCheck()));
		return -1;
	}
	putchar('\n');

	if (!dumpSuperBlock && !dumpRootNode && !dumpInode && !dumpBTree
		&& !dumpHex) {
		printf("  Name:\t\t\t\"%s\"\n", disk.SuperBlock()->name);
		printf("    (disk is %s)\n\n",
			disk.ValidateSuperBlock() == B_OK ? "valid" : "invalid!!");
		printf("  Block Size:\t\t%" B_PRIu32 " bytes\n", disk.BlockSize());
		printf("  Number of Blocks:\t%12" B_PRIdOFF "\t%10g MB\n",
			disk.NumBlocks(), disk.NumBlocks() * disk.BlockSize()
				/ (1024.0*1024));
		if (disk.BlockBitmap() != NULL) {
			printf("  Used Blocks:\t\t%12" B_PRIdOFF "\t%10g MB\n",
				disk.BlockBitmap()->UsedBlocks(),
				disk.BlockBitmap()->UsedBlocks() * disk.BlockSize()
					/ (1024.0*1024));
			printf("  Free Blocks:\t\t%12" B_PRIdOFF "\t%10g MB\n",
				disk.BlockBitmap()->FreeBlocks(),
				disk.BlockBitmap()->FreeBlocks() * disk.BlockSize()
					/ (1024.0*1024));
		}
		int32 size
			= (disk.AllocationGroups() * disk.SuperBlock()->blocks_per_ag);
		printf("  Bitmap Size:\t\t%" B_PRIu32 " bytes (%" B_PRId32 " blocks, %"
			B_PRId32 " per allocation group)\n", disk.BlockSize() * size, size,
			disk.SuperBlock()->blocks_per_ag);
		printf("  Allocation Groups:\t%" B_PRIu32 "\n\n",
			disk.AllocationGroups());
		dump_block_run("  Log:\t\t\t", disk.Log());
		printf("    (was %s)\n\n", disk.SuperBlock()->flags == SUPER_BLOCK_CLEAN
			? "cleanly unmounted" : "not unmounted cleanly!");
		dump_block_run("  Root Directory:\t", disk.Root());
		putchar('\n');
	} else if (dumpSuperBlock) {
		dump_super_block(disk.SuperBlock());
		putchar('\n');
	}

	if (disk.ValidateSuperBlock() < B_OK) {
		fprintf(stderr, "The disk's superblock is corrupt (or it's not a BFS "
			"device)!\n");
		return 0;
	}

	if (dumpRootNode) {
		bfs_inode inode;
		if (disk.ReadAt(disk.ToOffset(disk.Root()), (void *)&inode,
				sizeof(bfs_inode)) < B_OK) {
			fprintf(stderr,"Could not read root node from disk!\n");
		} else {
			puts("Root node:\n-----------------------------------------");
			dump_inode(NULL, &inode, showOffsets);
			dump_indirect_stream(disk, &inode, showOffsets);
			putchar('\n');
		}
	}

	char buffer[disk.BlockSize()];
	bfs_inode* bfsInode = (bfs_inode*)buffer;
	block_run run;
	Inode *inode = NULL;

	if (dumpInode || dumpBTree || dumpHex || validateBTree) {
		// Set the block_run to the right value (as specified on the command
		// line)
		if (!argv[1]) {
			fprintf(stderr, "The -i/b/f options need the allocation group and "
				"starting offset (or the block number) of the node to dump!\n");
			return -1;
		}
		run = parseBlockRun(disk, argv[1], argv[2]);

		if (disk.ReadAt(disk.ToOffset(run), buffer, disk.BlockSize()) <= 0) {
			fprintf(stderr,"Could not read node from disk!\n");
			return -1;
		}

		inode = Inode::Factory(&disk, bfsInode, false);
		if (inode == NULL || inode->InitCheck() < B_OK) {
			fprintf(stderr,"Not a valid inode!\n");
			delete inode;
			inode = NULL;
		}
	}

	if (dumpInode) {
		printf("Inode at block %" B_PRIdOFF ":\n------------------------------"
			"-----------\n", disk.ToBlock(run));
		dump_inode(inode, bfsInode, showOffsets);
		dump_indirect_stream(disk, bfsInode, showOffsets);
		dump_double_indirect_stream(disk, bfsInode, showOffsets);
		dump_small_data(inode);
		putchar('\n');
	}

	if (dumpBTree && inode != NULL) {
		printf("B+Tree at block %" B_PRIdOFF ":\n-----------------------------"
			"------------\n", disk.ToBlock(run));
		if (inode->IsDirectory() || inode->IsAttributeDirectory()) {
			dump_bplustree(disk, (Directory *)inode, inode->Size(), dumpHex);
			putchar('\n');
		} else
			fprintf(stderr, "Inode is not a directory!\n");
	}

	if (validateBTree && inode != NULL) {
		printf("Validating B+Tree at block %" B_PRIdOFF ":\n------------------"
			"-----------------------\n", disk.ToBlock(run));
		if (inode->IsDirectory() || inode->IsAttributeDirectory()) {
			BPlusTree *tree;
			if (((Directory *)inode)->GetTree(&tree) == B_OK) {
				if (tree->Validate(true) < B_OK)
					puts("B+Tree is corrupt!");
				else
					puts("B+Tree seems to be okay.");
			}
		} else
			fprintf(stderr, "Inode is not a directory!\n");
	}

	if (dumpHex) {
		printf("Hexdump from inode at block %" B_PRIdOFF ":\n-----------------"
			"------------------------\n", disk.ToBlock(run));
		dump_block(buffer, disk.BlockSize());
		putchar('\n');
	}

	delete inode;

	return 0;
}
Esempio n. 20
0
void TestBSDF(void (*createBSDF)(BSDF*, MemoryArena&),
              const char* description) {
    MemoryArena arena;

    Options opt;
    pbrtInit(opt);

    const int thetaRes = CHI2_THETA_RES;
    const int phiRes = CHI2_PHI_RES;
    const int sampleCount = CHI2_SAMPLECOUNT;
    Float* frequencies = new Float[thetaRes * phiRes];
    Float* expFrequencies = new Float[thetaRes * phiRes];
    RNG rng;

    int index = 0;
    std::cout.precision(3);

    // Create BSDF, which requires creating a Shape, casting a Ray that
    // hits the shape to get a SurfaceInteraction object.
    BSDF* bsdf = nullptr;
    Transform t = RotateX(-90);
    Transform tInv = Inverse(t);
    {
        bool reverseOrientation = false;
        ParamSet p;

        std::shared_ptr<Shape> disk(
            new Disk(&t, &tInv, reverseOrientation, 0., 1., 0, 360.));
        Point3f origin(0.1, 1,
                       0);  // offset slightly so we don't hit center of disk
        Vector3f direction(0, -1, 0);
        Float tHit;
        Ray r(origin, direction);
        SurfaceInteraction isect;
        disk->Intersect(r, &tHit, &isect);
        bsdf = ARENA_ALLOC(arena, BSDF)(isect);
        createBSDF(bsdf, arena);
    }

    for (int k = 0; k < CHI2_RUNS; ++k) {
        /* Randomly pick an outgoing direction on the hemisphere */
        Point2f sample {rng.UniformFloat(), rng.UniformFloat()};
        Vector3f woL = CosineSampleHemisphere(sample);
        Vector3f wo = bsdf->LocalToWorld(woL);

        FrequencyTable(bsdf, wo, rng, sampleCount, thetaRes, phiRes,
                       frequencies);

        IntegrateFrequencyTable(bsdf, wo, sampleCount, thetaRes, phiRes,
                                expFrequencies);

        std::string filename = StringPrintf("/tmp/chi2test_%s_%03i.m",
                                            description, ++index);
        DumpTables(frequencies, expFrequencies, thetaRes, phiRes,
                   filename.c_str());

        auto result =
            Chi2Test(frequencies, expFrequencies, thetaRes, phiRes, sampleCount,
                     CHI2_MINFREQ, CHI2_SLEVEL, CHI2_RUNS);
        EXPECT_TRUE(result.first) << result.second << ", iteration " << k;
    }

    delete[] frequencies;
    delete[] expFrequencies;

    pbrtCleanup();
}
Esempio n. 21
0
void Splitter::sendCueData()
{
    bool cdQuality = disk()->audioFile()->isCdQuality();
    OutFormat *format = OutFormat::currentFormat();

    bool fakeIndex = (format->createCue() and
                      format->preGapType() == OutFormat::PreGapAddToFirstTrack);

    QFile cue(disk()->cueFile());
    cue.open(QFile::ReadOnly);

    int trackNum = 0;
    QByteArray line;
    while (!cue.atEnd())
    {
        line = cue.readLine();
        QString str = QString(line).trimmed();
        QString key = str.section(' ', 0, 0).toUpper();

        if (key == "TRACK")
        {
            trackNum++;
            mProcess->write(line);
            continue;
        }

        if (key == "INDEX")
        {
            int indexNum = str.section(' ', 1, 1).toInt();

            if (fakeIndex && trackNum == 1)
            {
                if (indexNum == 1)
                {
                    if (cdQuality)
                        mProcess->write("  INDEX 01 00:00:00\n");
                    else
                        mProcess->write("  INDEX 01 00:00.000\n");
                }
            }
            else
            {
                CueIndex index(str.section(' ', 2));
                mProcess->write(QString("  INDEX %1 %2\n")
                                .arg(indexNum, 2, 10, QChar('0'))
                                .arg(index.toString(cdQuality))
                                .toLocal8Bit());
            }
            continue;
        }

        if (key == "FILE")
        {
            mProcess->write(line);
            continue;
        }

    }

    cue.close();
}
Esempio n. 22
0
int
main(int argc,char **argv)
{
	puts("Copyright (c) 2001-2008 pinc Software.");

	char *toolName = argv[0];
	if (argc < 2 || !strcmp(argv[1],"--help"))
	{
		printUsage(toolName);
		return -1;
	}

	while (*++argv)
	{
		char *arg = *argv;
		if (*arg == '-')
		{
			while (*++arg && isalpha(*arg))
			{
				switch (*arg)
				{
					case 'i':
						gDoNotCheckIndex = true;
						break;
					case 'f':
						gDoNotCheckForFiles = true;
						break;
					case 'a':
						gCheckAll = true;
						break;
				}
			}
		}
		else
			break;
	}

	char *attribute = argv[0];
	if (!gCheckAll && attribute == NULL)
	{
		printUsage(toolName);
		return -1;
	}

	dev_t device = dev_for_path(".");
	if (device < B_OK)
	{
		fprintf(stderr,"Could not find device for current location: %s\n",strerror(device));
		return -1;
	}

	fs_info info;
	if (fs_stat_dev(device,&info) < B_OK)
	{
		fprintf(stderr,"Could not get stats for device: %s\n",strerror(errno));
		return -1;
	}

	Disk disk(info.device_name);
	status_t status;
	if ((status = disk.InitCheck()) < B_OK)
	{
		fprintf(stderr,"Could not open device or file \"%s\": %s\n",info.device_name,strerror(status));
		return -1;
	}

	if (disk.ValidateSuperBlock() < B_OK)
	{
		fprintf(stderr,"The disk's superblock is corrupt!\n");
		return -1;
	}

	Directory *indices = (Directory *)Inode::Factory(&disk,disk.Indices());
	if (indices == NULL || (status = indices->InitCheck()) < B_OK)
	{
		fprintf(stderr,"  Could not get indices directory: %s!\n",indices ? strerror(status) : "not found/corrupted");
		delete indices;
		return -1;
	}
	BPlusTree *tree;
	if (indices->GetTree(&tree) < B_OK || tree->Validate() < B_OK)
	{
		fprintf(stderr,"  Indices B+Tree seems to be corrupt!\n");
		delete indices;
		return -1;
	}

	block_run run;

	if (gCheckAll)
	{
		putchar('\n');
		collectFiles(disk);

		char name[B_FILE_NAME_LENGTH];
		while (indices->GetNextEntry(name,&run) >= B_OK)
			checkIndex(disk,name,run,false);
	}
	else if (indices->FindEntry(attribute,&run) == B_OK)
		checkIndex(disk,attribute,run,true);
	else
		fprintf(stderr,"  Could not find index directory for \"%s\"!\n",attribute);

	delete indices;

	gHashtable.MakeEmpty(HASH_EMPTY_NONE,HASH_EMPTY_FREE);

	return 0;
}
Esempio n. 23
0
/*

  Print the program options.

  \param name : Program name.
  \param badparam : Bad parameter name.
  \param ipath: Input image path.
  \param opath : Output image path.
  \param user : Username.

 */
void usage(const char *name, const char *badparam, std::string ipath, std::string opath, std::string user)
{
  fprintf(stdout, "\n\
Read an image from the disk (Klimt.pgm), crop a rectangular area\n\
and save the cropped image on the disk (Klimt_cropped.pgm).\n\
\n\
SYNOPSIS\n\
  %s [-i <input image path>] [-o <output image path>]\n\
     [-h]\n						      \
", name);

  fprintf(stdout, "\n\
OPTIONS:                                               Default\n\
  -i <input image path>                                %s\n\
     Set image input path.\n\
     From this path read \"ViSP-images/Klimt/Klimt.pgm\"\n\
     image.\n\
     Setting the VISP_INPUT_IMAGE_PATH environment\n\
     variable produces the same behaviour than using\n\
Esempio n. 24
0
int main(int argc, char **argv) {
	
	FILE *fpt;
	char packages[50] = " ";
	fpt = popen ("dpkg --list|wc -l", "r");
	fgets(packages, 50, fpt);
	pclose(fpt);

	struct sysinfo info;
	sysinfo(&info);
	struct passwd *p;
	uid_t uid=1000; // 1000 user uid number.

	if ((p = getpwuid(uid)) == NULL) 
		perror("getpwuid() error");
 
    if (argc >= 2) {
        int c;
        while ((c = getopt(argc, argv, "h")) != -1) {
            switch (c) {
                case 'h':
                default:
                    help();
                    break;
    }
  }
}
{
        char computer[256];
        struct utsname uts;
        time_t timeval;       
        (void)time(&timeval);      
        if(gethostname(computer, 255) != 0 || uname(&uts) < 0) {  
                fprintf(stderr, "Could not get host information, so f**k off\n");
                exit(1);
         }
time_t now;
printf(Z2"     █████                                     █████\n"Z0);   
printf(Z2"  ▒███ ▒██████▒   ▓███████████████████▓   ▓██████ ▓███"Z0);printf(CLR_GRY"\t\t\t\t\t   ╔═══════════╗\n"CLR_RST); 
printf(Z2" ▓██▓       █████████▓             ▓████████▓       ███"Z0);printf(CLR_GRY"\t\t\t\t\t   ║"CLR_RST);printf(Z3" Uptime    ");printf(CLR_GRY"║ %02ld:%02ld:%02ld\n"CLR_RST, info.uptime/3600, info.uptime%3600/60,info.uptime%60);
printf(Z2" ██▓         ███ ▓█    █                ▒███         ██"Z0);printf(CLR_GRY"▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀\n"CLR_RST);
printf(Z2"  ███      ▒███ ███▓  ██                  ███       ███"Z0);printf(Z3" ▄███████▄    ▄████████    ▄████████  ████████▄  ███    █▄     ▄████████ \n"Z0);
printf(Z2"   ████   ▓██▓   ▒▒                        ███    ████"Z0);printf(Z3"\t███    ███   ███    ███   ███    ███ ███   ▀███ ███    ███   ███    ███ \n"Z0);
printf(Z2"    ▓███████▓ ███▒  █▒                      ████████▒"Z0);printf(Z3"\t███    ███   ███    ███   ███    ███ ███    ███ ███    ███   ███    █▀  \n"Z0);
printf(Z2"      █████▒                                 ██████"Z0);printf(Z3"\t███    ███   ███    ███  ▄███▄▄▄▄██▀ ███    ███ ███    ███   ███        \n"Z0);
printf(Z2"      ▒███▒                                   ▓███"Z0);printf(Z3"    ▀█████████▀  ▀███████████ ▀▀███▀▀▀▀▀   ███    ███ ███    ███ ▀███████████ \n"Z0);
printf(Z2"      ███▒                                     ███▒"Z0);printf(Z3"\t███          ███    ███ ▀███████████ ███    ███ ███    ███          ███ \n"Z0);
printf(Z2"     ▒██▒          ██▓███      ▒██▓▓██          ███"Z0);printf(Z3"\t███          ███    ███   ███    ███ ███   ▄███ ███    ███    ▄█    ███ \n"Z0);
printf(Z2"     ▒██                █      ▒█               ▒██"Z0);printf(Z3"    ▄████▀        ███    █▀    ███    ███ ████████▀  ████████▀   ▄████████▀  \n"Z0);
printf(Z2"      ██▒              ██       █▓              ███"Z0);printf(CLR_GRY"▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀");printf(Z3"███");printf(CLR_GRY"▀▀▀▀"CLR_RST);;printf(Z3"███"Z0);printf(CLR_GRY"▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀\n"CLR_RST);
printf(Z2"      ███             ▒█        ▒█          ██  ███"Z0);printf(CLR_GRY"\t\t\t\t\t   ║"CLR_RST);printf(Z3" OS        "Z0);printf(CLR_GRY"║ %s\n"CLR_RST, uts.sysname);   
printf(Z2"      ▓██                                ▓█    ▒██▒"Z0);printf(CLR_GRY"\t\t\t\t\t   ║"CLR_RST);printf(Z3" User      "Z0);printf(CLR_GRY"║ %s\n"CLR_RST, p->pw_name);// getlogin());  
printf(Z2"       ██▓       ▒█    ▒█████████     █     ██████"Z0);printf(CLR_GRY"\t\t\t\t\t   ║"CLR_RST);printf(Z3" Hostname  "Z0);printf(CLR_GRY"║ %s\n"CLR_RST, computer);  
printf(Z2"       ███      ██▒      ███████      ▓█▒      ██▓"Z0);printf(CLR_GRY"\t\t\t\t\t   ║"CLR_RST);printf(Z3" Kernel    "Z0);printf(CLR_GRY"║ %s\n"CLR_RST, uts.release);  
printf(Z2"        ████▓  ███    ▓█▒ ▒███  ██▒   ▒██   ▓████"Z0);printf(CLR_GRY"\t\t\t\t\t   ║"CLR_RST);printf(Z3" Hardware  "Z0);printf(CLR_GRY"║ %s\n"CLR_RST, uts.machine);  
printf(Z2"           ████████▒ ▒██▒   █   ▓█▓  ▓████████▒"Z0);printf(CLR_GRY"\t\t\t\t\t\t   ║"CLR_RST);printf(Z3" Shell     "Z0);printf(CLR_GRY"║ %s\n"CLR_RST, p->pw_shell);  
printf(Z2"             ██ ▓████  ▒█   █   █▒  ████▒ ██"Z0);printf(CLR_GRY"\t\t\t\t\t\t   ║"CLR_RST);printf(Z3" Userdir   "Z0);printf(CLR_GRY"║ %s\n"CLR_RST, p->pw_dir);  
printf(Z2"          █▓    █▒ ███     ██▓    ▒███ █▓    ██"Z0);printf(CLR_GRY"\t\t\t\t\t\t   ║"CLR_RST);printf(Z3" Packages  "Z0);printf(CLR_GRY"║ %s"CLR_RST, packages);   
printf(Z2"       ▒█     █▒   ▓███▓███   ██▓███▓█   █▓     █"Z0);disk();   
printf(Z2"            ▒▓   █    ███▒     ▒███   ▓▓   █"Z0);printf(CLR_GRY"\t\t\t\t\t\t   ║"CLR_RST);printf(Z3" Date      "Z0);printf(CLR_GRY"║ %s"CLR_RST, ctime(&timeval));  
printf(Z2"               ▒█       █████████       █"Z0);printf(CLR_GRY"\t\t\t\t\t\t   ╚═══════════╝\n"CLR_RST);      
printf(Z2"              ▒▒                         ▓"Z0);          
printf("\n");
  }
}                              
Esempio n. 25
0
void trydisk(void)
{
	if(mousex>10 && mousex<XSIZE-10 && mousey>10 && mousey<YSIZE-10)
		disk(mousex,mousey,8);
}
Esempio n. 26
0
void Splitter::parseOut()
{
    Track *track = disk()->track(0);

    bool deletePregap = !OutFormat::currentFormat()->createCue();
    char c;
    QByteArray buf;

    while(mProcess->waitForReadyRead(-1))
    {
        while (mProcess->read(&c, 1))
        {
            // .......................................
            if (c == '\n')
            {
                if (buf.contains(": error:"))
                {
                    error(track, QString::fromLocal8Bit(buf.mid(17)));
                    return;
                }
                buf = "";
            }


            // .......................................
            else if (c == '%')
            {
                bool ok;
                int percent = buf.right(3).trimmed().toInt(&ok);
                if (!ok)
                    continue;


                // Splitting [/home/user/inDir/input.wav] (10:00.000) --> [/home/user/outDir/tmp-15196-00000.wav] (0:00.440) : 100% OK

                QString pattern = "[" +  mWorkDir + "/" + mFilePrefix;
                QString sbuf = QString::fromLocal8Bit(buf);
                int n = sbuf.indexOf(pattern, disk()->audioFileName().length() + 20);

                if (n < 0 && sbuf.length() < n + pattern.length() + 4)
                {
                    qWarning() << "I can't parse" << sbuf;
                    continue;
                }

                QString fileName = sbuf.mid(n + 1, + pattern.length() - 1 + 4 + 4); // -1 for leading "[", 4 for 4 digits tracknum, 4 - file ext ".wav"

                int trackNum = fileName.mid(fileName.length() - 8, 4).toInt(&ok);

                if (!ok)
                {
                    qWarning() << "I can't parse" << sbuf;
                    continue;
                }



                if (trackNum > disk()->count())
                {
                    error(disk()->track(0), tr("The number of tracks is higher than expected."));
                    return;
                }

                track = (trackNum == 0) ? disk()->preGapTrack() : disk()->track(trackNum - 1);
                mPreGapExists = mPreGapExists || (trackNum == 0);

                emit trackProgress(track, Track::Splitting, percent);

                if (percent == 100)
                {
                    if (trackNum == 0 && deletePregap)
                        deleteFile(fileName);
                    else
                        emit trackReady(track, fileName);
                }
            }

            // .......................................
            else
            {
                buf += c;
            }

            //std::cerr << c;
        }
    }
}
Esempio n. 27
0
int main(int argc, char* argv[]) {
    Options opt;
    pbrtInit(opt);

    // number of monte carlo estimates
    // const int estimates = 1;
    const int estimates = 10000000;

    // radiance of uniform environment map
    const double environmentRadiance = 1.0;

    fprintf(stderr,
            "outgoing radiance from a surface viewed\n"
            "straight on with uniform lighting\n\n"
            "    uniform incoming radiance = %.3f\n"
            "    monte carlo samples = %d\n\n\n",
            environmentRadiance, estimates);

    CreateBSDFFunc BSDFFuncArray[] = {
        createLambertian,
        createOrenNayar0,
        createOrenNayar20,
        [](BSDF* bsdf) -> void
        { createMicrofacet(bsdf, true, true, 0.5, 0.5); },
        [](BSDF* bsdf) -> void
        { createMicrofacet(bsdf, false, true, 0.5, 0.5); },
        [](BSDF* bsdf) -> void
        { createMicrofacet(bsdf, true, true, 0.2, 0.1); },
        [](BSDF* bsdf) -> void
        { createMicrofacet(bsdf, false, true, 0.2, 0.1); },
        [](BSDF* bsdf) -> void
        { createMicrofacet(bsdf, true, true, 0.15, 0.25); },
        [](BSDF* bsdf) -> void
        { createMicrofacet(bsdf, false, true, 0.15, 0.25); },
        [](BSDF* bsdf) -> void
        { createMicrofacet(bsdf, true, true, 0.33, 0.033); },
        [](BSDF* bsdf) -> void
        { createMicrofacet(bsdf, false, true, 0.33, 0.033); },
        [](BSDF* bsdf) -> void
        { createMicrofacet(bsdf, true, false, 0.5, 0.5); },
        [](BSDF* bsdf) -> void
        { createMicrofacet(bsdf, false, false, 0.5, 0.5); },
        [](BSDF* bsdf) -> void
        { createMicrofacet(bsdf, true, false, 0.2, 0.1); },
        [](BSDF* bsdf) -> void
        { createMicrofacet(bsdf, false, false, 0.2, 0.1); },
        [](BSDF* bsdf) -> void
        { createMicrofacet(bsdf, true, false, 0.15, 0.25); },
        [](BSDF* bsdf) -> void
        { createMicrofacet(bsdf, false, false, 0.15, 0.25); },
        [](BSDF* bsdf) -> void
        { createMicrofacet(bsdf, true, false, 0.33, 0.033); },
        [](BSDF* bsdf) -> void
        { createMicrofacet(bsdf, false, false, 0.33, 0.033); },
        [](BSDF* bsdf) -> void
        { createFresnelBlend(bsdf, true, true, 0.15, 0.25); },
        [](BSDF* bsdf) -> void
        { createFresnelBlend(bsdf, false, true, 0.15, 0.25); },
        [](BSDF* bsdf) -> void
        { createFresnelBlend(bsdf, true, false, 0.15, 0.25); },
        [](BSDF* bsdf) -> void
        { createFresnelBlend(bsdf, false, false, 0.15, 0.25); },
    };

    const char* BSDFFuncDescripArray[] = {
        "Lambertian",
        "Oren Nayar (sigma 0)",
        "Oren Nayar (sigma 20)",
        "Beckmann (roughness 0.5, sample visible mf area)",
        "Trowbridge-Reitz (roughness 0.5, sample visible mf area)",
        "Beckmann (roughness 0.2/0.1, sample visible mf area)",
        "Trowbridge-Reitz (roughness 0.2/0.1, sample visible mf area)",
        "Beckmann (roughness 0.15/0.25, sample visible mf area)",
        "Trowbridge-Reitz (roughness 0.15/0.25, sample visible mf area)",
        "Beckmann (roughness 0.33/0.033, sample visible mf area)",
        "Trowbridge-Reitz (roughness 0.33/0.033, sample visible mf area)",
        "Beckmann (roughness 0.5, traditional sample wh)",
        "Trowbridge-Reitz (roughness 0.5, traditional sample wh)",
        "Beckmann (roughness 0.2/0.1, traditional sample wh)",
        "Trowbridge-Reitz (roughness 0.2/0.1, traditional sample wh)",
        "Beckmann (roughness 0.15/0.25, traditional sample wh)",
        "Trowbridge-Reitz (roughness 0.15/0.25, traditional sample wh)",
        "Beckmann (roughness 0.33/0.033, traditional sample wh)",
        "Trowbridge-Reitz (roughness 0.33/0.033, traditional sample wh)",
        "Fresnel Blend Beckmann (roughness 0.15/0.25, sample visible mf area)",
        "Fresnel Blend Trowbridge-Reitz (roughness 0.15/0.25, sample visible mf area)",
        "Fresnel Blend Beckmann (roughness 0.15/0.25, traditional sample wh)",
        "Fresnel Blend Trowbridge-Reitz (roughness 0.15/0.25, traditional sample wh)",
    };

    GenSampleFunc SampleFuncArray[] = {
        Gen_Sample_f,
        // CO        Gen_CosHemisphere,
        // CO        Gen_UniformHemisphere,
    };

    const char* SampleFuncDescripArray[] = {
        "BSDF Importance Sampling",
        // CO        "Cos Hemisphere",
        // CO        "Uniform Hemisphere",
    };

    int numModels = sizeof(BSDFFuncArray) / sizeof(BSDFFuncArray[0]);
    int numModelsDescrip =
        sizeof(BSDFFuncDescripArray) / sizeof(BSDFFuncDescripArray[0]);
    int numGenerators = sizeof(SampleFuncArray) / sizeof(SampleFuncArray[0]);
    int numGeneratorsDescrip =
        sizeof(SampleFuncDescripArray) / sizeof(SampleFuncDescripArray[0]);

    if (numModels != numModelsDescrip) {
        fprintf(stderr,
                "BSDFFuncArray and BSDFFuncDescripArray out of sync!\n");
        exit(1);
    }

    if (numGenerators != numGeneratorsDescrip) {
        fprintf(stderr,
                "SampleFuncArray and SampleFuncDescripArray out of sync!\n");
        exit(1);
    }

    // for each bsdf model
    for (int model = 0; model < numModels; model++) {
        BSDF* bsdf;

        // create BSDF which requires creating a Shape, casting a Ray
        // that hits the shape to get a SurfaceInteraction object.
        {
            Transform t = RotateX(-90);
            bool reverseOrientation = false;
            ParamSet p;

            std::shared_ptr<Shape> disk(
                new Disk(new Transform(t), new Transform(Inverse(t)),
                         reverseOrientation, 0., 1., 0, 360.));
            Point3f origin(
                0.1, 1, 0);  // offset slightly so we don't hit center of disk
            Vector3f direction(0, -1, 0);
            Float tHit;
            Ray r(origin, direction);
            SurfaceInteraction isect;
            disk->Intersect(r, &tHit, &isect);
            bsdf = ARENA_ALLOC(arena, BSDF)(isect);
            (BSDFFuncArray[model])(bsdf);
        }

        // facing directly at normal
        Vector3f woL = Normalize(Vector3f(0, 0, 1));
        Vector3f wo = bsdf->LocalToWorld(woL);
        // was bsdf->dgShading.nn
        const Normal3f n = Normal3f(bsdf->LocalToWorld(Vector3f(0, 0, 1)));

        // for each method of generating samples over the hemisphere
        for (int gen = 0; gen < numGenerators; gen++) {
            double redSum = 0.0;

            const int numHistoBins = 10;
            double histogram[numHistoBins][numHistoBins];
            for (int i = 0; i < numHistoBins; i++) {
                for (int j = 0; j < numHistoBins; j++) {
                    histogram[i][j] = 0;
                }
            }
            int badSamples = 0;
            int outsideSamples = 0;

            int warningTarget = 1;
            for (int sample = 0; sample < estimates; sample++) {
                Vector3f wi;
                Float pdf;
                Spectrum f;

                // sample hemisphere around bsdf, wo is fixed
                (SampleFuncArray[gen])(bsdf, wo, &wi, &pdf, &f);

                double redF = spectrumRedValue(f);

                // add hemisphere sample to histogram
                Vector3f wiL = bsdf->WorldToLocal(wi);
                float x = Clamp(wiL.x, -1.f, 1.f);
                float y = Clamp(wiL.y, -1.f, 1.f);
                float wiPhi = (atan2(y, x) + Pi) / (2.0 * Pi);
                float wiCosTheta = wiL.z;
                bool validSample = (wiCosTheta > 1e-7);
                if (wiPhi < -0.0001 || wiPhi > 1.0001 || wiCosTheta > 1.0001) {
                    // wiCosTheta can be less than 0
                    fprintf(stderr, "bad wi! %.3f %.3f %.3f, (%.3f %.3f)\n",
                            wiL[0], wiL[1], wiL[2], wiPhi, wiCosTheta);
                } else if (validSample) {
                    int histoPhi = (int)(wiPhi * numHistoBins);
                    if (histoPhi == numHistoBins)
                      --histoPhi;
                    int histoCosTheta = (int)(wiCosTheta * numHistoBins);
                    if (histoCosTheta == numHistoBins)
                      --histoCosTheta;
                    assert(histoPhi >= 0 && histoPhi < numHistoBins);
                    assert(histoCosTheta >= 0 && histoCosTheta < numHistoBins);
                    histogram[histoCosTheta][histoPhi] += 1.0 / pdf;
                }

                if (!validSample) {
                    outsideSamples++;
                } else if (pdf == 0.f || std::isnan(pdf) || redF < 0 ||
                           std::isnan(redF)) {
                    if (badSamples == warningTarget) {
                        fprintf(stderr,
                                "warning %d, bad sample %d! "
                                "pdf: %.3f, redF: %.3f\n",
                                warningTarget, sample, pdf, redF);
                        warningTarget *= 10;
                    }
                    badSamples++;
                } else {
                    // outgoing radiance estimate =
                    //   bsdf * incomingRadiance * cos(wi) / pdf
                    redSum += redF * environmentRadiance * AbsDot(wi, n) / pdf;
                }
            }
            int goodSamples = estimates - badSamples;

            // print results
            fprintf(stderr,
                    "*** BRDF: '%s', Samples: '%s'\n\n"
                    "wi histogram showing the relative weight in each bin\n"
                    "  all entries should be close to 2pi = %.5f:\n"
                    "  (%d bad samples, %d outside samples)\n\n"
                    "                          phi bins\n",
                    BSDFFuncDescripArray[model], SampleFuncDescripArray[gen],
                    Pi * 2.0, badSamples, outsideSamples);
            double totalSum = 0.0;
            for (int i = 0; i < numHistoBins; i++) {
                fprintf(stderr, "  cos(theta) bin %02d:", i);
                for (int j = 0; j < numHistoBins; j++) {
                    fprintf(stderr, " %5.2f", histogram[i][j] * numHistoBins *
                                                  numHistoBins / goodSamples);
                    totalSum += histogram[i][j];
                }
                fprintf(stderr, "\n");
            }
            fprintf(stderr,
                    "\n  final average :  %.5f (error %.5f)\n\n"
                    "  radiance = %.5f\n\n",
                    totalSum / goodSamples, totalSum / goodSamples - Pi * 2.0,
                    redSum / goodSamples);
        }
    }

    pbrtCleanup();
    return 0;
}