Example #1
0
 LinkLinuxImpl(bool server, LinkGroupRef group, LoggerRef logger, const std::string& dir, const std::string& name, const std::string& alias) :
     Link(),
     logger(logger),
     group(group),
     pin(PipePosix::create(server, true, logger, dir, name + getExt(server), alias + getExt(server) + "In")),
     pout(PipePosix::create(server, false, logger, dir, name + getExt(!server), alias + getExt(!server) + "Out")),
     name(name),
     alias(alias) {
     TRACE_OBJECT_NEW("LinkLinuxImpl");
 }
Example #2
0
int main(int argc, const char* argv[])
{
	char fileExt[64];
	BGFunction* functions;

	if (argc != 3)
	{
		printf("usage: <input file> <output file>\nExample: bind_generator foo.h out.cs");
		return 0;
	}

	functions = parseHeader(argv[1]);

	if (!getExt(fileExt, argv[2]))
	{
		printf("Unable to find file extension for %s", argv[2]);
		return -1;
	}

	// This is a bit hacky but like this because of extra params handling in tundra. Hopefully
	// this can be fixed by sending is some proper commandline args instead

	if (!strcmp(fileExt, ".c"))
	{
		if (!generate_exp(argv[2], functions))
			return -1;
	}
	else if (!strcmp(fileExt, ".cs"))
	{
		generate_cs(argv[2], functions);
	}

	return 0;
}
Example #3
0
int segmenter_can_segment(segmenter_t * S, const char *filename)
{
  char *ext = getExt(filename);
  int ok = (strcasecmp(ext, "mp3") == 0) || (strcasecmp(ext, "ogg") == 0);
  mc_free(ext);
  return ok;
}
Example #4
0
int segmenter_create(segmenter_t * S)
{
  // assert that this segment isn't opened.
  int reopen=0;
  if (segmenter_stream(S) != NULL) {
    reopen=1;
    segmenter_close(S);
  }

  char *filename = S->segment.filename;
  char *ext = getExt(filename);
  if (ext == NULL) {
    S->last_result = SEGMENTER_ERR_FILETYPE;
    return S->last_result;
  } else if (strcasecmp(ext, "mp3") == 0) {
    mc_free(ext);
    return split_mp3(S);
  } else if (strcasecmp(ext, "ogg") == 0) {
    mc_free(ext);
    return split_ogg(S);
  } else {
    mc_free(ext);
    S->last_result = SEGMENTER_ERR_FILETYPE;
    return S->last_result;
  }

  if (reopen) {
    segmenter_open(S);
  }
}
Example #5
0
bool gIsProject(const char *path) {

	/* FIXME - checks too weak */

	if (getExt(path) == ".gprj" && gDirExists(path))
		return 1;
	return 0;
}
Example #6
0
/* \brief check if file is a Assimp supported file */
int _glhckFormatAssimp(const char *file)
{
    int ret;
    CALL(0, "%s", file);
    ret = (aiIsExtensionSupported(getExt(file))?RETURN_OK:RETURN_FAIL);
    RET(0, "%d", ret);
    return ret;
}
Example #7
0
static void ShowBuildTime(char *trgPath)
{
	trgPath = makeFullPath(trgPath);

	if(existDir(trgPath))
	{
		autoList_t *paths = lss(trgPath);
		char *path;
		uint index;

		sortJLinesICase(paths);

		foreach(paths, path, index)
		{
			char *relPath = changeRoot(strx(path), trgPath, NULL);

			if(existDir(path))
			{
				cout("------------------------ %s\n", relPath);
			}
			else if(
				!_stricmp("exe", getExt(path)) ||
				!_stricmp("dll", getExt(path)) ||
				!_stricmp("exe_", getExt(path)) ||
				!_stricmp("dll_", getExt(path))
				)
			{
				ShowBuildTime_File(path, relPath);
			}
			else
			{
				char *hash = md5_makeHexHashFile(path);

				hash[16] = '\0';

				cout("    %s     %s\n", hash, relPath);

				memFree(hash);
			}
			memFree(relPath);
		}
		releaseDim(paths, 1);
	}
Example #8
0
void MessageBinaryImpl::setFile(std::string& nFile)
{
    filename = nFile;

    std::string ext = getExt(filename);

    if(ext == "png")
        this->setHeaderElement("Content-Type", "image/png");
    else if(ext == "jpg" || ext == "jpeg" || ext == "jpe")
        this->setHeaderElement("Content-Type", "image/jpeg");
}
Example #9
0
void AsyncFileDevice::Engine::write(Sys::AltAsyncFile *file,Packet<uint8,Sys::AsyncFile::WriteExt> packet1,FilePosType off)
 {
  auto packet=packet1.getPtr();
  
  auto packet2=packet1.pushExt<WriteWork>(file,packet,off);

  auto ext=packet2.getExt();
  
  packet2.pushExt<WorkBase *>(ext);

  proc.process(ext);
 }
Example #10
0
//=============================================================================
Fl_Image * openTextureFile(string strFileName)
{
	Fl_Image *img = NULL;
	try
	{
		if (getExt(strFileName) == ".jpg" || getExt(strFileName) == ".jpeg")
			img = new Fl_JPEG_Image(strFileName.c_str());
		else if (getExt(strFileName) == ".png")
			img = new Fl_PNG_Image(strFileName.c_str());
		else
			img = new Fl_BMP_Image(strFileName.c_str());
	}
	catch(std::bad_alloc x)
	{
		mem_alloc_failure(__FILE__, __LINE__);
		return NULL;
	}

	//  return if no image
	if (img->d() == 0 || img->h() == 0 || img->w() == 0)
	{
		delete img;
		return NULL;
	}

	//  downsize if image is too big
	if (img->h() > 4096 || img->w() > 4096)
	{
		cout << ("Downsizing image to maximum of 4096 a side");
		int h = img->h() >= img->w() ? 4096 : 4096 * img->h() / img->w();
		int w = img->w() >= img->h() ? 4096 : 4096 * img->w() / img->h();
		Fl_Image *img2 = img->copy(w, h);
		delete img;
		img = img2;
	}
	
	return img;
}
Example #11
0
void FileName::setBase( const char * base )
{
   String path = getPath();
   String ext = getExt();
   
   char buf[ FILENAME_MAX_LENGTH ];
   if( base )
   {
      AssertFatal( ( ( strlen( path.c_str() ) + strlen( base ) + strlen( ext.c_str() ) ) < FILENAME_MAX_LENGTH ), "Filename too long." );
      sprintf( buf, "%s%s.%s", path.c_str(), base, ext.c_str() );
   }
   else
      sprintf( buf, "%s.%s", path.c_str(), ext.c_str() );
   rep = buf;
}
Example #12
0
const char *cue_entry_vfile(cue_entry_t * ce)
{
  if (ce->vfile == NULL) {
    cue_t *c = (cue_t *) ce->sheet;
    char *name = (char *)mc_malloc(10 + strlen(cue_entry_title(ce)) + 4);
    char *ext = getExt(cue_audio_file(c));
    sprintf(name, "%02d - %s.%s", ce->tracknr, ce->title, ext);
    int i,N;
    for(i=0,N=strlen(name);i<N;i++) {
      if (name[i]=='/') { name[i]=' '; }
    }

    mc_free(ext);
    ce->vfile = name;
  }
  return ce->vfile;
}
Example #13
0
void ConfigData::saveTo(QString name)
{
    QFile file(name);
    file.open(QIODevice::WriteOnly);

    QTextStream stream(&file);
    stream.setCodec("UTF-8");

    stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n";
    stream << "<config>\n";
    stream << "\t<language>"+QString::number(getLanguage())+"</language>\n";
    stream << "\t<multiThread>"+QString::number(getMultiThread())+"</multiThread>\n";
    stream << "\t<autoFinishedDelete>"+QString::number(getAutoFinishedDelete())+"</autoFinishedDelete>\n";
    stream << "\t<ext>"+QString::number(getExt())+"</ext>\n";
    stream << "\t<rewrite>"+QString::number(getRewrite())+"</rewrite>\n";
    stream << "</config>";
}
Example #14
0
static char *GetProjFile(void)
{
	autoList_t *files = lsFiles(".");
	char *file;
	uint index;

	eraseParents(files);

	foreach(files, file, index)
		if(!_stricmp("vcproj", getExt(file)))
			break;

	errorCase(!file); // ? not found

	file = strx(file);
	releaseDim(files, 1);
	return file;
}
Example #15
0
bool Convertor::initialize()
{
    mInput.open(mInputFile.c_str());
    mOutput.open(mOutputFile.c_str());

    if (!mInput || !mOutput)
    {
    	std::cerr << "Error cannot open/write file(s)..." << std::endl;
    	return false;
    }

    mOutput << "#include \"" << mClassName << "." << getExt() << "\"" << std::endl << std::endl;

    mLineCount = 0;
    mCommented = false;
    mStruct = false;
    return true;
}
Example #16
0
/* =============================================================================
 =============================================================================== */
int C3DSceneMgr::createTexture(string strFileName, int &width, int &height, int iTxMode)
{
	if (strFileName == "") //  Return from the function if no file name was passed in
		return -1;
	if (!fileexists(strFileName))
		return -1;

	//  Load the image and store the data
	int textureID = -1;
	if (getExt(strFileName) == ".dds")
	{
		DDS_IMAGE_DATA	*pDDSImageData = NULL;
		if ((pDDSImageData = loadDDSTextureFile(strFileName)) != NULL)
		{
			textureID = createTextureDDS(pDDSImageData);
			height = pDDSImageData->sizeY;
			width = pDDSImageData->sizeX;
		}
		else	//  case where worldwind wraps jpegs in dds files
		{
			Fl_RGB_Image *img = new Fl_JPEG_Image(strFileName.c_str());
			if (img->d() == 0)
				return -1;
			width = img->w();
			height = img->h();
			const unsigned char *pData = (const unsigned char *) img->data()[0];
			textureID = createTexture(pData, width, height, GL_RGB, GL_RGB, iTxMode);
			delete img;
		}
	}
	else
	{
		Fl_Image * img = openTextureFile(strFileName);
		if (img == NULL)
			return -1;
		width = img->w();
		height = img->h();
		const unsigned char *pData = (const unsigned char *) img->data()[0];
		textureID = createTexture(pData, width, height, img->d() == 4 ? GL_RGBA : GL_RGB, GL_RGBA, iTxMode);
		delete img;
	}

	return textureID;
}
Example #17
0
int main(void){
    int Q, n, x, y, x1, y1;
    char ev;
    while(scanf("%d %d %d", &X, &Y, &P), X){
        memset(c, 0, sizeof(c));
        scanf("%d", &Q);
        while(Q--){
            scanf(" %c", &ev);
            if(ev == 'A'){
                scanf("%d %d %d", &n, &x, &y);
                x++; y++; set(x, y, n);
            }else{
                scanf("%d %d %d %d", &x, &y, &x1, &y1);
                x++; y++; x1++; y1++;
                printf("%d\n", getExt(x, y, x1, y1) * P);
            }
        }
        printf("\n");
    }
    return 0;
}
Example #18
0
    IAudioBuffer* cAudioManager::createBuffer(const char* filename)
    {
		if(!Initialized) return NULL;

		cAudioMutexBasicLock lock(Mutex);
		cAudioString path = fromUTF8(filename);
		cAudioString ext = getExt(path);
		IAudioDecoderFactory* factory = getAudioDecoderFactory(toUTF8(ext));

		if(!factory) {
			getLogger()->logError("AudioManager", "Failed to create Audio Buffer: No decoder could be found for (.%s).", toUTF8(ext));
			return NULL;
		}

		for(size_t i=0; i<dataSourcePriorityList.size(); ++i)
		{
			const cAudioString dataSourceName = dataSourcePriorityList[i].second;
			IDataSourceFactory* dataFactory = datasourcemap[dataSourceName];
			if(dataFactory)
			{
				IDataSource* source = dataFactory->CreateDataSource(filename, false);
				if(source && source->isValid())
				{
					IAudioDecoder* decoder = factory->CreateAudioDecoder(source);
					source->drop();

                    IAudioBuffer* buffer = CAUDIO_NEW cAudioBuffer(decoder);

					if(buffer != NULL)
						return buffer;

					//if(source)
					//	source->drop();

					return NULL;
				}
			}
		}
		return NULL;
    }
Example #19
0
    IAudioSource* cAudioManager::create(const char* name, const char* filename, bool stream)
    {
		if(!Initialized) return NULL;

		cAudioMutexBasicLock lock(Mutex);
		cAudioString audioName = safeCStr(name);
		cAudioString path = safeCStr(filename);
		cAudioString ext = getExt(path);
		IAudioDecoderFactory* factory = getAudioDecoderFactory(ext.c_str());

		if(!factory) {
			getLogger()->logError("AudioManager", "Failed to create Audio Source (%s): No decoder could be found for (.%s).", audioName.c_str(), ext.c_str());
			return NULL;
		}

		for(size_t i=0; i<dataSourcePriorityList.size(); ++i)
		{
			const cAudioString dataSourceName = dataSourcePriorityList[i].second;
			IDataSourceFactory* dataFactory = datasourcemap[dataSourceName];
			if(dataFactory)
			{
				IDataSource* source = dataFactory->CreateDataSource(filename, stream);
				if(source && source->isValid())
				{
					IAudioDecoder* decoder = factory->CreateAudioDecoder(source);
					source->drop();

					IAudioSource* audio = createAudioSource(decoder, audioName, dataSourceName);
					if(audio != NULL)
						return audio;

					if(source)
						source->drop();

					return NULL;
				}
			}
		}		
		return NULL;
    }
Example #20
0
void loadAllImages(const std::string &path)
{
    DIR *dirp = opendir(path.c_str());
    struct dirent* dp;
    
    std::vector<std::string> fileNames;
    while ((dp = readdir(dirp)) != NULL){
        if (getExt(dp->d_name) == "jpg") {
            fileNames.push_back(std::string(dp->d_name));
        }
    }
    
    std::sort(fileNames.begin(), fileNames.end());
    
    for(size_t i=0;i<fileNames.size();i++){
        unsigned char* rgbdata;
        int width,height;
        readJPEG(path + fileNames[i], rgbdata, width, height);
        write(1,rgbdata,width*height*3);
        free(rgbdata);
    }
}
Example #21
0
bool gIsPatch(const char *path) {
	if (getExt(path) == ".gptc")
		return 1;
	return 0;
}
Example #22
0
//*--------------------------------------------------------------------------*//
//* MAIN                                                                MAIN *//
//*--------------------------------------------------------------------------*//
int main(int argc, char* argv[])
{  
   // Initialise random number generator
	srandom(time(NULL));
	clock_t t0 = clock();
   
   // Print header
   printHeader();
	
	// Read options
   Options uo = parseCommandLine(argc,argv);
   if(!uo.noHybrid)
   {
      if(uo.funcGroupVec[AROM] && uo.funcGroupVec[LIPO])
      {
         uo.funcGroupVec[HYBL] = true;
      }
      if(uo.funcGroupVec[HDON] && uo.funcGroupVec[HACC])
      {
         uo.funcGroupVec[HYBH] = true;
      }
   }
   std::cerr << uo.print() << std::endl;
   
   if (uo.version)
   {
		printHeader();
		exit(0);
	}
   
	if (uo.help)
   {
		printUsage();
		exit(0);
	}
	
	// Db file and pharmacophore out are mandatory elements
	if (uo.dbInpFile.empty())
   {
		mainErr("Missing database file. This is a required option (-d).");
	}
   
	if (uo.pharmOutFile.empty() && uo.molOutFile.empty() && uo.scoreOutFile.empty())
   {
		mainErr("No output file defined. So there is actually no use to compute anything at all.");
	}	
   
	if ((uo.pharmOutFile.empty() && uo.scoreOutFile.empty()) && !uo.molOutFile.empty())
   {
		mainErr("No file defined to write pharmacophore information.");
	}	
	
	if (uo.refInpFile.empty() && uo.pharmOutFile.empty() && uo.molOutFile.empty() && !uo.scoreOutFile.empty())
   {
		mainErr("Only score file requested when no reference is given. Unable to generate this output.");
	}	
  
	// Reference variables
   Pharmacophore refPharm;
   refPharm.clear();
   std::string refId;
   double refVolume(0.0);
   int refSize(0);
	int exclSize(0);
  
	// Database variables
   std::vector<Result*> resList;
   Pharmacophore dbPharm;
   std::string dbId;
   double dbVolume(0.0);
   int dbSize(0);
  
   //----------------------------------------------------------------------------
	//...(A).. Process the reference
   //----------------------------------------------------------------------------
  
	if (!uo.refInpFile.empty())
	{
      //-------------------------------------------------------
      //...(1).. get reference pharmacophore
      //-------------------------------------------------------
    
      if (uo.refInpType == UNKNOWN)
      {
         std::string ext(getExt(uo.refInpFile));
         if (ext == ".phar")
         {
            uo.refInpType = PHAR;
         }
         else 
         {
            uo.refInpType = MOL;
         }
      }
		
      if (uo.refInpType == MOL)
      {
         OpenBabel::OBMol m;
         OpenBabel::OBConversion* reader = new OpenBabel::OBConversion();
         reader->SetInFormat(reader->FormatFromExt(uo.refInpFile.c_str()));
         if (!reader->Read(&m, uo.refInpStream))
         {
            mainErr("Unable to read reference molecule");
         }
         calcPharm(&m, &refPharm, uo);
         refId = m.GetTitle();
         delete reader;
         reader = NULL;
      }
      else if (uo.refInpType == PHAR)
      {
         PharmacophoreReader* reader = new PharmacophoreReader();
         refPharm = reader->read(uo.refInpStream, refId);
         if (refPharm.empty())
         {
            mainErr("Error reading reference pharmacophore");
         }
         delete reader;
         reader = NULL;
      }
      else
      {
         mainErr("Unknown format of reference molecule.");
      }
		
      //-------------------------------------------------------
		//...(2).. process reference pharmacophore
      //-------------------------------------------------------
		
      if (uo.merge)
      {
         pharMerger.merge(refPharm);
      }
    
      refSize = refPharm.size();
      for (unsigned int i(0); i < refSize; ++i)
		{
         if (refPharm[i].func == EXCL)
         {
				// extract overlap with exclusion spheres
				for (unsigned int j(0); j < refPharm.size(); ++j)
            {
					if (refPharm[j].func != EXCL)
               {
						refVolume -= VolumeOverlap(refPharm[i], refPharm[j], !uo.noNormal);
					}
				}
				exclSize++;
			}
         else
         {
				// add point self-overlap
				refVolume += VolumeOverlap(refPharm[i], refPharm[i], !uo.noNormal);
			}
      }
      
      if(!uo.isQuiet)
      {
         std::cerr << "Reference pharmacophore " << refId << std::endl;
         std::cerr << "   number of points:            " << refSize - exclSize << std::endl;
			std::cerr << "   number of exclusion spheres: " << exclSize << std::endl;
         std::cerr << "   totalvolume:                 " << refVolume << std::endl;
      }
	}

   //----------------------------------------------------------------------------
	//...(B).. Process the database file
   //----------------------------------------------------------------------------

   // DB files
   if (uo.dbInpType == UNKNOWN)
   {
      std::string ext(getExt(uo.dbInpFile));
      if (ext==".phar")
      {
         uo.dbInpType = PHAR;
      }
      else
      {
         uo.dbInpType = MOL;
      }
   }
	
	// local storage of the rotation matrix
	SiMath::Matrix rotMat(3,3,0.0);

   unsigned int molCount(0);
   
   OpenBabel::OBConversion* molReader = NULL;
	PharmacophoreReader* pharmReader = NULL;
   
   if (uo.dbInpType == PHAR)
   {
      pharmReader = new PharmacophoreReader();
   }
   else if (uo.dbInpType == MOL)
   {
      molReader = new OpenBabel::OBConversion();
      molReader->SetInFormat(molReader->FormatFromExt(uo.dbInpFile.c_str()));
      molReader->SetInStream(uo.dbInpStream);
   }
   else
   {
      mainErr("Unknown format of db file.");
   }

   bool done(false);
   OpenBabel::OBMol m;
   while (!done)
   {	
      dbPharm.clear();
      m.Clear();

      if (uo.dbInpType == MOL)
      {
         if (!molReader->Read(&m))
         {
            done = true;
            break;
         }
         else
         {
            calcPharm(&m, &dbPharm, uo);
            dbId = m.GetTitle();
         }
      }
      else
      {
         if (uo.dbInpStream->eof())
         {
            done = true;
            break;
         }
         else
         {
            dbPharm = pharmReader->read(uo.dbInpStream, dbId);
         }
      }
      if (dbPharm.empty())
      {
         continue;
      }

      ++molCount;
      if (!uo.isQuiet )
      {
         if ((molCount % 10) == 0)
         {
            std::cerr << "." << std::flush;
         }
         if ((molCount % 500) == 0)
         {
            std::cerr << molCount << std::endl << std::flush;
         }
      }

			
      if (uo.merge)
      {
         pharMerger.merge(dbPharm);
      }
      
      if (uo.refInpFile.empty())
      {
         if (!(uo.isQuiet))
         {
            printProgress(molCount);
         } 
         if( !uo.pharmOutFile.empty())
         {
            uo.pharmOutWriter->write(dbPharm, uo.pharmOutStream, dbId);
         }
         continue;
      }

      //-------------------------------------------------------
      //...(1).. Alignment
      //-------------------------------------------------------
      
      dbSize = dbPharm.size();
      dbVolume = 0.0;
      for (unsigned int i(0); i < dbSize; ++i) 
      {
         if (dbPharm[i].func == EXCL)
         {
            continue;
         }
         dbVolume += VolumeOverlap(dbPharm[i], dbPharm[i], !uo.noNormal);
      }
			
      // Create a result structure
      Result res;
      res.refId           = refId;
      res.refVolume       = refVolume;
      res.dbId            = dbId;
      res.dbVolume        = dbVolume;
      res.overlapVolume   = 0.0;
      res.exclVolume      = 0.0;
      res.resMol          = m;
      res.resPharSize     = 0;
			
      if (uo.scoreOnly)
      {
         FunctionMapping funcMap(&refPharm, &dbPharm, uo.epsilon);
         PharmacophoreMap fMap = funcMap.getNextMap();
         double volBest(-9999.999);
         
         // loop over all reference points
         while (!fMap.empty())
         {
            double newVol(0.0);
            double exclVol(0.0);
            for (PharmacophoreMap::iterator itP = fMap.begin(); itP != fMap.end(); ++itP) 
            {
               if ((itP->first)->func == EXCL)
               {
                  exclVol += VolumeOverlap((itP->first), (itP->second), !uo.noNormal);					
               }
               else if (((itP->first)->func == (itP->second)->func ) || 
                       (((itP->first)->func == HYBH || 
                         (itP->first)->func == HDON || 
                         (itP->first)->func == HACC) 
                     && ((itP->second)->func == HDON || 
                         (itP->second)->func == HACC ||
                         (itP->second)->func == HYBH))
                     || (((itP->first)->func == HYBL || 
                          (itP->first)->func == AROM || 
                          (itP->first)->func == LIPO)
                      && ((itP->second)->func == AROM || 
                          (itP->second)->func == LIPO || 
                          (itP->second)->func == HYBL)))
               {
                  newVol += VolumeOverlap((itP->first),(itP->second), !uo.noNormal);
               }
            }
					
            if ((newVol - exclVol) > volBest)
            {
               res.resPhar.clear();
               res.resPharSize = 0;
               for (PharmacophoreMap::iterator itP = fMap.begin(); itP != fMap.end(); ++itP) 
               {
                  // add point to resulting pharmacophore
                  PharmacophorePoint p(itP->second);
                  (res.resPhar).push_back(p);
                  ++res.resPharSize;
               }						
               res.overlapVolume = newVol;
               res.exclVolume = exclVol;
               volBest = newVol - exclVol;
            }
            // get the next map
            fMap.clear();
            fMap = funcMap.getNextMap();
         }
      }
      else
      {
         FunctionMapping funcMap(&refPharm, &dbPharm, uo.epsilon);
         PharmacophoreMap fMap = funcMap.getNextMap();
         PharmacophoreMap bestMap;
				
         // default solution
         SolutionInfo best;
         best.volume = -999.9;
         
         // rotor is set to no rotation 
         best.rotor.resize(4);
         best.rotor = 0.0;
         best.rotor[0] = 1.0;
				
         double bestScore = -1000;
         int mapSize(fMap.size());
         int maxSize = mapSize - 3;
				
         while (!fMap.empty())
         {
            int msize = fMap.size();
            
            // add the exclusion spheres to the alignment procedure
            if (uo.withExclusion)
            {
               for (unsigned int i(0); i < refSize ; ++i)
               {
                  if (refPharm[i].func != EXCL)
                  {
                     continue;
                  }
                  for (unsigned int j(0); j < dbSize; ++j)
                  {
                     if (dbPharm[j].func == EXCL)
                     {
                        continue;
                     }
                     fMap.insert(std::make_pair(&(refPharm[i]), &(dbPharm[j])));
                  }
               }
            }
					
            // Only align if the expected score has any chance of being larger 
            // than best score so far
            if ((msize > maxSize)
            && (((double) msize / (refSize - exclSize + dbSize - msize)) > bestScore))
            {
               Alignment align(fMap);
               SolutionInfo r = align.align(!uo.noNormal);

               if (best.volume < r.volume)
               {
                  best = r;
                  bestScore = best.volume / (refVolume + dbVolume - best.volume);
                  bestMap = fMap;
                  mapSize = msize;
               }
            }
            else
            {
               // Level of mapping site to low
               break;
            }
	
            if (bestScore > 0.98)
            {
               break;
            }
					
            // Get the next map
            fMap.clear();
            fMap = funcMap.getNextMap();
         }
				
         // Transform the complete pharmacophore and the molecule towards the 
         // best alignment
         rotMat = quat2Rotation(best.rotor);
         positionPharmacophore(dbPharm, rotMat, best);
         positionMolecule(&res.resMol, rotMat, best);
				
         // Update result
         res.info = best;

         // Compute overlap volume between exlusion spheres and pharmacophore 
         // points
         for (int i(0); i < refSize; ++i) 
         {
            if (refPharm[i].func != EXCL)
            {
               continue;
            }
            for (int j(0); j < dbSize; ++j)
            {
               res.exclVolume += VolumeOverlap(refPharm[i], dbPharm[j], !uo.noNormal);
            }
         }
				
         // make copy of the best map and compute the volume overlap
         for (PharmacophoreMap::iterator itP = bestMap.begin(); itP != bestMap.end(); ++itP) 
         {
            if(((itP->first)->func == EXCL) || ((itP->second)->func == EXCL))
            { 
               continue; 
            }
					
            // compute overlap
            res.overlapVolume += VolumeOverlap(itP->first, itP->second, !uo.noNormal);
					
            // add point to resulting pharmacophore
				PharmacophorePoint p(itP->second);
            (res.resPhar).push_back(p);
            ++res.resPharSize;
         }
      }
			
      // update scores
      res.info.volume = res.overlapVolume - res.exclVolume;
      if (res.info.volume > 0.0)
      {
         res.tanimoto = res.info.volume / (res.refVolume + res.dbVolume - res.info.volume);
         res.tversky_ref = res.info.volume / res.refVolume;
         res.tversky_db = res.info.volume / res.dbVolume;
      }

      switch (uo.rankby) 
      {
         case TANIMOTO:
            res.rankbyScore = res.tanimoto;
            break;
         case TVERSKY_REF:
            res.rankbyScore = res.tversky_ref;
            break;
         case TVERSKY_DB:
            res.rankbyScore = res.tversky_db;
            break;
      }

      //-------------------------------------------------------
      //...(5).. Generate output
      //-------------------------------------------------------
      if (uo.cutOff != 0.0)
      {
         if (res.rankbyScore < uo.cutOff)
         {
            continue;
         }
      }

      if (uo.best != 0)
      {
         addBest(res, uo, resList);
      }
      else 
      { 
         if (!uo.molOutFile.empty())
         { 
            logOut(&res, uo);
         }
         if (!uo.pharmOutFile.empty())
         {
            logPharmacophores(&res, uo);
         }
         if (!uo.scoreOutFile.empty())
         {
            logScores(&res, uo);
         }
      }
   }

   if (molReader)
   {
      delete molReader;
      molReader = NULL;
   }
   if (pharmReader)
   {
      delete pharmReader;
      pharmReader = NULL;
   }
  
   //----------------------------------------------------------------------------
   //...(C).. Process best list (if defined)
   //----------------------------------------------------------------------------

   if (uo.best != 0)
   {
      std::vector<Result*>::iterator itR;
      for (itR = resList.begin(); itR != resList.end(); ++itR) 
      {
         Result* res(*itR);
         if (!uo.molOutFile.empty())
         {
            logOut(res, uo);
         }
         if (!uo.pharmOutFile.empty())
         {
            logPharmacophores(res, uo);
         }
         if (!uo.scoreOutFile.empty())
         {
            logScores(res, uo);
         }
         delete res;
      }
   }

   // done processing database
   if (!uo.isQuiet)
   {
      if (uo.refInpFile.empty())
      {
         std::cerr << std::endl;
         std::cerr << "Processed " << molCount << " molecules";
         double tt = (double)(clock() - t0 )/CLOCKS_PER_SEC;
         std::cerr << " in " << tt << " seconds (";
         std::cerr << molCount/tt << " molecules per second)." << std::endl;
      }
      else
      {
         std::cerr << std::endl;
         std::cerr << "Processed " << molCount << " molecules" << std::endl;
         double tt = (double)(clock() - t0 )/CLOCKS_PER_SEC;
         std::cerr << molCount << " alignments in " << tt << " seconds (";
         std::cerr << molCount/tt << " alignments per second)." << std::endl;
      }
   }
	
   exit(0);

}
Example #23
0
static int mp3splt(segmenter_t * S)
{
  char *ext = getExt(S->segment.filename);

  //log_debug("mp3splt_split: entered");

  mc_free(S->memory_block);
  S->size = -1;
  S->memory_block = NULL;
#ifndef SEGMENT_USING_FILE
  FILE *f = open_memstream((char **)&S->memory_block, &S->size);
#endif

  int begin_offset_in_hs = S->segment.begin_offset_in_ms / 10;
  int end_offset_in_hs = -1;
  if (S->segment.end_offset_in_ms >= 0) {
    end_offset_in_hs = S->segment.end_offset_in_ms / 10;
  }
  // Creating state
  splt_state *state = mp3splt_new_state(NULL);
  //log_debug("new state");
  mp3splt_find_plugins(state);
  //log_debug("plugins found");

  // Set split path and custom name
  mp3splt_set_path_of_split(state, "/tmp");
  //log_debug("split path set");
  mp3splt_set_int_option(state, SPLT_OPT_OUTPUT_FILENAMES, SPLT_OUTPUT_CUSTOM);
  //log_debug("custom split set");

  // Set filename to split and pretend mode, for memory based splitting
  mp3splt_set_filename_to_split(state, S->segment.filename);
  //log_debug("filename to split set");
#ifndef SEGMENT_USING_FILE
  mp3splt_set_int_option(state, SPLT_OPT_PRETEND_TO_SPLIT, SPLT_TRUE);
  mp3splt_set_pretend_to_split_write_function(state, mp3splt_writer, (void *)f);
  //log_debug("pretend split and write function set");
#endif

  // Create splitpoints
  splt_point *point = mp3splt_point_new(begin_offset_in_hs, NULL);
  mp3splt_point_set_type(point, SPLT_SPLITPOINT);
#ifdef SEGMENT_USING_FILE
  char buf[20];
  sprintf(buf, "mp3cue%09d", ++splitnr);
  mp3splt_point_set_name(point, buf);
#endif
  mp3splt_append_splitpoint(state, point);

  splt_point *skip = mp3splt_point_new(end_offset_in_hs, NULL);
  mp3splt_point_set_type(skip, SPLT_SKIPPOINT);
  mp3splt_append_splitpoint(state, skip);
  //log_debug("split points set");

  // Append cuesheet tags and merge with existing
  {
    splt_tags *tags = mp3splt_tags_new(NULL);

    char *title = S->segment.title;
    char *artist = S->segment.artist;
    char *album = S->segment.album;
    char *performer = S->segment.album_artist;
    char year[20];
    sprintf(year, "%d", S->segment.year);
    char *comment = S->segment.comment;
    char *genre = S->segment.genre;
    char track[20];
    sprintf(track, "%d", S->segment.track);

    mp3splt_read_original_tags(state);
    //log_debug("original tags read");

    mp3splt_tags_set(tags, SPLT_TAGS_ORIGINAL, "true", NULL);
    //log_debug("SPLT_TAGS_ORIGINAL set");
    mp3splt_tags_set(tags,
         SPLT_TAGS_TITLE, title,
         SPLT_TAGS_ARTIST, artist,
         SPLT_TAGS_ALBUM, album,
         SPLT_TAGS_PERFORMER, performer,
         SPLT_TAGS_YEAR, year,
         SPLT_TAGS_COMMENT, comment, SPLT_TAGS_GENRE, genre, SPLT_TAGS_TRACK, track, NULL);
    //log_debug("tags set");
    mp3splt_append_tags(state, tags);
    //log_debug("tag appended");
  }

  // split the stuff
  int error = SPLT_OK;
  error = mp3splt_split(state);
  //log_debug("split done");
  mp3splt_free_state(state);
  //log_debug("state freeed");
  log_debug2("mp3splt_split: result=%d", error);

#ifndef SEGMENT_USING_FILE
  fclose(f);
  mc_take_control(S->memory_block, S->size);
  //log_debug("memory file closed");
#endif

  if (error == SPLT_OK_SPLIT || error == SPLT_OK_SPLIT_EOF) {
#ifdef SEGMENT_USING_FILE
    char fn[250];
    sprintf(fn, "/tmp/%s.%s", buf, ext);
    FILE *f = fopen(fn, "rb");
    FILE *g = open_memstream((char **)&S->memory_block, &S->size);
    int size;
    char fbuf[10240];
    while ((size = fread(fbuf, 1, 10240, f)) > 0) {
      fwrite(fbuf, size, 1, g);
    }
    fclose(f);
    fclose(g);
    unlink(fn);
#endif
    mc_free(ext);
    return SEGMENTER_OK;
  } else {
    mc_free(ext);
    return SEGMENTER_ERR_CREATE;
  }
}
Example #24
0
int ogg (int   argc,
         char *argv[])
{

    GstElement *pipeline, *source, *demuxer, *decodera, *decoderv , *conv, *sinka , *sinkv , *queuea, *queuev, *volume, *gamma , *videobalance;
    GstBus *bus;

    /* Initialisation */
    gst_init (&argc, &argv);
    double vol=1;
    double gam=1.0;
    double sat=1;
    double cont=1;
    double br=0;
    bool ascii=false;

    int  i;
//gestion des éléments arg[i] initialisation des options
    for(i=1; i<argc; i++) {
        if(strstr (argv[i], "volume")!=NULL) {
            vol=(double)atof(getExt(argv[i])+1);
        }
        else if(strstr (argv[i], "gamma")!=NULL) {
            gam=(double)atof(getExt(argv[i])+1);
        }
        else if(strstr (argv[i], "saturation")!=NULL) {
            sat=(double)atof(getExt(argv[i])+1);
        }
        else if(strstr (argv[i], "contrast")!=NULL) {
            cont=(double)atof(getExt(argv[i])+1);
        }
        else if(strstr (argv[i], "brightness")!=NULL) {
            br=(double)atof(getExt(argv[i])+1);
        }
        else if(strstr (argv[i], "ascii")!=NULL) {
            ascii=true;
        }
        else if(strstr (argv[i], "start")!=NULL) {
            search=(atoi(getExt(argv[i])+1));
        }
        else if(strstr (argv[i], "info")!=NULL) {
            tag(argc,argv);
        }
        else if(strstr (argv[i], "options")!=NULL) {
            printf("volume=[0.0-10.0]\ngamma=[0.0-10.0]\nsaturation=[0.0-2.0]\ncontrast=[0.0-2.0]\nbrightness=[-1.0-1.0]\n");
        }
    }


    loop = g_main_loop_new (NULL, FALSE);

    /* Verification des arguments d'entree */
    if (argc < 2) {
        g_printerr ("Usage: %s <Ogg/Vorbis filename>\n", argv[3]);
        return -1;
    }

    /* Creation des elements gstreamer */
    pipeline = gst_pipeline_new ("video-player");
    source   = gst_element_factory_make ("filesrc",       "file-source");
    demuxer  = gst_element_factory_make ("oggdemux",      "ogg-demuxer");
    queuea  = gst_element_factory_make ("queue",      "queue-audio");
    queuev  = gst_element_factory_make ("queue",      "queue-video");
    decodera  = gst_element_factory_make ("vorbisdec",     "vorbis-decoder");
    decoderv  = gst_element_factory_make ("theoradec",     "theora-decoder");
    conv     = gst_element_factory_make ("audioconvert",  "converter");
    sinka     = gst_element_factory_make ("autoaudiosink", "audio-output");
    if(!ascii) sinkv     = gst_element_factory_make ("xvimagesink", "video-output");
    else sinkv     = gst_element_factory_make ("aasink", "video-output");
    volume     = gst_element_factory_make ("volume", "option1");
    gamma     = gst_element_factory_make ("gamma", "option2");
    videobalance     = gst_element_factory_make ("videobalance", "option3");



    if (!pipeline || !source || !demuxer || !queuea || !queuev || !videobalance || !gamma || !volume || !decodera || !decoderv || !conv || !sinka || !sinkv) {
        g_printerr ("One element could not be created. Exiting.\n");
        return -1;
    }


    /* Mise en place du pipeline */
    /* on configurer le nom du fichier a l'element source */
//configuration des valeurs des éléments options
    g_object_set (G_OBJECT (source), "location", argv[1], NULL);
    g_object_set(G_OBJECT(volume), "volume",vol, NULL);
    g_object_set(G_OBJECT(gamma), "gamma",gam, NULL);
    g_object_set(G_OBJECT(videobalance), "saturation",sat, NULL);
    g_object_set(G_OBJECT(videobalance), "contrast",cont, NULL);
    g_object_set(G_OBJECT(videobalance), "brightness",br, NULL);

//printf("source: %s",argv[1]);

    /* on rajoute une gestion de messages */
    bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
    gst_bus_add_watch (bus, bus_call, pipeline);//on passe ici en paramètre le pipeline et non loop car on veut pouvoir interagir avec dans bus_call
    gst_object_unref (bus);




    /* on rajoute tous les elements dans le pipeline */
    gst_bin_add_many (GST_BIN (pipeline),
                      source, demuxer , queuea , decodera, conv, volume, sinka, queuev , decoderv, gamma, videobalance, sinkv , NULL);

    /* On relie les elements entre eux */
    gst_element_link (source, demuxer);
    gst_element_link_many (queuev, decoderv, gamma , videobalance , /*conv,*/ sinkv, NULL);
    gst_element_link_many (queuea, decodera , conv, volume, sinka, NULL);
    g_signal_connect (demuxer, "pad-added", G_CALLBACK (on_pad_added), queuea);
    g_signal_connect (demuxer, "pad-added", G_CALLBACK (on_pad_added), queuev);

    /* passage a l'etat "playing" du pipeline */
    g_print ("Lecture de : %s\n", argv[1]);

    gst_element_set_state (pipeline, GST_STATE_PLAYING);

    /* Iteration */
    g_print ("En cours...\n");
    g_main_loop_run (loop);



    /* En dehors de la boucle principale, on nettoie proprement */
    g_print ("Arret de la lecture\n");
    gst_element_set_state (pipeline, GST_STATE_NULL);
    g_print ("Suppression du pipeline\n");
    gst_object_unref (GST_OBJECT (pipeline));
    return 0;
}
Example #25
0
bool DesignMng::readCommand(string cmd){
	try {
        
        if(verboseMode){
            cout << "[" << name << "]$ " << cmd << endl;
            addToHistoryLog(cmd);
            if (cmd.size()){
                commandlog.push_back(cmd);
                poscmdlog = commandlog.size();
            }
        }
        
        vector<string> words;
        
        // Parser, analyzing tokens
        int inicio=0, fim=0;
        bool insideaspas=false, ok=false;
        
        for (int c=0; c < cmd.size(); ++c){
            
            if (cmd[c] != ' ')
                fim = c;
            
            if (insideaspas)
                fim = fim-1;
            
            if ((c == cmd.size()-1 && cmd[cmd.size()-1] != ' ') || (cmd[c] == ' ' && !insideaspas && fim-inicio >= 0))
                ok = true;
            
            if (ok){
                string tmp = cmd.substr(inicio,fim-inicio+1);
                words.push_back(tmp);
                ok = false;
                inicio = c+1;
            }
            switch (cmd[c]){
                case '"':
                    if (!insideaspas)
                        inicio = c+1;
                    insideaspas = !insideaspas;
                    break;
                case ' ':
                    if (!insideaspas)
                        inicio = c+1;
                    break;
            }
        }
        // tokens are separated and inserted in vector 'words'
        int tmp;
        if (words.size() != 0){
            switch (getCommandCode(words)){
                    
                case NEW_DESIGN:{
                    delete circuit;
                    delete placer;
                    delete rules;
                    delete autocell;
                    delete router;
                    
                    circuit = new Circuit();
                    placer = new Placer();
                    rules = new Rules();
                    autocell = new AutoCell();
                    router = new Router();
                    circuit->setRules(rules);
                    placer->setCircuit(circuit);
                    router->setCircuit(circuit);
                    
                    setName(words[2].c_str());
                }
                    break;
                    
                case NEW_CELL:{
                    CellNetlst tmp;
                    tmp.setName(words[2]);
                    circuit->insertCell(tmp);
                    }
                    break;
                    
                    /****  LOAD - 6  ****/
                case LOAD_PROJECT:
                    cout << "-> Loading project from file: " << words[2] << endl;
                    verboseMode=0;
                    run(words[2]);
                    verboseMode=1;
                    break;
                    
                case LOAD_TECHNOLOGY:
                    cout << "-> Loading technology from file: " << words[2] << endl;
                    rules->readRules(words[2]);
                    break;
                    
                case LOAD_NETLIST:{
                    string tipo=upcase(getExt(words[2]));
                    cout << "-> Loading cells netlist from file: " << words[2] << endl;
                    if(tipo=="V"){
                        Verilog vlog;
                        if(!vlog.readFile(words[2], *circuit))
                            throw AstranError("Could not read verilog file: " + words[2]);
                    }else {//if(tipo=="SP" || tipo="LIB"){
                        Spice spice;
                        spice.readFile(words[2], *circuit, false);
                    }
                }
                    break;
                    
                case LOAD_LAYOUTS:
                {
                    cout << "-> Loading LEF library: " << words[2] << endl;
                    Lef lef;
                    lef.readFile(words[2], *circuit, false);
                }
                    break;
                    
                case LOAD_PLACEMENT:{
                    string tipo=upcase(getExt(words[2]));
                    cout << "-> Loading placement from file: " << words[2] << endl;
                    if(tipo=="PL"){
                        placer->readBookshelfPlacement(words[2]);
                    }else if(tipo=="MPP")
                        placer->readMangoParrotPlacement(words[2]);
                    else
                        throw AstranError("File extension not supported" + getExt(words[2]));
                }
                    break;
                    
                case LOAD_ROUTING:
                    cout << "-> Loading routing from file: " << words[2] << endl;
                    router->readRoutingRotdl(words[2]);
                    break;
                    
                    /****  SAVE - 7  ****/
                case SAVE_PROJECT:
                    cout << "-> Saving project to file: " << words[2] << endl;
                    saveProjectConfig(words[2], removeExt(words[2]));
                    break;
                    
                case SAVE_TECHNOLOGY:
                    rules->saveRules(words[2]);
                    break;
                    
                case SAVE_NETLIST:{
                    cout << "-> Saving spice netlist to file: " << words[2] << endl;
                    Spice spice;
                    spice.saveFile(words[2], *circuit);
                }
                    break;
                    
                case SAVE_LAYOUTS:{
                    cout << "-> Saving layouts to file: " << words[2] << endl;
                    Lef lef;
                    lef.saveFile(words[2], *circuit);
                }
                    break;
                    
                case SAVE_PLACEMENT:
                    cout << "-> Saving placement to file: " << words[2] << endl;
                    placer->writeBookshelfFiles(removeExt(getFileName(words[2])), true);
                    break;
                    
                case SAVE_ROUTING:
                    cout << "-> Saving routing to file: " << words[2] << endl;
                    router->saveRoutingRotdl(words[2]);
                    break;
                    
                case SAVE_HISTORY:
                    cout << "-> Saving script to file: " << words[2] << endl;
                    saveHistory(words[2]);
                    break;
                    
                    /****  IMPORT - 2  ****/
                case IMPORT_NETLIST:{
                    cout << "-> Importing netlist from file: " << words[2] << endl;
                    Spice spice;
                    spice.readFile(words[2], *circuit, true);
                }
                    break;
                    
                case IMPORT_LEF:{
                    cout << "-> Importing LEF library: " << words[2] << endl;
                    Lef lef;
                    lef.readFile(words[2], *circuit, true);
                }
                    break;
                    
                    /****  EXPORT - 3  ****/
                case EXPORT_LAYOUT:{
                    string tipo=upcase(getExt(words[3]));
                    string filename=words[3];
                    if(circuit->getLayout(upcase(words[2]))){
                        if(tipo=="GDS"){
                            rules->saveGDSIILayerTable(getPath(filename)+"GDSIILTable.txt");
                            cout << "-> Saving layout " << words[2] << " to file: " << filename << endl;
                            Gds g(filename);
                            char tmp[20] = "                   ";
                            strcpy(tmp, words[2].substr(0,19).c_str());
                            g.open(); 
                            g.generateHeader(1);
                            g.generateLibrary();
                            g.generateLibname(tmp);
                            g.generateUnits();
                            g.generateStruct();
                            g.generateStructname(tmp);
                            //Insert Boxes
                            list <Box>::iterator layer_it;
                            map <layer_name , list<Box> >::iterator layers_it; // iterador das camadas		
                            for (layers_it = circuit->getLayout(words[2])->layers.begin(); layers_it != circuit->getLayout(words[2])->layers.end(); layers_it++) {
                                if ( !layers_it->second.empty() ) {
                                    int layer = strToInt(rules->getGDSIIVal(layers_it->first));
                                    for ( layer_it = layers_it->second.begin(); layer_it != layers_it->second.end(); layer_it++ ){
                                        long int x1 = 2*layer_it->getX1();
                                        long int y1 = 2*layer_it->getY1();
                                        long int x2 = 2*layer_it->getX2();
                                        long int y2 = 2*layer_it->getY2();
                                        if(x2-x1!=0 & y2-y1!=0){
                                            g.generateBox(layer, x1, y1, x2, y2);
//                                            cout << layer << "-"<< x1 << "-" << y1 << "-" << x2 << "-" << y2 << endl;
                                            g.generateEndelement();
                                        }
                                    }
                                }
                            }
                            
                            list<Label>::iterator labels_it;
                            for (labels_it = circuit->getLayout(words[2])->labels.begin(); labels_it != circuit->getLayout(words[2])->labels.end(); labels_it++){
                                strcpy(tmp, labels_it->text.c_str());
                                g.generateLabel(strToInt(rules->getGDSIIVal(MET1)), 2*labels_it->pt.getX(), 2*labels_it->pt.getY(), tmp);
                                g.generateEndelement();
                            }
                            
                            
                            g.generateEndStruct();
                            g.generateEndLibrary();
                        }else if(tipo=="C2C"){
                            Cif cifOut(removeExt(filename)+".cif", *rules);
                            cifOut.cellCif(*(circuit->getLayouts()), words[2]);
                            cifOut.cif2Cadence(name,  words[2]);
                        }else if(tipo=="CIF"){
                            Cif cifOut(filename, *rules);
                            cifOut.cellCif(*(circuit->getLayouts()), words[2]);
                        }else 
                            throw AstranError("Unknown file type: " + tipo);			
                    }else
                        throw AstranError("Cell not found: " + words[2]);
                }
                    break;
                    
                case EXPORT_CELLSIZES:
                    cout << "-> Writing Cell Sizes to file: " << words[2] << endl;
                    circuit->writeCellSizesFile(words[2]);
                    break;
                    
                case EXPORT_PLACEMENT:
                    cout << "-> Saving placement to file: " << words[2] << endl;
                    placer->writeCadende(words[2]);
                    break;
                    
                case READ:
                    run(words[1]);
                    break;
                    
                    /****  PLACE - 7  ****/
                case PLACE_TERMINALS:
                    placer->placeInterfaceTerminals();
                    break;
                    
                case PLACE_FPLACE:{
                    cout << "-> Writing bookshelf files for placement..." << endl;
                    placer->writeBookshelfFiles("test", false);
                    string cmd = "\"" + placerFile + "\"" + " test > temp.log";
                    cout << "-> Calling placement tool: " << cmd << endl;
                    FILE *x = _popen(cmd.c_str(), "r");
                    if ( x == NULL ) 
                        throw AstranError("Could not execute: " + cmd);
                    _pclose(x);
                    cout << "-> Placing Cells..." << endl;
                    placer->readBookshelfPlacement("test_mp.pl");
                }
                    break;
                    
                case PLACE_GETWL:
                    placer->checkWL();
                    break;
                    
                case PLACE_INSTANCE:{
                    CLayout *tmp=circuit->getLayout(upcase(words[2]));
                    if(!tmp)
                        throw AstranError("Could not find Layout: " + upcase(words[2]));
                    tmp->placeCell(upcase(words[3]), atoi(words[4].c_str()), atoi(words[5].c_str()), atoi(words[6].c_str()), atoi(words[7].c_str()));
                    break;
                }    
                case PLACE_AUTOFLIP:
                    placer->autoFlip();
                    break;
                    
                case PLACE_INCREMENTAL:
                    placer->incrementalPlacement(router, lpSolverFile);
                    break;
                    
                case PLACE_CHECK:
                    placer->checkPlacement();
                    break;
                    
                    /****  ROUTE - 6  ****/
                case ROUTE_ROTDL:
                    router->setup(placer->getHSize(), placer->getVSize(), 3);
                    router->rotdl(rotdlFile);
                    break;
                    
                case ROUTE_PFINDER:
                    router->setup(placer->getHSize(), placer->getVSize(), 3);
                    router->route(atoi(words[2].c_str()));
                    break;
                    
                case ROUTE_OPTIMIZE:
                    router->optimize();
                    break;
                    
                case ROUTE_COMPACT:
                    router->compactLayout(lpSolverFile);
                    break;
                    
                case ROUTE_TEST:
                    router->test(rotdlFile);
                    break;
                    
                case ROUTE_CLEAR:
                    router->getPathfinderRt()->clear();
                    break;
                    
                    /****  PRINT - 4  ****/
                case PRINT_INSTANCE:
                    circuit->printInstance(circuit->getLayout(upcase(words[2])), upcase(words[3]));
                    break;
                    
                case PRINT_CELL:
                    circuit->getCellNetlst(upcase(words[2]))->print();
                    break;
                    
                case PRINT_NET:
                    circuit->printNet(upcase(words[2]));
                    break;
                    
                case PRINT_INTERFACE:
                    circuit->printInterface(upcase(words[2]));
                    break;
                    
                    /****  PREFERENCES - 6  ****/
                case SET_PLACER:
                    if (!fileExist(words[2]))
                        throw AstranError("Could not find file: " + words[2]);
                    
                    placerFile=words[2];
                    cout << "-> Setting placer executable to: " << placerFile << endl;
                    break;
                    
                case SET_ROTDL:
                    if (!fileExist(words[2]))
                        throw AstranError("Could not find file: " + words[2]);
                    
                    rotdlFile=words[2];
                    cout << "-> Setting rotdl executable path to: " << rotdlFile << endl;
                    break;
                    
                case SET_VIEWER:
                    if (!fileExist(words[2]))
                        throw AstranError("Could not find file: " + words[2]);
                    
                    viewerProgram=words[2];
                    cout << "-> Setting viewer executable path to: " << viewerProgram << endl;
                    break;
                    
                case SET_LPSOLVE:
                    if (!fileExist(words[2]))
                        throw AstranError("Could not find file: " + words[2]);
                    
                    lpSolverFile=words[2];
                    cout << "-> Setting lpsolve executable to: " << lpSolverFile << endl;
                    break;
                    
                case SET_LOG:
                    historyFile = words[2];
                    remove(historyFile.c_str());
                    cout << "-> Saving history log to file: " << historyFile << endl;
                    break;
                    
                case SET_VERBOSEMODE:
                    cout << "-> Setting verbose mode = " << words[2] << endl;
                    verboseMode=atoi(words[2].c_str());
                    break;
                    
                    /****  TECHNOLOGY - 8  ****/
                case SET_TECH_NAME:
                    rules->setTechName(words[3].c_str());
                    break;
                    
                case SET_TECH_MLAYERS:
                    rules->setMLayers(words[3].c_str());
                    break;
                    
                case SET_TECH_SOI:
                    rules->setSOI(words[3].c_str());
                    break;
                    
                case SET_TECH_RESOLUTION:
                    rules->setResolution(atoi(words[3].c_str()));
                    break;
                    
                case SET_TECH_RULE:
                    tmp=rules->findRule(words[3].c_str());
                    if (tmp==-1)
                        throw AstranError("Rule not Found: " + words[3]);
                    
                    rules->setRule((rule_name)tmp, atof(words[4].c_str()));
                    break;
                    
                case SET_TECH_CIF:
                    tmp=rules->findLayerName(words[3].c_str());
                    if (tmp==-1)
                        throw AstranError("Layer not Found: " + words[3]);
                    
                    rules->setCIFVal((layer_name)tmp, words[4].c_str());
                    break;
                    
                case SET_TECH_GDSII:
                    tmp=rules->findLayerName(words[3].c_str());
                    if (tmp==-1)
                        throw AstranError("Layer not Found: " + words[3]);
                    
                    rules->setGDSIIVal((layer_name)tmp, words[4].c_str());
                    break;
                    
                case SET_TECH_VALTECH:
                    tmp=rules->findLayerName(words[3].c_str());
                    if (tmp==-1)
                        throw AstranError("Layer not Found: " + words[3]);
                    
                    rules->setTechVal((layer_name)tmp, words[4].c_str());
                    break;
                    
                    /****  CIRCUIT - 8  ****/
                case SET_DESIGNNAME:
                    setName(words[2].c_str());
                    break;
                    
                case SET_GRID:
                    circuit->setHPitch(atof(words[2].c_str()));
                    circuit->setVPitch(atof(words[3].c_str()));
                    break;
                    
                case SET_HGRID:
                    circuit->setHPitch(atof(words[2].c_str()));
                    break;
                    
                case SET_VGRID:
                    circuit->setVPitch(atof(words[2].c_str()));
                    break;
                    
                case SET_HGRID_OFFSET:
                    circuit->setHGridOffset(upcase(words[2].c_str())=="YES"?true:false);
                    break;
                    
                case SET_VGRID_OFFSET:
                    circuit->setVGridOffset(upcase(words[2].c_str())=="YES"?true:false);
                    break;
                    
                case SET_VDDNET:
                    circuit->setVddNet(upcase(words[2].c_str()));
                    break;
                    
                case SET_GNDNET:
                    circuit->setGndNet(upcase(words[2].c_str()));
                    break;
                    
                case SET_ROWHEIGHT:
                    circuit->setRowHeight(atoi(words[2].c_str()));
                    break;
                    
                case SET_SUPPLYSIZE:
                    circuit->setSupplyVSize(atof(words[2].c_str()));
                    break;
                    
                case SET_NWELLPOS:
                    circuit->setnWellPos(atof(words[2].c_str()));
                    break;
                    
                case SET_NWELLBORDER:
                    circuit->setnWellBorder(atof(words[2].c_str()));
                    break;
                    
                case SET_PNSELBORDER:
                    circuit->setpnSelBorder(atof(words[2].c_str()));
                    break;
                    
                case SET_CELLTEMPLATE:
                    circuit->setCellTemplate(words[2].c_str());
                    break;
                    
                    /****  FLOORPLAN - 3  ****/
                case SET_TOPCELL:
                    circuit->setTopCell(upcase(words[2]));
                    break;
                    
                case SET_AREA:
                    placer->setArea(atoi(words[2].c_str()), atof(words[3].c_str()));
                    break;
                    
                case SET_MARGINS:
                    circuit->setMargins(atof(words[2].c_str()), atof(words[3].c_str()), atof(words[4].c_str()), atof(words[5].c_str()));
                    break;
                    
                case CALCPINSPOS:
                    circuit->calculateCellsPins();
                    break;
                    
                    /****  CELLGEN - 9  ****/
                    
                case CELLGEN_SELECT:
                    autocell->selectCell(circuit,upcase(words[2]));
                    break;
                    
                case CELLGEN_AUTOFLOW:
                    autocell->autoFlow(lpSolverFile);
                    break;

                case CELLGEN_FOLD:
                    autocell->calcArea(atoi(words[2].c_str()), atoi(words[3].c_str()));
                    autocell->foldTrans();
                    break;
                    
                case CELLGEN_PLACE:
                    autocell->placeTrans(true, atoi(words[2].c_str()), atoi(words[3].c_str()), atoi(words[4].c_str()), atoi(words[5].c_str()), atoi(words[6].c_str()), atoi(words[7].c_str()), atoi(words[8].c_str()));
                    break;
                    
                case CELLGEN_GETARCCOST:
                    cout << autocell->getRouting()->getArcCost(atoi(words[2].c_str()), atoi(words[3].c_str()));
                    break;
                    
                case CELLGEN_SETARCCOST:
                    cout << autocell->getRouting()->setArcCost(atoi(words[2].c_str()), atoi(words[3].c_str()), atoi(words[4].c_str()));
                    break;
                    
                case CELLGEN_ROUTE:
                    autocell->route(atoi(words[2].c_str()), atoi(words[3].c_str()), atoi(words[4].c_str()), atoi(words[5].c_str()));
                    break;
                    
                case CELLGEN_COMPACT:
                    if(!autocell->compact(lpSolverFile, atoi(words[2].c_str()), atoi(words[3].c_str()), atoi(words[4].c_str()), atoi(words[5].c_str()), atoi(words[6].c_str()), atoi(words[7].c_str()), atoi(words[8].c_str()), atoi(words[9].c_str()), atoi(words[10].c_str()), atoi(words[11].c_str())))
                        throw AstranError("Could not solve the ILP model. Try to adjust the constraints!");                        
                    break;
                    
                    /****  HELP - 2  ****/
                case HELP:
                    for (int i=0; i<NR_COMMANDS; ++i)
                        cout << commands_lst[i].name << endl;
                    cout << "-> Note: For detailed instructions, use command \"HELP <str_Command>\"\n\n";
                    break;
                    
                case HELP_PARAM:
                    for (int i=0; i<NR_COMMANDS; ++i)
                        if (commands_lst[i].name.find(upcase(words[1])) != string::npos)
                            cout << commands_lst[i].name << " - " << commands_lst[i].desc << endl;
                    break;
                    
                case COMMENT:
                    break;
                case EXIT:
                    exit(EXIT_SUCCESS);
                    break;
            }
        }
    } catch (AstranError& e){
        cout << "** ERROR: " << e.what() << endl;
        return false;
    }
    return true;
}
Example #26
0
//----------------------------------------------------------
int ofxDirList::listDir(string directory){
	
    directory = ofToDataPath(directory);

	nameArray.clear();
	pathArray.clear();

    if(directory.length() <= 0)return 0;

    //if the trailing slash was not added - then add it
	if( directory[directory.length()-1] != '/'){
        directory = directory + "/";
	}

	DIR *dir = NULL;
	struct dirent *entry;

    //open the directory
    ofLog(OF_LOG_VERBOSE, "ofxDirList - attempting to open %s", directory.c_str());
    dir = opendir(directory.c_str());

	if(dir == NULL){
		ofLog(OF_LOG_ERROR, "ofxDirList - error opening directory");
		return 0;
	}else{
		ofLog(OF_LOG_VERBOSE, "ofxDirList - success opening directory");
	}

    string entry_name = "";
    string ext = "";
	bool skip = false;

	while ((entry = readdir(dir)) != NULL){

        //turn it into a C++ string
        entry_name = entry->d_name;

        //lets get the length of the string here as we query it again
        int fileLen = entry_name.length();

		if(fileLen <= 0)continue; //if the name is not existant
		if(entry_name[0] == '.')continue; //ignore invisible files, ./ and ../

		//by default we don't skip files unless we are checking extensions
		skip = false;

		if(allowedFileExt.size() > 0){
			//we will skip this files unless it has an allowed extension
			skip = true;
			for(int i = 0; i < (int)allowedFileExt.size(); i++){

				//if the wildecard * has been entered for an ext type then don't check any extensions
				if( allowedFileExt[i] == "*"){ skip = false; break; }


				int extLen = allowedFileExt[i].length();

				//the extension has to be shorter than the filename - simple check
				if(extLen >= fileLen) continue;

                //lets get the ext as lowercase
                ext = strToLower( getExt(entry_name) );

                //if no ext - then skip this ext check
                if( ext == "" )continue;

                //if we find a match then stop checking and approve this file
                if(ext == allowedFileExt[i]){
                    skip = false;
                    break;
                }
			}
		}
		if(skip) continue;

		//finally we store the result
        pathArray.push_back(directory + entry_name);
        nameArray.push_back(entry_name);

		ofLog(OF_LOG_VERBOSE, "ofxDirList - listing %s ", nameArray.back().c_str());
	}
	if(dir != NULL) closedir(dir);

	ofLog(OF_LOG_VERBOSE, "ofxDirList - listed %i files in %s", nameArray.size(), directory.c_str());
	return nameArray.size();
}
Example #27
0
void *requestHandle(void *context)
{

	// Get the arguments
	char 	buffert[PATH_MAX] = {0},
				reqBuf[BUF_REQ] = {0},
				date[64] = {0},
				error[1024] = {0},
				*req_line = NULL,
				*req_token = NULL;

	_rqhd_header 	head;
	_rqhd_req 		req;
	_rqhd_args 		*args = (_rqhd_args*) context;

	struct 	sockaddr_in pin = args->pin;
	struct 	stat stat_buf = {0};
	int		sd = args->sd;
	FILE 	*reqFile = NULL;

	// Init variables
	head.protocol[0] 	= '\0';
	head.status[0] 		= '\0';
	head.server[0] 		= '\0';
	head.type[0] 		= '\0';
	head.cache[0] 		= '\0';
	head.modified[0] 	= '\0';
	head.size 			= 0;
	req.method[0] 		= '\0';
	req.uri[0] 			= '\0';
	req.protocol[0] 	= '\0';
	req.error			= false;

  // Recieve the data, thank you
  if (recv(sd, reqBuf, sizeof(reqBuf), 0) == -1) {
		snprintf(error, sizeof(error), "Unable to recieve request, %s", strerror(errno));
		log_server(LOG_ERR, error);
		// Cleanup
    close(sd);
		free(args);
		return NULL;
  }

	// PARSE REQUEST -------------------------------------
	// First line is the actual request
	req_line = strtok(reqBuf, "\r\n");

	// Check if GET or HEAD is set
	req_token = strtok(req_line, " ");
	if (req_token != NULL) {
		if (strncmp(req_token, "GET", 3) == 0 || strncmp(req_token, "HEAD", 4) == 0) {
			strncpy(req.method, req_token, BUF_VAL);

			// Get uri
			req_token = strtok(NULL, " ");
			if (req_token != NULL) {
				strncpy(req.uri, req_token, BUF_VAL);

				/* Dosent matter
				// Get Protocol
				req_token = strtok(NULL, " ");
				if (req_token != NULL) {
					// Don't bother with the protocol
					strncpy(req.protocol, req_token, BUF_VAL);

				} else {
					// If no protocol set 400 Bad Request
					strncpy(head.status, "400 Bad Request", sizeof(head.status));
					req.error = true;
					strncpy(req.path, "/errpg/400.html", sizeof(req.path));
				}*/
				strncpy(req.protocol, "HTTP/1.0", BUF_VAL);
			} else {
				// If no uri set 400 Bad Request
				strncpy(head.status, "400 Bad Request", sizeof(head.status));
				req.error = true;
				strncpy(req.path, "/errpg/400.html", sizeof(req.path));
			}
		} else {
			// If invalid method set 501 Not Implemented
			strncpy(head.status, "501 Not Implemented", sizeof(head.status));
			req.error = true;
			strncpy(req.path, "/errpg/501.html", sizeof(req.path));
		}
	} else {
		// If no method set 400 Bad Request
		strncpy(head.status, "400 Bad Request", sizeof(head.status));
		req.error = true;
		strncpy(req.path, "/errpg/400.html", sizeof(req.path));
	}

	// If '/' was only character in uri set index
	if (strncmp(req.uri, "/", 1) == 0) {
		strncpy(req.path, "/index.html", sizeof(req.path));
	}
	// Else set the requested path unless the request is bad
	else if(!req.error) {
		strncpy(req.path, req.uri, sizeof(req.path));
	}

	// Check if file exists with realpath
	if (realpath(req.path, buffert) == NULL) {
		// If file does not exists
		snprintf(error, sizeof(error), "%s was not found, sending error page instead", req.path);
		log_server(LOG_INFO, error);
		strncpy(head.status, "404 Not Found", sizeof(head.status));
		req.error = true;
		// Load error page instead
		strncpy(req.path, "/errpg/404.html", sizeof(req.path));
		realpath(req.path, buffert);
	}
	// If file exists and there was no error set status to 200
	else if(!req.error) {
		strncpy(head.status, "200 OK", sizeof(head.status));
	}

	// Open the file
	if ((reqFile = fopen(buffert, "r")) == NULL) {
		// If we can't open the file send 500
		req.error = true;
		strncpy(head.status, "500 Internal Server Error", sizeof(head.status));
		strncpy(head.protocol, "HEAD", sizeof(head.protocol));
	}

	// Get the file size
	if (reqFile != NULL) {
		fstat(fileno(reqFile), &stat_buf);
	}

	// HEADER -------------------------------------
	// Server name
	strncpy(head.server, _SERVER_NAME" "_SERVER_VERSION, sizeof(head.server));
	// Protocol
	strncpy(head.protocol, "HTTP/"_SERVER_HTTP_VER, sizeof(head.protocol));
	// Type
	if (strncmp(getExt(req.uri), ".png", 4) == 0) {
		strncpy(head.type, "image/png", sizeof(head.type));
	} else if (strncmp(getExt(req.uri), ".jpg", 4) == 0) {
		strncpy(head.type, "image/jpg", sizeof(head.type));
	} else if (strncmp(getExt(req.uri), ".gif", 4) == 0) {
		strncpy(head.type, "image/gif", sizeof(head.type));
	} else if (strncmp(getExt(req.uri), ".css", 4) == 0) {
		strncpy(head.type, "text/css", sizeof(head.type));
	} else if (strncmp(getExt(req.uri), ".js", 3) == 0) {
		strncpy(head.type, "application/javascript", sizeof(head.type));
	} else if (strncmp(getExt(req.uri), ".html", 5) == 0) {
		strncpy(head.type, "text/html", sizeof(head.type));
	}
	// Size
	head.size	= (int)stat_buf.st_size;
	// Cache
	strncpy(head.cache, "public", sizeof(head.cache));
	// Last-Modified
	strftime(date, sizeof(date), "%a, %d %b %Y %T %z", localtime(&stat_buf.st_ctime));
	strncpy(head.modified, date, sizeof(head.modified));

	// Send header
	if (sendHeader(sd, &head) == -1) {
		snprintf(error, sizeof(error), "Unable to send header, %s. Aborting", strerror(errno));
		log_server(LOG_WARNING, error);
		DIE_CON
	}
Example #28
0
int getTrackType(const char *fname){
	const char *sext=getExt(fname);
	int tt=sext ? getTypeByExt(sext) : 0;
	return tt;
}