コード例 #1
0
        private string Tabularize(List <ServerInfo> serverList)
        {
            var scoreTable = new DataTable();

            scoreTable.Columns.Add("# SERVER", typeof(string));
            scoreTable.Columns.Add("SCORE", typeof(string));
            scoreTable.Columns.Add("LEVEL", typeof(string));
            scoreTable.Columns.Add("NICKNAME", typeof(string));
            scoreTable.Columns.Add("PLAYER COUNT", typeof(string));

            foreach (var server in serverList)
            {
                scoreTable.Rows.Add(server.Label, server.TopPlayerScore, server.TopPlayerLevel, server.TopPlayerName, server.ClientCount);
            }

            var result = "```md\n";

            result += ConsoleTableBuilder.From(scoreTable)
                      .WithFormat(ConsoleTableBuilderFormat.Minimal)
                      .Export()
                      .ToString();

            result += "```";
            return(result);
        }
        public async Task <int> CreateStatsAsync(MonsterCreationOption creationOption)
        {
            try
            {
                var _monsterStatsGenerator = _monsterStatsGeneratorStrategyFactory.Get(creationOption);
                var monsterStats           = new List <MonsterStats>
                {
                    _monsterStatsGenerator.GenerateMonsterStats(creationOption)
                };

                ConsoleTableBuilder.From(monsterStats)
                .WithFormat(ConsoleTableBuilderFormat.MarkDown)
                .ExportAndWriteLine();

                if (creationOption.WriteToFile)
                {
                    await _fileCreatorService.CreateFile(creationOption.Path, monsterStats);
                }
            }
            catch (Exception ex)
            {
                _logger.LogDebug(ex, "Something went wrong...");
                return(-1);
            }

            return(0);
        }
コード例 #3
0
        static void Main(string[] args)
        {
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
            ///Specify the name of the database
            string database = "db_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var    builder  = new TaosConnectionStringBuilder()
            {
                DataSource = "114.116.231.247",
                DataBase   = database,
                Username   = "******",
                Password   = "******",
                Port       = 6060
            };

            //Example for ADO.Net
            using (var connection = new TaosConnection(builder.ConnectionString))
            {
                connection.Open();

                Console.WriteLine("create {0} {1}", database, connection.CreateCommand($"create database {database};").ExecuteNonQuery());
                Console.WriteLine("create table t {0} {1}", database, connection.CreateCommand($"create table {database}.t (ts timestamp, cdata int);").ExecuteNonQuery());
                Console.WriteLine("insert into t values  {0}  ", connection.CreateCommand($"insert into {database}.t values ({(long)(DateTime.Now.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds)}, 10);").ExecuteNonQuery());
                //Console.WriteLine("insert into t values  {0} ", connection.CreateCommand($"insert into {database}.t values ({(long)(DateTime.Now.AddMonths(1).Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds)}, 20);").ExecuteNonQuery());
                var cmd_select = connection.CreateCommand();
                cmd_select.CommandText = $"select * from {database}.t";
                var reader = cmd_select.ExecuteReader();
                Console.WriteLine(cmd_select.CommandText);
                Console.WriteLine("");
                ConsoleTableBuilder.From(reader.ToDataTable()).WithFormat(ConsoleTableBuilderFormat.MarkDown).ExportAndWriteLine();
                Console.WriteLine("");
                Console.WriteLine("DROP TABLE  {0} {1}", database, connection.CreateCommand($"DROP TABLE  {database}.t;").ExecuteNonQuery());
                Console.WriteLine("DROP DATABASE {0} {1}", database, connection.CreateCommand($"DROP DATABASE   {database};").ExecuteNonQuery());
                connection.Close();
            }
            //Example for  Entity Framework Core
            using (var context = new TaosContext(new DbContextOptionsBuilder()
                                                 .UseTaos(builder.ConnectionString).Options))
            {
                Console.WriteLine("EnsureCreated");
                context.Database.EnsureCreated();
                for (int i = 0; i < 10; i++)
                {
                    var rd = new Random();
                    context.sensor.Add(new sensor()
                    {
                        ts = DateTime.Now.AddMilliseconds(i), degree = rd.NextDouble(), pm25 = rd.Next(0, 1000)
                    });
                }
                Console.WriteLine("Saveing");
                context.SaveChanges();
                Console.WriteLine("");
                Console.WriteLine("from s in context.sensor where s.pm25 > 0 select s ");
                Console.WriteLine("");
                var f   = from s in context.sensor where s.pm25 > 0 select s;
                var ary = f.ToArray();
                ConsoleTableBuilder.From(ary.ToList()).WithFormat(ConsoleTableBuilderFormat.MarkDown).ExportAndWriteLine();
                context.Database.EnsureDeleted();
            }
            Console.WriteLine("");
        }
コード例 #4
0
        static void Main(string[] args)
        {
            while (true)
            {
                Console.Clear();
                Console.WriteLine("Enter First Name ");
                fName = Console.ReadLine().ToLower();

                Console.WriteLine("Enter Last Name ");
                LName = Console.ReadLine().ToLower();


                ////int word1Score = GenerateScoreValue(word1);
                ////  Console.WriteLine(word1Score);

                //Console.WriteLine("Enter Word 2");
                //string word2 = Console.ReadLine().ToUpper();
                ////int word2Score = GenerateScoreValue(word2);
                //// Console.WriteLine(word2Score);



                //Console.WriteLine(val);



                ConsoleTableBuilder
                .From(GetRealData())
                .ExportAndWriteLine();
                // Should_Be_Similar();
                Console.ReadKey();
            }
        }
コード例 #5
0
        private string BuildTabularData(Answer answerResult)
        {
            var answerResponse  = string.Empty;
            var tablularHeaders = answerResult.Facts.Value[0].RichCaption.Header;
            var tabularData     = answerResult.Facts.Value[0].RichCaption.Rows;

            var table = new DataTable();

            foreach (var header in tablularHeaders)
            {
                if (string.IsNullOrWhiteSpace(header))
                {
                    table.Columns.Add(" ");
                }
                else
                {
                    table.Columns.Add(header);
                }
            }

            foreach (var row in tabularData)
            {
                var cells = row.Cells.Select(r => r.Text).ToArray();
                table.Rows.Add(cells);
            }

            var tableBuilder = ConsoleTableBuilder.From(table);

            answerResponse = "```\n" + tableBuilder.Export().ToString() + "\n```";

            return(answerResponse);
        }
