public void Test_AsyncSender_SendSuccess() { ManualResetEventSlim senderCalledWaiter = new ManualResetEventSlim(initialState: false); bool sendCalled = false; Task AsyncSenderSend(SharedBuffer buffer, BackgroundErrorCallback raiseBackgroundError) { sendCalled = true; senderCalledWaiter.Set(); return(Task.CompletedTask); } FactoryContext factoryContext = CreateFactoryContext(asyncSendFunc: AsyncSenderSend); LiveModel liveModel = CreateLiveModel(factoryContext); liveModel.Init(); RankingResponse response = liveModel.ChooseRank(EventId, ContextJsonWithPdf); senderCalledWaiter.Wait(TimeSpan.FromSeconds(1)); Assert.IsTrue(sendCalled); }
/// <summary> Wrapper method of ChooseRank </summary> public override RankingResponseWrapper ChooseRank(string eventId, string contextJson, ActionFlags actionFlags) { RankingResponse rankingResponse = liveModel.ChooseRank(eventId, contextJson, actionFlags); RankingResponseWrapper rankingResponseWrapper = rankingResponse == null ? null : new RankingResponseWrapper(rankingResponse); return(rankingResponseWrapper); }
public RankingResponse Response(envelopes.ResponseEnvelope <dto.ranking.Ranking> envelope) { var response = new RankingResponse(); response.HttpStatusCode = (int)envelope.HttpStatusCode; if (envelope.Success) { response.Ranking = new RankingMessage { DataProcessamento = envelope.Item.DataProcessamento.Ticks }; foreach (var posicao in envelope.Item.Posicoes) { response.Ranking.Posicoes.Add(new PosicaoMessage { UsuarioId = posicao.UsuarioId.ToString(), Pontos = posicao.Pontos, Valor = posicao.Valor, UsuarioAtual = posicao.UsuarioAtual }); } } return(response); }
public envelopes.ResponseEnvelope <comum_dto.ranking.Ranking> Response(RankingResponse response) { var envelopeResponse = new envelopes.ResponseEnvelope <comum_dto.ranking.Ranking>(); envelopeResponse.HttpStatusCode = (HttpStatusCode)response.HttpStatusCode; if (envelopeResponse.Success) { envelopeResponse.Item = new comum_dto.ranking.Ranking { DataProcessamento = new DateTime(response.Ranking.DataProcessamento) }; foreach (var posicao in response.Ranking.Posicoes) { envelopeResponse.Item.Posicoes.Add(new comum_dto.ranking.Posicao { UsuarioId = posicao.UsuarioId.ToGuid(), Pontos = posicao.Pontos, Valor = posicao.Valor, UsuarioAtual = posicao.UsuarioAtual }); } } return(envelopeResponse); }
public static void PdfExample(string configPath) { const float outcome = 1.0f; const string eventId = "event_id"; const string contextJson = "{\"GUser\":{\"id\":\"a\",\"major\":\"eng\",\"hobby\":\"hiking\"},\"_multi\":[ { \"TAction\":{\"a1\":\"f1\"} },{\"TAction\":{\"a2\":\"f2\"}}],\"p\":[0.2, 0.8]}"; LiveModel liveModel = Helpers.CreateLiveModelOrExit(configPath); ApiStatus apiStatus = new ApiStatus(); RankingResponse rankingResponse = new RankingResponse(); if (!liveModel.TryChooseRank(eventId, contextJson, rankingResponse, apiStatus)) { Helpers.WriteStatusAndExit(apiStatus); } long actionId; if (!rankingResponse.TryGetChosenAction(out actionId, apiStatus)) { Helpers.WriteStatusAndExit(apiStatus); } Console.WriteLine($"Chosen action id: {actionId}"); if (!liveModel.TryQueueOutcomeEvent(eventId, outcome, apiStatus)) { Helpers.WriteStatusAndExit(apiStatus); } }
private void Run_GetRankingModelId_Test(string modelIdToReturn) { RankingResponse rankingResponse = new RankingResponse(); GCHandle valueToReturnHandle = default(GCHandle); try { IntPtr valueToReturnPtr = IntPtr.Zero; if (modelIdToReturn != null) { byte[] valueToReturnUtf8Bytes = NativeMethods.StringEncoding.GetBytes(modelIdToReturn); valueToReturnHandle = GCHandle.Alloc(valueToReturnUtf8Bytes, GCHandleType.Pinned); valueToReturnPtr = valueToReturnHandle.AddrOfPinnedObject(); } NativeMethods.GetRankingModelIdOverride = (IntPtr rankingResponsePtr) => { return(valueToReturnPtr); }; string getResult = rankingResponse.ModelId; Assert.AreEqual(modelIdToReturn ?? String.Empty, getResult, "Marshalling result does not work properly in GetRankingModelId"); } finally { if (valueToReturnHandle != null && valueToReturnHandle.IsAllocated) { valueToReturnHandle.Free(); } rankingResponse?.Dispose(); rankingResponse = null; } }
// TODO: Pull this out to a separate sample once we implement the simulator in this. public static void BasicUsageExample(string [] args) { const float outcome = 1.0f; const string eventId = "event_id"; const string contextJson = "{'GUser':{'id':'a','major':'eng','hobby':'hiking'},'_multi':[ { 'TAction':{'a1':'f1'} },{'TAction':{'a2':'f2'}}]}"; if (args.Length != 1) { WriteErrorAndExit("Missing path to client configuration json"); } if (!File.Exists(args[0])) { WriteErrorAndExit($"Could not find file with path '{args[0]}'."); } string json = File.ReadAllText(args[0]); ApiStatus apiStatus = new ApiStatus(); Configuration config; if (!Configuration.TryLoadConfigurationFromJson(json, out config, apiStatus)) { WriteStatusAndExit(apiStatus); } LiveModel liveModel = new LiveModel(config); if (!liveModel.TryInit(apiStatus)) { WriteStatusAndExit(apiStatus); } RankingResponse rankingResponse = new RankingResponse(); if (!liveModel.TryChooseRank(eventId, contextJson, rankingResponse, apiStatus)) { WriteStatusAndExit(apiStatus); } long actionId; if (!rankingResponse.TryGetChosenAction(out actionId, apiStatus)) { WriteStatusAndExit(apiStatus); } Console.WriteLine($"Chosen action id: {actionId}"); if (!liveModel.TryReportOutcome(eventId, outcome, apiStatus)) { WriteStatusAndExit(apiStatus); } }
public async IAsyncEnumerable <Illustration> MoveNextAsync() { const string query = "/v1/illust/recommended"; context = (await HttpClientFactory.AppApiHttpClient.GetStringAsync(context == null ? query : context.NextUrl)).FromJson <RankingResponse>(); foreach (var contextIllust in context.Illusts.Where(illustration => illustration != null)) { yield return(contextIllust.Parse()); } }
public void Test_LiveModel_ChooseRankE2E() { LiveModel liveModel = this.ConfigureLiveModel(); RankingResponse rankingResponse1 = liveModel.ChooseRank(PseudoLocEventId, PseudoLocContextJsonWithPdf); ValidatePdf(rankingResponse1); RankingResponse rankingResponse2 = liveModel.ChooseRank(PseudoLocEventId, PseudoLocContextJsonWithPdf, ActionFlags.Deferred); ValidatePdf(rankingResponse2); }
private void ValidatePdf(RankingResponse rankingResponse) { List <ActionProbability> actionProbabilities = rankingResponse.ToList(); Assert.AreEqual(ExpectedPdf.Length, actionProbabilities.Count, "Input PDF length does not match samping PDF length."); for (int i = 0; i < actionProbabilities.Count; i++) { int actionIndex = (int)actionProbabilities[i].ActionIndex; Assert.AreEqual(ExpectedPdf[actionIndex], actionProbabilities[i].Probability, float.Epsilon, "PDF score does not match input probability."); } }
public override async ValueTask <bool> MoveNextAsync() { if (entity == null) { if (await TryGetResponse("/v1/illust/recommended") is (true, var model)) { entity = model; UpdateEnumerator(); } else { throw new QueryNotRespondingException(); } Enumerable.ReportRequestedPages(); }
public override async ValueTask <bool> MoveNextAsync() { if (_entity == null) { if (await TryGetResponse($"/v1/illust/ranking?filter=for_android&mode={_rankOptionParameter}&date={_dateTimeParameter}") is (true, var result)) { _entity = result; UpdateEnumerator(); } else { throw new QueryNotRespondingException(); } Enumerable.ReportRequestedPages(); }
public async Task <Message> GetCarousel(RankingResponse standings) { var itemList = GetItemList(standings); AddLastItem(itemList, Flow.Standings); var menu = new DocumentCollection() { Items = itemList.ToArray(), Total = itemList.Count, ItemType = DocumentSelect.MediaType }; var menuMessage = new Message() { Content = menu }; return(menuMessage); }
IEnumerator UploadScore() { // Hashtable header = new Hashtable (); Dictionary <string, string> header = new Dictionary <string, string>(); // jsonでリクエストを送るのへッダ例 header.Add("Content-Type", "application/json; charset=UTF-8"); // LitJsonを使いJSONデータを生成 JsonData data = new JsonData(); string uuid = PlayerPrefs.GetString("uuid"); data ["uuid"] = uuid; data ["name"] = playerName; data ["point"] = result_pts * 10; Debug.Log("UUID" + uuid); // シリアライズする(LitJson.JsonData→JSONテキスト) string postJsonStr = data.ToJson(); byte[] postBytes = Encoding.Default.GetBytes(postJsonStr); // 送信開始 WWW www = new WWW(Define.ServerUrl, postBytes, header); yield return(www); // 成功 if (www.error == null) { Debug.Log("Upload Success"); RankingResponse response2 = JsonMapper.ToObject <RankingResponse> (www.text); rank = int.Parse(response2.rank) + 1; Debug.Log("Current rank" + rank); } // 失敗 else { Debug.Log("Post Failure"); } }
public override Task <RankingResponse> Obter(RankingRequest request, ServerCallContext context) { var response = new RankingResponse(); try { var usuarioId = request.UsuarioId.ToGuid(); var envelopeResponse = servico.Obter(usuarioId); var obterParser = new RankingObter(); response = obterParser.Response(envelopeResponse); } catch (Exception ex) { response.HttpStatusCode = (int)HttpStatusCode.InternalServerError; } return(Task.FromResult(response)); }
public async Task <JsonResult> GetRankingFromTo(RankingTypes rankingType, int?from, int?to, bool asc) { if (rankingType == RankingTypes.Invalid) { return(Json(new InvalidRequestFailure())); } var playerCount = await GetPlayerCount(); int lower = (from ?? 0); int upper = (to + 1 ?? int.MaxValue); var ranking = (await _db.Rankings.Where(r => r.Position <= upper && r.Position >= lower) .ToListAsync()).OrderBy(d => d.Position).ToList(); var result = await GetRankingData(ranking); var response = new RankingResponse { PlayerCount = playerCount, Ranking = result }; return(Json(response)); }
public void Test_CustomSender_SendSuccess() { ManualResetEventSlim senderCalledWaiter = new ManualResetEventSlim(initialState: false); bool sendCalled = false; void SenderSend(SharedBuffer buffer, ApiStatus status) { sendCalled = true; senderCalledWaiter.Set(); } FactoryContext factoryContext = CreateFactoryContext(sendAction: SenderSend); LiveModel liveModel = CreateLiveModel(factoryContext); liveModel.Init(); RankingResponse response = liveModel.ChooseRank(EventId, ContextJsonWithPdf); senderCalledWaiter.Wait(TimeSpan.FromSeconds(1)); Assert.IsTrue(sendCalled); }
private List <DocumentSelect> GetItemList(RankingResponse standings) { var itemList = new List <DocumentSelect>(); var standingList = standings.Content.Take(5).ToList(); foreach (Content r in standingList) { var item = new DocumentSelect { Header = new DocumentContainer { Value = new MediaLink { AspectRatio = MyConstants.FacebookCarouselAspectRatio, Uri = new Uri(r.Competitor.Logo), Title = $"#{r.Placement}: {r.Competitor.Name}", Text = $"W:{r.Records[0].MatchWin}|L:{r.Records[0].MatchLoss}" } }, Options = new DocumentSelectOption[] { new DocumentSelectOption { Label = new DocumentContainer { Value = "🔔Add Alert" }, Value = new DocumentContainer { Value = $"Add#Alert_{r.Competitor.AbbreviatedName}" } } } }; itemList.Add(item); } return(itemList); }
// TODO: Pull this out to a separate sample. public static void BasicUsageExample(string [] args) { const float outcome = 1.0f; const string eventId = "event_id"; const string contextJson = "{\"GUser\":{\"id\":\"a\",\"major\":\"eng\",\"hobby\":\"hiking\"},\"_multi\":[ { \"TAction\":{\"a1\":\"f1\"} },{\"TAction\":{\"a2\":\"f2\"}}]}"; if (args.Length != 1) { WriteErrorAndExit("Missing path to client configuration json"); } LiveModel liveModel = CreateLiveModelOrExit(args[0]); ApiStatus apiStatus = new ApiStatus(); RankingResponse rankingResponse = new RankingResponse(); if (!liveModel.TryChooseRank(eventId, contextJson, rankingResponse, apiStatus)) { WriteStatusAndExit(apiStatus); } long actionId; if (!rankingResponse.TryGetChosenAction(out actionId, apiStatus)) { WriteStatusAndExit(apiStatus); } Console.WriteLine($"Chosen action id: {actionId}"); if (!liveModel.TryReportOutcome(eventId, outcome, apiStatus)) { WriteStatusAndExit(apiStatus); } }
/// <summary> Initializes a new instance of RankingResponseWrapper. </summary> /// <param name="rankResponse"> An rank response </param> public RankingResponseWrapper(RankingResponse rankResponse) { _rankingResponse = rankResponse ?? throw new ArgumentNullException(nameof(rankResponse)); }