public void Initialize() { // Finding GameObjects m_object_player = GameObject.Find("Player"); m_object_helpers = GameObject.Find ("Helpers"); m_object_duckfield = GameObject.Find("Duckfield"); m_object_audio = GameObject.Find("Audio"); m_object_cameraman = GameObject.Find("Main Camera"); // Finding Components m_collision_prober = m_object_player.GetComponent<CollisionProber>(); m_scoring = m_object_player.GetComponent<Scoring>(); m_health = m_object_player.GetComponent<Health>(); m_walker = m_object_player.GetComponent<Walker>(); m_jumper = m_object_player.GetComponent<Jumper>(); m_time_helper = m_object_helpers.GetComponent<TimeHelper>(); m_screen_helper = m_object_helpers.GetComponent<ScreenHelper>(); m_duckfield = m_object_duckfield.GetComponent<DuckField>(); m_duckization = m_object_audio.GetComponent<DuckizationController>(); m_cameraman = m_object_cameraman.GetComponent<Cameraman>(); m_ig_menu = m_object_cameraman.GetComponent<IgMenu>(); }
internal static List <SCHElement> ParseByteArray(Stream stream) { List <SCHElement> Elements = new List <SCHElement>(); unchecked { while (stream.Position != stream.Length) { //===== Reading metadata ===== SCHMetadata metadata = new SCHMetadata(); //Name UInt16 nameLen = BitConverter.ToUInt16(ReadToBuffer(stream, nameBlockLength), 0); metadata.Name = Encoding.UTF8.GetString(ReadToBuffer(stream, nameLen)); //Autor byte autorLen = ReadToBuffer(stream, autorBlockLength)[0]; metadata.Autor = Encoding.UTF8.GetString(ReadToBuffer(stream, autorLen)); //Autor UInt16 descrLen = BitConverter.ToUInt16(ReadToBuffer(stream, descrBlockLength), 0); metadata.Description = Encoding.UTF8.GetString(ReadToBuffer(stream, descrLen)); //Creation date metadata.CreationDate = TimeHelper.UnixTimestampToDateTime( BitConverter.ToDouble(ReadToBuffer(stream, dateTimeBlockLength), 0)); //===== Reading data ===== SCHMData data = new SCHMData(); //Action type data.ActionType = (ActionType)ReadToBuffer(stream, autorBlockLength)[0]; //Action data UInt16 actionDataLen = BitConverter.ToUInt16(ReadToBuffer(stream, actionDataBlockLength), 0); data.ActionData = ReadToBuffer(stream, actionDataLen); if (data.ActionType == ActionType.CSharpCode) { data._cSharpData = new SCHMData.CSharpData(data.ActionData); } //Command type data.CommandType = (CommandType)ReadToBuffer(stream, autorBlockLength)[0]; if (data.CommandType == CommandType.OneTime) { //One time date data.OneTimeDate = TimeHelper.UnixTimestampToDateTime( BitConverter.ToDouble(ReadToBuffer(stream, dateTimeBlockLength), 0)); } else { //RepeatableType data.RepeatableType = (RepeatableType)ReadToBuffer(stream, autorBlockLength)[0]; if (data.RepeatableType == RepeatableType.Monotonous) { //Monotonous Start Time data.MonotonousStartTime = TimeHelper.UnixTimestampToDateTime( BitConverter.ToDouble(ReadToBuffer(stream, dateTimeBlockLength), 0)); //Monotonous Period data.MonotonousPeriod = BitConverter.ToUInt32(ReadToBuffer(stream, periodBlockLength), 0); //Monotonous Repeat Count data.MonotonousRepeatCount = BitConverter.ToUInt16(ReadToBuffer(stream, countBlockLength), 0); data.ProceedMonotonous(); } else { //Specific Dates Count UInt16 count = BitConverter.ToUInt16(ReadToBuffer(stream, countBlockLength), 0); List <DateTime> dates = new List <DateTime>(); for (UInt16 i = 0; i < count; i++) { var date = TimeHelper.UnixTimestampToDateTime(BitConverter.ToDouble(ReadToBuffer(stream, dateTimeBlockLength), 0)); if (DateTime.Now < date) { dates.Add(date); } } data.SpecificDates = dates; } } if (data.ActionData != null && data.ActionData.Length != 0) { Elements.Add(new SCHElement() { Data = data, Metadata = metadata }); } } } return(Elements); }
public bool SaveSettingsToFile() // TestingForm oTestingForm) { bool bRet = false; string sFile = string.Empty; string sConnectionSettings = string.Empty; //SetDataFromForm(oTestingForm); if (UserIoHelper.PickSaveFileToFolder(FormDataFilePath, "Connection Settings " + TimeHelper.NowMashup() + ".xml", ref sFile, "XML files (*.xml)|*.xml")) { sConnectionSettings = SerialHelper.SerializeObjectToString <TestSettingsData>(SettingsData); if (sConnectionSettings != string.Empty) { try { System.IO.File.WriteAllText(sFile, sConnectionSettings); bRet = true; } catch (Exception ex) { MessageBox.Show(ex.Message, "Error Saving File"); } } } return(bRet); }
private void EnterStory(NPC_StoryConfig story) { Debug.Log("Lizzy--当前任务ID" + story.taskId + "---" + story.description); _curLizzyTask = story; _lizzyAudioController.PlaySound(story.audioId); _lizzyController.SetTargetPoint(story.targetPos); _taskStartTime = TimeHelper.GetCurrentRealTimestamp(); if (story.audioId > 0) { _audioWaitTime = _lizzyAudioController.GetCurAudioLength(story.audioId); } else { _audioWaitTime = 0f; } switch (_lizzyStoryProcess.curTaskID) { case 1001: //出现 //FinishCurTaskImmediately(1007); //test //_isStartDetection = true; //_lizzyController.SetCanSkipStep(false); //_lizzyController.SetState(LizzyController.STATE.RUN); //FinishCurTask(); //test break; case 1002: //说话:快帮帮我们!我们需要帮助! _isStartTimer = true; //FinishCurTask(); //test break; case 1003: //说话:你到底在想些什么? _isStartTimer = true; //FinishCurTask(); //test break; case 1004: //说话:好我知道! _isStartTimer = true; //FinishCurTask(); //test break; case 1005: //逃跑 _lizzy.transform.position = new Vector3(-0.74f, 80.61f, 36.32f); //_lizzyController.SetCanSkipStep(false); _isStartDetection = true; _lizzyController.SetState(LizzyController.STATE.IDLE); //FinishCurTask(); //test break; case 1006: //陷入困境 _isStartDetection = true; _lizzyController.SetCanSkipStep(false); _lizzyController.SetState(LizzyController.STATE.RUN); break; case 1007: //看到玩家后,说话:啊呃呃,救我…救我出这里! FinishCurTask(); break; case 1008: //说话:谁..你是谁?…噢是你!对不起不是我的错。George...! FinishCurTask(); break; case 1009: //(哭泣道)…我不想死…至少不要在今天… TaskStepManagaer.Instance.FinishCurTaskImmediately(); FinishCurTask(); //_isStartDetection = true; break; case 1010: //如果玩家走开不救,:不…不要…不要留我在这里等死!求求你!!!(Lizzy剧情结束) _isStartDetection = true; _lizzyController.SetCanSkipStep(false); _lizzyController.SetState(LizzyController.STATE.RUN); //if (_isRescued) //救了就立即跳到下一步 //{ // FinishCurTaskImmediately(); //} break; case 1011: //如果被救,:谢谢你救我!对于之前发生的事情,我很抱歉,因为我太害怕了! _lizzyController.SetState(LizzyController.STATE.DEATH); TaskStepManagaer.Instance.FinishCurTaskImmediately(); //FinishCurTask(); break; case 1012: //如果被救,:谢谢你救我!对于之前发生的事情,我很抱歉,因为我太害怕了! FinishCurTask(); break; case 1013: //:不管怎么样…我知道有条路可以带你到顶楼。跟我来! FinishCurTask(); break; case 1014: //带领玩家走 _lizzyController.SetCanSkipStep(true); _lizzyController.SetState(LizzyController.STATE.WALK); TaskStepManagaer.Instance.FinishCurTaskImmediately(); //FinishCurTask(); break; case 1015: //搬橱柜,玩家帮忙 _isStartDetection = true; _lizzyController.SetState(LizzyController.STATE.IDLE); //FinishCurTask(); break; case 1016: //“这个通道直达那边的楼梯,通过楼梯到上一层,那里有...” FinishCurTask(); break; case 1017: //被攻击,“阿呃呃” _lizzyController.SetState(LizzyController.STATE.DEATH); break; case 1018: //技能动作,被攻击 FinishCurTask(); break; case 1019: //躺在地上,奄奄一息 //_lizzyController.SetState(LizzyController.STATE.LAY_DOWN); FinishCurTask(); break; case 1020: //打败敌人后,“咳咳…我想我活不了了。救救Rick…” FinishCurTask(); break; case 1021: //咳嗽,吐血 FinishCurTask(); break; case 1022: //“谢谢你…还有..对不…起” FinishCurTask(); break; case 1023: //极乐 _lizzyController.SetState(LizzyController.STATE.DEATH); break; } }
/// <summary> /// 取整点及头尾有效数据 /// </summary> /// <param name="tbNew"></param> /// <returns></returns> public DataTable ChangeData(DataTable tbNew, int dura_min) { int scale = 1; if (dura_min > 60) { dura_min = 60; } if (dura_min < 10) { dura_min = 10; } scale = 60 / dura_min; DataTable tbOld = new DataTable(); try { tbOld = tbNew.Clone(); tbOld.PrimaryKey = null; tbOld.Columns["ID_RealTimeUsage"].DataType = typeof(string);//指定Age为Int类型 if (tbNew.Rows.Count > 0) { for (int i = 0; i < tbNew.Rows.Count; i++) { if (i == 0) { tbOld.Rows.Add(tbNew.Rows[i].ItemArray); } else if (i == tbNew.Rows.Count - 1 && tbNew.Rows.Count > 2) { tbOld.Rows.Add(tbNew.Rows[i].ItemArray); int count = tbOld.Rows.Count - 1; tbOld.Rows[count][2] = scale * (Convert.ToInt32(tbOld.Rows[count][1]) - Convert.ToInt32(tbOld.Rows[count - 1][1])); continue; } else if (Convert.ToInt64(tbNew.Rows[i][0]) >= Convert.ToInt64(tbOld.Rows[tbOld.Rows.Count - 1][0]) + (long)dura_min * 60 * 1000) { tbOld.Rows.Add(tbNew.Rows[i].ItemArray); int count = tbOld.Rows.Count - 1; tbOld.Rows[count][2] = scale * (Convert.ToInt32(tbOld.Rows[count][1]) - Convert.ToInt32(tbOld.Rows[count - 1][1])); continue; } } } for (int i = 0; i < tbOld.Rows.Count; i++) { //转换时间格式 tbOld.Rows[i][0] = TimeHelper.GetStringToDateTime((tbOld.Rows[i][0].ToString())); tbOld.Rows[i][2] = Convert.ToInt32(tbOld.Rows[i][2]) < 0 ? 0 : (Convert.ToInt32(tbOld.Rows[i][2]) / 2); } } catch (Exception ex) { logger.Error(ex.Message); } return(tbOld); }
/// <summary> // 导出至Excel. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ExportToExceltoolStripMenuItem_Click(object sender, EventArgs e) { DataGridViewRowCollection drRows = this.dgv.Rows; if (drRows.Count == 0) { return; } //1. 先确定 image path if (CmdHelper.ifExistsTheProcessByName("excel") || CmdHelper.ifExistsTheProcessByName("et")) { Tools.FrmPrompt frmPrompt = new Tools.FrmPrompt("excel.exe|et.exe"); frmPrompt.ShowDialog(); } //2. 打开Excel //先获取时间字符串 string currTimeStr = TimeHelper.getCurrentTimeStr(); string xlsFileName = "成衣成本汇总_" + currTimeStr + ".xls"; string srcFilePath = Application.StartupPath + "\\成本汇总\\ProductsCostSummaryTemplate.xls"; string destDir = Application.StartupPath + "\\成本汇总\\"; string destFileName = xlsFileName; CmdHelper.copyFileToDestDirWithNewFileName(srcFilePath, destDir, destFileName); //目的文件名为: destFilePath = destDir + xlsFileName; MyExcel myExcel = new MyExcel(destFilePath); myExcel.open(true); Usual_Excel_Helper uEHelper = new Usual_Excel_Helper(myExcel.getFirstWorkSheetAfterOpen()); for (int index = 0; index <= drRows.Count - 1; index++) { DataGridViewRow currRow = drRows[index]; string product_name = currRow.Cells["Product_Name"].Value.ToString(); uEHelper.setSpecificCellValue("A" + (2 + index).ToString(), product_name); //(drRow.Cells["product_name"] uEHelper.setSpecificCellValue("B" + (2 + index).ToString(), currRow.Cells["total_man_hours"].Value.ToString()); uEHelper.setSpecificCellValue("C" + (2 + index).ToString(), currRow.Cells["total_labour_cost"].Value.ToString()); uEHelper.setSpecificCellValue("D" + (2 + index).ToString(), currRow.Cells["supplier"].Value.ToString()); uEHelper.setSpecificCellValue("E" + (2 + index).ToString(), currRow.Cells["latest_update_time"].Value.ToString()); //picture //保存此图片 //Image image = ((Image)(currRow.Cells["picture"].Value)); byte[] pictureByteArray = (byte[])currRow.Cells["picture"].Value; Image image = PictureHelper.ReturnPhoto(pictureByteArray); string picPath = string.Format(@"{0}\{1}.jpg", destDir, product_name); image.Save(picPath, image.RawFormat); Microsoft.Office.Interop.Excel.Range range = uEHelper.getRange("F" + (2 + index).ToString(), "F" + (2 + index).ToString()); uEHelper.pastePicture(range, picPath); } myExcel.saveWithoutAutoFit(); myExcel.close(); ShowResult.show(lblResult, string.Format(@"导出完毕,存于:{0}", destFilePath), true); timerRestoreLabel.Start(); }
private void CriaAcimaAbaixo(double overValor, IWebElement tabelaClassificacao, EClassificacaoTipo tipo, Time time) { var trTimes = tabelaClassificacao.FindElements(By.ClassName("highlight")); foreach (var tr in trTimes) { var nomeTime = tr.FindElement(By.ClassName("team_name_span")) .FindElement(By.TagName("a")).Text; if (time.Nome == nomeTime) { var qtdJogos = tr.FindElement(By.ClassName("col_matches_played")).Text; var gols = tr.FindElement(By.ClassName("col_goals")).Text; var gj = tr.FindElement(By.ClassName("col_avg_goals_match")).Text; var asTag = tr.FindElement(By.ClassName("col_last_5")) .FindElements(By.TagName("a")); var overs = tr.FindElements(By.ClassName("form-over")).Count; var unders = tr.FindElements(By.ClassName("form-under")).Count; Over o = new Over(overValor, gols, gj, overs, unders, overs + unders, TimeHelper.GolsRealizadosConvert(gols), TimeHelper.GolsSofridosConvert(gols)); o.J = int.Parse(qtdJogos); var aa = new AcimaAbaixo(tipo); aa.Overs.Add(o); time.AcimaAbaixo.Add(aa); } } }
public static void AwardViewersCoins(int setamount = 0) { List <string> usernames = ParseViewersFromJsonAndFindActiveViewers(); if (usernames != null) { foreach (string username in usernames) { Viewer viewer = GetViewer(username); if (viewer.IsBanned) { continue; } if (setamount > 0) { viewer.GiveViewerCoins(setamount); } else { int baseCoins = ToolkitSettings.CoinAmount; float baseMultiplier = viewer.GetViewerKarma() / 100; if (viewer.IsSub) { baseCoins += ToolkitSettings.SubscriberExtraCoins; baseMultiplier *= ToolkitSettings.SubscriberCoinMultiplier; } else if (viewer.IsVIP) { baseCoins += ToolkitSettings.VIPExtraCoins; baseMultiplier *= ToolkitSettings.VIPCoinMultiplier; } else if (viewer.mod) { baseCoins += ToolkitSettings.ModExtraCoins; baseMultiplier *= ToolkitSettings.ModCoinMultiplier; } // check if viewer is active in chat int minutesSinceViewerWasActive = TimeHelper.MinutesElapsed(viewer.last_seen); if (ToolkitSettings.ChatReqsForCoins) { if (minutesSinceViewerWasActive > ToolkitSettings.TimeBeforeHalfCoins) { baseMultiplier *= 0.5f; } if (minutesSinceViewerWasActive > ToolkitSettings.TimeBeforeNoCoins) { baseMultiplier *= 0f; } } double coinsToReward = (double)baseCoins * baseMultiplier; Store_Logger.LogString($"{viewer.username} gets {baseCoins} * {baseMultiplier} coins, total {(int)Math.Ceiling(coinsToReward)}"); viewer.GiveViewerCoins((int)Math.Ceiling(coinsToReward)); } } } }
public SavePageHtmlContentResponse Execute(PageContentViewModel request) { if (request.DesirableStatus == ContentStatus.Published) { DemandAccess(RootModuleConstants.UserRoles.PublishContent); } if (request.Id == default(Guid) || request.DesirableStatus != ContentStatus.Published) { DemandAccess(RootModuleConstants.UserRoles.EditContent); } UnitOfWork.BeginTransaction(); PageContent pageContent; if (!request.Id.HasDefaultValue()) { pageContent = Repository.AsQueryable <PageContent>().Where(f => f.Id == request.Id && !f.IsDeleted).FirstOne(); } else { pageContent = new PageContent(); pageContent.Order = contentService.GetPageContentNextOrderNumber(request.PageId); } pageContent.Page = Repository.AsProxy <Root.Models.Page>(request.PageId); pageContent.Region = Repository.AsProxy <Region>(request.RegionId); var contentToSave = new HtmlContent { Id = request.ContentId, ActivationDate = request.LiveFrom, ExpirationDate = TimeHelper.FormatEndDate(request.LiveTo), Name = request.ContentName, Html = request.PageContent ?? string.Empty, UseCustomCss = request.EnabledCustomCss, CustomCss = request.CustomCss, UseCustomJs = request.EanbledCustomJs, CustomJs = request.CustomJs, EditInSourceMode = request.EditInSourceMode }; // Preserve content if user is not authorized to change it. if (!SecurityService.IsAuthorized(RootModuleConstants.UserRoles.EditContent) && request.Id != default(Guid)) { var originalContent = Repository.First <HtmlContent>(request.ContentId); var contentToPublish = (HtmlContent)(originalContent.History != null ? originalContent.History.FirstOrDefault(c => c.Status == ContentStatus.Draft) ?? originalContent : originalContent); contentToSave.Name = contentToPublish.Name; contentToSave.Html = contentToPublish.Html; contentToSave.UseCustomCss = contentToPublish.UseCustomCss; contentToSave.CustomCss = contentToPublish.CustomCss; contentToSave.UseCustomJs = contentToPublish.UseCustomJs; contentToSave.CustomJs = contentToPublish.CustomJs; contentToSave.EditInSourceMode = contentToPublish.EditInSourceMode; } pageContent.Content = contentService.SaveContentWithStatusUpdate( contentToSave, request.DesirableStatus); Repository.Save(pageContent); UnitOfWork.Commit(); // Notify. if (request.DesirableStatus != ContentStatus.Preview) { Events.PageEvents.Instance.OnPageContentInserted(pageContent); } return(new SavePageHtmlContentResponse { PageContentId = pageContent.Id, ContentId = pageContent.Content.Id, RegionId = pageContent.Region.Id, PageId = pageContent.Page.Id }); }
/// <summary> /// Executes the specified request. /// </summary> /// <param name="request">The request.</param> /// <returns>Blog post view model</returns> public SaveBlogPostCommandResponse Execute(BlogPostViewModel request) { if (request.DesirableStatus == ContentStatus.Published) { AccessControlService.DemandAccess(Context.Principal, RootModuleConstants.UserRoles.PublishContent); } var layout = LoadLayout(); var region = LoadRegion(); var isNew = request.Id.HasDefaultValue(); var userCanEdit = false; if (isNew || request.DesirableStatus != ContentStatus.Published) { AccessControlService.DemandAccess(Context.Principal, RootModuleConstants.UserRoles.EditContent); userCanEdit = true; } else { userCanEdit = SecurityService.IsAuthorized(RootModuleConstants.UserRoles.EditContent); } // UnitOfWork.BeginTransaction(); // NOTE: this causes concurrent data exception. BlogPost blogPost; BlogPostContent content = null; PageContent pageContent = null; Pages.Models.Redirect redirectCreated = null; // Loading blog post and it's content, or creating new, if such not exists if (!isNew) { blogPost = Repository.First <BlogPost>(request.Id); content = Repository.FirstOrDefault <BlogPostContent>(c => c.PageContents.Any(x => x.Page == blogPost && x.Region == region && !x.IsDeleted)); if (content != null) { pageContent = Repository.FirstOrDefault <PageContent>(c => c.Page == blogPost && c.Region == region && !c.IsDeleted && c.Content == content); } if (userCanEdit && !string.Equals(blogPost.PageUrl, request.BlogUrl) && request.BlogUrl != null) { request.BlogUrl = urlService.FixUrl(request.BlogUrl); pageService.ValidatePageUrl(request.BlogUrl, request.Id); if (request.RedirectFromOldUrl) { var redirect = redirectService.CreateRedirectEntity(blogPost.PageUrl, request.BlogUrl); if (redirect != null) { Repository.Save(redirect); redirectCreated = redirect; } } blogPost.PageUrl = urlService.FixUrl(request.BlogUrl); } } else { blogPost = new BlogPost(); AddDefaultAccessRules(blogPost); } if (pageContent == null) { pageContent = new PageContent { Region = region, Page = blogPost }; } // Push to change modified data each time. blogPost.ModifiedOn = DateTime.Now; blogPost.Version = request.Version; if (userCanEdit) { blogPost.Title = request.Title; blogPost.Description = request.IntroText; blogPost.Author = request.AuthorId.HasValue ? Repository.AsProxy <Author>(request.AuthorId.Value) : null; blogPost.Category = request.CategoryId.HasValue ? Repository.AsProxy <Category>(request.CategoryId.Value) : null; blogPost.Image = (request.Image != null && request.Image.ImageId.HasValue) ? Repository.AsProxy <MediaImage>(request.Image.ImageId.Value) : null; if (isNew || request.DesirableStatus == ContentStatus.Published) { blogPost.ActivationDate = request.LiveFromDate; blogPost.ExpirationDate = TimeHelper.FormatEndDate(request.LiveToDate); } } if (isNew) { if (!string.IsNullOrWhiteSpace(request.BlogUrl)) { blogPost.PageUrl = urlService.FixUrl(request.BlogUrl); pageService.ValidatePageUrl(blogPost.PageUrl); } else { blogPost.PageUrl = blogService.CreateBlogPermalink(request.Title); } blogPost.MetaTitle = request.Title; blogPost.Layout = layout; UpdateStatus(blogPost, request.DesirableStatus); } else if (request.DesirableStatus == ContentStatus.Published) { UpdateStatus(blogPost, request.DesirableStatus); } // Create content. var newContent = new BlogPostContent { Id = content != null ? content.Id : Guid.Empty, Name = request.Title, Html = request.Content ?? string.Empty, EditInSourceMode = request.EditInSourceMode, ActivationDate = request.LiveFromDate, ExpirationDate = TimeHelper.FormatEndDate(request.LiveToDate) }; // Preserve content if user is not authorized to change it. if (!userCanEdit) { if (content == null) { throw new SecurityException("Forbidden: Access is denied."); // User has no rights to create new content. } var contentToPublish = (BlogPostContent)(content.History != null ? content.History.FirstOrDefault(c => c.Status == ContentStatus.Draft) ?? content : content); newContent.Name = contentToPublish.Name; newContent.Html = contentToPublish.Html; } content = (BlogPostContent)contentService.SaveContentWithStatusUpdate(newContent, request.DesirableStatus); pageContent.Content = content; blogPost.PageUrlHash = blogPost.PageUrl.UrlHash(); blogPost.UseCanonicalUrl = request.UseCanonicalUrl; Repository.Save(blogPost); Repository.Save(content); Repository.Save(pageContent); // Save tags if user has edit right. IList <Tag> newTags = null; if (userCanEdit) { tagService.SavePageTags(blogPost, request.Tags, out newTags); } // Commit UnitOfWork.Commit(); // Notify about new or updated blog post. if (isNew) { Events.BlogEvents.Instance.OnBlogCreated(blogPost); } else { Events.BlogEvents.Instance.OnBlogUpdated(blogPost); } // Notify about new created tags. Events.RootEvents.Instance.OnTagCreated(newTags); // Notify about redirect creation. if (redirectCreated != null) { Events.PageEvents.Instance.OnRedirectCreated(redirectCreated); } return(new SaveBlogPostCommandResponse { Id = blogPost.Id, Version = blogPost.Version, Title = blogPost.Title, PageUrl = blogPost.PageUrl, ModifiedByUser = blogPost.ModifiedByUser, ModifiedOn = blogPost.ModifiedOn.ToFormattedDateString(), CreatedOn = blogPost.CreatedOn.ToFormattedDateString(), PageStatus = blogPost.Status, DesirableStatus = request.DesirableStatus, PageContentId = pageContent.Id }); }
public static long ToTicks(this DateTime dateTime) { long result = TimeHelper.GetTicks(dateTime); return(result); }
//创建Version.txt public static void Modify() { PlatformType type; VersionConfig newVersionconfig = new VersionConfig(); newVersionconfig.Version = (int)TimeHelper.ClientNowSeconds(); #if UNITY_ANDROID Log.Debug("创建新Android资源版本" + newVersionconfig.Version.ToString()); type = PlatformType.Android; #elif UNITY_IOS Log.Debug("创建新iOS资源版本" + newVersionconfig.Version.ToString()); type = PlatformType.IOS; #elif UNITY_WEBGL Log.Debug("创建新WEBGL资源版本" + newVersionconfig.Version.ToString()); type = PlatformType.WebGL; #elif UNITY_STANDALONE_OSX Log.Debug("创建新Mac资源版本" + newVersionconfig.Version.ToString()); type = PlatformType.MacOS; #else Log.Debug("创建新PC资源版本" + newVersionconfig.Version.ToString()); type = PlatformType.PC; #endif //获取本地热更新文件目录地址 string resFold = string.Format("../WebRes/{0}/StreamingAssets/", type); Log.Info($"============={resFold}==============="); DirectoryInfo directoryInfo = new DirectoryInfo(resFold); if (directoryInfo.Exists) { long size = 0; //遍历本地文件 为每个文件建立一个FileVersionInfo FileInfo[] fileInfos = directoryInfo.GetFiles(); foreach (FileInfo fileInfo in fileInfos) { if (fileInfo.Name.EndsWith("meta")) { continue; } FileVersionInfo a = new FileVersionInfo(); a.File = fileInfo.Name; a.MD5 = GetBundleMD5(fileInfo.Name, resFold); a.Size = GetBundleSize(fileInfo.Name, resFold); newVersionconfig.FileInfoDict.Add(fileInfo.Name, a); size = a.Size + size; } //添加Version.txt到目录 FileVersionInfo version = new FileVersionInfo(); version.File = "Version.txt"; version.MD5 = ""; version.Size = 0; newVersionconfig.FileInfoDict.Add("Version.txt", version); newVersionconfig.TotalSize = size; //输出为文件 string path = resFold + "/Version.txt"; using (FileStream fs = new FileStream(path, FileMode.Create)) { byte[] data = System.Text.Encoding.ASCII.GetBytes(JsonHelper.ToJson(newVersionconfig)); fs.Write(data, 0, data.Length); } } else { Log.Error("热更新目录不存在"); } }
private TwitterRateLimiting(int limit, int remaining, int reset) { Limit = limit; Remaining = remaining; Reset = TimeHelper.GetDateTimeFromUnixTime(reset); }
/// <summary> /// Ons the action executing. /// </summary> /// <param name="context">Filter context.</param> public override void OnActionExecuting(ActionExecutingContext context) { ExternalRequesViewModel RequestObj = null; var errCode = SysCode.Ok; var _sys = context.HttpContext.RequestServices.GetService <ISystems>(); ExternalResponesViewModel <object> Response = null; var route = context.RouteData.Values; var action = route["action"]; string md5 = string.Empty; try { context.HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);//FromBody 不加读取不到参数 using (var sr = new StreamReader(context.HttpContext.Request.Body)) { RequestObj = JsonHelper.DeserializeJsonToObject <ExternalRequesViewModel>(sr.ReadToEnd()); //业务参数,加密方式 } } catch (Exception) { errCode = SysCode.LackParameter; Response = new ExternalResponesViewModel <object>(errCode, _sys, null); context.Result = new JsonResult(Response); //缺少参数 return; } /*appkey校验*/ var appConfigDto = _sys.GetAppConfig(RequestObj.AppKey); if (appConfigDto == null) { errCode = SysCode.AppKey; Response = new ExternalResponesViewModel <object>(errCode, _sys, null); context.Result = new JsonResult(Response); return; } ; /*时间戳校验 */ long ltime = TimeHelper.ConvertDateTimeToInt(DateTime.Now) - long.Parse(RequestObj.Stimestamp); if (ltime > 120000) { errCode = SysCode.TimestampErr; Response = new ExternalResponesViewModel <object>(errCode, _sys, null); context.Result = new JsonResult(Response); return; } /*签名验证 appKey+appSecret+data+uuId+timestamp*/ md5 = _sys.Md5Encode($"{appConfigDto.Keys}{appConfigDto.Secret}{RequestObj.Data}{RequestObj.Stimestamp}"); if (!RequestObj.Sign.Equals(md5)) { errCode = SysCode.SignCheckErr; Response = new ExternalResponesViewModel <object>(errCode, _sys, null); context.Result = new JsonResult(Response); return; } string strTemp = RequestObj.Data.ToString(); (string strJson, var code) = _sys.Base64Decode(Encoding.UTF8, strTemp); if (code != SysCode.Ok) { //64解码失败 errCode = SysCode.Base64DecodeErr; Response = new ExternalResponesViewModel <object>(errCode, _sys, null); context.Result = new JsonResult(Response); return; } RequestObj.Data = JsonHelper.DeserializeJsonToObject <dynamic>(strJson); //这里需要增加strJson是否是json格式的判断 var claimsIdentity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, JsonHelper.SerializeObject(RequestObj)), }, "Basic"); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); context.HttpContext.User = claimsPrincipal; /*业务参数校验*/ if (true) { ExternalResponesViewModel <object> response = new ExternalResponesViewModel <object>(_sys.CheckParameters(RequestObj.Data, action.ToString()), _sys, null); if (response.Code != 0) { context.Result = new JsonResult(response); return; } } }
public void DateTimeToUnixMilliseconds_WithMilliseconds() { Assert.AreEqual(1362575700420, TimeHelper.DateTimeToUnixMilliseconds(DateTime.Parse("2013-03-06T13:15:00.42"))); }
/// <summary> /// Saves the blog post. /// </summary> /// <param name="request">The request.</param> /// <param name="childContentOptionValues">The child content option values.</param> /// <param name="principal">The principal.</param> /// <param name="errorMessages">The error messages.</param> /// <returns> /// Saved blog post entity /// </returns> /// <exception cref="System.ComponentModel.DataAnnotations.ValidationException"></exception> /// <exception cref="SecurityException">Forbidden: Access is denied.</exception> public BlogPost SaveBlogPost(BlogPostViewModel request, IList <ContentOptionValuesViewModel> childContentOptionValues, IPrincipal principal, out string[] errorMessages) { errorMessages = new string[0]; string[] roles; if (request.DesirableStatus == ContentStatus.Published) { accessControlService.DemandAccess(principal, RootModuleConstants.UserRoles.PublishContent); roles = new[] { RootModuleConstants.UserRoles.PublishContent }; } else { accessControlService.DemandAccess(principal, RootModuleConstants.UserRoles.EditContent); roles = new[] { RootModuleConstants.UserRoles.EditContent }; } var isNew = request.Id.HasDefaultValue(); var userCanEdit = securityService.IsAuthorized(RootModuleConstants.UserRoles.EditContent); ValidateData(isNew, request); BlogPost blogPost; BlogPostContent content; PageContent pageContent; GetBlogPostAndContentEntities(request, principal, roles, ref isNew, out content, out pageContent, out blogPost); var beforeChange = new UpdatingBlogModel(blogPost); // Master page / layout Layout layout; Page masterPage; Region region; LoadDefaultLayoutAndRegion(out layout, out masterPage, out region); if (masterPage != null) { var level = accessControlService.GetAccessLevel(masterPage, principal); if (level < AccessLevel.Read) { var message = BlogGlobalization.SaveBlogPost_FailedToSave_InaccessibleMasterPage; const string logMessage = "Failed to save blog post. Selected master page for page layout is inaccessible."; throw new ValidationException(() => message, logMessage); } } if (pageContent.Region == null) { pageContent.Region = region; } // Load master pages for updating page's master path and page's children master path IList <Guid> newMasterIds; IList <Guid> oldMasterIds; IList <Guid> childrenPageIds; IList <MasterPage> existingChildrenMasterPages; PrepareForUpdateChildrenMasterPages(isNew, blogPost, request, out newMasterIds, out oldMasterIds, out childrenPageIds, out existingChildrenMasterPages); // TODO: TEST AND TRY TO FIX IT: TRANSACTION HERE IS REQUIRED! // UnitOfWork.BeginTransaction(); // NOTE: this causes concurrent data exception. Redirect redirectCreated = null; if (!isNew && userCanEdit && !string.Equals(blogPost.PageUrl, request.BlogUrl) && !string.IsNullOrWhiteSpace(request.BlogUrl)) { request.BlogUrl = urlService.FixUrl(request.BlogUrl); pageService.ValidatePageUrl(request.BlogUrl, request.Id); if (request.RedirectFromOldUrl) { var redirect = redirectService.CreateRedirectEntity(blogPost.PageUrl, request.BlogUrl); if (redirect != null) { repository.Save(redirect); redirectCreated = redirect; } } blogPost.PageUrl = urlService.FixUrl(request.BlogUrl); } // Push to change modified data each time. blogPost.ModifiedOn = DateTime.Now; if (userCanEdit) { blogPost.Title = request.Title; blogPost.Description = request.IntroText; blogPost.Author = request.AuthorId.HasValue ? repository.AsProxy <Author>(request.AuthorId.Value) : null; blogPost.Category = request.CategoryId.HasValue ? repository.AsProxy <Category>(request.CategoryId.Value) : null; blogPost.Image = (request.Image != null && request.Image.ImageId.HasValue) ? repository.AsProxy <MediaImage>(request.Image.ImageId.Value) : null; if (isNew || request.DesirableStatus == ContentStatus.Published) { blogPost.ActivationDate = request.LiveFromDate; blogPost.ExpirationDate = TimeHelper.FormatEndDate(request.LiveToDate); } } if (isNew) { if (!string.IsNullOrWhiteSpace(request.BlogUrl)) { blogPost.PageUrl = urlService.FixUrl(request.BlogUrl); pageService.ValidatePageUrl(blogPost.PageUrl); } else { blogPost.PageUrl = CreateBlogPermalink(request.Title, null, blogPost.Category != null ? (Guid?)blogPost.Category.Id : null); } blogPost.MetaTitle = request.MetaTitle ?? request.Title; if (masterPage != null) { blogPost.MasterPage = masterPage; masterPageService.SetPageMasterPages(blogPost, masterPage.Id); } else { blogPost.Layout = layout; } UpdateStatus(blogPost, request.DesirableStatus); AddDefaultAccessRules(blogPost, principal, masterPage); } else if (request.DesirableStatus == ContentStatus.Published || blogPost.Status == PageStatus.Preview) { // Update only if publishing or current status is preview. // Else do not change, because it may change from published to draft status UpdateStatus(blogPost, request.DesirableStatus); } // Create content. var newContent = new BlogPostContent { Id = content != null ? content.Id : Guid.Empty, Name = request.Title, Html = request.Content ?? string.Empty, EditInSourceMode = request.EditInSourceMode, ActivationDate = request.LiveFromDate, ExpirationDate = TimeHelper.FormatEndDate(request.LiveToDate) }; // Preserve content if user is not authorized to change it. if (!userCanEdit) { if (content == null) { throw new SecurityException("Forbidden: Access is denied."); // User has no rights to create new content. } var contentToPublish = (BlogPostContent)(content.History != null ? content.History.FirstOrDefault(c => c.Status == ContentStatus.Draft) ?? content : content); newContent.Name = contentToPublish.Name; newContent.Html = contentToPublish.Html; } content = SaveContentWithStatusUpdate(isNew, newContent, request, principal); pageContent.Content = content; optionService.SaveChildContentOptions(content, childContentOptionValues, request.DesirableStatus); blogPost.PageUrlHash = blogPost.PageUrl.UrlHash(); blogPost.UseCanonicalUrl = request.UseCanonicalUrl; MapExtraProperties(isNew, blogPost, content, pageContent, request, principal); // Notify about page properties changing. var cancelEventArgs = Events.BlogEvents.Instance.OnBlogChanging(beforeChange, new UpdatingBlogModel(blogPost)); if (cancelEventArgs.Cancel) { errorMessages = cancelEventArgs.CancellationErrorMessages.ToArray(); return(null); } repository.Save(blogPost); repository.Save(content); repository.Save(pageContent); masterPageService.UpdateChildrenMasterPages(existingChildrenMasterPages, oldMasterIds, newMasterIds, childrenPageIds); pageContent.Content = content; blogPost.PageContents = new [] { pageContent }; IList <Tag> newTags = null; if (userCanEdit) { newTags = SaveTags(blogPost, request); } // Commit unitOfWork.Commit(); // Notify about new created tags. Events.RootEvents.Instance.OnTagCreated(newTags); // Notify about new or updated blog post. if (isNew) { Events.BlogEvents.Instance.OnBlogCreated(blogPost); } else { Events.BlogEvents.Instance.OnBlogUpdated(blogPost); } // Notify about redirect creation. if (redirectCreated != null) { Events.PageEvents.Instance.OnRedirectCreated(redirectCreated); } return(blogPost); }
/// <summary> /// 获取疑似重返手术室列表 /// </summary> /// <param name="empid"></param> /// <returns></returns> public static List <Models.OperationMaster> GetSuspectedReturns() { var list = IBatisAccess.OperationMasterDao.Instance.GetSuspectedReturns(null, null).ToList(); var result = new List <Models.OperationMaster>(); string operation_name_keys = SystemContext.Instance.OperationParameter[SystemConst.OperationParameter.operation_name_keys]; string operation_keys_count = SystemContext.Instance.OperationParameter[SystemConst.OperationParameter.operation_keys_count]; string filtering_characters = SystemContext.Instance.OperationParameter[SystemConst.OperationParameter.filtering_characters]; foreach (var item1 in list) { if (item1.OPERATION_NAME == null) { item1.OPERATION_NAME = string.Empty; } bool isDisplay = false; foreach (var item2 in list.Where(m => m.PATIENT_ID == item1.PATIENT_ID && m.OPER_ID != item1.OPER_ID)) { if (item2.OPERATION_NAME == null) { item2.OPERATION_NAME = string.Empty; } if (item1.OPERATION_NAME.ToUpper().Contains("MRI") || item2.OPERATION_NAME.ToUpper().Contains("MRI")) { break; } if (item1.OPERATION_NAME.ToUpper().Contains("CT") || item2.OPERATION_NAME.ToUpper().Contains("MRI")) { break; } //判断两次手术是否有关键字 if (!string.IsNullOrEmpty(operation_name_keys)) { if (StringOperation.IsHaveKeyWord(item1.OPERATION_NAME, operation_name_keys.Split(',')) || StringOperation.IsHaveKeyWord(item2.OPERATION_NAME, operation_name_keys.Split(','))) { isDisplay = true; break; } } //判断两次手术是否有两个汉字以上重复 string lcsstr = StringOperation.LCS(item1.OPERATION_NAME, item2.OPERATION_NAME); if (lcsstr.Length >= int.Parse(operation_keys_count)) { isDisplay = true; } //排除关键字 if ((item1.OPERATION_NAME.Contains("左") && item2.OPERATION_NAME.Contains("右")) || (item1.OPERATION_NAME.Contains("右") && item2.OPERATION_NAME.Contains("左"))) { break; } //排除关键字 if (item2.OPERATION_NAME.Contains("部分") && (item2.OPERATION_NAME.Contains("全部") || item2.OPERATION_NAME.Contains("根治"))) { break; } foreach (var item in filtering_characters.Split(',')) { if (item1.OPERATION_NAME.Contains(item) || item1.OPERATION_NAME.Contains(item)) { isDisplay = false; break; } } } if (isDisplay) { item1.CONTINUED_TIMESPAN = TimeHelper.GetTimeSpanMin(item1.START_DATE_TIME, item1.END_DATE_TIME); result.Add(item1); } } //排除已经确认的二次手术患者 var lstScOpreation = IBatisAccess.ScOperationDao.Instance.GetReturnRoom(); for (int i = result.Count - 1; i >= 0; i--) { var item = result[i]; if (lstScOpreation.Where(m => m.PATIENT_ID == item.PATIENT_ID).Count() > 0) { result.Remove(item); } } return(result); }
public void CriaAcimaAbaixoTotal(double overValor, IWebElement tabelaClassificacao, EClassificacaoTipo tipo, List <Time> times) { var trTimes = tabelaClassificacao.FindElements(By.ClassName("highlight")); foreach (var tr in trTimes) { var nomeTime = tr.FindElement(By.ClassName("team_name_span")) .FindElement(By.TagName("a")).Text; var qtdJogos = tr.FindElement(By.ClassName("col_matches_played")).Text; var gols = tr.FindElement(By.ClassName("col_goals")).Text; var gj = tr.FindElement(By.ClassName("col_avg_goals_match")).Text; var asTag = tr.FindElement(By.ClassName("col_last_5")) .FindElements(By.TagName("a")); bool?ultimoOverPositivo; var underovers = tr.FindElement(By.ClassName("matches-5")).FindElements(By.TagName("a")); if (underovers.Count > 1) { string classInfo = underovers[1].GetAttribute("class"); ultimoOverPositivo = classInfo.Contains("form-under") ? false : true; times.FirstOrDefault(t => t.Nome == nomeTime).UltimoOverPositivo = ultimoOverPositivo; } var overs = tr.FindElements(By.ClassName("form-over")).Count; var unders = tr.FindElements(By.ClassName("form-under")).Count; Over o = new Over(overValor, gols, gj, overs, unders, overs + unders, TimeHelper.GolsRealizadosConvert(gols), TimeHelper.GolsSofridosConvert(gols)); o.J = int.Parse(qtdJogos); var aa = new AcimaAbaixo(tipo); aa.Overs.Add(o); times.FirstOrDefault(t => t.Nome == nomeTime).AcimaAbaixo.Add(aa); } }
// 向router申请 private static async ETTask <uint> Connect(IPEndPoint routerAddress, IPEndPoint realAddress, uint localConn, uint remoteConn) { uint connectId = RandomHelper.RandUInt32(); using Socket socket = new Socket(routerAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp); int count = 30; byte[] sendCache = new byte[512]; byte[] recvCache = new byte[512]; uint synFlag = localConn == 0? KcpProtocalType.RouterSYN : KcpProtocalType.RouterReconnectSYN; sendCache.WriteTo(0, synFlag); sendCache.WriteTo(1, localConn); sendCache.WriteTo(5, remoteConn); sendCache.WriteTo(9, connectId); byte[] addressBytes = realAddress.ToString().ToByteArray(); Array.Copy(addressBytes, 0, sendCache, 13, addressBytes.Length); Log.Info($"router connect: {connectId} {localConn} {remoteConn} {routerAddress} {realAddress}"); EndPoint recvIPEndPoint = new IPEndPoint(IPAddress.Any, 0); long lastSendTimer = 0; while (true) { long timeNow = TimeHelper.ClientFrameTime(); if (timeNow - lastSendTimer > 300) { if (--count < 0) { Log.Error($"router connect timeout fail! {localConn} {remoteConn} {routerAddress} {realAddress}"); return(0); } lastSendTimer = timeNow; // 发送 socket.SendTo(sendCache, 0, addressBytes.Length + 13, SocketFlags.None, routerAddress); } await TimerComponent.Instance.WaitFrameAsync(); // 接收 if (socket.Available > 0) { int messageLength = socket.ReceiveFrom(recvCache, ref recvIPEndPoint); if (messageLength != 9) { Log.Error($"router connect error1: {connectId} {messageLength} {localConn} {remoteConn} {routerAddress} {realAddress}"); continue; } byte flag = recvCache[0]; if (flag != KcpProtocalType.RouterReconnectACK && flag != KcpProtocalType.RouterACK) { Log.Error($"router connect error2: {connectId} {synFlag} {flag} {localConn} {remoteConn} {routerAddress} {realAddress}"); continue; } uint recvRemoteConn = BitConverter.ToUInt32(recvCache, 1); uint recvLocalConn = BitConverter.ToUInt32(recvCache, 5); Log.Info($"router connect finish: {connectId} {recvRemoteConn} {recvLocalConn} {localConn} {remoteConn} {routerAddress} {realAddress}"); return(recvLocalConn); } } }
public void PreencheCamposAnaliseJogo(Jogo jogo) { var time1_05_15_25_Overs = jogo.Time1.AcimaAbaixo.Where(a => a.Tipo == EClassificacaoTipo.Casa) .SelectMany(a => a.Overs) .ToList(); var time2_05_15_25_Overs = jogo.Time2.AcimaAbaixo.Where(a => a.Tipo == EClassificacaoTipo.Fora) .SelectMany(a => a.Overs) .ToList(); // Time1 var time1_overs05 = TimeHelper.GetOvers(jogo.Time1, 0.5, EClassificacaoTipo.Casa); var time1_overs15 = TimeHelper.GetOvers(jogo.Time1, 1.5, EClassificacaoTipo.Casa); var time1_overs25 = TimeHelper.GetOvers(jogo.Time1, 2.5, EClassificacaoTipo.Casa); // Time2 var time2_overs05 = TimeHelper.GetOvers(jogo.Time2, 0.5, EClassificacaoTipo.Fora); var time2_overs15 = TimeHelper.GetOvers(jogo.Time2, 1.5, EClassificacaoTipo.Fora); var time2_overs25 = TimeHelper.GetOvers(jogo.Time2, 2.5, EClassificacaoTipo.Fora); //MediaGols double time1_mediaGols = TimeHelper.MediaGols(jogo.Time1, EClassificacaoTipo.Casa); double time2_mediaGols = TimeHelper.MediaGols(jogo.Time2, EClassificacaoTipo.Fora); double mediaGols = (time1_mediaGols + time2_mediaGols) / 2; var m1 = time1_05_15_25_Overs.FirstOrDefault()?.Gols ?? ""; var m2 = time2_05_15_25_Overs.FirstOrDefault()?.Gols ?? ""; var classTime1 = jogo.Time1.Classificacoes.FirstOrDefault().Lugar; var classTime2 = jogo.Time2.Classificacoes.FirstOrDefault().Lugar; var classTotal = jogo.Time1.Classificacoes.FirstOrDefault().TotalLugares; bool golsIrregularTime1 = TimeValidations.TimeGolsIrregular(jogo.Time1.AcimaAbaixo.FirstOrDefault().Overs.FirstOrDefault().Gols); bool golsIrregularTime2 = TimeValidations.TimeGolsIrregular(jogo.Time2.AcimaAbaixo.FirstOrDefault().Overs.FirstOrDefault().Gols); bool jogoComTimeComGolsIrregulares = golsIrregularTime1 || golsIrregularTime2; bool timesComPoucaDiferencaClassificacao = JogoValidations.TimesPoucaDiferencaClassificacao(jogo); bool umDosTimesFazMaisGol = JogoValidations.UmDosTimesFazMaisGol(jogo); bool osDoisTimesFazemPoucosGols = JogoValidations.OsDoisTimesFazemPoucosGols(jogo); int time1GolsR = TimeHelper.GolsRealizadosConvert(m1); int time1GolsS = TimeHelper.GolsSofridosConvert(m1); int time2GolsR = TimeHelper.GolsRealizadosConvert(m2); int time2GolsS = TimeHelper.GolsSofridosConvert(m2); var somaOvers05 = time1_overs05 + time2_overs05; var somaOvers15 = time1_overs15 + time2_overs15; var somaOvers25 = time1_overs25 + time2_overs25; jogo.Time1.MediaGols = time1_mediaGols; jogo.Time2.MediaGols = time2_mediaGols; jogo.Time1.Gols = m1; jogo.Time2.Gols = m2; jogo.MediaGolsTotal = mediaGols; jogo.Time1.Overs05 = time1_overs05; jogo.Time1.Overs15 = time1_overs15; jogo.Time1.Overs25 = time1_overs25; jogo.Time2.Overs05 = time2_overs05; jogo.Time2.Overs15 = time2_overs15; jogo.Time2.Overs25 = time2_overs25; jogo.SomaOvers05 = time1_overs05 + time2_overs05; jogo.SomaOvers15 = time1_overs15 + time2_overs15; jogo.SomaOvers25 = time1_overs25 + time2_overs25; jogo.SomaTotalOvers = jogo.SomaOvers05 + jogo.SomaOvers15 + jogo.SomaOvers25; jogo.UmTimeFazMaisGolQueOOutro = JogoValidations.UmDosTimesFazMaisGol(jogo); jogo.Time1.Classificacao = classTime1; jogo.Time2.Classificacao = classTime2; jogo.ClassificaoTotal = classTotal; jogo.ClassifPerto = timesComPoucaDiferencaClassificacao; jogo.UmOuOsDoisTimesFazemMaisGols = umDosTimesFazMaisGol; jogo.OsDoisTimesSofremGols = osDoisTimesFazemPoucosGols; jogo.GolsIrregulares = jogoComTimeComGolsIrregulares; jogo.TimesComPoucosJogos = TimeValidations.PoucosJogosTime(jogo.Time1, EClassificacaoTipo.Casa) || TimeValidations.PoucosJogosTime(jogo.Time2, EClassificacaoTipo.Fora); jogo.LinkResultados = GetLinkResultadosId(jogo.IdJogoBet); jogo.Time1.GolsRealizados = time1GolsR; jogo.Time1.GolsSofridos = time1GolsS; jogo.Time2.GolsRealizados = time2GolsR; jogo.Time2.GolsSofridos = time2GolsS; jogo.GolsTotal = jogo.GolsTime1 + jogo.GolsTime2; jogo.UmTimeFazMaisGolEOutroSofreMaisGol = JogoValidations.UmTimeFazMaisGolEOutroSofreMaisGols(jogo); jogo.Time1.QtdTotalDeJogosOvers = TimeHelper.GetQtdJogos(jogo.Time1, EClassificacaoTipo.Casa); jogo.Time2.QtdTotalDeJogosOvers = TimeHelper.GetQtdJogos(jogo.Time2, EClassificacaoTipo.Fora); jogo.UmOuOsDoisTimesTemJogosOversMenorQue5 = (jogo.Time1.QtdTotalDeJogosOvers < 5 || jogo.Time2.QtdTotalDeJogosOvers < 5); jogo.JogoComTimeComODobroDeGols = JogoValidations.JogoComTimeFazODobroDeGols(jogo); AnalisaGolsTotal(jogo); }
public override async Task <TaskRes> Execute(Account acc) { if (acc.Farming.OasisFarmed == null) { acc.Farming.OasisFarmed = new List <(Coordinates, DateTime)>(); } // Clear global oasis list that were attacked 100 hours + ago acc.Farming.OasisFarmed.RemoveAll(x => x.Item2 < DateTime.Now.AddHours(-100)); var previouslyFarmed = acc.Farming.OasisFarmed .Where(x => DateTime.Now.AddHours(-Vill.FarmingNonGold.OasisFarmingDelay) < x.Item2) .ToList(); // If we don't send to nearest oasis first, check if we have enough troops. // This will save a lot of time / requests. base.TroopsMovement = new TroopsSendModel(); if (Vill.FarmingNonGold.OasisFarmingType != OasisFarmingType.NearestFirst) { var troopsInVill = new int[11]; base.TroopsMovement.Troops = new int[11]; base.SetCoordsInUrl = false; base.TroopsCallback = (Account _, int[] troops) => { troopsInVill = troops; return(false); // Don't continue with the SendTroops }; await base.Execute(acc); var enoughTroops = TroopsCountRecieved(acc, troopsInVill); // If we don't have enough troops in the village, retry later if (!enoughTroops) { return(Retry()); } } await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/karte.php"); // Get map tiles around the current village var mapTiles = MapHelper.GetMapTiles(acc, Vill.Coordinates); // Get oasis coordinates var oasisCoords = GetUnoccupiedOasisCoordinates(acc, mapTiles); var oasisCoordsOrdered = oasisCoords .OrderBy(oasis => MapHelper.CalculateDistance(acc, oasis, this.Vill.Coordinates)) .ToList(); var oasisFiltered = oasisCoordsOrdered.Where(o => MapHelper.CalculateDistance(acc, o, this.Vill.Coordinates) <= Vill.FarmingNonGold.OasisMaxDistance && // Oasis is in range !previouslyFarmed.Any(x => x.Item1.Equals(o)) // Oasis wasn't recently attacked ).ToList(); acc.Wb.Log($"Found {oasisCoordsOrdered.Count} oasis, {oasisFiltered.Count} are in range and weren't recently attacked"); // (Coordinates, number of animals) var list = new List <(Coordinates, int[])>(); for (int i = 0; i < oasisFiltered.Count; i++) { var oasis = oasisFiltered[i]; await Task.Delay(AccountHelper.Delay() * 3); acc.Wb.Log($"[{i + 1}/{oasisFiltered.Count}] Searching for oasis to attack, checking {oasis}"); var animals = MapHelper.GetOasisAnimals(acc, oasis); // Check if oasis deff power is above threshold // -1 will ignore deff power if (Vill.FarmingNonGold.MaxDeffPower != -1 && Vill.FarmingNonGold.MaxDeffPower < GetOasisDeffPower(animals)) { continue; } list.Add((oasis, animals)); // If we want to first attack nearest oasis first, don't search for other oasis if (Vill.FarmingNonGold.OasisFarmingType == OasisFarmingType.NearestFirst) { break; } } if (list.Count == 0) { if (0 < previouslyFarmed.Count) { acc.Wb.Log("No oasis that matched criteria was found! Change your criteria and try again"); return(TaskRes.Executed); } this.NextExecute = previouslyFarmed.First().Item2; acc.Wb.Log($"No oasis that matched criteria was found! Will retry at {this.NextExecute}"); return(TaskRes.Retry); } switch (Vill.FarmingNonGold.OasisFarmingType) { case OasisFarmingType.NearestFirst: // We only have 1 oasis, since we broke out of foreach loop break; case OasisFarmingType.MaxResFirst: list = list.OrderByDescending(x => GetOasisResources(x.Item2)).ToList(); break; case OasisFarmingType.LeastPowerFirst: list = list.OrderBy(x => GetOasisDeffPower(x.Item2)).ToList(); break; case OasisFarmingType.MaxResProfitFirst: // Not yet implemented, implement combat simulator from: // https://github.com/kirilloid/travian/tree/master/src/model/t4/combat break; } var attackCoords = list.First().Item1; acc.Wb.Log($"Bot will attack oasis {attackCoords}"); base.SetCoordsInUrl = true; // Since we are searching oasis from the map base.TroopsMovement.TargetCoordinates = attackCoords; base.TroopsMovement.MovementType = Classificator.MovementType.Raid; // Bot will configure amount of troops to be sent when it parses // the amount of troops available at home base.TroopsMovement.Troops = new int[11]; base.TroopsCallback = TroopsCountRecieved; var response = await base.Execute(acc); // If we didn't have enough troops to send the attack. Will retry in 10-30 min if (response == TaskRes.Retry) { return(Retry()); } acc.Farming.OasisFarmed.Add((attackCoords, DateTime.Now)); // Repeat the task after troops come back if (Vill.FarmingNonGold.OasisFarmingEnabled) { // TODO: take in account the hero map DateTime troopsHome = DateTime.Now + TimeHelper.MultiplyTimespan(base.Arrival, 2); this.NextExecute = TimeHelper.RanDelay(acc, troopsHome); } return(TaskRes.Executed); }
private static async ETTask RunTask(this ActorLocationSender self, ActorTask task) { ActorMessageSender actorMessageSender = Game.Scene.GetComponent <ActorMessageSenderComponent>().Get(self.ActorId); IActorResponse response; try { // 这里必须使用不抛异常的rpc,因为服务端handler很可能出现错误,返回一个rpc fail的错误,结果这里抛了异常 // 这里抛了异常就会导致队列中的消息无法继续发送,导致整个actorlocationsender堵塞 response = await actorMessageSender.CallWithoutException(task.ActorRequest); } catch (Exception e) { self.GetParent <ActorLocationSenderComponent>().Remove(self.Id); return; } // 发送成功 switch (response.Error) { case ErrorCode.ERR_NotFoundActor: // 如果没找到Actor,重试 ++self.FailTimes; // 失败MaxFailTimes次则清空actor发送队列,返回失败 if (self.FailTimes > ActorLocationSender.MaxFailTimes) { // 失败直接删除actorproxy Log.Info($"actor send message fail, actorid: {self.Id}"); self.RunError(response.Error); self.GetParent <ActorLocationSenderComponent>().Remove(self.Id); return; } // 等待0.5s再发送 await Game.Scene.GetComponent <TimerComponent>().WaitAsync(500); self.ActorId = await Game.Scene.GetComponent <LocationProxyComponent>().Get(self.Id); self.AllowGet(); return; case ErrorCode.ERR_ActorNoMailBoxComponent: self.RunError(response.Error); self.GetParent <ActorLocationSenderComponent>().Remove(self.Id); return; default: self.LastRecvTime = TimeHelper.Now(); self.FailTimes = 0; self.WaitingTasks.Dequeue(); // 如果所有的发送消息都得到了返回,发送任务完成,那么删除这个ActorLocationSender,及时回收发送对象 if (self.WaitingTasks.Count == 0) { self.GetParent <ActorLocationSenderComponent>().Remove(self.Id); } if (task.Tcs != null) { IActorLocationResponse actorLocationResponse = response as IActorLocationResponse; if (actorLocationResponse == null) { task.Tcs.SetException(new Exception($"actor location respose is not IActorLocationResponse, but is: {response.GetType().Name}")); } task.Tcs.SetResult(actorLocationResponse); } return; } }
//获取微信信息 public static string InitUrl(string hosts, string passTicket) => String.Format("https://{0}{1}?r={2}&pass_ticket={3}", hosts, "/cgi-bin/mmwebwx-bin/webwxinit", TimeHelper.GetTimeStamp(), passTicket);
/// <summary> /// 取整点及头尾有效数据 ,10分钟取一次 /// </summary> /// <param name="tbNew"></param> /// <returns></returns> public DataTable ChangeTable(DataTable tbNew, int dura_min = 5) { if (dura_min > 60) { dura_min = 60; } if (dura_min < 5) { dura_min = 5; } DataTable tbOld = new DataTable(); try { tbOld = tbNew.Clone(); tbOld.PrimaryKey = null; tbOld.Columns["ID_RealTimeUsage"].DataType = typeof(string);//指定Age为Int类型 if (tbNew.Rows.Count > 0) { for (int i = 0; i < tbNew.Rows.Count; i++) { if (i == 0) { tbOld.Rows.Add(tbNew.Rows[i].ItemArray); } else if (i == tbNew.Rows.Count - 1 && tbNew.Rows.Count > 2) { tbOld.Rows.Add(tbNew.Rows[i].ItemArray); continue; } else if (Convert.ToInt64(tbNew.Rows[i][0]) >= Convert.ToInt64(tbOld.Rows[tbOld.Rows.Count - 1][0]) + (long)dura_min * 60 * 1000) { tbOld.Rows.Add(tbNew.Rows[i].ItemArray); continue; } } } for (int i = 0; i < tbOld.Rows.Count; i++) { //转换时间格式 tbOld.Rows[i][0] = TimeHelper.GetStringToDateTime((tbOld.Rows[i][0].ToString())); tbOld.Rows[i][2] = Convert.ToInt32(tbOld.Rows[i][2]) < 0 ? 0 : (Convert.ToInt32(tbOld.Rows[i][2]) / 2); } } catch (Exception ex) { logger.Error(ex.Message); } return(tbOld); //DataTable tbOld = new DataTable(); //tbOld = tbNew.Clone(); //tbOld.PrimaryKey = null; //tbOld.Columns["ID_RealTimeUsage"].DataType = typeof(string);//指定Age为Int类型 //try //{ // if (tbNew.Rows.Count > 0) //{ // if (tbNew.Rows.Count > Count) // { // int j = tbNew.Rows.Count / Count + 1; // for (int i = 0; i < tbNew.Rows.Count; i++) // { // //取收尾两 // if (i == 0 || i == tbNew.Rows.Count - 1) // { // //加入首尾两行 // tbOld.Rows.Add(tbNew.Rows[i].ItemArray); // } // else // { // if (i * j < tbNew.Rows.Count) // { // tbOld.Rows.Add(tbNew.Rows[i * j].ItemArray); // } // } // } // } // else // { // //数据条数低于Count ,则去除间隔低于1分钟的数据 // for (int i = 0; i < tbNew.Rows.Count; i++) // { // if (i == 0) // tbOld.Rows.Add(tbNew.Rows[i].ItemArray); // else if (i == tbNew.Rows.Count - 1 && tbNew.Rows.Count > 2) // { // tbOld.Rows.Add(tbNew.Rows[i].ItemArray); // continue; // } // else if (Convert.ToInt64(tbNew.Rows[i][0]) >= Convert.ToInt64(tbNew.Rows[i - 1][0]) + (long)60*1000) // { // tbOld.Rows.Add(tbNew.Rows[i].ItemArray); // continue; // } // } // } //} //for (int i = 0; i < tbOld.Rows.Count; i++) //{ // //转换时间格式 // tbOld.Rows[i][0] = TimeHelper.GetStringToDateTime((tbOld.Rows[i][0].ToString())); //} //} //catch (Exception ex) //{ // logger.Error(ex.Message); //} //return tbOld; }
private bool checkDomainSelling(string domain) { string findStr = new JObject() { { "fullDomain", domain }, { "displayName", "NNSfixedSellingLaunched" }, { "ttl", new JObject { { "$gt", TimeHelper.GetTimeStamp() } } } }.ToString(); return(mh.GetDataCount(mongodbConnStr, mongodbDatabase, NNSfixedSellingStateCol, findStr) > 0); }
public static long GenerateId() { long time = TimeHelper.ClientNowSeconds(); return((AppId << 48) + (time << 16) + ++value); }
public void CanNotParse() { BoolMessageItem <TimeSpan> result = TimeHelper.Parse("sf"); Assert.IsFalse(result.Success); }
private static void Main(string[] args) { Options options = null; Parser.Default.ParseArguments <Options>(args) .WithParsed(res => options = res) .WithNotParsed(err => Environment.Exit(1)); var stopWatch = Stopwatch.StartNew(); if (!File.Exists(options.FileName)) { Console.WriteLine($"File {options.FileName} doesn't exist."); return; } Console.Write($"Start parsing file: {options.FileName} "); City city; try { using (var reader = new StreamReader(options.FileName)) { city = (City) new XmlSerializer(typeof(City)).Deserialize(reader); } } catch (Exception e) { Console.WriteLine( $"Unable to parse osm file: {e.Message}. See about downloading here: https://github.com/bruce-willis/City-Roads/blob/develop/docs/download.md"); return; } Console.WriteLine($"Elapsed time: {stopWatch.Elapsed}"); TimeHelper.MeasureTime(() => SvgHelper.GenerateSvg(city, options), "generationg svg file"); if (options.GenerateNodesList) { TimeHelper.MeasureTime(() => CsvHelper.WriteNodesInfo(options.OutputDirectory), "creating csv with nodes' information"); } if (options.GenerateAdjacencyList) { TimeHelper.MeasureTime(() => CsvHelper.WriteAdjacencyList(options.OutputDirectory), "creating csv with adjacency list"); } if (options.GenerateAdjacencyMatrix) { TimeHelper.MeasureTime(() => CsvHelper.WriteAdjacencyMatrix(options.OutputDirectory), "creating csv with adjacency matrix"); } DistanceHelper.AddNodes(city); if (options.FindShortestPathes) { DistanceHelper.CompareAlgorithms(options.OutputDirectory); } if (options.SolveSalesmanProblem) { Directory.CreateDirectory(Path.Combine(options.OutputDirectory, "Salesman")); TimeHelper.MeasureTime(() => CommonSalesman.Distances.GetType(), "calculating distances and pathes between destinations"); TimeHelper.MeasureTime(() => NearestNeighbour.Calculate(options.OutputDirectory), "solving travelling salesman problem using nearest neighbour"); TimeHelper.MeasureTime(() => NearestNeighbour.Calculate(options.OutputDirectory, withRandom: true), "solving travelling salesman problem using nearest neighbour and random"); //int i = 0; //double d1, d2; //do //{ // d1 = NearestNeighbour.Calculate(city, options.OutputDirectory); // d2 = NearestNeighbour.CalculateWithRandom(city, options.OutputDirectory); // Console.WriteLine(i++); //} while (d1 <= d2); //Console.WriteLine(d1); //Console.WriteLine(d2); TimeHelper.MeasureTime(() => SimulatedAnnealing.Calculate(10, 0.00001, options.OutputDirectory), "solving tsp using simulated annealing"); } Console.WriteLine($"\nJob done! Now it's time for tea. Total time elapsed: {stopWatch.Elapsed}"); Console.WriteLine(new Random().Next(0, 2) == 1 ? "Лучший в СПбГУ - Факультет ПМ-ПУ" : "Ответ на главный вопрос жизни, вселенной и всего такого - 42"); }
private DateTimeOffset ExtractTime(string timeText) { return(TimeHelper.ParseTimeOrMinValue(timeText, _visitDate, _locationInfo.UtcOffset)); }
public void Update() { //TODO 先硬编码一波,这一块要放到行为树去处理的 fui5V5Map = Game.Scene.GetComponent <FUIComponent>().Get(FUI5V5Map.UIPackageName) as FUI5V5Map; if (fui5V5Map == null) { return; } if (this.userInputComponent.QDown) { SessionComponent.Instance.Session.Send(new UserInput_SkillCmd() { Message = "Q" }); if (fui5V5Map.SkillQ_CDInfo.visible) { return; } fui5V5Map.SkillQ_CDInfo.text = "5"; fui5V5Map.SkillQ_CDInfo.visible = true; fui5V5Map.SkillQ_Bar.self.value = 100; fui5V5Map.SkillQ_Bar.Visible = true; fui5V5Map.SkillQ_Bar.self.TweenValue(0, 5).OnComplete(() => { fui5V5Map.SkillQ_CDInfo.visible = false; fui5V5Map.SkillQ_Bar.Visible = false; }); m_CDComponent.TriggerCD(this.Entity.Id, "QCD"); } if (this.userInputComponent.WDown) { SessionComponent.Instance.Session.Send(new UserInput_SkillCmd() { Message = "W" }); if (fui5V5Map.SkillW_CDInfo.visible) { return; } fui5V5Map.SkillW_CDInfo.text = "7"; fui5V5Map.SkillW_CDInfo.visible = true; fui5V5Map.SkillW_Bar.self.value = 100; fui5V5Map.SkillW_Bar.self.visible = true; fui5V5Map.SkillW_Bar.self.TweenValue(0, 7).OnComplete(() => { fui5V5Map.SkillW_CDInfo.visible = false; fui5V5Map.SkillW_Bar.self.visible = false; }); m_CDComponent.TriggerCD(this.Entity.Id, "WCD"); } if (this.userInputComponent.EDown) { SessionComponent.Instance.Session.Send(new UserInput_SkillCmd() { Message = "E" }); if (fui5V5Map.SkillE_CDInfo.visible) { return; } fui5V5Map.SkillE_CDInfo.text = "10"; fui5V5Map.SkillE_CDInfo.visible = true; fui5V5Map.SkillE_Bar.self.value = 100; fui5V5Map.SkillE_Bar.self.visible = true; fui5V5Map.SkillE_Bar.self.TweenValue(0, 10).OnComplete(() => { fui5V5Map.SkillE_CDInfo.visible = false; fui5V5Map.SkillE_Bar.self.visible = false; }); m_CDComponent.TriggerCD(this.Entity.Id, "ECD"); } if (this.userInputComponent.RDown) { SessionComponent.Instance.Session.Send(new UserInput_SkillCmd() { Message = "R" }); } long currentTime = TimeHelper.ClientNow(); if (fui5V5Map.SkillQ_CDInfo.visible) { fui5V5Map.SkillQ_CDInfo.text = Math.Ceiling((double)(this.m_QCDInfo.LastTriggerTimer + this.m_QCDInfo.Interval - currentTime) / 1000) .ToString(); } if (fui5V5Map.SkillW_CDInfo.visible) { fui5V5Map.SkillW_CDInfo.text = Math.Ceiling((double)(this.m_WCDInfo.LastTriggerTimer + this.m_WCDInfo.Interval - currentTime) / 1000) .ToString(); } if (fui5V5Map.SkillE_CDInfo.visible) { fui5V5Map.SkillE_CDInfo.text = Math.Ceiling((double)(this.m_ECDInfo.LastTriggerTimer + this.m_ECDInfo.Interval - currentTime) / 1000) .ToString(); } }
/// <summary> /// Creates EndSession object with provided values /// </summary> /// <param name="appKey">App key for the application being tracked; find in the Countly Dashboard under Management > Applications</param> /// <param name="deviceId">Unique ID for the device the app is running on</param> public EndSession(string appKey, string deviceId) { Content = String.Format("/i?app_key={0}&device_id={1}&end_session=1×tamp={2}", appKey, deviceId, TimeHelper.ToUnixTime(DateTime.Now.ToUniversalTime())); }