Exemplo n.º 1
0
        private static void SetupDependencies()
        {
            var timeParser = new TimeParser();
            var timeMapper = new TimeMapper();

            _talkingClockService = new TalkingClockService(timeParser, timeMapper);
        }
        public async Task <IActionResult> GetIdTimesAsync([FromHeader] string authToken, [FromRoute] int id, [FromRoute] DateTime date)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (!await _tokenService.HasTokenAsync(authToken))
            {
                return(Unauthorized());
            }

            User user = await _context.Users.Include(x => x.Times).SingleOrDefaultAsync(x => x.Id == id);

            if (user == null)
            {
                ModelState.AddModelError("UserNotExist", "User does not exist");
            }


            if (ModelState.ErrorCount != 0)
            {
                return(BadRequest(ModelState));
            }
            return(Ok(TimeMapper.MapToTimeDTO(user).Where(x => x.Date == date.FirstOfMonth())));
        }
Exemplo n.º 3
0
        public void Setup()
        {
            _timeScope  = new TimeScope();
            _timeScopes = new List <TimeScope> {
                _timeScope
            };

            _timeMapper = new TimeMapper();
        }
        public async Task <IActionResult> PostIdTimesAsync([FromHeader] string authToken, [FromRoute] int id, [FromBody] TimeDTO model)
        {
            _logger.LogWarning("start:" + model.Category.ToString());
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (!await _tokenService.HasTokenAsync(authToken))
            {
                return(Unauthorized());
            }

            User user = await _context.Users.Include(x => x.Times).SingleOrDefaultAsync(x => x.Id == id);

            if (user == null)
            {
                ModelState.AddModelError("UserNotExist", "User does not exist");
            }
            else
            {
                Time time = user.Times.SingleOrDefault(x => x.Category == model.Category && x.Date == model.Date.FirstOfMonth());

                if (time == null)
                {
                    user.Times.Add(TimeMapper.Map(model));
                }
                else
                {
                    int index = user.Times.IndexOf(time);
                    user.Times[index] = TimeMapper.Map(model, time);
                }

                try
                {
                    _context.Users.Update(user);
                    await _context.SaveChangesAsync();
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("Error", ex.Message);
                }
            }


            _logger.LogWarning("end:" + model.Category.ToString());
            if (ModelState.ErrorCount != 0)
            {
                return(BadRequest(ModelState));
            }
            return(Ok());
        }
Exemplo n.º 5
0
        public override Expression Evaluate(EvalStore store)
        {
            Table data = store.Get<Table>("$DATA");

            if (data == null) return ConstExpr.Empty;

            if (data.Rows == 0) return new ConstExpr(data);

            List<Mapper> mappers = new List<Mapper>();

            foreach (Expression expr in _exprs) {
                switch (expr.ExpressionType) {
                    case Language.ExpressionType.ID: {
                            int col = data.ColumnDefinitions.IndexOf((expr as IdentifierExpr).Name);
                            Mapper m = new Mapper(col);
                            mappers.Add(m);
                        }
                        break;
                    case Language.ExpressionType.FUNCTION: {
                            FuncExpr f = expr as FuncExpr;
                            int col = data.ColumnDefinitions.IndexOf(f.Name.ToLower());
                            Expression c = f.Arguments[0].Evaluate(store);
                            TimeMapper m = new TimeMapper(col, c.Value);
                            mappers.Add(m);
                        }
                        break;
                }
            }

            List<int> p = new List<int>();
            for (int i = 0; i < data.Rows; i++) { p.Add(i); }

            List<List<int>> groups = CreateGroups(data, p, mappers);

            store.Put<List<List<int>>>("$GROUPS", groups);

            if (_havingClause != null) {
                _havingClause.Evaluate(store);
            }

            return new ConstExpr(data);
        }
Exemplo n.º 6
0
        public void TestTimeMapper()
        {
            TimeMapper mapper = new TimeMapper();

            mapper.SetInputRange(0, 1000);
            mapper.SetSlowMotionRange(0, 2);
            mapper.FileInterval    = 50;
            mapper.UserInterval    = 25;
            mapper.CaptureInterval = 2.5;

            double t = 0;

            t = mapper.GetInterval(-1);
            t = mapper.GetInterval(0);
            t = mapper.GetInterval(10);
            t = mapper.GetInterval(100);
            t = mapper.GetInterval(500);
            t = mapper.GetInterval(999);
            t = mapper.GetInterval(1000);
            t = mapper.GetInterval(1001);

            t = mapper.GetRealtimeMultiplier(-1);
            t = mapper.GetRealtimeMultiplier(0);
            t = mapper.GetRealtimeMultiplier(10);
            t = mapper.GetRealtimeMultiplier(100);
            t = mapper.GetRealtimeMultiplier(500);
            t = mapper.GetRealtimeMultiplier(999);
            t = mapper.GetRealtimeMultiplier(1000);
            t = mapper.GetRealtimeMultiplier(1001);

            double i = 0;

            i = mapper.GetInputFromSlowMotion(-1);
            i = mapper.GetInputFromSlowMotion(0);
            i = mapper.GetInputFromSlowMotion(0.1);
            i = mapper.GetInputFromSlowMotion(0.5);
            i = mapper.GetInputFromSlowMotion(1);
            i = mapper.GetInputFromSlowMotion(1.5);
            i = mapper.GetInputFromSlowMotion(2);
            i = mapper.GetInputFromSlowMotion(2.1);
        }
