Пример #1
0
        /**
         * Run
         */
        public bool Run(NetworkStream stream, WriteManager writeManager, string input)
        {
            try
            {
                if (!input.StartsWith("/"))
                {
                    return(writeManager.Run(stream, Wrapper.Type.Message, input));
                }

                input = input.ToLower();
                foreach (DictionaryEntry entry in Table)
                {
                    if (!((string[])entry.Key).Any(alias => Regex.Split(input, @"\s+")[0].Equals(alias)))
                    {
                        continue;
                    }

                    if (writeManager.Run(stream, (Wrapper.Type)entry.Value, input))
                    {
                        return(true);
                    }

                    Console.Out.WriteLineAsync("Invalid Arguments");
                    return(false);
                }
                Console.Out.WriteLineAsync("Invalid Command");
                return(false);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Пример #2
0
        private void Percentiles(List <OutcomeSummary> list, InputData input)
        {
            WriteManager.Write($" * Percentile Outcomes:");

            var outcomeInvestmentAmount = new List <Narvalo.Money>();

            foreach (var outcome in list)
            {
                outcomeInvestmentAmount.Add(outcome.Outcomes.Last().NewPortfolio.InvestmentAmount);
            }
            outcomeInvestmentAmount.Sort();
            var outcomesAsDecimal = new List <decimal>();

            foreach (var outcome in outcomeInvestmentAmount)
            {
                outcomesAsDecimal.Add(outcome.Amount);
            }

            WriteManager.Write($"   - Min: {outcomeInvestmentAmount.First().ToDecimal().MakeReadable()}");

            foreach (var item in new double[] { .001, .01, .03, .05, .08, .10, .25, .40, .50, .60, .75, .85, .95, .99, .999 })
            {
                var value = $"000{item * 100}";
                WriteManager.Write($"   - {value.Substring(value.Length-4)}%'tile: {outcomesAsDecimal.ToPercentile(item).MakeReadable()}");
            }
            WriteManager.Write($"   - Max: {outcomeInvestmentAmount.Last().ToDecimal().MakeReadable()}");
        }
Пример #3
0
        public void ParseAndDispatch(string[] args)
        {
            var pArgs = GenericArgsParser.Parse(args);

            if (!string.IsNullOrEmpty(pArgs.ErrorMessage))
            {
                WriteManager.Write(pArgs.ErrorMessage);
                return;
            }
            switch (pArgs.DispatchMode)
            {
            case DispatchModes.Test:
                new DispatchTest().Execute(pArgs);
                break;

            case DispatchModes.Input:
                new DispatchInputData().Execute(pArgs);
                break;

            case DispatchModes.Help:
                new DispatchHelp().Execute(pArgs);
                break;

            case DispatchModes.Create:
                new DispatchCreateFile().Execute(pArgs);
                break;

            //TODO Help.
            default:
                WriteManager.Write($"Invalid Mode: {pArgs.DispatchMode}");
                return;
            }
        }
Пример #4
0
        public override void Report(List <OutcomeSummary> list, InputData input)
        {
            //I'm imagining a time where an external program like a website call the exe and wants only this output...
            WriteManager.Writer = WriterToResetTo;
            var text = CreateGiantCsv(list, input);

            WriteManager.Write(text);
        }
Пример #5
0
 public override void Report(List <OutcomeSummary> list, InputData input)
 {
     foreach (var item in CreateCsvReport(list, input))
     {
         WriteManager.Write($"Writing data to {item.Key}");
         System.IO.File.WriteAllText(item.Key, item.Value);
     }
 }
Пример #6
0
        public void TestWebWriterSuccess()
        {
            _mockConfig.Setup(x => x.GetWriter()).Returns(new HellowWorld.Web.WebWriter());
            WriteManager mgr = new WriteManager(_mockConfig.Object);
            var          msg = mgr.write(HelloWorld);

            Assert.AreEqual(msg, HelloWorld);
        }
Пример #7
0
        static void Main(string[] args)
        {
            var factory = new WriterFactory();

            IWriteManager helloWorldWriter = new WriteManager(factory);

            helloWorldWriter.write("Hello World");

            Console.ReadLine();
        }
Пример #8
0
        protected void Bingtop10write()
        {
            DataTable top10 = WriteManager.top10write();

            if (top10 != null)
            {
                writeView.DataSource = top10;
                writeView.DataBind();
            }
        }
Пример #9
0
        public override void Report(List <OutcomeSummary> list, InputData input)
        {
            var filename = $"Execution_{Guid.NewGuid()}.csv";
            var path     = System.IO.Path.GetTempPath();
            var fullPath = path + filename;

            var text = CreateGiantCsv(list, input);

            WriteManager.Write($"Writing data to {fullPath}");
            System.IO.File.WriteAllText(fullPath, text);
        }
Пример #10
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            Button bt = (Button)sender;

            if (Session["user_name"] != null)
            {
                try
                {
                    Write write = new Write();
                    write.Wr_user_id1 = int.Parse(Session["user_id"].ToString());
                    write.Wri_name1   = txtTitle1.Text.Trim();
                    write.Wri_mess1   = txtContent.Text;

                    //write.Wri_iamge1 = @"~/Write_image/" + FileUpload_img.PostedFile.FileName;
                    write.Wri_time1 = DateTime.Now;

                    if (FileUpload_img.HasFile)
                    {
                        string filePathImg     = FileUpload_img.PostedFile.FileName;
                        string fileNameImg     = filePathImg.Substring(filePathImg.LastIndexOf("\\") + 1);
                        string serverpathImg   = Server.MapPath(@"~/Write_image/") + fileNameImg;
                        string relativepathImg = @"~/Write_image/" + fileNameImg;
                        FileUpload_img.PostedFile.SaveAs(serverpathImg);
                        write.Wri_image1 = relativepathImg;
                    }
                    else
                    {
                        Page.ClientScript.RegisterClientScriptBlock(typeof(Object), "alert", "<script>alert('请添加截屏照片!');</script>");
                        return;
                    }


                    if (WriteManager.addwri(write) == 1)
                    {
                        txtContent.Text = "";
                        txtTitle1.Text  = "";

                        Page.ClientScript.RegisterClientScriptBlock(typeof(Object), "alert", "<script>alert('发表成功');</script>");
                    }
                    else
                    {
                        Page.ClientScript.RegisterClientScriptBlock(typeof(Object), "alert", "<script>alert('发表失败');</script>");
                    }
                }
                catch (Exception ex)
                {
                    Response.Write("错误原因:" + ex.Message);
                }
            }
            else
            {
                Page.ClientScript.RegisterClientScriptBlock(typeof(Object), "alert", "<script>alert('请先登录!');</script>");
            }
        }
Пример #11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            CKFinder.FileBrowser fileBrowser = new CKFinder.FileBrowser();
            fileBrowser.BasePath = "../ckfinder/";  //设置CKFinder的基路径
            fileBrowser.SetupCKEditor(txtContent);
            Bindwrite();

            BingWW();
            Bingshoucang();
            panel_a.Visible = true;
            ViewState["id"] = Convert.ToInt32(Request.QueryString["id"]);
            Choose();
            string wriname;

            if (!IsPostBack)
            {
                try
                {
                    if (Request.QueryString["wri_name"] != null)
                    {
                        wriname = Request.QueryString["wri_name"].ToString();
                        WriteManager.delete(wriname);
                        BingWW();
                        Bindwrite();
                        Page.ClientScript.RegisterClientScriptBlock(typeof(Object), "alert", "<script>alert('删除成功!');</script>");
                    }
                }
                catch (Exception ex)
                {
                    Response.Write("错误原因:" + ex.Message);
                }
            }
            string wkid;

            if (!IsPostBack)
            {
                try
                {
                    if (Request.QueryString["wk_id"] != null)
                    {
                        wkid = Request.QueryString["wk_id"].ToString();
                        Write_KeepManager.delete(wkid);
                        Bingshoucang();
                        Page.ClientScript.RegisterClientScriptBlock(typeof(Object), "alert", "<script>alert('删除成功!');</script>");
                    }
                }
                catch (Exception ex)
                {
                    Response.Write("错误原因:" + ex.Message);
                }
            }
        }
