Пример #1
0
std::string FConfigVariableManager::GetConfigurationFileName() const
{
	char FileNameBuffer[256];
	GetModuleFileName(nullptr, FileNameBuffer, sizeof(FileNameBuffer));
	std::string ConfigurationFileName = RemoveExtension(GetNameFromPath(FileNameBuffer));
	return ConfigurationFileName + ".ini";
}
Пример #2
0
void checkOutput(Parameters& par) {
  if (!*par.outfile) {
    RemoveExtension(par.outfile, par.infile);
    strcat(par.outfile, ".hhr");
    HH_LOG(INFO) << "Search results will be written to " << par.outfile << "\n";
  }
}
Пример #3
0
HRESULT GetAddInName(std::wstring& addInName)
{
	HRESULT hr;
	std::wstring header;
	std::wstring clrVersion;
	bool shadowCopyFiles;
	std::wstring createSandboxedAppDomainValue;

	hr = GetDnaHeader(false, header);	// Don't show errors here.
	if (!FAILED(hr))
	{
		hr = ParseDnaHeader(header, addInName, clrVersion, shadowCopyFiles, createSandboxedAppDomainValue); // No errors yet.
		if (FAILED(hr))
		{
			return E_FAIL;
		}
		if (addInName.empty())
		{
			std::wstring xllPath(GetAddInFullPath());
			StripPath(xllPath);
			RemoveExtension(xllPath);
			addInName = xllPath;
		}
	}
	return hr;
}
Пример #4
0
CStdString LocalTempCopyOfFile::FixUnicodeFileNameForXP(CStdString sFileName)
{
	char *ansistr;
	
	int lenW = (int)sFileName.length();
	int lenA = ::WideCharToMultiByte(CP_ACP, 0, sFileName.c_str(), lenW, 0, 0, NULL, NULL);
	if (lenA > 0)
	{
		ansistr = new char[lenA + 1]; // allocate a final null terminator as well
		BOOL bDefaultCharUsed = FALSE;
		::WideCharToMultiByte(CP_ACP, 0, sFileName.c_str(), lenW, ansistr, lenA, NULL, &bDefaultCharUsed);
		ansistr[lenA] = 0; // Set the null terminator 

		CStdString sRetVal(ansistr);

		if ( bDefaultCharUsed && IsFullyMessedUpString(sRetVal) )
		{
			TCHAR szTempFileBuffer[MAX_PATH];

			::GetTempFileName(m_sTempFolder, _T("wmtemp"), rand(), szTempFileBuffer );
			sRetVal = ::PathFindFileName(szTempFileBuffer);
		
			sRetVal = RemoveExtension(sRetVal);
			sRetVal += ::PathFindExtension(sFileName.c_str());
		}

		delete[] ansistr;
		return sRetVal;
	}

	return _T("");
}
Пример #5
0
/**
 * This function update the mirror's databases, if one is supplied only that's updated, otherwise all mirrors.
 * @param name A database name (if NULL, then all databases)
 * @return If no error ocurr, 0 is returned. If the database given doesn't exists, 1 is returned. In case of error, -1 (And an error message is issued)
 */
int UpdateMirrorDB(char *db)
{
	int i = 0, fd = 0;
	char dbpath[PATH_MAX];
	char dbLink[PATH_MAX];
	char dbDesc[PATH_MAX];
	DIR *dip;
	struct dirent *dit;

	/* If only one database was issued */
	if (db) {

		/* Get the path */
		snprintf(dbpath, PATH_MAX, "%s/%s.kdb", MIRRORS_DIRECTORY, db);
		if ((fd = open(dbpath, O_RDONLY)) < 0) {
			fprintf(stdout, "Database %s doesn't exists\n", db);
			return 1;
		}
		close(fd);

		/* Get its data */
		memset(dbLink, '\0', sizeof(dbLink));
		memset(dbDesc, '\0', sizeof(dbDesc));
		if (GetDataFromMirrorDatabase(dbpath, "LINK", dbLink) == -1)
			return -1;
		if (GetDataFromMirrorDatabase(dbpath, "DESC", dbDesc) == -1)
			return -1;

		/* Show comments for this database if any */
		if (dbDesc[0] != '\0')
			fprintf(stdout, "Comments for [%s]:\n%s\n", db, dbDesc);

		/* Get the database! */
		if (dbLink[0] != '\0')
			if (Download(dbLink, dbpath) == -1)
				return -1;

		return 0;
	}

	/* Get the databases from the directories */
	if ((dip = opendir(MIRRORS_DIRECTORY)) == NULL) {
		fprintf(stderr, "Couldn't open the mirror's database directory %s (%s)\n", MIRRORS_DIRECTORY, strerror(errno));
		return -1;
	}

	i = 1;
	while ((dit = readdir(dip)) != NULL) {
		/* Skip directories . and .. */
		if (!strcmp(dit->d_name, ".") || !strcmp(dit->d_name, ".."))
			continue;

		if (!UpdateMirrorDB(RemoveExtension(dit->d_name)))
			i = 0;
	}
	closedir(dip);

	return i;
}
Пример #6
0
bool C4VectorFont::Init(C4Group &hGrp, const char *szFilename, C4Config &rCfg)
	{
	// name by file
	Name.Copy(GetFilenameOnly(szFilename));
#if defined(_WIN32) && !defined(HAVE_FREETYPE)
	// check whether group is directory or packed
	if (!hGrp.IsPacked())
		{
		// it's open: use the file directly
		SCopy(hGrp.GetFullName().getData(), FileName, _MAX_PATH);
		AppendBackslash(FileName);
		SAppend(szFilename, FileName);
		if (!FileExists(FileName)) { *FileName=0; return false; }
		fIsTempFile = false;
		}
	else
		{
		// it's packed: extract to temp path
		SCopy(rCfg.AtTempPath(szFilename), FileName, _MAX_PATH);
		// make sure the filename is not in use, in case multiple instances of the engine are run
		if (FileExists(FileName))
			{
			RemoveExtension(FileName);
			StdStrBuf sNewFilename;
			for (int i=0; i<1000; ++i)
				{
				sNewFilename.Format("%s%x", FileName, (int)rand());
				if (*GetExtension(szFilename))
					{
					sNewFilename.AppendChar('.');
					sNewFilename.Append(GetExtension(szFilename));
					}
				if (!FileExists(sNewFilename.getData())) break;
				}
			SCopy(sNewFilename.getData(), FileName, _MAX_PATH);
			}
		if (!hGrp.ExtractEntry(szFilename, FileName)) { *FileName=0; return false; }
		fIsTempFile = true;
		}
	// add the font resource
	//if (!AddFontResourceEx(FileName, FR_PRIVATE, NULL)) requires win2k
	if (!AddFontResource(FileName))
		{
		if (fIsTempFile) EraseFile(FileName);
		*FileName='\0';
		return false;
		}
#else
	if (!hGrp.LoadEntry(szFilename, Data)) return false;
#endif
	// success
	return true;
	}