コード例 #6
0
        private void ReadEntries(string SheetName)
        {
            string range = $"{SheetName}!A:F";

            SpreadsheetsResource.ValuesResource.GetRequest request = service.Spreadsheets.Values.Get(SpreadSheetID, range);

            ValueRange response = request.Execute();

            IList <IList <object> > values = response.Values;

            if (values != null && values.Count > 0)
            {
                DataTable table = new DataTable(SheetName);

                foreach (object rowheader in values[0])
                {
                    table.Columns.Add(rowheader.ToString(), typeof(string));
                }

                foreach (IList <object> row in values.Skip(1))
                {
                    table.Rows.Add(row.Cast <string>().ToArray());
                }

                ConsoleTableBuilder
                .From(table)
                .WithFormat(ConsoleTableBuilderFormat.MarkDown)
                .ExportAndWriteLine();
            }
            else
            {
                Console.WriteLine("No data found.");
            }
        }
コード例 #7
0
ファイル: Program.cs プロジェクト: kogratte/ProjectManagement
        private static void PrintFwkVersion(List <Solution> solutions, CommandLineOption opts)
        {
            List <IGrouping <string, Solution> > a = solutions.GroupBy(s => s.TargetFramework).ToList();
            DataTable table = new DataTable();

            table.Columns.Add("Framework", typeof(string));
            table.Columns.Add("Projects", typeof(string));

            if (!string.IsNullOrEmpty(opts.NetFwkOutputFile))
            {
                File.Delete(opts.NetFwkOutputFile);
            }

            a.ForEach((grouping) =>
            {
                grouping.ToList().ForEach(solution =>
                {
                    if (!string.IsNullOrEmpty(opts.NetFwkOutputFile))
                    {
                        File.AppendAllText(opts.NetFwkOutputFile, $"{solution.Name};{solution.TargetFramework};{Environment.NewLine}");
                    }
                    table.Rows.Add(solution.TargetFramework, solution.Name);
                });
            });

            if (opts.Verbose)
            {
                ConsoleTableBuilder.From(table).ExportAndWriteLine();
            }
        }
コード例 #8
0
        static void DisplayQuickNetworkResponse()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("EXPECTED");
            dt.Columns.Add("ACTUAL");
            dt.Columns.Add("PROBABILITY [%]");


            for (int l = 0; l < X.Length; l++)
            {
                double[][] x = Matrix.Create(1, N);
                x[0] = X[l];

                int expectedResponse = Y[l].ToList().IndexOf(Y[l].Max());

                var    y = CalculateReponse(x);
                double actualMaxValue = y.Max();
                int    actualResponse = y.ToList().IndexOf(actualMaxValue);

                DataRow row = dt.NewRow();
                row[0] = (Animals)expectedResponse;
                row[1] = (Animals)actualResponse;
                row[2] = actualMaxValue;

                dt.Rows.Add(row);
            }

            ConsoleTableBuilder builder = ConsoleTableBuilder.From(dt);

            builder.ExportAndWrite();
        }
コード例 #9
0
        /// <summary>
        /// writes the sheet in tabular form to standard output
        /// </summary>
        /// <param name="sheet"> A google spreadsheet </param>
        public static void ConsoleLogSheet(Sheet sheet)
        {
            if (sheet != null)
            {
                DataTable table = new DataTable();
                // header
                foreach (var item in sheet.Data[0].RowData[0].Values)
                {
                    table.Columns.Add(item.FormattedValue, typeof(string));
                }

                var body = sheet.Data[0].RowData.Skip(1);
                // rows
                foreach (var rowData in body)
                {
                    table.Rows.Add(rowData.Values.Select(r => r.FormattedValue).ToArray());
                }

                // print
                ConsoleTableBuilder
                .From(table)
                .ExportAndWriteLine();
            }
            else
            {
                Console.WriteLine("No data found");
            }
        }
コード例 #10
0
ファイル: Main.cs プロジェクト: ulyanovsemen/git-analyzer
        internal static void Work(string[] args)
        {
            var inputData = ConsoleParamsParser.GetParams(args);

            var calculator = new Calculator(inputData);

            calculator.Init();

            var resultTable = new DataTable();

            resultTable.Columns.Add("Автор", typeof(string));

            var results = new List <Result>();

            var totalDays = (inputData.DtTill - inputData.DtFrom).Days;

            for (int i = 0; i <= totalDays; i = i + INTERVAL)
            {
                var dtStepFrom = inputData.DtFrom.AddDays(i);
                var dtStepTill = inputData.DtFrom.AddDays(i + INTERVAL);

                resultTable.Columns.Add(dtStepFrom.ToShortDateString() + " - " + dtStepTill.ToShortDateString(), typeof(int));

                var result = calculator.Calculate(dtStepFrom, dtStepTill);
                results.Add(result);
            }

            FillResultTable(results, resultTable);

            if (resultTable.Rows.Count != 0)
            {
                ConsoleTableBuilder.From(resultTable).ExportAndWriteLine();
            }
        }