Exemplo n.º 7
0
 public TimeMapperShould()
 {
     _timeMapper = new TimeMapper();
 }
Exemplo n.º 8
0
        public static void Main(string[] args)
        {
            Logger.Info("Application Started");

            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["csvpath"].ToString()))
            {
                CsvImporter.CsvPath = ConfigurationManager.AppSettings["csvpath"].ToString();
            }
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["jsonpath"].ToString()))
            {
                JsonOverrideFactory.JsonPath = ConfigurationManager.AppSettings["jsonpath"].ToString();
            }

            var categories =
                new CategoryCreator()
                .SetRawPath("Events.csv")
                .SetOverrideFactory("events.json")
                .Create();
            var athletes =
                new AthleteCreator()
                .SetRawPath("Competitors.csv")
                .SetOverrideFactory("athletes.json")
                .Create();

            var clubs = new ClubCreator(athletes).SetOverrideFactory("clubs.json").Create();

            AthleteClubMapper.Map(athletes, clubs);

            var startpositions = new StartPositionFactory("startpositions.json").Create();
            var crews          =
                new CrewCreator(categories, clubs, startpositions, athletes)
                .SetRawPath("Crews.csv")
                .SetOverrideFactory("crews.json")
                .Create()
                .OrderBy(cr => cr.StartNumber)
                .ToList();

            // todo - this is almost certainly not the best place to do this
            var bandProportions = ConfigurationManager.AppSettings["OpenBands"].Split(',').Select(i => Int32.Parse(i)).ToList();

            foreach (Gender gender in (Gender[])Enum.GetValues(typeof(Gender)))
            {
                var openBands = categories.Where(cat => cat is EventCategory).Select(c => (EventCategory)c).Where(c => c.Gender == gender && c.UseForCRI).Select(c => c.EventId).ToList();

                IList <Func <List <int> > > del = new List <Func <List <int> > >
                {
                    () => crews.Where(cr => cr.Gender == gender).Select(cr => cr.CRI(false)).ToList(),
                    () => crews.Where(crew => categories.Where(cat => cat is EventCategory).Select(c => (EventCategory)c).Where(c => c.Gender == gender && c.UseForCRI).Select(c => c.EventId).Contains(crew.EventCategory.EventId)).Select(cr => cr.CRI(false)).ToList()
                };

                foreach (var fn in del)
                {
                    var crisToInclude = fn(); // crews.Where(crew => openBands.Contains(crew.EventCategory.EventId)).Select(cr => cr.CRI).ToList();
                    crisToInclude.Sort();
                    if (crisToInclude.Count > 0)
                    {
                        Logger.DebugFormat("{0} crews [#{2}] {1}", gender, crisToInclude.Select(c => c.ToString()).Aggregate((h, t) => String.Format("{0}, {1}", h, t)), crisToInclude.Count);

                        int tally = 0;
                        int lower = 0;
                        for (int i = 0; i < bandProportions.Count; i++)
                        {
                            tally += bandProportions[i];
                            int upper = i + 1 == bandProportions.Count ? crisToInclude.Count - 1 : 1 + (int)Math.Floor((decimal)crisToInclude.Count * tally / 100);
                            Logger.DebugFormat("Band {0} [{1}, {2}{4}. #{3} ", i + 1, crisToInclude[lower], crisToInclude[upper], (i + 1 == bandProportions.Count ? 1 : 0) + upper - lower, i + 1 < bandProportions.Count ? ")" : "]"); // crisToInclude[mag-1], crisToInclude[mag]);
                            lower = upper;
                        }
                        foreach (var b in new List <bool> {
                            true, false
                        })
                        {
                            Logger.InfoFormat("Correlation between CRI{2} and points ({1}): {0}",
                                              PearsonCorrelation(crews.Where(cr => cr.Gender == gender).Select(cr => (double)cr.CRI(b)).ToList(), crews.Where(cr => cr.Gender == gender).Select(cr => (double)cr.Points).ToList()),
                                              gender,
                                              b ? "Max" : "");
                        }
                    }
                }
            }
            foreach (var b in new List <bool> {
                true, false
            })
            {
                Logger.InfoFormat("Correlation between CRI{1} and points (all): {0}",
                                  PearsonCorrelation(crews.Select(cr => (double)cr.CRI(b)).ToList(), crews.Select(cr => (double)cr.Points).ToList()),
                                  b ? "Max" : "");
            }

            CategoryCrewMapper.Map(categories, crews);

            // TODO: move results into the config file?
            if (args.Count() == 0 || args[0].ToLowerInvariant() != "results")
            {
                StartPositionGenerator.Generate(crews);



                bool valid =
                    new CrewValidator(athletes).Validate(crews) &&
                    new ClubValidator().Validate(clubs) &&
                    new AthleteValidator().Validate(athletes) &&
                    new CategoryValidator().Validate(categories);

                if (!valid)
                {
                    return;
                }
            }
            else
            {
                var starttimes  = new SequenceItemFactory("start-times.json").Create();
                var finishtimes = new SequenceItemFactory("finish-times.json").Create();
                var penalties   = new PenaltyFactory("penalties.json").Create();
                var adjustments = new AdjustmentFactory("adjustments.json").Create();
                // todo - is there a weighed in file?

                TimeMapper.Map(crews, starttimes, finishtimes);
                TimeMapper.Penalise(crews, penalties);
                TimeMapper.Adjust(crews, adjustments);

                CategoryResultsGenerator.Generate(categories);

                ResultsPrinter.Dump(crews);
            }

            Logger.Info("Application stopped.");
        }