Пример #7
0
CFilePath &CFilePath::RenameExtension(LPCTSTR psNewExt)
{
    if (psNewExt == NULL || *psNewExt != '.')
    {
        RemoveExtension();
        return AddExtension(psNewExt);
    }

    int nMaxLen = msPath.GetLength() + _tcslen(psNewExt) + 1;
    PathRenameExtension(CStringLock(msPath, nMaxLen), psNewExt);

    return *this;
}
//---------------------------------------------------------------------------
__fastcall TFormScoreTests::TFormScoreTests(TComponent* Owner)
        : TForm(Owner)
{
  StringGridStudents->Cells[0][0] = "#";
  StringGridStudents->Cells[1][0] = "Name";
  StringGridStudents->Cells[2][0] = "Score";
  StringGridStudents->Cells[3][0] = "Comment";

  StringGridQuestions->Cells[0][0] = "#";
  StringGridQuestions->Cells[1][0] = "f";
  StringGridQuestions->Cells[2][0] = "Question";

  assert(RemovePath("Test.txt")=="Test.txt");
  assert(RemovePath("C:\\Test.txt")=="Test.txt");
  assert(RemovePath("C:\\Test\\Test.txt")=="Test.txt");
  assert(RemovePath("C:\\Test\\Test\\Test.txt")=="Test.txt");

  assert(RemoveExtension("Test.txt")=="Test");
  assert(RemoveExtension("C:\\Test.txt")=="C:\\Test");
  assert(RemoveExtension("C:\\Test\\Test.txt")=="C:\\Test\\Test");
  assert(RemoveExtension("C:\\Test\\Test\\Test.txt")=="C:\\Test\\Test\\Test");

}
Пример #9
0
bool LocalTempCopyOfFile::IsFullyMessedUpString(CStdString sFileName)
{
	CStdString sFileNameWithoutExtension = RemoveExtension(sFileName);
	
	CPINFO codepageInfo;	
	::GetCPInfo(CP_ACP, &codepageInfo);

	for(unsigned int i=0; i<sFileNameWithoutExtension.length(); i++)
	{
		if ( sFileNameWithoutExtension[i] != codepageInfo.DefaultChar[0])
			return false;
	}

	return true;
}
Пример #10
0
C4FileSelDlg::DefaultListItem::DefaultListItem(const char *szFilename,
                                               bool fTruncateExtension,
                                               bool fCheckbox, bool fGrayed,
                                               C4GUI::Icons eIcon)
    : C4FileSelDlg::ListItem(szFilename),
      pLbl(NULL),
      pCheck(NULL),
      pKeyCheck(NULL),
      fGrayed(fGrayed) {
  StdStrBuf sLabel;
  if (szFilename)
    sLabel.Ref(::GetFilename(szFilename));
  else
    sLabel.Ref(LoadResStr("IDS_CTL_NONE"));
  if (szFilename && fTruncateExtension) {
    sLabel.Copy();
    char *szFilename = sLabel.GrabPointer();
    RemoveExtension(szFilename);
    sLabel.Take(szFilename);
  }
  rcBounds.Hgt = C4GUI::GetRes()->TextFont.GetLineHeight();
  UpdateSize();
  C4GUI::ComponentAligner caMain(GetContainedClientRect(), 0, 0);
  int32_t iHeight = caMain.GetInnerHeight();
  if (fCheckbox) {
    pCheck = new C4GUI::CheckBox(caMain.GetFromLeft(iHeight), NULL, false);
    if (fGrayed) pCheck->SetEnabled(false);
    AddElement(pCheck);
    pKeyCheck = new C4KeyBinding(
        C4KeyCodeEx(K_SPACE), "FileSelToggleFileActive", KEYSCOPE_Gui,
        new C4GUI::ControlKeyCB<ListItem>(*this, &ListItem::UserToggleCheck),
        C4CustomKey::PRIO_Ctrl);
  }
  C4GUI::Icon *pIco = new C4GUI::Icon(caMain.GetFromLeft(iHeight), eIcon);
  AddElement(pIco);
  pLbl = new C4GUI::Label(
      sLabel.getData(), caMain.GetAll(), ALeft,
      fGrayed ? C4GUI_CheckboxDisabledFontClr : C4GUI_CheckboxFontClr);
  AddElement(pLbl);
}
Пример #11
0
bool Platform::AddExtension(std::shared_ptr<gd::PlatformExtension> extension) {
  if (!extension) return false;

  std::cout << "Loading " << extension->GetName() << "...";
  if (IsExtensionLoaded(extension->GetName())) {
    std::cout << " (replacing existing extension)";
    RemoveExtension(extension->GetName());
  }
  std::cout << std::endl;

  extensionsLoaded.push_back(extension);

  // Load all creation/destruction functions for objects provided by the
  // extension
  vector<gd::String> objectsTypes = extension->GetExtensionObjectsTypes();
  for (std::size_t i = 0; i < objectsTypes.size(); ++i) {
    creationFunctionTable[objectsTypes[i]] =
        extension->GetObjectCreationFunctionPtr(objectsTypes[i]);
  }

  return true;
}
void ProcessMolfileDirectory(string Directory,string OutputDirectory) {
	vector<string> DirectoryList = GetDirectoryFileList(Directory);

	Data* NewData = new Data(0);
	for (int i=0; i < int(DirectoryList.size()); i++) {
		cout << DirectoryList[i] << endl;
		Species* NewSpecies = new Species("", NewData, false);
		if (DirectoryList[i].length() > 0) {
			NewSpecies->ReadFromMol(Directory+DirectoryList[i]);
			NewSpecies->LabelAtoms();
			string FileRoot = RemovePath(RemoveExtension(DirectoryList[i]));
			ofstream Output;
			if (OpenOutput(Output,OutputDirectory+FileRoot+".txt")) {
				Output << "Atom index;Group;GroupIndex" << endl;
				for (int j=0; j < NewSpecies->FNumAtoms(); j++) {
					Output << j << ";" << NewSpecies->GetAtom(j)->FGroupString() << ";" << NewSpecies->GetAtom(j)->FGroupIndex() << endl;
				}
				Output.close();
			}
		}
		delete NewSpecies;
	}
}
Пример #13
0
bool C4DefGraphics::Load(C4Group &hGroup, StdMeshSkeletonLoader &loader, bool fColorByOwner)
{
	char Filename[_MAX_PATH+1]; *Filename=0;

	// load skeletons
	hGroup.ResetSearch();
	while (hGroup.FindNextEntry("*", Filename, NULL, !!*Filename))
	{
		if (!WildcardMatch(C4CFN_DefSkeleton, Filename) && !WildcardMatch(C4CFN_DefSkeletonXml, Filename)) continue;
		LoadSkeleton(hGroup, Filename, loader);
	}

	// Try from Mesh first
	if (!LoadMesh(hGroup, C4CFN_DefMesh, loader))
		if(!LoadMesh(hGroup, C4CFN_DefMeshXml, loader))
			LoadBitmap(hGroup, C4CFN_DefGraphics, C4CFN_ClrByOwner, C4CFN_NormalMap, fColorByOwner);

	// load additional graphics
	C4DefGraphics *pLastGraphics = this;
	const int32_t iOverlayWildcardPos = SCharPos('*', C4CFN_ClrByOwnerEx);
	hGroup.ResetSearch(); *Filename=0;
	const char* const AdditionalGraphics[] = { C4CFN_DefGraphicsEx, C4CFN_DefGraphicsExMesh, C4CFN_DefGraphicsExMeshXml, NULL };
	while (hGroup.FindNextEntry("*", Filename, NULL, !!*Filename))
	{
		for(const char* const* szWildcard = AdditionalGraphics; *szWildcard != NULL; ++szWildcard)
		{
			if(!WildcardMatch(*szWildcard, Filename)) continue;
			// skip def graphics
			if (SEqualNoCase(Filename, C4CFN_DefGraphics) || SEqualNoCase(Filename, C4CFN_DefMesh) || SEqualNoCase(Filename, C4CFN_DefMeshXml)) continue;
			// skip scaled def graphics
			if (WildcardMatch(C4CFN_DefGraphicsScaled, Filename)) continue;
			// get name
			char GrpName[_MAX_PATH+1];
			const int32_t iWildcardPos = SCharPos('*', *szWildcard);
			SCopy(Filename + iWildcardPos, GrpName, _MAX_PATH);
			RemoveExtension(GrpName);
			// remove trailing number for scaled graphics
			int32_t extpos; int scale;
			if ((extpos = SCharLastPos('.', GrpName)) > -1)
				if (sscanf(GrpName+extpos+1, "%d", &scale) == 1)
					GrpName[extpos] = '\0';
			// clip to max length
			GrpName[C4MaxName]=0;
			// create new graphics
			pLastGraphics->pNext = new C4AdditionalDefGraphics(pDef, GrpName);
			pLastGraphics = pLastGraphics->pNext;
			if(*szWildcard == AdditionalGraphics[0])
			{
				// create overlay-filename
				char OverlayFn[_MAX_PATH+1];
				if(fColorByOwner)
				{
					// GraphicsX.png -> OverlayX.png
					SCopy(C4CFN_ClrByOwnerEx, OverlayFn, _MAX_PATH);
					OverlayFn[iOverlayWildcardPos]=0;
					SAppend(Filename + iWildcardPos, OverlayFn);
					EnforceExtension(OverlayFn, GetExtension(C4CFN_ClrByOwnerEx));
				}

				// create normal filename
				char NormalFn[_MAX_PATH+1];
				SCopy(C4CFN_NormalMapEx, NormalFn, _MAX_PATH);
				NormalFn[iOverlayWildcardPos]=0;
				SAppend(Filename + iWildcardPos, NormalFn);
				EnforceExtension(NormalFn, GetExtension(C4CFN_NormalMapEx));

				// load them
				if (!pLastGraphics->LoadBitmap(hGroup, Filename, fColorByOwner ? OverlayFn : NULL, NormalFn, fColorByOwner))
					return false;
			}
			else
			{
				if (!pLastGraphics->LoadMesh(hGroup, Filename, loader))
					return false;
			}
		}
	}
	// done, success
	return true;
}
Пример #14
0
std::string ReplaceExtenstion(const std::string& path, const std::string& extension) {
  return RemoveExtension(path) + extension;
}
Пример #15
0
// Load compressed MIN ROM
static int PokeMini_iLoadROMZip(const char *zipfile, int *colorloaded)
{
	unzFile uf = NULL;
	unz_global_info64 gi;
	unz_file_info64 file_inf;
	char filein[PMTMPV];
	void *new_data;
	int i, size, loaded = 0, cloaded = 0;

	if (colorloaded) *colorloaded = 0;

	// Open ZIP
	uf = unzOpen(zipfile);
	if (!uf) {
		if (PokeMini_OnUnzipError) PokeMini_OnUnzipError(zipfile, "Opening ZIP error");
		return 0;
	}
	if (unzGetGlobalInfo64(uf, &gi) != UNZ_OK) {
		if (PokeMini_OnUnzipError) PokeMini_OnUnzipError(zipfile, "Getting global info");
		unzClose(uf);
		return 0;
	}

	// Find and load MIN
	for (i=0; i<gi.number_entry; i++) {
		if (unzGetCurrentFileInfo64(uf, &file_inf, filein, PMTMPV, NULL, 0, NULL, 0) != UNZ_OK) {
			if (PokeMini_OnUnzipError) PokeMini_OnUnzipError(zipfile, "Current file info");
			unzClose(uf);
			return 0;
		}
		if (ExtensionCheck(filein, ".min") && (!loaded)) {
			if (unzLocateFile(uf, filein, 0) != UNZ_OK) {
				if (PokeMini_OnUnzipError) PokeMini_OnUnzipError(zipfile, "LocateFile failed");
				unzClose(uf);
				return 0;
			}
			if (unzOpenCurrentFile(uf) != UNZ_OK) {
				if (PokeMini_OnUnzipError) PokeMini_OnUnzipError(zipfile, "Opening file error");
				unzClose(uf);
				return 0;
			}
			size = GetMultiple2(file_inf.uncompressed_size);
			new_data = (void *)malloc(size);
			memset(new_data, 0xFF, size);
			if (!new_data) {
				if (PokeMini_OnUnzipError) PokeMini_OnUnzipError(zipfile, "Not enough memory");
				unzCloseCurrentFile(uf);
				unzClose(uf);
				return 0;
			}
			size = unzReadCurrentFile(uf, new_data, file_inf.uncompressed_size);
			if (size < 0) {
				if (PokeMini_OnUnzipError) PokeMini_OnUnzipError(zipfile, "Reading file error");
				unzCloseCurrentFile(uf);
				unzClose(uf);
				return 0;
			}
			PokeMini_FreeColorInfo();	// Free existing color information
			PokeMini_SetMINMem((uint8_t *)new_data, file_inf.uncompressed_size);
			PM_ROM_Alloc = 1;
			if (unzCloseCurrentFile(uf) != UNZ_OK) {
				if (PokeMini_OnUnzipError) PokeMini_OnUnzipError(zipfile, "Closing file error");
				unzClose(uf);
				return 0;
			}
			if (PokeMini_OnAllocMIN) PokeMini_OnAllocMIN(PM_ROM_Size, 1);
			if (PokeMini_OnLoadMINFile) PokeMini_OnLoadMINFile(zipfile, 1);
			loaded = 1;
			break;
		}
		if ((i+1) < gi.number_entry) {
			if (unzGoToNextFile(uf) != UNZ_OK) {
				if (PokeMini_OnUnzipError) PokeMini_OnUnzipError(zipfile, "No next file");
				unzClose(uf);
				return 0;
			}
		}
	}

	// Check if there's color information file
	strcat(filein, "c");
	if (!loaded) {
		if (PokeMini_OnUnzipError) PokeMini_OnUnzipError(zipfile, "No ROM in ZIP");
		unzClose(uf);
		return 0;
	} else {
		if (unzGoToFirstFile(uf) != UNZ_OK) {
			if (PokeMini_OnUnzipError) PokeMini_OnUnzipError(zipfile, "No first file");
			unzClose(uf);
			return 0;
		}
		if (unzLocateFile(uf, filein, 0) == UNZ_OK) {
			if (unzOpenCurrentFile(uf) != UNZ_OK) {
				if (PokeMini_OnUnzipError) PokeMini_OnUnzipError(zipfile, "Opening file error");
				unzClose(uf);
				return 0;
			}
			if (!PokeMini_LoadColorStream(PokeMini_StreamFromZIP, uf)) {
				if (PokeMini_OnUnzipError) PokeMini_OnUnzipError(zipfile, "Reading file error");
				unzCloseCurrentFile(uf);
				unzClose(uf);
				return 0;
			}
			if (unzCloseCurrentFile(uf) != UNZ_OK) {
				if (PokeMini_OnUnzipError) PokeMini_OnUnzipError(zipfile, "Closing file error");
				unzClose(uf);
				return 0;
			}
			cloaded = 1;
			if (colorloaded) *colorloaded = 1;
			if (PokeMini_OnLoadColorFile) PokeMini_OnLoadColorFile(zipfile, 1);
		}
	}

	// Close ZIP
	unzClose(uf);

	// Try to load color information from a file outside if wasn't found in the zip
	if (!cloaded) {
		// Filename based of the ROM inside the zip
		RemoveExtension(filein);
		strcat(filein, ".minc");
		if (FileExist(filein)) {
			if (PokeMini_LoadColorFile(filein)) {
				if (colorloaded) *colorloaded = 1;
				if (PokeMini_OnLoadColorFile) PokeMini_OnLoadColorFile(zipfile, 1);
				return 1;
			}
		}
		// Filename based of the zip
		strcpy(filein, zipfile);
		RemoveExtension(filein);
		strcat(filein, ".minc");
		if (FileExist(filein)) {
			if (PokeMini_LoadColorFile(filein)) {
				if (colorloaded) *colorloaded = 1;
				if (PokeMini_OnLoadColorFile) PokeMini_OnLoadColorFile(zipfile, 1);
				return 1;
			}
		}
	}

	return 1;
}
//---------------------------------------------------------------------------
void TFormScoreTests::ReadFile(const String& filename)
{
  const int row = StringGridStudents->RowCount - 1;
  const std::string file_stripped = RemoveExtension(RemovePath(filename.c_str()));
  ++StringGridStudents->RowCount;
  StringGridStudents->Cells[0][row] = row;
  StringGridStudents->Cells[1][row] = file_stripped.c_str();
  StringGridStudents->Cells[2][row] = "";
  StringGridStudents->Cells[3][row] = "";

  const int key = EditKey->Text.ToInt();
  const int penalty = EditPenalty->Text.ToInt();
  const Encranger e(key);


  //Load file
  std::vector<std::string> v = FileToVector(filename.c_str());

  const int sz = v.size();
  for (int i=0; i!=sz; ++i)
  {
    //Deencrypt file
    v[i] = e.Deencrypt(v[i]);
    //Remove asterisks
    v[i] = ReplaceAll(v[i],"*","");
  }

  const std::string username = FindUserName(v);

  if (username.empty())
  {
    StringGridStudents->Cells[3][row] = "Username not found";
    StringGridStudents->Cells[2][row] = "1.0 or 1.1";
    return;
  }

  if (username != file_stripped)
  {
    StringGridStudents->Cells[3][row] = "Filename differs from username";
    StringGridStudents->Cells[2][row] = "1.1";
    return;
  }


  int n_correct = 0;
  const int n_questions = CountQuestions(v);
  LabelNquestions->Caption = "#questions: " + IntToStr(n_questions);

  for (int i=0; i!=sz; ++i)
  {
    if (v[i].empty()) continue;

    const std::vector<std::string> line_markup = SeperateString(v[i],",");

    //Replace {comma} by a comma for each std::string in v
    const std::vector<std::string> line = ReplaceAll(line_markup,"{comma}",",");

    OutputDebugString(line.size() >= 1 ? line[0].c_str() : "line[0] = {}");
    OutputDebugString(line.size() >= 2 ? line[1].c_str() : "line[1] = {}");
    OutputDebugString(line.size() >= 3 ? line[2].c_str() : "line[2] = {}");
    OutputDebugString(line.size() >= 4 ? line[3].c_str() : "line[3] = {}");

    //assert(line.size() == 2); WORKAROUND



    if (line[0]=="NAME") continue;
    const bool is_correct = (line[line.size()-1]=="Y"); //WORKAROUND
    assert(line[line.size()-1]=="Y" || line[line.size()-1]=="N"); //WORKAROUND 
    if (is_correct) ++n_correct;
    ScoreQuestion(line[0],is_correct);
  }

  //Calculate student's score
  assert(n_questions - penalty > 0);
  const double fraction
      = static_cast<double>(n_correct - penalty)
      / static_cast<double>(n_questions - penalty);
  const double init_score = 1.0 + (9.0 * fraction);
  const double score_above_one = (init_score < 1.0 ? 1.0 : init_score);
  const double score_below_ten = (score_above_one > 10.0 ? 10.0 : score_above_one);
  const double score = score_below_ten;

  StringGridStudents->Cells[2][row] = score;
}
Пример #17
0
std::string ribi::ndsm::Ndsmake::GetTarget() const noexcept
{
  return m_pro_file.GetTarget().empty()
    ? RemoveExtension( this->m_pro_file.GetQtCreatorProFilename() )
    : (*m_pro_file.GetTarget().begin());
}
Пример #18
0
bool C4ObjectInfo::Save(C4Group &hGroup, bool fStoreTiny, C4DefList *pDefs)
{
	// Set group file name; rename if necessary
	char szTempGroup[_MAX_PATH+1];
	SCopy(Name, szTempGroup, _MAX_PATH);
	MakeFilenameFromTitle(szTempGroup);
	SAppend(".oci",szTempGroup, _MAX_PATH);
	if (!SEqualNoCase(Filename, szTempGroup))
	{
		if (!Filename[0])
		{
			// first time creation of file - make sure it's not a duplicate
			SCopy(szTempGroup, Filename, _MAX_PATH);
			while (hGroup.FindEntry(Filename))
			{
				// if a crew info of that name exists already, rename!
				RemoveExtension(Filename);
				int32_t iFinNum = GetTrailingNumber(Filename), iLen = SLen(Filename);
				while (iLen && Inside(Filename[iLen-1], '0', '9')) --iLen;
				if (iLen>_MAX_PATH-22) { LogF("Error generating unique filename for %s(%s): Path overflow", Name, hGroup.GetFullName().getData()); break; }
				snprintf(Filename+iLen, 22, "%d", iFinNum+1);
				EnforceExtension(Filename, "oci");
			}
		}
		else
		{
			// Crew was renamed; file rename necessary, if the name is not blocked by another crew info
			if (!hGroup.FindEntry(szTempGroup))
			{
				if (hGroup.Rename(Filename, szTempGroup))
					SCopy(szTempGroup, Filename, _MAX_PATH);
				else
				{
					// could not rename. Not fatal; just use old file
					LogF("Error adjusting crew info for %s into %s: Rename error from %s to %s!", Name, hGroup.GetFullName().getData(), Filename, szTempGroup);
				}
			}
		}
	}
	// Open group
	C4Group hTemp;
	if (!hTemp.OpenAsChild(&hGroup, Filename, false, true))
		return false;
	// custom rank image present?
	if (pDefs && !fStoreTiny)
	{
		C4Def *pDef = pDefs->ID2Def(id);
		if (pDef)
		{
			if (pDef->pRankSymbols)
			{
				C4FacetSurface fctRankSymbol;
				if (C4RankSystem::DrawRankSymbol(&fctRankSymbol, Rank, pDef->pRankSymbols, pDef->iNumRankSymbols, true))
				{
					fctRankSymbol.GetFace().SavePNG(hTemp, C4CFN_ClonkRank);
				}
			}
			else
			{
				// definition does not have custom rank symbols: Remove any rank image from Clonk
				hTemp.Delete(C4CFN_ClonkRank);
			}
		}
	}

	// Save info to temp group
	if (!C4ObjectInfoCore::Save(hTemp, pDefs))
		{ hTemp.Close(); return false; }
	// Close temp group
	hTemp.Close();
	// Success
	return true;
}
Пример #19
0
// Returns only the filename without extension, i.e. will not include a path.
std::wstring CPathUtils::GetFileNameWithoutExtension( const std::wstring& path )
{
    return RemoveExtension(GetFileName(path));
}
BOOL CFileUtil::FindFiles(const char*szInDirectory, BOOL bDirs, const char*szInName, const char*szExtension, CArrayChars* paszFiles, BOOL bHidden)
{
	WIN32_FIND_DATA		sFindData;
	CChars				szFindName;
	CChars				szTemp;
	HANDLE				hFindHandle;
	BOOL				bContinue;
	int					iFileExtension;
	BOOL				bValid;
	CChars				szFake;
	CChars				szDirectory;

	szDirectory.Init(szInDirectory);
	FullPath(&szDirectory);
	szFindName.Init(szDirectory);
	AppendToPath(&szFindName, "*.*");

	hFindHandle = FindFirstFile(szFindName.Text(), &sFindData);
	bContinue = (hFindHandle != INVALID_HANDLE_VALUE);

	if (!bContinue)
	{
		szDirectory.Kill();
		szFindName.Kill();
		return FALSE;
	}

	while (bContinue)
	{
		if (!(sFindData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) || bHidden)
		{
			bValid = TRUE;
			if (sFindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			{
				if (bDirs)
				{
					if (szInName != NULL)
					{
						szTemp.Init(sFindData.cFileName);
						RemoveExtension(&szTemp);
						if (!szTemp.ContainsIgnoreCase(szInName))
						{
							bValid = FALSE;
						}
						szTemp.Kill();
					}
				}
				else
				{
					bValid = FALSE;
				}
			}
			else
			{
				if (!bDirs)
				{
					if (szExtension != NULL)
					{
						szFake.Fake(sFindData.cFileName);
						iFileExtension = FindExtension(szFake.Text());
						if (iFileExtension != -1)
						{
							if (!(szFake.SubStringEquals(iFileExtension+1, szExtension)))
							{
								bValid = FALSE;
							}
						}
						else
						{
							//If there is no file extension on the current file and the
							//extension being looked for is not empty...
							if (szExtension[0] != 0)
							{
								//Then this file is not valid.
								bValid = FALSE;
							}
						}
					}
					if (szInName != NULL)
					{
						szTemp.Init(sFindData.cFileName);
						RemoveExtension(&szTemp);
						if (!szTemp.ContainsIgnoreCase(szInName))
						{
							bValid = FALSE;
						}
						szTemp.Kill();
					}
				}
				else
				{
					bValid = FALSE;
				}
			}
		}
		else
		{
			bValid = FALSE;
		}

		if (bValid)
		{
			if (!((strcmp(sFindData.cFileName, ".") == 0) || (strcmp(sFindData.cFileName, "..") == 0)))
			{
				szTemp.Init(szDirectory);
				AppendToPath(&szTemp, sFindData.cFileName);
				paszFiles->Add(szTemp.Text());
				szTemp.Kill();
			}
		}

		bContinue = FindNextFile(hFindHandle, &sFindData);
	}
	FindClose(hFindHandle);

	szDirectory.Kill();
	szFindName.Kill();
	return TRUE;
}
void LoadDatabaseFile(const char* DatabaseFilename) {
	if (GetParameter("Network output location").compare("none") != 0 && GetParameter("Network output location").length() > 0) {
		if (GetParameter("os").compare("windows") == 0) {
			system(("move "+GetDatabaseDirectory(GetParameter("database"),"output directory")+GetParameter("output folder")+" "+GetParameter("Network output location")).data());
		} else {
			system(("cp -r "+GetDatabaseDirectory(GetParameter("database"),"output directory")+GetParameter("output folder")+" "+GetParameter("Network output location")).data());
		}
	}
	
	//Getting filename that all compound and reaction data will be saved into
	string Filename(DatabaseFilename);	
	if (Filename.length() == 0) {
		Filename = AskString("Input filename for database: ");
	}
	
	//Creating datastructure for all program data
	Data* NewData = new Data(0);
	NewData->ClearData("NAME",STRING);
	NewData->AddData("NAME",RemoveExtension(RemovePath(Filename)).data(),STRING);

	//Loading data from file
	if (NewData->LoadSystem(Filename) == FAIL) {
		delete NewData;
		return;
	}
	//Performing a variety of tasks according to the parameters in the parameters files including KEGG lookup, reaction and compound printing etc.
	NewData->PerformAllRequestedTasks();
	// Test for Adjustment of DeltaGs for PH for COMPOUNDS
	bool TestCpds = 0;

	if (TestCpds){

		double IonicS = 0.25;
		FErrorFile() << "Std Transformed Gibbs Energy of Formation vs pH" << endl;
		
		for (int i=0; i < NewData->FNumSpecies(); i++){
			
			string CompoundID = NewData->GetSpecies(i)->GetData("DATABASE",STRING); // gets the cpdID
			string Name = NewData->GetSpecies(i)->GetData("NAME",STRING); // gets the name of the cpd

			Species* Temp = NewData->FindSpecies("DATABASE",CompoundID.data());
			
			//if (CompoundID.compare("cpd00003") == 0 || CompoundID.compare("cpd00004") == 0 || CompoundID.compare("cpd00002") == 0) {
			double AdjDeltaG5 = Temp->AdjustedDeltaG(IonicS,5,298.15);
			double AdjDeltaG5_kJ = 4.184*AdjDeltaG5;

			double AdjDeltaG6 = Temp->AdjustedDeltaG(IonicS,6,298.15);
			double AdjDeltaG6_kJ = 4.184*AdjDeltaG6;

			double AdjDeltaG7 = Temp->AdjustedDeltaG(IonicS,7,298.15);
			double AdjDeltaG7_kJ = 4.184*AdjDeltaG7;

			double AdjDeltaG8 = Temp->AdjustedDeltaG(IonicS,8,298.15);
			double AdjDeltaG8_kJ = 4.184*AdjDeltaG8;

			double AdjDeltaG9 = Temp->AdjustedDeltaG(IonicS,9,298.15);
			double AdjDeltaG9_kJ = 4.184*AdjDeltaG9;

			FErrorFile() << CompoundID << "\t" << AdjDeltaG5_kJ << "\t" << AdjDeltaG6_kJ << "\t" << AdjDeltaG7_kJ << "\t" << AdjDeltaG8_kJ << "\t" << AdjDeltaG9_kJ << endl;
			//}
		}

		FlushErrorFile();
	}
	// Test for Adjustment of DeltaGs for IONIC STRENGTH for COMPOUNDS
	bool TestCpdsIS = 0;

	if (TestCpdsIS){
	
		FErrorFile() << "Std Transformed Gibbs Energy of Formation vs Ionic Strength" << endl;

		for (int i=0; i < NewData->FNumSpecies(); i++){

			string CompoundID = NewData->GetSpecies(i)->GetData("DATABASE",STRING); // gets the cpdID
			string Name = NewData->GetSpecies(i)->GetData("NAME",STRING); // gets the name of the cpd

			Species* Temp = NewData->FindSpecies("DATABASE",CompoundID.data());

			double AdjDeltaG_IS0 = Temp->AdjustedDeltaG(0,7,298.15);
			double AdjDeltaG_IS0_kJ = 4.184*AdjDeltaG_IS0;

			double AdjDeltaG_IS10 = Temp->AdjustedDeltaG(0.1,7,298.15);
			double AdjDeltaG_IS10_kJ = 4.184*AdjDeltaG_IS10;

			double AdjDeltaG_IS25 = Temp->AdjustedDeltaG(0.25,7,298.15);
			double AdjDeltaG_IS25_kJ = 4.184*AdjDeltaG_IS25;

			FErrorFile() << CompoundID << "\t" << AdjDeltaG_IS0_kJ << "\t" << AdjDeltaG_IS10_kJ << "\t" << AdjDeltaG_IS25_kJ << endl;
		
		}

		FlushErrorFile();
	}
	// Test for Adjustment of DeltaGs for pH for REACTIONS
	bool TestRxns = 0;

	if (TestRxns){
		
		double IonicS = 0.25;
		//double pH = 7;
		FErrorFile() << "Std Transformed Gibbs Energy of Reaction (kJmol-1) vs pH" << endl;

		for (int i=0; i < NewData->FNumReactions(); i++){
			Reaction* Rxn = NewData->GetReaction(i);
			string RxnID = Rxn->GetData("DATABASE",STRING);
			string Name = Rxn->GetData("NAME",STRING);
		
			double DG5 = Rxn->FEstDeltaG(5,IonicS)*4.184;
			double DG6 = Rxn->FEstDeltaG(6,IonicS)*4.184;
			double DG7 = Rxn->FEstDeltaG(7,IonicS)*4.184;
			double DG8 = Rxn->FEstDeltaG(8,IonicS)*4.184;
			double DG9 = Rxn->FEstDeltaG(9,IonicS)*4.184;
			
			FErrorFile() << RxnID << "\t" << DG5 << "\t" << DG6 << "\t" << DG7 << "\t" << DG8 << "\t" << DG9 << endl;
		}
		FlushErrorFile();
	}
	// Test for Adjustment of DeltaGs for IONIC STRENGTH for REACTIONS
	bool TestRxnsIS = 0;

	if (TestRxnsIS){
		
		FErrorFile() << "Std Transformed Gibbs Energy of Reaction (kJmol-1) vs Ionic Strength" << endl;
		
		for (int i=0; i < NewData->FNumReactions(); i++){
			Reaction* Rxn = NewData->GetReaction(i);
			string RxnID = Rxn->GetData("DATABASE",STRING);
			string Name = Rxn->GetData("NAME",STRING);
			
			double DG_IS0 = Rxn->FEstDeltaG(7,0.25)*4.184;
			double DG_IS10 = Rxn->FEstDeltaG(7,0.15)*4.184;
			double DG_IS25 = Rxn->FEstDeltaG(7,0.25)*4.184;
			
			FErrorFile() << RxnID << "\t" << DG_IS0 << "\t" << DG_IS10 << "\t" << DG_IS25 << endl;

		}
		// FlushErrorFile();
	}
	delete NewData;
};
Пример #22
0
////////////////////////////////////////////////////////////////////////
// Main prefilter function
////////////////////////////////////////////////////////////////////////
  void Prefilter::prefilter_db(HMM* q_tmp, Hash<Hit>* previous_hits,
      const int threads, const int prefilter_gap_open,
      const int prefilter_gap_extend, const int prefilter_score_offset,
      const int prefilter_bit_factor, const double prefilter_evalue_thresh,
      const double prefilter_evalue_coarse_thresh,
      const int preprefilter_smax_thresh, const int min_prefilter_hits, const int maxnumdb,
      const float R[20][20],
      std::vector<std::pair<int, std::string> >& new_prefilter_hits,
      std::vector<std::pair<int, std::string> >& old_prefilter_hits) {

    Hash<char>* doubled = new Hash<char>;
    doubled->New(16381, 0);

    int element_count = (VECSIZE_INT * 4);
    //W = (LQ+15) / 16;   // band width = hochgerundetes LQ/16
    int W = (q_tmp->L + (element_count - 1)) / element_count;
    // query profile (states + 1 because of ANY char)
    unsigned char* qc = (unsigned char*)malloc_simd_int((hh::NUMCOLSTATES+1)*(q_tmp->L+element_count)*sizeof(unsigned char));
    stripe_query_profile(q_tmp, prefilter_score_offset, prefilter_bit_factor, W, qc);

    simd_int ** workspace = new simd_int *[threads];

    std::vector<std::pair<int, int> > first_prefilter;
    std::vector<std::pair<double, int> > hits;

    int count_dbs = 0;
    int gap_init = prefilter_gap_open + prefilter_gap_extend;
    int gap_extend = prefilter_gap_extend;
    int LQ = q_tmp->L;
    const float log_qlen = flog2(LQ);
    const double factor = (double) num_dbs * LQ;

    for (int i = 0; i < threads; i++)
      workspace[i] = (simd_int*) malloc_simd_int(
          3 * (LQ + element_count) * sizeof(char));

#pragma omp parallel for schedule(static)
    // Loop over all database sequences
    for (size_t n = 0; n < num_dbs; n++) {
      int thread_id = 0;
#ifdef OPENMP
      thread_id = omp_get_thread_num();
#endif
      // Perform search step
      int score = ungapped_sse_score(qc, LQ, first[n], length[n],
          prefilter_score_offset, workspace[thread_id]);

      score = score
          - (int) (prefilter_bit_factor * (log_qlen + flog2(length[n])));

#pragma omp critical
      first_prefilter.push_back(std::pair<int, int>(score, n));
    }
    //filter after calculation of ungapped sse score to include at least min_prefilter_hits
    std::vector<std::pair<int, int> >::iterator it;

    sort(first_prefilter.begin(), first_prefilter.end());
    std::reverse(first_prefilter.begin(), first_prefilter.end());

    std::vector<std::pair<int, int> >::iterator first_prefilter_begin_erase =
        first_prefilter.end();
    std::vector<std::pair<int, int> >::iterator first_prefilter_end_erase =
        first_prefilter.end();
    count_dbs = 0;
    for (it = first_prefilter.begin(); it < first_prefilter.end(); it++) {
      if (count_dbs >= min_prefilter_hits
          && (*it).first <= preprefilter_smax_thresh) {
        first_prefilter_begin_erase = it;
        break;
      }
      else {
        count_dbs++;
      }
    }

    first_prefilter.erase(first_prefilter_begin_erase,
        first_prefilter_end_erase);

    HH_LOG(INFO)
        << "HMMs passed 1st prefilter (gapless profile-profile alignment)  : "
        << count_dbs << std::endl;

#pragma omp parallel for schedule(static)
    // Loop over all database sequences
//  for (int n = 0; n < count_dbs; n++) {
    for (size_t i = 0; i < first_prefilter.size(); i++) {
      int thread_id = 0;
#ifdef OPENMP
      thread_id = omp_get_thread_num();
#endif

      int n = first_prefilter[i].second;

      // Perform search step
      int score = swStripedByte(qc, LQ, first[n], length[n], gap_init,
          gap_extend, workspace[thread_id], workspace[thread_id] + W,
          workspace[thread_id] + 2 * W, prefilter_score_offset);

      double evalue = factor * length[n] * fpow2(-score / prefilter_bit_factor);

      if (evalue < prefilter_evalue_coarse_thresh) {
#pragma omp critical
        hits.push_back(std::pair<double, int>(evalue, n));
      }
    }

    //filter after calculation of evalues to include at least min_prefilter_hits
    sort(hits.begin(), hits.end());

    std::vector<std::pair<double, int> >::iterator second_prefilter_begin_erase =
        hits.end();
    std::vector<std::pair<double, int> >::iterator second_prefilter_end_erase =
        hits.end();
    std::vector<std::pair<double, int> >::iterator it2;

    count_dbs = 0;
    for (it2 = hits.begin(); it2 < hits.end(); it2++) {
      if (count_dbs >= min_prefilter_hits
          && (*it2).first > prefilter_evalue_thresh) {
        second_prefilter_begin_erase = it2;
        break;
      }
      else {
        count_dbs++;
      }
    }

    hits.erase(second_prefilter_begin_erase, second_prefilter_end_erase);

    count_dbs = 0;

    for (it2 = hits.begin(); it2 < hits.end(); it2++) {
      // Add hit to dbfiles
      count_dbs++;
      char db_name[NAMELEN];
      strcpy(db_name, dbnames[(*it2).second]);

      char name[NAMELEN];
      RemoveExtension(name, db_name);

      if (!doubled->Contains(db_name)) {
        doubled->Add(db_name);

        std::pair<int, std::string> result;
        result.first = length[(*it2).second];
        result.second = std::string(db_name);

        // check, if DB was searched in previous rounds
        strcat(name, "__1");  // irep=1

        if (previous_hits->Contains(name)) {
          old_prefilter_hits.push_back(result);
        }
        else {
          new_prefilter_hits.push_back(result);
        }
      }
      if (count_dbs >= maxnumdb)
      {
        HH_LOG(WARNING)
        << "Number of hits passing 2nd prefilter (reduced from " << hits.size() << " to allowed maximum of " << maxnumdb << ").\n"
        <<"You can increase the allowed maximum using the -maxfilt <max> option.\n";
        break;
      }
    }


      
      
    // Free memory
    free(qc);
    for (int i = 0; i < threads; i++)
      free(workspace[i]);
    delete[] workspace;
    if (doubled)
      delete doubled;
  }
void C4ConsoleQtDefinitionListModel::ReInit()
{
	// Re-fill definition model with all loaded definitions matching condition
	// (TODO: Add conditional lists)
	root = std::make_unique<C4ConsoleQtDefinitionListModel::DefListNode>();
	int32_t index = 0; C4Def *def;
	while ((def = ::Definitions.GetDef(index++)))
	{
		// Ignore hidden defs
		if (def->HideInCreator) continue;
		// Build path leading to this definition
		DefListNode *node_parent = root.get();
		StdCopyStrBuf fn(def->Filename), fn2;
		StdCopyStrBuf fn_full;
		fn.ReplaceChar(AltDirectorySeparator, DirectorySeparator);
		for (;;)
		{
			bool is_parent_folder = fn.SplitAtChar(DirectorySeparator, &fn2);
			if (fn_full.getLength())
			{
				fn_full.AppendChar(DirectorySeparator);
			}
			fn_full.Append(fn);
			if (!is_parent_folder || WildcardMatch(C4CFN_DefFiles, fn.getData())) // ignore non-.ocd-folders (except for final definition)
			{
				// Find if path is already there
				RemoveExtension(&fn);
				DefListNode *node_child = nullptr;
				for (auto &test_node_child : node_parent->items)
					if (test_node_child->filename == fn)
					{
						node_child = &*test_node_child;
						break;
					}
				// If not, create it
				if (!node_child)
				{
					node_parent->items.emplace_back((node_child = new DefListNode()));
					node_child->idx = node_parent->items.size() - 1;
					node_child->parent = node_parent;
					const char *localized_name = ::Definitions.GetLocalizedGroupFolderName(fn_full.getData());
					node_child->name.Copy(localized_name ? localized_name : fn.getData());
					node_child->filename.Copy(fn);
				}
				// And fill in node if this is not a parent folder
				if (!is_parent_folder)
				{
					node_child->def = def;
					const char *def_name = def->GetName();
					if (def_name && *def_name) node_child->name.Copy(def_name);
					break;
				}
				else
				{
					// Parent folder: Next path segment
					node_parent = node_child;
				}
			}
			fn = fn2;
		}
	}
	// Descend into singleton root classes. I.e. if all elements are children of Objects/Items, move the root in there.
	DefListNode *new_root = root.get();
	while (new_root->items.size() == 1 && !new_root->items[0]->def)
	{
		std::unique_ptr<DefListNode> tmp(new_root->items[0].release());
		root.reset(tmp.release());
		new_root = root.get();
	}
	root->parent = nullptr;
	// Copy group path names into definitions for later lookup by script
	QStringList group_names;
	DefListNode *node = root.get();
	while (node)
	{
		if (node->def)
		{
			node->def->ConsoleGroupPath.Copy(group_names.join('/').toUtf8());
		}
		// Walk over tree. Remember groups in group_names string list.
		if (!node->items.empty())
		{
			if (node != root.get()) group_names.append(node->name.getData());
			node = node->items[0].get();
		}
		else
		{
			int32_t idx = node->idx + 1;
			while ((node = node->parent))
			{
				if (node->items.size() > idx)
				{
					node = node->items[idx].get();
					break;
				}
				if (group_names.size()) group_names.pop_back();
				idx = node->idx + 1;
			}
		}
	}
	// Sort everything by display name (recursively)
	root->SortByName();
	// Model reset to invalidate all indexes
	beginResetModel();
	endResetModel();
}
Пример #24
0
/////////////////////////////////////////////////////////////////////////////////////
//// MAIN PROGRAM
/////////////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv) {
    char* argv_conf[MAXOPT]; // Input arguments from .hhdefaults file (first=1: argv_conf[0] is not used)
    int argc_conf;               // Number of arguments in argv_conf

    strcpy(par.infile, "");
    strcpy(par.outfile, "");
    strcpy(par.alnfile, "");

    //Default parameter settings
    par.nseqdis = MAXSEQ - 1;        // maximum number of sequences to be written
    par.showcons = 0;
    par.cons = 1;
    par.Ndiff = 0;
    par.max_seqid = 100;
    par.coverage = 0;
    par.pc_hhm_context_engine.pca = 0.0;  // no amino acid pseudocounts
    par.pc_hhm_nocontext_a = 0.0;  // no amino acid pseudocounts
    par.gapb = 0.0; // no transition pseudocounts

    // Make command line input globally available
    par.argv = argv;
    par.argc = argc;
    RemovePathAndExtension(program_name, argv[0]);

    // Enable changing verbose mode before defaults file and command line are processed
    int v = 2;
    for (int i = 1; i < argc; i++) {
        if (!strcmp(argv[i], "-def"))
            par.readdefaultsfile = 1;
        else if (strcmp(argv[i], "-v") == 0) {
            v = atoi(argv[i + 1]);
        }
    }
    par.v = Log::from_int(v);
    Log::reporting_level() = par.v;

    par.SetDefaultPaths();

    // Read .hhdefaults file?
    if (par.readdefaultsfile) {
        // Process default otpions from .hhconfig file
        ReadDefaultsFile(argc_conf, argv_conf);
        ProcessArguments(argc_conf, argv_conf);
    }

    // Process command line options (they override defaults from .hhdefaults file)
    ProcessArguments(argc, argv);

    Alignment* qali = new Alignment(MAXSEQ, par.maxres);
    HMM* q = new HMM(MAXSEQDIS, par.maxres);        //Create a HMM with maximum of par.maxres match states

    // q is only available after maxres is known, so we had to move this here
    for (int i = 1; i <= argc - 1; i++) {
        if (!strcmp(argv[i], "-name") && (i < argc - 1)) {
            strmcpy(q->name, argv[++i], NAMELEN - 1); //copy longname to name...
            strmcpy(q->longname, argv[i], DESCLEN - 1);   //copy full name to longname
        }
    }

    // Check command line input and default values
    if (!*par.infile) {
        help();
        HH_LOG(ERROR) << "Input file is missing!" << std::endl;
        exit(4);
    }

    // Get basename
    RemoveExtension(q->file, par.infile); //Get basename of infile (w/o extension):

    // Outfile not given? Name it basename.hhm
    if (!*par.outfile && !*par.alnfile) {
        RemoveExtension(par.outfile, par.infile);
        strcat(par.outfile, ".seq");
    }

    // Prepare CS pseudocounts lib
    if (!par.nocontxt && *par.clusterfile) {
        InitializePseudocountsEngine(par, context_lib, crf, pc_hhm_context_engine,
                                     pc_hhm_context_mode, pc_prefilter_context_engine,
                                     pc_prefilter_context_mode);
    }

    // Set substitution matrix; adjust to query aa distribution if par.pcm==3
    SetSubstitutionMatrix(par.matrix, pb, P, R, S, Sim);

    // Read input file (HMM, HHM, or alignment format), and add pseudocounts etc.
    char input_format = 0;
    ReadQueryFile(par, par.infile, input_format, par.wg, q, qali, pb, S, Sim);

    // Same code as in PrepareQueryHMM(par.infile,input_format,q,qali), except that we add SS prediction
    // Add Pseudocounts, if no HMMER input
    if (input_format == 0) {
        // Transform transition freqs to lin space if not already done
        q->AddTransitionPseudocounts(par.gapd, par.gape, par.gapf, par.gapg,
                                     par.gaph, par.gapi, par.gapb, par.gapb);

        // Comput substitution matrix pseudocounts
        if (par.nocontxt) {
            // Generate an amino acid frequency matrix from f[i][a] with full pseudocount admixture (tau=1) -> g[i][a]
            q->PreparePseudocounts(R);
            // Add amino acid pseudocounts to query: p[i][a] = (1-tau)*f[i][a] + tau*g[i][a]
            q->AddAminoAcidPseudocounts(par.pc_hhm_nocontext_mode,
                                        par.pc_hhm_nocontext_a, par.pc_hhm_nocontext_b,
                                        par.pc_hhm_nocontext_c);
        }
        else {
            // Add full context specific pseudocounts to query
            q->AddContextSpecificPseudocounts(pc_hhm_context_engine,
                                              pc_hhm_context_mode);
        }
    }
    else {
        q->AddAminoAcidPseudocounts(0, par.pc_hhm_nocontext_a,
                                    par.pc_hhm_nocontext_b, par.pc_hhm_nocontext_c);
    }

    q->CalculateAminoAcidBackground(pb);

    if (par.columnscore == 5 && !q->divided_by_local_bg_freqs)
        q->DivideBySqrtOfLocalBackgroundFreqs(
            par.half_window_size_local_aa_bg_freqs, pb);

    // Write consensus sequence to sequence file
    // Consensus sequence is calculated in hhalignment.C, Alignment::FrequenciesAndTransitions()
    if (*par.outfile) {
        FILE* outf = NULL;
        if (strcmp(par.outfile, "stdout")) {
            outf = fopen(par.outfile, "a");
            if (!outf)
                OpenFileError(par.outfile, __FILE__, __LINE__, __func__);
        }
        else
            outf = stdout;
        // OLD
        //// ">name_consensus" -> ">name consensus"
        //strsubst(q->sname[q->nfirst],"_consensus"," consensus");
        //fprintf(outf,">%s\n%s\n",q->sname[q->nfirst],q->seq[q->nfirst]+1);
        // NEW (long header needed for NR30cons database)
        fprintf(outf, ">%s\n%s\n", q->longname, q->seq[q->nfirst] + 1);
        fclose(outf);
    }

    // Print A3M/A2M/FASTA output alignment
    if (*par.alnfile) {
        HalfAlignment qa;
        int n = imin(q->n_display,
                     par.nseqdis + (q->nss_dssp >= 0) + (q->nss_pred >= 0)
                     + (q->nss_conf >= 0) + (q->ncons >= 0));
        qa.Set(q->name, q->seq, q->sname, n, q->L, q->nss_dssp, q->nss_pred,
               q->nss_conf, q->nsa_dssp, q->ncons);

        if (par.outformat == 1)
            qa.BuildFASTA();
        else if (par.outformat == 2)
            qa.BuildA2M();
        else if (par.outformat == 3)
            qa.BuildA3M();
        if (qali->readCommentLine)
            qa.Print(par.alnfile, par.append, qali->longname); // print alignment to outfile
        else
            qa.Print(par.alnfile, par.append);   // print alignment to outfile
    }

    delete qali;
    delete q;

    DeletePseudocountsEngine(context_lib, crf, pc_hhm_context_engine,
                             pc_hhm_context_mode, pc_prefilter_context_engine,
                             pc_prefilter_context_mode);
}
Пример #25
0
bool C4MainMenu::ActivateSavegame(int32_t iPlayer)
{
	// Check if saving is possible
	if (!Game.CanQuickSave()) return false;

	// Menu symbol/init
	char DirPath[_MAX_PATH+1];
	char ScenName[_MAX_PATH+1]; *ScenName=0;

	InitRefSym(GfxR->fctMenu.GetPhase(0), LoadResStr("IDS_MENU_CPSAVEGAME"), iPlayer);
	SetAlignment(C4MN_Align_Left | C4MN_Align_Bottom);
	SetPermanent(true);

	// target file name mask
	// get folder & filename to store in
	// some magic is needed to ensure savegames are stored properly into their folders
	SCopy(GetFilename(Game.ScenarioFilename), DirPath);
	if (DirPath[strlen(DirPath) - 1] == '\\') DirPath[strlen(DirPath) - 1] = 0;
	RemoveExtension(DirPath);
	if (LooksLikeInteger(DirPath))
	{
		// ScenTitle.ocf\%d.ocs-names (old-style savegames)
		// get owning folder
		if (Game.pParentGroup)
		{
			// owning folder determines filename
			SCopy(GetFilenameOnly(Game.pParentGroup->GetName()), ScenName);
		}
		else
		{
			// no owning folder known: too bad
			// make a vague guess based on the scenario title
			SCopy(GetFilenameOnly(Game.ScenarioFilename), ScenName);
		}
	}
	else
	{
		// DirPath is a valid filename for now...
		SCopy(DirPath, ScenName);
		// but remove trailing numbers to adjust new-style savegames
		char *pScenNameEnd = ScenName+SLen(ScenName);
		while (Inside<char>(*--pScenNameEnd, '0', '9'))
			if (pScenNameEnd == ScenName)
			{
				// should not happen: digit-only-filenames should have been caught earlier
				SCopy("dbg_error!", ScenName);
				pScenNameEnd = ScenName+SLen(ScenName)-1;
			}
		pScenNameEnd[1]=0;
	}

	// New Style 2007:
	// * scenarios are saved into ScenName.ocf/ScenName123.ocs to keep umlauts out of filenames
	// * language titles are stored in folders as title component
	StdStrBuf strFilename, strTitle;
	strFilename.Format("%s.ocf%c%s%%d.ocs", ScenName, DirectorySeparator, ScenName);
	strTitle = Game.ScenarioTitle;

	// Create menu items
	StdStrBuf strFilenameIndexed, strCommand, strCaption, strSavePath;
	for (int32_t i = 1; i <= 10; i++)
	{
		// Index filename
		strFilenameIndexed.Format(strFilename.getData(), i);
		// Compose commmand
		strCommand.Format("Save:Game:%s:%s", strFilenameIndexed.getData(), strTitle.getData()); // Notice: the language title might contain ':' and thus confuse the segment list - but C4Menu::MenuCommand will try to handle this...
		// Check free slot
		strSavePath.Format("%s%c%s", Config.AtUserDataPath(C4CFN_Savegames), DirectorySeparator, strFilenameIndexed.getData());
		bool fFree = !C4Group_IsGroup(strSavePath.getData());
		// Item caption
		strCaption = LoadResStr("IDS_MENU_CPSAVEGAME");
		// add menu item
		AddRefSym(strCaption.getData(), GfxR->fctMenu.GetPhase(i - 1, fFree ? 2 : 1), strCommand.getData(), C4MN_Item_NoCount, NULL, LoadResStr("IDS_MENU_CPSAVEGAMEINFO"));
	}

	// Go back to options menu on close
	SetCloseCommand("ActivateMenu:Main");

	return true;
}
Пример #26
0
TRISTATE CFileFinder::FindFiles(char* szInDirectory, BOOL bDirs, char* szInName, char* szExtension)
{
	DIR*                pDIR;
	struct dirent*      pDirEnt;
	char				szFindName[MAX_PATH];
	char				szTemp[MAX_PATH];
	BOOL				bValid;
	char				szDirectory[MAX_PATH];
	char				szFile[MAX_PATH];
	char*				szFileExtension;
	int                 iStatus;
	struct stat         sBuffer;
	BOOL                bDir;
	CFileUtil           cFileUtil;

	if (!cFileUtil.FullPath(szDirectory, szInDirectory, MAX_PATH))
	{
		return TRIERROR;
	}

	pDIR = opendir(szDirectory);

	if (pDIR == NULL)
	{
		return TRITRUE;
	}

	pDirEnt = readdir(pDIR);
	while (pDirEnt != NULL)
	{
		bValid = TRUE;

		sprintf(szTemp, "%s%s%s", szDirectory, FILE_SEPARATOR, pDirEnt->d_name);
		iStatus = stat(szTemp, &sBuffer);
		if (iStatus == -1)
		{
			printf("%s: %s\n", strerror(errno), szTemp);
			return TRIERROR;
		}
		bDir = S_ISDIR(sBuffer.st_mode);
		if (bDir) //Directory
		{
			if (bDirs)
			{
				if (szInName != NULL)
				{
					strcpy(szFile, pDirEnt->d_name);
					RemoveExtension(szFile);
					if (StrIStr(szFile, szInName) == NULL)
					{
						bValid = FALSE;
					}
				}
				else
				{
					bValid = FALSE;
				}
			}
		}
		else
		{
			if (!bDirs)
			{
				if (szExtension != NULL)
				{
					szFileExtension = FindExtension(pDirEnt->d_name);
					szFileExtension++;
					if (StrICmp(szFileExtension, szExtension) != 0)
					{
						bValid = FALSE;
					}
				}
				if (szInName != NULL)
				{
					strcpy(szFile, pDirEnt->d_name);
					RemoveExtension(szFile);
					if (StrIStr(szFile, szInName) == NULL)
					{
						bValid = FALSE;
					}
				}
			}
			else
			{
				bValid = FALSE;
			}
		}

		if (bValid)
		{
			mcFiles.Add(szTemp, 0);
		}

		pDirEnt = readdir(pDIR);
	}

	closedir(pDIR);
	return TRITRUE;
}
Пример #27
0
void GetFileNameNoExtension(char* Result, const char* Path)
{
	const char* FileName = GetFileName(Path);
	RemoveExtension(Result, FileName);
}