コード例 #11
0
        public void AlternativeFormatWithUtf8CharactersDataTable()
        {
            var strBuilder =
                ConsoleTableBuilder
                .From <dynamic>(SampleData.SampleListWithUtf8Characters)
                .WithTitle("a中123午b", ConsoleColor.Yellow, ConsoleColor.DarkGray)
                .WithFormat(ConsoleTableBuilderFormat.Alternative)
                .Export();

            Assert.IsTrue(strBuilder.ToString() == @"
+-------------+-------------- a中123午b +-----------+------+---------+
| Id          | Name                    | Host      | Port | status  |
+-------------+-------------------------+-----------+------+---------+
| 中午午午午c | tab其它语言test         | 127.0.0.1 | 80   | success |
+-------------+-------------------------+-----------+------+---------+
| a中午b      | London语a言aa它xx       | 127.0.0.1 | 80   | success |
+-------------+-------------------------+-----------+------+---------+
| Airi Satou  | Accountant              | 127.0.0.1 | 80   | Tokyo   |
+-------------+-------------------------+-----------+------+---------+
| Ashton Cox  | Junior Technical Author | 127.0.0.1 | 80   | success |
+-------------+-------------------------+-----------+------+---------+
".TrimStart());

            var lines = strBuilder.ToString().Split('\n');

            Assert.IsTrue(lines.Length == 12);
        }
コード例 #12
0
 public static ConsoleTableBuilder ApplyVisualStyle(this ConsoleTableBuilder consoleTableBuilder)
 {
     return(consoleTableBuilder
            .WithCharMapDefinition(new Dictionary <CharMapPositions, char> {
         { CharMapPositions.BottomLeft, '=' },
         { CharMapPositions.BottomCenter, '=' },
         { CharMapPositions.BottomRight, '=' },
         { CharMapPositions.BorderTop, '=' },
         { CharMapPositions.BorderBottom, '=' },
         { CharMapPositions.BorderLeft, '|' },
         { CharMapPositions.BorderRight, '|' },
         { CharMapPositions.DividerY, '|' },
     })
            .WithHeaderCharMapDefinition(new Dictionary <HeaderCharMapPositions, char> {
         { HeaderCharMapPositions.TopLeft, '=' },
         { HeaderCharMapPositions.TopCenter, '=' },
         { HeaderCharMapPositions.TopRight, '=' },
         { HeaderCharMapPositions.BottomLeft, '|' },
         { HeaderCharMapPositions.BottomCenter, '-' },
         { HeaderCharMapPositions.BottomRight, '|' },
         { HeaderCharMapPositions.Divider, '|' },
         { HeaderCharMapPositions.BorderTop, '=' },
         { HeaderCharMapPositions.BorderBottom, '-' },
         { HeaderCharMapPositions.BorderLeft, '|' },
         { HeaderCharMapPositions.BorderRight, '|' },
     }));
 }
コード例 #13
0
        static void DisplayFullNetworkResponse()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("y1");
            dt.Columns.Add("y2");
            dt.Columns.Add("y3");

            for (int l = 0; l < X_train.Length; l++)
            {
                double[][] x = Matrix.Create(1, N);
                x[0] = X_train[l];

                var y = CalculateReponse(x);

                DataRow row = dt.NewRow();
                row[0] = "PD";
                row[1] = "PI";
                row[2] = "PID";
                row[3] = y[0];
                row[4] = y[1];
                row[5] = y[2];

                dt.Rows.Add(row);
            }

            ConsoleTableBuilder builder = ConsoleTableBuilder.From(dt);

            builder.ExportAndWrite();
        }
コード例 #14
0
        protected void Table(string name, IEnumerable <object> rows)
        {
            if (rows.Any())
            {
                var type       = rows.First().GetType();
                var properties = type.GetProperties();

                var dt = new DataTable();
                foreach (var property in properties)
                {
                    dt.Columns.Add(property.Name);
                }

                foreach (var row in rows)
                {
                    dt.Rows.Add(properties.Select(p => Truncate(p.GetValue(row)?.ToString(), 75)).ToArray());
                }

                ConsoleTableBuilder
                .From(dt)
                .WithOptions(new ConsoleTableBuilderOption
                {
                    Delimiter  = " ",
                    TrimColumn = true
                })
                .WithFormat(ConsoleTableBuilderFormat.Minimal)
                .ExportAndWriteLine();
            }
            else
            {
                Console.WriteLine($"{name} has no data");
            }
        }
コード例 #15
0
ファイル: Init.cs プロジェクト: olivierh59500/inVtero.net
        private static void InitImpl()
        {
            ArgPipelineObjectMapper.CurrentMapper = new JObjectArgPipelineMapper();

            PipelineOutputFormatter.RegisterFormatter(typeof(JObject), FuncPipelineOutputFormatter.Create((obj) =>
            {
                JObject jObj = (JObject)obj;
                ConsoleTableBuilder builder  = new ConsoleTableBuilder();
                List <ConsoleString> headers = new List <ConsoleString>()
                {
                    new ConsoleString("PROPERTY", ConsoleColor.Yellow), new ConsoleString("VALUE", ConsoleColor.Yellow)
                };
                List <List <ConsoleString> > rows = new List <List <ConsoleString> >();
                foreach (var prop in jObj.Properties())
                {
                    rows.Add(new List <ConsoleString>()
                    {
                        new ConsoleString(prop.Name, ConsoleColor.Gray), new ConsoleString("" + prop.Value, ConsoleColor.Green)
                    });
                }

                var jObjRet = builder.FormatAsTable(headers, rows);
                jObjRet     = new ConsoleString("Pipeline output of type JObject: \n") + jObjRet;
                return(jObjRet);
            }));
        }
コード例 #16
0
        static void ChargeInterests()
        {
            if (_bank.AccountsCount > 0)
            {
                Console.WriteLine($"Accounts charged: ({_bank.AccountsCount})");

                var table = new DataTable();

                table.Columns.Add("ID", typeof(string));
                table.Columns.Add("Old Balance", typeof(string));
                table.Columns.Add("New Balance", typeof(string));
                table.Columns.Add("Differential", typeof(string));
                table.Columns.Add("Interest", typeof(string));


                _bank.Accounts.ForEach(account =>
                {
                    var oldBalance = account.Balance;
                    _bank.ChargeInterest(account);
                    var newBalance = account.Balance;
                    table.Rows.Add(account.Id, $"{oldBalance} kr", $"{newBalance} kr", $"{oldBalance - newBalance} kr", $"{account.InterestRate * 100} %");
                });

                ConsoleTableBuilder.From(table).WithFormat(ConsoleTableBuilderFormat.Minimal).ExportAndWriteLine();
            }
            else
            {
                Console.WriteLine("There are no registered accounts...");
            }

            Console.Read();
        }
コード例 #17
0
        static void DisplayAccounts()
        {
            Console.Clear();

            if (_bank.AccountsCount > 0)
            {
                Console.WriteLine($"Registered accounts: ({_bank.AccountsCount})");

                var table = new DataTable();

                table.Columns.Add("ID", typeof(string));
                table.Columns.Add("Name", typeof(string));
                table.Columns.Add("Balance", typeof(string));
                table.Columns.Add("Account Type", typeof(string));


                _bank.Accounts.ForEach(account =>
                {
                    table.Rows.Add(account.Id, account.Name, $"{account.Balance} kr", account.Type.ToString());
                });

                ConsoleTableBuilder.From(table).WithFormat(ConsoleTableBuilderFormat.Minimal).ExportAndWriteLine();
            }
            else
            {
                Console.WriteLine("There are no registered accounts...");
            }

            Console.Read();
        }