Пример #12
0
        public void Report(List <OutcomeSummary> list, InputData input)
        {
            var percentage = input.PercentageOfInitialPortolioIsClose * 100;

            WriteManager.Write($" * Simulations: {list.Count}");
            WriteManager.Write($" * Failures: {list.Count(a => a.IsFail)}");
            WriteManager.Write($" * Close to Failures, but not failed ({percentage}% or less initial portfolio): {list.Count(a => a.IsClose && !a.IsFail)}");
            WriteManager.Write($" * Failure Probability: {((decimal)((decimal)list.Count(a => a.IsFail) / (decimal)list.Count) * 100M).MakeReadable()}%");

            Percentiles(list, input);

            PercentageDropFromInitialInvestment(list, input);
        }
Пример #13
0
        public void Execute(GenericArgsParser args)
        {
            var input = ArgsToInputData(args);

            var method        = args.EvaluationMethod;
            var defaultMethod = "AllYears";

            if (method == null || !Simulation.ContainsKey(method))
            {
                WriteManager.Write($"Invalid evaluation method '{method}'.  Replacing with '{defaultMethod}'");
                method = defaultMethod;
            }
            Simulation[method].Mode = args.Mode;
            Simulation[method].ExecuteSimulate(input);
        }
Пример #14
0
        public static InputData FromFileSafe(string path, InputData defaultValue)
        {
            InputData data;

            if (!File.Exists(path))
            {
                WriteManager.Write($"Unable to find '{path}'.  Using default values.");
                data = defaultValue;
            }
            else
            {
                data = FromString(File.ReadAllText(path));
            }

            return(data);
        }
