public static void SpaceShip() { for (int i = 1; i <= 100; i++) { if (i % 2 == 0) { Console.WriteLine(@" | \ : / `. __/ \__.' _ \ / _ _ /_ _\ .' \ / `. / : \ | ", Color.Yellow); } else { Console.WriteLine(@" : \ | / \ : / `. __/ \__ .' _ _ \ / _ _ /_ _\ .' \ / `. / : \ / | \ : ", Color.Goldenrod); } Thread.Sleep(5); Console.Clear(); System.Console.WriteLine($"LOAING {i} %"); } }
public static void Print() { Console.Clear(); Console.WriteLine(@" ======================================================== .______ .______ _______ ___ _______ | _ \ | _ \ | ____| / \ | \ | |_) | | |_) | | |__ / ^ \ | .--. | | _ < | / | __| / /_\ \ | | | | | |_) | | |\ \----.| |____ / _____ \ | '--' | |______/ | _| `._____||_______|/__/ \__\ |_______/ ========================================================= ", Color.Red); StyleSheet styleSheet = new StyleSheet(Color.Green); styleSheet.AddStyle("1[1-9]*", Color.Red); styleSheet.AddStyle("2[1-9]*", Color.Cyan); styleSheet.AddStyle("3[1-9]*", Color.Yellow); styleSheet.AddStyle("4[1-9]*", Color.Yellow); styleSheet.AddStyle("M[A-Z]*", Color.White); //Menu string string Menu = (@" | [1] + Wheat bread loaf | | [2] + White bread loaf | | [3] + 9 Grain bread loaf | | [4] + Rye bread loaf | | [M] Main Menu | "); //print Menu Console.WriteStyled(Menu, styleSheet); Console.WriteLine(); Console.Write(" Enter : ", Color.Green); }
static void Main(string[] args) { try { /* #Instances * Create an instance to the class. * Create the instances that are in the constructor */ _ownerProfile = new OwnerProfile(); _gameInformation = new GameInformation(); _gameInformationClassicMode = new GameInformationClassicMode(); _SecondChanceQuestion = new GameInformationClassicMode.SecondChanceQuestion(); _variables = new Variables(); _handlerFiddlerCore = new HandlerFiddlerCore(); _consoleOutput = new ConsoleOutput(); /* #EndInstances*/ handler = new ConsoleEventDelegate(ConsoleEventCallback); //Instance for the method ConsoleEventCallback SetConsoleCtrlHandler(handler, true); // Call to the API SetConsoleCtrlHandler _consoleOutput.ConsoleWelcome(); _handlerFiddlerCore.Start(); // Start the proxy, install the certificate and the event for sessions capture _consoleOutput.WriteLine("Inicie ahora sesión en FaceBook si aún no lo hizo y luego entre en alguna partida que sea modo Clásico. \nEsperando...", "Cheat"); _variables.ImStarted = true; _consoleOutput.WriteLine(""); while (true) { System.Threading.Thread.Sleep(1800000); } // Prevent the application from closing } catch (Exception e) { _consoleOutput.WriteError(e); _handlerFiddlerCore.Stop(); Certificate.Uninstall(); _consoleOutput.WriteLine("\n\nThe application will close after pressing a key"); Console.ReadKey(); } }
public static void Main(string[] args) { Console.Title = $"Deoxys - Version {CurrentVersion} | https://github.com/StackUnderflowRE/Deoxys"; ILogger logger = new ConsoleLogger(); if (args.Length == 0) { logger.Error("Use <Deoxys.exe> --help"); Console.ReadLine(); return; } var options = Parser.Default.ParseArguments <ParseOptions>(args).WithNotParsed(q => { logger.Info($"Usage : <Deoxys.exe> <Input File> <Settings>"); Console.ReadLine(); Environment.Exit(0); }); var deoxysOptions = new DeoxysOptions(args[0], options.Value); var ctx = new DeoxysContext(deoxysOptions, logger); PrintInfo(ctx); var devirtualizer = new Devirtualizer(ctx); bool result = devirtualizer.Devirtualize(); if (result) { devirtualizer.Save(); logger.Success("Finished Devirtualization With No Errors!"); } else { logger.Error("Could not finish Devirtualization."); } Console.ReadLine(); }
public async Task soloRob() { int roubos = 0; while (!Console.KeyAvailable) { if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape) { break; } Console.Clear(); showTheCrimsBot(); showInfo(); Console.WriteLine("Roubos: " + roubos, Color.DarkGreen); await this.service.Rob(); roubos++; } Console.Clear(); showTheCrimsBot(); Console.WriteLine("Operação de roubos cancelada", Color.GreenYellow); await menu(); }
/// <summary> /// function for reading user direction key input /// </summary> /// <param name="direction"></param> /// <param name="right"></param> /// <param name="left"></param> /// <param name="down"></param> /// <param name="up"></param> public void CheckUserInput(ref int direction, byte right, byte left, byte down, byte up) { //User key pressed statement: depends on which direction the user want to go to get food or avoid obstacle if (Console.KeyAvailable) { ConsoleKeyInfo userInput = Console.ReadKey(true); // Disable the display of pressed key if (userInput.Key == ConsoleKey.LeftArrow) { if (direction != right) { direction = left; } } if (userInput.Key == ConsoleKey.RightArrow) { if (direction != left) { direction = right; } } if (userInput.Key == ConsoleKey.UpArrow) { if (direction != down) { direction = up; } } if (userInput.Key == ConsoleKey.DownArrow) { if (direction != up) { direction = down; } } } }
public void DisplayGraph() { try { Console.Clear(); DisplayMainScreen(); var position = MainView.PathfindingStatisticsPosition; if (position != null) { Console.SetCursorPosition(position.X, position.Y + 1); } Console.CursorVisible = true; } catch (ArgumentOutOfRangeException ex) { Console.Clear(); log.Warn(ex); } catch (Exception ex) { Console.Clear(); log.Error(ex); } }
private QuitReason EventLoop() { QuitReason quitReason; do { Console.Clear(); // Print the current location Console.WriteLine($"Planet: {hero.planet.name} Age: {hero.age:f2} years Credits: {hero.money:f1}\n"); // Print a description of that location Console.WriteLine(hero.planet.description); // Provide options to the user re. things they can do PrintOptionList(); var key = UI.ElicitInput(); quitReason = ShouldQuit(HandleInput(key)); } while (quitReason == QuitReason.DontQuit); return(quitReason); }
private int GetForumEntry(string hint) { Console.Write(hint); string entry = Console.ReadLine().Trim().ToLower(); if (entry == "q") { Environment.Exit(0); } else if (entry == "b") { return(-1); } else if (int.TryParse(entry, out _)) { return(int.Parse(entry) - 1); } else { Console.WriteLine("Problem with stuff..."); GetForumEntry(hint); } return(-1); }
//////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Try request asynchronous. </summary> /// /// <param name="action"> The action. This cannot be null. </param> /// <param name="maxFailures"> The maximum failures. </param> /// <param name="startTimeoutMS"> (Optional) The start timeout milliseconds. </param> /// <param name="resetTimeout"> (Optional) The reset timeout. </param> /// <param name="OnError"> (Optional) The on error. This may be null. </param> /// /// <returns> The asynchronous result. </returns> //////////////////////////////////////////////////////////////////////////////////////////////////// public async Task TryRequestAsync([NotNull] Func <Task> action, int maxFailures, int startTimeoutMS = 100, int resetTimeout = 10000, [CanBeNull] Action <Exception> OnError = null) { Requires.True(maxFailures >= 1, string.Intern("maxFailures must be >= 1")); Requires.True(startTimeoutMS >= 1, string.Intern("startTimeoutMS must be >= 1")); Requires.True(resetTimeout >= 1, string.Intern("resetTimeout must be >= 1")); Requires.True(action != null, string.Intern("action is null")); try { // Initialize the circuit breaker var circuitBreaker = new CircuitBreaker( TaskScheduler.Default, maxFailures: maxFailures, invocationTimeout: TimeSpan.FromMilliseconds(startTimeoutMS), circuitResetTimeout: TimeSpan.FromMilliseconds(resetTimeout)); Assumes.True(circuitBreaker != null, string.Intern("circuitBreaker is null")); await circuitBreaker.ExecuteAsync(action); } catch (CircuitBreakerOpenException e1) { OnError?.Invoke(e1); Console.WriteLine(e1.Message, Color.Red); } catch (CircuitBreakerTimeoutException e2) { OnError?.Invoke(e2); Console.WriteLine(e2.Message, Color.Red); } catch (Exception e3) { OnError?.Invoke(e3); Console.WriteLine(e3.Message, Color.Red); } }
public void ExecuteExercise() { Console.WriteLine($"Escriba el texto para guardarlo en el fichero {Util.USER_PHRASES_FILE}"); Helper.WriteFileWhileWriteInConsole(Util.USER_PHRASES_FILE); Console.WriteLine("Pasamos a la lectura de todo el documento", Color.DarkGreen); Console.WriteLine("Inicio del documento", Color.DarkBlue); try { using (var streamReader = new StreamReader(Util.USER_PHRASES_FILE)) { while (!streamReader.EndOfStream) { Console.WriteLine(streamReader.ReadLine()); } } Console.WriteLine("Final del documento", Color.DarkBlue); } catch (Exception exception) { Console.WriteLine("Excepcion capturada" + $"\n {exception.Message}", Color.DarkRed); } }
public static Terminal Init(ColorScheme colorScheme) { _colorScheme = colorScheme; Console.BackgroundColor = colorScheme.BackgroundColor; Console.ForegroundColor = colorScheme.Text; _terminal = GetTerminal(); if (_terminal != Terminal.Powershell) { Console.ResetColor(); } if (_terminal != Terminal.Cygwin) { Console.Clear(); } Assembly assembly = typeof(CliConsole).Assembly; AssemblyInformationalVersionAttribute versionAttribute = assembly.GetCustomAttributes(false).OfType <AssemblyInformationalVersionAttribute>().FirstOrDefault(); string version = versionAttribute?.InformationalVersion; Console.WriteLine("**********************************************", _colorScheme.Comment); Console.WriteLine(); Console.WriteLine("Nethermind CLI {0}", GetColor(_colorScheme.Good), version); Console.WriteLine(" https://github.com/NethermindEth/nethermind", GetColor(_colorScheme.Interesting)); Console.WriteLine(" https://nethermind.readthedocs.io/en/latest/", GetColor(_colorScheme.Interesting)); Console.WriteLine(); Console.WriteLine("powered by:", _colorScheme.Text); Console.WriteLine(" https://github.com/sebastienros/jint", GetColor(_colorScheme.Interesting)); Console.WriteLine(" https://github.com/tomakita/Colorful.Console", GetColor(_colorScheme.Interesting)); Console.WriteLine(" https://github.com/tonerdo/readline", GetColor(_colorScheme.Interesting)); Console.WriteLine(); Console.WriteLine("**********************************************", _colorScheme.Comment); Console.WriteLine(); return(_terminal); }
public static void ShowDark(string text, string button) { string[] messageBox = { "╔════════════════════ M E S S A G E ═════════════════════╗", "║ ║", "║ ║", "║ ║", "║ ║", "╚═══════════════════════════════════════════════════════════╝", }; Console.WriteLine(); Console.BackgroundColor = Color.Blue; for (int i = 0; i < messageBox.Length; i++) { Console.SetCursorPosition((Console.WindowWidth - messageBox[i].Length) / 2, Console.CursorTop); Console.WriteLine(messageBox[i], Color.White); } Console.SetCursorPosition((Console.WindowWidth - text.Length) / 2, Console.CursorTop - 4); Console.WriteLine(text, Color.Black); Console.SetCursorPosition((Console.WindowWidth - button.Length) / 2, Console.CursorTop + 1); Console.WriteLine(button, Color.Black); Console.BackgroundColor = Color.Black; }
/// <summary> /// Рисует вверху экрана информационную панель /// </summary> /// <param name="statusEmailService">Статус сервиса Email</param> /// <param name="statusSendBidsService">Статус сервиса SendBids</param> /// <param name="statusProblemDevicesService">Статус сервиса ProblemDevices</param> /// <param name="statusReportsService">Статус сервиса Reports</param> static void DrawScreen(bool statusEmailService, bool statusSendBidsService, bool statusProblemDevicesService, bool statusReportsService) { List <char> logo = new List <char>() { '-', '-', '-', 'S', 'E', 'R', 'V', 'I', 'C', 'E', 'S', '-', '-', '-' }; // Clear Console Console.Clear(); Console.WriteWithGradient(logo, Color.Crimson, Color.Fuchsia); Console.WriteLine(Environment.NewLine); // Draw Statusbar again on the 'top' Console.WriteLine("----------------------------------"); Console.WriteLine("Сервис 'Email' {0}", statusEmailService ? "запущен" : "остановлен", statusEmailService ? Color.SeaGreen : Color.Crimson); Console.WriteLine("Сервис 'Send bids' {0}", statusSendBidsService ? "запущен" : "остановлен", statusSendBidsService ? Color.SeaGreen : Color.Crimson); Console.WriteLine("Сервис 'Problem devices' {0}", statusProblemDevicesService ? "запущен" : "остановлен", statusProblemDevicesService ? Color.SeaGreen : Color.Crimson); Console.WriteLine("Сервис 'Reports' {0}", statusReportsService ? "запущен" : "остановлен", statusReportsService ? Color.SeaGreen : Color.Crimson); Console.WriteLine("----------------------------------"); Console.WriteLine(Environment.NewLine); // Draw additional stuff }
private static void AddMoreStudents() { while (true) { Console.WriteLine("¿Desea agregar más estudiantes? si(s) / no(n)"); var decision = Console.ReadLine()?.ToLower(); if (decision != null && (decision.Equals("s") || decision.Equals("si"))) { var newStudent = AddStudentWithConstructorDefault(); if (!_classrooms.Any()) { SchoolHelper.ConsoleWriteLine("No existe ninguna clase aún,¿Desea agregar nueva aula? si(s) / no(n)", Color.White); var decisionClassroom = Console.ReadLine()?.ToLower(); if (decisionClassroom != null && (decisionClassroom.Equals("s") || decisionClassroom.Equals("si"))) { AddClassroom(false); } } AddPossibleStudentIntoClassroom(newStudent); ShowBasicInfoStudent(newStudent, false); } break; } }
public bool Run() { PrepareData(); var graph = new Graph(); //import GraphDef from pb file graph.Import(Path.Join(dir, pbFile)); var input_name = "input"; var output_name = "output"; var input_operation = graph.OperationByName(input_name); var output_operation = graph.OperationByName(output_name); var labels = File.ReadAllLines(Path.Join(dir, labelFile)); var result_labels = new List <string>(); var sw = new Stopwatch(); using (var sess = tf.Session(graph)) { foreach (var nd in file_ndarrays) { sw.Restart(); var results = sess.run(output_operation.outputs[0], (input_operation.outputs[0], nd)); results = np.squeeze(results); int idx = np.argmax(results); Console.WriteLine($"{labels[idx]} {results[idx]} in {sw.ElapsedMilliseconds}ms", Color.Tan); result_labels.Add(labels[idx]); } } return(result_labels.Contains("military uniform")); }
static void Introduction() { BlackMesaLogo(); Console.Clear(); Console.WriteLine("Welcome to Black Mesa Elevator Simulator!"); Console.WriteLine("-----------------------------------------"); Console.WriteLine("Here you can observe our special agents going up and\n" + "down the elevator until they decide to leave. Black\n" + "Mesa, as we've built it here, has different floors, each\n" + "with different security clearance.\n"); Console.WriteLine("The floors of the base are as follows:\n" + " - G - ground floor\n" + " - S - secret floor with nuclear weapons\n" + " - T1 - secret floor with experimemtal weapons\n" + " - T2 - top-secret floor that stores alien remains\n"); Console.WriteLine("Our scientists and their security clearances are:"); Console.WriteLine(" - Barney Calhoun - confidential - level G", Color.Cyan); Console.WriteLine(" - Dr. Eli Vance - secret - levels G and S", Color.Lime); Console.WriteLine(" - Dr. Gordon Freeman - top-secret - levels G, S, T1 and T2", Color.Orange); Console.WriteLine("At the beginning of each day all our scientists\n" + "start at the ground floor - that's where\n" + "the elevator initially is, too. Somebody\n" + "gets inside and goes to a random floor.\n" + "If their security clearance is not enough,\n" + "the doors won't open and they have to choose\n" + "another floor. If they can leave on this floor,\n" + "they do it. An agent goes home if they've been to\n" + "at least one floor other than G and then return to G.\n"); Console.WriteLine("Press ENTER to begin the simulation!"); Console.ReadLine(); Console.Clear(); }
public void RightQuest() { var notChosen = false; while (!notChosen) { var userInput = ReadQuest("You can now either go forward or look more in the bar. What do you do?", "forward", "look", "Sorry, but that is not an alternative"); if (userInput == "forward") { Console.Clear(); PrintQuest(Forward); notChosen = true; SoundQuest(); } else if (userInput == "look") { notChosen = true; LookMoreInBarQuest(); } } }
public static void Start() { char[] alpha = "AfnOmhIFoWUb73dauQpLg6XwqJxiNY5T1r4SlkvztH2yeBsGE8DRPCVMcKZ9".ToCharArray(); // 16 char gift url generatorDate = DateTime.Now.ToString(); Console.WriteLine($"[INF] Starting generator at : {generatorDate}", ColorTranslator.FromHtml("#0972ec")); Thread.Sleep(2000); for (int i = 0; i < amount; i++) { List <char> tmpCode = new List <char> { }; for (int j = 0; j < 16; j++) { Random rand = new Random(); int itemNum = rand.Next(0, alpha.Length - 1); char tmpChar = alpha[itemNum]; tmpCode.Add(tmpChar); } string completeCode = String.Join("", tmpCode); Console.WriteLine($"[-] {completeCode}", ColorTranslator.FromHtml("#08d91a")); codeSave.Add(completeCode); } Save(); }
private void HandlePosts(HtmlNodeCollection posts) { Console.WriteLine("Please select the thread to open:"); List <dynamic[]> postHandling = new List <dynamic[]>(); for (int i = 0; i < posts.Count; i++) { HtmlNode post = posts[i]; dynamic[] postCat = GetPostCat(post); HtmlNode topic = post.SelectSingleNode(".//span[contains(@class, \"topic\")]"); string link = Etc.DEFAULT_URI + post.GetAttributeValue("href", ""); string title = HttpUtility.HtmlDecode(topic.InnerText); string replies = topic.NextSibling.InnerText; //[posturl, corresponding Class.Get() function] postHandling.Add(new dynamic[] { link, postCat[2] }); //num Console.Write(String.Format("{0, -3}", (i + 1) + ".")); //category Console.Write(String.Format("{0, -8}", postCat[0]), postCat[1]); //thread title Console.Write(title + " (" + replies + ")\n"); } string hint = "(1-" + posts.Count + ", Q to quit, B to return): "; int intEntry = GetForumEntry(hint); if (intEntry > -1) { string _link = postHandling[intEntry][0]; dynamic obj = postHandling[intEntry][1]; //calls the .Get function in the class referenced in it's own _CAT variable obj.Get(_link); } }
public static void TardisCaveText(bool doctorPresent)// change this a little more { Console.WriteLine("Your drill emerges into a vast cave system, right next to a blue phone box with a light glow eminating from its windows\n\n"); if (doctorPresent) { Console.WriteLine("The Doctor is ecstatic!\n\n" + "\"I was hoping I left my TARDIS here!\"\n\n" + "The Doctor mummbles something about \"fishfingers and custard\".\n\n" + "They bid everyone adieu and enter the box.\n\n" + "The blue phone box turns transparent and disappears with a distinctive noise.\n\n" + "Eveyone pauses for a moment to realize they now have one less in the party.\n\n" + "On the plus side when the TARDIS leaves you find a deep lava tube behind it."); Sounds.TardisWoosh(); //Thread.Sleep(5_000); // Tardis sound takes a while } else { Console.WriteLine("Your crew is amazed by the box.\n\n" + "They try to open it no avail and find nothing external powering it\n\n" + "You make sure to log it so you can report it to the SCP foundation when you get surface side\n\n" + "As you prepare to resume your journey you find some lava tubes leading deeper into the Earth\n\n"); Thread.Sleep(10_000); // Tardis sound takes a while } }
public void PrintBoard() { // Rows from 1 to 10 // Columns from A to K // Each item is 3 chars, surrounded by "|" on either side // Color is given by Ownership: Gray for Board, Red for FirstPlayer, Blue for SecondPlayer // Due to print order, we first print the LAST rows going down Console.BackgroundColor = Color.Black; Console.ForegroundColor = Color.Bisque; var reverse_list = this.State.Reverse(); for (int RowIndex = 10; RowIndex > 0; RowIndex--) { Console.WriteLine(); // Print row number Console.Write(String.Format("{0} ", RowIndex).Substring(0, 3)); // Print the whole row, color-coded var row_enum = reverse_list.Skip(DefaultBoardSize - RowIndex).Take(DefaultBoardSize).Reverse(); row_enum.Select(cell => { CellFormaterPrinter(cell); return(true); }); Console.Write("|"); } // Print the lower Column designations Console.Write(" "); for (char col_index = 'A'; col_index < 'K'; col_index++) { Console.Write(" {0} ", col_index); } Console.WriteLine(); Console.WriteLine("- - - - - - - - - - "); }
public static void HeySatanText(bool priestPresent) //some kind of red and black theme { Console.WriteLine("You fall into a cave system. All around, rocks are bursting into flame and pools of acid bubble.\n\n" + "A huge being with curved horns and massive hooves sits upon a throne and speaks in a powerful, terrible voice.\n\n" + "\"Who dares enter my domain ?\"\n\n"); Sounds.HellNoise(); if (priestPresent) { Console.WriteLine("The Priest shakily creeps up to the microphone, a rosary clutched in one fist.\n\n" + "We are the servants of the most high God! I rebuke thee, Satan! I cast the into Hell in the name of the Father,\nand the Son, and the Holy Ghost!\n\n" + "The great beast laughs as nothing happens.\n\n" + "\"You cannot command me from within my own domain!\"\n\n" + "The beast laughed again, then grew thoughtful.\n\n" + "\"But you know, I have always wanted to cast someone into the depths of Hell.\"\n\n" + "The beast flicks his finger and tosses your drill deep into the depths of hell… and that much closer to your goal."); Sounds.SantaLaugh(); Thread.Sleep(15_000); } else { Console.WriteLine("None of you know how to answer the beast’s challenge. You run from the demons of hell as they attack."); Thread.Sleep(10_000); } }
private void InputLifts() { var operation = -1; do { ShowMenuTrails(); try { operation = int.Parse(Console.ReadLine()); } catch (Exception) { Console.WriteLine("Invalid input!", Color.Salmon); } switch (operation) { case 0: Exit(); break; case 1: Add(); break; case 2: Remove(); break; case 3: ListAll(); break; } } while (true); }
public static void HeyLizardPeepsText(bool mechanistPresent) { Console.WriteLine("You break through a wall into a room that is lavishly decorated in blue and gold.\n\n" + "A wide table spans the center of the room and robed figures cluster around it.\n\n" + "They seem to have been involved in a meeting of some sort, and they look up when you break through.\n\n" + "Long, scaly snouts protrude from their hoods, sniffing the air with forked tongues.\n\n" + "You have interrupted a meeting of the secret lizard illuminati masons!\n\n"); if (mechanistPresent) { Console.WriteLine("The Mechanist realizes that the blinking in their eyes conforms to a Fourier series.\n\n" + "\"They’re robots!\" he yells.\n\n" + "The secret lizard illuminati masons are embarrassed to have been discovered so easily.\n\n" + "They promise to provide you with the cure to the common cold if you will leave and not tell anyone about their secret."); Sounds.ActuallyRobots(); Thread.Sleep(15_000); } else { Console.WriteLine("The secret lizard illuminati masons are angry that you have interrupted their planning meeting.\n\n" + "They attack you and you must fight your way out.\n\n" + "You push your drill to its limits and keep going until the only thing outside is the harsh glow of the core"); Thread.Sleep(15_000); } }
public void Get(string postURL, bool prompt = false, HtmlNode matchNode = null) { //reinitialising stuff this.prompt = prompt; HtmlDocument doc = Etc.GetDocFromURL(postURL); //will use match page document node if provided HtmlNode contents = (matchNode == null) ? doc.DocumentNode.SelectSingleNode("//div[@class=\"contentCol\"]") : matchNode.SelectSingleNode("//div[@class=\"contentCol\"]"); //only finds op if on forum and not the match page if (matchNode == null) { //gets op/first box in thread HtmlNode opContainer = contents.SelectSingleNode(".//div[contains(@class, \"forumthread\")]"); HtmlNode opPost = opContainer.SelectSingleNode(".//div[@class=\"standard-box\"]"); string[] opString = GetPostString(opPost, op: true); Console.WriteLine("\n" + String.Join("\n", opString) + "\n"); } //gets all replies HtmlNode replyContainer = contents.SelectSingleNode(".//div[@class=\"forum no-promode\"]"); //yes there's a space there. single slash for getting post 1 level down HtmlNodeCollection mainPosts = replyContainer.SelectNodes("./div[@class=\"post \"]"); foreach (HtmlNode post in mainPosts) { string[] parentString = GetPostString(post, op: false); string formattedComment = FormatConsole("", parentString); Console.WriteLine(formattedComment); //children are sibling elements that contain replies to the post currently working on HtmlNode childrenNode = post.NextSibling.NextSibling; if (childrenNode.HasChildNodes) { HandleChildren(childrenNode, TAB); } } }
/// <summary> /// Connect to the server. /// </summary> public void Connect() { try { connection = new TcpClient(Server, Port); } catch { if (Debug) { Console.WriteLine("Connection Error"); } } try { networkStream = connection.GetStream(); streamReader = new StreamReader(networkStream); streamWriter = new StreamWriter(networkStream); } catch { if (Debug) { Console.WriteLine("Communication Error"); } } finally { Connected = true; if (Password != null) { SendData("PASS", Password); } SendData("USER", Nick + " something something " + Name); SendData("NICK", Nick); backgroundWorker.DoWork += Work; } }
public static void Main(string[] args) { Console.WriteAscii("Unsplash", Color.MediumSlateBlue); Console.WriteLine("Version 1.2.5", Color.YellowGreen); Console.WriteLine("Help us @ https://github.com/redbaty/Unsplash.Desktop\n", Color.Gray); if (args.Length == 0 || args[0] != "-g") { try { Settings = JsonConvert.DeserializeObject <Settings>( File.ReadAllText(Environment.ExpandEnvironmentVariables("%USERPROFILE%\\Unsplash.desktop")), JsonSettings ); } catch (Exception ex) { Console.WriteLine("> Failed to load settings.", Color.Crimson); Console.WriteLine(ex.Message, Color.Crimson); Console.WriteLine("> Run the program with -g to generate another one.", Color.CadetBlue); return; } } else if (args.Length != 0 && args[0] == "-g") { GenerateSettings(); } Console.WriteLine("> Downloading wallpaper image...", Color.Gray); Wallpaper.Set( new Uri(Settings.Source.BuildUrlString(Settings)), Settings.WallpaperDisplayStyle); Console.WriteLine("> New wallpaper set!", Color.LimeGreen); Console.WriteLine("> Press any key to continue", Color.Gray); }
public void Execute(CommandContext context) { try { if (!File.Exists(FilePath)) { ConsoleHelper.PrintError($"文件不存在:{FilePath}"); } else { var fileDir = new FileInfo(FilePath).DirectoryName; var fileContent = File.ReadAllText(FilePath); var imgHandler = new ImageHandler(); var imgList = imgHandler.Process(fileContent); ConsoleHelper.PrintMsg($"提取图片成功,共 {imgList.Count} 个。"); //循环上传图片 foreach (var img in imgList) { if (img.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { ConsoleHelper.PrintMsg($"图片跳过:{img} "); continue; } try { var imgPhyPath = Path.Combine(fileDir !, img); if (File.Exists(imgPhyPath)) { var imgUrl = ImageUploadHelper.Upload(imgPhyPath); if (!ReplaceDic.ContainsKey(img)) { ReplaceDic.Add(img, imgUrl); } ConsoleHelper.PrintMsg($"{img} 上传成功. {imgUrl}"); } else { ConsoleHelper.PrintMsg($"{img} 未发现文件."); } } catch (Exception e) { Console.WriteLine(e.Message); } } //替换 fileContent = ReplaceDic.Keys.Aggregate(fileContent, (current, key) => current.Replace(key, ReplaceDic[key])); var newFileName = FilePath.Substring(0, FilePath.LastIndexOf('.')) + "-cnblog" + Path.GetExtension(FilePath); File.WriteAllText(newFileName, fileContent, FileEncodingType.GetType(FilePath)); ConsoleHelper.PrintMsg($"处理完成!文件保存在:{newFileName}"); } } catch (Exception e) { ConsoleHelper.PrintError(e.Message); } }
private void Append(string message, Color color) { Console.ForegroundColor = color; Console.Write(message); }