コード例 #18
0
        private void LoadAndTest(FlowProfile profile, IEnumerable <IPacketRecord> packets)
        {
            var getFlowKeyFunc  = FlowKey.GetFlowKeyFunc(profile.FlowAggregation);
            var getModelKeyFunc = profile.ProtocolFactory.GetModelKeyFunc(profile.ModelKey);

            var startTime  = packets.First().TimeEpoch;
            var packetBins = packets.GroupBy(p => (int)Math.Floor((p.TimeEpoch - startTime) / profile.WindowSize));

            var normalTotal   = 0;
            var abnormalTotal = 0;
            var unknownTotal  = 0;

            foreach (var group in packetBins)
            {
                var flows       = profile.ProtocolFactory.CollectCoapFlows(group, getModelKeyFunc, getFlowKeyFunc);
                var testResults = TestAndPrint(profile, flows, $"{DateTime.UnixEpoch.AddSeconds((long)startTime + (group.Key * profile.WindowSize))}");
                normalTotal   += testResults.Normal;
                abnormalTotal += testResults.Abnormal;
                unknownTotal  += testResults.Unknown;
            }
            var measuresTable = new DataTable();

            measuresTable.Columns.Add("Metric", typeof(string));
            measuresTable.Columns.Add("Value", typeof(double));
            measuresTable.Rows.Add("Normal", normalTotal);
            measuresTable.Rows.Add("Abnormal", abnormalTotal);
            measuresTable.Rows.Add("Unknown", unknownTotal);
            Console.WriteLine("Measures:");
            ConsoleTableBuilder.From(measuresTable)
            .WithFormat(ConsoleTableBuilderFormat.MarkDown)
            .ExportAndWriteLine();
        }
コード例 #19
0
        public static void PrintConfusionTable(List <string> labelnames, int[,] matrix)
        {
            Console.WriteLine("Konfusionstabel");
            DataTable dt = new DataTable();

            dt.Columns.Add("Forfatter");
            for (int dimension = 0; dimension < labelnames.Count; dimension++)
            {
                dt.Columns.Add(labelnames[dimension]);
            }

            for (int element = 0; element < (labelnames.Count); element++)
            {
                DataRow row = dt.NewRow();
                for (int dimension = 0; dimension < labelnames.Count; dimension++)
                {
                    //         Console.Write("{0} ", matrix[element, dimension]);
                    row[0] = labelnames[element];
                    if (labelnames[dimension] != "")
                    {
                        row[labelnames[dimension]] = matrix[element, dimension];
                    }
                }

                dt.Rows.Add(row);
            }
            ConsoleTableBuilder.From(dt).WithFormat(ConsoleTableBuilderFormat.Alternative).ExportAndWriteLine();
        }
コード例 #20
0
        void PrintEvaluation(int truePositive, int trueNegative, int falsePositive, int falseNegative)
        {
            var contingencyTable = new DataTable();

            contingencyTable.Columns.Add("", typeof(string));
            contingencyTable.Columns.Add("Normal Predicted", typeof(int));
            contingencyTable.Columns.Add("Abnormal Predicted", typeof(int));
            contingencyTable.Rows.Add("Normal Actual", truePositive, falseNegative);
            contingencyTable.Rows.Add("Abnormal Actual", falsePositive, trueNegative);
            Console.WriteLine("Confusion Matrix:");
            ConsoleTableBuilder.From(contingencyTable)
            .WithFormat(ConsoleTableBuilderFormat.MarkDown)
            .ExportAndWriteLine();

            // compute precision
            var precision     = truePositive / (double)(truePositive + falsePositive);
            var recall        = truePositive / (double)(truePositive + falseNegative);
            var accuracy      = (truePositive + trueNegative) / (double)(truePositive + trueNegative + falsePositive + falseNegative);
            var fmeasure      = 2 * (precision * recall) / (precision + recall);
            var measuresTable = new DataTable();

            measuresTable.Columns.Add("Metric", typeof(string));
            measuresTable.Columns.Add("Value", typeof(double));
            measuresTable.Rows.Add("Precision", precision);
            measuresTable.Rows.Add("Recall", recall);
            measuresTable.Rows.Add("Accuracy", accuracy);
            measuresTable.Rows.Add("F-measure", fmeasure);
            Console.WriteLine("Measures:");
            ConsoleTableBuilder.From(measuresTable)
            .WithFormat(ConsoleTableBuilderFormat.MarkDown)
            .ExportAndWriteLine();
        }
コード例 #21
0
        private void ImprimirTabelaAsync(AnaliseDto analiseDto)
        {
            List <AnaliseDto> listaBaseTabela = new List <AnaliseDto>()
            {
                analiseDto
            };

            ConsoleTableBuilder
            .From(listaBaseTabela)
            .WithFormat(ConsoleTableBuilderFormat.Alternative)
            .WithColumn(
                "Nome Arquivo",
                "Tamanho Arquivo",
                "Caminho Físico",
                "Número Iterações",
                "Tempo Total Geração Arquivo",
                "Tempo Médio Geração Arquivo")
            .WithTextAlignment(new Dictionary <int, TextAligntment>()
            {
                { 1, TextAligntment.Right },
                { 3, TextAligntment.Right },
                { 4, TextAligntment.Right },
                { 5, TextAligntment.Right }
            })
            .ExportAndWriteLine(TableAligntment.Left);
        }