Пример #15
0
 /**
  * Initialize method which will create the socket
  */
 private void Initialize(string ip, int port)
 {
     IsInitialized = false;
     try
     {
         ReadManager.Initialize(ReadHandlers);
         WriteManager.Initialize(WriteHandlers);
         InputManager.Initialize(InputInfos);
         Socket.Connect(ip, port);
         Stream        = Socket.GetStream();
         IsInitialized = true;
     }
     catch (Exception e)
     {
         Console.Out.WriteLineAsync(e.ToString());
     }
 }
Пример #16
0
        public override async Task <WriteDataItemsResult> WriteDataItems(string group, IList <DataItemValue> values, Duration?timeout)
        {
            if (!await TryConnect() || connection == null)
            {
                var failed = values.Select(div => new FailedDataItemWrite(div.ID, "No connection to server")).ToArray();
                return(WriteDataItemsResult.Failure(failed));
            }

            var writeMan = new WriteManager <VariableValue, VariableError>(values, request => {
                if (mapId2Info.ContainsKey(request.ID))
                {
                    ItemInfo info = mapId2Info[request.ID];
                    return(VariableValue.Make(info.VarRef, request.Value));
                }
                else
                {
                    throw new Exception("No Address defined");
                }
            });

            try {
                var         dataItemsToWrite = writeMan.GetRefsList();
                WriteResult res = await connection.WriteVariablesSyncIgnoreMissing(dataItemsToWrite, timeout);

                if (!res.IsOK())
                {
                    writeMan.AddWriteErrors(res.FailedVariables, failedVar => {
                        VariableRef v = failedVar.Variable;
                        int idx       = dataItemsToWrite.FindIndexOrThrow(vv => vv.Variable == v);
                        string id     = writeMan.GetWriteRequest(idx).ID;
                        return(new FailedDataItemWrite(id, failedVar.Error));
                    });
                }
            }
            catch (Exception exp) {
                Task      ignored = CloseConnection();
                Exception e       = exp.GetBaseException() ?? exp;
                string    msg     = $"Write exception: {e.Message}";
                LogWarn("WriteExcept", msg, details: e.ToString());
                var failed = values.Select(div => new FailedDataItemWrite(div.ID, msg)).ToArray();
                return(WriteDataItemsResult.Failure(failed));
            }

            return(writeMan.GetWriteResult());
        }
Пример #17
0
 protected void BingWW()
 {
     if (Session["user_name"] != null)
     {
         try
         {
             int       user_id = int.Parse(Session["user_id"].ToString());
             DataTable ui      = WriteManager.wdwrite(user_id);
             if (ui != null)
             {
                 ListView2.DataSource = ui;
                 ListView2.DataBind();
             }
         }
         catch (Exception ex)
         {
             Response.Write("错误原因:" + ex.Message);
         }
     }
 }
Пример #18
0
        /**
         * Broadcast to all connected clients
         */
        public void Broadcast(string msg, bool flag = false, Client client = null)
        {
            if (flag && client == null)
            {
                return; // Add some security for NullReferenceException
            }
            foreach (var item in ClientList)
            {
                var broadcastClient = item.Value;
                if (broadcastClient == client)
                {
                    continue; // Stop if it is the same socket
                }
                if (broadcastClient.Lobby != null)
                {
                    continue; // Stop if the client is in a Lobby
                }
                NetworkStream broadcastStream;
                try
                {
                    broadcastStream = broadcastClient.Socket.GetStream();
                }
                catch (InvalidOperationException)
                {
                    // Remove client if we can't get its stream
                    PendingDisconnection.Add(broadcastClient);
                    continue;
                }

                WriteManager.Run(broadcastStream, Wrapper.Type.Message,
                                 flag
                        ? client.Info.Name + " says : " + msg
                        : msg);
            }

            // Check disconnection after all broadcast
            CheckDisconnection();
        }
