public static bool Insert(SpellVM Spelling) { if (Spellings.Any(s => s.Text == Spelling.Text)) { var old_Spell = Spellings.First(s => s.Text == Spelling.Text); var old_score = ScoreHelper.GetScoreFromImportance(old_Spell.Importance); var new_score = ScoreHelper.GetScoreFromImportance(Spelling.Importance); if (new_score > old_score) { var to_update = new SpellVM(old_Spell.Id, old_Spell.Text, Spelling.Importance, old_Spell.IsActive); return(Update(to_update)); } else { return(Errors.ThrowErrorMsg(ErrorType.AlreadyInserted, Spelling.Text)); } } if (!ValidWordsAndAnswerSize(Spelling.Text)) { return(false); } if (!InsertSpelling(Spelling.ToModel())) { return(false); } Spelling.LoadCrossData(); return(true); }
public string GetScoreDescription(Scores scores) { var score1Description = ScoreHelper.GetScoreDescription(scores.Score1); var score2Description = ScoreHelper.GetScoreDescription(scores.Score2); return($"{score1Description}-{score2Description}"); }
public CreateGridTests() { _categoriesInitial = new List <string> { "Animal", "Colour", "Bird", "News", "Food", "Boat", "Plane", "Car", "Fruit" }; _categoriesShuffled1 = new List <string> { "Food", "Fruit", "Colour", "Car", "Animal", "Plane", "Boat", "Bird", "News" }; _categoriesShuffled2 = new List <string> { "Colour", "Fruit", "Boat", "Animal", "Plane", "Bird", "News", "Car", "Food" }; _shuffleHelper = Substitute.For <IShuffleHelper <string> >(); _shuffleHelper .ShuffleList(_categoriesShuffled1) .Returns(_categoriesShuffled1); _shuffleHelper .ShuffleList(_categoriesShuffled2) .Returns(_categoriesShuffled2); var scoreHelper = new ScoreHelper(); _userThoughtsAndCrosses = new UserThoughtsAndCrosses(scoreHelper, _shuffleHelper); }
public static bool Insert(PronVM Pronunciation) { if (Pronunciations.Any(s => s.Text == Pronunciation.Text)) { var old_Pron = Pronunciations.First(s => s.Text == Pronunciation.Text); var old_score = ScoreHelper.GetScoreFromImportance(old_Pron.Importance); var new_score = ScoreHelper.GetScoreFromImportance(Pronunciation.Importance); if (new_score > old_score) { var to_update = new PronVM(old_Pron.Id, old_Pron.Text, old_Pron.Phonemes, Pronunciation.Importance, old_Pron.IsActive); return(Update(to_update)); } else { return(Errors.ThrowErrorMsg(ErrorType.AlreadyInserted, Pronunciation.Text)); } } if (!InsertPronunciation(Pronunciation.ToModel())) { return(false); } Pronunciation.LoadCrossData(); return(true); }
public void WhenGivenAListOfBoolAScoreShouldBeCalculated(bool[] scoreList, int expectedScore) { var scoreHelper = new ScoreHelper(); var score = scoreHelper.CalculateThoughtsAndCrossesScore(scoreList.ToList()); score.Should().Be(expectedScore); }
public static bool Insert(VocVM Vocabulary) { if (Vocabularies.Any(s => s.Text == Vocabulary.Text)) { var old_Voc = Vocabularies.First(s => s.Text == Vocabulary.Text); var old_score = ScoreHelper.GetScoreFromImportance(old_Voc.Importance); var new_score = ScoreHelper.GetScoreFromImportance(Vocabulary.Importance); if (new_score > old_score) { var to_update = new VocVM(old_Voc.Id, old_Voc.Text, old_Voc.Answer, old_Voc.Definition, old_Voc.PtBr, Vocabulary.Importance, old_Voc.IsActive); return(Update(to_update)); } else { return(Errors.ThrowErrorMsg(ErrorType.AlreadyInserted, Vocabulary.Text)); } } if (!ValidWordsAndAnswerSize(Vocabulary.Text, Vocabulary.Answer)) { return(false); } if (!InsertVocabulary(Vocabulary.ToModel())) { return(false); } Vocabulary.LoadCrossData(); return(true); }
public ActionResult Update([Deserialize] ScoreVars model) { //string spName = null, // elemparm = null; //switch(model.type) //{ // case ScoreType.Qvote: // spName = "ScoreQUpdate"; // elemparm = "Q"; // break; // case ScoreType.Avote: // spName = "ScoreAUpdate"; // elemparm = "A"; // break; // case ScoreType.GSOvote: // spName = "ScoreGSOUpdate"; // elemparm = "GSO"; // break; //} //var reader = unitOfWork.ReaderRepository.GetSPDataReader( // spName, // new SqlParameter(elemparm, model.elemId), // new SqlParameter("sig", model.sign), // new SqlParameter("granterId", WebSecurity.CurrentUserId)); //int res = 0; //while (reader.Read()) //{ // res = reader.GetInt32(0); //} var res = ScoreHelper.Update(model); return(Json(new { Result = res })); }
/// <summary> /// Delete the progress for a specific assignment and the currently logged in user. /// </summary> public HttpResponseMessage Delete() { // Tried to fixx the "not being able to start an assignment if you reloaded the page during one" problem. if (_participant.Progress == null) { return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Geen opdracht is gestart.")); } try{ var timeDifference = TimeDifferenceHelper.GetTimeDifference(_participant.Progress.StartTime); if (timeDifference > _participant.Progress.Assignment.MaxSolveTime) { timeDifference = _participant.Progress.Assignment.MaxSolveTime; } var score = ScoreHelper.CreateScore(_participant.Progress.Assignment, _participant, false, timeDifference); _context.Scores.Add(score); _context.Progresses.Remove(_participant.Progress); _context.SaveChanges(); } catch { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Error bij het opslaan in de database.")); throw; } return(Request.CreateResponse(HttpStatusCode.OK)); }
public void CalculateScore_IncompleteHand_IsMinusOne() { List <Card> emptyList = new List <Card>(); int result = ScoreHelper.CalculateScore(emptyList); Assert.AreEqual(-1, result); }
public ActionResult AnswerAccept(string AId) { NullChecker.NullCheck(new object[] { AId }); var answer = unitOfWork.AnswerRepository.GetByID(EncryptionHelper.Unprotect(AId)); if (AuthorizationHelper.isRelevant(answer.Question.questionerID)) { if (answer.accept) { answer.accept = false; unitOfWork.AnswerRepository.Update(answer); unitOfWork.Save(); return(Json(new { Success = true, Result = false })); } else { answer.accept = true; unitOfWork.Save(); unitOfWork.AnswerRepository.Update(answer); NotificationHelper.NotificationInsert(NotificationType.AnswerAccept, elemId: answer.answerID); FeedHelper.FeedInsert(FeedType.AnswerAccept, answer.questionID, answer.answererID ); ScoreHelper.Update(new ScoreVars { type = ScoreType.Aacc, elemId = answer.answerID, sign = 1 }); return(Json(new { Success = true, Result = true })); } } throw new JsonCustomException(ControllerError.ajaxErrorAnswerAcception); }
void Start() { var scoreString = "Score: " + String.Format("{0:0}", ScoreHelper.GetInstance().GetScore()); Debug.Log(scoreString); scoreText.text = scoreString; }
public void StartGame(User user) { if (user == null) { user = new User(); } int score = 0; LineInstaller line = new LineInstaller(); line.DrawShapes(); Point food = FoodFactory.GetRandomFood(119, 20, '+'); Console.ForegroundColor = ColorHelper.GetRandomColor(new Random().Next(1, 5)); food.DrawPoint(); Console.ResetColor(); Snake snake = new Snake(); snake.CreateSnake(5, new Point(5, 5, 'z'), DirectionEnum.Right); snake.DrawLine(); ScoreHelper.GetScore(score); while (true) { if (line.Collision(snake) || snake.CollisionWithOwnTail()) { break; } if (snake.Eat(food)) { score++; ScoreHelper.GetScore(score); food = FoodFactory.GetRandomFood(119, 20, '+'); Console.ForegroundColor = ColorHelper.GetRandomColor(new Random().Next(1, 5)); food.DrawPoint(); Console.ResetColor(); } Thread.Sleep(100); snake.Move(); if (Console.KeyAvailable) { ConsoleKeyInfo key = Console.ReadKey(); snake.PressKey(key.Key); } } user.Score = score; _userService.SaveScore(user); }
// Update is called once per frame void LateUpdate() { if (target.position.y > transform.position.y) { ScoreHelper.GetInstance().Add(target.position.y - transform.position.y); Vector3 newPosition = new Vector3(transform.position.x, target.position.y, transform.position.z); transform.position = newPosition; } }
public HomeArticleSpotlightViewModel(ArticleDom article) { ID = article.ArticleID; Day = article.CreationDay; CountryFlag = Images.GetCountryFlag(article.CountryID).VM; ArticleImage = new ImageViewModel(article.ImgURL); Title = article.Title; Score = ScoreHelper.ToString(article.VoteScore); }
public DevIssueViewModel(DevIssue issue) { ID = issue.ID; Name = issue.Name; Content = issue.Content; PlayerType = SessionHelper.LoggedCitizen.GetPlayerType(); Day = issue.Day; Time = issue.Time.ToShortTimeString(); Avatar = new SmallEntityAvatarViewModel(issue.Citizen.Entity); Avatar.Classname = "avatar"; Files = issue.DevIssueUploadedFiles.ToList() .Select(f => new DevIssueUploadedFileViewModel(f)).ToList(); var actualLabels = issue.DevIssueLabelTypes.ToList(); foreach (var label in Enum.GetValues(typeof(DevIssueLabelTypeEnum)).Cast <DevIssueLabelTypeEnum>()) { var item = new SelectListItem() { Text = label.ToString(), Value = ((int)label).ToString(), Selected = actualLabels.Any(l => l.ID == (int)label) }; LabelTypes.Add(item); } foreach (var visibility in Enum.GetValues(typeof(VisibilityOptionEnum)).Cast <VisibilityOptionEnum>()) { var item = new SelectListItem() { Text = visibility.ToString(), Value = ((int)visibility).ToString(), Selected = issue.VisibilityOptionID == (int)visibility }; VisiblityOptions.Add(item); } foreach (var label in actualLabels) { labelIDs.Add(label.ID); Labels.Add(new DevIssueLabelViewModel(label)); } Score = ScoreHelper.ToString(issue.DevIssueVotes.Sum(v => v.Score)); CanVote = issue.DevIssueVotes.Any(v => v.CitizenID == SessionHelper.LoggedCitizen.ID) == false; CanUnvote = !CanVote; loadComments(issue); }
public GameManager(LevelManager levelManager, SignalBus signalBus, UIManager uiManager, ScoreHelper scoreHelper, [Inject(Id = "GlobalAudio")] AudioSource audioSource) { _levelManager = levelManager; _uiManager = uiManager; _scoreHelper = scoreHelper; _audioSource = audioSource; _signalBus = signalBus; _signalBus.Subscribe <PlayerReachedEndSignal>(OnPlayerReachedEnd); _signalBus.Subscribe <BrickDestroyedSignal>(OnBrickDestroyed); }
public string GetScoreDescription(Scores scores) { switch (scores.Score1) { case 0: case 1: case 2: return $"{ScoreHelper.GetScoreDescription(scores.Score1)}-All"; default: return "Deuce"; } }
void Awake() { this.dbLoader = GetComponentInChildren <DatabaseLoader>(); dbManager = new DatabaseManager(); vocabularyHelper = new VocabularyHelper(dbManager); scoreHelper = new ScoreHelper(dbManager); teacherAI = new TeacherAI(dbManager, vocabularyHelper, scoreHelper); // Load the first profile LoadProfile(DEBUG_PLAYER_UUID); }
private IEnumerator InitCO() { AppSettingsManager = new AppSettingsManager(); AssetManager = new AssetManager(); yield return(ReloadEdition()); // TODO refactor: standardize initialisation of managers VocabularyHelper = new VocabularyHelper(DB); JourneyHelper = new JourneyHelper(DB); ScoreHelper = new ScoreHelper(DB); Teacher = new TeacherAI(DB, VocabularyHelper, ScoreHelper); LogManager = new LogManager(); GameLauncher = new MiniGameLauncher(Teacher); FirstContactManager = new FirstContactManager(); Services = new ServicesManager(); FacebookManager = gameObject.AddComponent <FacebookManager>(); FacebookManager.verbose = true; // MonoBehaviors NavigationManager = gameObject.AddComponent <NavigationManager>(); NavigationManager.Init(); gameObject.AddComponent <KeeperManager>(); gameObject.AddComponent <BookManager>(); RewardSystemManager = new RewardSystemManager(); RewardSystemManager.Init(); PlayerProfileManager = new PlayerProfileManager(); PlayerProfileManager.LoadPlayerSettings(); Services = new ServicesManager(); Debug.Log("AppManager Init(): UIDirector.Init()"); UIDirector.Init(); // Must be called after NavigationManager has been initialized // Debugger setup if (!ApplicationConfig.I.DebugLogEnabled) { Debug.LogWarning("LOGS ARE DISABLED - check the App Config"); } Debug.unityLogger.logEnabled = ApplicationConfig.I.DebugLogEnabled; gameObject.AddComponent <Debugging.DebugManager>(); Debug.Log("AppManager Init(): UpdateAppVersion"); // Update settings AppSettingsManager.UpdateAppVersion(); Time.timeScale = 1; Loaded = true; }
private void LoadChanceToAppear() { // peso 2 var daysSince = LastTry != null?DateTime.Now.Subtract(LastTry.When).Days : 100; var lastTry_score = 0; if (daysSince < 20 && daysSince >= 1) { lastTry_score = daysSince / 2; } else if (daysSince == 0) { Chance = 1; Chance_toolTip = "Question already completed today."; return; } else { lastTry_score = 20; } // peso 4 var inv_avg = 40.0; if (daysSince <= 7) { inv_avg -= ((20 * Avg_week) / 100) + ((15 * Avg_month) / 100) + ((05 * Avg_all) / 100); } else if (daysSince <= 30) { inv_avg -= ((30 * Avg_month) / 100) + ((10 * Avg_all) / 100); } else if (daysSince <= 7) { inv_avg -= ((40 * Avg_all) / 100); } // peso 1 var lastWasWrong = Tries != null && Tries.Any() ? (LastTry.Score == 100 ? 0 : 10) : 10; // peso 3 var imp_score = ScoreHelper.GetScoreFromImportance(Importance) * 3; Chance = Math.Round(lastTry_score + inv_avg + lastWasWrong + imp_score, 2); Chance_toolTip = inv_avg + " (inv_avg) -> " + (daysSince <= 7 ? "avg_week (20%) + avg_month (15%) + avg_all (5%)" : (daysSince <= 30 ? "avg_month (30%) + avg_all (10%)" : "avg_all (40%) + ")) + "\n"; Chance_toolTip += lastTry_score + " (lastTry) + " + lastWasWrong + " (lastWrong) + " + imp_score + " (imp)"; }
public void CalculateScore_RoyalFlush_Is914() { Card ace = new Card(14, 1); Card king = new Card(13, 1); Card queen = new Card(12, 1); Card jack = new Card(11, 1); Card ten = new Card(10, 1); List <Card> hand = new List <Card> { ace, king, queen, jack, ten }; int score = ScoreHelper.CalculateScore(hand); Assert.AreEqual(914, score); }
public static ScoreHelper GetInstance() { if (instance == null) { lock (theLock) { if (instance == null) { instance = new ScoreHelper(); } } } return(instance); }
public TeacherAI(DatabaseManager _dbManager, PlayerProfile _playerProfile) { I = this; dbManager = _dbManager; playerProfile = _playerProfile; wordHelper = new WordHelper(_dbManager); journeyHelper = new JourneyHelper(_dbManager, this); scoreHelper = new ScoreHelper(_dbManager); logAI = new LogAI(_dbManager); minigameSelectionAI = new MiniGameSelectionAI(dbManager, playerProfile); wordAI = new WordSelectionAI(dbManager, playerProfile, this, wordHelper); difficultySelectionAI = new DifficultySelectionAI(dbManager, playerProfile); }
/// <summary> /// Build and runs an assignment and checks the scores for the user submitted code. /// </summary> /// <param name="runJob">See RunController.</param> /// <returns></returns> public HttpResponseMessage Post(RunController.RunJob runJob) { _compiler.CompileFromPlainText(_participant, runJob.Code); var runResult = _runner.RunAndCheckInput(_participant); var correctOutput = IsCorrectOutput(runResult); var timeDifference = TimeDifferenceHelper.GetTimeDifference(_participant.Progress.StartTime); var score = ScoreHelper.CreateScore(_participant.Progress.Assignment, _participant, correctOutput, timeDifference); _context.Scores.Add(score); _context.Progresses.Remove(_participant.Progress); _context.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.Created)); }
/// <summary> /// first Init, from Awake() /// </summary> protected override void Init() { if (alreadySetup) { return; } alreadySetup = true; AppSettingsManager = new AppSettingsManager(); DB = new DatabaseManager(); // TODO refactor: standardize initialisation of managers LogManager = new LogManager(); VocabularyHelper = new VocabularyHelper(DB); JourneyHelper = new JourneyHelper(DB); ScoreHelper = new ScoreHelper(DB); Teacher = new TeacherAI(DB, VocabularyHelper, ScoreHelper); GameLauncher = new MiniGameLauncher(Teacher); FirstContactManager = new FirstContactManager(); Services = new ServicesManager(); FacebookManager = gameObject.AddComponent <FacebookManager>(); FacebookManager.verbose = true; // MonoBehaviors NavigationManager = gameObject.AddComponent <NavigationManager>(); NavigationManager.Init(); gameObject.AddComponent <KeeperManager>(); gameObject.AddComponent <BookManager>(); RewardSystemManager = new RewardSystemManager(); RewardSystemManager.Init(); PlayerProfileManager = new PlayerProfileManager(); PlayerProfileManager.LoadPlayerSettings(); Services = new ServicesManager(); Debug.Log("AppManager Init(): UIDirector.Init()"); UIDirector.Init(); // Must be called after NavigationManager has been initialized // Debugger setup Debug.unityLogger.logEnabled = AppConfig.DebugLogEnabled; gameObject.AddComponent <Debugging.DebugManager>(); Debug.Log("AppManager Init(): UpdateAppVersion"); // Update settings AppSettingsManager.UpdateAppVersion(); }
public async Task <IActionResult> Put([FromBody] Resources.UserPoints points) { List <Resources.Recommendation> recommendations = new List <Resources.Recommendation>(); (await genreRepository.GetAll()).Where(g => g.IdGenre == points.Genre.Id) .Join(movieDataRepository.GetAll().Result, g => g.IdMovieData, md => md.IdMovieData, (g, md) => md) .ToList().ForEach(movie => { Resources.Movie data = _mapper.Map <Resources.Movie>(movie); int score = ScoreHelper.GetRecommendationScore(points, data, movieDataRepository, reviewRepository); Resources.Recommendation temp = new Resources.Recommendation { Movie = data, Score = score }; recommendations.Add(temp); }); return(Ok(recommendations.OrderByDescending(val => val.Score).Take(10))); }
public ActionResult AcceptOffer(string GSOId) { NullChecker.NullCheck(new object[] { GSOId }); var offer = unitOfWork.GroupSessionOfferRepository.GetByID(EncryptionHelper.Unprotect(GSOId)); if (offer.GroupSession.Group.Admins.Any(a => AuthorizationHelper.isRelevant(a.UserId))) { string text = Resource.Resource.acceptedNotSessionOffer; string message = Resource.Resource.acceptedNotSessionOfferMessage; if (offer.isAccepted) { offer.isAccepted = false; } else { offer.isAccepted = true; text = Resource.Resource.acceptedSessionOffer; message = Resource.Resource.acceptedSessionOfferMessage; } unitOfWork.GroupSessionOfferRepository.Update(offer); unitOfWork.Save(); if (offer.isAccepted) { FeedHelper.FeedInsert(FeedType.SessionOfferAccept, offer.sessionId, offer.offererId ); NotificationHelper.NotificationInsert( NotificationType.SessionOfferAccept, elemId: offer.offerId ); ScoreHelper.Update(new ScoreVars { type = ScoreType.GSOacc, elemId = offer.offerId, sign = 1 }); } return(Json(new { Accepted = offer.isAccepted, Message = message, Result = text })); } throw new JsonCustomException(ControllerError.ajaxError); }
void Awake() { this.dbLoader = GetComponentInChildren <DatabaseLoader>(); dbLoader.langCode = langCode; dbManager = new DatabaseManager(true, langCode); vocabularyHelper = new VocabularyHelper(dbManager); scoreHelper = new ScoreHelper(dbManager); teacherAI = new TeacherAI(dbManager, vocabularyHelper, scoreHelper); if (TestCustomProfile != string.Empty) { LoadCustomProfile(TestCustomProfile); } else { LoadProfile(DEBUG_PLAYER_UUID); } }
private Scoretable GetScores(string json) { string palautus = ""; string azureFunctionKey = _config.GetValue <string>("ModelFunctionKey"); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var content = new StringContent(json, Encoding.UTF8, "application/json"); var response = client.PostAsync($"https://sanasorsa-helper.azurewebsites.net/api/get_distances?code={azureFunctionKey}", content).Result; var responseString = response.Content.ReadAsStringAsync().Result; palautus = responseString; } ScoreHelper listofscores = JsonConvert.DeserializeObject <ScoreHelper>(palautus); Scoretable st = new Scoretable(listofscores.data); return(st); }
private static SourceScore ToSourceScore(ScoreObject scoreObject, ReadSourceOptions options) { var score = new SourceScore(); var scoreIndex = options.ScoreIndex; var difficulty = (Difficulty)scoreIndex; var trackType = ScoreHelper.MapDifficultyToTrackType(difficulty); var tracks = ScoreHelper.GetTrackIndicesFromTrackType(trackType); score.Notes = scoreObject.NoteEvents .Where(nd => Array.IndexOf(tracks, nd.Track) >= 0) .Select(n => ToNote(n, tracks)) .Where(n => n != null).ToArray(); score.Conductors = scoreObject.ConductorEvents.Select(ToConductor).ToArray(); score.MusicOffset = scoreObject.BgmOffset; score.ScoreIndex = scoreIndex; score.TrackCount = tracks.Length; return(score); }