コード例 #22
0
        public void AlternativeFormatWithDataTable()
        {
            var strBuilder =
                ConsoleTableBuilder
                .From(SampleData.SampleTableData)
                .WithFormat(ConsoleTableBuilderFormat.Alternative)
                .Export();

            Assert.IsTrue(strBuilder.ToString() == @"
+----------------+-------------------------------+---------------+-----+------------------------+
| Name           | Position                      | Office        | Age | Start Date             |
+----------------+-------------------------------+---------------+-----+------------------------+
| Airi Satou     | Accountant                    | Tokyo         | 33  | 5/9/2017 12:00:00 AM   |
+----------------+-------------------------------+---------------+-----+------------------------+
| Angelica Ramos | Chief Executive Officer (CEO) | New York      | 47  | 1/12/2017 12:00:00 AM  |
+----------------+-------------------------------+---------------+-----+------------------------+
| Ashton Cox     | Junior Technical Author       | London        | 46  | 4/2/2017 12:00:00 AM   |
+----------------+-------------------------------+---------------+-----+------------------------+
| Bradley Greer  | Software Engineer             | San Francisco | 28  | 11/15/2017 12:00:00 AM |
+----------------+-------------------------------+---------------+-----+------------------------+
".TrimStart());

            var lines = strBuilder.ToString().Split('\n');

            Assert.IsTrue(lines.Length == 12);
        }
コード例 #23
0
        public void ConsoleTableBasic()
        {
            ConsoleTableBuilder builder = new ConsoleTableBuilder();

            var columns = new List <ConsoleString>()
            {
                new ConsoleString("NAME"), new ConsoleString("ADDRESS"), new ConsoleString("DESCRIPTION")
            };
            var rows = new List <List <ConsoleString> >()
            {
                new List <ConsoleString>()
                {
                    new ConsoleString("Adam Abdelhamed"), new ConsoleString("One Microsoft Way, Redmond WA 98052"), new ConsoleString("The author of PowerArgs, the world's greatest command line parser and invoker.  Hooray for PowerArgs!  We love PowerArgs so much cuz it is awesome and great.  Yay!!!!  In fact, PowerArgs is so fun that nothing in the entire universe is more fun.  ")
                },
                new List <ConsoleString>()
                {
                    new ConsoleString("Alicia Abdelhamed"), new ConsoleString("Two Microsoft Way, Redmond WA 98052"), new ConsoleString("The wife of the author of PowerArgs, the world's greatest command line parser and invoker.  Hooray for PowerArgs!")
                },
            };


            var output = builder.FormatAsTable(columns, rows);
            var outstr = output.ToString();

            var expected =
                @"
NAME                ADDRESS                               DESCRIPTION                                                                                                                                                                                                                                               
Adam Abdelhamed     One Microsoft Way, Redmond WA 98052   The author of PowerArgs, the world's greatest command line parser and invoker.  Hooray for PowerArgs!  We love PowerArgs so much cuz it is awesome and great.  Yay!!!!  In fact, PowerArgs is so fun that nothing in the entire universe is more fun.     
Alicia Abdelhamed   Two Microsoft Way, Redmond WA 98052   The wife of the author of PowerArgs, the world's greatest command line parser and invoker.  Hooray for PowerArgs!                                                                                                                                         
".TrimStart();

            Helpers.AssertAreEqualWithDiffInfo(expected.Replace("\r\n", "\n"), outstr.Replace("\r\n", "\n"));
        }
コード例 #24
0
        static void DisplayTransactions()
        {
            Console.Clear();

            if (_bank.TransactionsCount > 0)
            {
                Console.WriteLine($"Registered transactions: ({_bank.TransactionsCount})");

                var table = new DataTable();

                table.Columns.Add("ID", typeof(string));
                table.Columns.Add("Sender", typeof(string));
                table.Columns.Add("Reciever", typeof(string));
                table.Columns.Add("Amount", typeof(string));


                _bank.Transactions.ForEach(transaction =>
                {
                    table.Rows.Add(transaction.Id.Substring(0, 12), transaction.Sender?.Id ?? "null", transaction.Reciever?.Id ?? "null", transaction.Amount.ToString("0.00"));
                });

                ConsoleTableBuilder.From(table).WithFormat(ConsoleTableBuilderFormat.Minimal).ExportAndWriteLine();
            }
            else
            {
                Console.WriteLine("There are no registered transactions...");
            }

            Console.Read();
        }
コード例 #25
0
        public void ConsoleTableTestLongWord()
        {
            ConsoleProvider.Current.BufferWidth = 160;
            ConsoleTableBuilder builder = new ConsoleTableBuilder();

            var columns = new List <ConsoleString>()
            {
                new ConsoleString("Word 1"), new ConsoleString("Word 2")
            };
            var rows = new List <List <ConsoleString> >()
            {
                new List <ConsoleString>()
                {
                    new ConsoleString(" ThisIsAVeryLongWord"), new ConsoleString("Hello. ThisIsAVeryLongWord ThisIsAnother AnotherVeryLongWord")
                }
            };

            var columnOverflowBehaviors = new List <ColumnOverflowBehavior>()
            {
                new SmartWrapOverflowBehavior()
                {
                    DefineMaxWidthBasedOnConsoleWidth = false, MaxWidthBeforeWrapping = 10
                },
                new SmartWrapOverflowBehavior()
                {
                    DefineMaxWidthBasedOnConsoleWidth = false, MaxWidthBeforeWrapping = 10
                }
            };

            builder.FormatAsTable(columns, rows, rowPrefix: "", columnOverflowBehaviors: columnOverflowBehaviors);
        }
コード例 #26
0
    public void Run()
    {
        var toRun   = Discover();
        var results = new UIBenchmarkComparison[toRun.Length];

        for (var i = 0; i < toRun.Length; i++)
        {
            results[i] = toRun[i].Run();
            GC.Collect(2, GCCollectionMode.Forced);
        }

        var headers = new List <ConsoleString>()
        {
            "Test".ToYellow(),
            "Work Done".ToYellow(),
            "Speedup".ToYellow(),
        };

        var output = new ConsoleTableBuilder().FormatAsTable(headers, results.Select(r => new List <ConsoleString>()
        {
            r.Test.ToString().ToWhite(),
            r.Temp.WorkDone.ToString("N0").ToWhite(),
            r.PaintSpeedupString,
        }).ToList());

        output.WriteLine();
    }
コード例 #27
0
ファイル: Parser.cs プロジェクト: Kucha1122/TextFileParser
        public void Display(List <Product> products)
        {
            var tableData = new List <List <object> >();

            foreach (var product in products)
            {
                var row = new List <object>
                {
                    product.Id,
                    product.Brand,
                    product.Screen.Size, product.Screen.Type, product.Screen.Touch,
                    product.Cpu.Series, product.Cpu.Cores, product.Cpu.Clock,
                    product.Ram,
                    product.Disk.Capacity, product.Disk.Type,
                    product.GraphicCard.Type, product.GraphicCard.Vram,
                    product.OperatingSystem,
                    product.DriverType
                };

                tableData.Add(row);
            }

            ConsoleTableBuilder
            .From(tableData)
            .WithFormat(ConsoleTableBuilderFormat.Alternative)
            .WithColumn("Id", "Producent", "Przekątna ekranu", "Typ matrycy", "Dotykowy ekran",
                        "Nazwa CPU", "Ilość rdzeni", "Prędkość taktowania(MHz)", "Pamięć RAM", "Pojemność dysku",
                        "Rodzaj dysku", "GPU", "Ilość VRAM", "Systemu operacyjny", "Napęd")
            .ExportAndWriteLine(TableAligntment.Left);
        }
コード例 #28
0
ファイル: Program.cs プロジェクト: kogratte/ProjectManagement
        private static void PrintNugetConsolidationInformations(List <Solution> solutions, CommandLineOption opts)
        {
            IEnumerable <Nuget> nugets = solutions.SelectMany(s => s.Nugets);

            if (!string.IsNullOrEmpty(opts.FilterDependency))
            {
                nugets = nugets.Where(n => n.Name.Equals(opts.FilterDependency));
            }

            nugets.Select(n => n.Name).Distinct().ToList().ForEach(n =>
            {
                DataTable table = new DataTable();

                table.Columns.Add("Nuget Name", typeof(string));
                table.Columns.Add("Target Framework", typeof(string));
                table.Columns.Add("Used versions", typeof(string));

                nugets.Select(_n => _n.TargetFramework).Distinct().ToList().ForEach(tv =>
                {
                    var usedNugetVersions = nugets.Where(_n => _n.Name == n && _n.TargetFramework == tv).Select(_n => _n.Version).Distinct().ToList();
                    if (usedNugetVersions.Any())
                    {
                        table.Rows.Add(n, tv, string.Join(", ", usedNugetVersions));
                    }
                });

                if (opts.Verbose)
                {
                    ConsoleTableBuilder.From(table).ExportAndWriteLine();
                    Console.WriteLine(Environment.NewLine);
                }
            });
        }
コード例 #29
0
        static void DisplayQuickNetworkResponse()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("EXPECTED");
            dt.Columns.Add("ACTUAL");
            dt.Columns.Add("PROBABILITY [%]");


            for (int l = 0; l < Y_validation.Length; l++)
            {
                int expectedResponse = Y_validation[l].ToList().IndexOf(Y_validation[l].Max());

                var    y = Validate(l);
                double actualMaxValue = y.Max();
                int    actualResponse = y.ToList().IndexOf(actualMaxValue);

                DataRow row = dt.NewRow();
                row[0] = (PID)expectedResponse;
                row[1] = (PID)actualResponse;
                row[2] = actualMaxValue;

                dt.Rows.Add(row);
            }

            ConsoleTableBuilder builder = ConsoleTableBuilder.From(dt);

            builder.ExportAndWrite();
        }