Пример #19
0
        /**
         * Initiliaze listener
         */
        private bool Initialize(int port = DefaultServerPort)
        {
            IsInitialized = false;
            try
            {
                ReadManager.Initialize(ReadHandlers);
                WriteManager.Initialize(WriteHandlers);

                Listener = new TcpListener(IPAddress.Any, port);

                ClientList = new Dictionary <int, Client>();
                LobbyList  = new List <Lobby>();

                Listener.Start();
                IsInitialized = true;
                return(true);
            }
            catch (Exception e)
            {
                Console.Out.WriteLineAsync(e.ToString());
                return(false);
            }
        }
Пример #20
0
        protected void Page_Load(object sender, EventArgs e)
        {
            BindView();
            string wriname;

            if (!IsPostBack)
            {
                try
                {
                    if (Request.QueryString["wri_name"] != null)
                    {
                        wriname = Request.QueryString["wri_name"].ToString();
                        WriteManager.delete(wriname);
                        BindView();
                        Page.ClientScript.RegisterClientScriptBlock(typeof(Object), "alert", "<script>alert('删除成功!');</script>");
                    }
                }
                catch (Exception ex)
                {
                    Response.Write("错误原因:" + ex.Message);
                }
            }
        }
Пример #21
0
        public void Report(List <OutcomeSummary> list, InputData input)
        {
            foreach (var summary in list)
            {
                WriteManager.Write($"***********Run # {summary.RowNumber}***********");
                WriteManager.Write("-----");
                WriteManager.Write($"Started: {summary.PortolioStartTime.PrettyDate()} ");
                WriteManager.Write($"- Is Failure: {summary.IsFail}");
                WriteManager.Write($"- Is Close: {summary.IsClose}");
                WriteManager.Write($"- Worst Month: {summary.WorstMonth}");
                WriteManager.Write($"- Worst Amount: {summary.WorstAmount.MakeReadable()}");
                WriteManager.Write($"- Total Returns By Category: {summary.TotalReturnsByCategory.DictToString()}");
                WriteManager.Write("-----");

                var period = 0;
                foreach (var item in summary.Outcomes)
                {
                    period++;
                    WriteManager.Write($"Period: {period} - {item}");
                }
                WriteManager.Write($"***********End of Run # {summary.RowNumber}***********");
            }
        }
Пример #22
0
        private void PercentageDropFromInitialInvestment(List <OutcomeSummary> list, InputData input)
        {
            WriteManager.Write($" * % of portfolios that fell between:");
            var initAmt = input.InitialAmount;

            var tenPercentOfInitAmt = initAmt / 10;

            var outcomeInvestmentAmount = new List <decimal>();

            //var lowestValue = initAmt;
            foreach (var outcomeSummary in list)
            {
                //foreach (var outcome in outcomeSummary.Outcomes)
                //{
                //    var checkedValue = outcome.NewPortfolio.InvestmentAmount;
                //    if (lowestValue>checkedValue)
                //    {
                //        lowestValue = checkedValue;
                //    }

                //}
                outcomeInvestmentAmount.Add(outcomeSummary.WorstAmount);
                //lowestValue = initAmt;
            }

            WriteManager.Write($"  - Portfolios that fell between 0-10% of initial investment: {PercentageDropCalculation(outcomeInvestmentAmount, decimal.MinValue, tenPercentOfInitAmt)}");

            foreach (var item in new decimal[] { 10, 20, 30, 40, 50, 60, 70, 80 })
            {
                var dec = .1M * item;

                WriteManager.Write($"  - Portfolios that fell between {item}-{item+10}%  of initial investment: {PercentageDropCalculation(outcomeInvestmentAmount, dec * tenPercentOfInitAmt, (dec+1) * tenPercentOfInitAmt)}");
            }

            WriteManager.Write($"  - Portfolios that fell between 90-100% of initial investment: {PercentageDropCalculation(outcomeInvestmentAmount, tenPercentOfInitAmt * 9, decimal.MaxValue)}");
        }
