/// <summary> /// Global method for entities generation /// </summary> /// <param name="inputPath">The input path</param> /// <param name="output">Output stream</param> static void GenerateEntities(string inputPath, TextWriter output, string language) { output.WriteLine("<wis>"); var jarRoot = StanfordEnv.GetStanfordHome(); var classifiersDirectory = jarRoot + StanfordEnv.CLASIFIERS; string[] fileEntries = FilesUtils.GetFiles(inputPath); foreach (var document in fileEntries) { string text = FilesUtils.FileToText(document); // XXX: Better a NullObject, but string can't be inherited I think. if (text == null) { var stderr = new StreamWriter(Console.OpenStandardError()); stderr.WriteLine($"The file '{document}' is not supported"); stderr.Close(); continue; } var classifier = CRFClassifiers.GetClassifierByLang(language); //CRFClassifier.getClassifierNoExceptions(classifiersDirectory + StanfordEnv.GetNerLanguageFiles(language)); output.WriteLine(classifier.classifyToString(text, "xml", true)); } output.WriteLine("</wis>"); }
}// end method string CompareSeedValues() /// <summary> /// Writes the current seed values to a file. /// </summary> /// <returns>Whether the process is completed or not</returns> public bool LogCurrentSeeds() { var isDone = false; try { var lastSeeds = GetCurrentSeed(); long lastUserID = lastSeeds[0], lastIssuerID = lastSeeds[1], lastBranchID = lastSeeds[2], lastUserGroupID = lastSeeds[3], lastProductID = lastSeeds[4]; var logMsg = string.Format("{0},{1},{2},{3},{4}", lastUserID, lastIssuerID, lastBranchID, lastUserGroupID, lastProductID); var fileName = string.Format("{0}{1}", seedDirPath, DateTime.Now.ToString("dd-MMM-yy hh mm ss")); isDone = FilesUtils.CreateFile(fileName, logMsg, FileExtension.CSV); }// end try catch { throw; }// end catch return(isDone); }// end method bool LogCurrentSeeds()
private static async Task Find(IServiceProvider serviceProvider, Command cmd, FindOptions options) { var search = serviceProvider.GetService <ISearch>(); var results = await search.Get(cmd.Value, options); if (results.Any()) { var displayResultsHandler = serviceProvider.GetService <IDisplayResults>(); var optionsToDisplay = results.Select(r => $"{r.Folder} => {r.Name}{r.Extention}").Distinct().ToList(); var selection = displayResultsHandler.ShowResultsAndGetSelection(optionsToDisplay, cmd.Value); System.Console.WriteLine(Environment.NewLine); if (selection != -1) { var selectedResult = results.ToArray()[selection]; await search.Select(selectedResult); if (!options.DisplayResultInTerminal) { FilesUtils.OpenFolder(selectedResult.Folder); } else { FilesUtils.ChangeDir(selectedResult.Folder); } } } else { System.Console.WriteLine($"qfind didnt find any results for {cmd.Value}"); } }
public IEnumerable <VideosListItem> GetOutputFiles() { return(new DirectoryInfo(GetRootPath(MediaType.Output)) .GetFiles() .Where(f => Constants.VideoFormatsExtensions.Contains(f.Extension.ToLowerInvariant())) .Select(f => new VideosListItem(f.Name, FilesUtils.BytesToMB(f.Length)))); }
/// <summary> /// Load the VTF files in the given directory and add them to the list /// </summary> /// <param name="directory"></param> private void BrowseVTFDirectory(string directory) { if (directory != null) { VTF_ListBox.Items.Clear(); BrowseSelectAll_Uncheck(); BrowseSelectAll_Hide(); PreviewGenerateButtons_Disable(); PreviewGenerateButtons_Hide(); if (System.IO.Directory.Exists(directory)) { if (System.IO.Path.IsPathRooted(directory)) { string[] vtfsList = FilesUtils.TryGetFilesDirectory(directory, VMTUtils.ExtensionsVTF); if (vtfsList != null) { foreach (string vtfFile in vtfsList) { ListBoxItem lbi = new ListBoxItem { Content = System.IO.Path.GetFileName(vtfFile) }; VTF_ListBox.Items.Add(lbi); } outputPath = directory; UpdateVisibility_Buttons(); } } } } }
public static void CreatAssetViewConst(Dictionary <string, BuildAddressablesData> bundles) { string[] resSpit; string labs; string temp = "public class ViewConst{0}{1}{2}"; StringBuilder build = new StringBuilder(); build.AppendLine(""); foreach (string bundlesKey in bundles.Keys) { labs = ""; for (int i = 0; i < bundles[bundlesKey].Lable.Length; i++) { labs += bundles[bundlesKey].Lable[i]; labs += ";"; } string des = string.Format("//Group:{0} ;Label:{1}", bundles[bundlesKey].GroupName, labs); foreach (string entitysKey in bundles[bundlesKey].entitys.Keys) { resSpit = entitysKey.Split('.'); build.AppendLine(des); build.AppendLine(string.Format(" public const string {0} = {2}{1}{2};", string.Format("{0}_{1}", resSpit[1], resSpit[0]), entitysKey, "\"")); } } temp = string.Format(temp, "{", build.ToString(), "}"); if (File.Exists(Application.dataPath + "/ViewConst.cs")) { File.Delete(Application.dataPath + "/ViewConst.cs"); } FilesUtils.CreateTextFile(Application.dataPath + "/ViewConst.cs", temp); }
/// <summary> /// Generates the match between textentities and dictionary entities. /// </summary> /// <param name="options">Options.</param> public override void Run() { if (options.Verbose) { Console.Error.WriteLine("Option 3."); } if (options.Dictionary == null) { Console.Error.WriteLine("Dictionary required. Exiting..."); return; } TextWriter output; if (string.IsNullOrEmpty(options.Output)) { output = new StreamWriter(Console.OpenStandardOutput()); } else { output = new StreamWriter(options.Output); } foreach (string dic in FilesUtils.GetFiles(options.Dictionary)) { DictionaryMatcher.MatchEntitiesInFiles(options.InputFile, dic, output, options.Separator, options.Language); } output.Close(); }
public void HandleInput(string[] args) { var(item1, item2) = ParseArgs(args); var files = FilesUtils.GetAllFiles(item1, item2); CountLines(files, out var res); res.FilesFound = files; _view.PrintStatistic(res); }
public Match(string filePath, List <string[]> items) { Text = FilesUtils.FileToText(filePath); FilePath = filePath; if (Text == null) { throw new ArgumentException(); } Items = items; }
/// <summary> /// Generates migration reports for an issuer being migrated /// </summary> /// <param name="selectedIssuer"></param> /// <returns></returns> public static bool GenerateReport(DbContext context, dynamic selectedIssuer, bool afterReportMigration = false) { var isDone = false; try { if (!Directory.Exists(reportScriptPath)) { throw new Exception("Scripts' Reports directory could not be located!"); } var scriptFiles = Directory.GetFiles(reportScriptPath); for (int i = 0; i < scriptFiles.Length; i++) { scriptFiles[i] = scriptFiles[i].Replace(@"\", "/"); }// end for (int i = 0; i < scriptFiles.Length; i++) var cardsReport = GenerateCardsReport(context, scriptFiles, selectedIssuer); var branchesReport = GenerateBranchesReport(context, scriptFiles, selectedIssuer); var usersReport = GenerateUsersReport(context, scriptFiles, selectedIssuer); var userGroupsReport = GenerateUserGroupsReport(context, scriptFiles, selectedIssuer); var reportVersion = afterReportMigration ? "After" : "Original"; var cardsReportName = string.Format("{0}{1}/{1} Cards Report {2}", @"/Reports/", selectedIssuer.issuer_name, reportVersion); var branchReportName = string.Format("{0}{1}/{1} Branches Report {2}", @"/Reports/", selectedIssuer.issuer_name, reportVersion); var usersReportName = string.Format("{0}{1}/{1} Users Report {2}", @"/Reports/", selectedIssuer.issuer_name, reportVersion); var usergroupsReportName = string.Format("{0}{1}/{1} User Groups Report {2}", @"/Reports/", selectedIssuer.issuer_name, reportVersion); isDone = FilesUtils.CreateFile(branchReportName, branchesReport, FileExtension.CSV, FileMode.Create); if (isDone) { isDone = FilesUtils.CreateFile(cardsReportName, cardsReport, FileExtension.CSV, FileMode.Create); } if (isDone) { isDone = FilesUtils.CreateFile(usersReportName, usersReport, FileExtension.CSV, FileMode.Create); } if (isDone) { isDone = FilesUtils.CreateFile(usergroupsReportName, userGroupsReport, FileExtension.CSV, FileMode.Create); } }// end try catch { throw; }// end catch return(isDone); }// end method bool GenerateReport(issuer theIssuer)
private void timer_Tick(object sender, EventArgs e) { for (int i = 0; i < DirectoriesCount; i++) { var path = FilesUtils.GetFilePath(DirectoriesFactory.Instance.GetDirectory(i, _rootDirectory, Extensions), Extensions, _counter); Images[i].Title = FilesUtils.GetFileName(path); Images[i].Path = new Uri(path, UriKind.Relative); } if (++_counter == _imagecounter) { _counter = 0; } }
public void GetImages(string selectedPath) { _rootDirectory = selectedPath; Images.Clear(); DirectoriesCount = DirectoriesUtils.DirectoriesWithFilesByExtensionsCount(_rootDirectory, Extensions); _imagecounter = FilesUtils.GetFilesCount(DirectoriesFactory.Instance.GetDirectory(0, _rootDirectory, Extensions), Extensions); for (var i = 0; i < DirectoriesCount; i++) { Images.Add(ImagesFactory.Instance.GetImageModel(i, DirectoriesFactory.Instance.GetDirectory(i, selectedPath, Extensions))); if (i > 0 && _imagecounter != FilesUtils.GetFilesCount(DirectoriesFactory.Instance.GetDirectory(i, _rootDirectory, Extensions), Extensions)) { throw new Exception("Images count in folders not equal"); } } }
/// <summary> /// Writes to the output stream a csv with the match results against the dictionary /// </summary> /// <param name="inputPath">Files path.</param> /// <param name="dicPath">Dictionary path.</param> /// <param name="output">Output stream.</param> public static void MatchEntitiesInFiles(string inputPath, string dicPath, TextWriter output, char sep, string language) { string[] files = FilesUtils.GetFiles(inputPath); foreach (string file in files) { string xml = NER.GenerateEntitiesToString(file, language); string csv = CSVUtils.RemoveDuplicates(CSVUtils.EntitiesToCsv(xml, sep)); List <string[]> dicTable = CSVUtils.TabulateCSV(new StreamReader(dicPath), sep); List <string[]> fileTable = CSVUtils.TabulateCSV(new StringReader(csv), sep); List <string> entitiesTable = GetEntitiesFromDic(dicTable); var matchs = MatchEntities(fileTable, entitiesTable); GenerateMatchedEntriesCSV(file, dicPath, matchs, output, sep); } }
public static void SaveResultToFile(string answer) { while (true) { try { string filePath = ConsoleUtils.IOUtils.ReadValueFromConsole <string>("путь к выходному файлу"); FilesUtils.Write(filePath, answer); return; } catch (Exception e) { ConsoleUtils.IOUtils.ShowError("Невозможно записать данные в этот файл"); } } }
static int[,] ReadArrFromFile() { while (true) { try { string filePath = ConsoleUtils.IOUtils.ReadValueFromConsole <string>("путь к входному файлу"); string arrText = FilesUtils.Read(filePath); return(DataConverter.StrToArray2D <int>(arrText)); } catch (Exception e) { ConsoleUtils.IOUtils.ShowError("Невозможно считать данные из этого файла"); } } }
private void сохранитьToolStripMenuItem_Click(object sender, EventArgs ee) { if (saveFileDialog.ShowDialog() == DialogResult.OK) { try { string result = Convert.ToString(label1); FilesUtils.Write(saveFileDialog.FileName, result); MessagesUtils.Show("Данные сохранены"); } catch (Exception e) { MessagesUtils.ShowError("Ошибка сохранения данных"); } } }
private string GenerateVMT(string vtfName) { StringBuilder sb = new StringBuilder(); string vmtFilePath = VMTUtils.GetVMTFilePath(OutputPath, vtfName); string vmtString = VMTUtils.GetVMTString(VMTData, vtfName); bool success = FilesUtils.TryWriteAllText(vmtFilePath, vmtString); if (success) { sb.Append($"Generated {vtfName}.vmt in \"{OutputPath}\""); } else { sb.Append($"Unable to create {vtfName}.vmt in \"{OutputPath}\""); } sb.AppendLine(); return(sb.ToString()); }
private void MainMenuFileOpen_Click_1(object sender, EventArgs e) { if (OpenFileDialog.ShowDialog() == DialogResult.OK) { try { string path = OpenFileDialog.FileName; List <Programmer> prList = FilesUtils.ReadFromFile(path); DgvConvert.ListToDgv(InputDGV, prList); MessagesUtils.ShowMessage("Данные загружены из файла"); } catch (Exception ex) { MessagesUtils.ShowError("Ошибка чтения из файла"); } } }
private void MainMenuFileSave_Click(object sender, EventArgs e) { if (SaveFileDialog.ShowDialog() == DialogResult.OK) { try { string path = SaveFileDialog.FileName; List <Programmer> list = DgvConvert.DgvToList(InputDGV); FilesUtils.SaveToFile(path, list); MessagesUtils.ShowMessage("Данные сохранены в файл"); } catch (Exception ex) { MessagesUtils.ShowError("Ошибка сохранения в файл"); } } }
// Загружает игровое поле из файла private static CubiconCell[,] LoadLevelFieldFromFile(string path) { string levelStr = FilesUtils.Read(path); string[] rows = levelStr.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); // Если прочитали пустой набор столбцов if (rows.Length == 0) { throw new Exception(); } string[] firstRowParts = rows[0].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); // Создаём массив для хранения данных поля int rowsCount = rows.Length; int colsCount = firstRowParts.Length; CubiconCell[,] field = new CubiconCell[rows.Length, firstRowParts.Length]; // Заполняем массив поля for (int i = 0; i < rowsCount; i++) { string[] rowParts = rows[i].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (rowParts.Length != colsCount) { throw new Exception(); } for (int j = 0; j < colsCount; j++) { field[i, j] = new CubiconCell(); field[i, j].Row = i; field[i, j].Col = j; field[i, j].State = states[int.Parse(rowParts[j])]; } } return(field); }
private void открытьToolStripMenuItem_Click(object sender, EventArgs ee) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { try { string arrText = FilesUtils.Read(openFileDialog1.FileName); int[,] arr = DataConverter.StrToArray2D <int>(arrText); DataGridViewUtils.Array2ToGrid(dataGridView, arr); MessagesUtils.Show("Данные загружены"); } catch (Exception e) { MessagesUtils.ShowError("Ошибка загрузки данных"); } } }
private void MainMeneFileSave_Click(object sender, EventArgs ev) { if (SaveFileDialog.ShowDialog() == DialogResult.OK) { try { // Преобразуем содержимое DataGridView в массив int[,] arr = DataGridViewUtils.GridToArray2 <int>(outputDataGridView); // Записываем полученный массив в файл, предварительно // преобразовав его в строку FilesUtils.Write(SaveFileDialog.FileName, DataConverter.Array2DToStr <int>(arr)); MessagesUtils.Show("Данные сохранены"); } catch (Exception e) { MessagesUtils.ShowError("Ошибка сохранения данных"); } } }
public static void SaveResultToFile(string answer) { while (true) { try { string filePath = IOUtils.ReadValueFromConsole <string>("путь к выходному файлу"); // Пытаемся записать данные в файл и выйти из метода FilesUtils.Write(filePath, answer); return; } catch (Exception e) { // Если во время считывания из файла ошибка, то выводим её, // а затем просим ввести путь ещё раз IOUtils.ShowError("Невозможно записать данные в этот файл"); } } }
private void MainMeneFileOpen_Click(object sender, EventArgs ev) { if (LoadFileDialog.ShowDialog() == DialogResult.OK) { try { // Читаем содержимое выбранного файла и преобразуем его в массив string arrText = FilesUtils.Read(LoadFileDialog.FileName); int[,] arr = DataConverter.StrToArray2D <int>(arrText); // Копируем полученный массив в DataGridView DataGridViewUtils.Array2ToGrid(inputDataGridView, arr); MessagesUtils.Show("Данные загружены"); } catch (Exception e) { MessagesUtils.ShowError("Ошибка загрузки данных"); } } }
static int[,] ReadArrFromFile() { while (true) { try { string filePath = IOUtils.ReadValueFromConsole <string>("путь к входному файлу"); // Считываем данные из файла, преобразовываем их в массив // и возвращаем вызывающему коду string arrText = FilesUtils.Read(filePath); return(DataConverter.StrToArray2D <int>(arrText)); } catch (Exception e) { // Если во время считывания из файла ошибка, то выводим её, // а затем просим ввести путь ещё раз IOUtils.ShowError("Невозможно считать данные из этого файла"); } } }
private void Open_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) { try { // Читаем содержимое выбранного файла и преобразуем его в массив string arrText = FilesUtils.Read(openFileDialog.FileName); int[,] arr = helper.StrToArray2D <int>(arrText); // Копируем полученный массив в DataGridView DataGridViewUtils.Array2ToGrid(inputGrid, arr); MessagesUtils.Show("Данные загружены. Можем начинать!"); } catch { MessagesUtils.ShowError("Ошибка загрузки данных"); } } }
private void MainMenuFileSave_Click(object sender, EventArgs e) { try { // Записываем текст из блока результатов вычислений в файл string answer = OutputTextLbl.Text; if (answer == "") { throw new Exception(); } if (SaveFileDialog.ShowDialog() == DialogResult.OK) { FilesUtils.Write(SaveFileDialog.FileName, answer); MessagesUtils.Show("Данные сохранены"); } } catch (Exception exception) { MessagesUtils.ShowError("Ошибка сохранения данных"); } }
}// end method bool DatabaseExists() public bool SetupDatabase(string masterKey) { var isDone = false; var scripts = FilesUtils.GetSQLScript("Create"); if (scripts.Count <= 0) { throw new Exception("No setup scripts in directory."); } var keys = scripts.Keys.ToList(); keys.Sort(); using (SqlConnection conn = new SqlConnection("data source=veneka-dev;integrated security=True;App=EntityFramework")) { Server server = new Server(new ServerConnection(conn)); Console.WriteLine("Connecting to Database Server..."); server.ConnectionContext.Connect(); //server.ConnectionContext.BeginTransaction(); try { double total = 0; Stopwatch sw = new Stopwatch(); foreach (var key in keys) { var script = scripts[key]; string scriptText = String.Empty; using (var reader = script.OpenText()) scriptText = reader.ReadToEnd(); if (scriptText.Contains("{DATABASE_NAME}")) { scriptText = scriptText.Replace("{DATABASE_NAME}", NewIndigoDataModel.Database.Connection.Database); } if (scriptText.Contains("{MASTER_KEY}")) { scriptText = scriptText.Replace("{MASTER_KEY}", masterKey); } if (scriptText.Contains("{EXPITY_DATE}")) { scriptText = scriptText.Replace("{EXPITY_DATE}", DateTime.Now.AddYears(10).ToString("yyyyMMdd")); } Console.WriteLine("Start Executing Script: " + script.Name); sw.Restart(); int result = server.ConnectionContext.ExecuteNonQuery(scriptText); sw.Stop(); total += sw.Elapsed.TotalMilliseconds; Console.WriteLine("End Executing Script, elapsed time: {0}ms", sw.Elapsed.TotalMilliseconds); } Console.WriteLine("Done creating schema, total time: {0}ms.", total); Console.WriteLine("Validating Schema."); var newDB = server.Databases[NewIndigoDataModel.Database.Connection.Database]; if (newDB != null) { StringBuilder sb = new StringBuilder(); var dir = Directory.CreateDirectory(Path.Combine("C:\\veneka\\Migration\\", DateTime.Now.ToString("yyyyMMddhhmmss"))); //Tables foreach (Table table in newDB.Tables) { sb.AppendLine(table.Name); } sb.AppendLine("Total: " + newDB.Tables.Count); File.WriteAllText(Path.Combine(dir.FullName, "tables.txt"), sb.ToString()); //Views sb.Clear(); int viewCount = 0; foreach (View view in newDB.Views) { if (view.Schema == "dbo") { viewCount++; sb.AppendLine(view.Name); } } sb.AppendLine("Total: " + viewCount); File.WriteAllText(Path.Combine(dir.FullName, "views.txt"), sb.ToString()); //SPs int spCount = 0; sb.Clear(); foreach (StoredProcedure sp in newDB.StoredProcedures) { if (sp.Schema != "sys") { spCount++; sb.AppendLine(sp.Name); } } sb.AppendLine("Total: " + spCount); File.WriteAllText(Path.Combine(dir.FullName, "storedProcs.txt"), sb.ToString()); sb.Clear(); //MasterKey sb.Clear(); sb.AppendLine("Master Key: created " + newDB.MasterKey.CreateDate); //SymmetricKeys foreach (SymmetricKey key in newDB.SymmetricKeys) { sb.AppendLine("SymmetricKey: " + key.Name + " " + key.EncryptionAlgorithm + " " + key.KeyLength); } sb.AppendLine("Total SymmetricKeys: " + newDB.SymmetricKeys.Count); //Certificates foreach (Certificate cert in newDB.Certificates) { sb.AppendLine("Certificate:" + cert.Name + " " + cert.ExpirationDate + " " + cert.PrivateKeyEncryptionType); cert.Export(Path.Combine("C:\\Veneka\\Migration\\", cert.Name + ".crt"), Path.Combine("C:\\Veneka\\Migration\\", cert.Name + "_pvtKey"), "Jungle01$"); } sb.AppendLine("Total Certificates: " + newDB.Certificates.Count); File.WriteAllText(Path.Combine(dir.FullName, "encryption.txt"), sb.ToString()); sb.Clear(); string MasterKeyFile = Path.Combine("C:\\Veneka\\Migration\\", "MaskterKey"); //BackupKeys newDB.MasterKey.Export(MasterKeyFile, "Jungle01$"); if (newDB.Tables.Count == 155 && spCount == 355 && viewCount == 13 && newDB.SymmetricKeys.Count == 3 && newDB.Certificates.Count == 3) { isDone = true; } } //trn.Commit(); //} //server.ConnectionContext.CommitTransaction(); } //catch //{ // //server.ConnectionContext.RollBackTransaction(); // throw; //} finally { server.ConnectionContext.Disconnect(); } } return(isDone); }// end method bool SetupDatabase()
/// <summary> /// Event Handler for the Browse button /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BrowseButton_Click(object sender, RoutedEventArgs e) { string directory = FilesUtils.OpenFolderDialog(); BrowseVTFDirectory(directory); }
public static bool CheckLangFiles(String language) { return(FilesUtils.ExistsModels(StanfordEnv.PARSER_MODELS + @"/lexparser/" + language + @"PCFG.ser.gz")); }