コード例 #30
0
ファイル: Program.cs プロジェクト: kogratte/ProjectManagement
        private static void PrintNugetUsageFor(List <Solution> solutions, CommandLineOption opts)
        {
            DataTable table = new DataTable();

            table.Columns.Add("Solution", typeof(string));
            table.Columns.Add("Nuget Name", typeof(string));
            table.Columns.Add("Version", typeof(string));
            table.Columns.Add("Target Framework", typeof(string));

            if (!string.IsNullOrEmpty(opts.NugetOutputFile))
            {
                File.Delete(opts.NugetOutputFile);
            }
            solutions.ForEach(solution =>
            {
                solution.Nugets.ForEach(nuget =>
                {
                    if (!string.IsNullOrEmpty(opts.NugetOutputFile))
                    {
                        File.AppendAllText(opts.NugetOutputFile, $"{solution.Name};{nuget.Name};{nuget.Version};{nuget.TargetFramework};{Environment.NewLine}");
                    }
                    table.Rows.Add(solution.Name, nuget.Name, nuget.Version, nuget.TargetFramework);
                });
            });

            if (opts.Verbose)
            {
                ConsoleTableBuilder.From(table).ExportAndWriteLine();
            }
        }
コード例 #31
0
        public void ConsoleTableTestFromExpressionManual()
        {
            var objects = new object[]
            {
                new{ FirstName = "Adam", LastName = "Abdelhamed" },
                new{ FirstName = "John", LastName = "Doe" },
            };

            var table = new ConsoleTableBuilder().FormatAsTable(objects, "FirstName LastName");
            table.WriteLine();

            Assert.IsTrue(table.Contains("FirstName"));
            Assert.IsTrue(table.Contains("LastName"));
            Assert.IsTrue(table.Contains("Adam"));
            Assert.IsTrue(table.Contains("Abdelhamed"));
            Assert.IsTrue(table.Contains("John"));
            Assert.IsTrue(table.Contains("Doe"));
        }
コード例 #32
0
        public void ConsoleTableBasic()
        {
            ConsoleTableBuilder builder = new ConsoleTableBuilder();

            var columns = new List<ConsoleString>() { new ConsoleString("NAME"), new ConsoleString("ADDRESS"), new ConsoleString("DESCRIPTION") };
            var rows = new List<List<ConsoleString>>()
            {
                new List<ConsoleString>(){ new ConsoleString("Adam Abdelhamed"), new ConsoleString("One Microsoft Way, Redmond WA 98052"), new ConsoleString("The author of PowerArgs, the world's greatest command line parser and invoker.  Hooray for PowerArgs!  We love PowerArgs so much cuz it is awesome and great.  Yay!!!!  In fact, PowerArgs is so fun that nothing in the entire universe is more fun.  ") },
                new List<ConsoleString>(){ new ConsoleString("Alicia Abdelhamed"), new ConsoleString("Two Microsoft Way, Redmond WA 98052"), new ConsoleString("The wife of the author of PowerArgs, the world's greatest command line parser and invoker.  Hooray for PowerArgs!") },
            };

            var output = builder.FormatAsTable(columns, rows);
            var outstr = output.ToString();

            var expected =
            @"
            NAME                ADDRESS                               DESCRIPTION
            Adam Abdelhamed     One Microsoft Way, Redmond WA 98052   The author of PowerArgs, the world's greatest command line parser and invoker.  Hooray for PowerArgs!  We love PowerArgs so much cuz it is awesome and great.  Yay!!!!  In fact, PowerArgs is so fun that nothing in the entire universe is more fun.
            Alicia Abdelhamed   Two Microsoft Way, Redmond WA 98052   The wife of the author of PowerArgs, the world's greatest command line parser and invoker.  Hooray for PowerArgs!
            ".TrimStart();

            Helpers.AssertAreEqualWithDiffInfo(expected.Replace("\r\n", "\n"), outstr.Replace("\r\n", "\n"));
        }