Пример #23
0
 public override void PrintSimulationSpecificDetails(List <OutcomeSummary> list)
 {
     WriteManager.Write($" * Failure Details: \n  - {string.Join("\n  - ", list.Where(a => a.IsFail).OrderBy(b => b.IsCloseFirstMonth).Select(b => $" Initial Date: {b.PortolioStartTime.PrettyDate()}, First Close Month: {b.IsCloseFirstMonth}, First Failure Month: {b.FirstFailureMonth}, Worst Month: {b.WorstMonth}, Worst Amount: {b.WorstAmount.MakeReadable()}").ToList())}");
     WriteManager.Write($" * Close Details: \n  - {string.Join("\n  - ", list.Where(a => a.IsClose && !a.IsFail).OrderBy(b => b.IsCloseFirstMonth).Select(b => $" Initial Date: {b.PortolioStartTime.PrettyDate()}, First Close Month: {b.IsCloseFirstMonth}, Worst Month: {b.WorstMonth}, Worst Amount: {b.WorstAmount.MakeReadable()}").ToList())}");
     WriteManager.Write($" * Top 10 Worst Details: \n  - {string.Join("\n  - ", list.OrderBy(a => a.WorstAmount).Take(10).Select(b => $" Initial Date: {b.PortolioStartTime.PrettyDate()}, Worst Month: {b.WorstMonth}, Worst Amount: {b.WorstAmount.MakeReadable()}").ToList())}");
 }
Пример #24
0
 public void Write(string write)
 {
     WriteManager.Write(write);
 }
Пример #25
0
 protected void BindView()
 {
     topicView.DataSource = WriteManager.allwrite();
     topicView.DataBind();
 }
Пример #26
0
 protected void BindView()
 {
     Repeater1.DataSource = WriteManager.Swirid(int.Parse(Request.QueryString["wri_id"]));
     Repeater1.DataBind();
 }
Пример #27
0
 //protected void Bindhuati()
 //{
 //    huatiView.DataSource = TopicManager.alltop();
 //    huatiView.DataBind();
 //}
 protected void Bindwrite()
 {
     writeView.DataSource = WriteManager.allwri();
     writeView.DataBind();
 }
Пример #28
0
        public void Execute(GenericArgsParser args)
        {
            var input = new InputData();

            input.IncomeAndExpenses.Add(
                new ExpenseOffset()
            {
                OffsetAmount = (((InputData.InitialAmt * .043M) / 12) * -1).AsMoney()
            });


            input.IncomeAndExpenses.Add(new ExpenseOffset()
            {
                StartMonth   = 380,
                OffsetAmount = 1099.AsMoney(),
            });

            input.IncomeAndExpenses.Add(new ExpenseOffset()
            {
                StartMonth   = 40,
                EndMonth     = 200,
                OffsetAmount = 800.AsMoney(),
            });

            input.FilePath = "";
            input.Adjustments.Clear();

            input.AdjustmentTranslation = new List <AdjustmentTranslationData>()
            {
                new AdjustmentTranslationData()
                {
                    Type = "AdjustByGlide",
                    NameToStringValue = new Dictionary <string, List <string> >
                    {
                        { "from", new List <string>()
                          {
                              "Equity"
                          } },
                        { "to", new List <string>()
                          {
                              "Bond"
                          } },
                    },
                    NameToDecimalValue = new Dictionary <string, decimal>()
                    {
                        { "glide", 5m / 12 }
                    }
                },

                new AdjustmentTranslationData()
                {
                    Type = "AdjustByMaxValues",
                    NameToDecimalValue = new Dictionary <string, decimal>()
                    {
                        { "Equity", 75 }
                    }
                },
                new AdjustmentTranslationData()
                {
                    Type = "AdjustByMinValues",
                    NameToDecimalValue = new Dictionary <string, decimal>()
                    {
                        { "Bond", 5 },
                        { "Equity", 20 },
                        { "Gold", 15 },
                    }
                },
                new AdjustmentTranslationData()
                {
                    Type = "AdjustByCapeRatio",
                    NameToStringValue = new Dictionary <string, List <string> >
                    {
                        { "from", new List <string>()
                          {
                              "Bond"
                          } },
                        { "to", new List <string>()
                          {
                              "Equity"
                          } },
                    },
                    NameToDecimalValue = new Dictionary <string, decimal>()
                    {
                        { "max_cape_before_action", 20 },
                        { "percentage_to_adjust_by", .2M },
                        { "amount_of_cape_excess_to_increase_adjustment", 10M }
                    }
                }
            };

            Input.ToFile(input, args.InputFilePath);

            WriteManager.Write("Execution Completed.");
        }