public void CanCheckForPathExistenceUsingNormalSlashInsteadOfBackslash() { var pathStr = @"c:\whatever;d:\omg"; var path = new Paths(pathStr); path.Contains(@"c:/whatever/").Should().Be.True(); }
public void CanCheckForPathExistenceUsingDifferentCasing() { var pathStr = @"c:\whatever;d:\omg"; var path = new Paths(pathStr); path.Contains(@"C:/Whatever/").Should().Be.True(); }
private static async Task ConvertAsync(TopicData topic, IDictionary<string, TopicData> name2topic, Paths paths, IFile destFile, CancellationToken cancellationToken) { using (var destStream = await destFile.OpenAsync(FileAccess.ReadAndWrite, cancellationToken)) { await ConvertAsync(topic, destStream, name2topic, paths, cancellationToken); } }
private static async Task ConvertAsync(TopicData topic, Stream destStream, IDictionary<string, TopicData> name2topic, Paths paths, CancellationToken cancellationToken) { using (var writer = new StreamWriter(destStream)) { await Writers.TopicWriter.WriteAsync(topic, name2topic, writer, paths, cancellationToken); } }
public void CanCheckForPathExistenceUsingSameTrailingSlashNormalization() { var pathStr = @"c:\whatever;d:\omg"; var path = new Paths(pathStr); path.Contains(@"c:\whatever").Should().Be.True(); }
public void AddPaths(Paths poly) { if (poly.Count == 0) return; PolyInfo pi = new PolyInfo(); pi.polygons = poly; pi.si = style.Clone(); PolyInfoList.Add(pi); }
/// <summary> /// Converts the topic to MAML. /// </summary> /// <param name="paths">Paths.</param> /// <param name="name2topic">Mapping from topic name to data.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <param name="progress">Progress indicator.</param> /// <returns>Asynchronous task.</returns> public static async Task ConvertAsync(Paths paths, IDictionary<string, TopicData> name2topic, CancellationToken cancellationToken = default(CancellationToken), IProgress<Indicator> progress = null) { var topicsArray = name2topic.Values.ToArray(); var count = topicsArray.Length; Indicator.Report(progress, count); for (var index = 0; index < count; index++) await ConvertAsync(topicsArray[index], paths, name2topic, cancellationToken, progress, index, count); }
public void CanFindIndividualPathItems() { var pathStr = @"c:\whatever;d:\omg"; var path = new Paths(pathStr); path.Should().Have.SameSequenceAs( @"c:\whatever", @"d:\omg"); }
public void CanGetPathStringFromPathList() { var path = new Paths(""); path.Add(@"c:\a"); path.Add(@"d:\b"); path.Add(@"e:/C"); path.ToString().Should().Be(@"c:\a\;d:\b\;e:\c\"); }
/// <summary> /// Matches the topics to their IDs from content layout and creates a mapping from topic name to topic. /// </summary> /// <param name="topics">The topics.</param> /// <param name="paths">Paths.</param> /// <param name="title2id">Gets the topic ID from the topic title.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <param name="progress">Progress indicator.</param> /// <returns>Matched topic mapping.</returns> public static async Task<Dictionary<string, TopicData>> MatchAsync(IEnumerable<TopicData> topics, Paths paths, IDictionary<string, Guid> title2id, CancellationToken cancellationToken = default(CancellationToken), IProgress<Indicator> progress = null) { var topicsArray = topics.ToArray(); var count = topicsArray.Length; Indicator.Report(progress, count); var tasks = Enumerable.Range(0, count).Select(index => MatchAsync(topicsArray[index], paths, title2id, cancellationToken, progress, count, index)); topics = await Task.WhenAll(tasks); return topics.ToDictionary(topic => topic.Name, topic => topic); }
public void AddingNonNormalizedPathWillNormalizeAndAddItToList() { var pathStr = @"c:\whatever;d:\omg"; var path = new Paths(pathStr); path.Add("E:/Wtf").Should().Be(@"e:\wtf\"); path.Should().Have.SameSequenceAs( @"c:\whatever", @"d:\omg", @"e:\wtf\"); }
/// <summary> /// Parses the topics. /// </summary> /// <param name="topics">The topics.</param> /// <param name="paths">Paths.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <param name="progress">Progress indicator.</param> /// <returns>Parsed topics.</returns> public static async Task<IEnumerable<TopicData>> ParseAsync(IEnumerable<TopicData> topics, Paths paths, CancellationToken cancellationToken = default(CancellationToken), IProgress<Indicator> progress = null) { var topicsArray = topics.ToArray(); var count = topicsArray.Length; Indicator.Report(progress, count); var tasks = Enumerable.Range(0, count).Select(index => ParseAsync(topicsArray[index], paths, cancellationToken, progress, index, count)); await Task.WhenAll(tasks); return topics; }
/// <summary> /// Parses the topic. /// </summary> /// <param name="topic">The topic.</param> /// <param name="paths">Paths.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <param name="progress">Progress indicator.</param> /// <param name="index">Index.</param> /// <param name="count">Count.</param> /// <returns>Parsed topic.</returns> public static async Task<TopicParserResult> ParseAsync(TopicData topic, Paths paths, CancellationToken cancellationToken, IProgress<Indicator> progress = null, int index = 0, int count = 0) { var srcFilePath = Path.Combine(paths.Source, topic.RelativePath, topic.FileName); var file = await FileSystem.Current.GetFileFromPathAsync(srcFilePath, cancellationToken) .ConfigureAwait(false); using (var stream = await file.OpenAsync(FileAccess.Read, cancellationToken)) using (var reader = new StreamReader(stream)) { var parserResult = topic.ParserResult = TopicParser.Parse(reader); Indicator.Report(progress, count, index + 1, () => Path.Combine(topic.RelativePath, topic.Name)); return parserResult; } }
/// <summary> /// Converts the topic to MAML. /// </summary> /// <param name="topic">Topic data.</param> /// <param name="paths">Paths.</param> /// <param name="name2topic">Mapping from topic name to data.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <param name="progress">Progress indicator.</param> /// <param name="index">Index.</param> /// <param name="count">Count.</param> /// <returns>Asynchronous task.</returns> public static async Task ConvertAsync(TopicData topic, Paths paths, IDictionary<string, TopicData> name2topic, CancellationToken cancellationToken, IProgress<Indicator> progress = null, int index = 0, int count = 0) { var destDir = Path.Combine(paths.Destination, topic.RelativePath); var fileName = Path.GetFileName(topic.FileName); var destName = Path.ChangeExtension(fileName, ".aml"); var destFolder = await FileSystem.Current.LocalStorage.CreateFolderAsync(destDir, CreationCollisionOption.OpenIfExists, cancellationToken); var destFile = await destFolder.CreateFileAsync(destName, CreationCollisionOption.ReplaceExisting, cancellationToken); await ConvertAsync(topic, name2topic, paths, destFile, cancellationToken); Indicator.Report(progress, count, index + 1, () => Path.Combine(topic.RelativePath, topic.Name)); }
/// <summary> /// Initializes a new instance of maze cell with locations /// </summary> /// <param name="location">The location on the graphics surface</param> /// <param name="position">The location on the 2d array</param> public unsafe Cell(Point location, Point position) { this.location = location; this.position = position; // initially, all walls are intact this.LeftWall = true; this.RightWall = true; this.UpWall = true; this.DownWall = true; this.Path = Paths.None; // must be initialized, since it is a member of a struct this.Visited = false; this.Previous = null; }
/// <summary> /// Indexes the content layout. /// </summary> /// <param name="paths">Paths.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>Mapping from topic title to its ID.</returns> public static async Task<IDictionary<string, Guid>> IndexAsync(Paths paths, CancellationToken cancellationToken) { var title2id = new Dictionary<string, Guid>(); var layoutPath = paths.ContentLayout; if (layoutPath == null) return title2id; ContentLayout layout; var file = await FileSystem.Current.GetFileFromPathAsync(layoutPath, cancellationToken) .ConfigureAwait(false); using (var stream = await file.OpenAsync(FileAccess.Read, cancellationToken)) using (var reader = new StreamReader(stream)) { var serializer = new XmlSerializer(typeof(ContentLayout)); layout = (ContentLayout)serializer.Deserialize(reader); } return Index(title2id, layout.Topics); }
public static Paths ParsePathsFile(string[] fileLines) { Paths p = new Paths(); foreach (string l in fileLines) { //Ignore whitspace lines if (l.Trim().Length == 0) continue; //Ignore comment lines if (l.Trim().StartsWith("#")) continue; string[] parts = l.Trim().Split('='); if (parts.Length < 2) { Logger.LogWarning("Ignoring " + l + " in " + PATHS_FILE); continue; } if (!parts[1].EndsWith("\\")) parts[1] += '\\'; switch (parts[0].ToLower()) { case "articlesdir": p.ArticlesRootDir = parts[1].Trim(); break; case "virtualarticlesdir": p.VirtualArticlesRootDir = parts[1].Trim(); break; case "templatesdir": p.TemplatesRootDir = parts[1].Trim(); break; case "macrosdir": p.MacrosRootDir = parts[1].Trim(); break; case "outputdir": p.OutputRootDir = parts[1].Trim(); break; default: break; } } return p; }
public Task Call(IDictionary<string, object> env) { var paths = new Paths(env); var path = paths.Path; var pathBase = paths.PathBase; var match = _map.FirstOrDefault(m => path.StartsWith(m.Item1)); if (match == null) { // fall-through to default return _defaultApp(env); } // Map moves the matched portion of Path into PathBase paths.PathBase = pathBase + match.Item1; paths.Path = path.Substring(match.Item1.Length); return match.Item2.Invoke(env).Then(() => { // Path and PathBase are restored as the call returns paths.Path = path; paths.PathBase = pathBase; }); }
public void Call( IDictionary<string, object> env, ResultDelegate result, Action<Exception> fault) { var paths = new Paths(env); var path = paths.Path; var pathBase = paths.PathBase; Action finish = () => { paths.Path = path; paths.PathBase = pathBase; }; var match = _map.FirstOrDefault(m => path.StartsWith(m.Item1)); if (match == null) { // fall-through to default _app(env, result, fault); return; } paths.PathBase = pathBase + match.Item1; paths.Path = path.Substring(match.Item1.Length); match.Item2.Invoke(env, result, fault); }
public Task<ResultParameters> Call(CallParameters call) { var paths = new Paths(call.Environment); var path = paths.Path; var pathBase = paths.PathBase; var match = _map.FirstOrDefault(m => path.StartsWith(m.Item1)); if (match == null) { // fall-through to default return _app(call); } // Map moves the matched portion of Path into PathBase paths.PathBase = pathBase + match.Item1; paths.Path = path.Substring(match.Item1.Length); return match.Item2.Invoke(call).Then(result => { // Path and PathBase are restored as the call returnss paths.Path = path; paths.PathBase = pathBase; return result; }); }
public static async Task CheckAndSwapInstalledExternalPlugins() { try { if (ConfigManager.IsVersionChanged) { string minerPluginsPath = Paths.MinerPluginsPath(); var zipPackages = Directory.GetFiles(Paths.RootPath("plugins_packages"), "*.zip", SearchOption.TopDirectoryOnly); var installedExternalPackages = Directory.GetDirectories(minerPluginsPath); foreach (var installedPath in installedExternalPackages) { try { var uuid = installedPath.Replace(minerPluginsPath, "").Trim('\\'); if (!System.Guid.TryParse(uuid, out var _)) { continue; } var zipPackage = zipPackages.FirstOrDefault(package => package.Contains(uuid)); if (zipPackage == null) { continue; } // uzip to temp dir var tmpPluginDir = installedPath + "_tmp"; Directory.CreateDirectory(tmpPluginDir); await ArchiveHelpers.ExtractFileAsync(zipPackage, tmpPluginDir, null, CancellationToken.None); // now copy move over files var tmpPackageFiles = Directory.GetFiles(tmpPluginDir, "*", SearchOption.AllDirectories); var installedPackagePaths = Directory.GetFiles(installedPath, "*", SearchOption.AllDirectories); foreach (var path in installedPackagePaths) { // skip if not file and skip all bins if (!File.Exists(path) || path.Contains("bins")) { continue; } var fileName = Path.GetFileName(path); var moveFile = tmpPackageFiles.FirstOrDefault(file => Path.GetFileName(file) == fileName); if (moveFile == null) { continue; } try { File.Copy(moveFile, path, true); } catch (Exception e) { Logger.Error("CheckAndSwapInstalledExternalPlugins", e.Message); } } Directory.Delete(tmpPluginDir, true); } catch (Exception e) { Logger.Error("CheckAndSwapInstalledExternalPlugins", e.Message); } } } } catch (Exception e) { Logger.Error("CheckAndSwapInstalledExternalPlugins", e.Message); } }
//------------------------------------------------------------------------------ public bool AddPolygons(Paths ppg, PolyType polyType) { bool result = false; for (int i = 0; i < ppg.Count; ++i) if (AddPath(ppg[i], polyType, true)) result = true; return result; }
private void App_OnStartup(object sender, StartupEventArgs e) { // Set working directory to exe var pathSet = false; var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (path != null) { Paths.SetRoot(path); Environment.CurrentDirectory = path; pathSet = true; } // Add common folder to path for launched processes const string pathKey = "PATH"; var pathVar = Environment.GetEnvironmentVariable(pathKey); pathVar += $";{Path.Combine(Environment.CurrentDirectory, "common")}"; Environment.SetEnvironmentVariable(pathKey, pathVar); Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; // Set security protocols ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3; // Initialize config ConfigManager.InitializeConfig(); // Check multiple instances if (!ConfigManager.GeneralConfig.AllowMultipleInstances) { try { var current = Process.GetCurrentProcess(); if (Process.GetProcessesByName(current.ProcessName).Any(p => p.Id != current.Id)) { // Shutdown to exit Shutdown(); } } catch { } } // Init logger Logger.ConfigureWithFile(ConfigManager.GeneralConfig.LogToFile, Level.Info, ConfigManager.GeneralConfig.LogMaxFileSize); if (ConfigManager.GeneralConfig.DebugConsole) { PInvokeHelpers.AllocConsole(); Logger.ConfigureConsoleLogging(Level.Info); } if (!pathSet) { Logger.Warn(Tag, "Path not set to executable"); } // Set to explicit shutdown or else these intro windows will cause shutdown ShutdownMode = ShutdownMode.OnExplicitShutdown; // Init ExchangeRateApi and TimeUnit ExchangeRateApi.ActiveDisplayCurrency = ConfigManager.GeneralConfig.DisplayCurrency; TimeFactor.UnitType = ConfigManager.GeneralConfig.TimeUnit; Logger.Info(Tag, $"Starting up {ApplicationStateManager.Title}"); if (ConfigManager.GeneralConfig.agreedWithTOS != ApplicationStateManager.CurrentTosVer) { Logger.Info(Tag, $"TOS differs! agreed: {ConfigManager.GeneralConfig.agreedWithTOS} != Current {ApplicationStateManager.CurrentTosVer}"); var eula = new EulaWindow { WindowStartupLocation = WindowStartupLocation.CenterScreen }; var accepted = eula.ShowDialog(); if (accepted.HasValue && eula.AcceptedTos) { ConfigManager.GeneralConfig.agreedWithTOS = ApplicationStateManager.CurrentTosVer; } else { Logger.Error(Tag, "TOS differs AFTER TOS confirmation window"); Shutdown(); return; } } // Chose lang if (string.IsNullOrEmpty(ConfigManager.GeneralConfig.Language)) { var langToSet = "en"; if (Translations.GetAvailableLanguagesNames().Count > 1) { var lang = new ChooseLanguageWindow { LangNames = Translations.GetAvailableLanguagesNames(), WindowStartupLocation = WindowStartupLocation.CenterScreen }; lang.ShowDialog(); langToSet = Translations.GetLanguageCodeFromIndex(lang.SelectedLangIndex); } ConfigManager.GeneralConfig.Language = langToSet; ConfigManager.GeneralConfigFileCommit(); } Translations.SelectedLanguage = ConfigManager.GeneralConfig.Language; // Check sys requirements var canRun = ApplicationStateManager.SystemRequirementsEnsured(); if (!canRun) { Shutdown(); } // Check 3rd party miners if (ConfigManager.GeneralConfig.Use3rdPartyMiners == Use3rdPartyMiners.NOT_SET) { var thirdPty = new _3rdPartyTosWindow { WindowStartupLocation = WindowStartupLocation.CenterScreen }; var result = thirdPty.ShowDialog(); // Note result is a Nullable<bool>, hence the verbose if-else if (result == true) { ConfigManager.GeneralConfig.Use3rdPartyMiners = Use3rdPartyMiners.YES; } else if (result == false) { ConfigManager.GeneralConfig.Use3rdPartyMiners = Use3rdPartyMiners.NO; } ConfigManager.GeneralConfigFileCommit(); } var main = new MainWindow(); main.Show(); // Set shutdown mode back to default ShutdownMode = ShutdownMode.OnLastWindowClose; }
public void MergeByTreeNodesAsync( IEnumerable <TreeNode> fileNodesToMerge, string mergedModName) { _bgWorker.DoWork += (sender, e) => { _checkedFileNodes = fileNodesToMerge.ToArray(); _mergedModName = mergedModName; var checkedModNodesForFile = _checkedFileNodes.Select( fileNode => fileNode.GetTreeNodes().Where( modNode => modNode.Checked ).ToArray() ).ToArray(); ProgressInfo.TotalMergeCount = checkedModNodesForFile.Sum(modNodes => modNodes.Length - 1); ProgressInfo.TotalFileCount = _checkedFileNodes.Length; for (int i = 0; i < _checkedFileNodes.Length; ++i) { var fileNode = _checkedFileNodes[i]; ProgressInfo.CurrentFileName = Path.GetFileName(fileNode.Text); ProgressInfo.CurrentFileNum = i + 1; var checkedModNodes = checkedModNodesForFile[i]; ProgressInfo.CurrentAction = "Starting merge"; if (checkedModNodes.Any(node => (new LoadOrderComparer()).Compare(node.Text, _mergedModName) < 0) && !ConfirmRemainingConflict(_mergedModName)) { continue; } var isNew = false; var merge = _inventory.Merges.FirstOrDefault(m => m.RelativePath.EqualsIgnoreCase(fileNode.Text)); if (merge == null) { isNew = true; merge = new Merge { RelativePath = fileNode.Text, MergedModName = _mergedModName }; } if ((ModFileCategory)fileNode.Parent.Tag == Categories.BundleText) { merge.BundleName = Path.GetFileName(Paths.RetrieveMergedBundlePath()); MergeBundleFileNode(fileNode, checkedModNodes, merge, isNew); } else { MergeFlatFileNode(fileNode, checkedModNodes, merge, isNew); } } if (_bundleChanged) { var newBundlePath = PackNewBundle(Paths.RetrieveMergedBundlePath()); if (newBundlePath != null) { ProgressInfo.CurrentAction = "Adding bundle merge to inventory"; foreach (var bundleMerge in _pendingBundleMerges) { _inventory.Merges.Add(bundleMerge); } if (Program.Settings.Get <bool>("PlayCompletionSounds")) { System.Media.SystemSounds.Asterisk.Play(); } if (Program.Settings.Get <bool>("ReportAfterPack")) { using (var reportForm = new PackReportForm(newBundlePath)) { ProgressInfo.CurrentAction = "Showing pack report"; Program.MainForm.ShowModal(reportForm); } } } } CleanUpTempFiles(); CleanUpEmptyDirectories(); }; _bgWorker.RunWorkerAsync(); }
//////////////////////////////////////////////// static void Main(string[] args) { ////quick test with random polygons ... //Paths ss = new Paths(1), cc = new Paths(1), sss = new Paths(); //Random r = new Random((int)DateTime.Now.Ticks); //int scale = 1000000000; //tests 128bit math //ss.Add(MakeRandomPolygon(r, 400, 350, 9, scale)); //cc.Add(MakeRandomPolygon(r, 400, 350, 9, scale)); //Clipper cpr = new Clipper(); //cpr.AddPaths(ss, PolyType.ptSubject, true); //cpr.AddPaths(cc, PolyType.ptClip, true); //cpr.Execute(ClipType.ctUnion, sss, PolyFillType.pftNonZero, PolyFillType.pftNonZero); //sss = Clipper.OffsetPolygons(sss, -5.0 * scale, JoinType.jtMiter, 4); //SVGBuilder svg1 = new SVGBuilder(); //svg1.style.brushClr = Color.FromArgb(0x20, 0, 0, 0x9c); //svg1.style.penClr = Color.FromArgb(0xd3, 0xd3, 0xda); //svg1.AddPaths(ss); //svg1.style.brushClr = Color.FromArgb(0x20, 0x9c, 0, 0); //svg1.style.penClr = Color.FromArgb(0xff, 0xa0, 0x7a); //svg1.AddPaths(cc); //svg1.style.brushClr = Color.FromArgb(0xAA, 0x80, 0xff, 0x9c); //svg1.style.penClr = Color.FromArgb(0, 0x33, 0); //svg1.AddPaths(sss); //svg1.SaveToFile("solution.svg", 1.0 / scale); //return; if (args.Length < 5) { string appname = System.Environment.GetCommandLineArgs()[0]; appname = System.IO.Path.GetFileName(appname); Console.WriteLine(""); Console.WriteLine("Usage:"); Console.WriteLine(" {0} CLIPTYPE s_file c_file INPUT_DEC_PLACES SVG_SCALE [S_FILL, C_FILL]", appname); Console.WriteLine(" where ..."); Console.WriteLine(" CLIPTYPE = INTERSECTION|UNION|DIFFERENCE|XOR"); Console.WriteLine(" FILLMODE = NONZERO|EVENODD"); Console.WriteLine(" INPUT_DEC_PLACES = signific. decimal places for subject & clip coords."); Console.WriteLine(" SVG_SCALE = scale of SVG image as power of 10. (Fractions are accepted.)"); Console.WriteLine(" both S_FILL and C_FILL are optional. The default is EVENODD."); Console.WriteLine("Example:"); Console.WriteLine(" Intersect polygons, rnd to 4 dec places, SVG is 1/100 normal size ..."); Console.WriteLine(" {0} INTERSECTION subj.txt clip.txt 0 0 NONZERO NONZERO", appname); return; } ClipType ct; switch (args[0].ToUpper()) { case "INTERSECTION": ct = ClipType.ctIntersection; break; case "UNION": ct = ClipType.ctUnion; break; case "DIFFERENCE": ct = ClipType.ctDifference; break; case "XOR": ct = ClipType.ctXor; break; default: Console.WriteLine("Error: invalid operation - {0}", args[0]); return; } string subjFilename = args[1]; string clipFilename = args[2]; if (!File.Exists(subjFilename)) { Console.WriteLine("Error: file - {0} - does not exist.", subjFilename); return; } if (!File.Exists(clipFilename)) { Console.WriteLine("Error: file - {0} - does not exist.", clipFilename); return; } int decimal_places = 0; if (!Int32.TryParse(args[3], out decimal_places)) { Console.WriteLine("Error: invalid number of decimal places - {0}", args[3]); return; } if (decimal_places > 8) { decimal_places = 8; } else if (decimal_places < 0) { decimal_places = 0; } double svg_scale = 0; if (!double.TryParse(args[4], out svg_scale)) { Console.WriteLine("Error: invalid value for SVG_SCALE - {0}", args[4]); return; } if (svg_scale < -18) { svg_scale = -18; } else if (svg_scale > 18) { svg_scale = 18; } svg_scale = Math.Pow(10, svg_scale - decimal_places);//nb: also compensate for decimal places PolyFillType pftSubj = PolyFillType.pftEvenOdd; PolyFillType pftClip = PolyFillType.pftEvenOdd; if (args.Length > 6) { switch (args[5].ToUpper()) { case "EVENODD": pftSubj = PolyFillType.pftEvenOdd; break; case "NONZERO": pftSubj = PolyFillType.pftNonZero; break; default: Console.WriteLine("Error: invalid cliptype - {0}", args[5]); return; } switch (args[6].ToUpper()) { case "EVENODD": pftClip = PolyFillType.pftEvenOdd; break; case "NONZERO": pftClip = PolyFillType.pftNonZero; break; default: Console.WriteLine("Error: invalid cliptype - {0}", args[6]); return; } } Paths subjs = new Paths(); Paths clips = new Paths(); if (!LoadFromFile(subjFilename, subjs, decimal_places)) { Console.WriteLine("Error processing subject polygons file - {0} ", subjFilename); OutputFileFormat(); return; } if (!LoadFromFile(clipFilename, clips, decimal_places)) { Console.WriteLine("Error processing clip polygons file - {0} ", clipFilename); OutputFileFormat(); return; } Console.WriteLine("wait ..."); Clipper cp = new Clipper(); cp.AddPaths(subjs, PolyType.ptSubject, true); cp.AddPaths(clips, PolyType.ptClip, true); Paths solution = new Paths(); //Paths solution = new Paths(); if (cp.Execute(ct, solution, pftSubj, pftClip)) { SaveToFile("solution.txt", solution, decimal_places); //solution = Clipper.OffsetPolygons(solution, -4, JoinType.jtRound); SVGBuilder svg = new SVGBuilder(); svg.style.brushClr = Color.FromArgb(0x20, 0, 0, 0x9c); svg.style.penClr = Color.FromArgb(0xd3, 0xd3, 0xda); svg.AddPaths(subjs); svg.style.brushClr = Color.FromArgb(0x20, 0x9c, 0, 0); svg.style.penClr = Color.FromArgb(0xff, 0xa0, 0x7a); svg.AddPaths(clips); svg.style.brushClr = Color.FromArgb(0xAA, 0x80, 0xff, 0x9c); svg.style.penClr = Color.FromArgb(0, 0x33, 0); svg.AddPaths(solution); svg.SaveToFile("solution.svg", svg_scale); Console.WriteLine("finished!"); } else { Console.WriteLine("failed!"); } }
public void InstallGame(IPackage package) { Log.InfoFormat("Installing game {0} {1}", package.Id, package.Title); try { Log.InfoFormat("Creating path {0} {1}", package.Id, package.Title); var dirPath = Path.GetTempPath(); dirPath = Path.Combine(dirPath, "o8ginstall-" + Guid.NewGuid()); Log.InfoFormat("Extracting package {0} {1} {2}", dirPath, package.Id, package.Title); GameFeedManager.Get().ExtractPackage(dirPath, package); Log.InfoFormat("Making def path {0} {1}", package.Id, package.Title); var defPath = Path.Combine(dirPath, "def"); if (!Directory.Exists(defPath)) { Log.WarnFormat("Def path doesn't exist in the game package {0} {1}", package.Id, package.Title); return; } var di = new DirectoryInfo(defPath); Log.InfoFormat("Copying temp files {0} {1}", package.Id, package.Title); foreach (var f in di.GetFiles("*", SearchOption.AllDirectories)) { Log.InfoFormat("Copying temp file {0} {1} {2}", f.FullName, package.Id, package.Title); var relPath = f.FullName.Replace(di.FullName, ""); relPath = relPath.TrimStart('\\', '/'); var newPath = Path.Combine(Paths.Get().DatabasePath, package.Id); newPath = Path.Combine(newPath, relPath); var newFileInfo = new FileInfo(newPath); if (newFileInfo.Directory != null) { Log.InfoFormat("Creating directory {0} {1} {2}", newFileInfo.Directory.FullName, package.Id, package.Title); Directory.CreateDirectory(newFileInfo.Directory.FullName); } Log.InfoFormat("Copying file {0} {1} {2} {3}", f.FullName, newPath, package.Id, package.Title); f.MegaCopyTo(newPath); Log.InfoFormat("File copied {0} {1} {2} {3}", f.FullName, newPath, package.Id, package.Title); } //Sets//setid//Cards//Proxies var setsDir = Path.Combine(Paths.Get().DatabasePath, package.Id, "Sets"); var imageSetsDir = Path.Combine(Paths.Get().ImageDatabasePath, package.Id, "Sets"); if (!Directory.Exists(imageSetsDir)) { Directory.CreateDirectory(imageSetsDir); } Log.InfoFormat("Installing decks {0} {1}", package.Id, package.Title); var game = GameManager.Get().GetById(new Guid(package.Id)); if (game == null) { throw new UserMessageException("Game {0} could not be installed. Please restart your computer and try again", package.Title); } if (Directory.Exists(Path.Combine(game.InstallPath, "Decks"))) { foreach ( var f in new DirectoryInfo(Path.Combine(game.InstallPath, "Decks")).GetFiles( "*.o8d", SearchOption.AllDirectories)) { Log.InfoFormat("Found deck file {0} {1} {2}", f.FullName, package.Id, package.Title); var relPath = f.FullName.Replace(new DirectoryInfo(Path.Combine(game.InstallPath, "Decks")).FullName, "").TrimStart('\\'); var newPath = Path.Combine(Paths.Get().DeckPath, game.Name, relPath); Log.InfoFormat("Creating directories {0} {1} {2}", f.FullName, package.Id, package.Title); if (new DirectoryInfo(newPath).Exists) { Directory.Move(newPath, Paths.Get().GraveyardPath); } Directory.CreateDirectory(new FileInfo(newPath).Directory.FullName); Log.InfoFormat("Copying deck to {0} {1} {2} {3}", f.FullName, newPath, package.Id, package.Title); f.MegaCopyTo(newPath); } } foreach (var set in game.Sets()) { Log.InfoFormat("Checking set for decks {0} {1} {2}", setsDir, package.Id, package.Title); var dp = set.DeckPath; Log.InfoFormat("Got deck uri {0}", dp); var decki = new DirectoryInfo(dp); if (!decki.Exists) { Log.InfoFormat("No decks exist for set {0} {1} {2}", setsDir, package.Id, package.Title); continue; } Log.InfoFormat("Finding deck files in set {0} {1} {2}", setsDir, package.Id, package.Title); foreach (var f in decki.GetFiles("*.o8d", SearchOption.AllDirectories)) { Log.InfoFormat("Found deck file {0} {1} {2} {3}", f.FullName, setsDir, package.Id, package.Title); var relPath = f.FullName.Replace(decki.FullName, "").TrimStart('\\'); var newPath = Path.Combine(Paths.Get().DeckPath, game.Name, relPath); Log.InfoFormat("Creating directories {0} {1} {2} {3}", f.FullName, setsDir, package.Id, package.Title); Directory.CreateDirectory(new FileInfo(newPath).Directory.FullName); Log.InfoFormat("Copying deck to {0} {1} {2} {3} {4}", f.FullName, newPath, setsDir, package.Id, package.Title); f.MegaCopyTo(newPath); } } Log.InfoFormat("Deleting proxy cards {0} {1} {2}", setsDir, package.Id, package.Title); // Clear out all proxies if they exist foreach (var setdir in new DirectoryInfo(imageSetsDir).GetDirectories()) { var dirString = Path.Combine(setdir.FullName, "Cards", "Proxies"); var pdir = new DirectoryInfo(dirString); Log.InfoFormat("Checking proxy dir {0} {1} {2}", pdir, package.Id, package.Title); if (!pdir.Exists) { Log.InfoFormat("Proxy dir doesn't exist {0} {1} {2}", pdir, package.Id, package.Title); continue; } try { Log.InfoFormat("Deleting proxy dir {0} {1} {2}", pdir, package.Id, package.Title); pdir.MoveTo(Paths.Get().GraveyardPath); Log.InfoFormat("Deleted proxy dir {0} {1} {2}", pdir, package.Id, package.Title); Directory.CreateDirectory(dirString); } catch (Exception e) { Log.WarnFormat("Could not delete proxy directory {0}", pdir.FullName); } } Log.InfoFormat("Fire game list changed {0} {1}", package.Id, package.Title); this.OnGameListChanged(); Log.InfoFormat("Game list changed fired {0} {1}", package.Id, package.Title); //copy images over to imagedatabase foreach (var setdir in new DirectoryInfo(setsDir).GetDirectories()) { var cdir = new DirectoryInfo(Path.Combine(setdir.FullName, "Cards")); if (cdir.Exists) { IEnumerable <FileInfo> fiArr = cdir.GetFiles("*.*", SearchOption.TopDirectoryOnly).Where(s => !s.FullName.EndsWith(".xml", StringComparison.CurrentCultureIgnoreCase)); foreach (FileInfo fi in fiArr) { string copyDirPath = Path.Combine(Paths.Get().ImageDatabasePath, package.Id, "Sets", setdir.Name, "Cards"); if (!Directory.Exists(copyDirPath)) { Directory.CreateDirectory(copyDirPath); } fi.CopyTo(Path.Combine(copyDirPath, fi.Name), true); fi.Delete(); } } } } finally { Log.InfoFormat("Done {0} {1}", package.Id, package.Title); } }
public static bool ResetSkin() { Utils.WriteAllText(Paths.GetPath("skin.json"), JsonConvert.SerializeObject(new Skin())); SkinEngine.LoadSkin(); return(true); }
public TemplateCache(IEngineEnvironmentSettings environmentSettings) { _environmentSettings = environmentSettings; _paths = new Paths(environmentSettings); TemplateInfo = new List <TemplateInfo>(); }
public static async Task CleanupPlugins() { Action <string> deleteDirOrFile = (string path) => { if (Directory.Exists(path)) { try { Directory.Delete(path, true); } catch { } } if (File.Exists(path)) { try { File.Delete(path); } catch { } } }; Func <string, List <string> > getObsoletePaths = (string dirPath) => { var sorted = Directory.GetDirectories(dirPath, "*.*", SearchOption.TopDirectoryOnly).OrderBy(fullPathDir => { var verStr = fullPathDir.Replace(dirPath, "").Replace("\\", "").Trim(); return(Version.TryParse(verStr, out var ver) ? ver : new Version(1, 0)); }).ToList(); sorted.Remove(sorted.LastOrDefault()); return(sorted); }; Logger.Info("MinerPluginsManager", "CleanupPlugins START"); try { Logger.Info("MinerPluginsManager", "CleanupPlugins EXECUTE"); string minerPluginsPath = Paths.MinerPluginsPath(); var zipPackages = Directory.GetFiles(Paths.RootPath("plugins_packages"), "*.zip", SearchOption.TopDirectoryOnly); var installedExternalPackages = Directory.GetDirectories(minerPluginsPath, "*", SearchOption.TopDirectoryOnly); foreach (var installedPath in installedExternalPackages) { try { var uuid = installedPath.Replace(minerPluginsPath, "").Trim('\\'); if (!System.Guid.TryParse(uuid, out var _)) { continue; } var zipPackage = zipPackages.FirstOrDefault(package => package.Contains(uuid)); if (zipPackage == null) { continue; } // cleanup old bins and dll's var removePackageDirBins = getObsoletePaths(Path.Combine(installedPath, "bins")); foreach (var removeDir in removePackageDirBins) { deleteDirOrFile(removeDir); } var removePackageDirDlls = getObsoletePaths(Path.Combine(installedPath, "dlls")); foreach (var removeDir in removePackageDirDlls) { deleteDirOrFile(removeDir); } var installedPackageRootDlls = Directory.GetFiles(installedPath, "*.dll", SearchOption.TopDirectoryOnly); if (ConfigManager.IsVersionChanged || installedPackageRootDlls.Length > 1) { foreach (var dllFile in installedPackageRootDlls) { deleteDirOrFile(dllFile); } await ArchiveHelpers.ExtractFileAsync(zipPackage, installedPath, null, CancellationToken.None); } } catch (Exception e) { Logger.Error("MinerPluginsManager", $"CleanupPlugins {installedPath} Error: {e.Message}"); } } } catch (Exception e) { Logger.Error("MinerPluginsManager", $"CleanupPlugins Error: {e.Message}"); } }
protected override void Execute(GVFSEnlistment enlistment) { string diagnosticsRoot = Path.Combine(enlistment.DotGVFSRoot, "diagnostics"); if (!Directory.Exists(diagnosticsRoot)) { Directory.CreateDirectory(diagnosticsRoot); } string archiveFolderPath = Path.Combine(diagnosticsRoot, "gvfs_" + DateTime.Now.ToString("yyyyMMdd_HHmmss")); Directory.CreateDirectory(archiveFolderPath); using (FileStream diagnosticLogFile = new FileStream(Path.Combine(archiveFolderPath, "diagnostics.log"), FileMode.CreateNew)) using (this.diagnosticLogFileWriter = new StreamWriter(diagnosticLogFile)) { this.WriteMessage("Collecting diagnostic info into temp folder " + archiveFolderPath); this.WriteMessage(string.Empty); this.WriteMessage("gvfs version " + ProcessHelper.GetCurrentProcessVersion()); GitVersion gitVersion = null; string error = null; if (!string.IsNullOrEmpty(enlistment.GitBinPath) && GitProcess.TryGetVersion(enlistment.GitBinPath, out gitVersion, out error)) { this.WriteMessage("git version " + gitVersion.ToString()); } else { this.WriteMessage("Could not determine git version. " + error); } this.WriteMessage(enlistment.GitBinPath); this.WriteMessage(string.Empty); this.WriteMessage("Enlistment root: " + enlistment.EnlistmentRoot); this.WriteMessage("Cache Server: " + CacheServerResolver.GetCacheServerFromConfig(enlistment)); string localCacheRoot; string gitObjectsRoot; this.GetLocalCachePaths(enlistment, out localCacheRoot, out gitObjectsRoot); string actualLocalCacheRoot = !string.IsNullOrWhiteSpace(localCacheRoot) ? localCacheRoot : gitObjectsRoot; this.WriteMessage("Local Cache: " + actualLocalCacheRoot); this.WriteMessage(string.Empty); this.PrintDiskSpaceInfo(actualLocalCacheRoot, this.EnlistmentRootPathParameter); this.RecordVersionInformation(); this.ShowStatusWhileRunning( () => this.RunAndRecordGVFSVerb <StatusVerb>(archiveFolderPath, "gvfs_status.txt") != ReturnCode.Success || this.RunAndRecordGVFSVerb <UnmountVerb>(archiveFolderPath, "gvfs_unmount.txt", verb => verb.SkipLock = true) == ReturnCode.Success, "Unmounting", suppressGvfsLogMessage: true); this.ShowStatusWhileRunning( () => { // .gvfs this.CopyAllFiles(enlistment.EnlistmentRoot, archiveFolderPath, GVFSConstants.DotGVFS.Root, copySubFolders: false); // driver if (this.FlushKernelDriverLogs()) { string kernelLogsFolderPath = GVFSPlatform.Instance.KernelDriver.LogsFolderPath; // This copy sometimes fails because the OS has an exclusive lock on the etl files. The error is not actionable // for the user so we don't write the error message to stdout, just to our own log file. this.CopyAllFiles(Path.GetDirectoryName(kernelLogsFolderPath), archiveFolderPath, Path.GetFileName(kernelLogsFolderPath), copySubFolders: false, hideErrorsFromStdout: true); } // .git this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Root, copySubFolders: false); this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Hooks.Root, copySubFolders: false); this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Info.Root, copySubFolders: false); this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Logs.Root, copySubFolders: true); this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Refs.Root, copySubFolders: true); this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Objects.Info.Root, copySubFolders: false); this.LogDirectoryEnumeration(enlistment.WorkingDirectoryRoot, Path.Combine(archiveFolderPath, GVFSConstants.DotGit.Objects.Root), GVFSConstants.DotGit.Objects.Pack.Root, "packs-local.txt"); this.LogLooseObjectCount(enlistment.WorkingDirectoryRoot, Path.Combine(archiveFolderPath, GVFSConstants.DotGit.Objects.Root), GVFSConstants.DotGit.Objects.Root, "objects-local.txt"); // databases this.CopyAllFiles(enlistment.DotGVFSRoot, Path.Combine(archiveFolderPath, GVFSConstants.DotGVFS.Root), GVFSConstants.DotGVFS.Databases.Name, copySubFolders: false); // local cache this.CopyLocalCacheData(archiveFolderPath, localCacheRoot, gitObjectsRoot); // corrupt objects this.CopyAllFiles(enlistment.DotGVFSRoot, Path.Combine(archiveFolderPath, GVFSConstants.DotGVFS.Root), GVFSConstants.DotGVFS.CorruptObjectsName, copySubFolders: false); if (GVFSPlatform.Instance.UnderConstruction.SupportsGVFSService) { // service this.CopyAllFiles( Paths.GetServiceDataRoot(string.Empty), archiveFolderPath, this.ServiceName, copySubFolders: true); } if (GVFSPlatform.Instance.UnderConstruction.SupportsGVFSUpgrade) { // upgrader this.CopyAllFiles( ProductUpgraderInfo.GetUpgradesDirectoryPath(), archiveFolderPath, DeprecatedUpgradeLogsDirectory, copySubFolders: true, targetFolderName: Path.Combine(ProductUpgraderInfo.UpgradeDirectoryName, DeprecatedUpgradeLogsDirectory)); this.CopyAllFiles( ProductUpgraderInfo.GetUpgradesDirectoryPath(), archiveFolderPath, ProductUpgraderInfo.LogDirectory, copySubFolders: true, targetFolderName: Path.Combine(ProductUpgraderInfo.UpgradeDirectoryName, ProductUpgraderInfo.LogDirectory)); this.LogDirectoryEnumeration( ProductUpgraderInfo.GetUpgradesDirectoryPath(), Path.Combine(archiveFolderPath, ProductUpgraderInfo.UpgradeDirectoryName), ProductUpgraderInfo.DownloadDirectory, "downloaded-assets.txt"); } if (GVFSPlatform.Instance.UnderConstruction.SupportsGVFSConfig) { this.CopyFile(Paths.GetServiceDataRoot(string.Empty), archiveFolderPath, LocalGVFSConfig.FileName); } return(true); }, "Copying logs"); this.ShowStatusWhileRunning( () => this.RunAndRecordGVFSVerb <MountVerb>(archiveFolderPath, "gvfs_mount.txt") == ReturnCode.Success, "Mounting", suppressGvfsLogMessage: true); this.CopyAllFiles(enlistment.DotGVFSRoot, Path.Combine(archiveFolderPath, GVFSConstants.DotGVFS.Root), "logs", copySubFolders: false); } string zipFilePath = archiveFolderPath + ".zip"; this.ShowStatusWhileRunning( () => { ZipFile.CreateFromDirectory(archiveFolderPath, zipFilePath); this.fileSystem.DeleteDirectory(archiveFolderPath); return(true); }, "Creating zip file", suppressGvfsLogMessage: true); this.Output.WriteLine(); this.Output.WriteLine("Diagnostics complete. All of the gathered info, as well as all of the output above, is captured in"); this.Output.WriteLine(zipFilePath); }
public Installer(IEngineEnvironmentSettings environmentSettings) { _environmentSettings = environmentSettings; _paths = new Paths(environmentSettings); }
internal static string BufferPathInvoke(string path, Func <string, StringBuffer, uint> invoker, bool utilizeExtendedSyntax = true) { if (path == null) { return(null); } string originalPath = path; bool hadExtendedPrefix = Paths.IsExtended(path); bool addedExtendedPrefix = false; if (utilizeExtendedSyntax && !hadExtendedPrefix && (path.Length > Paths.MaxPath)) { path = Paths.AddExtendedPrefix(path); addedExtendedPrefix = true; } return(StringBufferCache.CachedBufferInvoke(Paths.MaxPath, (buffer) => { uint returnValue = 0; while ((returnValue = invoker(path, buffer)) > (uint)buffer.CharCapacity) { // Need more room for the output string buffer.EnsureCharCapacity(returnValue); } if (returnValue == 0) { // Failed int error = Marshal.GetLastWin32Error(); throw GetIoExceptionForError(error, originalPath); } buffer.Length = returnValue; uint startIndex = 0; if (addedExtendedPrefix && buffer.StartsWithOrdinal(Paths.ExtendedPathPrefix)) { // Remove the prefix if (buffer.StartsWithOrdinal(Paths.ExtendedUncPrefix)) { // UNC, need to convert from \\?\UNC\ to \\. startIndex = (uint)Paths.ExtendedUncPrefix.Length - 2; buffer[startIndex] = Paths.DirectorySeparator; } else { startIndex = (uint)Paths.ExtendedPathPrefix.Length; } } // If the string did not change, return the original (to cut back on identical string pressure) if (buffer.SubStringEquals(originalPath, startIndex: startIndex)) { return originalPath; } else { return buffer.SubString(startIndex: startIndex); } })); }
public bool TrySetConfig(out string error) { string coreGVFSFlags = Convert.ToInt32( GitCoreGVFSFlags.BlockCommands | GitCoreGVFSFlags.MissingOk | GitCoreGVFSFlags.FetchSkipReachabilityAndUploadPack | GitCoreGVFSFlags.PrefetchDuringFetch) .ToString(); string expectedHooksPath = Path.Combine(this.Context.Enlistment.WorkingDirectoryRoot, ScalarConstants.DotGit.Hooks.Root); expectedHooksPath = Paths.ConvertPathToGitFormat(expectedHooksPath); if (!this.UseGvfsProtocol.HasValue) { this.UseGvfsProtocol = this.Context.Enlistment.UsesGvfsProtocol; } // These settings are required for normal Scalar functionality. // They will override any existing local configuration values. // // IMPORTANT! These must parallel the settings in ControlGitRepo:Initialize // Dictionary <string, string> requiredSettings = new Dictionary <string, string> { { "am.keepcr", "true" }, { "core.autocrlf", "false" }, { "checkout.optimizenewbranch", "true" }, { "core.fscache", "true" }, { "core.multiPackIndex", "true" }, { "core.preloadIndex", "true" }, { "core.safecrlf", "false" }, { "core.untrackedCache", ScalarPlatform.Instance.FileSystem.SupportsUntrackedCache ? "true" : "false" }, { "core.filemode", ScalarPlatform.Instance.FileSystem.SupportsFileMode ? "true" : "false" }, { "core.bare", "false" }, { "core.logallrefupdates", "true" }, { "core.hookspath", expectedHooksPath }, { GitConfigSetting.CredentialUseHttpPath, "true" }, { "credential.validate", "false" }, { "gc.auto", "0" }, { "gui.gcwarning", "false" }, { "index.threads", "true" }, { "index.version", "4" }, { "log.excludeDecoration", "refs/scalar/*" }, { "merge.stat", "false" }, { "merge.renames", "false" }, { "pack.useBitmaps", "false" }, { "pack.useSparse", "true" }, { "receive.autogc", "false" }, { "reset.quiet", "true" }, { "feature.manyFiles", "false" }, { "feature.experimental", "false" }, { "fetch.unpackLimit", "1" }, { "fetch.writeCommitGraph", "false" }, }; if (this.UseGvfsProtocol.Value) { requiredSettings.Add("core.gvfs", coreGVFSFlags); requiredSettings.Add(ScalarConstants.GitConfig.UseGvfsHelper, "true"); requiredSettings.Add("http.version", "HTTP/1.1"); } if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { requiredSettings.Add("http.sslBackend", "schannel"); } // If we do not use the GVFS protocol, then these config settings // are in fact optional. if (!this.TrySetConfig(requiredSettings, isRequired: this.UseGvfsProtocol.Value, out error)) { error = $"Failed to set some required settings: {error}"; this.Context.Tracer.RelatedError(error); return(false); } // These settings are optional, because they impact performance but not functionality of Scalar. // These settings should only be set by the clone or repair verbs, so that they do not // overwrite the values set by the user in their local config. Dictionary <string, string> optionalSettings = new Dictionary <string, string> { { "status.aheadbehind", "false" }, }; if (this.UseGvfsProtocol.Value) { // If a user's global config has "status.submoduleSummary=true", then // that could slow "git status" significantly here, even though the // GVFS protocol forbids submodules. Still, disable it optionally in // case the user really wants it in their local config. optionalSettings.Add("status.submoduleSummary", "false"); } if (!this.TrySetConfig(optionalSettings, isRequired: false, out error)) { error = $"Failed to set some optional settings: {error}"; this.Context.Tracer.RelatedError(error); return(false); } return(this.ConfigureWatchmanIntegration(out error)); }
static void LoadLegacyExtensionsFromIvyFiles() { //We can't use the cached native type scanner here since this is called to early for that to be built up. HashSet <string> ivyFiles; try { ivyFiles = new HashSet <string>(); string unityExtensionsFolder = FileUtil.CombinePaths(Directory.GetParent(EditorApplication.applicationPath).ToString(), "Data", "UnityExtensions"); string playbackEngineFolders = FileUtil.CombinePaths(Directory.GetParent(EditorApplication.applicationPath).ToString(), "PlaybackEngines"); foreach (var searchPath in new[] { FileUtil.NiceWinPath(EditorApplication.applicationContentsPath), FileUtil.NiceWinPath(unityExtensionsFolder), FileUtil.NiceWinPath(playbackEngineFolders) }) { if (!Directory.Exists(searchPath)) { continue; } ivyFiles.UnionWith(Directory.GetFiles(searchPath, "ivy.xml", SearchOption.AllDirectories)); } } catch (Exception ex) { Console.WriteLine("Error scanning for extension ivy.xml files: {0}", ex); return; } var packages = new Dictionary <string, List <IvyPackageFileData> >(); var artifactRegex = new Regex(@"<artifact(\s+(name=""(?<name>[^""]*)""|type=""(?<type>[^""]*)""|ext=""(?<ext>[^""]*)""|e:guid=""(?<guid>[^""]*)""))+\s*/>", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); foreach (var ivyFile in ivyFiles) { try { var ivyFileContent = File.ReadAllText(ivyFile); var artifacts = artifactRegex.Matches(ivyFileContent).Cast <Match>() .Select(IvyPackageFileData.CreateFromRegexMatch).ToList(); var packageDir = Path.GetDirectoryName(ivyFile); packages.Add(packageDir, artifacts); } catch (Exception ex) { Console.WriteLine("Error reading extensions from ivy.xml file at {0}: {1}", ivyFile, ex); } } try { foreach (var packageInfo in packages) { var files = packageInfo.Value; foreach (var packageInfoFile in files) { string fullPath = Paths.NormalizePath(Path.Combine(packageInfo.Key, packageInfoFile.filename)); if (!File.Exists(fullPath)) { Debug.LogWarningFormat( "Missing assembly \t{0} listed in ivy file {1}. Extension support may be incomplete.", fullPath, packageInfo.Key); } if (!packageInfoFile.IsDll) { continue; } if (!string.IsNullOrEmpty(packageInfoFile.guid)) { InternalEditorUtility.RegisterExtensionDll(fullPath.Replace('\\', '/'), packageInfoFile.guid); } else { InternalEditorUtility.RegisterPrecompiledAssembly(fullPath, fullPath); } } } } catch (Exception ex) { Console.WriteLine("Error scanning for extensions. {0}", ex); } }
private static string CombinePaths(params string[] paths) { return(Paths.Combine(paths)); }
//////////////////////////////////////////////// static bool LoadFromFile(string filename, Paths ppg, int dec_places, int xOffset = 0, int yOffset = 0) { double scaling; scaling = Math.Pow(10, dec_places); ppg.Clear(); if (!File.Exists(filename)) return false; StreamReader sr = new StreamReader(filename); if (sr == null) return false; string line; if ((line = sr.ReadLine()) == null) return false; int polyCnt, vertCnt; if (!Int32.TryParse(line, out polyCnt) || polyCnt < 0) return false; ppg.Capacity = polyCnt; for (int i = 0; i < polyCnt; i++) { if ((line = sr.ReadLine()) == null) return false; if (!Int32.TryParse(line, out vertCnt) || vertCnt < 0) return false; Path pg = new Path(vertCnt); ppg.Add(pg); if (scaling > 0.999 & scaling < 1.001) for (int j = 0; j < vertCnt; j++) { Int64 x, y; if ((line = sr.ReadLine()) == null) return false; char[] delimiters = new char[] { ',', ' ' }; string[] vals = line.Split(delimiters); if (vals.Length < 2) return false; if (!Int64.TryParse(vals[0], out x)) return false; if (!Int64.TryParse(vals[1], out y)) if (vals.Length < 2 || !Int64.TryParse(vals[2], out y)) return false; x = x + xOffset; y = y + yOffset; pg.Add(new IntPoint(x, y)); } else for (int j = 0; j < vertCnt; j++) { double x, y; if ((line = sr.ReadLine()) == null) return false; char[] delimiters = new char[] { ',', ' ' }; string[] vals = line.Split(delimiters); if (vals.Length < 2) return false; if (!double.TryParse(vals[0], out x)) return false; if (!double.TryParse(vals[1], out y)) if (vals.Length < 2 || !double.TryParse(vals[2], out y)) return false; x = x * scaling + xOffset; y = y * scaling + yOffset; pg.Add(new IntPoint((Int64)Math.Round(x), (Int64)Math.Round(y))); } } return true; }
public TemplateCreator(IEngineEnvironmentSettings environmentSettings) { _environmentSettings = environmentSettings; _paths = new Paths(environmentSettings); }
//////////////////////////////////////////////// static void Main(string[] args) { ////quick test with random polygons ... //Paths ss = new Paths(1), cc = new Paths(1), sss = new Paths(); //Random r = new Random((int)DateTime.Now.Ticks); //int scale = 1000000000; //tests 128bit math //ss.Add(MakeRandomPolygon(r, 400, 350, 9, scale)); //cc.Add(MakeRandomPolygon(r, 400, 350, 9, scale)); //Clipper cpr = new Clipper(); //cpr.AddPaths(ss, PolyType.ptSubject, true); //cpr.AddPaths(cc, PolyType.ptClip, true); //cpr.Execute(ClipType.ctUnion, sss, PolyFillType.pftNonZero, PolyFillType.pftNonZero); //sss = Clipper.OffsetPolygons(sss, -5.0 * scale, JoinType.jtMiter, 4); //SVGBuilder svg1 = new SVGBuilder(); //svg1.style.brushClr = Color.FromArgb(0x20, 0, 0, 0x9c); //svg1.style.penClr = Color.FromArgb(0xd3, 0xd3, 0xda); //svg1.AddPaths(ss); //svg1.style.brushClr = Color.FromArgb(0x20, 0x9c, 0, 0); //svg1.style.penClr = Color.FromArgb(0xff, 0xa0, 0x7a); //svg1.AddPaths(cc); //svg1.style.brushClr = Color.FromArgb(0xAA, 0x80, 0xff, 0x9c); //svg1.style.penClr = Color.FromArgb(0, 0x33, 0); //svg1.AddPaths(sss); //svg1.SaveToFile("solution.svg", 1.0 / scale); //return; if (args.Length < 5) { string appname = System.Environment.GetCommandLineArgs()[0]; appname = System.IO.Path.GetFileName(appname); Console.WriteLine(""); Console.WriteLine("Usage:"); Console.WriteLine(" {0} CLIPTYPE s_file c_file INPUT_DEC_PLACES SVG_SCALE [S_FILL, C_FILL]", appname); Console.WriteLine(" where ..."); Console.WriteLine(" CLIPTYPE = INTERSECTION|UNION|DIFFERENCE|XOR"); Console.WriteLine(" FILLMODE = NONZERO|EVENODD"); Console.WriteLine(" INPUT_DEC_PLACES = signific. decimal places for subject & clip coords."); Console.WriteLine(" SVG_SCALE = scale of SVG image as power of 10. (Fractions are accepted.)"); Console.WriteLine(" both S_FILL and C_FILL are optional. The default is EVENODD."); Console.WriteLine("Example:"); Console.WriteLine(" Intersect polygons, rnd to 4 dec places, SVG is 1/100 normal size ..."); Console.WriteLine(" {0} INTERSECTION subj.txt clip.txt 0 0 NONZERO NONZERO", appname); return; } ClipType ct; switch (args[0].ToUpper()) { case "INTERSECTION": ct = ClipType.ctIntersection; break; case "UNION": ct = ClipType.ctUnion; break; case "DIFFERENCE": ct = ClipType.ctDifference; break; case "XOR": ct = ClipType.ctXor; break; default: Console.WriteLine("Error: invalid operation - {0}", args[0]); return; } string subjFilename = args[1]; string clipFilename = args[2]; if (!File.Exists(subjFilename)) { Console.WriteLine("Error: file - {0} - does not exist.", subjFilename); return; } if (!File.Exists(clipFilename)) { Console.WriteLine("Error: file - {0} - does not exist.", clipFilename); return; } int decimal_places = 0; if (!Int32.TryParse(args[3], out decimal_places)) { Console.WriteLine("Error: invalid number of decimal places - {0}", args[3]); return; } if (decimal_places > 8) decimal_places = 8; else if (decimal_places < 0) decimal_places = 0; double svg_scale = 0; if (!double.TryParse(args[4], out svg_scale)) { Console.WriteLine("Error: invalid value for SVG_SCALE - {0}", args[4]); return; } if (svg_scale < -18) svg_scale = -18; else if (svg_scale > 18) svg_scale = 18; svg_scale = Math.Pow(10, svg_scale - decimal_places);//nb: also compensate for decimal places PolyFillType pftSubj = PolyFillType.pftEvenOdd; PolyFillType pftClip = PolyFillType.pftEvenOdd; if (args.Length > 6) { switch (args[5].ToUpper()) { case "EVENODD": pftSubj = PolyFillType.pftEvenOdd; break; case "NONZERO": pftSubj = PolyFillType.pftNonZero; break; default: Console.WriteLine("Error: invalid cliptype - {0}", args[5]); return; } switch (args[6].ToUpper()) { case "EVENODD": pftClip = PolyFillType.pftEvenOdd; break; case "NONZERO": pftClip = PolyFillType.pftNonZero; break; default: Console.WriteLine("Error: invalid cliptype - {0}", args[6]); return; } } Paths subjs = new Paths(); Paths clips = new Paths(); if (!LoadFromFile(subjFilename, subjs, decimal_places)) { Console.WriteLine("Error processing subject polygons file - {0} ", subjFilename); OutputFileFormat(); return; } if (!LoadFromFile(clipFilename, clips, decimal_places)) { Console.WriteLine("Error processing clip polygons file - {0} ", clipFilename); OutputFileFormat(); return; } Console.WriteLine("wait ..."); Clipper cp = new Clipper(); cp.AddPaths(subjs, PolyType.ptSubject, true); cp.AddPaths(clips, PolyType.ptClip, true); Paths solution = new Paths(); //Paths solution = new Paths(); if (cp.Execute(ct, solution, pftSubj, pftClip)) { SaveToFile("solution.txt", solution, decimal_places); //solution = Clipper.OffsetPolygons(solution, -4, JoinType.jtRound); SVGBuilder svg = new SVGBuilder(); svg.style.brushClr = Color.FromArgb(0x20, 0, 0, 0x9c); svg.style.penClr = Color.FromArgb(0xd3, 0xd3, 0xda); svg.AddPaths(subjs); svg.style.brushClr = Color.FromArgb(0x20, 0x9c, 0, 0); svg.style.penClr = Color.FromArgb(0xff, 0xa0, 0x7a); svg.AddPaths(clips); svg.style.brushClr = Color.FromArgb(0xAA, 0x80, 0xff, 0x9c); svg.style.penClr = Color.FromArgb(0, 0x33, 0); svg.AddPaths(solution); svg.SaveToFile("solution.svg", svg_scale); Console.WriteLine("finished!"); } else { Console.WriteLine("failed!"); } }
//Clipper public static List <Polygon> ToPolygons(this Paths v) { return(v.Select(ToPolygon).ToList()); }
void calculateRegionPath(ClipType clipType) { Clipper c = new Clipper(); var subjects = solution; //subjects.Add (solution); var clips = new Paths (); foreach (var path in regionList [regionList.Count - 1].regionPath) clips.Add (path); c.AddPolygons(subjects, PolyType.ptSubject); c.AddPolygons(clips, PolyType.ptClip); solution.Clear(); bool succeeded = c.Execute(clipType, solution, SUBJ_FILL_TYPE, CLIP_FILL_TYPE); if (succeeded) { PathsToInternalPath (solution); // Not sure what this is returning // var bounds = c.GetBounds (); // regionBounds.X = bounds.left / scale; // regionBounds.Y = bounds.top / scale; // regionBounds.Width = (bounds.right - bounds.left) / scale; // regionBounds.Height = (bounds.bottom - bounds.top) / scale; if (regionPath.IsEmpty) regionBounds = RectangleF.Empty; else regionBounds = regionPath.BoundingBox; } }
internal bool extract(ZipEntry entry, out Guid gameGuid, Guid testGuid) { try { Log.InfoFormat("Extracting {0},{1}", entry.FileName, testGuid); bool ret = false; gameGuid = testGuid; string[] split = entry.FileName.Split('/'); Log.InfoFormat("Split file name {0},{1}", entry.FileName, testGuid); if (split.Length == 5) { Log.InfoFormat("File name right count {0},{1}", entry.FileName, testGuid); O8cEntry o8cEntry = new O8cEntry() { gameGuid = split[0], setsDir = split[1], setGuid = split[2], cardsDir = split[3], cardImage = split[4] }; Log.InfoFormat("Checking if testGuid is empty {0},{1}", entry.FileName, testGuid); if (testGuid.Equals(Guid.Empty)) { Log.InfoFormat("testGuid is empty {0},{1}", entry.FileName, testGuid); testGuid = Guid.Parse(o8cEntry.gameGuid); gameGuid = Guid.Parse(o8cEntry.gameGuid); Log.InfoFormat("Setting gameguid and testguid {0},{1},{2}", entry.FileName, testGuid, gameGuid); } Log.InfoFormat("Checking if {0}=={1} {2}", testGuid, o8cEntry.gameGuid, entry.FileName); if (!testGuid.Equals(Guid.Parse(o8cEntry.gameGuid))) { Log.InfoFormat("{0}!={1} {2}", testGuid, o8cEntry.gameGuid, entry.FileName); return(ret); } Log.InfoFormat("Checking if should extract part {0},{1}", entry.FileName, testGuid); if (ShouldExtract(o8cEntry)) { Log.InfoFormat( "Should extract, so extracting {0},{1},{2}", Paths.Get().ImageDatabasePath, entry.FileName, testGuid); entry.Extract(Paths.Get().ImageDatabasePath, ExtractExistingFileAction.OverwriteSilently); Log.InfoFormat("Extracted {0},{1},{2}", Paths.Get().ImageDatabasePath, entry.FileName, testGuid); ret = true; } } Log.InfoFormat("Finishing {0},{1},{2}", ret, entry.FileName, testGuid); return(ret); } catch (IOException e) { throw new UserMessageException("Error extracting {0} to {1}\n{2}", entry.FileName, Paths.Get().DatabasePath, e.Message); } finally { Log.InfoFormat("Finished {0},{1}", entry.FileName, testGuid); } }
//: //this (type, obj, new Paths<List<IntPoint>>(path), clipType) public RegionEntry(RegionType type, object obj, Path path, RegionClipType clipType) { regionType = type; regionObject = obj; regionPath = new Paths() { path }; regionClipType = clipType; }
//////////////////////////////////////////////// static bool LoadFromFile(string filename, Paths ppg, int dec_places, int xOffset = 0, int yOffset = 0) { double scaling; scaling = Math.Pow(10, dec_places); ppg.Clear(); if (!File.Exists(filename)) { return(false); } StreamReader sr = new StreamReader(filename); if (sr == null) { return(false); } string line; if ((line = sr.ReadLine()) == null) { return(false); } int polyCnt, vertCnt; if (!Int32.TryParse(line, out polyCnt) || polyCnt < 0) { return(false); } ppg.Capacity = polyCnt; for (int i = 0; i < polyCnt; i++) { if ((line = sr.ReadLine()) == null) { return(false); } if (!Int32.TryParse(line, out vertCnt) || vertCnt < 0) { return(false); } Path pg = new Path(vertCnt); ppg.Add(pg); if (scaling > 0.999 & scaling < 1.001) { for (int j = 0; j < vertCnt; j++) { Int64 x, y; if ((line = sr.ReadLine()) == null) { return(false); } char[] delimiters = new char[] { ',', ' ' }; string[] vals = line.Split(delimiters); if (vals.Length < 2) { return(false); } if (!Int64.TryParse(vals[0], out x)) { return(false); } if (!Int64.TryParse(vals[1], out y)) { if (vals.Length < 2 || !Int64.TryParse(vals[2], out y)) { return(false); } } x = x + xOffset; y = y + yOffset; pg.Add(new IntPoint(x, y)); } } else { for (int j = 0; j < vertCnt; j++) { double x, y; if ((line = sr.ReadLine()) == null) { return(false); } char[] delimiters = new char[] { ',', ' ' }; string[] vals = line.Split(delimiters); if (vals.Length < 2) { return(false); } if (!double.TryParse(vals[0], out x)) { return(false); } if (!double.TryParse(vals[1], out y)) { if (vals.Length < 2 || !double.TryParse(vals[2], out y)) { return(false); } } x = x * scaling + xOffset; y = y * scaling + yOffset; pg.Add(new IntPoint((Int64)Math.Round(x), (Int64)Math.Round(y))); } } } return(true); }
public SchedulerTestBase(ITestOutputHelper output) : base(output) { m_paths = new Paths(Context.PathTable); m_fileFreshId = 0; }
private void OnDisable() { Options.instance.SaveToFile(Paths.GetOptionsFilePath()); }
public void GetFinalPathNameTest() { Assert.AreEqual(@"C:\Users", Paths.GetFinalPathName(@"c:\Documents and Settings")); Assert.AreEqual(@"C:\Users", Paths.GetFinalPathName(@"C:\Users")); Assert.AreEqual(@"\\server\someunc\testpath", Paths.GetFinalPathName(@"\\server\someunc\testpath")); }
//------------------------------------------------------------------------------ public static Paths ClosedPathsFromPolyTree(PolyTree polytree) { Paths result = new Paths(); result.Capacity = polytree.Total; AddPolyNodeToPaths(polytree, NodeType.ntClosed, result); return result; }
/// <summary> /// Initializes a new instance of the <see cref="Submenu"/> class and determines the path of the mdi client /// </summary> public Submenu() { this.repository = Paths.Instance; }
static void Main(string[] argv) { BUILD_TAG.ASSERT_COMPATIBLE_BUILDS(); // Set working directory to exe var pathSet = false; var path = Path.GetDirectoryName(Application.ExecutablePath); if (path != null) { Paths.SetRoot(path); Environment.CurrentDirectory = path; pathSet = true; } // Add common folder to path for launched processes var pathVar = Environment.GetEnvironmentVariable("PATH"); pathVar += ";" + Path.Combine(Environment.CurrentDirectory, "common"); Environment.SetEnvironmentVariable("PATH", pathVar); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; // set security protocols ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3; // #1 first initialize config ConfigManager.InitializeConfig(); // PRODUCTION NEW #if (TESTNET || TESTNETDEV || PRODUCTION_NEW) // on new production we allow only one instance try { var current = Process.GetCurrentProcess(); foreach (var process in Process.GetProcessesByName(current.ProcessName)) { if (process.Id != current.Id) { // already running instance, return from Main MessageBox.Show(Tr("{0} can run only one instance at a time.", NHMProductInfo.Name), Tr("{0} Already Running", NHMProductInfo.Name), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } } catch { } #else // PRODUCTION OLD // #2 check if multiple instances are allowed if (ConfigManager.GeneralConfig.AllowMultipleInstances == false) { try { var current = Process.GetCurrentProcess(); foreach (var process in Process.GetProcessesByName(current.ProcessName)) { if (process.Id != current.Id) { // already running instance, return from Main return; } } } catch { } } #endif // TODO set logging level Logger.ConfigureWithFile(ConfigManager.GeneralConfig.LogToFile, Level.Info, ConfigManager.GeneralConfig.LogMaxFileSize); if (ConfigManager.GeneralConfig.DebugConsole) { PInvokeHelpers.AllocConsole(); } // init active display currency after config load ExchangeRateApi.ActiveDisplayCurrency = ConfigManager.GeneralConfig.DisplayCurrency; Logger.Info("NICEHASH", $"Starting up {ApplicationStateManager.Title}"); if (!pathSet) { Logger.Info("NICEHASH", "Path not set to executable"); } // check TOS if (ConfigManager.GeneralConfig.agreedWithTOS != ApplicationStateManager.CurrentTosVer) { Logger.Info("NICEHASH", $"TOS differs! agreed: {ConfigManager.GeneralConfig.agreedWithTOS} != Current {ApplicationStateManager.CurrentTosVer}. Showing TOS Form."); Application.Run(new FormEula()); // check TOS after if (ConfigManager.GeneralConfig.agreedWithTOS != ApplicationStateManager.CurrentTosVer) { Logger.Info("NICEHASH", "TOS differs AFTER TOS confirmation FORM"); // TOS not confirmed return from Main return; } } // if config created show language select if (string.IsNullOrEmpty(ConfigManager.GeneralConfig.Language)) { if (Translations.GetAvailableLanguagesNames().Count > 1) { Application.Run(new Form_ChooseLanguage()); } else { ConfigManager.GeneralConfig.Language = "en"; ConfigManager.GeneralConfigFileCommit(); } } Translations.SetLanguage(ConfigManager.GeneralConfig.Language); // if system requirements are not ensured it will fail the program var canRun = ApplicationStateManager.SystemRequirementsEnsured(); if (!canRun) { return; } // 3rdparty miners TOS check if setting set if (ConfigManager.GeneralConfig.Use3rdPartyMiners == Use3rdPartyMiners.NOT_SET) { Application.Run(new Form_3rdParty_TOS()); ConfigManager.GeneralConfigFileCommit(); } // PRODUCTION #if !(TESTNET || TESTNETDEV || PRODUCTION_NEW) // if no BTC address show login/register form if (ConfigManager.GeneralConfig.BitcoinAddress.Trim() == "") { Application.Run(new EnterBTCDialogSwitch()); } #endif Application.Run(new Form_Main()); }
public void GetSafeFilenameTest() { Assert.AreEqual("test aaa", Paths.GetSafePathName("test >> aaa ")); }
static void WidenPath(GraphicsPath path, Pen pen, out List<PointF> widePoints, out List<byte> wideTypes) { widePoints = new List<PointF> (); wideTypes = new List<byte> (); var pathData = path.PathData; var iterator = new GraphicsPathIterator(path); var subPaths = iterator.SubpathCount; int startIndex = 0; int endIndex = 0; bool isClosed = false; var flattenedSubpath = new Paths(); var offsetPaths = new Paths(); var width = (pen.Width / 2) * scale; var miterLimit = pen.MiterLimit * scale; var joinType = JoinType.jtMiter; switch (pen.LineJoin) { case LineJoin.Round: joinType = JoinType.jtRound; break; case LineJoin.Bevel: joinType = JoinType.jtSquare; break; } for (int sp = 0; sp < subPaths; sp++) { var numOfPoints = iterator.NextSubpath(out startIndex, out endIndex, out isClosed); //Console.WriteLine("subPath {0} - from {1} to {2} closed {3}", sp+1, startIndex, endIndex, isClosed); var subPoints = pathData.Points.Skip(startIndex).Take(numOfPoints).ToArray(); //for (int pp = startIndex; pp <= endIndex; pp++) //{ // Console.WriteLine(" {0} - {1}", pathData.Points[pp], (PathPointType)pathData.Types[pp]); //} // Load our Figure Subpath flattenedSubpath.Clear(); flattenedSubpath.Add(Region.PointFArrayToIntArray(subPoints, scale)); // Calculate the outter offset region var outerOffsets = Clipper.OffsetPaths(flattenedSubpath, width, joinType, EndType.etClosed, miterLimit); // Calculate the inner offset region var innerOffsets = Clipper.OffsetPaths(flattenedSubpath, -width, joinType, EndType.etClosed, miterLimit); // Add the offsets to our paths offsetPaths.AddRange(outerOffsets); // revers our innerOffsets so that they create a hole when filling Clipper.ReversePaths (innerOffsets); offsetPaths.AddRange(innerOffsets); } foreach (var offPath in offsetPaths) { if (offPath.Count < 1) continue; var pointArray = Region.PathToPointFArray(offPath, scale); var type = (byte)PathPointType.Start; widePoints.Add (pointArray [0]); wideTypes.Add (type); type = (byte)PathPointType.Line; for (int i = 1; i < offPath.Count; i++) { widePoints.Add (pointArray [i]); wideTypes.Add (type); } if (widePoints.Count > 0) wideTypes [wideTypes.Count-1] = (byte) (wideTypes [wideTypes.Count-1] | (byte) PathPointType.CloseSubpath); } }
public void FixSeparatorsTest() { Assert.AreEqual(@"D:\GOG Games\Albion\DOSBOX\dosbox.exe", Paths.FixSeparators(@"D:/GOG Games//Albion\\\DOSBOX\\dosbox.exe")); }
//////////////////////////////////////////////// static void SaveToFile(string filename, Paths ppg, int dec_places) { double scaling = Math.Pow(10, dec_places); StreamWriter writer = new StreamWriter(filename); if (writer == null) return; writer.Write("{0}\r\n", ppg.Count); foreach (Path pg in ppg) { writer.Write("{0}\r\n", pg.Count); foreach (IntPoint ip in pg) writer.Write("{0:0.####}, {1:0.####}\r\n", (double)ip.X / scaling, (double)ip.Y / scaling); } writer.Close(); }
async Task BuildIndexType(IList <Post> data) { { await BuildDataIdList(data.Where( x => x.Type is PostType.Article).ToList().Select(x => x.Id).IgnoreNull().ToArray(), Paths.GetArticleRoot(RootPath)).ConfigureAwait(false); } { await BuildDataIdList(data.Where( x => x.Type is PostType.Slides).ToList().Select(x => x.Id).IgnoreNull().ToArray(), Paths.GetSlidesRoot(RootPath)).ConfigureAwait(false); } { await BuildDataIdList(data.Where( x => x.Type is PostType.Note).ToList().Select(x => x.Id).IgnoreNull().ToArray(), Paths.GetNoteRoot(RootPath)).ConfigureAwait(false); } }
public IEnumerator <PathEntry> GetEnumerator() => Paths.GetEnumerator();
public PathEntry this[string system, string type] => Paths.FirstOrDefault(p => p.IsSystem(system) && p.Type == type) ?? TryGetDebugPath(system, type);
void PathsToInternalPath(Paths paths) { regionPath = new CGPath (); foreach (var poly in solution) { regionPath.MoveToPoint(IntPointToPointF(poly[0])); for (var p =1; p < poly.Count; p++) { regionPath.AddLineToPoint (IntPointToPointF (poly [p])); } } }
public IRequest Marshall(CreateInvalidationRequest createInvalidationRequest) { IRequest request = new DefaultRequest(createInvalidationRequest, "AmazonCloudFront"); request.HttpMethod = "POST"; string uriResourcePath = "2013-11-22/distribution/{DistributionId}/invalidation"; uriResourcePath = uriResourcePath.Replace("{DistributionId}", createInvalidationRequest.IsSetDistributionId() ? createInvalidationRequest.DistributionId.ToString() : ""); if (uriResourcePath.Contains("?")) { int queryIndex = uriResourcePath.IndexOf("?", StringComparison.OrdinalIgnoreCase); string queryString = uriResourcePath.Substring(queryIndex + 1); uriResourcePath = uriResourcePath.Substring(0, queryIndex); foreach (string s in queryString.Split('&', ';')) { string[] nameValuePair = s.Split('='); if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0) { request.Parameters.Add(nameValuePair[0], nameValuePair[1]); } else { request.Parameters.Add(nameValuePair[0], null); } } } request.ResourcePath = uriResourcePath; StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings() { Encoding = System.Text.Encoding.UTF8, OmitXmlDeclaration = true })) { if (createInvalidationRequest != null) { InvalidationBatch invalidationBatchInvalidationBatch = createInvalidationRequest.InvalidationBatch; if (invalidationBatchInvalidationBatch != null) { xmlWriter.WriteStartElement("InvalidationBatch", "http://cloudfront.amazonaws.com/doc/2013-11-22/"); if (invalidationBatchInvalidationBatch != null) { Paths pathsPaths = invalidationBatchInvalidationBatch.Paths; if (pathsPaths != null) { xmlWriter.WriteStartElement("Paths", "http://cloudfront.amazonaws.com/doc/2013-11-22/"); if (pathsPaths.IsSetQuantity()) { xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2013-11-22/", pathsPaths.Quantity.ToString(CultureInfo.InvariantCulture)); } if (pathsPaths != null) { List <string> pathsPathsitemsList = pathsPaths.Items; if (pathsPathsitemsList != null && pathsPathsitemsList.Count > 0) { int pathsPathsitemsListIndex = 1; xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2013-11-22/"); foreach (string pathsPathsitemsListValue in pathsPathsitemsList) { xmlWriter.WriteStartElement("Path", "http://cloudfront.amazonaws.com/doc/2013-11-22/"); xmlWriter.WriteValue(pathsPathsitemsListValue); xmlWriter.WriteEndElement(); pathsPathsitemsListIndex++; } xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } } if (invalidationBatchInvalidationBatch.IsSetCallerReference()) { xmlWriter.WriteElementString("CallerReference", "http://cloudfront.amazonaws.com/doc/2013-11-22/", invalidationBatchInvalidationBatch.CallerReference.ToString(CultureInfo.InvariantCulture)); } xmlWriter.WriteEndElement(); } } } try { string content = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(content); request.Headers["Content-Type"] = "application/xml"; } catch (EncoderFallbackException e) { throw new AmazonServiceException("Unable to marshall request to XML", e); } return(request); }
public RegionEntry(RegionType type, object obj, Paths path, RegionClipType clipType) { regionType = type; regionObject = obj; regionPath = path; regionClipType = clipType; }
public static async Task MainLoop(string interpFramesPath) { try { UpdateChunkAndBufferSizes(); interpFramesFolder = interpFramesPath; videoChunksFolder = Path.Combine(interpFramesPath.GetParentDir(), Paths.chunksDir); if (Interpolate.currentlyUsingAutoEnc) { Directory.CreateDirectory(videoChunksFolder); } encodedFrameLines.Clear(); unencodedFrameLines.Clear(); Logger.Log($"[AutoEnc] Starting AutoEncode MainLoop - Chunk Size: {chunkSize} Frames - Safety Buffer: {safetyBufferFrames} Frames", true); int videoIndex = 1; string encFile = Path.Combine(interpFramesPath.GetParentDir(), Paths.GetFrameOrderFilename(Interpolate.current.interpFactor)); interpFramesLines = IOUtils.ReadLines(encFile).Select(x => x.Split('/').Last().Remove("'").Split('#').First()).ToArray(); // Array with frame filenames while (!Interpolate.canceled && GetInterpFramesAmount() < 2) { await Task.Delay(2000); } int lastEncodedFrameNum = 0; while (HasWorkToDo()) // Loop while proc is running and not all frames have been encoded { if (Interpolate.canceled) { return; } Logger.Log($"AutoEnc Loop iteration runs. Paused: {paused}", true); if (paused) { await Task.Delay(200); continue; } unencodedFrameLines.Clear(); for (int vfrLine = lastEncodedFrameNum; vfrLine < interpFramesLines.Length; vfrLine++) { unencodedFrameLines.Add(vfrLine); } bool aiRunning = !AiProcess.lastAiProcess.HasExited; if (unencodedFrameLines.Count > 0 && (unencodedFrameLines.Count >= (chunkSize + safetyBufferFrames) || !aiRunning)) // Encode every n frames, or after process has exited { try { List <int> frameLinesToEncode = aiRunning ? unencodedFrameLines.Take(chunkSize).ToList() : unencodedFrameLines; // Take all remaining frames if process is done string lastOfChunk = Path.Combine(interpFramesPath, interpFramesLines[frameLinesToEncode.Last()]); if (!File.Exists(lastOfChunk)) { Logger.Log($"[AutoEnc] Last frame of chunk doesn't exist; skipping loop iteration ({lastOfChunk})", true); await Task.Delay(500); continue; } busy = true; string outpath = Path.Combine(videoChunksFolder, "chunks", $"{videoIndex.ToString().PadLeft(4, '0')}{FFmpegUtils.GetExt(Interpolate.current.outMode)}"); int firstLineNum = frameLinesToEncode.First(); int lastLineNum = frameLinesToEncode.Last(); Logger.Log($"[AutoEnc] Encoding Chunk #{videoIndex} to '{outpath}' using line {firstLineNum} ({Path.GetFileName(interpFramesLines[firstLineNum])}) through {lastLineNum} ({Path.GetFileName(Path.GetFileName(interpFramesLines[frameLinesToEncode.Last()]))})", true, false, "ffmpeg"); await CreateVideo.EncodeChunk(outpath, Interpolate.current.outMode, firstLineNum, frameLinesToEncode.Count); if (Interpolate.canceled) { return; } if (aiRunning && Config.GetInt("autoEncMode") == 2) { Task.Run(() => DeleteOldFramesAsync(interpFramesPath, frameLinesToEncode)); } if (Interpolate.canceled) { return; } encodedFrameLines.AddRange(frameLinesToEncode); Logger.Log("Done Encoding Chunk #" + videoIndex, true, false, "ffmpeg"); lastEncodedFrameNum = (frameLinesToEncode.Last() + 1); videoIndex++; busy = false; } catch (Exception e) { Logger.Log($"AutoEnc Chunk Encoding Error: {e.Message}. Stack Trace:\n{e.StackTrace}"); Interpolate.Cancel("Auto-Encode encountered an error."); } } await Task.Delay(50); } if (Interpolate.canceled) { return; } await CreateVideo.ChunksToVideos(Interpolate.current.tempFolder, videoChunksFolder, Interpolate.current.outPath); } catch (Exception e) { Logger.Log($"AutoEnc Error: {e.Message}. Stack Trace:\n{e.StackTrace}"); Interpolate.Cancel("Auto-Encode encountered an error."); } }