コード例 #33
0
        public void ConsoleTableTestMultiOptions()
        {
            ConsoleProvider.Current.BufferWidth = 160;
            ConsoleTableBuilder builder = new ConsoleTableBuilder();

            var columns = new List<ConsoleString>() { new ConsoleString("NAME"), new ConsoleString("ADDRESS"), new ConsoleString("DESCRIPTION") };
            var rows = new List<List<ConsoleString>>()
            {
                new List<ConsoleString>(){ new ConsoleString("Adam Abdelhamed"), new ConsoleString("One Microsoft Way, Redmond WA 98052"), new ConsoleString("The author of PowerArgs, the world's greatest command line parser and invoker.  Hooray for PowerArgs!  We love PowerArgs so much cuz it is awesome and great.  Yay!!!!  In fact, PowerArgs is so fun that nothing in the entire universe is more fun.  ") },
                new List<ConsoleString>(){ new ConsoleString("Alicia Abdelhamed"), new ConsoleString("Two Microsoft Way, Redmond WA 98052"), new ConsoleString("The wife of the author of PowerArgs, the world's greatest command line parser and invoker.  Hooray for PowerArgs!") },
            };

            var columnOverflowBehaviors = new List<ColumnOverflowBehavior>()
            {
                new TruncateOverflowBehavior(){ColumnWidth = 7},
                new SmartWrapOverflowBehavior(){DefineMaxWidthBasedOnConsoleWidth = false, MaxWidthBeforeWrapping = 15},
                new SmartWrapOverflowBehavior(),
            };

            var output = builder.FormatAsTable(columns, rows, rowPrefix: "", columnOverflowBehaviors: columnOverflowBehaviors);
            var outstr = output.ToString();

            var expected =
            @"
            NAME         ADDRESS           DESCRIPTION
            Adam...      One Microsoft     The author of PowerArgs, the world's greatest command line parser and invoker.  Hooray for PowerArgs!  We love PowerArgs so
             Way, Redmond      much cuz it is awesome and great.  Yay!!!!  In fact, PowerArgs is so fun that nothing in the entire universe is more fun.
             WA 98052
            Alic...      Two Microsoft     The wife of the author of PowerArgs, the world's greatest command line parser and invoker.  Hooray for PowerArgs!
             Way, Redmond
             WA 98052".TrimStart();

            Helpers.AssertAreEqualWithDiffInfo(expected.Replace("\r\n", "\n"), outstr.Replace("\r\n", "\n"));
        }
コード例 #34
0
ファイル: Grid-View.cs プロジェクト: adamabdelhamed/PowerArgs
        private void PaintInternal(ConsoleBitmap context)
        {
            if (this.Height < 5)
            {
                context.DrawString("Grid can't render in a space this small", 0, 0);
                return;
            }

            if (VisibleColumns.Count == 0)
            {
                context.DrawString(NoVisibleColumnsMessage.ToConsoleString(Application.Theme.H1Color), 0, 0);
                return;
            }

            List<ConsoleString> headers = new List<ConsoleString>();
            List<List<ConsoleString>> rows = new List<List<ConsoleString>>();
            List<ColumnOverflowBehavior> overflowBehaviors = new List<ColumnOverflowBehavior>();

            if (VisibleColumns.Where(c => c.WidthPercentage != 0).Count() == 0)
            {
                foreach (var col in VisibleColumns)
                {
                    col.WidthPercentage = 1.0 / VisibleColumns.Count;
                }
            }

            foreach (var header in VisibleColumns)
            {
                headers.Add(header.ColumnDisplayName);
                var colWidth = (int)(header.WidthPercentage * this.Width);

                if (header.OverflowBehavior is SmartWrapOverflowBehavior)
                {
                    (header.OverflowBehavior as SmartWrapOverflowBehavior).MaxWidthBeforeWrapping = colWidth;
                }
                else if (header.OverflowBehavior is TruncateOverflowBehavior)
                {
                    (header.OverflowBehavior as TruncateOverflowBehavior).ColumnWidth = colWidth;
                }

                overflowBehaviors.Add(header.OverflowBehavior);
            }

            int viewIndex = visibleRowOffset;
            foreach (var item in DataView.Items)
            {
                List<ConsoleString> row = new List<ConsoleString>();
                int columnIndex = 0;
                foreach (var col in VisibleColumns)
                {
                    var value = PropertyResolver(item, col.ColumnName.ToString());
                    var displayValue = value == null ? "<null>".ToConsoleString() : (value is ConsoleString ? (ConsoleString)value : value.ToString().ToConsoleString());

                    if (viewIndex == SelectedIndex)
                    {
                        if (this.SelectionMode == GridSelectionMode.Row || (this.SelectionMode == GridSelectionMode.Cell && columnIndex == selectedColumnIndex))
                        {
                            displayValue = new ConsoleString(displayValue.ToString(), this.Background, HasFocus ? Application.Theme.FocusColor : Application.Theme.SelectedUnfocusedColor);
                        }
                    }

                    row.Add(displayValue);
                    columnIndex++;
                }
                viewIndex++;
                rows.Add(row);
            }

            ConsoleTableBuilder builder = new ConsoleTableBuilder();
            ConsoleString table;
            #if PROFILING
            using (new TimeProfiler("Grid.FormatAsTable"))
            {
            #endif
                table = builder.FormatAsTable(headers, rows, RowPrefix.ToString(), overflowBehaviors, Gutter);
            #if PROFILING
            }
            #endif

            if (FilterText != null)
            {
                table = table.Highlight(FilterText, Application.Theme.HighlightContrastColor, Application.Theme.HighlightColor, StringComparison.InvariantCultureIgnoreCase);
            }

            if (DataView.IsViewComplete == false)
            {
                table += "Loading more rows...".ToConsoleString(Application.Theme.H1Color);
            }
            else if (DataView.IsViewEndOfData && DataView.Items.Count == 0)
            {
                table += NoDataMessage.ToConsoleString(Application.Theme.H1Color);
            }
            else if (DataView.IsViewEndOfData)
            {
                table += EndOfDataMessage.ToConsoleString(Application.Theme.H1Color);
            }
            else
            {
                table += "more data below".ToConsoleString(Application.Theme.H1Color);
            }
            context.DrawString(table, 0, 0);

            if (FilteringEnabled)
            {

            }
        }
コード例 #35
0
        /// <summary>
        /// Renders the table given a data context
        /// </summary>
        /// <param name="context">the data context</param>
        /// <returns>the console friendly table, as a ConsoleString</returns>
        public ConsoleString Evaluate(DocumentRendererContext context)
        {
            var eval = context.EvaluateExpression(this.EvalToken.Value);

            if(eval == null)
            {
                throw new DocumentRenderException("NullReference for '" + this.EvalToken.Value + "'", this.EvalToken);
            }
            else if(eval is IEnumerable == false)
            {
                throw new DocumentRenderException("'" + this.EvalToken.Value + "' is not enumerable", this.EvalToken);
            }

            IEnumerable collection = (IEnumerable)eval;

            List<ConsoleString> headers = new List<ConsoleString>();
            List<List<ConsoleString>> rows = new List<List<ConsoleString>>();
            List<ColumnOverflowBehavior> overflows = new List<ColumnOverflowBehavior>();

            for (int colIndex = 0; colIndex < Columns.Count; colIndex++ )
            {
                var col = Columns[colIndex];
                var colValue = col.Value;

                if (colValue.EndsWith("+"))
                {
                    colValue = colValue.Substring(0, colValue.Length - 1);
                    overflows.Add(new SmartWrapOverflowBehavior());
                    if(colIndex != Columns.Count-1)
                    {
                        throw new DocumentRenderException("The auto expand indicator '+' can only be used on the last column", col);
                    }
                }
                else
                {
                    overflows.Add(new GrowUnboundedOverflowBehavior());
                }

                if (colValue.Contains(">"))
                {
                    var newColName = colValue.Split('>')[1];
                    headers.Add(new ConsoleString(newColName, ConsoleColor.Yellow));
                }
                else
                {
                    headers.Add(new ConsoleString(colValue, ConsoleColor.Yellow));
                }
            }

            foreach(var element in collection)
            {
                if(element is CommandLineArgument && ((CommandLineArgument)element).OmitFromUsage)
                {
                    continue;
                }

                var row = new List<ConsoleString>();
                foreach (var col in Columns)
                {
                    string propName;
                    if (col.Value.Contains(">"))
                    {
                        propName = col.Value.Split('>')[0];
                    }
                    else
                    {
                        propName = col.Value;
                    }

                    if(propName.EndsWith("+"))
                    {
                        propName = propName.Substring(0, propName.Length - 1);
                    }

                    var propToGet = element.GetType().GetProperty(propName, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
                    if (propToGet == null) throw new DocumentRenderException("'" + propName + "' is not a valid property for type '" + element.GetType().FullName + "'", col);
                    var value = propToGet.GetValue(element, null);

                    ConsoleString valueString;

                    if(value != null)
                    {
                        valueString = new ConsoleString(value.ToString());
                        if (ShowDefaultValuesForArguments && element is CommandLineArgument && propToGet.Name == "Description" && ((CommandLineArgument)element).DefaultValue != null)
                        {
                            valueString+= new ConsoleString(" [Default='" + ((CommandLineArgument)element).DefaultValue.ToString() + "'] ", ConsoleColor.DarkGreen);
                        }
                    }
                    else
                    {
                        valueString = ConsoleString.Empty;
                    }
                    row.Add(valueString);
                }
                rows.Add(row);

                if(ShowPossibleValuesForArguments && element is CommandLineArgument && ((CommandLineArgument)element).IsEnum)
                {
                    foreach (var val in ((CommandLineArgument)element).EnumValuesAndDescriptions)
                    {
                        List<ConsoleString> possibilitiesRow = new List<ConsoleString>();
                        for (int i = 0; i < Columns.Count - 1; i++)
                        {
                            possibilitiesRow.Add(ConsoleString.Empty);
                        }
                        possibilitiesRow.Add(new ConsoleString(val, ConsoleColor.DarkGreen));
                        rows.Add(possibilitiesRow);
                    }
                }
            }

            string rowPrefix = "";
            for(int i = 0; i < indent; i++)
            {
                rowPrefix += " ";
            }

            ConsoleTableBuilder builder = new ConsoleTableBuilder();
            var tableText = builder.FormatAsTable(headers, rows, rowPrefix: rowPrefix, columnOverflowBehaviors: overflows);

            // remove the prefix from the first row
            tableText = tableText.Substring(indent);
            var tableTextStr = tableText.ToString();
            return tableText;
        }
コード例 #36
-1
ファイル: Init.cs プロジェクト: abbottdev/PowerArgs
        private static void InitImpl()
        {
            ArgPipelineObjectMapper.CurrentMapper = new JObjectArgPipelineMapper();

            PipelineOutputFormatter.RegisterFormatter(typeof(JObject), FuncPipelineOutputFormatter.Create((obj) =>
            {
                JObject jObj = (JObject)obj;
                ConsoleTableBuilder builder = new ConsoleTableBuilder();
                List<ConsoleString> headers = new List<ConsoleString>() { new ConsoleString("PROPERTY", ConsoleColor.Yellow), new ConsoleString("VALUE", ConsoleColor.Yellow) };
                List<List<ConsoleString>> rows = new List<List<ConsoleString>>();
                foreach (var prop in jObj.Properties())
                {
                    rows.Add(new List<ConsoleString>() { new ConsoleString(prop.Name, ConsoleColor.Gray), new ConsoleString("" + prop.Value, ConsoleColor.Green) });
                }

                var jObjRet = builder.FormatAsTable(headers, rows);
                jObjRet = new ConsoleString("Pipeline output of type JObject: \n") + jObjRet;
                return jObjRet;
            }));
        }